From 2718245916266aa27156d011ebc3690dd73fd4fc Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:42:06 +0800 Subject: [PATCH 001/122] fix(sidebar-right): drop the left divider in fullscreen The first dock column draws a left border that separates the sidebar from the conversation. Fullscreen has no conversation beside it, so the border showed as a stray line at the window's left edge. Fixes #7927 Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 6 ++++++ .../tests/sidebar-right-styles.client.spec.ts | 7 ++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 09119e640a..d4092a566b 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,6 +83,12 @@ --dsh-dockkit-dock-layer: 40; } +/* Fullscreen has no conversation beside the first column, so dockkit's + column-0 rule separating the two would only edge the window. */ +.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left: none; +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index d59a3c843f..6a90c738c1 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide and reveal-flash style contracts. */ +/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,6 +18,11 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) + it('drops the first column\'s conversation divider in fullscreen', () => { + expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` + + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + }) + it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From e5e7944ff3b0c9ebddbb4df73d4a5cbfd9a14bab Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:49:20 +0800 Subject: [PATCH 002/122] docs(sidebar-right): state the fullscreen divider reason for every platform Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index d4092a566b..c76b0f6e5f 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,7 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 rule separating the two would only edge the window. */ + column-0 divider has nothing to separate. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } From 8f00cc7f678d4e34bedc661372c0f81aa7330168 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:25:15 +0800 Subject: [PATCH 003/122] docs(sidebar-right): note why the fullscreen divider selector is longer Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../ui-sidebar-right/src/client/shell/SidebarRight.module.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index c76b0f6e5f..36314b48e0 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -84,7 +84,8 @@ } /* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. */ + column-0 divider has nothing to separate. The host attribute and child + combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ .panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { border-left: none; } From d1da247213f9bdf4a5f4a25ba2ce834ad7b65511 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 15:50:37 +0800 Subject: [PATCH 004/122] fix(sidebar-right): keep the fullscreen divider during the slide The open and close slides move the fullscreen panel across the conversation, so the first column keeps its divider until an opening slide ends and as soon as a closing slide starts. Only the border color changes, so the pane keeps its width. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 19 +++++++++++++------ .../tests/sidebar-right-styles.client.spec.ts | 11 ++++++++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 36314b48e0..6caf305fa3 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,11 +83,17 @@ --dsh-dockkit-dock-layer: 40; } -/* Fullscreen has no conversation beside the first column, so dockkit's - column-0 divider has nothing to separate. The host attribute and child - combinator outrank dockkit's (0,4,0) rule regardless of stylesheet order. */ -.panel[data-sidebar-right-panel='fullscreen'] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left: none; +/* Once open, fullscreen has no conversation beside the first column, so + dockkit's column-0 divider has nothing to separate. While the panel slides + in or out across the conversation the divider stays: an opening keeps it + for the slide's duration, and a closing panel no longer matches. Only the + color changes, so the pane keeps its width. */ +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: transparent; +} + +.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + transition: border-left-color 0s linear var(--ds-transition-duration-slow); } /* No whole-box subtraction here: Electron drag regions are window geometry, @@ -132,7 +138,8 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]), + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 6a90c738c1..7187986b63 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -18,9 +18,14 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('drops the first column\'s conversation divider in fullscreen', () => { - expect(css).toMatch(new RegExp(String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\] :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\)` - + String.raw` > :global\(\[data-dockkit-pane\]\)\s*\{\s*border-left: none;\s*}`)) + it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { + const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` + const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) + expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { From 261a86a1087c94aab090e87861443a605263c0b1 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 16:17:02 +0800 Subject: [PATCH 005/122] fix(sidebar-right): end the opening only with a docked item's slide A short transition inside the panel ended the opening early, which cancelled the delayed divider change mid-slide. A pane mounted by the opening also starts with the divider now. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 7 +++++++ .../src/client/shell/SidebarRight.tsx | 14 ++++++++++---- .../ui-sidebar-right/tests/seat.client.spec.tsx | 6 +++++- .../tests/sidebar-right-styles.client.spec.ts | 2 ++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 6caf305fa3..4bda4ee3e6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -96,6 +96,13 @@ transition: border-left-color 0s linear var(--ds-transition-duration-slow); } +/* A pane mounted by the opening starts with the divider, like one already mounted. */ +@starting-style { + .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + border-left-color: var(--dsw-alias-border-l4); + } +} + /* No whole-box subtraction here: Electron drag regions are window geometry, not stacking, so a strip row inside this fullscreen content that marks itself `data-window-drag` (ui-dockkit) still owns the drag over its own box, and diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index e0182a611b..86117bb069 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject } from 'react' +import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,6 +305,12 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } +/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ +function slideEnded(event: TransitionEvent): boolean { + return event.propertyName === 'transform' + && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") +} + /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -324,8 +330,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { setOpening(false) } : undefined} + onTransitionEnd={opening ? (event) => { if (slideEnded(event)) setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index c6ae78c2e8..106b3b6bf7 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,7 +626,11 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host) + // Short transitions inside an item, or other properties, do not end the slide. + fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) + fireEvent.transitionEnd(host, { propertyName: 'opacity' }) + expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) + fireEvent.transitionEnd(host, { propertyName: 'transform' }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 7187986b63..19cbfb270f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -24,6 +24,8 @@ describe('SidebarRight.module.css', () => { expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) + expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` + + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) }) From 3e6916a2d3d62318185fffb8dfc6088bcc9d4928 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:24:15 +0800 Subject: [PATCH 006/122] refactor(desktop): isolate publisher workspace for lightweight rollout --- .github/workflows/desktop-publish.yml | 8 ++-- .github/workflows/desktop-publisher-check.yml | 35 +++++++++++++++++ .github/workflows/desktop-rollout.yml | 37 +++++++++--------- apps/desktop-publisher/package.json | 19 ++++++++++ .../src}/cos-operation.ts | 0 .../desktop-auto-update-environment.d.mts | 0 .../src}/desktop-auto-update-environment.mjs | 0 .../src}/desktop-cos.ts | 2 +- .../src}/desktop-publication-failure.ts | 0 .../src}/desktop-publish-config.ts | 0 .../src}/desktop-publish-cos.ts | 5 ++- .../src}/desktop-publish-qualification.d.mts | 0 .../src}/desktop-publish-qualification.mjs | 0 .../src}/desktop-publish-record.ts | 2 +- .../src}/desktop-publish-route.ts | 0 .../src}/desktop-publish-targets.ts | 0 .../src}/desktop-publish.ts | 7 ++-- .../src}/desktop-purge-recovery.ts | 10 ++--- .../src/desktop-purge-types.ts | 7 ++++ .../src}/desktop-release-store.ts | 2 +- .../src/desktop-releases-root.ts | 15 ++++++++ .../src}/desktop-rollout.ts | 17 +++++---- .../src/desktop-upload-types.ts | 38 +++++++++++++++++++ .../src}/desktop-website-installer.ts | 8 ++-- .../src}/publish-desktop-rollout-ci.ts | 4 +- .../src}/publish-website-ci.ts | 6 +-- .../src}/resolve-desktop-publish-ci.ts | 6 +-- .../resolve-retained-desktop-publish-ci.ts | 6 +-- .../tests/cos-loopback.ts | 0 .../tests/cos-operation.spec.ts | 4 +- .../desktop-auto-update-environment.spec.ts | 2 +- .../tests/desktop-package-selection.spec.ts | 6 +-- .../tests/desktop-publication-failure.spec.ts | 10 ++--- .../tests/desktop-publish-config.spec.ts | 2 +- .../tests/desktop-publish-cos.spec.ts | 10 ++--- .../tests/desktop-publish-record.spec.ts | 4 +- .../tests/desktop-publish-route.spec.ts | 2 +- .../tests/desktop-publish.spec.ts | 4 +- .../tests/desktop-purge-recovery.spec.ts | 4 +- .../tests/desktop-release-store.spec.ts | 2 +- .../tests/desktop-website-installer.spec.ts | 10 ++--- .../tests/expected/cos-GetObject-denied.json | 0 .../tests/expected/cos-PutObject-denied.json | 0 .../tests/expected/website-purge-accepted.md | 0 .../expected/website-purge-unconfirmed.md | 0 .../tests/isolated-install.mjs | 18 +++++++++ .../tests/publish-website-ci.spec.ts | 4 +- apps/desktop-publisher/tests/workflow.spec.ts | 31 +++++++++++++++ apps/desktop/package.json | 3 +- apps/desktop/scripts/archive-desktop-ci.ts | 4 +- .../desktop/scripts/desktop-build-paths.d.mts | 2 +- .../desktop-build-version-discovery.ts | 4 +- apps/desktop/scripts/desktop-edgeone.ts | 11 ++---- .../scripts/desktop-package-environment.mjs | 2 +- .../scripts/desktop-policy-environment.mjs | 2 +- .../scripts/desktop-publication-summary.ts | 4 +- apps/desktop/scripts/desktop-rollback.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 33 ++-------------- apps/desktop/scripts/desktop-upload-run.ts | 6 ++- apps/desktop/scripts/development-project.ts | 2 +- .../scripts/electron-builder-config.mjs | 2 +- apps/desktop/scripts/installed-update-cos.ts | 4 +- .../scripts/macos-app-update-config.mjs | 2 +- apps/desktop/scripts/package-macos.ts | 2 +- apps/desktop/scripts/package-target.ts | 2 +- .../scripts/preflight-desktop-publish.mjs | 2 +- apps/desktop/scripts/publish-desktop-ci.ts | 16 ++++---- apps/desktop/scripts/retain-desktop-ci.ts | 23 ++++------- .../scripts/rollback-desktop-channel.ts | 8 ++-- apps/desktop/scripts/upload-target.ts | 4 +- .../scripts/verify-retained-desktop.ts | 4 +- .../tests/desktop-publication-summary.spec.ts | 2 +- .../tests/desktop-publish-templates.spec.ts | 2 +- apps/desktop/tests/desktop-rollback.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 22 +++++------ .../desktop/tests/desktop-upload-plan.spec.ts | 6 +-- apps/desktop/tests/desktop-upload-run.spec.ts | 6 +-- .../tests/installed-update-cos.spec.ts | 6 +-- apps/desktop/tests/purge-command.spec.ts | 4 +- apps/desktop/tests/retain-desktop-ci.spec.ts | 2 +- apps/desktop/tests/upload-target.spec.ts | 2 +- pnpm-lock.yaml | 24 ++++++++++++ scripts/check-workspace-constraints.spec.ts | 3 +- scripts/check-workspace-constraints.ts | 6 ++- scripts/desktop-publish-workflow.spec.ts | 4 +- tsconfig.base.json | 1 + tsconfig.host.json | 2 + 87 files changed, 372 insertions(+), 213 deletions(-) create mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/package.json rename apps/{desktop/scripts => desktop-publisher/src}/cos-operation.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-auto-update-environment.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-cos.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publication-failure.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-config.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-cos.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-qualification.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-record.ts (99%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-route.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish-targets.ts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-publish.ts (96%) rename apps/{desktop/scripts => desktop-publisher/src}/desktop-purge-recovery.ts (94%) create mode 100644 apps/desktop-publisher/src/desktop-purge-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-release-store.ts (98%) create mode 100644 apps/desktop-publisher/src/desktop-releases-root.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-rollout.ts (92%) create mode 100644 apps/desktop-publisher/src/desktop-upload-types.ts rename apps/{desktop/scripts => desktop-publisher/src}/desktop-website-installer.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-desktop-rollout-ci.ts (98%) rename apps/{desktop/scripts => desktop-publisher/src}/publish-website-ci.ts (97%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-desktop-publish-ci.ts (95%) rename apps/{desktop/scripts => desktop-publisher/src}/resolve-retained-desktop-publish-ci.ts (95%) rename apps/{desktop => desktop-publisher}/tests/cos-loopback.ts (100%) rename apps/{desktop => desktop-publisher}/tests/cos-operation.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-auto-update-environment.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-package-selection.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publication-failure.spec.ts (89%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-config.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-cos.spec.ts (91%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-record.spec.ts (96%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish-route.spec.ts (98%) rename apps/{desktop => desktop-publisher}/tests/desktop-publish.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-purge-recovery.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-release-store.spec.ts (97%) rename apps/{desktop => desktop-publisher}/tests/desktop-website-installer.spec.ts (94%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-GetObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/cos-PutObject-denied.json (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-accepted.md (100%) rename apps/{desktop => desktop-publisher}/tests/expected/website-purge-unconfirmed.md (100%) create mode 100644 apps/desktop-publisher/tests/isolated-install.mjs rename apps/{desktop => desktop-publisher}/tests/publish-website-ci.spec.ts (97%) create mode 100644 apps/desktop-publisher/tests/workflow.spec.ts diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 32efedf65c..8a1fa4d79d 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -57,7 +57,7 @@ jobs: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -99,7 +99,7 @@ jobs: working-directory: desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts + run: node --import tsx apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts - name: Verify local package without upload credentials id: check working-directory: desktop-publisher @@ -210,7 +210,7 @@ jobs: - name: Upload website installer id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts upload + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true @@ -255,7 +255,7 @@ jobs: - name: Recover and observe website cache purge id: website working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-website-ci.ts purge + run: node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml new file mode 100644 index 0000000000..37ad3220d2 --- /dev/null +++ b/.github/workflows/desktop-publisher-check.yml @@ -0,0 +1,35 @@ +name: Verify Desktop Publisher +on: + pull_request: + paths: + - 'apps/desktop-publisher/**' + - 'apps/desktop/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + - '.github/workflows/desktop-publisher-check.yml' + - '.github/workflows/desktop-rollout.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + isolated-install: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@v5.0.0 + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Install only publisher production dependencies + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without the Desktop or root development dependencies + working-directory: apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 13549da6b4..80932b63f2 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -50,14 +50,15 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - name: Resolve original package and machine id: route env: GH_TOKEN: ${{ github.token }} DESKTOP_PUBLISH_RUNNERS: ${{ vars.DESKTOP_PUBLISH_RUNNERS }} DESKTOP_PACKAGE_ATTEMPT: ${{ steps.preflight.outputs.attempt }} - run: node --import tsx apps/desktop/scripts/resolve-desktop-publish-ci.ts + working-directory: apps/desktop-publisher + run: node --import tsx src/resolve-desktop-publish-ci.ts prepare: needs: route @@ -92,20 +93,20 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts route + run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher + working-directory: desktop-publisher/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + run: node --import tsx src/publish-desktop-rollout-ci.ts check publish: name: Approve ${{ needs.prepare.outputs.label }} @@ -139,16 +140,16 @@ jobs: - name: Check local publication configuration before dependency installation working-directory: desktop-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: desktop-publisher - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts check + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts apply + working-directory: desktop-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true if: always() && steps.publish.outputs.record != '' @@ -191,12 +192,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Upload website installer id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-upload + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' continue-on-error: true @@ -246,12 +247,12 @@ jobs: - name: Check local publication configuration working-directory: website-publisher run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs - - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts working-directory: website-publisher - name: Recover and observe website cache purge id: website - working-directory: website-publisher - run: node --import tsx apps/desktop/scripts/publish-desktop-rollout-ci.ts website-purge + working-directory: website-publisher/apps/desktop-publisher + run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' continue-on-error: true diff --git a/apps/desktop-publisher/package.json b/apps/desktop-publisher/package.json new file mode 100644 index 0000000000..c8aaf573f7 --- /dev/null +++ b/apps/desktop-publisher/package.json @@ -0,0 +1,19 @@ +{ + "name": "@deepseek-ai/dsh-desktop-publisher", + "version": "0.2.2-rc.1", + "description": "Private Desktop release metadata, rollout and website publisher", + "private": true, + "type": "module", + "license": "MIT", + "exports": { + "./*": "./src/*" + }, + "dependencies": { + "zod": "4.6.6", + "js-yaml": "^4.3.2", + "semver": "^7.8.5", + "cos-nodejs-sdk-v5": "3.0.0", + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "tsx": "^4.23.13" + } +} diff --git a/apps/desktop/scripts/cos-operation.ts b/apps/desktop-publisher/src/cos-operation.ts similarity index 100% rename from apps/desktop/scripts/cos-operation.ts rename to apps/desktop-publisher/src/cos-operation.ts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.d.mts b/apps/desktop-publisher/src/desktop-auto-update-environment.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.d.mts rename to apps/desktop-publisher/src/desktop-auto-update-environment.d.mts diff --git a/apps/desktop/scripts/desktop-auto-update-environment.mjs b/apps/desktop-publisher/src/desktop-auto-update-environment.mjs similarity index 100% rename from apps/desktop/scripts/desktop-auto-update-environment.mjs rename to apps/desktop-publisher/src/desktop-auto-update-environment.mjs diff --git a/apps/desktop/scripts/desktop-cos.ts b/apps/desktop-publisher/src/desktop-cos.ts similarity index 97% rename from apps/desktop/scripts/desktop-cos.ts rename to apps/desktop-publisher/src/desktop-cos.ts index 6074d84a05..a117cec4ff 100644 --- a/apps/desktop/scripts/desktop-cos.ts +++ b/apps/desktop-publisher/src/desktop-cos.ts @@ -47,7 +47,7 @@ export function createDesktopCos(credentials: DesktopCosCredentials, timeoutMs: }) cos.on('before-send', (options: CosRequestOptions) => { for (const name of Object.keys(options.headers)) { - if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') delete options.headers[name] + if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') Reflect.deleteProperty(options.headers, name) } }) return cos diff --git a/apps/desktop/scripts/desktop-publication-failure.ts b/apps/desktop-publisher/src/desktop-publication-failure.ts similarity index 100% rename from apps/desktop/scripts/desktop-publication-failure.ts rename to apps/desktop-publisher/src/desktop-publication-failure.ts diff --git a/apps/desktop/scripts/desktop-publish-config.ts b/apps/desktop-publisher/src/desktop-publish-config.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-config.ts rename to apps/desktop-publisher/src/desktop-publish-config.ts diff --git a/apps/desktop/scripts/desktop-publish-cos.ts b/apps/desktop-publisher/src/desktop-publish-cos.ts similarity index 95% rename from apps/desktop/scripts/desktop-publish-cos.ts rename to apps/desktop-publisher/src/desktop-publish-cos.ts index 086303238e..cb89baada6 100644 --- a/apps/desktop/scripts/desktop-publish-cos.ts +++ b/apps/desktop-publisher/src/desktop-publish-cos.ts @@ -5,7 +5,7 @@ import { Readable, Writable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts' import { cosOperation } from './cos-operation.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' @@ -66,7 +66,8 @@ export function desktopPublishCos( if (actual.size !== digest.size || actual.sha512 !== digest.sha512) throw new Error('desktop publish: local input changed') const cos = client() const md5 = createHash('md5') - const bytes = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const bytes = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const chunk of bytes) md5.update(chunk) const body = artifact.contents === undefined ? createReadStream(artifact.path) : Readable.from([Buffer.from(artifact.contents)]) try { diff --git a/apps/desktop/scripts/desktop-publish-qualification.d.mts b/apps/desktop-publisher/src/desktop-publish-qualification.d.mts similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.d.mts rename to apps/desktop-publisher/src/desktop-publish-qualification.d.mts diff --git a/apps/desktop/scripts/desktop-publish-qualification.mjs b/apps/desktop-publisher/src/desktop-publish-qualification.mjs similarity index 100% rename from apps/desktop/scripts/desktop-publish-qualification.mjs rename to apps/desktop-publisher/src/desktop-publish-qualification.mjs diff --git a/apps/desktop/scripts/desktop-publish-record.ts b/apps/desktop-publisher/src/desktop-publish-record.ts similarity index 99% rename from apps/desktop/scripts/desktop-publish-record.ts rename to apps/desktop-publisher/src/desktop-publish-record.ts index 718146b86b..6e1fdd554b 100644 --- a/apps/desktop/scripts/desktop-publish-record.ts +++ b/apps/desktop-publisher/src/desktop-publish-record.ts @@ -108,7 +108,7 @@ export async function findDesktopPublication(root: string, expected: { for (const entry of entries) { if (!entry.isDirectory() || !entry.name.startsWith('publish-')) continue const directory = join(root, entry.name) - let operation + let operation: unknown try { operation = JSON.parse(await readFile(join(directory, 'operation.json'), 'utf8')) } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue throw error diff --git a/apps/desktop/scripts/desktop-publish-route.ts b/apps/desktop-publisher/src/desktop-publish-route.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-route.ts rename to apps/desktop-publisher/src/desktop-publish-route.ts diff --git a/apps/desktop/scripts/desktop-publish-targets.ts b/apps/desktop-publisher/src/desktop-publish-targets.ts similarity index 100% rename from apps/desktop/scripts/desktop-publish-targets.ts rename to apps/desktop-publisher/src/desktop-publish-targets.ts diff --git a/apps/desktop/scripts/desktop-publish.ts b/apps/desktop-publisher/src/desktop-publish.ts similarity index 96% rename from apps/desktop/scripts/desktop-publish.ts rename to apps/desktop-publisher/src/desktop-publish.ts index d11e2bd098..eb0f2a4ab6 100644 --- a/apps/desktop/scripts/desktop-publish.ts +++ b/apps/desktop-publisher/src/desktop-publish.ts @@ -4,7 +4,7 @@ import { createReadStream } from 'node:fs' import { load } from 'js-yaml' import { gt, valid } from 'semver' import { z } from 'zod' -import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-types.ts' /** File identity computed from bytes, never inferred from COS ETags. */ export interface DesktopObjectDigest { readonly size: number; readonly sha512: string } @@ -51,7 +51,8 @@ export class DesktopPublishError extends Error { export async function desktopArtifactDigest(artifact: DesktopUploadArtifact): Promise { const hash = createHash('sha512') let size = 0 - const stream = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)] + const stream = artifact.contents === undefined + ? createReadStream(artifact.path) as AsyncIterable : [Buffer.from(artifact.contents)] for await (const bytes of stream) { hash.update(bytes); size += bytes.length } return { size, sha512: hash.digest('base64') } } @@ -64,7 +65,7 @@ function version(contents: string, remote = false): string { try { const parsed = z.object({ version: z.string() }).parse(load(contents)) if (valid(parsed.version) !== null) return parsed.version - } catch (error) { /* Discard parser error details, which may include raw remote YAML. */ } + } catch (_error) { /* Discard parser error details, which may include raw remote YAML. */ } throw new DesktopPublishError(remote ? 'verification-failed' : 'invalid-plan', `desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`) } diff --git a/apps/desktop/scripts/desktop-purge-recovery.ts b/apps/desktop-publisher/src/desktop-purge-recovery.ts similarity index 94% rename from apps/desktop/scripts/desktop-purge-recovery.ts rename to apps/desktop-publisher/src/desktop-purge-recovery.ts index 890ea003ba..c23cac9ecf 100644 --- a/apps/desktop/scripts/desktop-purge-recovery.ts +++ b/apps/desktop-publisher/src/desktop-purge-recovery.ts @@ -1,6 +1,6 @@ /** Resume a fixed-URL purge without repeating ambiguous submissions. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' -import type { DesktopPurgeConfig } from './desktop-edgeone.ts' +import type { DesktopPurgeConfig } from './desktop-purge-types.ts' /** Non-secret evidence saved before submission and after every observation. */ export interface DesktopPurgeRecord { @@ -65,12 +65,12 @@ async function observe(record: DesktopPurgeRecord, client: DesktopPurgeRecoveryC if (offset >= response.TotalCount) break if (response.Tasks.length === 0 || offset >= 10_000) return unknown('task history could not be fully inspected') } while (true) - } catch (error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } + } catch (_error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') } if (matches.length === 0) return unknown(record.jobId ? 'accepted task not found in query history; execution result unconfirmed' : 'no matching submission found; purge may not have been submitted; inspect EdgeOne history before manual recovery') - if (matches.length !== 1) return unknown('multiple matching submissions found; cannot identify this submission') - const task = matches[0]! + const task = matches[0] + if (matches.length !== 1 || !task) return unknown('multiple matching submissions found; cannot identify this submission') if (!task.JobId || !/^[\w.-]{1,128}$/u.test(task.JobId) || task.JobId.includes(config.secretId) || task.JobId.includes(config.secretKey)) return unknown('query returned no usable task ID') const status = task.Status @@ -115,7 +115,7 @@ export async function recoverDesktopPurge(config: DesktopPurgeConfig, previous: await options.save(record) let response: Awaited> | undefined try { response = await client.CreatePurgeTask({ ZoneId: config.zoneId, Type: 'purge_url', Targets: [config.publicUrl] }) } - catch (error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } + catch (_error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ } const jobId = response?.JobId if (response?.FailedList?.length) { record = { ...record, status: 'failed' } diff --git a/apps/desktop-publisher/src/desktop-purge-types.ts b/apps/desktop-publisher/src/desktop-purge-types.ts new file mode 100644 index 0000000000..c55ec465ab --- /dev/null +++ b/apps/desktop-publisher/src/desktop-purge-types.ts @@ -0,0 +1,7 @@ +/** Validated production destination and credentials; never serialize this value. */ +export interface DesktopPurgeConfig { + readonly zoneId: string + readonly publicUrl: string + readonly secretId: string + readonly secretKey: string +} diff --git a/apps/desktop/scripts/desktop-release-store.ts b/apps/desktop-publisher/src/desktop-release-store.ts similarity index 98% rename from apps/desktop/scripts/desktop-release-store.ts rename to apps/desktop-publisher/src/desktop-release-store.ts index eb9d5457ff..ae7915443c 100644 --- a/apps/desktop/scripts/desktop-release-store.ts +++ b/apps/desktop-publisher/src/desktop-release-store.ts @@ -44,7 +44,7 @@ async function fingerprint(path: string) { if (!info.isFile() || info.isSymbolicLink()) throw new Error('desktop release store: expected a regular file') const hash = createHash('sha512') let size = 0 - for await (const bytes of createReadStream(path)) { size += bytes.length; hash.update(bytes) } + for await (const bytes of createReadStream(path) as AsyncIterable) { size += bytes.length; hash.update(bytes) } if (size === 0) throw new Error('desktop release store: empty artifact') return { size, sha512: hash.digest('base64') } } diff --git a/apps/desktop-publisher/src/desktop-releases-root.ts b/apps/desktop-publisher/src/desktop-releases-root.ts new file mode 100644 index 0000000000..3d7e11c141 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-releases-root.ts @@ -0,0 +1,15 @@ +/** Resolve retained Desktop storage independently of packaging and signing. */ +import { dirname, isAbsolute, join } from 'node:path' + +/** + * Resolve the persistent release root without assuming a particular user's home directory. + * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. + * @returns Absolute directory outside the disposable checkout. + */ +export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { + const configured = env.DSH_PACKAGING_CONFIG_DIR + if (!configured) throw new Error('desktop retention: DSH_PACKAGING_CONFIG_DIR is required') + const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') + if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') + return root +} diff --git a/apps/desktop/scripts/desktop-rollout.ts b/apps/desktop-publisher/src/desktop-rollout.ts similarity index 92% rename from apps/desktop/scripts/desktop-rollout.ts rename to apps/desktop-publisher/src/desktop-rollout.ts index 50750ef1e8..257830b1a3 100644 --- a/apps/desktop/scripts/desktop-rollout.ts +++ b/apps/desktop-publisher/src/desktop-rollout.ts @@ -7,15 +7,15 @@ import { dump, load } from 'js-yaml' import { z } from 'zod' import { desktopUpdateMetadataFilename, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' const percentage = z.number().int().min(0).max(100) const metadataSchema = z.object({ version: z.string(), - files: z.array(z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).passthrough()).length(1), + files: z.tuple([z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).loose()]), path: z.string().optional(), sha512: z.string().optional(), stagingPercentage: percentage.optional(), -}).passthrough() +}).loose() function metadata(contents: string) { if (Buffer.byteLength(contents) > 1024 * 1024) throw new Error('desktop rollout: metadata exceeds 1 MiB') @@ -26,7 +26,7 @@ function metadata(contents: string) { /** Validated immutable update identity; no installer bytes are read. */ export interface DesktopRolloutPlan { - readonly upload: DesktopUploadPlan + readonly upload: DesktopSingleUploadPlan readonly expected: string } @@ -56,7 +56,7 @@ export async function prepareDesktopRollout(directory: string, manifest: Desktop const parsed = metadata(contents) const payload = `deepseek-harness-${source.version}-${source.target}.${windows ? 'exe' : 'zip'}` const file = manifest.files.find(entry => entry.name === payload) - const entry = parsed.files[0]! + const entry = parsed.files[0] if (parsed.version !== source.version || entry.url !== payload || !file || entry.size !== file.size || entry.sha512 !== file.sha512 || (parsed.path !== undefined && parsed.path !== payload) @@ -103,8 +103,9 @@ export function verifyDesktopRolloutFeed(plan: DesktopRolloutPlan, remote: Deskt export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: number | undefined, operations: Pick) { if (target !== undefined) percentage.parse(target) - const artifact = plan.upload.artifacts[0]! + const artifact = plan.upload.artifacts[0] const before = await operations.transport.read(artifact.key, true) + if (!before?.contents) throw new Error('desktop rollout: published update feed is missing') const current = verifyDesktopRolloutFeed(plan, before) const next = target ?? current.percentage if (next < current.percentage) throw new Error('desktop rollout: percentage cannot decrease; inspect the current rollout') @@ -115,8 +116,8 @@ export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: nu const updated = { ...artifact, contents: dump({ ...current.metadata, stagingPercentage: next }) } const digest = await desktopArtifactDigest(updated) const confirmed = await operations.transport.read(artifact.key, true) - if (confirmed?.contents !== before?.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') - await operations.record({ type: 'put-intent', key: artifact.key, before: before!.contents!, after: updated.contents }) + if (confirmed?.contents !== before.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry') + await operations.record({ type: 'put-intent', key: artifact.key, before: before.contents, after: updated.contents }) await operations.transport.put(updated, digest, false) const actual = await operations.transport.read(artifact.key, true) if (actual?.size !== digest.size || actual.sha512 !== digest.sha512) { diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts new file mode 100644 index 0000000000..4faa48b399 --- /dev/null +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -0,0 +1,38 @@ +/** Shared upload contracts for Desktop packaging and publication. */ +import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' + +/** One local file and its final object metadata. */ +export interface DesktopUploadArtifact { + readonly path: string + readonly filename: string + readonly key: string + readonly contentType: string + /** Browser save name for fixed website downloads, preserving the validated installer basename. */ + readonly contentDisposition?: string + readonly channelMetadata: boolean + /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ + readonly contents?: string +} + +/** A validated installer or update upload, with any channel metadata ordered last. */ +export interface DesktopUploadPlan { + readonly environment: 'test' | 'production' + readonly target: DesktopAutoUpdateTarget + readonly version: string + /** Update feed directory URL, or the single installer URL for a fixed download. */ + readonly publicUrl: string + readonly bucket: string + readonly secretIdEnvName: string + readonly secretKeyEnvName: string + readonly artifacts: readonly DesktopUploadArtifact[] + /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ + readonly commit?: string + /** Whether that checkout carried uncommitted changes. */ + readonly dirty?: boolean +} + + +/** A publication operation targeting exactly one metadata object or installer. */ +export type DesktopSingleUploadPlan = Omit & { + readonly artifacts: readonly [DesktopUploadArtifact] +} diff --git a/apps/desktop/scripts/desktop-website-installer.ts b/apps/desktop-publisher/src/desktop-website-installer.ts similarity index 97% rename from apps/desktop/scripts/desktop-website-installer.ts rename to apps/desktop-publisher/src/desktop-website-installer.ts index 8e3838481f..f98cb20252 100644 --- a/apps/desktop/scripts/desktop-website-installer.ts +++ b/apps/desktop-publisher/src/desktop-website-installer.ts @@ -9,11 +9,11 @@ import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from import { cosOperation } from './cos-operation.ts' import type { DesktopObjectDigest, DesktopPublishTransport } from './desktop-publish.ts' import { DesktopCosOperationError } from './desktop-publication-failure.ts' -import type { DesktopUploadPlan } from './desktop-upload-plan.ts' +import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts' /** Verified file and destination; the caller closes the handle after publication. */ export interface DesktopWebsiteInstaller { - readonly plan: DesktopUploadPlan + readonly plan: DesktopSingleUploadPlan readonly digest: DesktopObjectDigest readonly md5: string readonly contentDisposition: string @@ -52,7 +52,7 @@ export async function prepareWebsiteInstaller(directory: string, manifest: Deskt const sha512 = createHash('sha512') const md5 = createHash('md5') let size = 0 - for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 })) { + for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 }) as AsyncIterable) { size += bytes.length sha512.update(bytes) md5.update(bytes) @@ -89,7 +89,7 @@ export async function uploadWebsiteInstaller(installer: DesktopWebsiteInstaller, record: (event: 'upload-intent' | 'uploaded') => Promise, options: { createClient?: typeof createDesktopCos; previouslyUploaded?: boolean } = {}, ): Promise<'uploaded' | 'present'> { - const artifact = installer.plan.artifacts[0]! + const artifact = installer.plan.artifacts[0] const matches = (remote: DesktopObjectDigest | null) => remote?.size === installer.digest.size && remote.sha512 === installer.digest.sha512 const remote = await transport.read(artifact.key, false) diff --git a/apps/desktop/scripts/publish-desktop-rollout-ci.ts b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts similarity index 98% rename from apps/desktop/scripts/publish-desktop-rollout-ci.ts rename to apps/desktop-publisher/src/publish-desktop-rollout-ci.ts index 4ab553b3c3..9a915049f3 100644 --- a/apps/desktop/scripts/publish-desktop-rollout-ci.ts +++ b/apps/desktop-publisher/src/publish-desktop-rollout-ci.ts @@ -4,7 +4,7 @@ import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { resolveRetainedDesktopPublication, retainedDesktopPublishApi } from './resolve-retained-desktop-publish-ci.ts' import { createDesktopPublicationRecord, findDesktopPublication, withDesktopChannelLock } from './desktop-publish-record.ts' @@ -49,7 +49,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) { || source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) { throw new Error('desktop rollout: repository or release qualification mismatch') } - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, source.preset) + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), source.preset) const environment = source.preset === 'test' ? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin, DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket } diff --git a/apps/desktop/scripts/publish-website-ci.ts b/apps/desktop-publisher/src/publish-website-ci.ts similarity index 97% rename from apps/desktop/scripts/publish-website-ci.ts rename to apps/desktop-publisher/src/publish-website-ci.ts index bd3c32f517..00b0ab96c3 100644 --- a/apps/desktop/scripts/publish-website-ci.ts +++ b/apps/desktop-publisher/src/publish-website-ci.ts @@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import { z } from 'zod' import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts' import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts' import { desktopPublishCos } from './desktop-publish-cos.ts' @@ -45,7 +45,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro || !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ATTEMPT || '')) throw new Error('website publication: invalid Actions identity or original machine') const root = desktopReleasesRoot(env) const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt) - const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, 'production') + const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), 'production') const approval = websiteApproval(manifest, config.bucket) if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed') const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID @@ -68,7 +68,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro const installer = await prepareWebsiteInstaller(retainedDesktopPath(root, route.runId, route.attempt), manifest, route, env.GITHUB_REPOSITORY || '', config.bucket) try { - const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0]!.key}`, async () => { + const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0].key}`, async () => { const previouslyUploaded = state.uploadConfirmed === true || state.upload === 'uploaded' return uploadWebsiteInstaller(installer, credentials, desktopPublishCos(installer.plan, credentials), async (event) => { state = event === 'upload-intent' diff --git a/apps/desktop/scripts/resolve-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-desktop-publish-ci.ts index d1ad2264d4..1f7dfce063 100644 --- a/apps/desktop/scripts/resolve-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-desktop-publish-ci.ts @@ -53,12 +53,12 @@ export function selectDesktopPackage(repository: string, inputsValue: unknown, r } packages = packages.filter(job => job.run_attempt === run.run_attempt && job.conclusion === 'success' && job.runner_name) if (packages.length !== 1) throw new Error('desktop publish: expected one successful package job') - const runnerName = packages[0]!.runner_name! + const runnerName = z.string().parse(packages[0]?.runner_name) const routes = desktopPublishRunnersSchema.parse(routesValue) const route = routes[runnerName] const target = (Object.keys(desktopPackageWorkflows) as Array) - .find(name => desktopPackageWorkflows[name] === run.path)! - if (!route || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') + .find(name => desktopPackageWorkflows[name] === run.path) + if (!route || target === undefined || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route') if (new Set(Object.values(routes).map(value => value.label)).size !== Object.keys(routes).length) { throw new Error('desktop publish: each configured machine needs its own unique runner label') } diff --git a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts similarity index 95% rename from apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts rename to apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts index 1f2526e78a..99c50b26fc 100644 --- a/apps/desktop/scripts/resolve-retained-desktop-publish-ci.ts +++ b/apps/desktop-publisher/src/resolve-retained-desktop-publish-ci.ts @@ -2,7 +2,7 @@ import { appendFile } from 'node:fs/promises' import { resolve } from 'node:path' import { z } from 'zod' -import { desktopReleasesRoot } from './retain-desktop-ci.ts' +import { desktopReleasesRoot } from './desktop-releases-root.ts' import { verifyRetainedDesktopRelease } from './desktop-release-store.ts' import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' @@ -15,7 +15,7 @@ import { resolveDesktopPublishRoute } from './desktop-publish-route.ts' */ export async function resolveRetainedDesktopPublication(env: NodeJS.ProcessEnv, api: (path: string) => unknown, readManifest = verifyRetainedDesktopRelease) { - const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).passthrough(), + const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).loose(), jobs: z.array(z.unknown()), routes: z.unknown(), runnerName: z.string() }).parse(JSON.parse(env.DESKTOP_PACKAGE_SELECTION || '{}')) if (!env.GITHUB_REPOSITORY || env.RUNNER_NAME !== selection.runnerName) throw new Error('desktop publish: task was dispatched to a different machine') const manifest = await readManifest(desktopReleasesRoot(env), String(selection.run.id), String(selection.run.run_attempt)) @@ -52,7 +52,7 @@ export function retainedDesktopPublishApi(env: NodeJS.ProcessEnv): (path: string signal: AbortSignal.timeout(60_000), }) if (!response.ok) throw new Error(`desktop publish: GitHub verification request failed (HTTP ${response.status})`) - return response.json() + return response.json() as Promise } } diff --git a/apps/desktop/tests/cos-loopback.ts b/apps/desktop-publisher/tests/cos-loopback.ts similarity index 100% rename from apps/desktop/tests/cos-loopback.ts rename to apps/desktop-publisher/tests/cos-loopback.ts diff --git a/apps/desktop/tests/cos-operation.spec.ts b/apps/desktop-publisher/tests/cos-operation.spec.ts similarity index 96% rename from apps/desktop/tests/cos-operation.spec.ts rename to apps/desktop-publisher/tests/cos-operation.spec.ts index 0a065363a0..d653d2e751 100644 --- a/apps/desktop/tests/cos-operation.spec.ts +++ b/apps/desktop-publisher/tests/cos-operation.spec.ts @@ -1,8 +1,8 @@ import { Readable, Writable } from 'node:stream' import type { ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import { cosOperation } from '../scripts/cos-operation.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback, type CosLoopback } from './cos-loopback.ts' const loopbacks: CosLoopback[] = [] diff --git a/apps/desktop/tests/desktop-auto-update-environment.spec.ts b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-auto-update-environment.spec.ts rename to apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts index 74fabee903..8b49573531 100644 --- a/apps/desktop/tests/desktop-auto-update-environment.spec.ts +++ b/apps/desktop-publisher/tests/desktop-auto-update-environment.spec.ts @@ -7,7 +7,7 @@ import { resolveDesktopAutoUpdateEnvironment, resolveDesktopAutoUpdateTarget, resolveDesktopUploadConfig, -} from '../scripts/desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' const RELEASE_ID = '0123456789abcdef0123456789abcdef' diff --git a/apps/desktop/tests/desktop-package-selection.spec.ts b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-package-selection.spec.ts rename to apps/desktop-publisher/tests/desktop-package-selection.spec.ts index 54d2aaec13..0d5342b2be 100644 --- a/apps/desktop/tests/desktop-package-selection.spec.ts +++ b/apps/desktop-publisher/tests/desktop-package-selection.spec.ts @@ -2,9 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { selectDesktopPackage } from '../scripts/resolve-desktop-publish-ci.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import { retainDesktopRelease, verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { selectDesktopPackage } from '../src/resolve-desktop-publish-ci.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import { retainDesktopRelease, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success', diff --git a/apps/desktop/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts similarity index 89% rename from apps/desktop/tests/desktop-publication-failure.spec.ts rename to apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index 721b839ba8..f8ced04f73 100644 --- a/apps/desktop/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -2,8 +2,8 @@ import { spawnSync } from 'node:child_process' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' import { z } from 'zod' -import { DesktopCosOperationError, desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { DesktopPublishError } from '../scripts/desktop-publish.ts' +import { DesktopCosOperationError, desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { DesktopPublishError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' it('preserves actionable validation and filesystem diagnostics', () => { expect(desktopPublicationFailure(new DesktopPublishError('conflict', 'desktop publish: object differs: bin/app.exe'), 'upload')) @@ -26,7 +26,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) + fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) expect(result.error).toBeUndefined() expect(result.signal).toBeNull() expect(result.status).toBe(1) @@ -47,7 +47,7 @@ it('omits malformed provider receipt fields and never copies raw errors into COS it('prints structured archival failure through the real CLI', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/archive-desktop-ci.ts', import.meta.url))], { + fileURLToPath(new URL('../../desktop/scripts/archive-desktop-ci.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, DESKTOP_ARCHIVE_NAME: '', GITHUB_OUTPUT: '' }, }) expect(result.error).toBeUndefined() @@ -66,7 +66,7 @@ it.each(['percentage cannot decrease; inspect the current rollout', 'feed change it.each([['check', 'extra'], ['route']])('prints actionable rollout CLI failures for %s', (...args) => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', - fileURLToPath(new URL('../scripts/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { + fileURLToPath(new URL('../src/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], { encoding: 'utf8', timeout: 30_000, env: { ...process.env, GITHUB_OUTPUT: '', GH_TOKEN: '' }, }) expect(result.error).toBeUndefined() diff --git a/apps/desktop/tests/desktop-publish-config.spec.ts b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish-config.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-config.spec.ts index 9577581d82..eaf0dd722f 100644 --- a/apps/desktop/tests/desktop-publish-config.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-config.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' it('reads public settings without opening the absent credential file and requires production App settings', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-config-')) diff --git a/apps/desktop/tests/desktop-publish-cos.spec.ts b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts similarity index 91% rename from apps/desktop/tests/desktop-publish-cos.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-cos.spec.ts index 4b42562d40..3b00ae23e7 100644 --- a/apps/desktop/tests/desktop-publish-cos.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-cos.spec.ts @@ -1,10 +1,10 @@ import { expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' -import { desktopArtifactDigest } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { desktopArtifactDigest } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' it.each([true, false])('preserves download headers and verified bytes with overwrite prevention %s', async (forbidOverwrite) => { const objects = new Map() diff --git a/apps/desktop/tests/desktop-publish-record.spec.ts b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts similarity index 96% rename from apps/desktop/tests/desktop-publish-record.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-record.spec.ts index 287af3e4a2..530e9ae3bf 100644 --- a/apps/desktop/tests/desktop-publish-record.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-record.spec.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' import { expect, it } from 'vitest' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '../scripts/desktop-publish-record.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' it('excludes another process while a channel lock is held and admits it after release', async () => { const root = await mkdtemp(join(tmpdir(), 'desktop-process-lock-')) @@ -18,7 +18,7 @@ it('excludes another process while a channel lock is held and admits it after re } ` const contender = () => promisify(execFile)(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script, - new URL('../scripts/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) + new URL('../src/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' }) try { await withDesktopChannelLock(root, 'bucket/mac', async () => { expect((await contender()).stdout).toBe('locked') diff --git a/apps/desktop/tests/desktop-publish-route.spec.ts b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts similarity index 98% rename from apps/desktop/tests/desktop-publish-route.spec.ts rename to apps/desktop-publisher/tests/desktop-publish-route.spec.ts index a4e1acb8a1..049863932e 100644 --- a/apps/desktop/tests/desktop-publish-route.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish-route.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { resolveDesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { resolveDesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' function fixture() { const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), path: '.github/workflows/macos-package.yml', diff --git a/apps/desktop/tests/desktop-publish.spec.ts b/apps/desktop-publisher/tests/desktop-publish.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-publish.spec.ts rename to apps/desktop-publisher/tests/desktop-publish.spec.ts index cf88751230..408129a913 100644 --- a/apps/desktop/tests/desktop-publish.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publish.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' -import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '../scripts/desktop-publish.ts' -import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts' function observed(contents: string): DesktopRemoteObject { return { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') } diff --git a/apps/desktop/tests/desktop-purge-recovery.spec.ts b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-purge-recovery.spec.ts rename to apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts index 2b4781fcce..19b78bd29e 100644 --- a/apps/desktop/tests/desktop-purge-recovery.spec.ts +++ b/apps/desktop-publisher/tests/desktop-purge-recovery.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts' -import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '../scripts/desktop-purge-recovery.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' +import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-recovery.ts' const config = { zoneId: 'zone-test', publicUrl: 'https://download.deepseek.com/desktop/test.dmg', secretId: 'secret-id', secretKey: 'secret-key' } const submittedAt = '2026-10-30T00:00:00.000Z' diff --git a/apps/desktop/tests/desktop-release-store.spec.ts b/apps/desktop-publisher/tests/desktop-release-store.spec.ts similarity index 97% rename from apps/desktop/tests/desktop-release-store.spec.ts rename to apps/desktop-publisher/tests/desktop-release-store.spec.ts index 899b38b8cf..0f0b427a02 100644 --- a/apps/desktop/tests/desktop-release-store.spec.ts +++ b/apps/desktop-publisher/tests/desktop-release-store.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/desktop-website-installer.spec.ts b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts similarity index 94% rename from apps/desktop/tests/desktop-website-installer.spec.ts rename to apps/desktop-publisher/tests/desktop-website-installer.spec.ts index d3c2a2a623..56a717f2a3 100644 --- a/apps/desktop/tests/desktop-website-installer.spec.ts +++ b/apps/desktop-publisher/tests/desktop-website-installer.spec.ts @@ -3,12 +3,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { createDesktopCos } from '../scripts/desktop-cos.ts' -import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' -import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '../scripts/desktop-website-installer.ts' -import type { DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import type { DesktopPublishRoute } from '../scripts/desktop-publish-route.ts' +import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '@deepseek-ai/dsh-desktop-publisher/desktop-website-installer.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts' const roots: string[] = [] afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) diff --git a/apps/desktop/tests/expected/cos-GetObject-denied.json b/apps/desktop-publisher/tests/expected/cos-GetObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-GetObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-GetObject-denied.json diff --git a/apps/desktop/tests/expected/cos-PutObject-denied.json b/apps/desktop-publisher/tests/expected/cos-PutObject-denied.json similarity index 100% rename from apps/desktop/tests/expected/cos-PutObject-denied.json rename to apps/desktop-publisher/tests/expected/cos-PutObject-denied.json diff --git a/apps/desktop/tests/expected/website-purge-accepted.md b/apps/desktop-publisher/tests/expected/website-purge-accepted.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-accepted.md rename to apps/desktop-publisher/tests/expected/website-purge-accepted.md diff --git a/apps/desktop/tests/expected/website-purge-unconfirmed.md b/apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md similarity index 100% rename from apps/desktop/tests/expected/website-purge-unconfirmed.md rename to apps/desktop-publisher/tests/expected/website-purge-unconfirmed.md diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs new file mode 100644 index 0000000000..049c56522f --- /dev/null +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -0,0 +1,18 @@ +/** Run only in a clean checkout after installing this workspace's production dependencies. */ +import '../src/resolve-desktop-publish-ci.ts' +import assert from 'node:assert/strict' +import { existsSync } from 'node:fs' +import { createRequire } from 'node:module' +import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' +import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' +import { teo } from 'tencentcloud-sdk-nodejs-teo' + +const require = createRequire(import.meta.url) +for (const dependency of ['electron', 'electron-builder', 'app-builder-lib', 'react', 'vite', 'typescript']) { + assert.throws(() => require.resolve(dependency), { code: 'MODULE_NOT_FOUND' }, `${dependency} must not be installed`) +} +assert.equal(existsSync(new URL('../../desktop/node_modules', import.meta.url)), false) +assert.equal(typeof teo.v20220901.Client, 'function') +assert.throws(() => desktopReleasesRoot({}), /DSH_PACKAGING_CONFIG_DIR is required/) +await assert.rejects(prepareDesktopRolloutCi({}), /runId/) +console.log('Desktop publisher isolated install: OK (no package build, credentials or remote operations)') diff --git a/apps/desktop/tests/publish-website-ci.spec.ts b/apps/desktop-publisher/tests/publish-website-ci.spec.ts similarity index 97% rename from apps/desktop/tests/publish-website-ci.spec.ts rename to apps/desktop-publisher/tests/publish-website-ci.spec.ts index 2c75150bc4..cdac810fb6 100644 --- a/apps/desktop/tests/publish-website-ci.spec.ts +++ b/apps/desktop-publisher/tests/publish-website-ci.spec.ts @@ -3,10 +3,10 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import * as desktopCos from '../scripts/desktop-cos.ts' +import * as desktopCos from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { answer, cosError, startCosLoopback } from './cos-loopback.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' -import { publishWebsiteCi, websiteApproval } from '../scripts/publish-website-ci.ts' +import { publishWebsiteCi, websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} })) afterEach(() => vi.restoreAllMocks()) diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts new file mode 100644 index 0000000000..738412c54a --- /dev/null +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -0,0 +1,31 @@ +import { existsSync, readFileSync } from 'node:fs' +import { resolve, relative } from 'node:path' +import { load } from 'js-yaml' +import { z } from 'zod' +import { expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '../../..') +const step = z.object({ + uses: z.string().optional(), run: z.string().optional(), + 'working-directory': z.string().optional(), + with: z.object({ path: z.string().optional() }).loose().optional(), +}).loose() +const workflowSchema = z.object({ jobs: z.record(z.string(), z.object({ steps: z.array(step) }).loose()) }) + +it('loads every rollout entry from its own installed package and the correct job checkout', () => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows/desktop-rollout.yml'), 'utf8'))) + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + const install = job.steps.find(entry => entry.run?.includes(' install ')) + expect(install?.run).toContain('--filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts') + for (const entry of job.steps) { + if (!entry.run?.startsWith('node --import tsx ')) continue + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('apps/desktop-publisher') + const script = entry.run.split(' ')[3]! + expect(existsSync(resolve(root, directory, script))).toBe(true) + } + expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) + } +}) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c3cf87bfa4..1642eeecd9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -90,6 +90,7 @@ "zod": "4.6.6", "@deepseek-ai/dsh-util-file-drag": "workspace:*", "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", - "tencentcloud-sdk-nodejs-teo": "4.1.330" + "tencentcloud-sdk-nodejs-teo": "4.1.330", + "@deepseek-ai/dsh-desktop-publisher": "workspace:*" } } diff --git a/apps/desktop/scripts/archive-desktop-ci.ts b/apps/desktop/scripts/archive-desktop-ci.ts index 1517d20dd4..3d36b4fcc6 100644 --- a/apps/desktop/scripts/archive-desktop-ci.ts +++ b/apps/desktop/scripts/archive-desktop-ci.ts @@ -2,9 +2,9 @@ import { execFileSync } from 'node:child_process' import { appendFile, mkdtemp } from 'node:fs/promises' import { join, resolve } from 'node:path' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' /** * Verify an original build without interpreting the archive job's attempt as a new build. diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index 910f3032ee..aaf7159d44 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -1,4 +1,4 @@ -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' /** Mutable target directories plus shared download and package caches. */ export interface DesktopTargetBuildPaths { diff --git a/apps/desktop/scripts/desktop-build-version-discovery.ts b/apps/desktop/scripts/desktop-build-version-discovery.ts index 68291ca3b8..d9e87b6965 100644 --- a/apps/desktop/scripts/desktop-build-version-discovery.ts +++ b/apps/desktop/scripts/desktop-build-version-discovery.ts @@ -20,8 +20,8 @@ import { readdir } from 'node:fs/promises' import { parse } from 'semver' import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_AUTO_UPDATE_ENV, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import type { DesktopPackageTargetName } from './package-target.ts' /** How long the whole bucket listing may take before the suggestion falls back to local artifacts. */ diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index e2faf122a0..dedbd8ad1d 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,16 +1,11 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' -import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -/** Validated production destination and credentials; never serialize this value. */ -export interface DesktopPurgeConfig { - readonly zoneId: string - readonly publicUrl: string - readonly secretId: string - readonly secretKey: string -} +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' +export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ export type DesktopPurgeClient = Pick, 'CreatePurgeTask'> diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 83e9dbbc0f..d301ac4b31 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -5,7 +5,7 @@ import { dirname, isAbsolute, join } from 'node:path' import { fileURLToPath } from 'node:url' import { readDesktopPackageSettings as readSettings } from './desktop-file-settings.mjs' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' import { validateMacOSSignatureCacheDirectory } from './macos-signature-cache-directory.mjs' diff --git a/apps/desktop/scripts/desktop-policy-environment.mjs b/apps/desktop/scripts/desktop-policy-environment.mjs index 591147578b..dafaa417ea 100644 --- a/apps/desktop/scripts/desktop-policy-environment.mjs +++ b/apps/desktop/scripts/desktop-policy-environment.mjs @@ -1,5 +1,5 @@ /** Resolve the required policy service from the same deployment as updater publication. */ -import { resolveDesktopAutoUpdateEnvironment } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateEnvironment } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function origin(value, name) { let url diff --git a/apps/desktop/scripts/desktop-publication-summary.ts b/apps/desktop/scripts/desktop-publication-summary.ts index a9e86575fd..13dfd0ae51 100644 --- a/apps/desktop/scripts/desktop-publication-summary.ts +++ b/apps/desktop/scripts/desktop-publication-summary.ts @@ -3,8 +3,8 @@ import { load } from 'js-yaml' import { z } from 'zod' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' -import { desktopWebsiteInstallerUrl } from './desktop-auto-update-environment.mjs' -import type { DesktopRetainedSource } from './desktop-release-store.ts' +import { desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' function text(value: string): string { diff --git a/apps/desktop/scripts/desktop-rollback.ts b/apps/desktop/scripts/desktop-rollback.ts index a96e5d652b..10eacbe555 100644 --- a/apps/desktop/scripts/desktop-rollback.ts +++ b/apps/desktop/scripts/desktop-rollback.ts @@ -2,7 +2,7 @@ import { load } from 'js-yaml' import { z } from 'zod' import type { DesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts' +import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' /** Outcome of an explicitly requested channel restoration. */ export interface DesktopRollbackResult { diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 39ff954bf5..9c8d9c47e7 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -11,7 +11,7 @@ import { desktopLatestInstallerFilename, desktopUpdateMetadataFilename, resolveDesktopUploadConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' @@ -27,35 +27,8 @@ const TARGETS = { readonly os: string }> -/** One local file and its final object metadata. */ -export interface DesktopUploadArtifact { - readonly path: string - readonly filename: string - readonly key: string - readonly contentType: string - /** Browser save name for fixed website downloads, preserving the validated installer basename. */ - readonly contentDisposition?: string - readonly channelMetadata: boolean - /** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */ - readonly contents?: string -} - -/** A validated installer or update upload, with any channel metadata ordered last. */ -export interface DesktopUploadPlan { - readonly environment: 'test' | 'production' - readonly target: DesktopPackageTargetName - readonly version: string - /** Update feed directory URL, or the single installer URL for a fixed download. */ - readonly publicUrl: string - readonly bucket: string - readonly secretIdEnvName: string - readonly secretKeyEnvName: string - readonly artifacts: readonly DesktopUploadArtifact[] - /** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */ - readonly commit?: string - /** Whether that checkout carried uncommitted changes. */ - readonly dirty?: boolean -} +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index 3bb305afde..ccf528b1f6 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { Readable } from 'node:stream' import type COS from 'cos-nodejs-sdk-v5' import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts' -import { DESKTOP_COS_REGION } from './desktop-cos.ts' +import { DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { recordPackagingEvent } from './packaging-run.mjs' const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'BadDigest', 'SignatureDoesNotMatch', @@ -84,7 +84,9 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re } const sourceSha256: Record = {} for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(join(import.meta.dirname, filename))).digest('hex') + sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' + ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) + : join(import.meta.dirname, filename))).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/development-project.ts b/apps/desktop/scripts/development-project.ts index d544ce6d36..becb8e79a4 100644 --- a/apps/desktop/scripts/development-project.ts +++ b/apps/desktop/scripts/development-project.ts @@ -16,7 +16,7 @@ import { dirname, join } from 'node:path' import { createDevelopmentProjectMetadata } from '../src/project-manager.ts' import type { DesktopRelease } from '../src/release.ts' import { DESKTOP_RUNTIME_FILE, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' -import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs' +import type { DesktopAutoUpdateTarget } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' interface PackageManifest { diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index d5522e3da9..36b0d4e3ba 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -20,7 +20,7 @@ import { resolveWindowsUpdatePublisher, scrubWindowsSigningEnvironment, } from './windows-sign.mjs' -import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' +import { resolveDesktopAutoUpdateConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { resolveDesktopBuildCommit } from './desktop-build-commit.mjs' import { resolveDesktopBuildVersion } from './desktop-build-version.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' diff --git a/apps/desktop/scripts/installed-update-cos.ts b/apps/desktop/scripts/installed-update-cos.ts index 7dcff940b4..dbc4220aa4 100644 --- a/apps/desktop/scripts/installed-update-cos.ts +++ b/apps/desktop/scripts/installed-update-cos.ts @@ -2,8 +2,8 @@ import { createReadStream } from 'node:fs' import { createHash } from 'node:crypto' import { Readable, Writable } from 'node:stream' -import { cosOperation } from './cos-operation.ts' -import { createDesktopCos, DESKTOP_COS_REGION } from './desktop-cos.ts' +import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import type { InstalledUpdatePublicationStore, InstalledUpdateRemoteObject } from './installed-update-publication.ts' diff --git a/apps/desktop/scripts/macos-app-update-config.mjs b/apps/desktop/scripts/macos-app-update-config.mjs index bdb400bcde..40addd5bf3 100644 --- a/apps/desktop/scripts/macos-app-update-config.mjs +++ b/apps/desktop/scripts/macos-app-update-config.mjs @@ -5,7 +5,7 @@ import { join } from 'node:path' import { dump, load } from 'js-yaml' const CONFIG_FILENAME = 'app-update.yml' -import { resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' function object(value, label) { if (typeof value !== 'object' || value === null || Array.isArray(value)) { diff --git a/apps/desktop/scripts/package-macos.ts b/apps/desktop/scripts/package-macos.ts index 4ba0fd12ca..23087c72e6 100644 --- a/apps/desktop/scripts/package-macos.ts +++ b/apps/desktop/scripts/package-macos.ts @@ -13,7 +13,7 @@ import { import { desktopUpdateMetadataFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { verifyMacOSAppUpdateConfig } from './macos-app-update-config.mjs' import { verifyMacOSNotarizedApplication, verifyMacOSSignature } from './verify-macos-signature.mjs' diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index b6bc6efb63..ea244526d5 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -7,7 +7,7 @@ import { join, resolve } from 'node:path' import { desktopBuildRecordFilename, resolveDesktopAutoUpdateConfig, -} from './desktop-auto-update-environment.mjs' +} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopArtifactOutput, desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts' import { loadDesktopPackageEnvironment, localMacOSPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop/scripts/preflight-desktop-publish.mjs index fbe6947398..536f3eefa7 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop/scripts/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop/scripts/publish-desktop-ci.ts b/apps/desktop/scripts/publish-desktop-ci.ts index e3d14abbff..cd60886f2e 100644 --- a/apps/desktop/scripts/publish-desktop-ci.ts +++ b/apps/desktop/scripts/publish-desktop-ci.ts @@ -3,19 +3,19 @@ import { createHash } from 'node:crypto' import { appendFile } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { z } from 'zod' -import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts' +import { readDesktopPublishConfig, readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { desktopReleasesRoot } from './retain-desktop-ci.ts' -import { retainedDesktopPath, verifyRetainedDesktopRelease } from './desktop-release-store.ts' +import { retainedDesktopPath, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyRetainedDesktopSignatures } from './verify-retained-desktop.ts' import { createDesktopUploadPlan } from './desktop-upload-plan.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from './desktop-publish-record.ts' -import { publishDesktopRelease } from './desktop-publish.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { publishDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' import { desktopPublicationSummary } from './desktop-publication-summary.ts' import { publishDesktopTag } from './desktop-publish-tag.ts' -import { websiteApproval } from './publish-website-ci.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' const routeSchema = z.object({ runId: z.string(), attempt: z.string(), commit: z.string(), runnerName: z.string(), sourceRef: z.string(), channel: z.enum(['nightly', 'stable']), diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index e672274992..fb53e9c065 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,13 +1,15 @@ +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' -import { dirname, isAbsolute, join, resolve } from 'node:path' +import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' -import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from './desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' -import { retainDesktopRelease, type DesktopRetainedSource } from './desktop-release-store.ts' +import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { desktopPublishRunnersSchema } from './desktop-publish-targets.ts' -import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' +import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' +import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] @@ -15,17 +17,6 @@ function required(env: NodeJS.ProcessEnv, name: string): string { return value } -/** - * Resolve the persistent release root without assuming a particular user's home directory. - * @param env Machine packaging configuration; an explicit releases directory overrides its sibling default. - * @returns Absolute directory outside the disposable checkout. - */ -export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string { - const configured = required(env, 'DSH_PACKAGING_CONFIG_DIR') - const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases') - if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute') - return root -} /** * Resolve the original machine's unique label before expensive packaging work. diff --git a/apps/desktop/scripts/rollback-desktop-channel.ts b/apps/desktop/scripts/rollback-desktop-channel.ts index fbefbe4f8b..d799d075a3 100644 --- a/apps/desktop/scripts/rollback-desktop-channel.ts +++ b/apps/desktop/scripts/rollback-desktop-channel.ts @@ -4,11 +4,11 @@ import { dirname, join, resolve } from 'node:path' import { parseArgs } from 'node:util' import { z } from 'zod' import { prepareDesktopPublication } from './publish-desktop-ci.ts' -import { readDesktopUploadCredentials } from './desktop-publish-config.ts' -import { desktopPublishCos } from './desktop-publish-cos.ts' -import { createDesktopPublicationRecord, withDesktopChannelLock } from './desktop-publish-record.ts' +import { readDesktopUploadCredentials } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' +import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import { createDesktopPublicationRecord, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' import { rollbackDesktopChannel } from './desktop-rollback.ts' -import { desktopPublicationFailure } from './desktop-publication-failure.ts' +import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts' if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { let phase = 'rollback arguments and local publication verification' diff --git a/apps/desktop/scripts/upload-target.ts b/apps/desktop/scripts/upload-target.ts index a1afdb3241..831d8096f0 100644 --- a/apps/desktop/scripts/upload-target.ts +++ b/apps/desktop/scripts/upload-target.ts @@ -3,8 +3,8 @@ import { resolve } from 'node:path' import { parseArgs } from 'node:util' import type { DesktopPackageTargetName } from './package-target.ts' -import { createDesktopCos } from './desktop-cos.ts' -import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' +import { requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { createDesktopUploadPlan, type DesktopUploadPlan } from './desktop-upload-plan.ts' diff --git a/apps/desktop/scripts/verify-retained-desktop.ts b/apps/desktop/scripts/verify-retained-desktop.ts index 613580da9a..fca85421ad 100644 --- a/apps/desktop/scripts/verify-retained-desktop.ts +++ b/apps/desktop/scripts/verify-retained-desktop.ts @@ -3,8 +3,8 @@ import { execFileSync } from 'node:child_process' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { DesktopRetainedManifest } from './desktop-release-store.ts' -import type { DesktopPublishConfig } from './desktop-publish-config.ts' +import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import type { DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' import { verifyMacOSDiskImage, verifyMacOSNotarizedApplication } from './verify-macos-signature.mjs' /** diff --git a/apps/desktop/tests/desktop-publication-summary.spec.ts b/apps/desktop/tests/desktop-publication-summary.spec.ts index 11ca2d064e..c23273f7b5 100644 --- a/apps/desktop/tests/desktop-publication-summary.spec.ts +++ b/apps/desktop/tests/desktop-publication-summary.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { desktopPublicationSummary } from '../scripts/desktop-publication-summary.ts' -import type { DesktopRetainedSource } from '../scripts/desktop-release-store.ts' +import type { DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' const source: DesktopRetainedSource = { diff --git a/apps/desktop/tests/desktop-publish-templates.spec.ts b/apps/desktop/tests/desktop-publish-templates.spec.ts index 0ead9a11ab..34c2a67d20 100644 --- a/apps/desktop/tests/desktop-publish-templates.spec.ts +++ b/apps/desktop/tests/desktop-publish-templates.spec.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join, posix, win32 } from 'node:path' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' -import { readDesktopPublishConfig, type DesktopPublishConfig } from '../scripts/desktop-publish-config.ts' +import { readDesktopPublishConfig, type DesktopPublishConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts' for (const platform of ['macos', 'windows'] as const) { for (const preset of ['test', 'production'] as const) { diff --git a/apps/desktop/tests/desktop-rollback.spec.ts b/apps/desktop/tests/desktop-rollback.spec.ts index f7912ea09b..4c858bf613 100644 --- a/apps/desktop/tests/desktop-rollback.spec.ts +++ b/apps/desktop/tests/desktop-rollback.spec.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { expect, it } from 'vitest' import { rollbackDesktopChannel } from '../scripts/desktop-rollback.ts' -import type { DesktopPublishOperations } from '../scripts/desktop-publish.ts' +import type { DesktopPublishOperations } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' function fixture() { diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 8109327090..4637982916 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -7,17 +7,17 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { teo } from 'tencentcloud-sdk-nodejs-teo' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopBuildRecordFilename, desktopWebsiteInstallerUrl } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { dump, load } from 'js-yaml' import { expect, it, vi } from 'vitest' -import { prepareDesktopRollout, rolloutDesktopRelease } from '../scripts/desktop-rollout.ts' -import * as cosTransport from '../scripts/desktop-publish-cos.ts' -import * as websitePublisher from '../scripts/publish-website-ci.ts' -import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '../scripts/publish-desktop-rollout-ci.ts' -import { createDesktopPublicationRecord } from '../scripts/desktop-publish-record.ts' -import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '../scripts/desktop-release-store.ts' -import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts' -import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '../scripts/desktop-publish.ts' +import { prepareDesktopRollout, rolloutDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-rollout.ts' +import * as cosTransport from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts' +import * as websitePublisher from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts' +import { prepareDesktopRolloutCi, publishDesktopRolloutCi } from '@deepseek-ai/dsh-desktop-publisher/publish-desktop-rollout-ci.ts' +import { createDesktopPublicationRecord } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts' +import { readRetainedDesktopManifest, type DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' +import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts' +import type { DesktopPublishEvent, DesktopRemoteObject, DesktopPublishTransport } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts' const digest = (contents: string) => ({ size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64'), @@ -284,7 +284,7 @@ it('runs the real route CLI without gh and emits the selected route and preset', routes: { runner: { label: 'dsh-runner', target: 'mac-arm64' } }, } const result = await promisify(execFile)(process.execPath, - ['--import', 'tsx/esm', 'apps/desktop/scripts/publish-desktop-rollout-ci.ts', 'route'], { + ['--import', 'tsx/esm', 'apps/desktop-publisher/src/publish-desktop-rollout-ci.ts', 'route'], { timeout: 30_000, env: { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toLowerCase() !== 'path')), PATH: '', GH_TOKEN: 'fixture-token', GITHUB_API_URL: `http://127.0.0.1:${address.port}`, GITHUB_OUTPUT: output, @@ -403,6 +403,6 @@ it('executes the master guard and keeps all rollout preflights ahead of dependen if (name === 'route') continue const local = job.steps.findIndex(step => step.run?.includes('preflight-desktop-publish-local.mjs')) expect(local).toBeGreaterThanOrEqual(0) - expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) + expect(local).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts')) } }) diff --git a/apps/desktop/tests/desktop-upload-plan.spec.ts b/apps/desktop/tests/desktop-upload-plan.spec.ts index 0d9e90f00d..144b249fb4 100644 --- a/apps/desktop/tests/desktop-upload-plan.spec.ts +++ b/apps/desktop/tests/desktop-upload-plan.spec.ts @@ -6,11 +6,11 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { load } from 'js-yaml' import { createDesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { desktopUpdateMetadataFilename } from '../scripts/desktop-auto-update-environment.mjs' +import { desktopUpdateMetadataFilename } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import type { DesktopPackageTargetName } from '../scripts/package-target.ts' -import { createDesktopCos } from '../scripts/desktop-cos.ts' +import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' -import { startCosLoopback } from './cos-loopback.ts' +import { startCosLoopback } from '../../desktop-publisher/tests/cos-loopback.ts' const temporaryDirectories: string[] = [] const TEST_ORIGIN = 'https://desktop-updates.example.com' diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index 2bbe2a66ab..d3e26bf25b 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -4,10 +4,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it } from 'vitest' -import { createDesktopCos, DESKTOP_COS_REGION } from '../scripts/desktop-cos.ts' +import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] const loopbacks: CosLoopback[] = [] @@ -107,7 +107,7 @@ describe('release upload audit with the real COS SDK and an isolated loopback or expect(plan.sourceSha256['upload-target.ts']).toBe(createHash('sha256') .update(await readFile(join(import.meta.dirname, '../scripts/upload-target.ts'))).digest('hex')) expect(plan.sourceSha256['desktop-cos.ts']).toBe(createHash('sha256') - .update(await readFile(join(import.meta.dirname, '../scripts/desktop-cos.ts'))).digest('hex')) + .update(await readFile(join(import.meta.dirname, '../../desktop-publisher/src/desktop-cos.ts'))).digest('hex')) const result = await json(join(directory, 'result.json')) expect(result).toMatchObject({ success: true, stage: 'complete', confirmedPuts: 2, publicReadback: 'not-performed' }) const events = await journal(join(directory, 'events.jsonl')) diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index ca8dd93ec0..81f9006c4f 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' -import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from './cos-loopback.ts' +import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ settings: 'test', @@ -18,8 +18,8 @@ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackag DOWNLOAD_TEST_COS_SECRET_KEY: 'fixture-key', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin-not-for-sdk', }) })) -vi.mock('../scripts/desktop-cos.ts', async (original) => { - const actual = await original() +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', async (original) => { + const actual = await original() return { ...actual, createDesktopCos: (credentials: Parameters[0]) => { const cos = actual.createDesktopCos(credentials) state.redirect?.(cos) diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index a690db7a35..9b826b0830 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -30,8 +30,10 @@ it('forwards the documented pnpm purge command through both package scripts to t for (const dependency of ['.bin', 'pnpm', 'tsx', 'semver']) { await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } + await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) + await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) - for (const filename of ['desktop-auto-update-environment.mjs', 'desktop-build-paths.mjs']) { + for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) } // Only command forwarding and parsing are under test; all external work fails closed. diff --git a/apps/desktop/tests/retain-desktop-ci.spec.ts b/apps/desktop/tests/retain-desktop-ci.spec.ts index fdddcdf451..48d204e522 100644 --- a/apps/desktop/tests/retain-desktop-ci.spec.ts +++ b/apps/desktop/tests/retain-desktop-ci.spec.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { unzipSync } from 'fflate' import { afterEach, expect, it } from 'vitest' import { desktopReleasesRoot, retainDesktopCi, resolveDesktopRetentionRunner } from '../scripts/retain-desktop-ci.ts' -import { verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts' +import { verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' import { verifyDesktopArchive } from '../scripts/archive-desktop-ci.ts' import { prepareDesktopPublication } from '../scripts/publish-desktop-ci.ts' diff --git a/apps/desktop/tests/upload-target.spec.ts b/apps/desktop/tests/upload-target.spec.ts index 94e9aa5b4f..fa62fbf9d2 100644 --- a/apps/desktop/tests/upload-target.spec.ts +++ b/apps/desktop/tests/upload-target.spec.ts @@ -13,7 +13,7 @@ vi.mock('../scripts/desktop-edgeone.ts', async importOriginal => ({ vi.mock('../scripts/desktop-package-environment.mjs', () => ({ loadDesktopPackageEnvironment: vi.fn() })) vi.mock('../scripts/desktop-upload-plan.ts', () => ({ createDesktopUploadPlan: vi.fn() })) -vi.mock('../scripts/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) +vi.mock('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts', () => ({ createDesktopCos: vi.fn() })) vi.mock('../scripts/desktop-upload-run.ts', () => ({ uploadDesktopRelease: vi.fn() })) vi.mock('../scripts/desktop-release-tag.ts', async importOriginal => ({ ...await importOriginal(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 718a239832..8057f54080 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,6 +734,9 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -843,6 +846,27 @@ importers: specifier: 4.6.6 version: 4.6.6 + apps/desktop-publisher: + dependencies: + zod: + specifier: 4.6.6 + version: 4.6.6 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + apps/desktop-host: dependencies: '@deepseek-ai/cordis': diff --git a/scripts/check-workspace-constraints.spec.ts b/scripts/check-workspace-constraints.spec.ts index a06ff702c2..eb03f5fe29 100644 --- a/scripts/check-workspace-constraints.spec.ts +++ b/scripts/check-workspace-constraints.spec.ts @@ -436,8 +436,7 @@ describe('package payload constraints', () => { }, ) - it('exempts the private plugin market generator from release rules in its own directory only', () => { - const dir = 'apps/plugin-market-generator' + it.each(['apps/plugin-market-generator', 'apps/desktop-publisher'])('exempts private tool %s from release rules in its own directory only', (dir) => { const manifest = JSON.parse(readFileSync(new URL(`../${dir}/package.json`, import.meta.url), 'utf8')) as WorkspaceManifest['manifest'] expect(checkWorkspaceManifest({ dir, manifest })).toEqual([]) expect(checkWorkspaceManifest({ dir: 'apps/other-tool', manifest })).not.toEqual([]) diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index 5356dba419..d13b0324e0 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -63,12 +63,14 @@ const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harn const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/ /** Private reference tool run from the repository; it publishes no files. */ const pluginMarketGeneratorDirectory = 'apps/plugin-market-generator' +/** Source-only private release tool, sharing the Desktop version. */ +const desktopPublisherDirectory = 'apps/desktop-publisher' /** * Ordinary directories whose packages this repository publishes: one release member each. The reference plugin * market generator is a private repository tool, not a published application. */ const standardReleaseMemberDirectory = new RegExp( - `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, + `^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$|${desktopPublisherDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`, 'u', ) /** Installable application assembled by electron-builder rather than published to npm. */ @@ -558,7 +560,7 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st return errors } - if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && manifest.name?.startsWith('@deepseek-ai/')) { + if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && dir !== desktopPublisherDirectory && manifest.name?.startsWith('@deepseek-ai/')) { const expectedFiles = appPackageFiles[manifest.name] if (expectedFiles === undefined) { errors.push(`${label}: app package has no publication files policy`) diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index f6dfa1c4f4..26df0d6b73 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -97,7 +97,7 @@ it('defaults to production website upload and separates cache-only recovery', () expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') } - expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload') - expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge') + expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload') + expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge') expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false) }) diff --git a/tsconfig.base.json b/tsconfig.base.json index 1429e8389a..7208c7f37e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -28,6 +28,7 @@ // not declaration path aliases, keep each package/vendor source compiled // under its own tsconfig boundary. "paths": { + "@deepseek-ai/dsh-desktop-publisher/*": ["./apps/desktop-publisher/src/*"], "@deepseek-ai/dsh-client-ui-file-actions": ["./packages/client/ui-file-actions/src/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/client": ["./packages/client/ui-file-actions/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-file-actions/types": ["./packages/client/ui-file-actions/src/types.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 51393074e9..3465ad1e16 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -245,6 +245,8 @@ "apps/cli/tests/**/*.ts", "apps/plugin-market-generator/tests/**/*.ts", "apps/desktop/scripts/**/*.ts", + "apps/desktop-publisher/src/**/*.ts", + "apps/desktop-publisher/tests/**/*.ts", "apps/desktop/tests/**/*.ts", "apps/desktop-host/tests/**/*.ts", "benchmarks/**/*.ts", From 939d83ab9c4be2f2c3c0fbb3dd8f9734d292ba5b Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:45:31 +0800 Subject: [PATCH 007/122] fix(desktop): validate isolated publisher entrypoints and checkout boundaries --- .github/AGENTS.md | 2 +- .github/workflows/ci-windows.yml | 35 +++++++++++- .github/workflows/ci.yml | 37 ++++++++++++- .github/workflows/desktop-publish.yml | 10 ++-- .github/workflows/desktop-publisher-check.yml | 35 ------------ .github/workflows/desktop-rollout.yml | 54 +++++++++---------- THIRD_PARTY_NOTICES.md | 4 +- apps/desktop-publisher/README.i18n.yaml | 28 ++++++++++ apps/desktop-publisher/README.md | 49 +++++++++++++++++ apps/desktop-publisher/README.zh.md | 49 +++++++++++++++++ .../src/desktop-upload-types.ts | 1 - .../preflight-desktop-publish-local.d.mts | 0 .../src}/preflight-desktop-publish-local.mjs | 0 .../src}/preflight-desktop-publish.d.mts | 0 .../src}/preflight-desktop-publish.mjs | 2 +- .../tests/desktop-publication-failure.spec.ts | 2 +- .../tests/isolated-install.mjs | 2 +- apps/desktop-publisher/tests/preinstall.mjs | 32 +++++++++++ apps/desktop-publisher/tests/workflow.spec.ts | 29 +++++++++- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 1 + apps/desktop/README.zh.md | 1 + apps/desktop/scripts/desktop-edgeone.ts | 2 +- apps/desktop/scripts/desktop-upload-plan.ts | 8 +-- apps/desktop/scripts/desktop-upload-run.ts | 13 +++-- apps/desktop/scripts/retain-desktop-ci.ts | 6 +-- .../desktop-publish-local-preflight.spec.ts | 6 +-- .../tests/desktop-publish-preflight.spec.ts | 2 +- apps/desktop/tests/desktop-rollout.spec.ts | 2 +- apps/desktop/tests/desktop-upload-run.spec.ts | 1 + .../tests/installed-update-cos.spec.ts | 1 + apps/desktop/tests/purge-command.spec.ts | 7 ++- pnpm-lock.yaml | 48 ++++++++--------- scripts/desktop-publish-workflow.spec.ts | 4 +- 34 files changed, 351 insertions(+), 126 deletions(-) delete mode 100644 .github/workflows/desktop-publisher-check.yml create mode 100644 apps/desktop-publisher/README.i18n.yaml create mode 100644 apps/desktop-publisher/README.md create mode 100644 apps/desktop-publisher/README.zh.md rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish-local.mjs (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.d.mts (100%) rename apps/{desktop/scripts => desktop-publisher/src}/preflight-desktop-publish.mjs (96%) create mode 100644 apps/desktop-publisher/tests/preinstall.mjs diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 733b45dac2..ffef007a51 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -8,4 +8,4 @@ The merge checks run from three workflows named `Policy`, which run on `pull_req The manual Desktop publication workflow selects the original successful `package` job attempt independently of `upload-artifact` archival status, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. -`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. +`Publish Desktop · Rollout & Website` reuses the same original-machine routing and approval Environments. Its preparation reads retained metadata and initial publication evidence without revalidating package binaries; it does not create release tags. Cache-only recovery uses the existing website approval and upload journal. Rollout installs only publisher production dependencies in `desktop-rollout` and `website-rollout` checkouts; do not reuse the full-install publication checkouts. Both publication workflows run dependency-free preflights from `apps/desktop-publisher/src`. The required CI verdicts include isolated publisher installation checks: Linux/macOS in `ci.yml`, native Windows in `ci-windows.yml`. diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 47ba28681e..142f4dfbd9 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -23,6 +23,39 @@ concurrency: cancel-in-progress: true jobs: + windows-publisher: + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-2vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') + || 'dsh-windows-2025-16core' }} + defaults: + run: + shell: pwsh + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Native builds and process tests block pull requests independently of coverage. # Observational checks reuse the successful build and remain non-blocking. # Dependabot PRs are excluded from the self-hosted pool and stay queued for @@ -258,7 +291,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [windows-build, windows-native-tests] + needs: [windows-publisher, windows-build, windows-native-tests] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 916971cfa4..d74e2355e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,41 @@ concurrency: cancel-in-progress: true jobs: + publisher-isolated: + strategy: + fail-fast: false + matrix: + os: [linux, macos] + runs-on: >- + ${{ matrix.os == 'macos' && 'macos-latest' + || vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + && github.event.pull_request.user.login != 'dependabot[bot]' + && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') + || 'ubuntu-latest' }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + path: publisher-isolated + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + - name: Check preflights before dependency installation + working-directory: publisher-isolated + run: node apps/desktop-publisher/tests/preinstall.mjs + - uses: pnpm/action-setup@v5.0.0 + with: + package_json_file: publisher-isolated/package.json + dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + - name: Install only publisher production dependencies + working-directory: publisher-isolated + run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts + - name: Load publisher without Desktop or root development dependencies + working-directory: publisher-isolated/apps/desktop-publisher + run: node --import tsx tests/isolated-install.mjs + # Three enterprise jobs isolate coverage, static analysis, and the # build-backed consumer tail. The consumer job owns the only Linux build so @@ -572,7 +607,7 @@ jobs: && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} - needs: [node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] + needs: [publisher-isolated, node-24, node-24-coverage, node-24-lint, node-24-bench, node-24-consumers, node-compat] if: ${{ !cancelled() && github.event_name == 'pull_request' }} steps: - name: Fail if any needed job did not succeed diff --git a/.github/workflows/desktop-publish.yml b/.github/workflows/desktop-publish.yml index 8a1fa4d79d..030a4cb63b 100644 --- a/.github/workflows/desktop-publish.yml +++ b/.github/workflows/desktop-publish.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -91,7 +91,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Resolve retained package and approval environment @@ -136,7 +136,7 @@ jobs: node-version: '24' - name: Check local publication configuration before dependency installation working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: desktop-publisher - name: Verify local package without upload credentials @@ -204,7 +204,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Upload website installer @@ -249,7 +249,7 @@ jobs: node-version: '24' - name: Check local publication configuration working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm install --frozen-lockfile working-directory: website-publisher - name: Recover and observe website cache purge diff --git a/.github/workflows/desktop-publisher-check.yml b/.github/workflows/desktop-publisher-check.yml deleted file mode 100644 index 37ad3220d2..0000000000 --- a/.github/workflows/desktop-publisher-check.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Verify Desktop Publisher -on: - pull_request: - paths: - - 'apps/desktop-publisher/**' - - 'apps/desktop/**' - - 'package.json' - - 'pnpm-lock.yaml' - - 'pnpm-workspace.yaml' - - '.github/workflows/desktop-publisher-check.yml' - - '.github/workflows/desktop-rollout.yml' - workflow_dispatch: -permissions: - contents: read -jobs: - isolated-install: - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - runs-on: ${{ matrix.os }} - timeout-minutes: 15 - steps: - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - - uses: pnpm/action-setup@v5.0.0 - - uses: actions/setup-node@v7.0.0 - with: - node-version: '24' - - name: Install only publisher production dependencies - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - - name: Load publisher without the Desktop or root development dependencies - working-directory: apps/desktop-publisher - run: node --import tsx tests/isolated-install.mjs diff --git a/.github/workflows/desktop-rollout.yml b/.github/workflows/desktop-rollout.yml index 80932b63f2..f2e6bec6d8 100644 --- a/.github/workflows/desktop-rollout.yml +++ b/.github/workflows/desktop-rollout.yml @@ -45,7 +45,7 @@ jobs: id: preflight env: GH_TOKEN: ${{ github.token }} - run: node apps/desktop/scripts/preflight-desktop-publish.mjs + run: node apps/desktop-publisher/src/preflight-desktop-publish.mjs - uses: pnpm/action-setup@v5.0.0 - uses: actions/setup-node@v7.0.0 with: @@ -82,28 +82,28 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Resolve retained package and approval environment id: local - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: GH_TOKEN: ${{ github.token }} run: node --import tsx src/publish-desktop-rollout-ci.ts route - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher env: DESKTOP_PUBLISH_ROUTE: ${{ steps.local.outputs.route }} run: node --import tsx src/publish-desktop-rollout-ci.ts check @@ -129,26 +129,26 @@ jobs: with: persist-credentials: false clean: false - path: desktop-publisher + path: desktop-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: desktop-publisher/package.json + package_json_file: desktop-rollout/package.json dest: ${{ runner.temp }}/publish-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration before dependency installation - working-directory: desktop-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: desktop-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: desktop-publisher + working-directory: desktop-rollout - name: Verify initial publication and metadata without upload credentials id: check - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts check - name: Apply rollout to the published feed id: publish - working-directory: desktop-publisher/apps/desktop-publisher + working-directory: desktop-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts apply - name: Retain publication audit continue-on-error: true @@ -181,22 +181,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Upload website installer id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-upload - name: Archive website feed verification if: always() && steps.website.outputs.rollout-record != '' @@ -236,22 +236,22 @@ jobs: with: persist-credentials: false clean: false - path: website-publisher + path: website-rollout - uses: pnpm/action-setup@v5.0.0 with: - package_json_file: website-publisher/package.json + package_json_file: website-rollout/package.json dest: ${{ runner.temp }}/website-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - uses: actions/setup-node@v7.0.0 with: node-version: '24' - name: Check local publication configuration - working-directory: website-publisher - run: node apps/desktop/scripts/preflight-desktop-publish-local.mjs + working-directory: website-rollout + run: node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs - run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts - working-directory: website-publisher + working-directory: website-rollout - name: Recover and observe website cache purge id: website - working-directory: website-publisher/apps/desktop-publisher + working-directory: website-rollout/apps/desktop-publisher run: node --import tsx src/publish-desktop-rollout-ci.ts website-purge - name: Archive website publication diagnostics if: always() && steps.website.outputs.record != '' diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c38e1a3cea..b932fe3827 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -87,6 +87,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`clsx`](https://github.com/lukeed/clsx) | MIT | | [`commander`](https://github.com/tj/commander.js) | MIT | | [`compression`](https://github.com/expressjs/compression) | MIT | +| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cross-spawn`](https://github.com/moxystudio/node-cross-spawn) | MIT | | [`diff`](https://github.com/kpdecker/jsdiff) | BSD-3-Clause | | [`dompurify`](https://github.com/cure53/DOMPurify) | (MPL-2.0 OR Apache-2.0) | @@ -144,6 +145,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`string_decoder`](https://github.com/nodejs/string_decoder) | MIT | | [`supports-color`](https://github.com/chalk/supports-color) | MIT | | [`tar`](https://github.com/isaacs/node-tar) | BlueOak-1.0.0 | +| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsx`](https://github.com/privatenumber/tsx) | MIT | | [`turndown`](https://github.com/mixmark-io/turndown) | MIT | | [`typescript`](https://github.com/microsoft/TypeScript) | Apache-2.0 | @@ -247,7 +249,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`@yao-pkg/pkg`](https://github.com/yao-pkg/pkg) | MIT | | [`@yarnpkg/cli-dist`](https://github.com/yarnpkg/berry) | BSD-2-Clause | | [`app-builder-lib`](https://github.com/electron-userland/electron-builder) | MIT | -| [`cos-nodejs-sdk-v5`](https://github.com/tencentyun/cos-nodejs-sdk-v5) | ISC | | [`cytoscape`](https://github.com/cytoscape/cytoscape.js) | MIT | | [`cytoscape-cose-bilkent`](https://github.com/cytoscape/cytoscape.js-cose-bilkent) | MIT | | [`dayjs`](https://github.com/iamkun/dayjs) | MIT | @@ -274,7 +275,6 @@ External packages **directly declared** for development, tests, types, or toolin | [`selfsigned`](https://github.com/jfromaniello/selfsigned) | MIT | | [`smol-toml`](https://github.com/squirrelchat/smol-toml) | BSD-3-Clause | | [`spdx-expression-parse`](https://github.com/jslicense/spdx-expression-parse.js) | MIT | -| [`tencentcloud-sdk-nodejs-teo`](https://github.com/tencentcloud/tencentcloud-sdk-nodejs) | Apache-2.0 | | [`tsdown`](https://github.com/rolldown/tsdown) | MIT | | [`typescript-language-server`](https://github.com/typescript-language-server/typescript-language-server) | Apache-2.0 | | [`vite`](https://github.com/vitejs/vite) | MIT | diff --git a/apps/desktop-publisher/README.i18n.yaml b/apps/desktop-publisher/README.i18n.yaml new file mode 100644 index 0000000000..c95af89587 --- /dev/null +++ b/apps/desktop-publisher/README.i18n.yaml @@ -0,0 +1,28 @@ +# 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 apps/desktop-publisher/README.md +/: + en: b6cea27035a6acd8 + zh: c8484ea772e48b76 +/desktop-publisher: + en: 2f3214a4c5f468bd + zh: 0344414f601ce5da +/desktop-publisher/summary: + en: 96e01061bb58ef81 + zh: 34e3e9da3adbdfef +/desktop-publisher/table-of-contents: + en: c910eb62c99ebaae + zh: a39d3e1344eb1b3d +/desktop-publisher/use-this-package: + en: 9678d489d32b9e7b + zh: 6d0ddae4cf96db94 +/desktop-publisher/implementation: + en: 62a7d718a25d4ea4 + zh: 10c8e93749810a15 +/desktop-publisher/limitations: + en: cc71e293492ce240 + zh: 1b9388bf9b108274 +/desktop-publisher/limitations/dev-note: + en: 0a1253c6f7b5e8b9 + zh: 9f56528562c7c914 diff --git a/apps/desktop-publisher/README.md b/apps/desktop-publisher/README.md new file mode 100644 index 0000000000..e4724165b7 --- /dev/null +++ b/apps/desktop-publisher/README.md @@ -0,0 +1,49 @@ +--- +description: "Run Desktop publication and staged rollout from retained packages without installing Desktop build dependencies." +kind: "package-library" +--- +# Desktop publisher + +English | [中文](README.zh.md) + +## Summary + +Publish retained Desktop packages, change an existing release's rollout percentage, and refresh website installers. The manual GitHub workflows select the original packaging machine and require the configured environment approvals. This private workspace shares the repository lockfile and runs TypeScript source directly with Node 24 and tsx. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Implementation](#implementation) +- [Limitations](#limitations) + +## Use this package + +Use [Publish Desktop](../../.github/workflows/desktop-publish.yml) for initial publication and [Rollout & Website](../../.github/workflows/desktop-rollout.yml) for an already published version. The workflows own operator inputs, runner routing, credentials, and approval steps. Rollout installs only this workspace's production dependencies with lifecycle scripts disabled; invoke its entrypoints with Node from this package directory to avoid pnpm's automatic dependency repair. + +The dependency-free preflights run before installation. Their executable regression check is: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## Implementation + +
+Maintainer details + +Desktop build and signing scripts stay in `apps/desktop`; publishing code imports no Desktop implementation. Desktop consumes publisher helpers through the workspace package exports. Runtime dependencies belong in this package's `dependencies`; tests and type checking use repository development tools. The root host TypeScript project checks this source, so there is no separate emitted package or package-local tsconfig. + +Full-install publication and filtered-install rollout use different checkout directories. Changing install modes in one checkout removes development dependency links and can retain stale Desktop directories. Release records live outside these checkouts and remain owned by the existing retained-release configuration. + +Tests under `apps/desktop` may reuse the publisher's loopback COS fixture. Publisher failure tests also exercise the Desktop rollback and archival CLIs as repository integration tests; these test-only paths are not runtime dependencies. The isolated-install CI checks load publisher source without Desktop or root development dependencies on Linux, macOS, and Windows, and contribute to required CI verdicts. + +
+ +## Limitations + +- This private tool is not published to npm and does not generate a standalone artifact. Workflow checkouts must contain the shared lockfile and workspace metadata. +- Isolated-install and preflight tests do not authorize a production write or prove that an installer upgrades a real client. + +### Dev Note + +None. diff --git a/apps/desktop-publisher/README.zh.md b/apps/desktop-publisher/README.zh.md new file mode 100644 index 0000000000..62fcc3dcbf --- /dev/null +++ b/apps/desktop-publisher/README.zh.md @@ -0,0 +1,49 @@ +--- +description: "从保留的安装包执行 Desktop 发布和灰度放量,无需安装 Desktop 构建依赖。" +kind: "package-library" +--- +# Desktop 发布工具 + +[English](README.md) | 中文 + +## 概述 + +发布保留的 Desktop 安装包、调整已发布版本的放量比例,以及刷新官网安装包。手动 GitHub 工作流选择原始打包机器,并要求通过配置的环境审批。此私有 workspace 共用仓库锁文件,通过 Node 24 和 tsx 直接执行 TypeScript 源码。 + +## 目录 + +- [使用此包](#use-this-package) +- [实现](#implementation) +- [限制](#limitations) + +## 使用此包 + +首次发布使用 [Publish Desktop](../../.github/workflows/desktop-publish.yml),已发布版本使用 [Rollout & Website](../../.github/workflows/desktop-rollout.yml)。工作流负责操作输入、运行器路由、凭据和审批步骤。放量仅安装此 workspace 的生产依赖,并禁用生命周期脚本;从此包目录使用 Node 调用入口,避免 pnpm 自动修复依赖。 + +无依赖预检在安装之前运行,其可执行回归检查为: + +```sh +node apps/desktop-publisher/tests/preinstall.mjs +``` + +## 实现 + +
+维护者说明 + +Desktop 构建和签名脚本保留在 `apps/desktop`;发布代码不导入 Desktop 实现。Desktop 通过 workspace 包导出使用发布辅助函数。运行时依赖归此包的 `dependencies` 所有;测试和类型检查使用仓库开发工具。根目录的 host TypeScript 项目检查这些源码,因此没有独立的编译产物或包级 tsconfig。 + +完整安装的发布与筛选安装的放量使用不同 checkout 目录。在同一 checkout 切换安装模式会移除开发依赖链接,也可能保留旧 Desktop 目录。发布记录位于这些 checkout 之外,仍由现有保留版本配置管理。 + +`apps/desktop` 下的测试可以复用发布工具的 loopback COS fixture。发布失败测试还将 Desktop 回滚和归档 CLI 作为仓库集成测试执行;这些测试路径不是运行时依赖。隔离安装 CI 在 Linux、macOS 和 Windows 上验证发布源码无需 Desktop 或根目录开发依赖即可加载,结果纳入必需的 CI 汇总检查。 + +
+ +## 限制 + +- 此私有工具不发布到 npm,也不生成独立产物。工作流 checkout 必须包含共用锁文件和 workspace 元数据。 +- 隔离安装和预检测试不授权生产写入,也不能证明安装包能升级真实客户端。 + +### 开发备注 + +无。 diff --git a/apps/desktop-publisher/src/desktop-upload-types.ts b/apps/desktop-publisher/src/desktop-upload-types.ts index 4faa48b399..48a3982e3a 100644 --- a/apps/desktop-publisher/src/desktop-upload-types.ts +++ b/apps/desktop-publisher/src/desktop-upload-types.ts @@ -31,7 +31,6 @@ export interface DesktopUploadPlan { readonly dirty?: boolean } - /** A publication operation targeting exactly one metadata object or installer. */ export type DesktopSingleUploadPlan = Omit & { readonly artifacts: readonly [DesktopUploadArtifact] diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish-local.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish-local.mjs b/apps/desktop-publisher/src/preflight-desktop-publish-local.mjs similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish-local.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish-local.mjs diff --git a/apps/desktop/scripts/preflight-desktop-publish.d.mts b/apps/desktop-publisher/src/preflight-desktop-publish.d.mts similarity index 100% rename from apps/desktop/scripts/preflight-desktop-publish.d.mts rename to apps/desktop-publisher/src/preflight-desktop-publish.d.mts diff --git a/apps/desktop/scripts/preflight-desktop-publish.mjs b/apps/desktop-publisher/src/preflight-desktop-publish.mjs similarity index 96% rename from apps/desktop/scripts/preflight-desktop-publish.mjs rename to apps/desktop-publisher/src/preflight-desktop-publish.mjs index 536f3eefa7..fbe6947398 100644 --- a/apps/desktop/scripts/preflight-desktop-publish.mjs +++ b/apps/desktop-publisher/src/preflight-desktop-publish.mjs @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { appendFile, readFile } from 'node:fs/promises' import { resolve } from 'node:path' -import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +import { desktopPublishQualificationError } from './desktop-publish-qualification.mjs' /** * Pin the requested attempt and reject its explicitly named debugging artifacts. diff --git a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts index f8ced04f73..b2ab402e2a 100644 --- a/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts +++ b/apps/desktop-publisher/tests/desktop-publication-failure.spec.ts @@ -24,6 +24,7 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie expect(desktopPublicationFailure({ code: 'AccessDenied', statusCode: 403 }, 'upload').message).toContain('HTTP 403') }) +// These repository integration tests execute Desktop CLIs; the publisher runtime never imports them. it('prints rollback usage through the real CLI before any audit or remote operation', () => { const result = spawnSync(process.execPath, ['--import', 'tsx/esm', fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 }) @@ -57,7 +58,6 @@ it('prints structured archival failure through the real CLI', () => { message: 'desktop archival: invalid ZIP output settings' }) }) - it.each(['percentage cannot decrease; inspect the current rollout', 'feed changed before write; inspect and retry', 'written feed is unconfirmed; inspect before retrying'])('retains rollout recovery instructions: %s', (message) => { expect(desktopPublicationFailure(new Error(`desktop rollout: ${message}`), 'desktop rollout')) diff --git a/apps/desktop-publisher/tests/isolated-install.mjs b/apps/desktop-publisher/tests/isolated-install.mjs index 049c56522f..dc4d844c9f 100644 --- a/apps/desktop-publisher/tests/isolated-install.mjs +++ b/apps/desktop-publisher/tests/isolated-install.mjs @@ -1,8 +1,8 @@ /** Run only in a clean checkout after installing this workspace's production dependencies. */ -import '../src/resolve-desktop-publish-ci.ts' import assert from 'node:assert/strict' import { existsSync } from 'node:fs' import { createRequire } from 'node:module' +import '../src/resolve-desktop-publish-ci.ts' import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts' import { desktopReleasesRoot } from '../src/desktop-releases-root.ts' import { teo } from 'tencentcloud-sdk-nodejs-teo' diff --git a/apps/desktop-publisher/tests/preinstall.mjs b/apps/desktop-publisher/tests/preinstall.mjs new file mode 100644 index 0000000000..17647a5192 --- /dev/null +++ b/apps/desktop-publisher/tests/preinstall.mjs @@ -0,0 +1,32 @@ +/** Exercise the pre-install entrypoints in a fixture with no workspace dependency links. */ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { copyFile, mkdtemp, realpath, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +const directory = await realpath(await mkdtemp(join(tmpdir(), 'publisher-preinstall-'))) +try { + for (const filename of ['preflight-desktop-publish.mjs', 'preflight-desktop-publish-local.mjs', 'desktop-publish-qualification.mjs']) { + await copyFile(new URL(`../src/${filename}`, import.meta.url), join(directory, filename)) + } + const { preflightDesktopPublish } = await import(pathToFileURL(join(directory, 'preflight-desktop-publish.mjs')).href) + assert.equal(preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [] }]), '2') + assert.throws(() => preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [{ name: 'windows-x64-unsigned-123-2' }] }]), /unsigned/) + const env = { ...process.env } + for (const key of ['GITHUB_EVENT_PATH', 'GITHUB_REPOSITORY', 'GITHUB_OUTPUT', 'DSH_PACKAGING_CONFIG_DIR', 'NODE_OPTIONS']) Reflect.deleteProperty(env, key) + for (const [filename, diagnostic] of [ + ['preflight-desktop-publish.mjs', 'Actions context required'], + ['preflight-desktop-publish-local.mjs', 'set DSH_PACKAGING_CONFIG_DIR'], + ]) { + const result = spawnSync(process.execPath, [join(directory, filename)], { env, encoding: 'utf8', timeout: 10_000 }) + assert.equal(result.error, undefined) + assert.equal(result.status, 1) + assert.ok(result.stderr.includes(diagnostic), result.stderr) + assert.ok(!result.stderr.includes('ERR_MODULE_NOT_FOUND'), result.stderr) + } + console.log('Desktop publisher pre-install entrypoints: OK') +} finally { + await rm(directory, { recursive: true, force: true }) +} diff --git a/apps/desktop-publisher/tests/workflow.spec.ts b/apps/desktop-publisher/tests/workflow.spec.ts index 738412c54a..0950cfec84 100644 --- a/apps/desktop-publisher/tests/workflow.spec.ts +++ b/apps/desktop-publisher/tests/workflow.spec.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' -import { resolve, relative } from 'node:path' +import { join, resolve, relative } from 'node:path' import { load } from 'js-yaml' import { z } from 'zod' import { expect, it } from 'vitest' @@ -22,10 +22,35 @@ it('loads every rollout entry from its own installed package and the correct job for (const entry of job.steps) { if (!entry.run?.startsWith('node --import tsx ')) continue const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) - expect(directory).toBe('apps/desktop-publisher') + expect(directory).toBe(join('apps', 'desktop-publisher')) const script = entry.run.split(' ')[3]! expect(existsSync(resolve(root, directory, script))).toBe(true) } expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false) } }) + +it.each(['desktop-rollout.yml', 'desktop-publish.yml'])('keeps %s preflights executable before install', (filename) => { + const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + let preflights = 0 + for (const job of Object.values(workflow.jobs)) { + const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@')) + const checkoutRoot = resolve(root, checkout?.with?.path ?? '.') + for (const [index, entry] of job.steps.entries()) { + if (!entry.run?.startsWith('node apps/desktop-publisher/src/preflight-')) continue + preflights++ + const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.')) + expect(directory).toBe('') + expect(existsSync(resolve(root, entry.run.split(' ')[1]!))).toBe(true) + expect(index).toBeLessThan(job.steps.findIndex(candidate => candidate.run?.includes(' install '))) + } + } + expect(preflights).toBe(5) +}) + +it('separates rollout checkouts from full-workspace publication checkouts', () => { + const read = (filename: string) => workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8'))) + const paths = (filename: string) => Object.values(read(filename).jobs).flatMap(job => job.steps.flatMap(entry => entry.uses?.startsWith('actions/checkout@') && entry.with?.path ? [entry.with.path] : [])) + const full = new Set(paths('desktop-publish.yml')) + for (const path of paths('desktop-rollout.yml')) expect(full.has(path)).toBe(false) +}) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dc6cb5f9e0..2216019fba 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -51,8 +51,8 @@ en: 617a89aeb28131b9 zh: 4d84bd5d86501c86 /deepseek-harness-desktop/package: - en: ac31ebdd9de54f34 - zh: 921e534d5c4b3a16 + en: 7200a35dbed997c3 + zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: en: f1302ed4a3ab58bb zh: cb53b9b349815028 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 68596d719f..e531d2c303 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -243,6 +243,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner - [Desktop packaging](packaging/README.md): local and Actions builds, versions, deployment settings, artifacts, logs and verification. - [Windows signing and runner operations](windows-signing/README.md): machine setup, accepted isolation risks, signing credentials, token failures and cache maintenance. - [Desktop publication](publishing/README.md): upload credentials, release identity, fixed downloads, update feeds and upload recovery. +- [Publisher workspace](../desktop-publisher/README.md): dependency ownership and isolated rollout installation. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 13661f0590..239a59e34e 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -243,6 +243,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否 - [Desktop 打包](packaging/README.zh.md):本地与 Actions 构建、版本、部署配置、产物、日志和验收。 - [Windows 签名与 runner 运维](windows-signing/README.zh.md):机器部署、已接受的隔离风险、签名凭据、Token 失败与缓存维护。 - [Desktop 发布](publishing/README.zh.md):上传凭据、发布标识、固定下载、更新清单和上传恢复。 +- [发布工具 workspace](../desktop-publisher/README.zh.md):依赖归属与放量隔离安装。 diff --git a/apps/desktop/scripts/desktop-edgeone.ts b/apps/desktop/scripts/desktop-edgeone.ts index dedbd8ad1d..f1f1875f4a 100644 --- a/apps/desktop/scripts/desktop-edgeone.ts +++ b/apps/desktop/scripts/desktop-edgeone.ts @@ -1,10 +1,10 @@ /** Submit one production fixed-installer cache purge to EdgeOne. */ import type { teo } from 'tencentcloud-sdk-nodejs-teo' import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' import { desktopLatestInstallerFilename, requiredEnvironmentValue, resolveDesktopAutoUpdateEnvironment, resolveDesktopUploadConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { desktopTargetPlatform } from './desktop-build-paths.mjs' -import type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' export type { DesktopPurgeConfig } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-types.ts' /** The single SDK operation needed to submit a purge. */ diff --git a/apps/desktop/scripts/desktop-upload-plan.ts b/apps/desktop/scripts/desktop-upload-plan.ts index 9c8d9c47e7..2e57bdb4c2 100644 --- a/apps/desktop/scripts/desktop-upload-plan.ts +++ b/apps/desktop/scripts/desktop-upload-plan.ts @@ -1,11 +1,12 @@ /** Validate packaged Desktop update artifacts before any network upload begins. */ +import type { DesktopPackageTargetName } from './package-target.ts' +import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' import { createHash } from 'node:crypto' import { createReadStream } from 'node:fs' import { readFile, stat } from 'node:fs/promises' import { basename, join, resolve } from 'node:path' import { dump, load } from 'js-yaml' -import type { DesktopPackageTargetName } from './package-target.ts' import { desktopBuildRecordFilename, desktopLatestInstallerFilename, @@ -15,6 +16,8 @@ import { import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { validateDesktopBuildVersion } from './desktop-build-version.mjs' +export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' + const APP_ROOT = resolve(import.meta.dirname, '..') const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..') const TARGETS = { @@ -27,9 +30,6 @@ const TARGETS = { readonly os: string }> -import type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' -export type { DesktopUploadArtifact, DesktopUploadPlan } from '@deepseek-ai/dsh-desktop-publisher/desktop-upload-types.ts' - /** Filesystem and environment inputs used to validate one upload. */ export interface DesktopUploadPlanOptions { /** Publish only the installer at its fixed download URL, replacing the previous object. */ diff --git a/apps/desktop/scripts/desktop-upload-run.ts b/apps/desktop/scripts/desktop-upload-run.ts index ccf528b1f6..584892e684 100644 --- a/apps/desktop/scripts/desktop-upload-run.ts +++ b/apps/desktop/scripts/desktop-upload-run.ts @@ -13,7 +13,12 @@ const FAILURE_CODES = new Set(['AccessDenied', 'InternalError', 'NoSuchBucket', 'RequestTimeout', 'TimeoutError', 'AbortError', 'ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ENOSPC', 'EACCES', 'EPERM', 'ENOENT']) /** Object keys fingerprinted into every upload record to bind evidence to this uploader. */ -const UPLOADER_SOURCES = ['desktop-upload-run.ts', 'upload-target.ts', 'desktop-upload-plan.ts', 'desktop-cos.ts'] +const UPLOADER_SOURCES = { + 'desktop-upload-run.ts': new URL('./desktop-upload-run.ts', import.meta.url), + 'upload-target.ts': new URL('./upload-target.ts', import.meta.url), + 'desktop-upload-plan.ts': new URL('./desktop-upload-plan.ts', import.meta.url), + 'desktop-cos.ts': new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')), +} async function fingerprint(artifact: DesktopUploadArtifact) { const sha512 = createHash('sha512') @@ -83,10 +88,8 @@ export async function uploadDesktopRelease(plan: DesktopUploadPlan, cos: COS, re artifacts.push({ ...artifact, ...await fingerprint(artifact) }) } const sourceSha256: Record = {} - for (const filename of UPLOADER_SOURCES) { - sourceSha256[filename] = createHash('sha256').update(await readFile(filename === 'desktop-cos.ts' - ? new URL(import.meta.resolve('@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts')) - : join(import.meta.dirname, filename))).digest('hex') + for (const [filename, source] of Object.entries(UPLOADER_SOURCES)) { + sourceSha256[filename] = createHash('sha256').update(await readFile(source)).digest('hex') } await writeFile(join(directory, 'plan.json'), `${JSON.stringify({ schemaVersion: 1, environment: plan.environment, target: plan.target, version: plan.version, bucket: plan.bucket, diff --git a/apps/desktop/scripts/retain-desktop-ci.ts b/apps/desktop/scripts/retain-desktop-ci.ts index fb53e9c065..d26e6a068c 100644 --- a/apps/desktop/scripts/retain-desktop-ci.ts +++ b/apps/desktop/scripts/retain-desktop-ci.ts @@ -1,9 +1,8 @@ -import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' -export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' /** Retain completed CI packages for later manual publication. */ import { appendFile, readFile } from 'node:fs/promises' import { join, resolve } from 'node:path' import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' +import { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' import { desktopBuildRecordFilename, desktopUpdateMetadataFilename, resolveDesktopUpdateChannel } from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs' import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' import { retainDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts' @@ -11,13 +10,14 @@ import { validateDesktopBuildVersion } from './desktop-build-version.mjs' import { desktopPublishRunnersSchema } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-targets.ts' import { desktopPublishQualificationError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-qualification.mjs' +export { desktopReleasesRoot } from '@deepseek-ai/dsh-desktop-publisher/desktop-releases-root.ts' + function required(env: NodeJS.ProcessEnv, name: string): string { const value = env[name] if (!value) throw new Error(`desktop retention: ${name} is required`) return value } - /** * Resolve the original machine's unique label before expensive packaging work. * @param env Machine identity, target and administrator-owned runner mapping. diff --git a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts index 9f5dccd580..56aa918b92 100644 --- a/apps/desktop/tests/desktop-publish-local-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-local-preflight.spec.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { preflightDesktopPublishLocal } from '../scripts/preflight-desktop-publish-local.mjs' +import { preflightDesktopPublishLocal } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish-local.mjs' it('checks the retained preset before approval and the approved preset before upload without opening credentials', async () => { const root = await mkdtemp(join(tmpdir(), 'publish-preflight-')) @@ -39,8 +39,8 @@ it('runs the local preflight before dependency installation in both self-hosted const workflow = await readFile('.github/workflows/desktop-publish.yml', 'utf8') for (const job of ['prepare', 'publish']) { const section = workflow.split(`\n ${job}:`)[1]!.split(/\n \w+:/u)[0]! - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) - expect(section.indexOf('node apps/desktop/scripts/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeGreaterThan(0) + expect(section.indexOf('node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')).toBeLessThan(section.indexOf('pnpm install --frozen-lockfile')) } }) diff --git a/apps/desktop/tests/desktop-publish-preflight.spec.ts b/apps/desktop/tests/desktop-publish-preflight.spec.ts index 755a0ce8a6..0398d58b81 100644 --- a/apps/desktop/tests/desktop-publish-preflight.spec.ts +++ b/apps/desktop/tests/desktop-publish-preflight.spec.ts @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { preflightDesktopPublish } from '../scripts/preflight-desktop-publish.mjs' +import { preflightDesktopPublish } from '@deepseek-ai/dsh-desktop-publisher/preflight-desktop-publish.mjs' it.each([ ['macos-x64-unnotarized-debug-1.0.0-42-2', '跳过了公证'], diff --git a/apps/desktop/tests/desktop-rollout.spec.ts b/apps/desktop/tests/desktop-rollout.spec.ts index 4637982916..c7457ea7bc 100644 --- a/apps/desktop/tests/desktop-rollout.spec.ts +++ b/apps/desktop/tests/desktop-rollout.spec.ts @@ -82,7 +82,7 @@ it.each([ expect(await rolloutDesktopRelease(f.plan, 100, operations)).toEqual({ before: 100, after: 100 }) expect(await rolloutDesktopRelease(f.plan, undefined, operations)).toEqual({ before: 100, after: 100 }) expect(mock.writes).toHaveLength(2) - expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0]!.key])) + expect(new Set(mock.reads)).toEqual(new Set([f.plan.upload.artifacts[0].key])) for (const [index, value] of mock.writes.entries()) { expect(load(value)).toEqual({ ...original, stagingPercentage: index === 0 ? 30 : 100 }) } diff --git a/apps/desktop/tests/desktop-upload-run.spec.ts b/apps/desktop/tests/desktop-upload-run.spec.ts index d3e26bf25b..775bc8e9b8 100644 --- a/apps/desktop/tests/desktop-upload-run.spec.ts +++ b/apps/desktop/tests/desktop-upload-run.spec.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { createDesktopCos, DESKTOP_COS_REGION } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts' import { uploadDesktopRelease } from '../scripts/desktop-upload-run.ts' import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackRequest } from '../../desktop-publisher/tests/cos-loopback.ts' const roots: string[] = [] diff --git a/apps/desktop/tests/installed-update-cos.spec.ts b/apps/desktop/tests/installed-update-cos.spec.ts index 81f9006c4f..f84c77c7a3 100644 --- a/apps/desktop/tests/installed-update-cos.spec.ts +++ b/apps/desktop/tests/installed-update-cos.spec.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import type COS from 'cos-nodejs-sdk-v5' import { afterEach, describe, expect, it, vi } from 'vitest' import { createInstalledUpdateCos } from '../scripts/installed-update-cos.ts' +// Repository-only fixture: deliberately excluded from the publisher runtime exports. import { answer, cosError, startCosLoopback, type CosLoopback, type CosLoopbackResponder } from '../../desktop-publisher/tests/cos-loopback.ts' const state = vi.hoisted(() => ({ diff --git a/apps/desktop/tests/purge-command.spec.ts b/apps/desktop/tests/purge-command.spec.ts index 9b826b0830..8bfcb69a3a 100644 --- a/apps/desktop/tests/purge-command.spec.ts +++ b/apps/desktop/tests/purge-command.spec.ts @@ -31,7 +31,11 @@ it('forwards the documented pnpm purge command through both package scripts to t await symlink(join(root, 'node_modules', dependency), join(directory, 'node_modules', dependency), 'junction') } await mkdir(join(directory, 'node_modules/@deepseek-ai'), { recursive: true }) - await symlink(join(root, 'apps/desktop-publisher'), join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher'), 'junction') + const publisher = join(directory, 'node_modules/@deepseek-ai/dsh-desktop-publisher') + await mkdir(publisher) + await writeFile(join(publisher, 'package.json'), JSON.stringify({ type: 'module', exports: { './*': './*' } })) + await copyFile(join(root, 'apps/desktop-publisher/src/desktop-auto-update-environment.mjs'), join(publisher, 'desktop-auto-update-environment.mjs')) + await writeFile(join(publisher, 'desktop-cos.ts'), "export const createDesktopCos = () => { throw new Error('unexpected COS') }") await copyFile(join(root, 'apps/desktop/scripts/upload-target.ts'), join(scripts, 'upload-target.ts')) for (const filename of ['desktop-build-paths.mjs']) { await copyFile(join(root, 'apps/desktop/scripts', filename), join(scripts, filename)) @@ -39,7 +43,6 @@ it('forwards the documented pnpm purge command through both package scripts to t // Only command forwarding and parsing are under test; all external work fails closed. const stubs = { 'desktop-package-environment.mjs': "export const loadDesktopPackageEnvironment = () => ({ DSH_DESKTOP_AUTO_UPDATE_ENV: 'production' })", - 'desktop-cos.ts': "export const createDesktopCos = () => { throw new Error('unexpected COS') }", 'desktop-upload-plan.ts': "export const createDesktopUploadPlan = () => { throw new Error('unexpected installer read') }", 'desktop-upload-run.ts': "export const uploadDesktopRelease = () => { throw new Error('unexpected upload') }", 'desktop-release-tag.ts': "export const desktopReleaseTag = () => { throw new Error('unexpected tag') }; export const tagDesktopRelease = desktopReleaseTag", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8057f54080..e8468e91e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -734,9 +734,6 @@ importers: specifier: ^8.21.3 version: 8.21.3 devDependencies: - '@deepseek-ai/dsh-desktop-publisher': - specifier: workspace:* - version: link:../desktop-publisher '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../packages/boot/app-boot @@ -767,6 +764,9 @@ importers: '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* version: link:../../packages/credentials/deepseek-account + '@deepseek-ai/dsh-desktop-publisher': + specifier: workspace:* + version: link:../desktop-publisher '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../packages/util/home-paths @@ -846,27 +846,6 @@ importers: specifier: 4.6.6 version: 4.6.6 - apps/desktop-publisher: - dependencies: - zod: - specifier: 4.6.6 - version: 4.6.6 - js-yaml: - specifier: ^4.3.2 - version: 4.3.2 - semver: - specifier: ^7.8.5 - version: 7.8.5 - cos-nodejs-sdk-v5: - specifier: 3.0.0 - version: 3.0.0 - tencentcloud-sdk-nodejs-teo: - specifier: 4.1.330 - version: 4.1.330(supports-color@9.4.0) - tsx: - specifier: ^4.23.13 - version: 4.23.13 - apps/desktop-host: dependencies: '@deepseek-ai/cordis': @@ -928,6 +907,27 @@ importers: specifier: workspace:* version: link:../../packages/util/workspace-path + apps/desktop-publisher: + dependencies: + cos-nodejs-sdk-v5: + specifier: 3.0.0 + version: 3.0.0 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + semver: + specifier: ^7.8.5 + version: 7.8.5 + tencentcloud-sdk-nodejs-teo: + specifier: 4.1.330 + version: 4.1.330(supports-color@9.4.0) + tsx: + specifier: ^4.23.13 + version: 4.23.13 + zod: + specifier: 4.6.6 + version: 4.6.6 + apps/plugin-market-generator: dependencies: '@deepseek-ai/dsh-plugin-market-index': diff --git a/scripts/desktop-publish-workflow.spec.ts b/scripts/desktop-publish-workflow.spec.ts index 26df0d6b73..e6093fe599 100644 --- a/scripts/desktop-publish-workflow.spec.ts +++ b/scripts/desktop-publish-workflow.spec.ts @@ -24,7 +24,7 @@ it('rejects debugging packages before dependency setup and pins the checked atte const preflight = steps.findIndex(step => step.id === 'preflight') expect(preflight).toBeGreaterThan(0) expect(preflight).toBeLessThan(steps.findIndex(step => step.uses?.startsWith('pnpm/'))) - expect(steps[preflight]?.run).toBe('node apps/desktop/scripts/preflight-desktop-publish.mjs') + expect(steps[preflight]?.run).toBe('node apps/desktop-publisher/src/preflight-desktop-publish.mjs') expect(steps.find(step => step.id === 'route')?.env?.DESKTOP_PACKAGE_ATTEMPT).toBe('${{ steps.preflight.outputs.attempt }}') }) @@ -92,7 +92,7 @@ it('defaults to production website upload and separates cache-only recovery', () for (const job of [upload, purge]) { expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'") expect(job.environment).toBe('desktop-production') - const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs') + const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs') expect(preflight).toBeGreaterThan(-1) expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile')) expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}') From fe91df778bbdfe3453b24c5f2b6c75af0c6ff3c6 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:49:30 +0800 Subject: [PATCH 008/122] test(ci): preserve worker limits with required publisher smoke --- .github/workflows/ci-windows.yml | 3 ++- .github/workflows/ci.yml | 4 +++- scripts/ci-workflow.spec.ts | 19 ++++++++++++------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index 142f4dfbd9..c3ea5c58fc 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -48,7 +48,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -63,6 +63,7 @@ jobs: # Blacksmith uses 2 vCPU for file-serial native tests and 16 for coverage # and the shared build/observational workspace. windows-build: + needs: windows-publisher if: github.event_name == 'pull_request' runs-on: >- ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d74e2355e0..fc83d5c7f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ concurrency: jobs: publisher-isolated: strategy: + max-parallel: 1 fail-fast: false matrix: os: [linux, macos] @@ -46,7 +47,7 @@ jobs: - uses: pnpm/action-setup@v5.0.0 with: package_json_file: publisher-isolated/package.json - dest: ${{ runner.temp }}/setup-pnpm-publisher-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }} - name: Install only publisher production dependencies working-directory: publisher-isolated run: pnpm --filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts @@ -494,6 +495,7 @@ jobs: node-compat: + needs: publisher-isolated if: github.event_name == 'pull_request' # Under the selfhosted leg this job admits only repository-owned PR code # to the persistent shared VM; the blacksmith branch targets ephemeral diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index ed7a360894..56bb3f9303 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -41,12 +41,17 @@ describe('CI workflow', () => { }) expect(workflowJob(ci, 'all-checks-passed').needs).toContain('node-compat') const ordinaryJobs = Object.entries(ci.jobs) - .filter(([name]) => !['node-compat', 'all-checks-passed'].includes(name)) + .filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated'].includes(name)) for (const [name, job] of ordinaryJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') expect(job).not.toHaveProperty('uses') } + // Publisher smoke reuses the compatibility/build concurrency slots before those jobs start. + expect(compatibility.needs).toBe('publisher-isolated') + expect(workflowJob(ci, 'publisher-isolated').strategy).toMatchObject({ 'max-parallel': 1, matrix: { os: ['linux', 'macos'] } }) + expect(workflowJob(ciWindows, 'windows-build').needs).toBe('windows-publisher') + expect(workflowJob(ciWindows, 'windows-publisher').defaults).toEqual({ run: { shell: 'pwsh' } }) // Python reports its own required verdict, so neither its jobs nor a // reusable workflow caller remain in the Linux or Windows workflow. expect(Object.keys(ci.jobs).filter(name => name.startsWith('python'))).toEqual([]) @@ -60,7 +65,7 @@ describe('CI workflow', () => { expect(runtime.with).toMatchObject({ targets: 'node24-linux-x64,node24-win-x64' }) expect(runtime.uses).toBe('./.github/workflows/build-exe-for-python-sdk.yml') const windowsJobs = Object.entries(ciWindows.jobs) - .filter(([name]) => name !== 'windows-checks-passed') + .filter(([name]) => !['windows-checks-passed', 'windows-publisher'].includes(name)) for (const [name, job] of windowsJobs) { if (!isRecord(job)) throw new TypeError(`${name} must define a job`) expect(job).not.toHaveProperty('strategy') @@ -95,7 +100,7 @@ describe('CI workflow', () => { expect(afterSdk).toBeLessThanOrEqual(11) }) - it('keeps the union of required PR verdicts equal to the pre-split blocking set', () => { + it('keeps required PR verdicts covering runtime and publisher jobs', () => { const verdicts = [ ['ci.yml', 'all-checks-passed'], ['ci-windows.yml', 'windows-checks-passed'], @@ -112,9 +117,7 @@ describe('CI workflow', () => { expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true) blocking.push(...(verdict.needs as string[])) } - // Splitting the workflows only moves jobs between verdicts; the blocking - // set itself must stay identical, or branch protection would accept a - // failure it rejected before the split. + // Every blocking lane must contribute to a branch-protection verdict. expect(blocking.sort()).toEqual([ 'node-24', 'node-24-bench', @@ -122,10 +125,12 @@ describe('CI workflow', () => { 'node-24-coverage', 'node-24-lint', 'node-compat', + 'publisher-isolated', 'python-runtime', 'python-sdk', 'windows-build', 'windows-native-tests', + 'windows-publisher', ]) }) @@ -547,7 +552,7 @@ describe('CI workflow', () => { expect(aggregate.needs).not.toContain('windows') // windows-coverage is temporarily non-blocking while Windows ACP // half-close tests are stabilized; observational stays out too. - expect(windowsAggregate.needs).toEqual(['windows-build', 'windows-native-tests']) + expect(windowsAggregate.needs).toEqual(['windows-publisher', 'windows-build', 'windows-native-tests']) expect(windowsAggregate.name).toBe('windows checks passed') expect(windowsAggregate['runs-on']).toBe(aggregate['runs-on']) expect(windowsAggregate.if).toBe(aggregate.if) From eea6dfef87de9dfce21359b847d49d9cfa6f15f2 Mon Sep 17 00:00:00 2001 From: winewill Date: Thu, 5 Nov 2026 17:55:24 +0800 Subject: [PATCH 009/122] test(snapshots): refresh terminal runtime context reminder --- snapshots/session/terminal-panel-tools/session.v4.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapshots/session/terminal-panel-tools/session.v4.jsonl b/snapshots/session/terminal-panel-tools/session.v4.jsonl index 01574413c3..290e17f9f6 100644 --- a/snapshots/session/terminal-panel-tools/session.v4.jsonl +++ b/snapshots/session/terminal-panel-tools/session.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:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"My tests fail in my terminal. What does it say?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\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."}],"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":"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-pro"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"session/title","data":{"title":"My tests fail in my","messageSeqs":[8],"source":{"kind":"fallback"}}} From e9591154b4919682faf539e5ea48951d189b3eae Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 17:57:11 +0800 Subject: [PATCH 010/122] fix(sidebar-right): clip the fullscreen divider past the window edge Make the fullscreen panel 1px wider than the viewport instead of hiding the first column's divider with state-dependent rules. At rest the divider sits past the left edge, where the frame clips it, and the pane's content box matches the viewport; during the open and close slides the divider moves with the panel and stays visible. Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- .../src/client/shell/SidebarRight.module.css | 23 +------------------ .../src/client/shell/SidebarRight.tsx | 21 ++++++++--------- .../tests/seat.client.spec.tsx | 9 +++----- .../tests/sidebar-right-styles.client.spec.ts | 14 +---------- 4 files changed, 14 insertions(+), 53 deletions(-) diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css index 454acbcd26..94d08c4f24 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.module.css @@ -83,26 +83,6 @@ --dsh-dockkit-dock-layer: 40; } -/* Once open, fullscreen has no conversation beside the first column, so - dockkit's column-0 divider has nothing to separate. While the panel slides - in or out across the conversation the divider stays: an opening keeps it - for the slide's duration, and a closing panel no longer matches. Only the - color changes, so the pane keeps its width. */ -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-open] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: transparent; -} - -.panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - transition: border-left-color 0s linear var(--ds-transition-duration-slow); -} - -/* A pane mounted by the opening starts with the divider, like one already mounted. */ -@starting-style { - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { - border-left-color: var(--dsw-alias-border-l4); - } -} - /* Dockkit owns its pane exclusions and marked strip rows. Electron composes their boxes in DOM order: a pane subtracts its box, then a marked strip adds its row back. ui-web excludes controls within that row and body portals; @@ -144,8 +124,7 @@ .panel :global([data-dockkit-divider]), .panel[data-sidebar-right-open] :global([data-dockkit-host='dock']), .panel[data-sidebar-right-open] :global([data-dockkit-empty]), - .panel[data-sidebar-right-open] :global([data-dockkit-divider]), - .panel[data-sidebar-right-panel='fullscreen'][data-sidebar-right-opening] :global([data-dockkit-host='dock'][data-dockkit-column='0']) > :global([data-dockkit-pane]) { + .panel[data-sidebar-right-open] :global([data-dockkit-divider]) { transition: none; } } diff --git a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx index 86117bb069..2659481ab6 100644 --- a/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx +++ b/packages/client/ui-sidebar-right/src/client/shell/SidebarRight.tsx @@ -30,7 +30,7 @@ * domain follows each session's store commits, including sessions off screen. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import type { CSSProperties, ReactNode, RefObject, TransitionEvent } from 'react' +import type { CSSProperties, ReactNode, RefObject } from 'react' import type { ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import { IconPanelLeftOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' @@ -305,12 +305,6 @@ function PanelChrome({ sessionId, fullscreen, actions, t, shortcuts, toggleFulls ) } -/** Whether a bubbled transition end is the open slide of a docked Grid item, not a short transition inside one. */ -function slideEnded(event: TransitionEvent): boolean { - return event.propertyName === 'transform' - && (event.target as Element).matches("[data-dockkit-host='dock'], [data-dockkit-empty], [data-dockkit-divider]") -} - /** * The panel: the docked surface with the two controls in its top-right strip, * anchored to the frame's right edge and slid off it while collapsed. @@ -330,8 +324,8 @@ function SidebarPanel(panel: PanelProps & { width: number; panelRef: RefObject { if (slideEnded(event)) setOpening(false) } : undefined} + onTransitionEnd={opening ? () => { setOpening(false) } : undefined} // Dockkit hides individual docked hosts; floating descendants remain accessible. aria-hidden={(!expanded && surface.layout.floats.length === 0) || undefined} > diff --git a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx index 106b3b6bf7..3d1f634711 100644 --- a/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx +++ b/packages/client/ui-sidebar-right/tests/seat.client.spec.tsx @@ -626,11 +626,7 @@ describe('RightbarSeat presentation', () => { // The tab the opening seeds mounts under the mark, so it starts at the closed position. const host = element(h.view.container, "[data-dockkit-host='dock']") expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - // Short transitions inside an item, or other properties, do not end the slide. - fireEvent.transitionEnd(element(host, '[data-dockkit-pane]'), { propertyName: 'transform' }) - fireEvent.transitionEnd(host, { propertyName: 'opacity' }) - expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(true) - fireEvent.transitionEnd(host, { propertyName: 'transform' }) + fireEvent.transitionEnd(host) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) act(() => { h.actions.splitPane(SESSION) }) expect(panel.hasAttribute('data-sidebar-right-opening')).toBe(false) @@ -657,7 +653,8 @@ describe('RightbarSeat presentation', () => { expect(panel.style.width).toBe('420px') fireEvent.click(element(h.view.container, '[data-sidebar-right-mode]')) expect(h.layout().mode).toBe('fullscreen') - expect(panel.style.width).toBe('100vw') + expect(panel.style.width).toBe('calc(1px + 100vw)') + expect(panel.style.getPropertyValue('--dsh-sidebar-width')).toBe('calc(100vw + 1px)') expect(panel.dataset['sidebarRightPanel']).toBe('fullscreen') expect(element(h.view.container, '[data-tab-body]')).toBe(body) expect(h.frame.openRightbar).toHaveBeenLastCalledWith(true, true) diff --git a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts index 19cbfb270f..d59a3c843f 100644 --- a/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts +++ b/packages/client/ui-sidebar-right/tests/sidebar-right-styles.client.spec.ts @@ -1,4 +1,4 @@ -/** Right sidebar slide, fullscreen edge, and reveal-flash style contracts. */ +/** Right sidebar slide and reveal-flash style contracts. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -18,18 +18,6 @@ describe('SidebarRight.module.css', () => { + String.raw`\.panel\[data-sidebar-right-open\] ${host}[^{}]*\{\s*transition: none;\s*}`)) }) - it('hides the first column\'s conversation divider in open fullscreen only after the opening slide', () => { - const fullscreen = String.raw`\.panel\[data-sidebar-right-panel='fullscreen'\]` - const pane = String.raw` :global\(\[data-dockkit-host='dock'\]\[data-dockkit-column='0'\]\) > :global\(\[data-dockkit-pane\]\)` - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-open\]${pane}\s*\{\s*border-left-color: transparent;\s*}`)) - expect(css).toMatch(new RegExp(String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*transition: border-left-color 0s linear var\(--ds-transition-duration-slow\);\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@starting-style\s*\{\s*${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{` - + String.raw`\s*border-left-color: var\(--dsw-alias-border-l4\);\s*}\s*}`)) - expect(css).toMatch(new RegExp(String.raw`@media \(prefers-reduced-motion: reduce\)\s*\{[^{}]*` - + String.raw`${fullscreen}\[data-sidebar-right-opening\]${pane}\s*\{\s*transition: none;\s*}`)) - }) - it('draws the reveal glow inside a docked pane above sticky code banners, and outside a floating panel over its own shadow', () => { const pane = String.raw`\.panel :global\(\[data-dockkit-pane\]\[data-sidebar-right-flash\]\)` const float = String.raw`\.panel :global\(\[data-dockkit-float\]\[data-sidebar-right-flash\]\)` From fa0b1522cb5ddc120b2135c503a8cbc4e9e5c5ac Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 18:41:39 +0800 Subject: [PATCH 011/122] test(web): expect the fullscreen sidebar 1px past the left edge Co-authored-by: std4453 <13191718+std4453@users.noreply.github.com> --- apps/web/tests/details-session-lifecycle.e2e.ts | 14 +++++++------- apps/web/tests/sidebar-right.e2e.ts | 12 ++++++------ apps/web/tests/support.ts | 10 ++++++++++ .../details-session-lifecycle/sidebar.expected.md | 12 ++++++------ 4 files changed, 29 insertions(+), 19 deletions(-) diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index e73eaa5d0b..05da4a6afa 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -10,7 +10,7 @@ import { fixtureUserPrompts, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' +import { connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/details-session-lifecycle', import.meta.url)) const HANDLES_EXPECTED = join(SNAPSHOT_DIR, 'handles.expected.md') @@ -110,8 +110,8 @@ async function sidebarSnapshot(page: Page) { mode: panel.getAttribute('data-sidebar-right-panel'), panelContentWidth: expanded ? Math.round(Number.parseFloat(style.width)) : 0, panelOuterWidth: expanded ? Math.round(rect.width) : 0, - coversViewport: expanded && rect.x === 0 && rect.y === 0 - && Math.round(rect.width) === window.innerWidth && Math.round(rect.height) === window.innerHeight, + coversViewport: expanded && rect.x === -1 && rect.y === 0 + && Math.round(rect.width) === window.innerWidth + 1 && Math.round(rect.height) === window.innerHeight, resizeHandleWidth: handle === null ? 0 : Math.round(handle.getBoundingClientRect().width), expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] button[aria-expanded="true"]')] .map(button => button.textContent?.trim()), @@ -195,7 +195,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await expect.poll(() => blankColumn.locator('[data-dockkit-host="dock"]:not([hidden])').evaluate(element => getComputedStyle(element).transform)) .toBe('none') await expect.poll(() => blankColumn.locator('[data-sidebar-right-panel]').boundingBox()) - .toEqual({ x: 0, y: 0, width: 767, height: blankViewport.height }) + .toEqual(fullscreenBox({ width: 767, height: blankViewport.height })) // A preview the files page opened starts with its tree hidden; shown, the tree fills the viewport. const treeToggle = blankColumn.locator('[data-files-navigator-toggle]') await expect.poll(() => treeToggle.getAttribute('aria-expanded')).toBe('false') @@ -360,7 +360,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await checkpoint('A normal: two panes') await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await columns(page)).toEqual(normalColumns) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) expect(await paneSnapshot(page)).toEqual(retainedA) @@ -395,7 +395,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') expect(await paneSnapshot(page)).toEqual(retainedA) await open() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await paneSnapshot(page)).toEqual(retainedA) await checkpoint('A restored: manual fullscreen, tabs, and panes') await column.locator('[data-sidebar-right-mode="push"]').click() @@ -433,7 +433,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await page.locator('[data-sidebar-right-expand]').click() await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420 - normalWidth, normalWidth]) await page.setViewportSize({ width: 767, height: viewport.height }) - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, width: 767, height: viewport.height }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox({ width: 767, height: viewport.height })) await expect.poll(() => columns(page)).toEqual([0, 767, 0]) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) await checkpoint('A automatic fullscreen at 767px') diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 461947ed21..c66eba54db 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -26,7 +26,7 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { acknowledgeReloadConnectionLoss, launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' import { - connectFreshWorkspace, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, + connectFreshWorkspace, fullscreenBox, newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE, } from './support.ts' /** The produced file the seeded turn writes, and what the preview should show. */ @@ -524,7 +524,7 @@ describe('web e2e: shipped right Sidebar', () => { expect(await width(column)).toBe(trackWidth) const viewport = page.viewportSize() if (viewport === null) throw new Error('expected a fixed viewport') - await expect.poll(async () => await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(async () => await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) await shot(page, '03-fullscreen-panel') @@ -558,7 +558,7 @@ describe('web e2e: shipped right Sidebar', () => { await frame.evaluate(async (node) => { await Promise.allSettled(node.getAnimations().map(animation => animation.finished)) }) const normalColumns = (await geometry()).columns await column.locator('[data-sidebar-right-mode="fullscreen"]').click() - await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + await expect.poll(() => panel.boundingBox()).toEqual(fullscreenBox(viewport)) await column.locator('[data-sidebar-right-toggle]').click() await Promise.all([ panel.evaluate(async (node) => { @@ -586,7 +586,7 @@ describe('web e2e: shipped right Sidebar', () => { await held.evaluate((state) => { (state.animation as Animation).finish() }) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect(await geometry()).toEqual({ columns: normalColumns, transition: 'none', handles: ['none'], animatingGrid: false }) const exit = await holdPanelSlide(panel) @@ -621,7 +621,7 @@ describe('web e2e: shipped right Sidebar', () => { await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBeNull() await expandOf(page).click() await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') - expect(await panel.boundingBox()).toEqual({ x: 0, y: 0, ...viewport }) + expect(await panel.boundingBox()).toEqual(fullscreenBox(viewport)) expect((await geometry()).columns).toBe(normalColumns) expect((await geometry()).animatingGrid).toBe(false) } finally { @@ -733,7 +733,7 @@ describe('web e2e: shipped right Sidebar', () => { await page.setViewportSize({ width: 767, height: viewport.height }) await expect.poll(async () => await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') - await expect.poll(async () => await width(panel)).toBe(767) + await expect.poll(async () => await width(panel)).toBe(768) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index cda15bafaf..ec7b5b1404 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -468,3 +468,13 @@ export async function openSettings(page: Page, locale: 'en' | 'zh' | 'ja'): Prom await trigger.click() await page.getByRole('menuitem', { name: labels[locale][1], exact: true }).click() } + +/** + * The right Sidebar's fullscreen panel box: 1px wider than the viewport, so the + * first column's divider sits past the window's left edge where the frame clips it. + * @param viewport - the page viewport size. + * @returns the panel's expected bounding box. + */ +export function fullscreenBox(viewport: { width: number; height: number }): { x: number; y: number; width: number; height: number } { + return { x: -1, y: 0, width: viewport.width + 1, height: viewport.height } +} diff --git a/snapshots/web/details-session-lifecycle/sidebar.expected.md b/snapshots/web/details-session-lifecycle/sidebar.expected.md index f205ed9765..4607cf35ed 100644 --- a/snapshots/web/details-session-lifecycle/sidebar.expected.md +++ b/snapshots/web/details-session-lifecycle/sidebar.expected.md @@ -64,8 +64,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -197,8 +197,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 1680, - "panelOuterWidth": 1680, + "panelContentWidth": 1681, + "panelOuterWidth": 1681, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], @@ -424,8 +424,8 @@ "columnTransition": "none", "expanded": true, "mode": "fullscreen", - "panelContentWidth": 767, - "panelOuterWidth": 767, + "panelContentWidth": 768, + "panelOuterWidth": 768, "coversViewport": true, "resizeHandleWidth": 0, "expandedDirectories": [], From ac96c518fb2de7f4700db38531533f1815147164 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:31:24 +0800 Subject: [PATCH 012/122] ci(preview): publish a snapshot diff page with each PR preview Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .../workflows/build-preview-cloudflare.yml | 32 ++- scripts/preview-workflow.spec.ts | 14 +- scripts/snapshot-diff-page.spec.ts | 76 ++++++ scripts/snapshot-diff-page.ts | 223 ++++++++++++++++++ 4 files changed, 333 insertions(+), 12 deletions(-) create mode 100644 scripts/snapshot-diff-page.spec.ts create mode 100644 scripts/snapshot-diff-page.ts diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index 5625d75a9c..c8cb718234 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -43,9 +43,12 @@ jobs: || 'ubuntu-24.04' }} name: cloudflare pages preview steps: + # The pull_request checkout is the merge commit; depth 2 brings its first + # parent, the base branch tip, for the snapshot diff page. - uses: actions/checkout@v7.0.1 with: persist-credentials: false + fetch-depth: 2 - uses: pnpm/action-setup@v5.0.0 with: @@ -98,6 +101,11 @@ jobs: find apps/web/dist -name '*.map' -delete cp apps/web/dist/preview.html apps/web/dist/index.html + # Reviewers read snapshot changes at /snapshot-diff/, which opens on the + # SDK blank-Session catalog (system prompt and tool schemas). + - name: Render the snapshot diff page + run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + - name: Upload to Cloudflare Pages id: upload continue-on-error: true @@ -164,7 +172,8 @@ jobs: # The alias URL follows from the pull request number, so it is stable # across redeploys and worth stating once. The marker makes the comment # idempotent: a pull request opened before this workflow existed never - # sees an `opened` event, and every later push must not restate the URL. + # sees an `opened` event, and every later push must not restate the URL; + # an existing comment with older text is edited in place. - name: Comment the preview URL id: comment continue-on-error: true @@ -173,18 +182,21 @@ jobs: PR: ${{ github.event.pull_request.number }} run: | marker='' - existing=$(gh pr view "$PR" --json comments \ - --jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty") - if [ -n "$existing" ]; then - echo "preview URL already commented: $existing" - exit 0 - fi + url="https://pr-$PR.${CF_PROJECT}.pages.dev" # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - printf '%s\n\n%s\n' \ + body=$(printf '%s\n\n%s\n' \ "$marker" \ - "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \ - | gh pr comment "$PR" --body-file - + "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ + --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + if [ -z "$existing" ]; then + printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null + else + echo "preview URL already commented" + fi # Publishing stays outside the required verdict: a Cloudflare, Access, or # comment failure warns, while a build failure still fails this check. diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index e38f18b776..bd21bc2c0a 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -25,12 +25,12 @@ describe('PR preview workflow', () => { expect(preview['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') expect(workflow.on).toEqual({ pull_request: { types: ['opened', 'synchronize', 'reopened'] } }) expect(workflow.permissions).toEqual({ contents: 'read', 'pull-requests': 'write' }) - expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false }) + expect(preview.steps.find(step => step.uses === 'actions/checkout@v7.0.1')?.with).toEqual({ 'persist-credentials': false, 'fetch-depth': 2 }) }) it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { @@ -79,5 +79,15 @@ describe('PR preview workflow', () => { const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.run).toContain('gh api -X PATCH') + }) + + it('renders the snapshot diff page into the upload against the base branch tip', () => { + const steps = preview.steps.map(step => step.name) + const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) + expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts new file mode 100644 index 0000000000..5147ec6dd0 --- /dev/null +++ b/scripts/snapshot-diff-page.spec.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' + +const limits = { fileLines: 100, totalChars: 10_000 } + +const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md +index 1111111..2222222 100644 +--- a/snapshots/sdk/text-turn/system-prompt.expected.md ++++ b/snapshots/sdk/text-turn/system-prompt.expected.md +@@ -1,2 +1,2 @@ + You are an agent. +-Old rule. ++New rule. +diff --git a/snapshots/web/ptc-round/session.jsonl b/snapshots/web/ptc-round/session.jsonl +deleted file mode 100644 +index 3333333..0000000 +--- a/snapshots/web/ptc-round/session.jsonl ++++ /dev/null +@@ -1 +0,0 @@ +-{"type":"header"} +diff --git a/snapshots/web/ptc-round/image.png b/snapshots/web/ptc-round/image.png +new file mode 100644 +index 0000000..4444444 +Binary files /dev/null and b/snapshots/web/ptc-round/image.png differ +diff --git a/snapshots/web/present/workspace.expected/a b/说明.txt b/snapshots/web/present/workspace.expected/a b/说明.txt +old mode 100644 +new mode 100755 +` + +const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + +describe('snapshot diff page', () => { + it('splits git diff output into files with their hunks', () => { + expect(parseUnifiedDiff(diff, limits)).toEqual([ + { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, + { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, + { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + ]) + expect(parseUnifiedDiff('', limits)).toEqual([]) + }) + + it('rejects paths git still quotes', () => { + expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + }) + + it('truncates long files and drops hunks once the total budget is spent', () => { + const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` + const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) + expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) + expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) + expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + }) + + it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { + const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) + expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ + ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], + ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + ]) + }) + + it('lists a path once when a type change splits it into two sections', () => { + const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } + const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } + expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + }) + + it('embeds the data so diff text cannot close the script element', () => { + const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + expect(page).not.toContain('') + const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + }) +}) diff --git a/scripts/snapshot-diff-page.ts b/scripts/snapshot-diff-page.ts new file mode 100644 index 0000000000..e4f6bbdc96 --- /dev/null +++ b/scripts/snapshot-diff-page.ts @@ -0,0 +1,223 @@ +/** + * Renders the PR preview's snapshot diff page: one self-contained HTML file + * listing every changed file under `snapshots/` between two revisions, grouped + * by scenario directory. The page opens on the SDK blank-Session catalog, the + * system prompt and tool schemas the `sdk/text-turn` scenario's first request + * carries, and shows "No change" when neither file changed. + * + * Usage: `tsx scripts/snapshot-diff-page.ts --base --head --out ` + */ +import { execFileSync } from 'node:child_process' +import { mkdirSync, writeFileSync } from 'node:fs' +import { dirname } from 'node:path' +import { parseArgs } from 'node:util' +import * as yaml from 'js-yaml' + +/** Scenario whose first request represents a blank SDK Session. */ +const CATALOG_SCENARIO = 'snapshots/sdk/text-turn' + +/** Per-file and total limits on embedded diff text; the page notes what it omits. */ +export interface DiffLimits { + readonly fileLines: number + readonly totalChars: number +} + +/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit and responsive in a browser. */ +const LIMITS: DiffLimits = { fileLines: 2000, totalChars: 8_000_000 } + +/** One `diff --git` section: a changed file and its unified diff text. */ +export interface FileDiff { + /** Repository-relative path. */ + readonly path: string + /** Unified diff lines from the first `@@` hunk header, empty for binary or mode-only changes. */ + readonly hunks: string + /** True when git reports a binary change. */ + readonly binary: boolean + /** Hunk lines left out of `hunks` by the limits. */ + readonly omitted: number +} + +/** A selectable group of file diffs on the page. */ +export interface DiffGroup { + readonly title: string + /** Distinct paths the group covers, including unchanged ones. */ + readonly paths: readonly string[] + readonly files: readonly FileDiff[] +} + +/** + * Splits git diff output into per-file sections. + * @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames`; + * a path git still quotes (one with `"`, `\\`, or a control character) is rejected. + * @param limits - Lines kept per file and characters kept across all files. + * @returns One entry per `diff --git` section, in output order. A path that + * changes between symlink and regular file has two sections. + */ +export function parseUnifiedDiff(text: string, limits: DiffLimits = LIMITS): FileDiff[] { + const files: FileDiff[] = [] + let budget = limits.totalChars + for (const section of text.split(/^(?=diff --git )/m)) { + if (!section.startsWith('diff --git ')) continue + const lines = section.split('\n') + // Without renames the header is `diff --git a/ b/` with both paths equal. + const header = section.slice('diff --git '.length, section.indexOf('\n') === -1 ? undefined : section.indexOf('\n')) + if (header.startsWith('"')) throw new Error(`unsupported quoted path in git diff header: ${header}`) + const path = header.slice('a/'.length, (header.length - ' '.length) / 2) + const hunkStart = lines.findIndex(line => line.startsWith('@@')) + const all = hunkStart === -1 ? [] : lines.slice(hunkStart, lines.at(-1) === '' ? -1 : undefined) + let kept = all.slice(0, limits.fileLines) + let hunks = kept.join('\n') + if (hunks.length > budget) { + kept = [] + hunks = '' + } + budget -= hunks.length + files.push({ path, hunks, binary: lines.some(line => line.startsWith('Binary files ')), omitted: all.length - kept.length }) + } + return files +} + +/** + * Groups changed files for the page: the catalog first, then one group per + * scenario directory (`snapshots//`) in path order. + * @param files - Changed files under `snapshots/`. + * @param catalogPaths - Files that make up the SDK blank-Session catalog. + * @returns The catalog group followed by the scenario groups. + */ +export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly string[]): DiffGroup[] { + const scenarios = new Map() + for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) { + const key = file.path.split('/').slice(0, 3).join('/') + scenarios.set(key, [...scenarios.get(key) ?? [], file]) + } + return [ + { title: 'SDK blank Session catalog', paths: catalogPaths, files: files.filter(file => catalogPaths.includes(file.path)) }, + ...[...scenarios].map(([key, group]) => ({ title: key.replace(/^snapshots\//, ''), paths: [...new Set(group.map(file => file.path))], files: group })), + ] +} + +/** + * Renders the self-contained page. + * @param groups - Groups from {@link groupDiffs}; the first one opens by default. + * @param heading - Revision description shown under the title. + * @returns HTML text. + */ +export function renderSnapshotDiffPage(groups: readonly DiffGroup[], heading: string): string { + const data = JSON.stringify({ groups, heading }).replace(/ + + + + +Snapshot changes + + + + +
+ + + + +` +} + +/** + * Reads the catalog files from the catalog scenario's `snapshot.yml`. + * @param rev - Revision to read. + * @returns The system prompt sidecar and the tool schema sidecar, which lives + * in the scenario named by `header.toolSchemasSource` when present. + */ +function catalogPaths(rev: string): string[] { + const spec = yaml.load(git('show', `${rev}:${CATALOG_SCENARIO}/snapshot.yml`), { schema: yaml.JSON_SCHEMA }) as { header?: { toolSchemasSource?: unknown } } + const source = spec.header?.toolSchemasSource + if (source !== undefined && typeof source !== 'string') throw new Error(`${CATALOG_SCENARIO}/snapshot.yml: header.toolSchemasSource must be a string`) + const paths = [`${CATALOG_SCENARIO}/system-prompt.expected.md`, `${source === undefined ? CATALOG_SCENARIO : `snapshots/${source}`}/tool-schemas.expected.json`] + for (const path of paths) { + try { + git('cat-file', '-e', `${rev}:${path}`) + } catch (error) { + throw new Error(`catalog file ${path} is missing at ${rev}`, { cause: error }) + } + } + return paths +} + +function git(...args: string[]): string { + return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 30 }) +} + +if (import.meta.main) { + const { values } = parseArgs({ options: { base: { type: 'string' }, head: { type: 'string' }, out: { type: 'string' } } }) + if (!values.base || !values.head || !values.out) throw new Error('usage: snapshot-diff-page.ts --base --head --out ') + const short = (rev: string) => git('rev-parse', '--short', rev).trim() + const files = parseUnifiedDiff(git('-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--unified=5', values.base, values.head, '--', 'snapshots/')) + // A PR that moves the tool schema source shows both the old and the new file. + const catalog = [...new Set([...catalogPaths(values.base), ...catalogPaths(values.head)])] + const page = renderSnapshotDiffPage(groupDiffs(files, catalog), `${short(values.base)} → ${short(values.head)}`) + mkdirSync(dirname(values.out), { recursive: true }) + writeFileSync(values.out, page) +} From aa90f0be5679c97e03d3f86817b53eaf0a037c34 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:10:50 +0800 Subject: [PATCH 013/122] feat(subagent): attach SubagentError codes to delegation tool failures Delegation, discovery, and control tools threw plain Errors for missing caller context, invalid selections, depth limits, and corrupt or unavailable child state, so tool/result records carried no error.code. SubagentDepthError now extends SubagentError with DEPTH_EXCEEDED; new SubagentError codes cover disabled or disallowed preset and model selection, invalid depth and cwd, a missing working-directory service, a failed join of the parent preset revision, and structured output submitted with pending input. Missing callers and services use ToolContextUnavailableError, and hand-checked route fields use ToolArgsError. A corrupt cold-restore descriptor becomes NOT_RESUMABLE, and the schedule tools read the delegation depth inside their error mapping. Refs #7869 --- packages/schedule/tool-schedule/src/index.ts | 6 ++--- .../tool-schedule/tests/tool-schedule.spec.ts | 15 +++++++++++ .../tests/subagent-spawn-in-process.spec.ts | 5 +++- packages/subagent/subagent/README.i18n.yaml | 4 +-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 25 ++++++++++++----- packages/subagent/subagent/src/depth.ts | 5 ++-- packages/subagent/subagent/src/manager.ts | 15 +++++++++-- .../subagent/subagent/src/out-of-process.ts | 6 +++-- packages/subagent/subagent/src/structured.ts | 5 +++- .../subagent/tests/child-agent.spec.ts | 8 ++++-- .../tests/continuation-presets.spec.ts | 17 +++++++++++- .../subagent/tests/continuation.spec.ts | 27 ++++++++++++++++++- .../subagent/tests/out-of-process.spec.ts | 8 +++--- .../subagent/tests/structured.spec.ts | 2 ++ .../subagent/tests/working-directory.spec.ts | 6 ++++- .../tool-subagent-control/src/index.ts | 6 ++--- .../tool-subagent-control/src/list-agents.ts | 4 +-- .../tests/list-agents.spec.ts | 1 + .../tests/tool-subagent-control.spec.ts | 2 ++ .../subagent/tool-subagent/README.i18n.yaml | 4 +-- packages/subagent/tool-subagent/README.md | 2 +- packages/subagent/tool-subagent/README.zh.md | 2 +- packages/subagent/tool-subagent/src/index.ts | 12 ++++++--- .../subagent/tool-subagent/src/list-models.ts | 22 +++++++-------- .../tool-subagent/src/model-selection.ts | 20 +++++++++----- .../tool-subagent/src/preset-selection.ts | 9 +++++-- .../tool-subagent/tests/list-models.spec.ts | 20 ++++++++++---- .../tests/model-selection-settings.spec.ts | 1 + .../tests/model-selection.spec.ts | 16 ++++++++++- .../tests/preset-selection.spec.ts | 10 +++++-- .../tool-subagent/tests/tool-subagent.spec.ts | 2 ++ .../session.v4.jsonl | 2 +- .../session.2.v4.jsonl | 2 +- .../session.1.v4.jsonl | 2 +- 36 files changed, 223 insertions(+), 74 deletions(-) diff --git a/packages/schedule/tool-schedule/src/index.ts b/packages/schedule/tool-schedule/src/index.ts index ab1ed612dc..65040e4c93 100644 --- a/packages/schedule/tool-schedule/src/index.ts +++ b/packages/schedule/tool-schedule/src/index.ts @@ -303,10 +303,10 @@ async function runForCaller( ): Promise | SubagentSessionError | InternalScheduleError> { const agent = exec.agent if (agent === undefined) return internalError() - if (delegationDepthOf(agent) > 0) { - return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } - } try { + if (delegationDepthOf(agent) > 0) { + return { code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' } + } return await operation(agent) } catch (error: unknown) { if (error instanceof ScheduleInputError) { diff --git a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts index 6d3d189d95..983f8a5daf 100644 --- a/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts +++ b/packages/schedule/tool-schedule/tests/tool-schedule.spec.ts @@ -229,6 +229,21 @@ describe('Schedule model tools', () => { expect((await test.service.list({})).total).toBe(0) }) + it('answers internal_error when the caller carries an invalid runtime delegation depth', async () => { + const test = await harness(); tests.push(test) + const caller = { ...agentFor(test.ctx, 'invalid-depth'), options: { subagentDepth: -1 } } + await test.ctx.agents.register(caller) + await mountToolSchedule(test.ctx, caller) + for (const [name, args] of CALLS) { + const result = await executeToolFixture(test.ctx, { + callId: ToolCallId('invalid-depth-call'), signal: new AbortController().signal, name, arguments: args, agent: caller, + }) + expect(result.isError).toBe(false) + expect(result.value).toEqual(INTERNAL_ERROR) + } + expect((await test.service.list({})).total).toBe(0) + }) + it('describes the create parameters for the model', async () => { const test = await setup() const schema = test.ctx.tools.schemas(test.agent).find(candidate => candidate.name === 'schedule_create') diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index c254b67c8c..3ffd937d4d 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -131,7 +131,10 @@ describe('dsh-subagent-spawn-in-process', () => { const { ctx, parent } = await setup([]) // parent is depth 0, child would be depth 1 — cap at 0 forbids any child. await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 })) - .rejects.toThrow('subagent depth 1 exceeds maxDepth 0') + .rejects.toMatchObject({ + name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: 'subagent depth 1 exceeds maxDepth 0', + attemptedDepth: 1, maxDepth: 0, + }) }) it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => { diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4ff564cb25..ceaac3229a 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: 0dc416ded19e304e - zh: 4726e5fe5f188709 + en: f5393c65bf8ee460 + zh: d037d42bc967f17b /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index b8fd869989..dcad891799 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e0f8f35bda..dfe7d1f835 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 98ebfc9d5d..9f4626641c 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -28,10 +28,10 @@ import type {} from '@deepseek-ai/dsh-agent-preset-registry' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' -/** Thrown when starting a child would exceed the requested depth cap. */ -export class SubagentDepthError extends Error { +/** Thrown when starting a child would exceed the requested depth cap; `code` is `DEPTH_EXCEEDED`. */ +export class SubagentDepthError extends SubagentError { constructor(public readonly attemptedDepth: number, public readonly maxDepth: number) { - super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`) + super(`subagent depth ${attemptedDepth} exceeds maxDepth ${maxDepth}`, 'DEPTH_EXCEEDED') this.name = 'SubagentDepthError' } } @@ -44,12 +44,12 @@ export class SubagentDepthError extends Error { * @param maxDepth - optional absolute cap the resolved depth must not exceed. * @returns the child's non-negative safe-integer depth. * @throws {SubagentDepthError} when the resolved depth exceeds `maxDepth`. - * @throws {RangeError} when the resolved depth leaves the safe-integer range. + * @throws {SubagentError} `DEPTH_EXCEEDED` when the resolved depth leaves the safe-integer range. */ export function resolveChildDepth(parent: Agent, maxDepth: number | undefined): number { const childDepth = delegationDepthOf(parent) + 1 if (!Number.isSafeInteger(childDepth)) { - throw new RangeError('subagent child depth exceeds the safe-integer range') + throw new SubagentError('subagent child depth exceeds the safe-integer range', 'DEPTH_EXCEEDED') } if (maxDepth !== undefined && childDepth > maxDepth) { throw new SubagentDepthError(childDepth, maxDepth) @@ -183,6 +183,8 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. */ export function applyChildComposition( childCtx: Context, @@ -198,7 +200,18 @@ export function applyChildComposition( applyChildOverrides(childCtx, composition) }) } - if (parent !== undefined) childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + if (parent !== undefined) { + try { + childCtx.get('agentPresets')?.composeFrom(childCtx, parent.ctx) + } catch (error: unknown) { + // The registry cannot import this package, so its plain join failures are classified here. + throw new SubagentError( + 'the child cannot join the parent agent\'s current preset revision', + 'PRESET_UNAVAILABLE', + { cause: error }, + ) + } + } applyChildOverrides(childCtx, composition) } diff --git a/packages/subagent/subagent/src/depth.ts b/packages/subagent/subagent/src/depth.ts index d9fabab860..033e953bf5 100644 --- a/packages/subagent/subagent/src/depth.ts +++ b/packages/subagent/subagent/src/depth.ts @@ -7,6 +7,7 @@ */ import type { Agent } from '@deepseek-ai/dsh-agent' +import { SubagentError } from './error.ts' declare module '@deepseek-ai/dsh-agent' { interface AgentOptions { @@ -23,12 +24,12 @@ declare module '@deepseek-ai/dsh-agent' { * let it delegate as if it were top-level. * @param agent - the agent whose header and options carry the depth. * @returns its non-negative safe-integer depth. - * @throws if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. + * @throws {SubagentError} `INVALID_DEPTH` if the runtime `AgentOptions.subagentDepth` is not a non-negative safe integer. */ export function delegationDepthOf(agent: Agent): number { const runtime = agent.options.subagentDepth if (runtime !== undefined && (!Number.isSafeInteger(runtime) || runtime < 0 || Object.is(runtime, -0))) { - throw new TypeError('agent subagentDepth must be a non-negative safe integer') + throw new SubagentError('agent subagentDepth must be a non-negative safe integer', 'INVALID_DEPTH') } // The header value was validated at the session boundary (creation and // persistence load both construct through the store). diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index db6f04b019..fa97141c76 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -830,7 +830,9 @@ export class SubagentManager { child.session.append('subagent/descriptor', create.descriptor) appendDelegatedPolicyOverrides(child.session, create.delegatedPolicies) const workingDirectory = childCtx.get('workingDirectory') - if (workingDirectory === undefined) throw new Error('local subagents require the working-directory service') + if (workingDirectory === undefined) { + throw new SubagentError('local subagents require the working-directory service', 'WORKING_DIRECTORY_UNAVAILABLE') + } await workingDirectory.set(child, create.cwd, inputs.signal) } if (inputs.composition.agentPreset === undefined) await applyChildComposition(childCtx, create?.parent, inputs.composition) @@ -1205,7 +1207,16 @@ export class SubagentManager { using source = await this.observeContinuation(childId, signal) this.assertAdmitting(root) const ownEvents = source.events.slice(source.inheritedEventCount) - const descriptor = foldSubagentDescriptor(ownEvents) + let descriptor: ReturnType + try { + descriptor = foldSubagentDescriptor(ownEvents) + } catch (error: unknown) { + throw new SubagentError( + `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + 'NOT_RESUMABLE', + { cause: error }, + ) + } if (descriptor === undefined || descriptor.mode !== 'continuable') { throw new SubagentError( `subagent "${childId}" has no supported continuation state and cannot be resumed; choose a different target`, diff --git a/packages/subagent/subagent/src/out-of-process.ts b/packages/subagent/subagent/src/out-of-process.ts index d8a5519c96..84f46ae387 100644 --- a/packages/subagent/subagent/src/out-of-process.ts +++ b/packages/subagent/subagent/src/out-of-process.ts @@ -13,6 +13,7 @@ import { accessSync, constants, statSync } from 'node:fs' import { isAbsolute } from 'node:path' import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { SubagentError } from './error.ts' import type { SubagentCapabilities, SubagentResult, SubagentRun, SubagentStopReason } from './types.ts' /** Maximum UTF-8 size of {@link SubagentResult.diagnostic}. */ @@ -100,13 +101,14 @@ function isEnterableDirectory(path: string): boolean { * @param label - which source supplied the value, for the diagnostic. * @param cwd - the candidate working directory. * @returns `cwd`, validated. + * @throws {SubagentError} `INVALID_CWD` when `cwd` is relative or not an enterable directory. */ export function assertUsableCwd(prefix: string, label: string, cwd: string): string { if (!isAbsolute(cwd)) { - throw new Error(`${prefix}: ${label} must be an absolute path: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} must be an absolute path: ${cwd}`, 'INVALID_CWD') } if (!isEnterableDirectory(cwd)) { - throw new Error(`${prefix}: ${label} is not an accessible directory: ${cwd}`) + throw new SubagentError(`${prefix}: ${label} is not an accessible directory: ${cwd}`, 'INVALID_CWD') } return cwd } diff --git a/packages/subagent/subagent/src/structured.ts b/packages/subagent/subagent/src/structured.ts index eeb8c1e86b..81f0952d09 100644 --- a/packages/subagent/subagent/src/structured.ts +++ b/packages/subagent/subagent/src/structured.ts @@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import type { ToolExecution, ToolRunContext } from '@deepseek-ai/dsh-tools' import { ToolArgsError, validateJsonSchemaValue, type ObjectJsonSchema } from '@deepseek-ai/dsh-tools' +import { SubagentError } from './error.ts' /** The model-facing tool name a structured child must call to finish. */ export const STRUCTURED_OUTPUT_TOOL = 'structured_output' @@ -96,7 +97,9 @@ export function attachStructuredRuntime( // ToolArgsError → isError result with INVALID_ARGS: the model retries // within the same turn, exactly like a schema-validated defineTool call. if (violations.length > 0) throw new ToolArgsError(violations) - if (!canComplete()) throw new Error('Process pending messages before submitting structured output.') + if (!canComplete()) { + throw new SubagentError('Process pending messages before submitting structured output.', 'STRUCTURED_OUTPUT_PENDING_INPUT') + } // Two-phase commit, keyed by THIS execution: later transformable // waterfalls may still turn the success into an error. ToolRuntime has // already frozen model-bound arguments at the actual input boundary. diff --git a/packages/subagent/subagent/tests/child-agent.spec.ts b/packages/subagent/subagent/tests/child-agent.spec.ts index 0b661cd21d..ad47b8f6d4 100644 --- a/packages/subagent/subagent/tests/child-agent.spec.ts +++ b/packages/subagent/subagent/tests/child-agent.spec.ts @@ -92,12 +92,16 @@ describe('delegation depth limits', () => { it.each([-1, -0, 0.5, Number.NaN, Number.POSITIVE_INFINITY])('rejects an invalid runtime depth %s', (depth) => { const parent = parentAgent() parent.options.subagentDepth = depth - expect(() => resolveChildDepth(parent, undefined)).toThrow('agent subagentDepth must be a non-negative safe integer') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'INVALID_DEPTH', message: 'agent subagentDepth must be a non-negative safe integer', + })) }) it('rejects a child depth beyond the exact integer range', () => { const parent = parentAgent() parent.options.subagentDepth = Number.MAX_SAFE_INTEGER - expect(() => resolveChildDepth(parent, undefined)).toThrow('subagent child depth exceeds the safe-integer range') + expect(() => resolveChildDepth(parent, undefined)).toThrow(expect.objectContaining({ + name: 'SubagentError', code: 'DEPTH_EXCEEDED', message: 'subagent child depth exceeds the safe-integer range', + })) }) }) diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 941d7faf16..594be164ac 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -1,7 +1,7 @@ /** Independent spawn presets and compatibility of persisted child compositions. */ import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' @@ -124,6 +124,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies a failed join of the parent preset revision as PRESET_UNAVAILABLE', async () => { + const { ctx, parent, adapter } = await setup() + const failure = new Error('Parent preset revision is unavailable') + vi.spyOn(ctx.agentPresets, 'composeFrom').mockImplementation(() => { throw failure }) + + await expect(ctx.subagents.startActivation(startSpec(parent))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'the child cannot join the parent agent\'s current preset revision', + cause: failure, + }) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..3948cde2f0 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -766,7 +766,7 @@ describe('SubagentRuntime.startActivation', () => { delivery: 'parent', ...startSpec(parent), prompt: message('deep'), parent, maxDepth: 0, - })).rejects.toThrow(/exceeds maxDepth 0/) + })).rejects.toMatchObject({ name: 'SubagentDepthError', code: 'DEPTH_EXCEEDED', message: expect.stringMatching(/exceeds maxDepth 0/) as string }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([SessionId('parent')]) }) @@ -1160,6 +1160,31 @@ describe('target-only Queue residency routing', () => { .rejects.toMatchObject({ code: 'NOT_RESUMABLE' }) }) + it('rejects a cold target whose persisted descriptor is corrupt as not resumable', async () => { + const { ctx, parent } = await setup([]) + const childId = SessionId('child-with-corrupt-descriptor') + const child = await ctx.agents.create({ + sessionId: childId, + meta: { origin: 'subagent', parentSession: parent.id }, + agentOptions: { provider: 'mock', model: 'mock' }, + setup: (_childCtx, agent) => { + agent.session.append('subagent/descriptor', { + version: SUBAGENT_DESCRIPTOR_VERSION, mode: 'continuable', provider: 'spawn', label: 7, + } as never) + }, + }) + await ctx.sessions.flush(child.agent.session) + await child.dispose() + + await expect(ctx.subagents.sendMessage(parent, childId, message('continue'), { signal: testSignal })) + .rejects.toMatchObject({ + name: 'SubagentError', + code: 'NOT_RESUMABLE', + message: `subagent "${childId}" has a corrupt continuation descriptor and cannot be resumed; choose a different target`, + cause: expect.objectContaining({ message: 'persisted subagent descriptor label must be a string' }) as Error, + }) + }) + it('reports an unknown child id as unavailable', async () => { const { ctx } = await setup([]) await expect(queuePrompt(ctx, SessionId('missing'), message('hello'))) diff --git a/packages/subagent/subagent/tests/out-of-process.spec.ts b/packages/subagent/subagent/tests/out-of-process.spec.ts index f4db734e96..79c44ccf4b 100644 --- a/packages/subagent/subagent/tests/out-of-process.spec.ts +++ b/packages/subagent/subagent/tests/out-of-process.spec.ts @@ -42,8 +42,8 @@ describe('assertPositiveFinite', () => { describe('child cwd resolution', () => { it('accepts an absolute enterable directory and rejects relative or missing paths', () => { expect(assertUsableCwd('p', 'config cwd', tmpdir())).toBe(tmpdir()) - expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow('must be an absolute path') - expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', 'relative/path')).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('must be an absolute path') as string })) + expect(() => assertUsableCwd('p', 'config cwd', join(tmpdir(), 'dsh-no-such-dir-xyz'))).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) }) it('rejects an existing path that is a file, not a directory', () => { @@ -51,7 +51,7 @@ describe('child cwd resolution', () => { const file = join(tmp, 'plain.txt') try { writeFileSync(file, 'not a dir\n') - expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', file)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { rmSync(tmp, { recursive: true, force: true }) } @@ -64,7 +64,7 @@ describe('child cwd resolution', () => { const tmp = mkdtempSync(join(tmpdir(), 'oop-noexec-')) chmodSync(tmp, 0o600) try { - expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow('not an accessible directory') + expect(() => assertUsableCwd('p', 'config cwd', tmp)).toThrow(expect.objectContaining({ name: 'SubagentError', code: 'INVALID_CWD', message: expect.stringContaining('not an accessible directory') as string })) } finally { chmodSync(tmp, 0o700) rmSync(tmp, { recursive: true, force: true }) diff --git a/packages/subagent/subagent/tests/structured.spec.ts b/packages/subagent/subagent/tests/structured.spec.ts index 60f5f8b19e..ea0f4e5109 100644 --- a/packages/subagent/subagent/tests/structured.spec.ts +++ b/packages/subagent/subagent/tests/structured.spec.ts @@ -138,6 +138,8 @@ describe('in-process structured output', () => { const events = run.localAgent.session.snapshotEvents() const first = events.find(event => event.type === 'tool/result' && event.data.message.toolCallId === 'before-input') expect(first?.type === 'tool/result' && first.data.message.isError).toBe(true) + expect(first?.type === 'tool/result' && first.data.error) + .toEqual({ name: 'SubagentError', code: 'STRUCTURED_OUTPUT_PENDING_INPUT' }) expect(events.some(event => event.type === 'user/message' && event.data.id === messageId)).toBe(true) expect(JSON.stringify(adapter.requests.at(-1)?.messages)).toContain('Correction: submit answer 42 instead.') } finally { diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index f3cb6aa47d..befe01a1da 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -101,7 +101,11 @@ describe('subagent working directories', () => { provider: 'spawn', label: 'unavailable directory service', childId, parent, cwd: second, prompt: [{ type: 'text', text: 'child' }], signal: new AbortController().signal, - })).rejects.toThrow(/subagents require the working-directory service/) + })).rejects.toMatchObject({ + name: 'SubagentError', + code: 'WORKING_DIRECTORY_UNAVAILABLE', + message: expect.stringMatching(/subagents require the working-directory service/) as string, + }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(parent.session.snapshotEvents().filter(event => event.type === 'subagent/catalog')).toEqual([]) diff --git a/packages/subagent/tool-subagent-control/src/index.ts b/packages/subagent/tool-subagent-control/src/index.ts index b6b89603ac..8f9ecc95ba 100644 --- a/packages/subagent/tool-subagent-control/src/index.ts +++ b/packages/subagent/tool-subagent-control/src/index.ts @@ -10,7 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +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' @@ -73,7 +73,7 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const sender = exec.agent if (!sender) { - throw new Error('send_message requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('send_message requires a calling agent (exec.agent was undefined)') } const message: ContentBlock[] = [{ type: 'text', text: args.message }] const targetId = await ctx.subagents.resolveName(sender, args.agent, exec.signal) @@ -146,7 +146,7 @@ export function apply(ctx: Context, config: Config = {}): void { const caller = exec.agent if (!caller) { // Ancestor authority requires an exact live calling agent. - throw new Error('interrupt_agent requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('interrupt_agent requires a calling agent (exec.agent was undefined)') } const targetId = await ctx.subagents.resolveName(caller, args.agent, exec.signal) // The service authorizes the exact live caller against the target's diff --git a/packages/subagent/tool-subagent-control/src/list-agents.ts b/packages/subagent/tool-subagent-control/src/list-agents.ts index 50780cf91d..555b16181e 100644 --- a/packages/subagent/tool-subagent-control/src/list-agents.ts +++ b/packages/subagent/tool-subagent-control/src/list-agents.ts @@ -1,7 +1,7 @@ /** Discover the caller's entire subagent tree; the control plugin owns registration. */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { SessionId } from '@deepseek-ai/dsh-session' @@ -78,7 +78,7 @@ export function registerListAgents(ctx: Context): ToolDefinition { const parent = exec.agent if (!parent) { // Non-agent callers have no session whose children could be listed. - throw new Error('list_agents requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('list_agents requires a calling agent (exec.agent was undefined)') } const root = ctx.subagents.rootOf(parent) const entries = await ctx.subagents.listDescendants(root.id, exec.signal) diff --git a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts index a1d0adf382..c927784c70 100644 --- a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts @@ -271,6 +271,7 @@ describe('list_agents', () => { const result = await callTool(ctx, 'list_agents', {}) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('unregisters with its plugin fiber (HMR safety)', async () => { 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 5ea4866a1c..c12f685212 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 @@ -463,6 +463,7 @@ describe('dsh-tool-subagent-control', () => { const result = await callTool(ctx, 'send_message', { agent: 'x', message: 'y' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it.each([{}, { interrupt: true }, { interrupt: false }])('unregisters and reloads with config %j (HMR safety)', async (config) => { @@ -692,5 +693,6 @@ describe('dsh-tool-subagent-control interrupt_agent', () => { const result = await callTool(ctx, 'interrupt_agent', { agent: 'x' }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) }) diff --git a/packages/subagent/tool-subagent/README.i18n.yaml b/packages/subagent/tool-subagent/README.i18n.yaml index 35252c76ab..eb73b24381 100644 --- a/packages/subagent/tool-subagent/README.i18n.yaml +++ b/packages/subagent/tool-subagent/README.i18n.yaml @@ -36,8 +36,8 @@ en: 373abf7c7aa3e4f1 zh: be0b4d4a7371d360 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/activation-ownership: - en: ef692c4d17290920 - zh: b1d0d3dab011e2cd + en: a72ddd82ad7810a1 + zh: 738f8fb157e51c59 /deepseek-ai-dsh-tool-subagent/understand-the-implementation/result-acknowledgement: en: 3c2d70d479be8e38 zh: 9aebdb72223a086e diff --git a/packages/subagent/tool-subagent/README.md b/packages/subagent/tool-subagent/README.md index e41c2161b6..f4d29d8b26 100644 --- a/packages/subagent/tool-subagent/README.md +++ b/packages/subagent/tool-subagent/README.md @@ -94,7 +94,7 @@ One instance is one provider plus one tool name. The plugin registers its defini ### Activation ownership -The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result; failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. +The tool calls `ctx.subagents.startActivation()` with parent delivery selected. The runtime owns startup cancellation, execution, outcome reporting, and cleanup. A startup failure is an errored tool result. Rejections before startup are coded: a missing calling Agent, `llm` service, or effective parent route throws `ToolContextUnavailableError`; an empty or unpaired route field throws `ToolArgsError`; and `SubagentError` reports a disabled selection (`MODEL_SELECTION_DISABLED`, `PRESET_SELECTION_DISABLED`), a preset outside the allowlist (`PRESET_NOT_ALLOWED`), an unauthorized route (`UNAUTHORIZED`), an unregistered discovery provider (`NO_PROVIDER`), or a provider replaced during route preflight (`PROVIDER_CHANGED`). Failures after publication arrive through the completion notice, with diagnostics and partial output preserved by the runtime. ### Result acknowledgement diff --git a/packages/subagent/tool-subagent/README.zh.md b/packages/subagent/tool-subagent/README.zh.md index 2093ff093a..5760c7f02c 100644 --- a/packages/subagent/tool-subagent/README.zh.md +++ b/packages/subagent/tool-subagent/README.zh.md @@ -94,7 +94,7 @@ kind: "package-reference" ### Activation 所有权 -工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果;发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 +工具调用 `ctx.subagents.startActivation()`,并选择向父任务交付。运行时拥有启动取消、执行、结果汇报与清理。启动失败产生出错的工具结果。启动前的拒绝都带 code:缺少调用方 Agent、`llm` 服务或有效的父级路由时抛出 `ToolContextUnavailableError`;路由字段为空或未成对提供时抛出 `ToolArgsError`;`SubagentError` 报告选择被禁用(`MODEL_SELECTION_DISABLED`、`PRESET_SELECTION_DISABLED`)、preset 不在允许列表中(`PRESET_NOT_ALLOWED`)、路由未授权(`UNAUTHORIZED`)、发现查询的提供方未注册(`NO_PROVIDER`),或路由预检期间提供方被替换(`PROVIDER_CHANGED`)。发布后的失败通过完成通知到达,运行时保留诊断和部分输出。 ### 结果确认 diff --git a/packages/subagent/tool-subagent/src/index.ts b/packages/subagent/tool-subagent/src/index.ts index 5f2f089363..4cce53ec87 100644 --- a/packages/subagent/tool-subagent/src/index.ts +++ b/packages/subagent/tool-subagent/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' import type { AgentOptions } from '@deepseek-ai/dsh-agent' import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' @@ -18,6 +18,7 @@ import { assertSubagentMaxDepth, delegationDepthOf, parentAgentOptionsForDelegation, + SubagentError, } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' import { @@ -275,7 +276,7 @@ export async function apply(ctx: Context, config: Config): Promise { const parent = exec.agent if (!parent) { // Non-agent callers provide no parent for delegation ownership. - throw new Error('subagent tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('subagent tool requires a calling agent (exec.agent was undefined)') } const routes = subagentModelSelectionPolicy(subagentModelSelectionProjectionHandle, parent.session) @@ -298,7 +299,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (requiresRoutePreflight) { const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot resolve the selected child LLM route because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot resolve the selected child LLM route because the `llm` service is unavailable') } const inheritParentReasoningEffort = providerRouteDefaults === undefined && !hasDelegationModelRequest(modelRequest) await preflightChildLlmRoute( @@ -309,7 +310,10 @@ export async function apply(ctx: Context, config: Config): Promise { inheritParentReasoningEffort, ) if (ctx.subagents.getProvider(config.provider) !== subagentProvider) { - throw new Error(`subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`) + throw new SubagentError( + `subagent provider "${config.provider}" changed while resolving the child LLM route; retry the delegation`, + 'PROVIDER_CHANGED', + ) } } exec.signal.throwIfAborted() diff --git a/packages/subagent/tool-subagent/src/list-models.ts b/packages/subagent/tool-subagent/src/list-models.ts index 966680a669..4c0ae9b94e 100644 --- a/packages/subagent/tool-subagent/src/list-models.ts +++ b/packages/subagent/tool-subagent/src/list-models.ts @@ -3,8 +3,8 @@ import type { Context } from '@deepseek-ai/cordis' import type LlmRuntime from '@deepseek-ai/dsh-llm' import type { LlmProviderInfo } from '@deepseek-ai/dsh-llm' -import { defineTool } from '@deepseek-ai/dsh-tools' -import { parentAgentOptionsForDelegation } from '@deepseek-ai/dsh-subagent' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' +import { parentAgentOptionsForDelegation, SubagentError } from '@deepseek-ai/dsh-subagent' import type { ToolRunContext } from '@deepseek-ai/dsh-tools' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { AllowedModelRoute, ModelSelectionPolicy } from './model-selection.ts' @@ -28,7 +28,7 @@ function registeredProvider( .filter(candidate => policy.routes.some(route => route.provider === candidate.id)) .map(candidate => candidate.id) .join(', ') || '(none)' - throw new Error(`LLM provider "${providerId}" is not registered; available providers: ${available}`) + throw new SubagentError(`LLM provider "${providerId}" is not registered; available providers: ${available}`, 'NO_PROVIDER') } /** Render one advertised or resolved model. */ @@ -43,24 +43,24 @@ async function listSubagentModels( request: ListSubagentModelsRequest, exec: ToolRunContext, ): Promise { - if (exec.agent === undefined) throw new Error('list_subagent_models requires a calling agent') + if (exec.agent === undefined) throw new ToolContextUnavailableError('list_subagent_models requires a calling agent') const routes = subagentModelSelectionPolicy(policyHandle, exec.agent.session) let policy = routes === undefined ? undefined : { routes } const selectionEnabled = policy !== undefined if (policy === undefined) { const { provider, model } = parentAgentOptionsForDelegation(exec.agent) if (provider === undefined || model === undefined) { - throw new Error('cannot discover child LLM routes without a parent provider and model') + throw new ToolContextUnavailableError('cannot discover child LLM routes without a parent provider and model') } policy = { routes: [{ provider, model }] } } const { signal } = exec const llm = ctx.get('llm') if (llm === undefined) { - throw new Error('cannot discover child LLM routes because the `llm` service is unavailable') + throw new ToolContextUnavailableError('cannot discover child LLM routes because the `llm` service is unavailable') } if (request.model !== undefined && request.provider === undefined) { - throw new Error('`model` requires `provider`') + throw new ToolArgsError(['`model` requires `provider`']) } if (request.provider === undefined) { const providers = llm.listProviders() @@ -69,11 +69,11 @@ async function listSubagentModels( ? '(no LLM providers)' : providers.map(provider => `${provider.id} — ${provider.name}`).join('\n') } - if (request.provider.length === 0) throw new Error('`provider` must be non-empty') + if (request.provider.length === 0) throw new ToolArgsError(['`provider` must be non-empty']) const allowedRoutes = policy.routes.filter(route => route.provider === request.provider) const [firstRoute] = allowedRoutes if (firstRoute === undefined) { - throw new Error(`LLM provider "${request.provider}" is not allowed for this Session`) + throw new SubagentError(`LLM provider "${request.provider}" is not allowed for this Session`, 'UNAUTHORIZED') } const provider = registeredProvider(llm, policy, request.provider) if (request.model === undefined) { @@ -85,9 +85,9 @@ async function listSubagentModels( ? `(no advertised models for ${provider.id})` : models.map(model => modelLine(provider.id, model)).join('\n') } - if (request.model.length === 0) throw new Error('`model` must be non-empty') + if (request.model.length === 0) throw new ToolArgsError(['`model` must be non-empty']) if (!allowedRoutes.some(route => route.model === request.model)) { - throw new Error(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`) + throw new SubagentError(`child LLM route "${provider.id}/${request.model}" is not allowed for this Session`, 'UNAUTHORIZED') } const model = await llm.resolveModelInfo(provider.id, request.model, signal) const efforts = model.reasoning?.efforts.map(effort => ( diff --git a/packages/subagent/tool-subagent/src/model-selection.ts b/packages/subagent/tool-subagent/src/model-selection.ts index cadeff0efe..7fa0da4c15 100644 --- a/packages/subagent/tool-subagent/src/model-selection.ts +++ b/packages/subagent/tool-subagent/src/model-selection.ts @@ -3,6 +3,8 @@ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { LlmRuntime } from '@deepseek-ai/dsh-llm' import type { AgentOptions } from '@deepseek-ai/dsh-agent' +import { SubagentError } from '@deepseek-ai/dsh-subagent' +import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import z from '@deepseek-ai/schemastery' /** One exact child LLM route authorized by a user setting. */ @@ -82,7 +84,7 @@ export function hasDelegationModelRequest(request: DelegationModelRequest): bool /** Reject an empty model-facing route value at the tool JSON boundary. */ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelRequest): void { if (value !== undefined && value.length === 0) { - throw new Error(`child LLM \`${field}\` must be non-empty`) + throw new ToolArgsError([`child LLM \`${field}\` must be non-empty`]) } } @@ -96,6 +98,9 @@ function assertNonEmpty(value: string | undefined, field: keyof DelegationModelR * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @returns Child Agent options, preserving omission when no layer contributes one. + * @throws {SubagentError} `MODEL_SELECTION_DISABLED` when this tool instance + * forbids selection, or `UNAUTHORIZED` when the Session does not allow the route. + * @throws {ToolArgsError} when a field is empty or `provider` and `model` are not supplied together. */ export function requestedAgentOptions( configured: AgentOptions | undefined, @@ -106,15 +111,15 @@ export function requestedAgentOptions( ): AgentOptions | undefined { if (!hasDelegationModelRequest(request)) return configured if (!enabled) { - throw new Error('child model selection is disabled for this tool instance') + throw new SubagentError('child model selection is disabled for this tool instance', 'MODEL_SELECTION_DISABLED') } assertNonEmpty(request.provider, 'provider') assertNonEmpty(request.model, 'model') assertNonEmpty(request.reasoning_effort, 'reasoning_effort') if (request.provider === undefined || request.model === undefined) { - throw new Error(request.reasoning_effort === undefined + throw new ToolArgsError([request.reasoning_effort === undefined ? 'child LLM `provider` and `model` must be supplied together' - : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields') + : 'child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields']) } assertAllowedModelSelection(policy, parentOptions, { provider: request.provider, model: request.model }) @@ -132,6 +137,7 @@ export function requestedAgentOptions( * @param policy - Session allowlist; omission permits only the current parent route. * @param parentOptions - Current parent route used when no policy is recorded. * @param route - Validated provider/model pair from the tool call. + * @throws {SubagentError} `UNAUTHORIZED` when the Session does not allow the route. */ export function assertAllowedModelSelection( policy: ModelSelectionPolicy | undefined, @@ -143,10 +149,10 @@ export function assertAllowedModelSelection( ? provider === parentOptions.provider && model === parentOptions.model : policy.routes.some(route => route.provider === provider && route.model === model) if (allowed) return - throw new Error(`child LLM route "${provider}/${model}" is not allowed for this Session` + throw new SubagentError(`child LLM route "${provider}/${model}" is not allowed for this Session` + (policy === undefined ? '; without a recorded model-selection policy, explicit selection is limited to the parent route' - : '')) + : ''), 'UNAUTHORIZED') } /** @@ -180,7 +186,7 @@ export async function preflightChildLlmRoute( const provider = requested?.provider ?? parentOptions.provider const model = requested?.model ?? parentOptions.model if (provider === undefined || model === undefined) { - throw new Error('cannot select child LLM values without an effective provider and model') + throw new ToolContextUnavailableError('cannot select child LLM values without an effective provider and model') } const routeChanged = provider !== parentOptions.provider || model !== parentOptions.model const reasoningEffort = requested?.reasoningEffort diff --git a/packages/subagent/tool-subagent/src/preset-selection.ts b/packages/subagent/tool-subagent/src/preset-selection.ts index 0bbb33f712..58da4a00e4 100644 --- a/packages/subagent/tool-subagent/src/preset-selection.ts +++ b/packages/subagent/tool-subagent/src/preset-selection.ts @@ -1,4 +1,5 @@ /** Deployment-owned preset choices for one delegation tool. */ +import { SubagentError } from '@deepseek-ai/dsh-subagent' import type { SubagentProvider } from '@deepseek-ai/dsh-subagent' /** Optional default and model-selectable preset ids for a spawn tool. */ @@ -59,13 +60,17 @@ export class SubagentPresetSelection { * Validate model input and apply the deployment default. * @param request - Model-supplied tool arguments. * @returns Selected preset id, or omission to inherit the parent. + * @throws {SubagentError} `PRESET_SELECTION_DISABLED` when this tool exposes no + * preset choice, or `PRESET_NOT_ALLOWED` when the id is outside the allowlist. */ resolve(request: PresetSelectionRequest): string | undefined { const id = request.agent_preset if (id === undefined) return this.config.agentPreset - if (this.choices === undefined) throw new Error('agent_preset selection is disabled for this tool instance') + if (this.choices === undefined) { + throw new SubagentError('agent_preset selection is disabled for this tool instance', 'PRESET_SELECTION_DISABLED') + } if (typeof id !== 'string' || !this.choices.includes(id)) { - throw new Error(`agent_preset must be one of: ${this.choices.join(', ')}`) + throw new SubagentError(`agent_preset must be one of: ${this.choices.join(', ')}`, 'PRESET_NOT_ALLOWED') } return id } diff --git a/packages/subagent/tool-subagent/tests/list-models.spec.ts b/packages/subagent/tool-subagent/tests/list-models.spec.ts index 654ab2f1b2..1bb3f053ba 100644 --- a/packages/subagent/tool-subagent/tests/list-models.spec.ts +++ b/packages/subagent/tool-subagent/tests/list-models.spec.ts @@ -177,7 +177,9 @@ describe('list_subagent_models', () => { await mountWorkingDirectoryFixture(ctx) await ctx.plugin(SubagentRuntime) await ctx.plugin(tool, { provider: 'unused', modelDiscovery: true }) - expect(text(await call(ctx, {}))).toContain('requires a calling agent') + const agentless = await call(ctx, {}) + expect(text(agentless)).toContain('requires a calling agent') + expect(agentless.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) await ctx.fiber.dispose() const parentContext = await setup({ provider: 'mock', withModelSelection: true, hostSelectionEnabled: false }) @@ -188,6 +190,7 @@ describe('list_subagent_models', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('without a parent provider and model') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('reads the recorded Session allowlist through the delegation plugin', async () => { @@ -217,6 +220,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, {}) expect(result.isError).toBe(true) expect(text(result)).toContain('`llm` service is unavailable') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('lists registered providers and follows live registration changes', async () => { @@ -259,6 +263,7 @@ describe('list_subagent_models', () => { const denied = await call(ctx, { provider: 'alpha', model: 'plain' }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('rejects an unauthorized provider before calling its adapter catalog', async () => { @@ -271,6 +276,7 @@ describe('list_subagent_models', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('provider "secret" is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) expect(listModels).not.toHaveBeenCalled() }) @@ -376,14 +382,15 @@ describe('list_subagent_models', () => { }) it.each([ - { args: { model: 'fast' }, expected: '`model` requires `provider`' }, - { args: { provider: '' }, expected: '`provider` must be non-empty' }, - { args: { provider: 'missing' }, expected: 'is not allowed for this Session' }, - ])('rejects incomplete or unavailable provider requests', async ({ args, expected }) => { + { args: { model: 'fast' }, expected: '`model` requires `provider`', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: '' }, expected: '`provider` must be non-empty', info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { args: { provider: 'missing' }, expected: 'is not allowed for this Session', info: { name: 'SubagentError', code: 'UNAUTHORIZED' } }, + ])('rejects incomplete or unavailable provider requests', async ({ args, expected, info }) => { const ctx = await setupListTool() const result = await call(ctx, args) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual(info) }) it('rejects an empty exact model after resolving the provider', async () => { @@ -392,6 +399,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'alpha', model: '' }) expect(result.isError).toBe(true) expect(text(result)).toContain('`model` must be non-empty') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('reports registered alternatives for an unavailable provider', async () => { @@ -403,6 +411,7 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: alpha') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) expect(text(result)).not.toContain('secret') }) @@ -411,5 +420,6 @@ describe('list_subagent_models', () => { const result = await call(ctx, { provider: 'missing' }) expect(result.isError).toBe(true) expect(text(result)).toContain('available providers: (none)') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'NO_PROVIDER' }) }) }) diff --git a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts index 5d26f6eb67..599fde1e79 100644 --- a/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection-settings.spec.ts @@ -285,6 +285,7 @@ describe('SubagentModelSelectionConfig', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) await ctx.fiber.dispose() }) diff --git a/packages/subagent/tool-subagent/tests/model-selection.spec.ts b/packages/subagent/tool-subagent/tests/model-selection.spec.ts index 014acf6d5b..9d8253ca80 100644 --- a/packages/subagent/tool-subagent/tests/model-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/model-selection.spec.ts @@ -119,6 +119,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) }) it('hides and rejects route fields without modelSelection', async () => { @@ -136,6 +137,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'forced route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('child model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } }) @@ -173,6 +175,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(start).not.toHaveBeenCalled() }) @@ -199,6 +202,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('is not allowed for this Session') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) }) it('discovers only the parent route without a Session policy and permits its explicit route and effort', async () => { @@ -403,12 +407,17 @@ describe('dsh-tool-subagent model selection', () => { }) expect(result.isError).toBe(true) expect(text(result)).toContain('`reasoning_effort` requires both `provider` and `model`') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects preflight without an effective provider and model', async () => { const ctx = await setup({ provider: 'mock' }) await expect(preflightChildLlmRoute(ctx.llm, {}, undefined, AbortSignal.abort())) - .rejects.toThrow('without an effective provider and model') + .rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: 'cannot select child LLM values without an effective provider and model', + }) }) it.each([ @@ -420,6 +429,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'partial route', prompt: 'do it', ...route }) expect(result.isError).toBe(true) expect(text(result)).toContain('`provider` and `model` must be supplied together') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(starts).toBe(0) }) @@ -432,6 +442,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'empty route', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('uses the LLM runtime for provider and reasoning-effort validation before child creation', async () => { @@ -524,6 +535,7 @@ describe('dsh-tool-subagent model selection', () => { const configured = await callSubagent(ctx, { description: 'configured effort', prompt: 'do it' }, { agent: parentWithRoute() }) expect(configured.isError).toBe(true) expect(text(configured)).toContain('`llm` service is unavailable') + expect(configured.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) @@ -566,6 +578,7 @@ describe('dsh-tool-subagent model selection', () => { }) expect(denied.isError).toBe(true) expect(text(denied)).toContain('is not allowed for this Session') + expect(denied.error?.info).toEqual({ name: 'SubagentError', code: 'UNAUTHORIZED' }) const invalidEffort = await callSubagent(ctx, { description: 'unsupported effort', prompt: 'do it', provider: 'alpha', model: 'fast-model', reasoning_effort: 'invalid', @@ -599,6 +612,7 @@ describe('dsh-tool-subagent model selection', () => { const result = await callSubagent(ctx, { description: 'fork work', prompt: 'do it', ...selection }) expect(result.isError).toBe(true) expect(text(result)).toContain('model selection is disabled for this tool instance') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'MODEL_SELECTION_DISABLED' }) } expect(started).not.toHaveBeenCalled() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 636c88805e..9bfa7e9e85 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -98,6 +98,7 @@ describe('spawn preset selection', () => { const forced = await callSubagent(ctx, { ...args, agent_preset: 'writer' }) expect(forced.isError).toBe(true) expect(text(forced)).toContain('selection is disabled') + expect(forced.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_SELECTION_DISABLED' }) expect(onStart).toHaveBeenCalledTimes(1) }) @@ -134,8 +135,13 @@ describe('spawn preset selection', () => { it('rejects forced selection at the model JSON resolver', () => { const selection = new SubagentPresetSelection({ allowedAgentPresets: ['writer'] }) - expect(() => selection.resolve({ agent_preset: 'unlisted' })).toThrow(/must be one of/) - expect(() => selection.resolve({ agent_preset: 1 })).toThrow(/must be one of/) + for (const agent_preset of ['unlisted', 1]) { + expect(() => selection.resolve({ agent_preset })).toThrow(expect.objectContaining({ + name: 'SubagentError', + code: 'PRESET_NOT_ALLOWED', + message: 'agent_preset must be one of: writer', + })) + } }) it('requires the preset service when selection is configured', async () => { diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 095d1de42c..6fcf375ad3 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -242,6 +242,7 @@ describe('dsh-tool-subagent', () => { const result = await pending expect(result.isError).toBe(true) expect(text(result)).toContain('changed while resolving the child LLM route') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PROVIDER_CHANGED' }) expect(oldStart).not.toHaveBeenCalled() expect(replacementStart).not.toHaveBeenCalled() }) @@ -342,6 +343,7 @@ describe('dsh-tool-subagent', () => { const result = await callSubagent(ctx, { description: 'd', prompt: 'p' }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('registers when the provider appears LATER — no load-order requirement (Loader starts siblings concurrently)', async () => { diff --git a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl index 725da9a4cd..a85b1ef583 100644 --- a/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl +++ b/snapshots/session/subagent-depth-context-disabled/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_one_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_one_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_one_rejected"},"toolCallId":"call_depth_one_rejected","content":[{"type":"text","text":"Error: subagent depth 1 exceeds maxDepth 0"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"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":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} 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 a8dbd992e8..dfa91ecadc 100644 --- a/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl +++ b/snapshots/session/subagent-depth-two-rejection/session.2.v4.jsonl @@ -15,7 +15,7 @@ {"type":"session/title","data":{"title":"Attempt one subagent call beyond","messageSeqs":[9],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:18}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1789625678968,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789625678968,"index":0,"dt":[],"id":"call_depth_three_rejected","name":"subagent","args":["{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"]},{"type":"chunk","time":1789625678968,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1789625678968,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_depth_three_rejected","name":"subagent","arguments":"{\"description\":\"Exceed depth cap\",\"prompt\":\"This child must never start.\",\"run_in_background\":false}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_depth_three_rejected"},"toolCallId":"call_depth_three_rejected","content":[{"type":"text","text":"Error: subagent depth 3 exceeds maxDepth 2"}],"isError":true,"id":"{{message:19}}"},"error":{"name":"SubagentDepthError","code":"DEPTH_EXCEEDED"}},"sourceEventSeqs":[15],"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":"text","text":"DEPTH_REJECTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:20}}"},"usage":{"inputTokens":10,"outputTokens":2},"stream":[{"type":"chunk","time":1789625678991,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1789625678991,"index":0,"dt":[],"texts":["DEPTH_REJECTED"]},{"type":"chunk","time":1789625678991,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DEPTH_REJECTED"}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}},{"type":"chunk","time":1789625678991,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl index 5062e09793..9f3180e9f2 100644 --- a/snapshots/session/subagent-structured-parent/session.1.v4.jsonl +++ b/snapshots/session/subagent-structured-parent/session.1.v4.jsonl @@ -16,7 +16,7 @@ {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"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":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}}},{"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":"call_structured_answer","name":"structured_output","arguments":"{\"answer\":41}"}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Agent lead sent a message: "},{"type":"text","text":"Correction: submit answer 42 instead."}],"source":{"kind":"agent-message","form":"relay","senderSessionId":"{{session:1}}"},"role":"user","id":"{{message:12}}"}]}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_structured_answer"},"toolCallId":"call_structured_answer","content":[{"type":"text","text":"Error: Process pending messages before submitting structured output."}],"isError":true,"id":"{{message:13}}"},"error":{"name":"SubagentError","code":"STRUCTURED_OUTPUT_PENDING_INPUT"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":2}} From fdd2dcc7e87eb3a0da7c83f7144b8b740dd30d60 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:14 +0800 Subject: [PATCH 014/122] feat(plan-mode): add PlanModeError for exit_plan_mode failures exit_plan_mode threw plain Errors, so its most common failure, the user choosing to keep planning, reached tool/result without an error.code. PlanModeError carries PLAN_NOT_ACTIVE, PLAN_REVIEW_INTERRUPTED, and PLAN_REVISION_REQUESTED. A plan without a leading heading is a ToolArgsError, and a missing caller, user-questions channel, or projection reader is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/plan.i18n.yaml | 4 +- docs/subsystems/plan.md | 2 +- docs/subsystems/plan.zh.md | 2 +- packages/plan/plan-mode/README.i18n.yaml | 12 +++--- packages/plan/plan-mode/README.md | 5 ++- packages/plan/plan-mode/README.zh.md | 5 ++- packages/plan/plan-mode/src/error.ts | 38 +++++++++++++++++++ packages/plan/plan-mode/src/index.ts | 28 +++++++++----- .../plan/plan-mode/tests/plan-mode.spec.ts | 23 +++++++++-- snapshots/sdk/plan-review/session.v4.jsonl | 2 +- 10 files changed, 94 insertions(+), 27 deletions(-) create mode 100644 packages/plan/plan-mode/src/error.ts diff --git a/docs/subsystems/plan.i18n.yaml b/docs/subsystems/plan.i18n.yaml index 5e92dac5a5..f172403181 100644 --- a/docs/subsystems/plan.i18n.yaml +++ b/docs/subsystems/plan.i18n.yaml @@ -15,8 +15,8 @@ en: ee04468005fae8e1 zh: 1347d554102951f2 /plan-mode/the-exit-tool-and-the-plan-command: - en: 32ecfb7086dd1578 - zh: 0aaeaa69bb63f255 + en: c9e86f6312dab80f + zh: 41b763216d6b1a54 /plan-mode/the-service: en: f3e6d5a7fe0b67f0 zh: 774cc97e493991fa diff --git a/docs/subsystems/plan.md b/docs/subsystems/plan.md index a37207d868..05dbdc50a9 100644 --- a/docs/subsystems/plan.md +++ b/docs/subsystems/plan.md @@ -30,7 +30,7 @@ A missing, blank, or non-string `section` and any unknown key fail at plugin loa ## The exit tool and the `/plan` command -[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails. In plan mode it requires a complete markdown plan starting with a `#` heading and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel and a service reload during review also fail the call rather than silently leaving plan mode. +[`exit_plan_mode`](../tool-catalog.md#deepseek-aidsh-plan-mode) is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so the first plan-mode entry adds it to the request tool declarations and later transitions change only the plan guidance. Native and PTC execution use the same admitted set; a call before the first entry returns `UNKNOWN_TOOL`, and a call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`. In plan mode it requires a complete markdown plan starting with a `#` heading, rejecting any other plan with `ToolArgsError`, and presents it for review through the [user-questions seam](user-questions.md). Approval returns `{ approved: true }` and records a silent (non-narrated) pending exit that is appended at the next accepted in-turn pre-step. Plan guidance therefore remains active for the rest of the assistant's current tool batch, and the tool result itself reports the transition. Keep-planning is a failed call with `PlanModeError` `PLAN_REVISION_REQUESTED` carrying the user's feedback, so the model revises and presents again. A dismissed review returns `{ approved: false }` and concludes the turn, so plan mode stays active until the user's next message. A missing interaction channel (`ToolContextUnavailableError`) and a service reload during review (`PLAN_REVIEW_INTERRUPTED`) also fail the call rather than silently leaving plan mode. When [`ctx.commands`](commands.md) is composed, the plugin registers `/plan [off|message]`: bare `/plan` selects plan mode, any other non-empty message selects it and then submits the text through `agent.steer()` so it becomes the next step's ordinary logged user message under plan guidance, and the exact argument `off` selects inactive, which also cancels a pending entry before it is appended and becomes visible to a request. diff --git a/docs/subsystems/plan.zh.md b/docs/subsystems/plan.zh.md index 8f45d70c5b..de51ac0569 100644 --- a/docs/subsystems/plan.zh.md +++ b/docs/subsystems/plan.zh.md @@ -30,7 +30,7 @@ interface PlanModeConfig { ## 退出工具与 `/plan` 命令 -[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用会失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次携带用户反馈的失败调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。评审期间交互通道缺失或服务重载同样使调用失败,而不是静默离开计划模式。 +[`exit_plan_mode`](../tool-catalog.zh.md#deepseek-aidsh-plan-mode) 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它进入请求的工具声明,之后的切换只改变计划指引。原生与 PTC 执行使用同一准入集合;首次进入之前调用返回 `UNKNOWN_TOOL`,计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败。在计划模式中,它要求一份以 `#` 标题开头的完整 markdown 计划,其他计划以 `ToolArgsError` 拒绝,并通过[用户交互 seam](user-questions.zh.md) 呈交评审。批准返回 `{ approved: true }`,并记录一个静默(不叙述)的待生效退出,由下一个被接受的轮内 pre-step 追加。因此,计划指引在 assistant 当前这批工具调用的剩余部分继续生效,而工具结果本身会报告这次转换。「继续规划」则是一次以 `PlanModeError` `PLAN_REVISION_REQUESTED` 失败并携带用户反馈的调用,模型据此修订并再次呈交。放弃评审返回 `{ approved: false }` 并结束当前轮次,计划模式保持激活,直到用户发出下一条消息。交互通道缺失(`ToolContextUnavailableError`)或评审期间服务重载(`PLAN_REVIEW_INTERRUPTED`)同样使调用失败,而不是静默离开计划模式。 当 [`ctx.commands`](commands.zh.md) 被组合时,插件注册 `/plan [off|message]`:单独的 `/plan` 选择计划模式;任何其他非空消息先选择计划模式,再通过 `agent.steer()` 提交该文本,使其在计划指引下成为下一步骤的普通已记录用户消息;确切参数 `off` 选择未激活,这还会在待生效条目被追加并对请求可见之前将其取消。 diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 96b7f724c7..31f4436eec 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -45,14 +45,14 @@ en: a7bf35c2a9da52bc zh: dea9f4b3a41f1a6d /deepseek-ai-dsh-plan-mode/understand-the-implementation/the-exit-tool: - en: 7736aea9e4934fa8 - zh: a595e477f54a199e + en: d14383e9c8c404dc + zh: 056ec01db0f9d63e /deepseek-ai-dsh-plan-mode/understand-the-implementation/session-projection-unit: en: 396d66816890f715 zh: fab5d67c027b33f5 /deepseek-ai-dsh-plan-mode/understand-the-implementation/source-map: - en: fa97e858495a8105 - zh: 8be1fbd7e420ff8a + en: 5c25e9fd2b7104b8 + zh: 00af162e5a9d080a /deepseek-ai-dsh-plan-mode/further-exploration: en: 5008d6d632002f49 zh: 65184d489ecdcec0 @@ -90,8 +90,8 @@ en: 9622e96bdc01276d zh: 53801e68a49f3d1d /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/what-the-model-sees: - en: 1b978a7b6eecdffe - zh: 338000d1bf8dd4a9 + en: 7f132783f06161cf + zh: 571852401060940f /deepseek-ai-dsh-plan-mode/model-experience/exit-tool-schema-and-review-exchange/token-effect: en: 5ef9db72f91e4a8c zh: 6e96335cc3eb5976 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 0ea3a4b33c..38971a5c94 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -90,7 +90,7 @@ The command child activates only when a commands service is composed. It maps ba ### The exit tool -`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel, or after a service reload while the review is pending, the call fails closed and `/plan off` remains the manual escape. +`exit_plan_mode` is disclosed progressively: it is admitted from the first step whose selected plan state is active and stays admitted for the rest of the Session, so entering plan mode the first time adds it together with the guidance, and later transitions change only the guidance; Native and PTC execution use the same admitted set. A call while plan mode is not committed fails with `PlanModeError` `PLAN_NOT_ACTIVE`, and a plan without a leading `#` heading fails with `ToolArgsError` before review. An approved review records a silent pending exit that the next accepted in-turn pre-step appends, keeping plan guidance for the rest of the current tool batch. Without a user-questions channel (`ToolContextUnavailableError`), or after a service reload while the review is pending (`PLAN_REVIEW_INTERRUPTED`), the call fails closed and `/plan off` remains the manual escape. [`src/error.ts`](src/error.ts) lists the `PlanModeError` codes. ### Session projection unit @@ -104,6 +104,7 @@ The unit turns logged `/plan` command runs into a candidate target, commits the |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: `Config` schema, the `ctx.planMode` service, `plan:policy` section, `/plan` command, `exit_plan_mode` tool | | [`src/types.ts`](src/types.ts) | The `plan` projection-key declaration and `PlanProjection` wire value | +| [`src/error.ts`](src/error.ts) | `PlanModeError` and its closed code list | | [`src/client.ts`](src/client.ts) | Client-namespace re-export of the types outlet | The review intent carries the originating tool-call id, so the Web client can reopen the same submitted plan after the review closes. The complete Markdown remains in the existing native call or PTC dispatch log. @@ -166,7 +167,7 @@ The user block is append-only conversation growth. Entering or leaving plan mode #### What the model sees -The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. +The [`exit_plan_mode` schema](../../../docs/tool-catalog.md#deepseek-aidsh-plan-mode) is offered from the first plan-mode entry in a Session; earlier calls return `UNKNOWN_TOOL`, calls after leaving plan mode fail as unavailable outside plan mode, and an approved in-mode review returns the canonical `{ approved: true }` value and renders the existing confirmation text. Rejection remains a failed call with `PLAN_REVISION_REQUESTED` carrying review feedback. A dismissed review returns `{ approved: false }`, renders a note that the user will reply, and concludes the turn without another model request. #### Token effect diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 90ee3c97e5..76d43e43ec 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -90,7 +90,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 ### 退出工具 -`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用会失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道,或评审等待期间服务重载,调用都会以拒绝方式失败,`/plan off` 仍是手动退路。 +`exit_plan_mode` 采用渐进式披露:从已选计划状态首次为激活的步骤起准入,并在会话剩余部分保持准入,因此首次进入计划模式时它与指引一起出现,之后的切换只改变指引;原生与 PTC 执行使用同一准入集合。计划模式未提交时调用以 `PlanModeError` `PLAN_NOT_ACTIVE` 失败,没有前导 `#` 标题的计划在评审前以 `ToolArgsError` 失败。经批准的评审会记录一个静默的待生效退出,由下一个被接受的轮内 pre-step 追加,当前这批工具调用剩余部分仍保留计划引导。缺少用户交互通道(`ToolContextUnavailableError`),或评审等待期间服务重载(`PLAN_REVIEW_INTERRUPTED`),调用都会以拒绝方式失败,`/plan off` 仍是手动退路。[`src/error.ts`](src/error.ts) 列出 `PlanModeError` 的 code。 ### 会话投影单元 @@ -104,6 +104,7 @@ agent 完成计划后,会以 markdown 形式、从标题开头书写计划并 |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:`Config` schema、`ctx.planMode` 服务、`plan:policy` 段落、`/plan` 命令、`exit_plan_mode` 工具 | | [`src/types.ts`](src/types.ts) | `plan` 投影 key 声明与 `PlanProjection` 协议值 | +| [`src/error.ts`](src/error.ts) | `PlanModeError` 及其封闭 code 列表 | | [`src/client.ts`](src/client.ts) | types 出口的客户端命名空间再导出 | 审批意图携带发起工具调用的标识,让 Web 客户端在审批关闭后重新打开同一份计划。完整 Markdown 保留在已有的原生调用或 PTC dispatch 日志中。 @@ -166,7 +167,7 @@ You are in plan mode. Explore and design before presenting the complete plan thr #### 模型看到什么 -[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是携带评审反馈的失败调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 +[`exit_plan_mode` schema](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plan-mode) 从会话首次进入计划模式起提供;此前的调用返回 `UNKNOWN_TOOL`,离开计划模式后的调用会以计划模式之外不可用而失败。模式内获批的评审返回规范值 `{ approved: true }` 并渲染现有确认文本。拒绝仍是以 `PLAN_REVISION_REQUESTED` 失败并携带评审反馈的调用。放弃评审返回 `{ approved: false }`,渲染一条说明用户将自行回复的文本,并结束当前轮次,不再发起模型请求。 #### Token 影响 diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts new file mode 100644 index 0000000000..e0227893bb --- /dev/null +++ b/packages/plan/plan-mode/src/error.ts @@ -0,0 +1,38 @@ +/** + * Typed `exit_plan_mode` failures. + * + * @module @deepseek-ai/dsh-plan-mode/error + */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every machine-routable plan-mode failure: + * - `PLAN_NOT_ACTIVE`: the caller's committed state is not plan mode; work without the exit tool. + * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. + * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. + */ +export const PLAN_MODE_ERROR_CODES = [ + 'PLAN_NOT_ACTIVE', + 'PLAN_REVIEW_INTERRUPTED', + 'PLAN_REVISION_REQUESTED', +] as const + +/** One plan-mode failure code. */ +export type PlanModeErrorCode = typeof PLAN_MODE_ERROR_CODES[number] + +/** Typed plan-mode failure; `code` is one of {@link PLAN_MODE_ERROR_CODES}. */ +export class PlanModeError extends HarnessError { + override readonly code: PlanModeErrorCode + + /** + * @param message - model-facing reason and next step. + * @param code - failure class from {@link PLAN_MODE_ERROR_CODES}. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: PlanModeErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'PlanModeError' + this.code = code + } +} diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 06af5c2828..636165c5e3 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -30,18 +30,20 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import { UserQuestionError, type AskUserQuestionAnswer } from '@deepseek-ai/dsh-user-questions' import type { CommandDefinitionId, CommandId } from '@deepseek-ai/dsh-commands' import type {} from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition, ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type { PlanProjection, PlanUnitState } from './types.ts' +import { PlanModeError } from './error.ts' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { 'plan-mode': { kind: 'plan-mode' } & ContextFormed } } export type * from './types.ts' +export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { @@ -301,15 +303,20 @@ export class PlanModeController extends Service { execute: async (args, exec) => { const agent = exec.agent // Admission outlives plan mode and follows the selected state, so check the committed state. - if (agent === undefined || !this.loggedActive(agent.session)) { - throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`) + if (agent === undefined) { + throw new ToolContextUnavailableError(`${EXIT_PLAN_MODE} requires a calling agent`) + } + if (!this.loggedActive(agent.session)) { + throw new PlanModeError(`${EXIT_PLAN_MODE} is only available in plan mode`, 'PLAN_NOT_ACTIVE') } if (!/^#\s+\S/.test(args.plan.trim())) { - throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`) + throw new ToolArgsError([`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`]) } const interaction = ctx.get('userQuestions') if (interaction === undefined) { - throw new Error('no user-questions channel is available to review the plan; ask the user to switch the session mode instead') + throw new ToolContextUnavailableError( + 'no user-questions channel is available to review the plan; ask the user to switch the session mode instead', + ) } let answer: AskUserQuestionAnswer try { @@ -345,15 +352,18 @@ export class PlanModeController extends Service { // A review may outlive this plugin fiber. Without its pre-step listener, // an approved selection could never be appended, so fail and keep planning. if (disposed) { - throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again') + throw new PlanModeError( + 'the plan-mode service was reloaded while the plan was under review; present the plan again', + 'PLAN_REVIEW_INTERRUPTED', + ) } const reviewItems = answer.answers.filter(entry => entry.id === REVIEW_ID) const item = reviewItems.length === 1 ? reviewItems[0] : undefined if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) { const feedback = item?.custom ?? '' - throw new Error(feedback === '' + throw new PlanModeError(feedback === '' ? 'The user chose to keep planning; revise the plan and present it again.' - : `The user chose to keep planning; their feedback: ${feedback}`) + : `The user chose to keep planning; their feedback: ${feedback}`, 'PLAN_REVISION_REQUESTED') } // Keep plan guidance for the rest of this assistant tool batch. The // silent selection is appended at the next accepted in-turn pre-step, @@ -394,7 +404,7 @@ export class PlanModeController extends Service { private planState(session: Session): PlanUnitState { if (this.planProjectionHandle === undefined) { - throw new Error('plan mode is not ready; await plugin activation before running an agent') + throw new ToolContextUnavailableError('plan mode is not ready; await plugin activation before running an agent') } return this.planProjectionHandle.stateOf(session) } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 99d72afd1d..0ebe17cb31 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -844,7 +844,11 @@ describe('exit_plan_mode', () => { arguments: { plan: '# P' }, token: Symbol('direct-exit') as ToolExecutionToken, signal: testToolSignal, deferContext() {}, concludeTurn() {}, } - await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toThrow(`${EXIT_PLAN_MODE} is only available in plan mode`) + await expect(exit?.execute({ plan: '# P' }, exec)).rejects.toMatchObject({ + name: 'ToolContextUnavailableError', + code: 'TOOL_CONTEXT_UNAVAILABLE', + message: `${EXIT_PLAN_MODE} requires a calling agent`, + }) }) it('keeps the exit tool after leaving plan mode and rejects a call outside it', async () => { @@ -855,6 +859,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('admits the exit tool for a selected entry but rejects a call before the entry is logged', async () => { @@ -866,6 +871,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode is only available in plan mode' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_NOT_ACTIVE' }) }) it('rejects an empty or heading-less plan before asking the reviewer', async () => { @@ -873,7 +879,8 @@ describe('exit_plan_mode', () => { for (const plan of ['', 'do things']) { const result = await callExit(ctx, agent, plan) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: invalid arguments: exit_plan_mode requires a non-empty markdown plan starting with a # heading' }]) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) } expect(asked).toHaveLength(0) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) @@ -885,6 +892,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: no user-questions channel is available to review the plan; ask the user to switch the session mode instead' }]) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1022,6 +1030,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: consider the resume path' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1030,6 +1039,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('a custom-text-only answer is feedback, never consent', async () => { @@ -1037,6 +1047,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: add tests first' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1045,6 +1056,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1053,6 +1065,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; their feedback: change the tests' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1067,6 +1080,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1076,6 +1090,7 @@ describe('exit_plan_mode', () => { const result = await callExit(ctx, agent) expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: The user chose to keep planning; revise the plan and present it again.' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVISION_REQUESTED' }) }) it('declares the plan-review presentation intent naming its approve option', async () => { @@ -1153,6 +1168,7 @@ describe('exit_plan_mode', () => { const result = await pending expect(result.isError).toBe(true) expect(result.content).toEqual([{ type: 'text', text: 'Error: the plan-mode service was reloaded while the plan was under review; present the plan again' }]) + expect(result.error?.info).toEqual({ name: 'PlanModeError', code: 'PLAN_REVIEW_INTERRUPTED' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) @@ -1161,7 +1177,8 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) diff --git a/snapshots/sdk/plan-review/session.v4.jsonl b/snapshots/sdk/plan-review/session.v4.jsonl index 5911c994ea..5113b1bcc2 100644 --- a/snapshots/sdk/plan-review/session.v4.jsonl +++ b/snapshots/sdk/plan-review/session.v4.jsonl @@ -34,7 +34,7 @@ {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":31}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:11}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"commands-tool-1"},"toolCallId":"commands-tool-1","content":[{"type":"text","text":"Error: The user chose to keep planning; their feedback: Add rollback."}],"isError":true,"id":"{{message:12}}"},"error":{"name":"PlanModeError","code":"PLAN_REVISION_REQUESTED"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":37}} From 551e5ce51a88b92c400f54bcd1e7c243f26045fc Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:15 +0800 Subject: [PATCH 015/122] feat(workflow): code workflow runs that end cancelled or failed The workflow tool threw a plain Error when a foreground run settled as cancelled or error, the most frequent uncoded workflow failure. It now throws WorkflowError CANCELLED or the new RUN_FAILED code, and rethrows the caller's abort reason when the calling step was aborted so the registry records AbortError ABORTED. A disabled run_in_background is UNSUPPORTED_OPTION, and a missing caller or jobs service is a ToolContextUnavailableError. Refs #7869 --- docs/subsystems/workflow.i18n.yaml | 4 +-- docs/subsystems/workflow.md | 2 +- docs/subsystems/workflow.zh.md | 2 +- .../workflow/tool-workflow/README.i18n.yaml | 12 ++++----- packages/workflow/tool-workflow/README.md | 6 ++--- packages/workflow/tool-workflow/README.zh.md | 6 ++--- packages/workflow/tool-workflow/src/index.ts | 27 ++++++++++--------- .../tool-workflow/tests/tool-workflow.spec.ts | 10 +++++-- packages/workflow/workflow/README.i18n.yaml | 4 +-- packages/workflow/workflow/README.md | 2 +- packages/workflow/workflow/README.zh.md | 2 +- packages/workflow/workflow/src/index.ts | 7 +++-- 12 files changed, 48 insertions(+), 36 deletions(-) diff --git a/docs/subsystems/workflow.i18n.yaml b/docs/subsystems/workflow.i18n.yaml index f3b906de0d..fdd069e032 100644 --- a/docs/subsystems/workflow.i18n.yaml +++ b/docs/subsystems/workflow.i18n.yaml @@ -18,8 +18,8 @@ en: a86b204323005042 zh: 82b691e28ed4dcd3 /workflow/failure-discipline-workflowerror-fatal: - en: 4d390801bb07374c - zh: 1099f053c2ee26ec + en: b53ef6f97fb9c092 + zh: 5a34538bff77e364 /workflow/events: en: de123821a128c1d1 zh: e50bcaea2812575a diff --git a/docs/subsystems/workflow.md b/docs/subsystems/workflow.md index 5b51dc1ff1..7b84c7f33b 100644 --- a/docs/subsystems/workflow.md +++ b/docs/subsystems/workflow.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## Failure discipline: `WorkflowError.fatal` -Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. +Hook misuse inside a script — bad arguments, unknown/deferred `agent()` options, a schema outside the [structured-output subset](../../packages/core/tools/README.md), a tripped cap, a seam start failure, cancellation — throws a `WorkflowError` with `fatal: true`. The `parallel()`/`pipeline()` combinators RE-THROW fatal errors instead of mapping the item to `null`: a typo'd option must kill the script loudly, never dissolve into something that reads as an ordinary child failure. The per-item `null` is reserved for child-run failures (a non-`completed` stop reason) and ordinary in-stage script errors. Because `WorkflowResult` carries only the failure message, the `workflow` tool classifies a run that settled as `cancelled` with `CANCELLED` and one that settled as `error` with `RUN_FAILED`; when the calling step itself was aborted, the tool runtime's `AbortError` `ABORTED` result applies instead. ## Events diff --git a/docs/subsystems/workflow.zh.md b/docs/subsystems/workflow.zh.md index 1514fa31d6..56e3a0ff22 100644 --- a/docs/subsystems/workflow.zh.md +++ b/docs/subsystems/workflow.zh.md @@ -113,7 +113,7 @@ interface WorkflowRun { ## 失败纪律:`WorkflowError.fatal` -脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。 +脚本内部的钩子误用:错误参数、未知或延迟的 `agent()` 选项、超出[结构化输出子集](../../packages/core/tools/README.zh.md)的 schema、超出上限、seam 启动失败、取消,都会抛出 `fatal: true` 的 `WorkflowError`。`parallel()`/`pipeline()` 组合器对 fatal 错误直接重新抛出,而非将该项映射为 `null`:一个拼写错误的选项必须明确报错并终止脚本,绝不能消融为看似普通子 agent 失败的结果。逐项的 `null` 保留给子运行失败(非 `completed` 的 stop reason)和阶段内的普通脚本错误。由于 `WorkflowResult` 只携带失败消息,`workflow` 工具把以 `cancelled` 结束的运行归类为 `CANCELLED`,把以 `error` 结束的运行归类为 `RUN_FAILED`;调用方步骤本身被中止时,改为使用工具运行时的 `AbortError` `ABORTED` 结果。 ## 事件 diff --git a/packages/workflow/tool-workflow/README.i18n.yaml b/packages/workflow/tool-workflow/README.i18n.yaml index 8f307582b3..0fd0d3a6ed 100644 --- a/packages/workflow/tool-workflow/README.i18n.yaml +++ b/packages/workflow/tool-workflow/README.i18n.yaml @@ -18,8 +18,8 @@ en: a0a9d655187f285d zh: 230b4556fff9f08b /deepseek-ai-dsh-tool-workflow/use-this-package/calling-the-tool: - en: aeebba9469f0558d - zh: e2e74d4272e94201 + en: 8b9606845ce5caf1 + zh: af0b71be80e1bb7c /deepseek-ai-dsh-tool-workflow/use-this-package/what-to-expect-during-a-run: en: 19ec4f830edb8e1a zh: 8579ae5274aca6de @@ -36,8 +36,8 @@ en: 6d09119d1393c254 zh: a7cc03daa59650ec /deepseek-ai-dsh-tool-workflow/understand-the-implementation/run-lifecycle: - en: 8ea9ce564251249a - zh: a59b88cc14a25a1f + en: ef2c2a573b30c262 + zh: 5a078b9fe31e333d /deepseek-ai-dsh-tool-workflow/understand-the-implementation/background-lifecycle: en: 35950b2015800ec5 zh: 5ae6f5a5e53dc585 @@ -87,8 +87,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/what-the-model-sees: - en: acd5e87161ced588 - zh: 5ffe85926ee1b88d + en: 483515bf4c1dc710 + zh: 69b23bd7f331ddea /deepseek-ai-dsh-tool-workflow/model-experience/tool-call-history-and-result/token-effect: en: 88cfc89c7dc19dbb zh: 75e674844f311937 diff --git a/packages/workflow/tool-workflow/README.md b/packages/workflow/tool-workflow/README.md index 5cdadb9ab5..7dc859d1f2 100644 --- a/packages/workflow/tool-workflow/README.md +++ b/packages/workflow/tool-workflow/README.md @@ -31,7 +31,7 @@ The `workflow` tool runs a model-authored orchestration script that fans work ou The model submits three parameters plus one flag: `meta` (required identity data: `name`, `description`, and optional `whenToUse` and `phases`), `script` (required plain JavaScript body — no `export const meta` statement; its parameter description carries the body rules and the tool description carries the hook contract), `args` (optional JSON object exposed to the script as the `args` global; wrap a bare list in a field so the wire schema stays honest), and `run_in_background` (optional; present only while `enableRunInBackground` holds). -A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancellation and execution failures return `Error: workflow run was cancelled` or `Error: workflow run failed: `; partial output is never reported as success. +A foreground success returns the envelope `{ kind: 'foreground', runId, agentsStarted, result }`, rendered to the model as `workflow "" completed ( agent).` followed by `Return value:` and the pretty-printed JSON. A workflow that cannot start — a script parse or meta validation failure — returns an error the model can correct from. Cancelling the calling step returns the tool runtime's `AbortError` `ABORTED` result; any other cancellation and execution failures return `Error: workflow run was cancelled` (`WorkflowError` `CANCELLED`) or `Error: workflow run failed: ` (`WorkflowError` `RUN_FAILED`); partial output is never reported as success. ### What to expect during a run @@ -67,7 +67,7 @@ The consumer owns the model-facing schema, the `tool:` system-prompt g ### Run lifecycle -`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. +`execute` starts the run and awaits `run.result` inside a `try/finally` that always disposes the run. `exec.signal` is bridged to `run.cancel()`, including the already-aborted-before-start case. A non-`completed` stop reason maps to an `isError` result reporting the reason, rethrowing the caller's abort reason when `exec.signal` aborted and otherwise throwing a `WorkflowError`; completion renders `{ kind, runId, agentsStarted, result }`, with the Native renderer truncating only that projection at `maxResultChars`. ### Background lifecycle @@ -150,7 +150,7 @@ Prefix-stable while `toolName`, definition, and visibility are unchanged. Renami #### What the model sees -The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)`. Intermediate child messages are omitted. +The full model-written script, metadata, and args remain in the assistant tool call. A foreground success is exactly `workflow "" completed ( agent).`, newline, `Return value:`, newline, and pretty-printed data-dependent JSON; a cap adds `… [truncated: more characters]` on a new line. A background acceptance is exactly `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`, and the same rendered value later reaches the model through the job's completion notice and `job_output`. Failures after a caller abort render the abort reason; other failures are exactly `Error: workflow run was cancelled`, optionally suffixed ` ()`, `Error: workflow run failed: `, or defensively `Error: workflow run ended abnormally ()`; a call without an owning agent becomes `Error: workflow tool requires a calling agent (exec.agent was undefined)` (`ToolContextUnavailableError`). Intermediate child messages are omitted. #### Token effect diff --git a/packages/workflow/tool-workflow/README.zh.md b/packages/workflow/tool-workflow/README.zh.md index dcc92b352c..5b9ebe44c1 100644 --- a/packages/workflow/tool-workflow/README.zh.md +++ b/packages/workflow/tool-workflow/README.zh.md @@ -31,7 +31,7 @@ kind: "package-reference" 模型提交三个参数外加一个开关:`meta`(必需的身份数据:`name`、`description`,以及可选的 `whenToUse` 与 `phases`)、`script`(必需的纯 JavaScript 脚本体——不含 `export const meta` 语句;其参数描述携带脚本体规则,工具描述携带钩子约定)、`args`(可选 JSON 对象,作为全局变量 `args` 向脚本公开;裸列表应包装到字段中,使协议 schema 如实表达形态),以及 `run_in_background`(可选;仅在 `enableRunInBackground` 生效时存在)。 -前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消与执行失败返回 `Error: workflow run was cancelled` 或 `Error: workflow run failed: `;部分输出绝不会被报告为成功。 +前台成功返回包络 `{ kind: 'foreground', runId, agentsStarted, result }`,向模型渲染为 `workflow "" completed ( agent).`,后接 `Return value:` 与美化打印的 JSON。无法启动的工作流——脚本解析或 meta 校验失败——返回模型可以修正的错误。取消调用方步骤时返回工具运行时的 `AbortError` `ABORTED` 结果;其他取消与执行失败返回 `Error: workflow run was cancelled`(`WorkflowError` `CANCELLED`)或 `Error: workflow run failed: `(`WorkflowError` `RUN_FAILED`);部分输出绝不会被报告为成功。 ### 运行期间的预期 @@ -67,7 +67,7 @@ kind: "package-reference" ### 运行生命周期 -`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 +`execute` 启动运行,并在 `try/finally` 内等待 `run.result`;该结构总会对运行执行 dispose。`exec.signal` 会桥接到 `run.cancel()`,包括启动前已经中止的情况。非 `completed` 结束原因会映射为报告原因的 `isError` 结果:`exec.signal` 已中止时重新抛出调用方的中止原因,否则抛出 `WorkflowError`;完成时渲染 `{ kind, runId, agentsStarted, result }`,Native 渲染器只会在 `maxResultChars` 处截断该投影。 ### 后台生命周期 @@ -150,7 +150,7 @@ Use the tool ONLY when the user explicitly asks for a workflow or for #### 模型看到什么 -由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`。中间子 agent 消息会被省略。 +由模型编写的完整脚本、元数据与 args 会保留在 assistant 工具调用中。前台成功结果精确为 `workflow "" completed ( agent).`、换行、`Return value:`、换行,以及美化打印且依赖数据的 JSON;达到上限时,会在新行添加 `… [truncated: more characters]`。后台受理结果精确为 `workflow "" started in the background as job . Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.`,同样渲染的值稍后经任务完成播报与 `job_output` 抵达模型。调用方中止后的失败渲染中止原因;其他失败结果精确为 `Error: workflow run was cancelled`(可以追加后缀 ` ()`)、`Error: workflow run failed: ` 或防御性的 `Error: workflow run ended abnormally ()`;没有所属 agent 的调用变为 `Error: workflow tool requires a calling agent (exec.agent was undefined)`(`ToolContextUnavailableError`)。中间子 agent 消息会被省略。 #### Token 影响 diff --git a/packages/workflow/tool-workflow/src/index.ts b/packages/workflow/tool-workflow/src/index.ts index 66fda2da15..c8e3135c1c 100644 --- a/packages/workflow/tool-workflow/src/index.ts +++ b/packages/workflow/tool-workflow/src/index.ts @@ -14,13 +14,14 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JobId, JobOutcome, JobToolCall } from '@deepseek-ai/dsh-jobs' import type { Session, SessionEventMap } from '@deepseek-ai/dsh-session' import type { JsonValue } from '@deepseek-ai/dsh-util-values' +import { WorkflowError } from '@deepseek-ai/dsh-workflow' import type { WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason, } from '@deepseek-ai/dsh-workflow' @@ -194,17 +195,17 @@ function presentWorkflowResult(args: WorkflowCallArgs, result: { content: Conten } /** A non-`completed` stop reason means the script did not finish cleanly. */ -function stopReasonError(result: WorkflowResult): string | undefined { +function stopReasonError(result: WorkflowResult): WorkflowError | undefined { switch (result.stopReason) { case 'completed': return undefined case 'cancelled': - return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}` + return new WorkflowError(`workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`, 'CANCELLED') case 'error': - return `workflow run failed: ${result.error ?? 'unknown error'}` + return new WorkflowError(`workflow run failed: ${result.error ?? 'unknown error'}`, 'RUN_FAILED') /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */ default: - return `workflow run ended abnormally (${String(result.stopReason satisfies never)})` + return new WorkflowError(`workflow run ended abnormally (${String(result.stopReason satisfies never)})`, 'RUN_FAILED') /* v8 ignore stop */ } } @@ -270,7 +271,7 @@ function startBackgroundRun( ): { kind: 'background'; jobId: JobId; runId: WorkflowRunId } { const jobs = ctx.get('jobs') if (jobs === undefined) { - throw new Error('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + throw new ToolContextUnavailableError('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') } let run!: WorkflowRun const jobId = jobs.start({ @@ -412,11 +413,11 @@ export function apply(ctx: Context, config: Config): void { // The loop sets `exec.agent` for every model-driven call; its absence // means a non-agent caller invoked the tool directly, which has no // parent to attribute the children to. Fail loud rather than guess. - throw new Error('workflow tool requires a calling agent (exec.agent was undefined)') + throw new ToolContextUnavailableError('workflow tool requires a calling agent (exec.agent was undefined)') } if (args.run_in_background === true) { if (!enableRunInBackground) { - throw new Error('run_in_background is disabled for this tool') + throw new WorkflowError('run_in_background is disabled for this tool', 'UNSUPPORTED_OPTION') } // No pre-abort check here, unlike bash/pwsh: ToolRuntime re-reads the // caller signal right before execute(), and this branch reaches @@ -455,9 +456,11 @@ export function apply(ctx: Context, config: Config): void { result = await run.result const error = stopReasonError(result) if (error !== undefined) { - // Map a non-clean finish to an isError result (the registry turns a - // throw into an isError). Report the reason, not partial output. - throw new Error(error) + // Caller cancellation keeps the registry's AbortError identity; any + // other non-clean finish becomes a coded isError result. Report the + // reason, not partial output. + exec.signal.throwIfAborted() + throw error } return { kind: 'foreground' as const, @@ -473,7 +476,7 @@ export function apply(ctx: Context, config: Config): void { await run.dispose() if (recordsRun) { /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */ - if (result === undefined) throw new Error('workflow run settled without a result') + if (result === undefined) throw new WorkflowError('workflow run settled without a result', 'RUN_FAILED') recorder.finish(run.id, result.stopReason) } } finally { diff --git a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts index 1502b428cd..98ea14d105 100644 --- a/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts +++ b/packages/workflow/tool-workflow/tests/tool-workflow.spec.ts @@ -5,7 +5,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' +import ToolRuntime, { TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import type { ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow' @@ -303,6 +303,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'RUN_FAILED' }) expect(engine.disposed).toBe(1) }) @@ -314,6 +315,7 @@ describe('dsh-tool-workflow', () => { const result = await pending expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'CANCELLED' }) const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent }) await vi.waitFor(() => { expect(engine.requests.length).toBe(2) }) @@ -337,6 +339,7 @@ describe('dsh-tool-workflow', () => { controller.abort() const result = await pending expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) expect(engine.cancels).toContain('parent step aborted') expect(engine.disposed).toBe(1) }) @@ -354,6 +357,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('requires a calling agent') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(engine.requests.length).toBe(0) }) @@ -614,6 +618,7 @@ describe('dsh-tool-workflow', () => { expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text) .toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('a disabled composition hides the parameter and rejects the call', async () => { @@ -624,6 +629,7 @@ describe('dsh-tool-workflow', () => { const result = await execute(ctx, { script: SCRIPT, meta: META, run_in_background: true }, { agent: parent }) expect(result.isError).toBe(true) expect((result.content[0] as { text: string }).text).toContain('run_in_background is disabled') + expect(result.error?.info).toEqual({ name: 'WorkflowError', code: 'UNSUPPORTED_OPTION' }) }) it('advertises the background semantics in the parameter', async () => { @@ -665,7 +671,7 @@ describe('dsh-tool-workflow', () => { controller.abort('user abort') const result = await pending expect(result.isError).toBe(true) - expect((result.content[0] as { text: string }).text).toContain('cancelled') + expect(result.error?.info).toEqual({ name: 'AbortError', code: TOOL_ABORTED }) }) it('a background run over the sandboxed PTC engine settles its job with the rendered return value', async () => { diff --git a/packages/workflow/workflow/README.i18n.yaml b/packages/workflow/workflow/README.i18n.yaml index dbd14da4fe..5760add38c 100644 --- a/packages/workflow/workflow/README.i18n.yaml +++ b/packages/workflow/workflow/README.i18n.yaml @@ -42,8 +42,8 @@ en: 95b074d816b52323 zh: dfa070a1531651f9 /deepseek-ai-dsh-workflow/understand-the-implementation/failure-discipline: - en: e2c2a6e2876457e8 - zh: 764cba9eede4bb79 + en: 8b862e7714718ba4 + zh: 21a04481ea85ff52 /deepseek-ai-dsh-workflow/further-exploration: en: 6b3752bee67372c3 zh: 92492c01c4d786d3 diff --git a/packages/workflow/workflow/README.md b/packages/workflow/workflow/README.md index 0bf762913f..0c3c5650f1 100644 --- a/packages/workflow/workflow/README.md +++ b/packages/workflow/workflow/README.md @@ -86,7 +86,7 @@ A run is holder-owned: engine-plugin unload prevents new starts but does not rev ### Failure discipline -`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, and cancellation; the exact set and meanings live in [`src/index.ts`](src/index.ts). +`WorkflowError` carries a machine-routable code and a `fatal` flag; every code is fatal, and `parallel()` and `pipeline()` re-throw fatal errors instead of mapping the item to `null` — a typo'd option must kill the script loudly. Codes cover start failures, contract violations, exceeded caps, provider and result faults, unserializable values, cancellation, and a consumer's classification of a run that settled with `stopReason: 'error'` (`RUN_FAILED`); the exact set and meanings live in [`src/index.ts`](src/index.ts). The per-item `null` is reserved for child-run failures and ordinary in-stage script errors, so a child that resolves normally with a non-completed stop reason is not an infrastructure exception: `agent()` returns `null`, letting the script handle an ordinary child failure. diff --git a/packages/workflow/workflow/README.zh.md b/packages/workflow/workflow/README.zh.md index 31c728a4f0..e6f1129263 100644 --- a/packages/workflow/workflow/README.zh.md +++ b/packages/workflow/workflow/README.zh.md @@ -86,7 +86,7 @@ return { reviewed: reviews.length } ### 失败纪律 -`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值与取消;完整集合与含义见 [`src/index.ts`](src/index.ts)。 +`WorkflowError` 携带机器可路由的 code 与 `fatal` 标志;每个 code 都是致命的,`parallel()` 与 `pipeline()` 会重新抛出致命错误,而不是把条目映射为 `null`——拼错的选项必须明确终止脚本。code 覆盖启动失败、约定违规、超出上限、提供方与结果故障、不可序列化值、取消,以及消费方对以 `stopReason: 'error'` 结束的运行所作的分类(`RUN_FAILED`);完整集合与含义见 [`src/index.ts`](src/index.ts)。 逐项 `null` 只保留给子运行失败与阶段内普通脚本错误,因此以非完成结束原因正常结算的子 agent 不属于基础设施异常:`agent()` 返回 `null`,让脚本处理普通子 agent 失败。 diff --git a/packages/workflow/workflow/src/index.ts b/packages/workflow/workflow/src/index.ts index b78a972977..3d16d576be 100644 --- a/packages/workflow/workflow/src/index.ts +++ b/packages/workflow/workflow/src/index.ts @@ -102,8 +102,10 @@ export type WorkflowEventName = /** * Machine-routable fatal workflow failures: parse/meta/argument/schema errors, * resource caps, subagent infrastructure failures, unserializable boundary - * values, and cancellation. An ordinary child failure resolves its item to - * `null` and is not one of these fatal codes. + * values, and cancellation. `RUN_FAILED` is the consumer's classification of a + * run that settled with `stopReason: 'error'`, whose {@link WorkflowResult} + * carries only the failure message. An ordinary child failure resolves its item + * to `null` and is not one of these fatal codes. */ export type WorkflowErrorCode = | 'SCRIPT_PARSE' @@ -117,6 +119,7 @@ export type WorkflowErrorCode = | 'AGENT_RESULT' | 'RESULT_UNSERIALIZABLE' | 'CANCELLED' + | 'RUN_FAILED' /** * Typed error for workflow-seam failures. Extends {@link HarnessError}, so the From 5fe691f6e50c554a2db88a5af03bfc5998f00042 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:16 +0800 Subject: [PATCH 016/122] feat(team,goal,todo): code projection and argument failures A failed Team or goal projection now rejects with TeamError TEAM_STATE_CORRUPT or GoalError GOAL_STATE_CORRUPT, and GoalError assigns its name literally. team_task_list cursor, limit, and filter violations and todo_write content checks throw ToolArgsError; missing callers throw ToolContextUnavailableError. todo_write violation messages now name the offending item path. Refs #7869 --- packages/goal/goal/README.i18n.yaml | 4 ++-- packages/goal/goal/README.md | 2 +- packages/goal/goal/README.zh.md | 2 +- packages/goal/goal/src/domain.ts | 1 + packages/goal/goal/src/index.ts | 2 +- packages/goal/goal/src/runtime.ts | 3 +-- packages/goal/goal/tests/projection.spec.ts | 3 ++- packages/team/agent-team/README.i18n.yaml | 4 ++-- packages/team/agent-team/README.md | 2 +- packages/team/agent-team/README.zh.md | 2 +- packages/team/agent-team/src/journal.ts | 4 ++-- packages/team/agent-team/tests/team.spec.ts | 5 +++-- packages/team/tool-agent-team/src/index.ts | 10 +++++----- .../team/tool-agent-team/tests/tool-team.spec.ts | 6 +++--- packages/todo/tool-todo/README.i18n.yaml | 4 ++-- packages/todo/tool-todo/README.md | 2 +- packages/todo/tool-todo/README.zh.md | 2 +- packages/todo/tool-todo/src/index.ts | 12 ++++++------ .../todo/tool-todo/tests/loader-composition.spec.ts | 1 + packages/todo/tool-todo/tests/tool-todo.spec.ts | 3 +++ 20 files changed, 40 insertions(+), 34 deletions(-) diff --git a/packages/goal/goal/README.i18n.yaml b/packages/goal/goal/README.i18n.yaml index 4aa0d5c88d..8a267e47bb 100644 --- a/packages/goal/goal/README.i18n.yaml +++ b/packages/goal/goal/README.i18n.yaml @@ -39,8 +39,8 @@ en: 592af7e68423bd1c zh: 9b1f08393db1b14e /deepseek-ai-dsh-goal/understand-the-implementation/design: - en: 6f19e891ffc79754 - zh: 9599e3b142f1e6b5 + en: c14410306499e607 + zh: 99d1d91259127aba /deepseek-ai-dsh-goal/understand-the-implementation/source-map: en: aef62dff93f32796 zh: dba79da0466218a7 diff --git a/packages/goal/goal/README.md b/packages/goal/goal/README.md index 9e0a1ee60d..f7dea16728 100644 --- a/packages/goal/goal/README.md +++ b/packages/goal/goal/README.md @@ -98,7 +98,7 @@ This section explains how the service realizes the behavior above; the observabl - **Compare-and-set mutations.** `ctx.goals` accepts only the exact live `Agent` registered under its id. `get()` returns a detached `GoalView`; mutations take a `GoalRef { id, revision }` and reject stale refs. Creation resolves the deployment default internally before committing. - **Activation is process-local.** `armed` and `disarmed` live in a per-session cache and are never persisted. A fresh cache and every `agent/created` edge disarm continuation even when replay finds an active durable phase; `disarm()` removes authority without writing a revision or emitting a mutation. - **Strict replay.** The fold derives lifecycle mutations only from `goal/change` and rejects malformed shapes, discontinuous revisions, illegal phase transitions, non-monotonic per-goal timestamps, and non-sequential admitted rounds. Positive rounds advance only on admitted goal-sourced `user/message` events, and mutation timestamps clamp against the preceding update when wall time moves backward. -- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure. +- **Projection unit.** The package requires the projection registry and registers a strict `goal` unit. Its host state retains replay validation data and the first failure, while its client view exposes the latest valid whole goal or `null`; `GoalService` rejects access after a retained replay failure with `GoalError` `GOAL_STATE_CORRUPT`. ### Source map diff --git a/packages/goal/goal/README.zh.md b/packages/goal/goal/README.zh.md index ac8fd3837b..515c2e85e9 100644 --- a/packages/goal/goal/README.zh.md +++ b/packages/goal/goal/README.zh.md @@ -98,7 +98,7 @@ view.activation // 'armed' | 'disarmed' — not persisted - **比较并设置的变更。** `ctx.goals` 只接受以对应 id 注册的完全相同的活跃 `Agent` 实例。`get()` 返回脱离状态的 `GoalView`;变更携带 `GoalRef { id, revision }` 并拒绝陈旧引用。创建在提交前于内部解析部署默认值。 - **续行启用状态是进程本地的。** `armed` 与 `disarmed` 保存在每会话缓存中,绝不持久化。新缓存与每次 `agent/created` 边界都会停用续行,即使回放发现持久 phase 为 active;`disarm()` 移除续行权限,不写入 revision 也不发出变更事件。 - **严格回放。** 折叠只从 `goal/change` 派生生命周期变更,并拒绝形状错误、不连续 revision、非法 phase 转换、每目标时间戳非单调,以及不连续的已准入 Round。只有已准入的来源为 goal 的 `user/message` 事件会推进正数 Round;挂钟时间倒退时,变更时间戳会限制在不早于上一次更新的值。 -- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会拒绝访问。 +- **投影单元。** 本包要求提供投影注册表,并注册一个严格的 `goal` 单元。其宿主状态保留回放校验数据与第一次失败,客户端视图提供最新有效的完整 goal 或 `null`;保留回放失败后,`GoalService` 会以 `GoalError` `GOAL_STATE_CORRUPT` 拒绝访问。 ### 源码地图 diff --git a/packages/goal/goal/src/domain.ts b/packages/goal/goal/src/domain.ts index 63f1573dc7..68cba67262 100644 --- a/packages/goal/goal/src/domain.ts +++ b/packages/goal/goal/src/domain.ts @@ -100,6 +100,7 @@ export type GoalErrorCode = | 'GOAL_INVALID_BLOCK_REASON' | 'GOAL_INVALID_EDIT' | 'GOAL_INVALID_TRANSITION' + | 'GOAL_STATE_CORRUPT' declare module '@deepseek-ai/cordis' { interface Events { diff --git a/packages/goal/goal/src/index.ts b/packages/goal/goal/src/index.ts index 3d54ed75d6..a6530bf789 100644 --- a/packages/goal/goal/src/index.ts +++ b/packages/goal/goal/src/index.ts @@ -477,7 +477,7 @@ export class GoalService extends TypertRemoteService { /** Read the current durable projection maintained by the registry. */ private state(session: Session): GoalProjection | null { const state = this.goalProjectionHandle.stateOf(session) - if (state.failure !== null) throw new Error(state.failure) + if (state.failure !== null) throw new GoalError(state.failure, 'GOAL_STATE_CORRUPT') return state.current } diff --git a/packages/goal/goal/src/runtime.ts b/packages/goal/goal/src/runtime.ts index 2f5c40735a..b7b9ad4c6c 100644 --- a/packages/goal/goal/src/runtime.ts +++ b/packages/goal/goal/src/runtime.ts @@ -22,9 +22,8 @@ export class GoalError extends HarnessError { * @param message - human-readable rejection reason. * @param code - stable machine-routable classification. */ - // Keep the constructor to narrow HarnessError's string code at this boundary. - // oxlint-disable-next-line typescript/no-useless-constructor -- type-only narrowing constructor(message: string, code: GoalErrorCode) { super(message, code) + this.name = 'GoalError' } } diff --git a/packages/goal/goal/tests/projection.spec.ts b/packages/goal/goal/tests/projection.spec.ts index b2aa38622d..05b72eef6c 100644 --- a/packages/goal/goal/tests/projection.spec.ts +++ b/packages/goal/goal/tests/projection.spec.ts @@ -243,7 +243,8 @@ describe('goal projection unit', () => { await expect(agentEvents(bench.ctx, bench.agent).serial('agent/created', { source: 'resume' })) .resolves.toBeUndefined() - expect(() => bench.ctx.goals.get(bench.agent)).toThrow(failure) + expect(() => bench.ctx.goals.get(bench.agent)) + .toThrow(expect.objectContaining({ name: 'GoalError', code: 'GOAL_STATE_CORRUPT', message: failure })) expect(bench.tailValues().goal).toMatchObject({ goal: { objective: 'poisoned replay' } }) }) diff --git a/packages/team/agent-team/README.i18n.yaml b/packages/team/agent-team/README.i18n.yaml index 2f1733cd95..f8f298dda8 100644 --- a/packages/team/agent-team/README.i18n.yaml +++ b/packages/team/agent-team/README.i18n.yaml @@ -66,8 +66,8 @@ en: a8baf51f2fcd6d49 zh: 357c8db36823fe0e /deepseek-ai-dsh-agent-team/understand-the-implementation/browser-projection: - en: ed33e64ea55d2b75 - zh: eb326025ff156dea + en: 1f8e19f2c73b1cf5 + zh: 1e535d354ad47c08 /deepseek-ai-dsh-agent-team/further-exploration: en: 60d969ec526f5556 zh: ed4f813006f86215 diff --git a/packages/team/agent-team/README.md b/packages/team/agent-team/README.md index a58392c1c3..d5d6c2f507 100644 --- a/packages/team/agent-team/README.md +++ b/packages/team/agent-team/README.md @@ -147,7 +147,7 @@ Unloading the service unregisters the projection. The retained handle remains re ### Browser projection -The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. +The `agentTeam` projection publishes non-deleted task views and any failure beside the last valid state. Historical roster and mailbox records cannot cause a task-board projection failure. A failed projection rejects task reads and mutations with `TeamError` `TEAM_STATE_CORRUPT` without appending task events. Mode selections can still be saved and applied, including disabling Team; the projection failure remains visible. Invalid mode payloads retain the last valid selection and publish a projection failure. The [subsystem reference](../../../docs/subsystems/agent-team.md#web-projection) defines the wire types. The [Web UI](../../client/ui-agent-team/README.md) displays tasks only. Ordinary subagent navigation owns the member list; task owner labels display the owner's full name, or its Session id when the owner has no name. diff --git a/packages/team/agent-team/README.zh.md b/packages/team/agent-team/README.zh.md index 9e57943fa1..204407b12d 100644 --- a/packages/team/agent-team/README.zh.md +++ b/packages/team/agent-team/README.zh.md @@ -147,7 +147,7 @@ Team 在激活前要求 `sessionPersistence` 可用。`Service.init` 等待 `age ### 浏览器投影 -`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 +`agentTeam` 投影发布未删除任务视图,并在最后有效状态旁报告失败。历史名册与邮箱记录不会导致任务板投影失败。投影失败后,任务读取和修改均以 `TeamError` `TEAM_STATE_CORRUPT` 报错,不再追加任务事件。模式选择仍可保存并生效,包括关闭 Team;投影错误持续可见。无效模式载荷保留最后有效选择,并发布投影错误。[子系统参考](../../../docs/subsystems/agent-team.zh.md#web-projection)定义线上的类型。 [Web UI](../../client/ui-agent-team/README.zh.md)仅展示任务。普通 subagent 导航负责成员列表;任务所有者标签显示所有者的完整名称,所有者没有名称时显示其 Session id。 diff --git a/packages/team/agent-team/src/journal.ts b/packages/team/agent-team/src/journal.ts index fd7c7fcfad..3e99c3b4d4 100644 --- a/packages/team/agent-team/src/journal.ts +++ b/packages/team/agent-team/src/journal.ts @@ -27,11 +27,11 @@ export class TeamJournal { * Read authoritative Team state for one exact live Lead. * @param root - exact live Team Lead. * @returns current projected state selected by the Lead Team id. - * @throws when the durable Team projection has failed. + * @throws {TeamError} `TEAM_STATE_CORRUPT` when the durable Team projection has failed. */ state(root: Agent): TeamState { const projection = this.teamProjectionHandle.stateOf(root.session) - if (projection.failure !== undefined) throw new Error(projection.failure) + if (projection.failure !== undefined) throw new TeamError(projection.failure, 'TEAM_STATE_CORRUPT') return projection } diff --git a/packages/team/agent-team/tests/team.spec.ts b/packages/team/agent-team/tests/team.spec.ts index f0724a9510..08d7d1e2c3 100644 --- a/packages/team/agent-team/tests/team.spec.ts +++ b/packages/team/agent-team/tests/team.spec.ts @@ -280,10 +280,11 @@ describe('Tree-owned task boards', () => { status: 'pending', blockedBy: [], writeScopes: [], }, }) - expect(() => ctx.agentTeams.listTasks(lead)).toThrow('must begin at revision 1') + const corrupt = { name: 'TeamError', code: 'TEAM_STATE_CORRUPT', message: expect.stringContaining('must begin at revision 1') as string } + expect(() => ctx.agentTeams.listTasks(lead)).toThrow(expect.objectContaining(corrupt)) const eventCount = lead.session.snapshotEvents().length await expect(ctx.agentTeams.createTask(lead, { subject: 'blocked', description: 'blocked' })) - .rejects.toThrow('must begin at revision 1') + .rejects.toMatchObject(corrupt) expect(lead.session.snapshotEvents()).toHaveLength(eventCount) }) diff --git a/packages/team/tool-agent-team/src/index.ts b/packages/team/tool-agent-team/src/index.ts index 353ad1c323..deaa07d572 100644 --- a/packages/team/tool-agent-team/src/index.ts +++ b/packages/team/tool-agent-team/src/index.ts @@ -6,7 +6,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { SubagentError } from '@deepseek-ai/dsh-subagent' import { TeamTaskId } from '@deepseek-ai/dsh-agent-team' import type { TeamTaskView } from '@deepseek-ai/dsh-agent-team' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { InferValue, ValueSchemaSpec } from '@deepseek-ai/dsh-tools' /** Cordis plugin name. */ @@ -82,7 +82,7 @@ type NamedTaskView = Omit & { readonly ow /** Recover the exact caller guaranteed by conditional Team-tool discovery. */ function callingAgent(agent: Agent | undefined, toolName: string): Agent { /* v8 ignore next 2 -- The Team condition rejects callers without an Agent before execution. */ - if (agent === undefined) throw new Error(`${toolName} requires a calling Agent`) + if (agent === undefined) throw new ToolContextUnavailableError(`${toolName} requires a calling Agent`) return agent } @@ -159,10 +159,10 @@ export function apply(ctx: Context, config: Config = {}): void { async execute(args, exec) { const cursor = args.cursor ?? 0 const limit = args.limit ?? 50 - if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('cursor must be a non-negative safe integer') - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error('limit must be an integer from 1 through 100') + if (!Number.isSafeInteger(cursor) || cursor < 0) throw new ToolArgsError(['cursor must be a non-negative safe integer']) + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new ToolArgsError(['limit must be an integer from 1 through 100']) const caller = callingAgent(exec.agent, 'team_task_list') - if (args.owner !== undefined && args.unowned !== undefined) throw new Error('owner and unowned filters cannot be combined') + if (args.owner !== undefined && args.unowned !== undefined) throw new ToolArgsError(['owner and unowned filters cannot be combined']) const owner = args.owner === undefined ? undefined : await ctx.subagents.resolveName(caller, args.owner, exec.signal) diff --git a/packages/team/tool-agent-team/tests/tool-team.spec.ts b/packages/team/tool-agent-team/tests/tool-team.spec.ts index db51194163..b286befd59 100644 --- a/packages/team/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/team/tool-agent-team/tests/tool-team.spec.ts @@ -529,8 +529,8 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { cursor: 1, })))).not.toHaveProperty('nextCursor') - expect((await execute(ctx, lead, 'team_task_list', { cursor: -1 })).isError).toBe(true) - expect((await execute(ctx, lead, 'team_task_list', { limit: 101 })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { cursor: -1 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) + expect(await execute(ctx, lead, 'team_task_list', { limit: 101 })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) const edited = await execute(ctx, lead, 'team_task_update', { task_id: first.id, @@ -588,7 +588,7 @@ describe('dsh-tool-team', () => { expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { owner: 'unowned' })))).toMatchObject({ tasks: [{ id: assigned.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: true })))).toMatchObject({ tasks: [{ id: pending.id }] }) expect(JSON.parse(text(await execute(ctx, lead, 'team_task_list', { unowned: false })))).toMatchObject({ tasks: [{ id: assigned.id }] }) - expect((await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).isError).toBe(true) + expect(await execute(ctx, lead, 'team_task_list', { owner: 'unowned', unowned: true })).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) await child.dispose() }) diff --git a/packages/todo/tool-todo/README.i18n.yaml b/packages/todo/tool-todo/README.i18n.yaml index 2899c17810..4121828f2e 100644 --- a/packages/todo/tool-todo/README.i18n.yaml +++ b/packages/todo/tool-todo/README.i18n.yaml @@ -69,8 +69,8 @@ en: 9717b983b6a857e3 zh: 611a2dadf7c0c706 /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/what-the-model-sees: - en: 05644654d1bce8c6 - zh: ea2a42470fbb2ee1 + en: 98dbd1d31d6179af + zh: cd899d7c4ab9f2be /deepseek-ai-dsh-tool-todo/model-experience/tool-call-history-and-result/token-effect: en: 7763a0e875faf53d zh: fe33c3973215dc53 diff --git a/packages/todo/tool-todo/README.md b/packages/todo/tool-todo/README.md index 1c31e14ddd..d08b26801a 100644 --- a/packages/todo/tool-todo/README.md +++ b/packages/todo/tool-todo/README.md @@ -135,7 +135,7 @@ Prefix-stable while the definition and visibility are unchanged. Plugin lifecycl #### What the model sees -Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are ``Error: invalid todo: `content` must be a non-empty string``, `Error: invalid todos: duplicate content ""`, `Error: todo_write requires an owning agent session`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid todos: at most one task may be in_progress (got )`. The full `todo/write` session event is UI and replay state, not a second model message. +Each assistant tool call retains the entire replacement list in its arguments. Success returns exactly `Updated todo list: pending, in progress, completed.` Stable failures are `Error: invalid arguments: todos[].content must be a non-empty string`, `Error: invalid arguments: todos[].content duplicates ""`, and — only where the deployment set `allowParallelInProgress: false` — `Error: invalid arguments: at most one task may be in_progress (got )`, all `ToolArgsError` `INVALID_ARGS`, plus `Error: todo_write requires an owning agent session` as `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE`. The full `todo/write` session event is UI and replay state, not a second model message. #### Token effect diff --git a/packages/todo/tool-todo/README.zh.md b/packages/todo/tool-todo/README.zh.md index 6ceae4cc3e..10ffd2f05f 100644 --- a/packages/todo/tool-todo/README.zh.md +++ b/packages/todo/tool-todo/README.zh.md @@ -135,7 +135,7 @@ agent 每次更新都发送完整列表;新列表替换旧列表,因此没 #### 模型看到什么 -每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 ``Error: invalid todo: `content` must be a non-empty string``、`Error: invalid todos: duplicate content ""`、`Error: todo_write requires an owning agent session`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid todos: at most one task may be in_progress (got )`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 +每次 assistant 工具调用都会在参数中保留整个替换列表。成功时原样返回 `Updated todo list: pending, in progress, completed.`。稳定失败文本为 `Error: invalid arguments: todos[].content must be a non-empty string`、`Error: invalid arguments: todos[].content duplicates ""`,以及——仅在部署设置 `allowParallelInProgress: false` 时——`Error: invalid arguments: at most one task may be in_progress (got )`,均为 `ToolArgsError` `INVALID_ARGS`;另有 `ToolContextUnavailableError` `TOOL_CONTEXT_UNAVAILABLE` 的 `Error: todo_write requires an owning agent session`。完整的 `todo/write` 会话事件是 UI 与回放状态,而非第二条模型消息。 #### Token 影响 diff --git a/packages/todo/tool-todo/src/index.ts b/packages/todo/tool-todo/src/index.ts index 0f59f7be17..53ac76ac86 100644 --- a/packages/todo/tool-todo/src/index.ts +++ b/packages/todo/tool-todo/src/index.ts @@ -9,7 +9,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { ZodType } from 'zod' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { TodoItem } from './types.ts' // Type-only: resolves the required ctx.sessionProjections service declaration. import type {} from '@deepseek-ai/dsh-session-projection' @@ -81,20 +81,20 @@ function toTodoList(raw: { content: string; status: string }[], allowParallel: b const todos: TodoItem[] = [] const seen = new Set() let active = 0 - for (const item of raw) { + for (const [index, item] of raw.entries()) { const content = item.content.trim() if (content.length === 0) { - throw new Error('invalid todo: `content` must be a non-empty string') + throw new ToolArgsError([`todos[${index}].content must be a non-empty string`]) } if (seen.has(content)) { - throw new Error(`invalid todos: duplicate content ${JSON.stringify(content)}`) + throw new ToolArgsError([`todos[${index}].content duplicates ${JSON.stringify(content)}`]) } seen.add(content) if (item.status === 'in_progress') active++ todos.push({ content, status: item.status as TodoItem['status'] }) } if (!allowParallel && active > 1) { - throw new Error(`invalid todos: at most one task may be in_progress (got ${active})`) + throw new ToolArgsError([`at most one task may be in_progress (got ${active})`]) } return todos } @@ -195,7 +195,7 @@ export async function apply(ctx: Context, config: Config): Promise { if (!exec.agent) { // The list is per-agent-session state; a non-agent caller (no owning // session) has nowhere to write it. Reject rather than silently no-op. - throw new Error('todo_write requires an owning agent session') + throw new ToolContextUnavailableError('todo_write requires an owning agent session') } exec.agent.session.append('todo/write', { todos }) const count = (status: TodoItem['status']): number => todos.filter(t => t.status === status).length diff --git a/packages/todo/tool-todo/tests/loader-composition.spec.ts b/packages/todo/tool-todo/tests/loader-composition.spec.ts index e6f39365b9..584d40c200 100644 --- a/packages/todo/tool-todo/tests/loader-composition.spec.ts +++ b/packages/todo/tool-todo/tests/loader-composition.spec.ts @@ -118,6 +118,7 @@ describe('tool-todo real Loader composition through cordis.yml', () => { }) expect(result.isError).toBe(true) expect(resultText(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(owner.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }, 30_000) diff --git a/packages/todo/tool-todo/tests/tool-todo.spec.ts b/packages/todo/tool-todo/tests/tool-todo.spec.ts index 1c8f49e221..01bfc8c638 100644 --- a/packages/todo/tool-todo/tests/tool-todo.spec.ts +++ b/packages/todo/tool-todo/tests/tool-todo.spec.ts @@ -157,6 +157,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: parallel }, { agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('at most one task may be in_progress') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) // A rejected call must not reach the durable log. expect(agent.session.snapshotEvents().some(e => e.type === 'todo/write')).toBe(false) }) @@ -198,6 +199,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos }) expect(result.isError).toBe(true) expect(text(result)).toContain(fragment) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a non-agent caller (the list has no owning session)', async () => { @@ -205,6 +207,7 @@ describe('dsh-tool-todo', () => { const result = await callTodo(ctx, { todos: [{ content: 'a', status: 'pending' }] }, { agent: undefined }) expect(result.isError).toBe(true) expect(text(result)).toContain('owning agent session') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('presents the call with a stable title and the list as raw input', async () => { From 5157e3205a8d7bb05387b5abfe6c1250ba9ee777 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:17 +0800 Subject: [PATCH 017/122] feat(user-questions): classify answerer failures and timed ask checks An answerer failure that is not a HarnessError now rejects with UserQuestionError PROVIDER_ERROR and keeps the original as cause, while a coded HarnessError keeps its name and code. The timed ask_user_question tool reports an invalid timeout as BAD_TIMEOUT, a repeated question id as the new DUPLICATE_QUESTION_ID, and a missing caller as CALLER_NOT_LIVE. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 8 ++++--- docs/subsystems/user-questions.zh.md | 8 ++++--- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tool-ask-user/README.i18n.yaml | 4 ++-- packages/interaction/tool-ask-user/README.md | 2 +- .../interaction/tool-ask-user/README.zh.md | 2 +- .../interaction/tool-ask-user/src/timed.ts | 10 +++++---- .../tool-ask-user/tests/tool-ask-user.spec.ts | 10 ++++++++- .../interaction/user-questions/src/index.ts | 9 +++++--- .../tests/user-questions.spec.ts | 21 +++++++++++-------- 11 files changed, 50 insertions(+), 30 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index 808a19468f..bacd251ef1 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: 5762b1498a426ab6 - zh: bb9987ec82103620 + en: eb0a4f94282f8c18 + zh: 92c41869431b120e diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index 2c86b22e1c..c87fe49f14 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index ad39e1004f..4dc465f750 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -286,8 +286,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..199ff2c9a5 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, or `DELEGATED_CALLER` when that live agent has subagent origin.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, diff --git a/packages/interaction/tool-ask-user/README.i18n.yaml b/packages/interaction/tool-ask-user/README.i18n.yaml index c065b0c79d..6bf59ccd8a 100644 --- a/packages/interaction/tool-ask-user/README.i18n.yaml +++ b/packages/interaction/tool-ask-user/README.i18n.yaml @@ -24,8 +24,8 @@ en: 3e4bc86d1d86eaab zh: 3c4c41666135f55d /deepseek-ai-dsh-tool-ask-user/use-this-package/when-the-call-fails: - en: c4ac3c584f900230 - zh: bd8d227f0637b8f1 + en: f18fe6f907ad9fe8 + zh: 5ea600e24c781522 /deepseek-ai-dsh-tool-ask-user/understand-the-implementation: en: e9b9d46be0b45ca2 zh: c02403486473cd80 diff --git a/packages/interaction/tool-ask-user/README.md b/packages/interaction/tool-ask-user/README.md index c479ab53ff..f2f4b18d90 100644 --- a/packages/interaction/tool-ask-user/README.md +++ b/packages/interaction/tool-ask-user/README.md @@ -71,7 +71,7 @@ For a finite timed call, `{ "pending": true, "callId": "…" }` means the foregr ### When the call fails -Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. +Legacy and `timeout: -1` calls wait for an answer or cancellation; without an accepting answerer, they return an error. A finite timed call without an answerer returns pending at its deadline. Cancellation and a caller that is not the exact live runtime root also return errors. A timed call rejects an out-of-range `timeout` with `BAD_TIMEOUT`, a repeated question id with `DUPLICATE_QUESTION_ID`, and a missing calling agent with `CALLER_NOT_LIVE`, all as `UserQuestionError`. A live child agent is rejected with `DELEGATED_CALLER` and must include the unresolved decision in its final result. ----- diff --git a/packages/interaction/tool-ask-user/README.zh.md b/packages/interaction/tool-ask-user/README.zh.md index 8c577cb40d..1f76d6ab68 100644 --- a/packages/interaction/tool-ask-user/README.zh.md +++ b/packages/interaction/tool-ask-user/README.zh.md @@ -71,7 +71,7 @@ kind: "package-reference" ### 调用何时失败 -Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 +Legacy 调用和 `timeout: -1` 调用会等待回答或取消;没有 answerer 接受时返回错误。有限时长的 timed 调用若没有 answerer,则在到期后返回 pending。取消调用,或调用方不是确切的存活运行时根时,也会返回错误。timed 调用会以 `BAD_TIMEOUT` 拒绝超出范围的 `timeout`,以 `DUPLICATE_QUESTION_ID` 拒绝重复的问题 id,以 `CALLER_NOT_LIVE` 拒绝缺少调用方 agent 的调用,均为 `UserQuestionError`。存活的子 agent 会以 `DELEGATED_CALLER` 被拒绝,必须在最终结果中包含尚未解决的决定。 ----- diff --git a/packages/interaction/tool-ask-user/src/timed.ts b/packages/interaction/tool-ask-user/src/timed.ts index 9f3260ddcd..c5f3c5c1a8 100644 --- a/packages/interaction/tool-ask-user/src/timed.ts +++ b/packages/interaction/tool-ask-user/src/timed.ts @@ -4,14 +4,14 @@ import type { Context } from '@deepseek-ai/cordis' import { defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools' -import { TIMED_WAIT_PARAMETER } from '@deepseek-ai/dsh-user-questions' +import { TIMED_WAIT_PARAMETER, UserQuestionError } from '@deepseek-ai/dsh-user-questions' import type { AskUserQuestionAnswer, AskUserQuestionRequestEvent, } from '@deepseek-ai/dsh-user-questions/types' function validateTimeout(timeout: number): number { if (timeout !== -1 && (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483)) { - throw new Error('timeout must be -1 or a positive integer up to 2147483 seconds') + throw new UserQuestionError('timeout must be -1 or a positive integer up to 2147483 seconds', 'BAD_TIMEOUT') } return timeout } @@ -19,7 +19,9 @@ function validateTimeout(timeout: number): number { function validateQuestionIds(questions: readonly { readonly id: string }[]): void { const ids = new Set() for (const question of questions) { - if (ids.has(question.id)) throw new Error(`question id ${JSON.stringify(question.id)} must be unique within this call`) + if (ids.has(question.id)) { + throw new UserQuestionError(`question id ${JSON.stringify(question.id)} must be unique within this call`, 'DUPLICATE_QUESTION_ID') + } ids.add(question.id) } } @@ -197,7 +199,7 @@ export function registerTimedAskUser(ctx: Context, timeout = 120): void { validateQuestionIds(args.questions) const request = questionRequest(args.questions, exec) if (timeout !== -1) { - if (exec.agent === undefined) throw new Error('timed questions require a live agent') + if (exec.agent === undefined) throw new UserQuestionError('timed questions require a live agent', 'CALLER_NOT_LIVE') const result = await ctx.userQuestions.askTimed({ ...request, agent: exec.agent }, exec.callId, timeout * 1000) return 'pending' in result ? { ...result, message: pendingNotice } : answerResult(result) } diff --git a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts index 122b03023b..30e2c4629f 100644 --- a/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts +++ b/packages/interaction/tool-ask-user/tests/tool-ask-user.spec.ts @@ -554,10 +554,16 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: timed questions require a live agent' }], + error: { info: { name: 'UserQuestionError', code: 'CALLER_NOT_LIVE' } }, }) }) - it.each([0, 1.5, 2_147_484])('rejects invalid timeout %s', async (timeout) => { + it.each([ + // The integer schema rejects a fraction before the tool body's range check. + { timeout: 0, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + { timeout: 1.5, info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + { timeout: 2_147_484, info: { name: 'UserQuestionError', code: 'BAD_TIMEOUT' } }, + ])('rejects invalid timeout $timeout', async ({ timeout, info }) => { const ctx = await setup({ mode: 'timed', timeout: -1 }) const result = await executeToolFixture(ctx, { @@ -570,6 +576,7 @@ describe('ask_user_question tool', () => { expect(result.isError).toBe(true) expect(result.content[0]).toMatchObject({ type: 'text' }) expect(result.content[0]?.type === 'text' ? result.content[0].text : '').toMatch(/timeout.*integer/i) + expect(result.error?.info).toEqual(info) }) it('rejects duplicate question ids before dispatching a timed call', async () => { @@ -590,6 +597,7 @@ describe('ask_user_question tool', () => { expect(result).toMatchObject({ isError: true, content: [{ type: 'text', text: 'Error: question id "scope" must be unique within this call' }], + error: { info: { name: 'UserQuestionError', code: 'DUPLICATE_QUESTION_ID' } }, }) expect(answerer).not.toHaveBeenCalled() }) diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 2804b9ca30..0242301291 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -285,8 +285,10 @@ export class UserQuestionService extends TypertRemoteService { * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent - * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent has subagent origin. + * is not the registry's exact live instance, `DELEGATED_CALLER` when + * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer + * fails with a value that is not a `HarnessError`; a coded `HarnessError` + * from an answerer keeps its `name` and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -356,7 +358,8 @@ export class UserQuestionService extends TypertRemoteService { if (request.signal?.aborted) { throw abortedQuestion(error) } - throw restored + if (restored instanceof HarnessError) throw restored + throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index b2097ba376..d76ade47db 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,7 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' @@ -178,14 +178,16 @@ describe('UserQuestionService', () => { name: 'UserQuestionError', })], ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('preserves %s from the provider', async (_label, rejection) => { + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) - await expect(ctx.userQuestions.ask({ + const failure = await ctx.userQuestions.ask({ questions: [{ id: 'confirm', question: 'Proceed?' }], - })).rejects.toBe(rejection) + }).then(() => undefined, (error: unknown) => error) + expect(failure).toBeInstanceOf(UserQuestionError) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -289,10 +291,10 @@ describe('UserQuestionService', () => { }) }) - it('preserves a provider rejection outside the UserQuestionError taxonomy', async () => { + it('preserves a coded provider rejection outside the UserQuestionError taxonomy', async () => { const ctx = new Context() await ctx.plugin(UserQuestionService) - const failure = new Error('provider failed') + const failure = new HarnessError('provider failed', 'PROVIDER_OFFLINE') registerAnswerer(ctx, { ask: () => Promise.reject(failure) }) await expect(ctx.userQuestions.ask({ @@ -568,14 +570,15 @@ describe('askTimed', () => { } }) - it('rethrows a provider failure that is not a question error', async () => { + it('classifies a provider failure that is not a question error as PROVIDER_ERROR', async () => { const ctx = await timedContext() const agent = liveAgent('timed-provider-crash') ctx.agents.enter(agent) - registerAnswerer(ctx, { ask: () => Promise.reject(new TypeError('provider crashed')) }) + const crash = new TypeError('provider crashed') + registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toThrow(TypeError) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) await ctx.fiber.dispose() }) From a2e31ad6f958f477d3a1073cfb068f3d9b201305 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:11:25 +0800 Subject: [PATCH 018/122] docs: regenerate catalogs for shifted source lines The config, persistence, and event producer-consumer catalogs record source line numbers that moved in the preceding error-code changes; no persisted type digest changed. Refs #7869 --- docs/config-catalog.md | 6 +++--- docs/config-catalog.zh.md | 6 +++--- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/persistence-catalog.i18n.yaml | 12 ++++++------ docs/persistence-catalog.md | 6 +++--- docs/persistence-catalog.zh.md | 6 +++--- docs/persistence-schema.json | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..a0eb5198ce 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2670,7 +2670,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4480,7 +4480,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4627,7 +4627,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..3d137345e3 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2672,7 +2672,7 @@ export interface Config { ## `@deepseek-ai/dsh-plan-mode` - `inject`: `tools` · `systemPrompt` · `sessionProjections` · `agents` -- `source`: [`packages/plan/plan-mode/src/index.ts:67`](../packages/plan/plan-mode/src/index.ts) +- `source`: [`packages/plan/plan-mode/src/index.ts:69`](../packages/plan/plan-mode/src/index.ts) ```ts config-catalog /** Deployment-owned plan guidance. */ @@ -4482,7 +4482,7 @@ export interface Config { - `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) -- `source`: [`packages/subagent/tool-subagent/src/index.ts:45`](../packages/subagent/tool-subagent/src/index.ts) +- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts) ```ts config-catalog /** Config: which registered provider this tool delegates to, plus child defaults. */ @@ -4629,7 +4629,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-workflow` - `inject`: `tools` · `workflowEngine` · `systemPrompt` -- `source`: [`packages/workflow/tool-workflow/src/index.ts:44`](../packages/workflow/tool-workflow/src/index.ts) +- `source`: [`packages/workflow/tool-workflow/src/index.ts:45`](../packages/workflow/tool-workflow/src/index.ts) ```ts config-catalog /** Config: the model-facing tool name plus result rendering caps. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..b610bfb030 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -53,7 +53,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `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`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..2d3999762a 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -55,7 +55,7 @@ | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | -| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | +| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:115`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `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`) | - | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index a5fb682b48..6929a9f050 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -153,8 +153,8 @@ en: 4294f78d26ed985b zh: 4294f78d26ed985b /session-persistence-event-catalog/events/plan/plan-mode-log-only: - en: 9ae5537eeae238de - zh: 6be761c7fd83fdce + en: bcc1f048e7a31f1e + zh: a9c29711722cd6c7 /session-persistence-event-catalog/events/request: en: a8df82440ebdf5f8 zh: a8df82440ebdf5f8 @@ -1227,8 +1227,8 @@ en: b45c7e8370d7be1e zh: 252fdc0ff2b9338c /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: - en: 9531468264499498 - zh: 9da23c0ad2776563 + en: 9815df505b8cd026 + zh: ce4f536eec979d77 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity~2: en: 13de8e35b749db45 zh: 01e4f3bcb6784fc8 @@ -1425,8 +1425,8 @@ en: a74e3dfa51c987af zh: 6c3c87974d7a7260 /session-persistence-event-catalog/resolved-persistence-types/active~2: - en: c861888d6239b700 - zh: a9b2271d3c6b8737 + en: 235f08eeb284a1a5 + zh: b6ebffbfd7b44a9b /session-persistence-event-catalog/resolved-persistence-types/agentpreset: en: 1282a0b3d5fa8d4d zh: aa533aea643dbefb diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6b80fbbc99..d75f7f9558 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -735,7 +735,7 @@ Source: [`packages/interaction/permission-presets/src/index.ts:53`](../packages/ 'plan/mode': { active: boolean } ``` -Source: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Source: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4779,7 +4779,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +Sources: [`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | Property | Presence | Type | |---|---|---| @@ -5870,7 +5870,7 @@ Array of `unknown` (opaque). SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -Sources: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +Sources: [`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c73b594c28..df1efe0f1e 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -737,7 +737,7 @@ export type SessionEvent = { 'plan/mode': { active: boolean } ``` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) ### `request/*` @@ -4781,7 +4781,7 @@ SHA-256: `bec5ca3a376f56f3d69df7f12a48e1cc07d4ea8305968773394c8734799faeb4` SHA-256: `07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235` -来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:9`](../packages/subagent/tool-subagent/src/model-selection.ts) +来源:[`packages/session/session-title/src/types.ts:20`](../packages/session/session-title/src/types.ts) · [`packages/subagent/tool-subagent/src/model-selection.ts:11`](../packages/subagent/tool-subagent/src/model-selection.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5872,7 +5872,7 @@ SHA-256: `b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7` SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` -来源:[`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/src/index.ts) +来源:[`packages/plan/plan-mode/src/index.ts:55`](../packages/plan/plan-mode/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 3a1b058f36..caf3ea2b15 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -80,7 +80,7 @@ {"digest":"05a2796621b1ee6c03ef7abe560b25116bb4da4d592312117242a78415a32b04","names":[],"sources":[]}, {"digest":"05d2ae1e0c7f8770f83f9a09047afb39a335d8ac986df3193659aa1e581472cf","names":["packages/interaction/user-approval/src/index.ts#ApprovalPolicy"],"sources":["packages/interaction/user-approval/src/index.ts:68"]}, {"digest":"0657d3ca5ac4e7bf79b00bcf860b1c7159d01a9da137497221ec2f1776e365f7","names":["packages/core/session/src/types.ts#SessionSeq"],"sources":["packages/core/session/src/types.ts:33"]}, - {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:9"]}, + {"digest":"07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235","names":["packages/session/session-title/src/types.ts#SessionTitleModelIdentity","packages/subagent/tool-subagent/src/model-selection.ts#AllowedModelRoute"],"sources":["packages/session/session-title/src/types.ts:20","packages/subagent/tool-subagent/src/model-selection.ts:11"]}, {"digest":"07eccc9ea2f9b5439d76cc77d5e062936677d43f07a23da749819b0a22ee36b7","names":[],"sources":[]}, {"digest":"09655b34d7f3cf1e9005974de2357de2d4a60deea165d16dac1eadaa6ec539a8","names":[],"sources":[]}, {"digest":"09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363","names":["packages/llm/llm/src/message.ts#SystemMessage"],"sources":["packages/llm/llm/src/message.ts:151"]}, @@ -155,7 +155,7 @@ {"digest":"1f1385dbc3e875c021e387c7096d671d606f22daec51b25c80348735b6bbfa10","names":[],"sources":[]}, {"digest":"1f8c126cfab3df812cd115cfc23e3256f0fa2383400f4ce91ecad313577e59b0","names":["packages/core/session/src/types.ts#TurnEndCancelCause"],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, - {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, + {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:55"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, From a528a6d33c7f0e25dfbe580a856e20b9f0a84a7b Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:16:20 +0800 Subject: [PATCH 019/122] feat(subagent): classify unavailable delegation presets A fresh delegation whose selected preset is unknown or cannot load received the registry's RemoteError, which is not a HarnessError, so the tool result had no error.code. applyChildComposition now converts that RemoteError into SubagentError PRESET_UNAVAILABLE, keeping its message and the original as cause. Restoration still propagates it so the manager reports NOT_RESUMABLE, and other mount failures are unchanged. Refs #7869 --- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/child-agent.ts | 13 ++++++++++--- .../subagent/tests/continuation-presets.spec.ts | 15 +++++++++++++++ .../tool-subagent/tests/preset-selection.spec.ts | 3 +++ 6 files changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index ceaac3229a..d89a9ce18b 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: f5393c65bf8ee460 - zh: d037d42bc967f17b + en: bdb3204a71ee2a8f + zh: 74d7d4e9eca20e2a /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index dcad891799..916c73346e 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index dfe7d1f835..8cc7e6bda9 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 9f4626641c..89b2a59447 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,6 +25,7 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -183,8 +184,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the - * child cannot join its creator's preset revision. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh + * delegation's preset is unknown or cannot load, or the child cannot join its creator's + * preset revision. Restoration propagates the registry's `RemoteError` unchanged. */ export function applyChildComposition( childCtx: Context, @@ -196,7 +198,12 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - return presets.mount(childCtx, composition.agentPreset).then(() => { + const mounted = presets.mount(childCtx, composition.agentPreset) + // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. + return (parent === undefined ? mounted : mounted.catch((error: unknown) => { + const failure = remoteErrorOf(error) + throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) + })).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 594be164ac..0cd3e0f69b 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -139,6 +139,21 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) + it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + const { ctx, parent, adapter } = await setup() + await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ + name: 'SubagentError', + code: 'PRESET_UNAVAILABLE', + message: 'Unknown agent preset: absent', + cause: { code: 'agent-preset/not-found' }, + }) + const failure = new Error('binding failed') + vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) + await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) + expect(adapter.requests).toEqual([]) + }) + it('rolls back an independent spawn when the preset service has unloaded', async () => { const { ctx, parent, adapter, presets } = await setup() await presets.dispose() diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 9bfa7e9e85..920697c323 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,6 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -179,6 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') + expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -363,6 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') + expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) From 80c3a3fe09365fdf62978c33ffda51b74beb5314 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 20:48:51 +0800 Subject: [PATCH 020/122] refactor(plan-mode): keep the code list off the plugin entry The plugin entry exports only the PlanModeError class and its code type; the code list stays module-local in src/error.ts, so the entry adds no value export that verify-plugin-entry-exports would reject. Refs #7869 --- packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index e0227893bb..38f98ee1d0 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -12,7 +12,7 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' * - `PLAN_REVIEW_INTERRUPTED`: the plan-mode service was reloaded during the review; present the plan again. * - `PLAN_REVISION_REQUESTED`: the user chose to keep planning; revise the plan from the feedback in `message`. */ -export const PLAN_MODE_ERROR_CODES = [ +const PLAN_MODE_ERROR_CODES = [ 'PLAN_NOT_ACTIVE', 'PLAN_REVIEW_INTERRUPTED', 'PLAN_REVISION_REQUESTED', diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 636165c5e3..685e060339 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -43,7 +43,7 @@ declare module '@deepseek-ai/dsh-llm' { } } export type * from './types.ts' -export { PLAN_MODE_ERROR_CODES, PlanModeError, type PlanModeErrorCode } from './error.ts' +export { PlanModeError, type PlanModeErrorCode } from './error.ts' declare module '@deepseek-ai/dsh-session/types' { interface SessionEventMap { From d212c0629af776d321e55dbdf021d8249c0cd0cb Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 21:55:52 +0800 Subject: [PATCH 021/122] refactor(plan-mode,user-questions): import HarnessError from dsh-error PlanModeError is the only base-class use this stack adds to plan-mode, so the package depends on the dependency-free dsh-error instead of reaching the base through dsh-llm; the user-questions test that builds a foreign HarnessError imports it from dsh-error as a dev dependency. Refs #7869 --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- packages/interaction/user-questions/package.json | 1 + .../interaction/user-questions/tests/user-questions.spec.ts | 3 ++- packages/plan/plan-mode/package.json | 2 ++ packages/plan/plan-mode/src/error.ts | 2 +- packages/plan/plan-mode/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 8 files changed, 19 insertions(+), 4 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..6913c9fca6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -910,6 +910,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1814,7 +1815,7 @@ flowchart TD | [`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) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`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) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..aa668a72c2 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -912,6 +912,7 @@ flowchart TD pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands + pkg_plan_mode --> pkg_error pkg_plan_mode --> pkg_llm pkg_plan_mode --> pkg_session pkg_plan_mode --> pkg_session_projection @@ -1816,7 +1817,7 @@ flowchart TD | [`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) | +| [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`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) | | [`compaction-image-offload`](../packages/compaction/compaction-image-offload) | `compaction` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/packages/interaction/user-questions/package.json b/packages/interaction/user-questions/package.json index 3eb448ad83..4665aa742d 100644 --- a/packages/interaction/user-questions/package.json +++ b/packages/interaction/user-questions/package.json @@ -60,6 +60,7 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index d76ade47db..a4f3208de1 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -7,7 +7,8 @@ import UserQuestionService, { type AskUserQuestionAnswer, type AskUserQuestionRequest, } from '@deepseek-ai/dsh-user-questions' -import { createToolResultMessage, createUserMessage, HarnessError, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { createToolResultMessage, createUserMessage, ToolCallId, type ToolSchema, type UserMessage } from '@deepseek-ai/dsh-llm' import { Session, SessionId, SESSION_FORMAT_VERSION, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' diff --git a/packages/plan/plan-mode/package.json b/packages/plan/plan-mode/package.json index b4685d4062..26a6273e2e 100644 --- a/packages/plan/plan-mode/package.json +++ b/packages/plan/plan-mode/package.json @@ -43,6 +43,7 @@ "peerDependencies": { "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", @@ -65,6 +66,7 @@ "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-ptc-runtime": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", diff --git a/packages/plan/plan-mode/src/error.ts b/packages/plan/plan-mode/src/error.ts index 38f98ee1d0..997eb5540e 100644 --- a/packages/plan/plan-mode/src/error.ts +++ b/packages/plan/plan-mode/src/error.ts @@ -4,7 +4,7 @@ * @module @deepseek-ai/dsh-plan-mode/error */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every machine-routable plan-mode failure: diff --git a/packages/plan/plan-mode/tsconfig.json b/packages/plan/plan-mode/tsconfig.json index f187853290..357509a9f0 100644 --- a/packages/plan/plan-mode/tsconfig.json +++ b/packages/plan/plan-mode/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../../util/error" + }, { "path": "../../core/tools" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..9d71501a7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13061,6 +13061,9 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -13905,6 +13908,9 @@ importers: '@deepseek-ai/dsh-commands': specifier: workspace:* version: link:../../interaction/commands + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm From fda29f726da9c2d23269d4a3638eef296a830f61 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:08 +0800 Subject: [PATCH 022/122] fix(user-questions): keep the answerer's message in PROVIDER_ERROR Wrapping a non-HarnessError answerer failure replaced its message with a generic sentence, so callers and the model lost the concrete reason, such as a closed connection. The PROVIDER_ERROR wrapper now keeps the original message and falls back to the generic sentence only for a value that is not an Error. Refs #7869 --- docs/subsystems/user-questions.i18n.yaml | 4 ++-- docs/subsystems/user-questions.md | 9 +++++---- docs/subsystems/user-questions.zh.md | 9 +++++---- packages/interaction/user-questions/src/index.ts | 10 ++++++---- .../user-questions/tests/user-questions.spec.ts | 12 ++++++------ packages/plan/plan-mode/tests/plan-mode.spec.ts | 2 +- 6 files changed, 25 insertions(+), 21 deletions(-) diff --git a/docs/subsystems/user-questions.i18n.yaml b/docs/subsystems/user-questions.i18n.yaml index bacd251ef1..483df1b1a4 100644 --- a/docs/subsystems/user-questions.i18n.yaml +++ b/docs/subsystems/user-questions.i18n.yaml @@ -24,5 +24,5 @@ en: 74fa698d4a115e80 zh: 4e9b03b5eab2ae5e /user-interaction/errors: - en: eb0a4f94282f8c18 - zh: 92c41869431b120e + en: 832b165cfa48839d + zh: 6989f734b373c1f9 diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index c87fe49f14..daf0db242a 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -209,7 +209,7 @@ After a Host restart, the Remote layer resumes the root agent when the Session r ## Errors -`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original as `cause`; another `HarnessError` keeps its own `name` and `code`. +`UserQuestionError` extends `HarnessError`, so `ctx.tools.execute()` preserves `{ name, code }` for model-facing tool failures such as `EMPTY_QUESTIONS`, `BAD_INTENT`, `NO_PROVIDER`, `ASK_ABORTED`, or UI-side cancellation. An answerer failure that is not a `HarnessError` becomes `PROVIDER_ERROR` with the original message and the original as `cause`; another `HarnessError` keeps its own `name` and `code`. ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index 4dc465f750..aeb1818584 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -209,7 +209,7 @@ Host 重启后,Session 重开时 Remote 层会恢复根 agent。之后的迟 ## 错误 -`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 +`UserQuestionError` 继承 `HarnessError`,因此 `ctx.tools.execute()` 会保留 `{ name, code }`,用于面向模型的工具失败,如 `EMPTY_QUESTIONS`、`BAD_INTENT`、`NO_PROVIDER`、`ASK_ABORTED` 或 UI 侧取消。不是 `HarnessError` 的应答方失败会变为 `PROVIDER_ERROR`,保留原 message,原错误作为 `cause`;其他 `HarnessError` 保留自身的 `name` 与 `code`。 ```ts type-equiv /** Stable error taxonomy for user-questions failures. */ @@ -287,9 +287,10 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/packages/interaction/user-questions/src/index.ts b/packages/interaction/user-questions/src/index.ts index 0242301291..5c850eeb54 100644 --- a/packages/interaction/user-questions/src/index.ts +++ b/packages/interaction/user-questions/src/index.ts @@ -286,9 +286,10 @@ export class UserQuestionService extends TypertRemoteService { * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, `DELEGATED_CALLER` when - * that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer - * fails with a value that is not a `HarnessError`; a coded `HarnessError` - * from an answerer keeps its `name` and `code`. + * that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the + * original message, when an answerer fails with a value that is not a + * `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` + * and `code`. */ async ask(request: AskUserQuestionRequest): Promise { if (request.signal?.aborted) { @@ -359,7 +360,8 @@ export class UserQuestionService extends TypertRemoteService { throw abortedQuestion(error) } if (restored instanceof HarnessError) throw restored - throw new UserQuestionError('the user-questions answerer failed before the user answered', 'PROVIDER_ERROR', { cause: error }) + const message = error instanceof Error ? error.message : 'the user-questions answerer failed before the user answered' + throw new UserQuestionError(message, 'PROVIDER_ERROR', { cause: error }) } } } diff --git a/packages/interaction/user-questions/tests/user-questions.spec.ts b/packages/interaction/user-questions/tests/user-questions.spec.ts index a4f3208de1..09a32fd961 100644 --- a/packages/interaction/user-questions/tests/user-questions.spec.ts +++ b/packages/interaction/user-questions/tests/user-questions.spec.ts @@ -174,12 +174,12 @@ describe('UserQuestionService', () => { }) it.each([ - ['an ordinary Error', new Error('provider failed')], + ['an ordinary Error', new Error('provider failed'), 'provider failed'], ['a namesake Error without a string code', Object.assign(new Error('provider failed'), { name: 'UserQuestionError', - })], - ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }], - ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection) => { + }), 'provider failed'], + ['a non-Error rejection', { name: 'UserQuestionError', code: 'ASK_CANCELLED' }, 'the user-questions answerer failed before the user answered'], + ])('classifies %s from the provider as PROVIDER_ERROR', async (_label, rejection, message) => { const ctx = new Context() await ctx.plugin(UserQuestionService) registerAnswerer(ctx, { ask: vi.fn().mockRejectedValue(rejection) }) @@ -188,7 +188,7 @@ describe('UserQuestionService', () => { questions: [{ id: 'confirm', question: 'Proceed?' }], }).then(() => undefined, (error: unknown) => error) expect(failure).toBeInstanceOf(UserQuestionError) - expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: rejection }) + expect(failure).toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message, cause: rejection }) }) it('rejects empty question batches before reaching the provider', async () => { @@ -579,7 +579,7 @@ describe('askTimed', () => { registerAnswerer(ctx, { ask: () => Promise.reject(crash) }) await expect(ctx.userQuestions.askTimed({ agent, questions: timedQuestions }, timedCallId, 120_000)) - .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', cause: crash }) + .rejects.toMatchObject({ name: 'UserQuestionError', code: 'PROVIDER_ERROR', message: 'provider crashed', cause: crash }) await ctx.fiber.dispose() }) diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 0ebe17cb31..b65e283886 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -1177,7 +1177,7 @@ describe('exit_plan_mode', () => { registerQuestionAnswerer(ctx, { ask: () => { throw new Error('review aborted') } }) const result = await callExit(ctx, agent) expect(result.isError).toBe(true) - expect(result.content).toEqual([{ type: 'text', text: 'Error: the user-questions answerer failed before the user answered' }]) + expect(result.content).toEqual([{ type: 'text', text: 'Error: review aborted' }]) expect(result.error?.info).toEqual({ name: 'UserQuestionError', code: 'PROVIDER_ERROR' }) expect(foldPlanMode(agent.session.snapshotEvents())).toBe(true) }) From 1440cf2fb97b6f393ae526a479958d631dcefaf6 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:10 +0800 Subject: [PATCH 023/122] test(subagent-dsh-sdk): expect ToolArgsError for effort-only delegation An effort-only route request now fails as ToolArgsError, whose message carries the "invalid arguments:" prefix; the production-profile e2e asserts that text and the recorded INVALID_ARGS identity. Refs #7869 --- .../subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts index b6d6e3d03f..bf7d3e394f 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/loader-composition.e2e.ts @@ -157,8 +157,9 @@ describe('SDK subagent routing and diagnostics through the production profile', expect(results[0]!.data.message.isError).toBe(true) expect(results[0]!.data.message.content).toEqual([{ type: 'text', - text: 'Error: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', + text: 'Error: invalid arguments: child LLM `reasoning_effort` requires both `provider` and `model`; supply both or omit all three fields', }]) + expect(results[0]!.data.error).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(events.some(event => event.type === 'subagent/catalog')).toBe(false) expect(existsSync(join(child.childHome, 'sessions'))).toBe(false) }, From de273ffe2d57d69dcd1aa327d8525421e00eab3d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:11 +0800 Subject: [PATCH 024/122] feat(typert): make RemoteError a HarnessError RemoteError extended plain Error because dsh-llm, which owned HarnessError, depends on dsh-typert-protocol. With HarnessError in the dependency-free dsh-error package, RemoteError now extends it and keeps its name, Remote code, details, and constructor, so a tool body that throws one records name RemoteError and its code on tool/result. An unknown or unloadable delegation preset therefore keeps the registry's agent-preset/not-found or agent-preset/invalid identity, and the subagent runtime no longer rewraps it as PRESET_UNAVAILABLE. Client bundles inline dsh-error with the protocol layer; no client code depends on HarnessError identity. Refs #7869 --- ...28-ctx-remote-failure-vocabulary.i18n.yaml | 4 ++-- ...026-08-28-ctx-remote-failure-vocabulary.md | 6 +++--- ...-08-28-ctx-remote-failure-vocabulary.zh.md | 6 +++--- docs/module-graph.md | 7 ++++--- docs/module-graph.zh.md | 7 ++++--- packages/client/tsdown.client.ts | 2 +- .../extensions/tool-cordis/src/api-catalog.ts | 8 ++++++-- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/package.json | 1 + packages/subagent/subagent/src/child-agent.ts | 14 ++++--------- .../tests/continuation-presets.spec.ts | 15 +++++--------- .../tests/preset-selection.spec.ts | 6 +++--- packages/typert/protocol/README.i18n.yaml | 4 ++-- packages/typert/protocol/README.md | 2 +- packages/typert/protocol/README.zh.md | 2 +- packages/typert/protocol/package.json | 6 ++++-- packages/typert/protocol/src/remote-error.ts | 12 ++++++----- .../protocol/tests/remote-error.spec.ts | 20 +++++++++++++++++++ packages/typert/protocol/tsconfig.json | 3 +++ pnpm-lock.yaml | 6 ++++++ 22 files changed, 84 insertions(+), 55 deletions(-) create mode 100644 packages/typert/protocol/tests/remote-error.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml index 2e76fba547..2589183c49 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.i18n.yaml @@ -9,8 +9,8 @@ en: 990d46f713fb6303 zh: 592cd6128a9640b1 /agent-note-one-remote-failure-vocabulary-for-ctx-remote/decision: - en: 120e2fb97ac765d8 - zh: 5d5f110db4a9b717 + en: b54b9d98a34eeaa1 + zh: ac8e3d493b554c2d /agent-note-one-remote-failure-vocabulary-for-ctx-remote/code-ownership: en: cc1d8b88f7349b77 zh: 70f010e3310e2667 diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md index 7238ae23b4..146a359889 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.md @@ -16,12 +16,12 @@ Fixed Host facts bypassed `ctx.remote` too: the Host home came from `(ctx.get('c ## Decision -`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a real `Error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. +`@deepseek-ai/dsh-typert-protocol` exports one failure class, `RemoteError`: a `HarnessError` from the dependency-free `@deepseek-ai/dsh-error` carrying readonly `code` and `details`, the structural marker `isDSHRemoteError`, and standard `ErrorOptions` (`cause` holds in-process only). The correspondence between codes and details lives in one merge-extensible `RemoteErrorDetailsMap`; `RemoteFailure` is the code-distributed union of instances, and `RemoteResult` keeps its shape. ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md index db0b2969bc..12b2ad4f8e 100644 --- a/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-28-ctx-remote-failure-vocabulary.zh.md @@ -16,12 +16,12 @@ Host 固定事实同样绕过了 `ctx.remote`:Host home 取自 `(ctx.get('conn ## Decision -`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个真 `Error`,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 +`@deepseek-ai/dsh-typert-protocol` 导出唯一的失败类 `RemoteError`:一个继承无依赖包 `@deepseek-ai/dsh-error` 中 `HarnessError` 的错误,带只读 `code` 与 `details`、结构标记 `isDSHRemoteError`,以及标准 `ErrorOptions`(`cause` 只在进程内有效)。码与 details 的对应关系收进一张 merge-extensible 的 `RemoteErrorDetailsMap`;`RemoteFailure` 是按码分布的实例 union,`RemoteResult` 形状不变。 ```text -export class RemoteError extends Error { +export class RemoteError extends HarnessError { readonly isDSHRemoteError: true = true - constructor(readonly code: Code, message: string, + constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions) } export type RemoteFailure = { [C in RemoteErrorCode]: RemoteError }[RemoteErrorCode] diff --git a/docs/module-graph.md b/docs/module-graph.md index 6913c9fca6..ef941e1c54 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -506,8 +506,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -553,6 +553,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1687,7 +1688,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1704,8 +1704,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`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) | @@ -1728,6 +1728,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`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) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index aa668a72c2..ff50815bc6 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -508,8 +508,8 @@ flowchart TD pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage pkg_subprocess --> pkg_http_proxy - pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry + pkg_typert_protocol --> pkg_error pkg_system_prompt --> pkg_llm pkg_system_prompt --> pkg_scope pkg_skill --> pkg_llm @@ -555,6 +555,7 @@ flowchart TD pkg_subprocess_local --> pkg_subprocess pkg_subprocess_local --> pkg_timeout pkg_otel --> pkg_session + pkg_remote_mock --> pkg_typert_protocol pkg_session_snapshot --> pkg_http_proxy pkg_session_snapshot --> pkg_session pkg_fs --> pkg_brand @@ -1689,7 +1690,6 @@ flowchart TD | [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | — | | [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — | | [`typert-generator`](../packages/typert/generator) | `typert` | — | -| [`typert-protocol`](../packages/typert/protocol) | `typert` | — | | [`typert-registry`](../packages/typert/registry) | `typert` | — | | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | @@ -1706,8 +1706,8 @@ flowchart TD | [`storage-json`](../packages/storage/storage-json) | `storage` | [`storage`](../packages/storage/storage) | | [`storage-sqlite`](../packages/storage/storage-sqlite) | `storage` | [`storage`](../packages/storage/storage) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`http-proxy`](../packages/util/http-proxy) | -| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`typert-loader`](../packages/typert/loader) | `typert` | [`typert-registry`](../packages/typert/registry) | +| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) | | [`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) | @@ -1730,6 +1730,7 @@ flowchart TD | [`settings`](../packages/settings/settings) | `settings` | [`brand`](../packages/util/brand), [`session`](../packages/core/session) | | [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) | +| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) | | [`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) | diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 7df6b6f529..592b634dfb 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 199ff2c9a5..4b650a2362 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4369,7 +4369,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Ask the scoped answerer waterfall and wait for the user\'s answer.\n\nWhen a caller supplies an agent, human interaction is valid only for the exact live instance of an ordinary Session. Explicit subagent origin rejects delegated callers; historical ordinary forks may retain parent metadata and still ask normally.', parameters: [{ name: 'request', description: 'Questions, owner agent, and abort signal.' }], returns: 'The answer chosen or typed by the human.', - throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR` when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], + throws: ['{UserQuestionError} code `ASK_ABORTED` when the supplied signal is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent is not the registry\'s exact live instance, `DELEGATED_CALLER` when that live agent has subagent origin, or `PROVIDER_ERROR`, keeping the original message, when an answerer fails with a value that is not a `HarnessError`; a coded `HarnessError` from an answerer keeps its `name` and `code`.'], }, ], }, @@ -6802,6 +6802,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'GrantRecord', declaration: 'export interface GrantRecord {\n readonly kind: \'grant\';\n readonly payload: unknown;\n}', }, + { + name: 'HarnessError', + declaration: 'export class HarnessError extends Error {\n readonly code: string;\n constructor(message: string, code: string, options?: ErrorOptions);\n}', + }, { name: 'HookBudget', declaration: 'export interface HookBudget {\n readonly ms: number;\n readonly remainingMs: number;\n}', @@ -8132,7 +8136,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'RemoteError', - declaration: 'export class RemoteError extends Error {\n readonly isDSHRemoteError: true;\n constructor(readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', + declaration: 'export class RemoteError extends HarnessError {\n readonly isDSHRemoteError: true;\n constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}', }, { name: 'RemoteErrorCode', diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index d89a9ce18b..01bc38e2e5 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -39,8 +39,8 @@ en: bf3175c2218a16dd zh: 4be9271efe71ddb7 /deepseek-ai-dsh-subagent/use-this-package/failure-and-recovery: - en: bdb3204a71ee2a8f - zh: 74d7d4e9eca20e2a + en: 4815c56bfcb844e9 + zh: 424c6133c4805a66 /deepseek-ai-dsh-subagent/understand-the-implementation: en: 74d91b364b23f88d zh: 19cc558105efe8df diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 916c73346e..6cac06daba 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -79,7 +79,7 @@ In-process spawn accepts an independent `agentPreset`; fork and external backend ### Failure and recovery -Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a fresh child whose selected preset is unknown or cannot load, or that cannot join its creator's preset revision, with `PRESET_UNAVAILABLE`, a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. +Starting without the `agents` service rejects with `CONTINUATION_UNAVAILABLE`; an available runtime rejects a missing or replaced parent with `UNAUTHORIZED`. Providers implementing neither execution method are rejected at registration with `UNSUPPORTED_CAPABILITY`; unsupported requested capabilities reject creation with the same code. If a provider is removed or replaced while directory resolution is pending, creation rejects with `PROVIDER_CHANGED` before invoking either provider; retry the delegation against the current registration. Every creation failure below is a `SubagentError`: a child beyond the requested depth rejects with the `SubagentDepthError` subclass and `DEPTH_EXCEEDED`, an invalid runtime `subagentDepth` with `INVALID_DEPTH`, a child that cannot join its creator's preset revision with `PRESET_UNAVAILABLE` (an unknown or unloadable selected preset keeps the registry's `RemoteError` code), a local child without the working-directory service with `WORKING_DIRECTORY_UNAVAILABLE`, and an out-of-process child whose cwd is relative or not enterable with `INVALID_CWD`. A cold target whose persisted descriptor is corrupt rejects with `NOT_RESUMABLE`, and `structured_output` called while input is pending fails with `STRUCTURED_OUTPUT_PENDING_INPUT`. The caller signal cancels only unpublished work; after publication, `dispose()` cancels the exact activation and waits for its resource cleanup. Creation descendants continue independently; hosts must await `drainDescendants([root])` before disposing the root handle to stop all members and await pending startup. `result` settles after teardown and notifications, carrying output, optional structured data, and a stop reason; capture failures reject it after teardown. Cleanup failures reject `dispose()` and mark the lifecycle end as failed; the result promise and parent notification retain the captured execution result. ----- diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index 8cc7e6bda9..1e8dbb6355 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -79,7 +79,7 @@ kind: "package-reference" ### 失败与恢复 -缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,所选 preset 未知或无法加载、或无法加入创建者 preset 版本的新建子代以 `PRESET_UNAVAILABLE` 拒绝,缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 +缺少 `agents` 服务时,启动请求以 `CONTINUATION_UNAVAILABLE` 拒绝;运行时可用但父级缺失或被替换时,以 `UNAUTHORIZED` 拒绝。未实现任何执行方法的提供方会在注册时以 `UNSUPPORTED_CAPABILITY` 被拒绝;请求不受支持的能力会以同一码使创建失败。如果等待目录解析期间提供方被移除或替换,创建会在调用任何一方之前以 `PROVIDER_CHANGED` 拒绝;调用方可根据当前注册重试委派。以下创建失败均为 `SubagentError`:超出请求深度的子代以 `SubagentDepthError` 子类和 `DEPTH_EXCEEDED` 拒绝,无效的运行时 `subagentDepth` 以 `INVALID_DEPTH` 拒绝,无法加入创建者 preset 版本的子代以 `PRESET_UNAVAILABLE` 拒绝(所选 preset 未知或无法加载时保留 registry 的 `RemoteError` code),缺少工作目录服务的本地子代以 `WORKING_DIRECTORY_UNAVAILABLE` 拒绝,cwd 为相对路径或不可进入的进程外子代以 `INVALID_CWD` 拒绝。持久化 descriptor 损坏的冷目标以 `NOT_RESUMABLE` 拒绝,有待处理输入时调用 `structured_output` 以 `STRUCTURED_OUTPUT_PENDING_INPUT` 失败。调用方信号仅取消尚未发布的工作;发布后通过 `dispose()` 取消该次 activation,并等待其资源清理完成。创建后代独立继续运行;宿主必须在释放根句柄前等待 `drainDescendants([root])`,以停止所有成员并等待正在启动的工作。`result` 在清理与通知结束后完成,携带输出、可选结构化数据与停止原因;结果捕获故障在清理后使其拒绝。清理失败使 `dispose()` 拒绝,并将生命周期结束事件标记为失败;结果 promise 与父级通知保留已捕获的执行结果。 ----- diff --git a/packages/subagent/subagent/package.json b/packages/subagent/subagent/package.json index 6bff46b9ee..7bfdb4194b 100644 --- a/packages/subagent/subagent/package.json +++ b/packages/subagent/subagent/package.json @@ -109,6 +109,7 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", diff --git a/packages/subagent/subagent/src/child-agent.ts b/packages/subagent/subagent/src/child-agent.ts index 89b2a59447..bbc669b363 100644 --- a/packages/subagent/subagent/src/child-agent.ts +++ b/packages/subagent/subagent/src/child-agent.ts @@ -25,7 +25,6 @@ import type {} from '@deepseek-ai/dsh-permission-presets' // keeps its model-facing rows on the host plane, where the child already sees // them through the tool registry's global layer. import type {} from '@deepseek-ai/dsh-agent-preset-registry' -import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import { delegationDepthOf } from './depth.ts' import { SubagentError } from './error.ts' @@ -184,9 +183,9 @@ export const SUBAGENT_DELEGATION_CONTEXT * @param parent - creator for fresh delegation; absent during target-only restoration. * @param composition - independent preset and any overrides read from a historical descriptor. * @returns A promise when mounting an independent preset; otherwise completes synchronously. - * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent, a fresh - * delegation's preset is unknown or cannot load, or the child cannot join its creator's - * preset revision. Restoration propagates the registry's `RemoteError` unchanged. + * @throws {SubagentError} `PRESET_UNAVAILABLE` when the preset service is absent or the + * child cannot join its creator's preset revision. An unknown or unloadable selected + * preset rejects with the registry's `RemoteError` code. */ export function applyChildComposition( childCtx: Context, @@ -198,12 +197,7 @@ export function applyChildComposition( if (presets === undefined) { throw new SubagentError('selecting a child agent preset requires the agent-presets service', 'PRESET_UNAVAILABLE') } - const mounted = presets.mount(childCtx, composition.agentPreset) - // Restoration leaves an unavailable preset to its caller's NOT_RESUMABLE classification. - return (parent === undefined ? mounted : mounted.catch((error: unknown) => { - const failure = remoteErrorOf(error) - throw failure === undefined ? error : new SubagentError(failure.message, 'PRESET_UNAVAILABLE', { cause: error }) - })).then(() => { + return presets.mount(childCtx, composition.agentPreset).then(() => { applyChildOverrides(childCtx, composition) }) } diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index 0cd3e0f69b..1dad8a15b1 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -13,6 +13,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry' +import { HarnessError } from '@deepseek-ai/dsh-error' import { createUserMessage } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -139,17 +140,11 @@ describe('child preset start validation', () => { expect(adapter.requests).toEqual([]) }) - it('classifies an unknown independent preset as PRESET_UNAVAILABLE and keeps other mount failures', async () => { + it('rejects an unknown independent preset with the registry RemoteError as a HarnessError', async () => { const { ctx, parent, adapter } = await setup() - await expect(ctx.subagents.startActivation(startSpec(parent, 'absent'))).rejects.toMatchObject({ - name: 'SubagentError', - code: 'PRESET_UNAVAILABLE', - message: 'Unknown agent preset: absent', - cause: { code: 'agent-preset/not-found' }, - }) - const failure = new Error('binding failed') - vi.spyOn(ctx.agentPresets, 'mount').mockRejectedValueOnce(failure) - await expect(ctx.subagents.startActivation(startSpec(parent, 'reviewing'))).rejects.toBe(failure) + const failure: unknown = await ctx.subagents.startActivation(startSpec(parent, 'absent')).catch((error: unknown) => error) + expect(failure).toBeInstanceOf(HarnessError) + expect(failure).toMatchObject({ name: 'RemoteError', code: 'agent-preset/not-found', message: 'Unknown agent preset: absent' }) expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id]) expect(adapter.requests).toEqual([]) }) diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index 920697c323..a29e780d36 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -162,7 +162,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('Unknown agent preset: absent') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -180,7 +180,7 @@ describe('spawn preset selection', () => { const result = await callSubagent(ctx, args, { agent: parent.agent }) expect(result.isError).toBe(true) expect(text(result)).toContain('missing-plugin') - expect(result.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(result.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/invalid' }) expect(ctx.agents.list()).toEqual([parent.agent]) expect(ctx.sessions.list()).toEqual(sessions) }) @@ -365,7 +365,7 @@ describe('spawn preset selection', () => { const failed = await callSubagent(ctx, args, { agent: handle.agent }) expect(failed.isError).toBe(true) expect(text(failed)).toContain('Unknown agent preset: later') - expect(failed.error?.info).toEqual({ name: 'SubagentError', code: 'PRESET_UNAVAILABLE' }) + expect(failed.error?.info).toEqual({ name: 'RemoteError', code: 'agent-preset/not-found' }) await ctx.agentPresets.register({ id: 'later', plugins: [] }) ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('reviewed')])) diff --git a/packages/typert/protocol/README.i18n.yaml b/packages/typert/protocol/README.i18n.yaml index 018aebf137..aebf5c816e 100644 --- a/packages/typert/protocol/README.i18n.yaml +++ b/packages/typert/protocol/README.i18n.yaml @@ -27,8 +27,8 @@ en: 3db384ae6f215632 zh: 56207184b09d4018 /deepseek-ai-dsh-typert-protocol/use-this-package/reporting-and-reading-a-remote-failure: - en: 4ba5266ddb014029 - zh: e31ae6438b9b4aa5 + en: 32d5fdd4b678d86c + zh: 00af91a97b891592 /deepseek-ai-dsh-typert-protocol/use-this-package/receiving-forwarded-host-events-on-the-client: en: 1101bd1d1419618c zh: 6ff036538d237e0a diff --git a/packages/typert/protocol/README.md b/packages/typert/protocol/README.md index 8613555bf7..c85039ab3e 100644 --- a/packages/typert/protocol/README.md +++ b/packages/typert/protocol/README.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. +An owner throws at the failure point; no package writes an error-class family or an exit-mapping function. A caller discriminates by `code` — never by `instanceof` — and a `code` branch narrows `details` with no cast, because `RemoteFailure` is the code-discriminated union of `RemoteError` instances. Infrastructure that must recognize a failure carried across a module or realm copy of the class calls `remoteErrorOf(value)`, which reads a structural marker instead of the prototype chain. `RemoteError` extends `HarnessError` from [`@deepseek-ai/dsh-error`](../../util/error/README.md), so a tool body that throws one records `name: 'RemoteError'` and its Remote `code` on `tool/result`. ### Receiving forwarded Host events on the Client diff --git a/packages/typert/protocol/README.zh.md b/packages/typert/protocol/README.zh.md index f02a8f5217..849a9c07be 100644 --- a/packages/typert/protocol/README.zh.md +++ b/packages/typert/protocol/README.zh.md @@ -81,7 +81,7 @@ declare module '@deepseek-ai/dsh-typert-protocol' { throw new RemoteError('goal/not-found', `goal "${id}" does not exist`, { goalId: id }) ``` -拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。 +拥有方在失败点直接抛出;没有任何包再写错误类家族或出口映射函数。调用方按 `code` 判别——绝不用 `instanceof`——且 `code` 分支无需 cast 即收窄 `details`,因为 `RemoteFailure` 就是 `RemoteError` 实例按码判别的 union。需要识别跨模块或跨 realm 类副本传来的失败时,基础设施调用 `remoteErrorOf(value)`,它读结构标记而不是原型链。`RemoteError` 继承 [`@deepseek-ai/dsh-error`](../../util/error/README.zh.md) 的 `HarnessError`,因此工具体抛出它时,`tool/result` 会记录 `name: 'RemoteError'` 及其 Remote `code`。 ### 在 Client 侧接收转发的 Host 事件 diff --git a/packages/typert/protocol/package.json b/packages/typert/protocol/package.json index 7fcc8f87f0..efb5f07aed 100644 --- a/packages/typert/protocol/package.json +++ b/packages/typert/protocol/package.json @@ -43,9 +43,11 @@ "zod": "4.6.6" }, "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/typert/protocol/src/remote-error.ts b/packages/typert/protocol/src/remote-error.ts index 90430a2093..476787eab9 100644 --- a/packages/typert/protocol/src/remote-error.ts +++ b/packages/typert/protocol/src/remote-error.ts @@ -1,15 +1,17 @@ /** The one Remote failure class shared by owners, the Gateway, and consumers. */ +import { HarnessError } from '@deepseek-ai/dsh-error' import type { RemoteErrorCode, RemoteErrorDetailsMap, RemoteFailure } from './types.ts' /** - * One Remote call failure: a real Error carrying its stable code and typed + * One Remote call failure: a `HarnessError` carrying its stable code and typed * details. Owners throw it at the failure point; the Host Gateway encodes it * onto the wire unchanged; the Client face rebuilds an instance for the * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. - * Discrimination is always by `code`, never by instanceof. + * A tool body that throws it records `name: 'RemoteError'` and its Remote code + * on `tool/result`. Discrimination is always by `code`, never by instanceof. */ -export class RemoteError extends Error { +export class RemoteError extends HarnessError { /** Structural marker: cross-realm/bundle identification never uses instanceof. */ readonly isDSHRemoteError: true = true @@ -20,12 +22,12 @@ export class RemoteError extends * @param options - standard Error options (`cause` survives in-process only). */ constructor( - readonly code: Code, + override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions, ) { - super(message, options) + super(message, code, options) this.name = 'RemoteError' } } diff --git a/packages/typert/protocol/tests/remote-error.spec.ts b/packages/typert/protocol/tests/remote-error.spec.ts new file mode 100644 index 0000000000..54c8388018 --- /dev/null +++ b/packages/typert/protocol/tests/remote-error.spec.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-error' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' + +describe('RemoteError', () => { + it('is a HarnessError that keeps its Remote code, details, and cause', () => { + const cause = new Error('backend closed') + const error = new RemoteError('gateway/bad-request', 'name is required', { issues: [{ path: ['name'] }] }, { cause }) + + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ + name: 'RemoteError', + code: 'gateway/bad-request', + message: 'name is required', + details: { issues: [{ path: ['name'] }] }, + cause, + }) + expect(remoteErrorOf(error)).toBe(error) + }) +}) diff --git a/packages/typert/protocol/tsconfig.json b/packages/typert/protocol/tsconfig.json index 342f636170..4f9fae2080 100644 --- a/packages/typert/protocol/tsconfig.json +++ b/packages/typert/protocol/tsconfig.json @@ -16,6 +16,9 @@ }, { "path": "../../util/brand" + }, + { + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9d71501a7c..29ea75b0e4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16442,6 +16442,9 @@ importers: '@deepseek-ai/dsh-attachment': specifier: workspace:* version: link:../../attachment/attachment + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs-sandbox': specifier: workspace:* version: link:../../fs/fs-sandbox @@ -17708,6 +17711,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error packages/typert/registry: dependencies: From 3aee25862d5d9b1681a15998cb9086c448a7224f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 18:15:52 +0800 Subject: [PATCH 025/122] ci(preview): link the snapshot diff page from the source chooser and harden it Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com> --- .github/preview-sizing/README.i18n.yaml | 4 +- .github/preview-sizing/README.md | 2 +- .github/preview-sizing/README.zh.md | 2 +- .../workflows/build-preview-cloudflare.yml | 36 ++- apps/web/tests/preview-boot.e2e.ts | 1 + .../experimental/webworker-packer/src/bin.ts | 1 + .../webworker-runtime/README.i18n.yaml | 4 +- .../experimental/webworker-runtime/README.md | 2 +- .../webworker-runtime/README.zh.md | 2 +- .../webworker-runtime/src/client/index.ts | 2 +- .../src/client/source-chooser.ts | 21 +- .../webworker-runtime/src/fixture-manifest.ts | 31 ++- .../webworker-runtime/src/index.ts | 2 +- .../tests/client/source-chooser.spec.ts | 26 ++ .../tests/fixture-manifest.spec.ts | 13 + scripts/preview-workflow.spec.ts | 15 +- scripts/snapshot-diff-page.spec.ts | 90 ++++--- scripts/snapshot-diff-page.ts | 229 ++++++++++++------ 18 files changed, 345 insertions(+), 138 deletions(-) diff --git a/.github/preview-sizing/README.i18n.yaml b/.github/preview-sizing/README.i18n.yaml index 065a63ad3e..2bb1cc7311 100644 --- a/.github/preview-sizing/README.i18n.yaml +++ b/.github/preview-sizing/README.i18n.yaml @@ -15,8 +15,8 @@ en: 2374f332d040ece2 zh: 7f914fb83cfb5caa /pr-preview-runner-sizing/publication-semantics: - en: 25ee2f4b26ef7770 - zh: 788b7fb4bee6e159 + en: 0d86702bcbbe23f4 + zh: cd0041c917ac8c55 /pr-preview-runner-sizing/dev-note: en: c3e8959997c4d5d0 zh: 109a391915c2bdfb diff --git a/.github/preview-sizing/README.md b/.github/preview-sizing/README.md index 5fcec8ad2c..fe47f0119e 100644 --- a/.github/preview-sizing/README.md +++ b/.github/preview-sizing/README.md @@ -26,7 +26,7 @@ A build-only benchmark does not deploy, access Cloudflare credentials, or post p ## Publication semantics -Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. +Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site and the snapshot diff page to the PR branch alias; that page embeds committed `snapshots/` diff text, never package sources. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines. diff --git a/.github/preview-sizing/README.zh.md b/.github/preview-sizing/README.zh.md index 43258d716a..36770bb7c5 100644 --- a/.github/preview-sizing/README.zh.md +++ b/.github/preview-sizing/README.zh.md @@ -26,7 +26,7 @@ ## 发布语义 -运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 +运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点和 snapshot diff 页面上传至 PR 分支别名;该页面嵌入已提交的 `snapshots/` diff 文本,不含包源码。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。 diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index c8cb718234..c9f60f3282 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -2,7 +2,8 @@ name: Build PR preview # Every push to a pull request publishes that pull request's preview to # Cloudflare Pages under its own branch alias, behind Cloudflare Access. The -# upload carries build products only: the workflow never grants the deployment +# upload carries build products plus the snapshot diff page, which embeds +# committed `snapshots/` diff text: the workflow never grants the deployment # platform access to this repository's sources. This lane also owns the # aggregate test and script type checks that the required Linux consumers no # longer repeat on every pull request. @@ -102,9 +103,16 @@ jobs: cp apps/web/dist/preview.html apps/web/dist/index.html # Reviewers read snapshot changes at /snapshot-diff/, which opens on the - # SDK blank-Session catalog (system prompt and tool schemas). + # SDK blank-Session catalog (system prompt and tool schemas); the source + # chooser links to it. The page serves review only, so a failure warns + # like publication instead of failing the build. - name: Render the snapshot diff page - run: pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html + id: snapshot-diff + continue-on-error: true + run: >- + pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD + --out apps/web/dist/snapshot-diff/index.html + --preview-manifest apps/web/dist/preview/fixtures.json - name: Upload to Cloudflare Pages id: upload @@ -180,29 +188,33 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR: ${{ github.event.pull_request.number }} + SNAPSHOT_DIFF: ${{ steps.snapshot-diff.outcome }} run: | marker='' url="https://pr-$PR.${CF_PROJECT}.pages.dev" + links="[Preview for #$PR]($url)" + if [ "$SNAPSHOT_DIFF" = success ]; then links="$links · [snapshot changes]($url/snapshot-diff/)"; fi # The marker sits on its own line: markdown renders no link on a # line that opens with a raw HTML comment. - body=$(printf '%s\n\n%s\n' \ - "$marker" \ - "[Preview for #$PR]($url) · [snapshot changes]($url/snapshot-diff/) (requires Cloudflare Access sign-in)") + body=$(printf '%s\n\n%s\n' "$marker" "$links (requires Cloudflare Access sign-in)") existing=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate \ - --jq "[.[] | select(.body | contains(\"$marker\"))] | first // empty | [.id, .body] | @json") + --jq "[.[] | select(.user.login == \"github-actions[bot]\" and (.body | contains(\"$marker\")))] | first // empty | [.id, .body] | @json") if [ -z "$existing" ]; then - printf '%s\n' "$body" | gh pr comment "$PR" --body-file - + printf '%s' "$body" | gh pr comment "$PR" --body-file - elif [ "$(jq -r '.[1]' <<< "$existing")" != "$body" ]; then gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$(jq -r '.[0]' <<< "$existing")" -f body="$body" > /dev/null else echo "preview URL already commented" fi - # Publishing stays outside the required verdict: a Cloudflare, Access, or - # comment failure warns, while a build failure still fails this check. + # Publishing stays outside the required verdict: a snapshot diff page, + # Cloudflare, Access, or comment failure warns, while a build failure + # still fails this check. - name: Report preview publication failures - if: steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' + if: >- + steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure' + || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure' run: | - message='preview publication failed; the build passed, see the upload, verify, and comment steps' + message='preview publication failed; the build passed, see the snapshot diff, upload, verify, and comment steps' echo "::warning::$message" echo "$message" >> "$GITHUB_STEP_SUMMARY" diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f1ea40b25c..70542e08d3 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -200,6 +200,7 @@ function requireVfsAssets(): PreviewAssets { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeAsset(`preview/${PREVIEW_FIXTURE_MANIFEST_FILE}`, `${JSON.stringify(fixtureManifest, null, 2)}\n`) return { overrides, manifest, cleanup: () => { rmSync(directory, { recursive: true, force: true }) } } diff --git a/packages/experimental/webworker-packer/src/bin.ts b/packages/experimental/webworker-packer/src/bin.ts index 18bf398e59..202b382724 100644 --- a/packages/experimental/webworker-packer/src/bin.ts +++ b/packages/experimental/webworker-packer/src/bin.ts @@ -80,6 +80,7 @@ const manifest: PreviewFixtureManifest = { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture: fixtures[0]?.id ?? null, fixtures, + links: [], } writeFileSync( join(dirname(outputFile), PREVIEW_FIXTURE_MANIFEST_FILE), diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index 68deb797c2..c4578dcd12 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-runtime/use-this-package: - en: 9f4c76d6c4391037 - zh: c55611045f4667e2 + en: 33c27e81e1e6212c + zh: 6e32be50142bdb44 /deepseek-ai-dsh-experimental-webworker-runtime/model-experience: en: 61fce9b4c7dc96e6 zh: dc2d931063a38327 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index e2bd1605ef..eeae07447e 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -31,7 +31,7 @@ Three build artifacts and one source-owned process layer: - **Lazy archives** — the manifest registers each page chunk the packer moved out of the base image by path and size, with its archive name relative to the image URL. Existence, stats, and listings answer at once; the first asynchronous read (`fs.promises.readFile`, `fs.promises.open`, `fs.createReadStream`, `fs.promises.cp`) fetches and inflates that archive once for every waiting reader, checks it against the registration, and mounts its files without publishing a mutation. A failed fetch rejects the read and leaves the files registered, so the next read fetches again. Until then, synchronous reads, writes, appends, truncation, chmod, rename, and link of a registered file fail with `ERR_DSH_VFS_DEFERRED` naming the archive; unlink and recursive removal drop the registration, and seeding the path replaces it. The archive name derives from its content digest, and the fetch checks only the registered paths and sizes, not the digest. An image that registers lazy archives must be passed as a URL. - **`lib/worker.js` (worker bundle)** — the assembly plus this package's Node-compatibility layer as one self-contained ES module. The module proxy table (`module-proxies.ts`) is the only platform fork: `node:*` builtins over VFS/tunnel/browser primitives, structural stubs that fail loud on the console for what a browser cannot do, and native/binary package replacements. `node:module` supplies `createRequire().resolve` and `.resolve.paths()` over the image package root, so unchanged packages can discover manifests without evaluating their modules. `node-addon-require-builtin` answers the Node v24.18.0 internal modules that the vendored Loader, app-boot, and HMR read without `--expose-internals`: the cascaded ESM loader's `resolveSync` and `import` over the Worker loader, with Node's `ERR_MODULE_NOT_FOUND` and `ERR_PACKAGE_PATH_NOT_EXPORTED` codes, and an empty `loadCache`; and the CommonJS loader, package reader, `modules` binding, and resolve-cache members that HMR replaces, which refuse when called. `process.versions.node` reports `24.18.0`, so `ModuleLoader.fromInternal()` and the Loader's `internal` reach that cascaded loader. `node:path.win32.isAbsolute` and `node:util.inherits` follow Node; other `win32` members throw. The `node:util` JSON-data comparator compares own enumerable properties, preserving Node admission decisions for recorded fields such as `__proto__`. The global `process` shim carries Node detection fields including `title`, preventing Worker execution from entering DOM-only branches; Node’s `global` alias references the same `globalThis` object for image-loaded packages. The pack-time parser reports statically named module requests, including module-scope direct calls of the form `createRequire(import.meta.url)('pkg')` through a named `node:module` or `module` import, to the packer's reachability walk. Stored, CommonJS-obtained, and rebased `createRequire` calls require image entry seeds. Lowered bodies read named and default imports through the required module object at each reference, so a module in an import cycle observes a binding once the exporting module initializes it; in a module with such imports, an assignment to an imported binding, a direct `eval`, and a declaration using the reserved `__dsh$` prefix fail the pack. VFS mutations drive `node:fs` callback, polling, and promise watchers, whose listeners run in the async context where the watcher was created rather than that of the writing code; open descriptors retain file identity and access mode across rename, replacement, and unlink, `FileHandle.stat({ bigint: true })` reports the same device and inode identity as a path stat while the name still refers to that file, and `FileHandle.chmod()` updates the opened file identity; `readable-stream` supplies `node:stream/promises` completion and pipeline helpers and the stream state machine used by file streams and unchanged image packages such as Chokidar and readdirp. The maintained `string_decoder` package supplies `node:string_decoder`, retaining incomplete multibyte characters between chunks. AsyncLocalStorage carries sync-stack causality across `await` through the snapshot/restore faces the pack-time lowering injects. The worker holds no compiler: an image the packer did not lower is refused at mount. The callback `fs.realpath.native` alias resolves within the mounted VFS and supports `util.promisify`. - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. -- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. +- **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. The manifest's optional `links` list of relative URLs renders beside the start button; the PR preview workflow adds one for its snapshot diff page. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. Before the shell entry runs, the page reads `GET /__assets__`, which the tunnel answers with an uncompressed tar of every package asset in the image, and supplies `resolveAsset`, which maps each `plugins//assets/` reference a bundle passes to `require.asset` to a Blob URL of those bytes. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. Callbacks and timers registered under an explicit root context retain its empty stores, so they cannot inherit an unrelated transaction. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index b666c692d8..b09bc78a5b 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -31,7 +31,7 @@ kind: "package-library" - **懒加载归档**——manifest 按路径和大小登记 packer 移出基础镜像的每个页面 chunk,并给出相对镜像 URL 的归档名。存在性、stat 和目录列表立即作答;第一次异步读取(`fs.promises.readFile`、`fs.promises.open`、`fs.createReadStream`、`fs.promises.cp`)为所有等待中的读取方只拉取并解压一次该归档,按登记内容校验后挂载其文件,不发布 mutation。拉取失败时本次读取被拒绝,文件保持登记状态,下次读取会重新拉取。在此之前,对已登记文件的同步读取、写入、追加、截断、chmod、rename 和 link 会以 `ERR_DSH_VFS_DEFERRED` 失败,错误中写明归档名;unlink 和递归删除会移除登记,再次 seed 该路径会替换登记。归档名由内容摘要派生,拉取时只校验登记的路径和大小,不校验摘要。登记了懒加载归档的镜像必须以 URL 传入。 - **`lib/worker.js`(worker 束)**——装配库加本包的 Node 兼容层,合成一个自含 ES module。模块代理表(`module-proxies.ts`)是唯一平台叉口:`node:*` 内建走 VFS、隧道和浏览器原语,浏览器做不到的走结构化 stub(调用即在 console 报错并抛出),native/binary 包则替换执行后端。`node:module` 在镜像 package 根之上提供 `createRequire().resolve` 与 `.resolve.paths()`,使未修改的包无需执行目标模块即可发现 manifest。`node-addon-require-builtin` 应答 vendor Loader、app-boot 和 HMR 在没有 `--expose-internals` 时读取的 Node v24.18.0 internal 模块:cascaded ESM loader 的 `resolveSync` 和 `import` 经 Worker 加载器完成,失败时带 Node 的 `ERR_MODULE_NOT_FOUND` 与 `ERR_PACKAGE_PATH_NOT_EXPORTED` 错误码,`loadCache` 为空;HMR 会替换的 CommonJS loader、package reader、`modules` binding 与 resolve cache 成员被调用时拒绝。`process.versions.node` 报告 `24.18.0`,因此 `ModuleLoader.fromInternal()` 和 Loader 的 `internal` 拿到的是这个 cascaded loader。`node:path.win32.isAbsolute` 与 `node:util.inherits` 与 Node 一致,其余 `win32` 成员抛出。`node:util` 的 JSON 数据比较器检查可枚举的自有属性,使 `__proto__` 等记录字段的准入判定与 Node 一致。全局 `process` shim 带有包括 `title` 在内的 Node 环境识别字段,避免 Worker 执行误入仅适用于 DOM 的分支;镜像中加载的包通过 Node 的 `global` 别名访问同一个 `globalThis` 对象。pack 期解析器会把名称静态可知的模块请求报告给 packer 的可达性遍历,其中包括通过 `node:module` 或 `module` 具名导入在模块作用域直接发起的 `createRequire(import.meta.url)('pkg')` 调用。保存、经 CommonJS 获取或另设基准的 `createRequire` 调用需要镜像入口种子。降低后的模块体在每次引用具名导入与 default 导入时,都经所 require 的模块对象读取,因此循环导入中的模块能在导出方完成初始化后读到该绑定;在含此类导入的模块中,对导入绑定赋值、直接调用 `eval`、声明使用保留前缀 `__dsh$` 的名字,都会使 pack 失败。VFS mutation 驱动 `node:fs` 的 callback、polling 和 promise watcher,监听回调运行在创建 watcher 时的异步上下文中,而不是写入方代码的上下文中;打开的 descriptor 在 rename、replacement 和 unlink 后仍保留文件身份与访问模式,只要文件名仍指向该文件,`FileHandle.stat({ bigint: true })` 报告的 device 与 inode 身份就与路径 stat 相同,`FileHandle.chmod()` 则更新打开文件身份的权限;`readable-stream` 提供 `node:stream/promises` 的完成等待与管道方法,以及文件流以及 Chokidar、readdirp 等未修改镜像包所用的流状态机。维护中的 `string_decoder` 包提供 `node:string_decoder`,在数据块之间保留不完整的多字节字符。AsyncLocalStorage 经 pack 时降低注入的 snapshot/restore 面在 `await` 间携带同步栈因果。worker 不带编译器:packer 未降低的镜像在挂载时被拒。回调式 `fs.realpath.native` 别名在已挂载的 VFS 内解析路径,并支持 `util.promisify`。 - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 -- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 +- **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。manifest 中可选的 `links` 列表只接受相对 URL,显示在开始按钮旁;PR 预览工作流为它的 snapshot diff 页面加了一条。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。在 shell 入口运行之前,页面读取 `GET /__assets__`(隧道以镜像中所有包资源组成的未压缩 tar 回答),并提供 `resolveAsset`,把 bundle 传给 `require.asset` 的每个 `plugins//assets/` 引用映射为这些字节的 Blob URL。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 在显式根上下文中登记的回调和定时器保留其空 store,避免继承无关事务。 diff --git a/packages/experimental/webworker-runtime/src/client/index.ts b/packages/experimental/webworker-runtime/src/client/index.ts index ab44c85d10..7366a56412 100644 --- a/packages/experimental/webworker-runtime/src/client/index.ts +++ b/packages/experimental/webworker-runtime/src/client/index.ts @@ -20,7 +20,7 @@ export { applyIndexInjections } from './apply-injections.ts' export { IMAGE_FILE_NAME } from '../image-layout.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from '../fixture-manifest.ts' /** Transport global the connection plugin reads instead of building an HTTP carrier. */ diff --git a/packages/experimental/webworker-runtime/src/client/source-chooser.ts b/packages/experimental/webworker-runtime/src/client/source-chooser.ts index 48d454eb94..95752bb84d 100644 --- a/packages/experimental/webworker-runtime/src/client/source-chooser.ts +++ b/packages/experimental/webworker-runtime/src/client/source-chooser.ts @@ -113,11 +113,23 @@ const CHOOSER_STYLE = ` font-size: 14px; line-height: 24px; } + [data-preview-source-footer] { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px 16px; + margin: 24px 0 0; + } + [data-preview-source-link] { + color: #61666b; + text-underline-offset: 3px; + } + [data-preview-source-link]:hover { color: #0f1115; } [data-preview-source-submit] { display: block; min-width: 120px; height: 36px; - margin: 24px 0 0 auto; + margin: 0 0 0 auto; padding: 0 14px; border: 0; border-radius: 18px; @@ -148,6 +160,8 @@ const CHOOSER_STYLE = ` [data-preview-source-option]:has(input:checked) { background: rgb(255 255 255 / 8%); } [data-preview-source-option]:has(input:checked) { border-color: rgb(255 255 255 / 12%); } [data-preview-source-option] input { accent-color: #f9fafb; } + [data-preview-source-link] { color: #cfd3d6; } + [data-preview-source-link]:hover { color: #f9fafb; } [data-preview-source-submit] { color: #0f1115; background: #f9fafb; } [data-preview-source-submit]:hover:not(:disabled) { background: #ebeef2; } [data-preview-source-submit]:focus-visible { outline-color: rgb(255 255 255 / 20%); } @@ -243,7 +257,10 @@ export async function choosePreviewSource(manifestUrl: URL): PromiseFilesystem source ${choices.map(choice => optionMarkup(choice, selected)).join('')} - +
+ ${manifest.links.map(link => `${escapeMarkup(link.label)}`).join('')} + +
` root.prepend(chooser) const form = chooser.querySelector('[data-preview-source-card]') diff --git a/packages/experimental/webworker-runtime/src/fixture-manifest.ts b/packages/experimental/webworker-runtime/src/fixture-manifest.ts index 7d2ecf2556..6d7804f727 100644 --- a/packages/experimental/webworker-runtime/src/fixture-manifest.ts +++ b/packages/experimental/webworker-runtime/src/fixture-manifest.ts @@ -14,12 +14,39 @@ export interface PreviewFixtureManifestEntry { readonly overlays: readonly string[] } +/** A page the source chooser links to, such as a report published beside the Preview. */ +export interface PreviewLink { + readonly label: string + /** URL resolved against the manifest URL; one that resolves to another origin is rejected. */ + readonly href: string +} + /** Complete built-in fixture catalog consumed before Worker startup. */ export interface PreviewFixtureManifest { readonly version: number /** Required default fixture id, or null when the chooser should default to an empty overlay. */ readonly defaultFixture: string | null readonly fixtures: readonly PreviewFixtureManifestEntry[] + /** Links shown on the source chooser; the parser reads an absent list as empty. */ + readonly links: readonly PreviewLink[] +} + +/** Resolving against this base shows whether an href could leave the manifest's origin. */ +const SAME_ORIGIN_PROBE = new URL('https://preview.invalid/') + +function parseLinks(value: unknown): PreviewLink[] { + if (value === undefined) return [] + if (!Array.isArray(value)) throw new Error('preview fixture manifest links must be an array') + return value.map((item) => { + const link = recordOf(item) + const label = link?.label + const href = link?.href + if (typeof label !== 'string' || label.length === 0 + || typeof href !== 'string' || href.length === 0 || new URL(href, SAME_ORIGIN_PROBE).origin !== SAME_ORIGIN_PROBE.origin) { + throw new Error('preview fixture manifest contains an invalid link') + } + return { label, href } + }) } function recordOf(value: unknown): Record | undefined { @@ -31,7 +58,7 @@ function recordOf(value: unknown): Record | undefined { /** * Validate the static fixture catalog before it controls Worker fetches. * @param value - Parsed JSON response. - * @returns A detached manifest with unique ids and non-empty overlay lists. + * @returns A detached manifest with unique ids, non-empty overlay lists, and relative links. */ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManifest { const record = recordOf(value) @@ -64,5 +91,5 @@ export function parsePreviewFixtureManifest(value: unknown): PreviewFixtureManif if (defaultFixture !== null && (typeof defaultFixture !== 'string' || !ids.has(defaultFixture))) { throw new Error('preview fixture manifest defaultFixture does not name a fixture') } - return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures } + return { version: PREVIEW_FIXTURE_MANIFEST_VERSION, defaultFixture, fixtures, links: parseLinks(record.links) } } diff --git a/packages/experimental/webworker-runtime/src/index.ts b/packages/experimental/webworker-runtime/src/index.ts index c8d8907d3a..788120c22d 100644 --- a/packages/experimental/webworker-runtime/src/index.ts +++ b/packages/experimental/webworker-runtime/src/index.ts @@ -43,7 +43,7 @@ export { } from './image-manifest.ts' export { parsePreviewFixtureManifest, PREVIEW_FIXTURE_MANIFEST_FILE, PREVIEW_FIXTURE_MANIFEST_VERSION, - type PreviewFixtureManifest, type PreviewFixtureManifestEntry, + type PreviewFixtureManifest, type PreviewFixtureManifestEntry, type PreviewLink, } from './fixture-manifest.ts' export { loadVfsImage, loadVfsOverlay, MemoryVfs } from './storage/memory.ts' export { inflateImage, inflateImageStream } from './storage/image-gzip.ts' diff --git a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts index f636c32ebe..14ded4eea2 100644 --- a/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts +++ b/packages/experimental/webworker-runtime/tests/client/source-chooser.spec.ts @@ -15,6 +15,7 @@ const MANIFEST: PreviewFixtureManifest = { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], } function setLocation(search = ''): void { @@ -108,6 +109,31 @@ describe('Preview source chooser', () => { expect(document.querySelector('[data-preview-source-style]')).toBeNull() }) + it('shows manifest links resolved against the manifest URL', async () => { + installManifest({ ...MANIFEST, links: [{ label: 'Snapshot ', href: '../snapshot-diff/' }] }) + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-link]')).not.toBeNull() + }) + const link = document.querySelector('[data-preview-source-link]') + expect([link?.textContent, link?.href]).toEqual(['Snapshot ', 'https://preview.test/snapshot-diff/']) + submitChooser() + await selected + }) + + it('shows no link when the manifest has none', async () => { + installManifest() + + const selected = choosePreviewSource(MANIFEST_URL) + await vi.waitFor(() => { + expect(document.querySelector('[data-preview-source-chooser]')).not.toBeNull() + }) + expect(document.querySelector('[data-preview-source-link]')).toBeNull() + submitChooser() + await selected + }) + it('selects the empty source when the manifest has no default', async () => { installManifest({ ...MANIFEST, defaultFixture: null }) diff --git a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts index 01b3d00e9a..804f0e7dbd 100644 --- a/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts +++ b/packages/experimental/webworker-runtime/tests/fixture-manifest.spec.ts @@ -23,9 +23,20 @@ describe('Preview fixture manifest', () => { description: 'A deterministic example.', overlays: ['fixtures/base.tar.gz', 'fixtures/tail.tar.gz'], }], + links: [], }) }) + it('accepts relative links', () => { + const links = [{ label: 'Snapshot changes', href: '../snapshot-diff/' }, { label: 'Root', href: '/report/' }] + expect(parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links }).links).toEqual(links) + }) + + it.each(['https://example.test/', 'javascript:alert(1)', '//example.test/', '\\\\example.test/', '', ' //evil.test/x', '/\t/evil.test/x', '\njavascript:alert(1)'])('rejects the link href %j', (href) => { + expect(() => parsePreviewFixtureManifest({ version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'L', href }] })) + .toThrow(/invalid link/) + }) + it.each([ [{ version: 2, defaultFixture: null, fixtures: [] }, /must use version/], [{ version: 1, defaultFixture: 'missing', fixtures: [] }, /defaultFixture/], @@ -42,6 +53,8 @@ describe('Preview fixture manifest', () => { defaultFixture: 'none', fixtures: [{ id: 'none', label: 'None', description: 'Reserved.', overlays: ['none.tar.gz'] }], }, /invalid fixture entry/], + [{ version: 1, defaultFixture: null, fixtures: [], links: {} }, /links must be an array/], + [{ version: 1, defaultFixture: null, fixtures: [], links: [{ label: '', href: 'a/' }] }, /invalid link/], ])('rejects malformed catalogs', (value, error) => { expect(() => parsePreviewFixtureManifest(value)).toThrow(error) }) diff --git a/scripts/preview-workflow.spec.ts b/scripts/preview-workflow.spec.ts index bd21bc2c0a..b7c851c3eb 100644 --- a/scripts/preview-workflow.spec.ts +++ b/scripts/preview-workflow.spec.ts @@ -30,14 +30,15 @@ describe('PR preview workflow', () => { it('fails the check only for build failures and warns about publication', () => { const byName = (name: string) => preview.steps.find(step => step.name === name) - for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload', 'Render the snapshot diff page']) { + for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) { expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined() } - for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { + for (const name of ['Render the snapshot diff page', 'Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) { expect(byName(name)?.['continue-on-error'], `${name} must warn instead of failing`).toBe(true) } const report = byName('Report preview publication failures') - expect(report?.if).toBe("steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") + expect(report?.if).toBe("steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'" + + " || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'") expect(report?.run).toContain('::warning::') }) @@ -78,15 +79,19 @@ describe('PR preview workflow', () => { expect(verify.env?.CF_ACCESS_CLIENT_SECRET).toBe('${{ secrets.CF_ACCESS_CLIENT_SECRET }}') const comment = preview.steps.find(step => step.name === 'Comment the preview URL')! expect(comment.run).toContain('') - expect(comment.run).toContain('gh pr comment "$PR" --body-file -') + expect(comment.run).toContain('printf \'%s\' "$body" | gh pr comment "$PR" --body-file -') expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)') + expect(comment.env?.SNAPSHOT_DIFF).toBe('${{ steps.snapshot-diff.outcome }}') + expect(comment.run).toContain('if [ "$SNAPSHOT_DIFF" = success ]') expect(comment.run).toContain('gh api -X PATCH') + expect(comment.run).toContain('select(.user.login == \\"github-actions[bot]\\"') }) it('renders the snapshot diff page into the upload against the base branch tip', () => { const steps = preview.steps.map(step => step.name) const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')! - expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD --out apps/web/dist/snapshot-diff/index.html') + expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD' + + ' --out apps/web/dist/snapshot-diff/index.html --preview-manifest apps/web/dist/preview/fixtures.json') expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload')) expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages')) }) diff --git a/scripts/snapshot-diff-page.spec.ts b/scripts/snapshot-diff-page.spec.ts index 5147ec6dd0..84ffd1dfff 100644 --- a/scripts/snapshot-diff-page.spec.ts +++ b/scripts/snapshot-diff-page.spec.ts @@ -1,7 +1,5 @@ import { describe, expect, it } from 'vitest' -import { groupDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' - -const limits = { fileLines: 100, totalChars: 10_000 } +import { addPreviewLink, catalogFiles, groupDiffs, limitDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts' const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md index 1111111..2222222 100644 @@ -27,50 +25,80 @@ old mode 100644 new mode 100755 ` -const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] +const file = (path: string, hunks = '') => ({ path, hunks, binary: false, omitted: 0 }) describe('snapshot diff page', () => { it('splits git diff output into files with their hunks', () => { - expect(parseUnifiedDiff(diff, limits)).toEqual([ - { path: 'snapshots/sdk/text-turn/system-prompt.expected.md', hunks: '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/session.jsonl', hunks: '@@ -1 +0,0 @@\n-{"type":"header"}', binary: false, omitted: 0 }, - { path: 'snapshots/web/ptc-round/image.png', hunks: '', binary: true, omitted: 0 }, - { path: 'snapshots/web/present/workspace.expected/a b/说明.txt', hunks: '', binary: false, omitted: 0 }, + expect(parseUnifiedDiff(diff)).toEqual([ + file('snapshots/sdk/text-turn/system-prompt.expected.md', '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.'), + file('snapshots/web/ptc-round/session.jsonl', '@@ -1 +0,0 @@\n-{"type":"header"}'), + { ...file('snapshots/web/ptc-round/image.png'), binary: true }, + file('snapshots/web/present/workspace.expected/a b/说明.txt'), ]) - expect(parseUnifiedDiff('', limits)).toEqual([]) + expect(parseUnifiedDiff('')).toEqual([]) }) - it('rejects paths git still quotes', () => { - expect(() => parseUnifiedDiff('diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n', limits)).toThrow('unsupported quoted path') + it.each([ + ['a quoted path', 'diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n'], + ['unequal header paths', 'diff --git a/snapshots/x b/snapshots/y\n'], + ['a missing prefix', 'diff --git snapshots/x snapshots/x\n'], + ])('rejects a header with %s', (_, text) => { + expect(() => parseUnifiedDiff(text)).toThrow('unsupported git diff header') }) - it('truncates long files and drops hunks once the total budget is spent', () => { - const section = (name: string, lines: number) => `diff --git a/${name} b/${name}\n--- a/${name}\n+++ b/${name}\n@@ -1,${lines} +1,${lines} @@\n${'+x\n'.repeat(lines - 1)}` - const [long, fits, over] = parseUnifiedDiff(section('a', 150) + section('b', 10) + section('c', 10), { fileLines: 100, totalChars: 365 }) - expect([long!.hunks.split('\n').length, long!.omitted]).toEqual([100, 50]) - expect([fits!.hunks.split('\n').length, fits!.omitted]).toEqual([10, 0]) - expect([over!.hunks, over!.omitted]).toEqual(['', 10]) + it('truncates long sections and drops sections past the byte budget of the escaped JSON', () => { + const lines = (count: number, line = '+x') => file(`f${count}`, ['@@', ...Array.from({ length: count - 1 }, () => line)].join('\n')) + const [long, fits, over] = limitDiffs([lines(150), lines(10), lines(10)], { fileLines: 100, totalBytes: 445 }) + expect([long?.hunks.split('\n').length, long?.omitted]).toEqual([100, 50]) + expect([fits?.hunks.split('\n').length, fits?.omitted]).toEqual([10, 0]) + expect([over?.hunks, over?.omitted]).toEqual(['', 10]) + // Quotes, `@@`, and nine lines of an escaped newline, `+`, and two six-byte \u003c escapes: 139 bytes. + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 138 })[0]?.omitted).toBe(10) + expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 139 })[0]?.omitted).toBe(0) }) - it('opens on the catalog, listing unchanged catalog files, then groups by scenario', () => { - const groups = groupDiffs(parseUnifiedDiff(diff, limits).slice(0, 3), catalog) - expect(groups.map(group => [group.title, group.paths, group.files.map(file => file.path)])).toEqual([ - ['SDK blank Session catalog', catalog, ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['sdk/text-turn', ['snapshots/sdk/text-turn/system-prompt.expected.md'], ['snapshots/sdk/text-turn/system-prompt.expected.md']], - ['web/ptc-round', ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl'], ['snapshots/web/ptc-round/image.png', 'snapshots/web/ptc-round/session.jsonl']], + it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => { + const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json'] + const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y'] + expect(groupDiffs([...paths, 'snapshots/web/b/x'].map(path => file(path)), catalog)).toEqual([ + { title: 'SDK blank Session catalog', paths: catalog }, + { title: 'snapshots', paths: ['snapshots/AGENTS.md'] }, + { title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] }, + { title: 'web/B', paths: ['snapshots/web/B/x'] }, + { title: 'web/b', paths: ['snapshots/web/b/a/y', 'snapshots/web/b/x'] }, ]) }) - it('lists a path once when a type change splits it into two sections', () => { - const removed = { path: 'snapshots/acp/cancel/system-prompt.expected.md', hunks: '@@ -1 +0,0 @@\n-../x', binary: false, omitted: 0 } - const added = { ...removed, hunks: '@@ -0,0 +1 @@\n+text' } - expect(groupDiffs([removed, added], catalog)[1]).toEqual({ title: 'acp/cancel', paths: [removed.path], files: [removed, added] }) + it.each([ + ['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'], + ['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'], + ['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'], + ])('resolves catalog sidecars when the manifest %s', (_, text, prompt, schemas) => { + expect(catalogFiles(text)).toEqual({ + systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`, + toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`, + }) + }) + + it.each([ + ['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'], + ['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'], + ])('rejects %s', (_, text, message) => { + expect(() => catalogFiles(text)).toThrow(message) }) it('embeds the data so diff text cannot close the script element', () => { - const page = renderSnapshotDiffPage([{ title: 't', paths: ['p'], files: [{ path: 'p', hunks: '+', binary: false, omitted: 0 }] }], 'a → b') + const files = [file('p', '+')] + const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') expect(page).not.toContain('') - const data = /', binary: false, omitted: 0 }] }], heading: 'a → b' }) + const data = / ')] - const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b') + it('embeds the index so a path cannot close the script element', () => { + const files = [{ path: 'p', added: 1, removed: 0 }] + const groups = [{ title: 't', paths: ['p'] }] + const page = renderSnapshotDiffPage(files, groups, 'a → b') expect(page).not.toContain('') const data = /