From 2718245916266aa27156d011ebc3690dd73fd4fc Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:42:06 +0800 Subject: [PATCH 001/205] 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/205] 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/205] 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/205] 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/205] 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 e9591154b4919682faf539e5ea48951d189b3eae Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 17:57:11 +0800 Subject: [PATCH 006/205] 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 007/205] 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 008/205] 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 009/205] 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 010/205] 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 011/205] 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 012/205] 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 013/205] 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 014/205] 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 015/205] 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 016/205] 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 017/205] 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 50577597e925fd37767dd9147b1ad9bb5d12a95c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 17:40:53 +0800 Subject: [PATCH 018/205] feat(cua-windows): port Windows provider from old branch Port the existing Windows CUA implementation from feat/cua-windows in deepseek-harness2 to the current branch, with adapters for the current app/window interfaces and Windows-only bundle activation. Retain the native Shell/UWP implementation for later interface work. --- package.json | 1 + .../experimental/cua-bundle/README.i18n.yaml | 16 +- packages/experimental/cua-bundle/README.md | 14 +- packages/experimental/cua-bundle/README.zh.md | 14 +- .../experimental/cua-bundle/cordis.patch.yml | 5 + packages/experimental/cua-bundle/package.json | 6 +- .../cua-bundle/tests/platform.spec.ts | 3 +- .../experimental/cua-windows/README.i18n.yaml | 10 + packages/experimental/cua-windows/README.md | 12 + .../experimental/cua-windows/README.zh.md | 12 + .../cua-windows/native/.gitignore | 3 + .../cua-windows/native/.npmignore | 3 + .../cua-windows/native/CuaWindows.csproj | 26 + .../cua-windows/native/Directory.Build.props | 6 + .../cua-windows/native/app.manifest | 13 + .../native/capture-probe/CaptureProbe.cs | 221 +++ .../capture-probe/CaptureProbe.exe.config | 6 + .../native/capture-probe/README.i18n.yaml | 28 + .../native/capture-probe/README.md | 93 ++ .../native/capture-probe/README.zh.md | 93 ++ .../native/capture-probe/app.manifest | 12 + .../cua-windows/native/capture-probe/run.ps1 | 28 + .../desktop-tests/DesktopFixture.csproj | 13 + .../native/desktop-tests/Program.cs | 95 ++ .../cua-windows/native/generate-protocol.ts | 9 + .../cua-windows/native/packages.lock.json | 95 ++ .../cua-windows/native/protocol.schema.json | 1414 +++++++++++++++++ .../native/protocol/AccessibilityText.cs | 74 + .../native/protocol/CuaProtocol.csproj | 14 + .../cua-windows/native/protocol/KeyChord.cs | 25 + .../native/protocol/NativeControlFrame.cs | 23 + .../native/protocol/NativeRequest.cs | 99 ++ .../native/protocol/TextSelection.cs | 49 + .../native/protocol/packages.lock.json | 37 + .../cua-windows/native/src/Accessibility.cs | 245 +++ .../native/src/AccessibilityActions.cs | 163 ++ .../cua-windows/native/src/Applications.cs | 291 ++++ .../native/src/CaptureAdmission.cs | 34 + .../cua-windows/native/src/ClipboardPaste.cs | 183 +++ .../cua-windows/native/src/DesktopExecutor.cs | 264 +++ .../cua-windows/native/src/DesktopSession.cs | 45 + .../cua-windows/native/src/DesktopWindows.cs | 109 ++ .../cua-windows/native/src/Dispatchers.cs | 178 +++ .../cua-windows/native/src/GlobalUsings.cs | 1 + .../cua-windows/native/src/Input.cs | 263 +++ .../cua-windows/native/src/LaunchEntries.cs | 88 + .../cua-windows/native/src/NativeServer.cs | 196 +++ .../cua-windows/native/src/Program.cs | 35 + .../cua-windows/native/src/SharedRuntime.cs | 110 ++ .../cua-windows/native/src/ShellBroker.cs | 111 ++ .../cua-windows/native/src/Win32.cs | 136 ++ .../cua-windows/native/src/WindowCapture.cs | 243 +++ .../cua-windows/native/src/Windows.cs | 176 ++ .../cua-windows/native/tests/Program.cs | 96 ++ .../native/tests/Protocol.Tests.csproj | 11 + .../native/tests/packages.lock.json | 40 + .../experimental/cua-windows/package.json | 95 ++ .../experimental/cua-windows/src/guidance.ts | 2 + .../experimental/cua-windows/src/index.ts | 91 ++ .../cua-windows/src/native-build.ts | 73 + .../cua-windows/src/native-runtime.ts | 354 +++++ .../cua-windows/src/native-transport.ts | 65 + .../cua-windows/src/windows-host.ts | 93 ++ .../cua-windows/tests/desktop-runtime.spec.ts | 22 + .../cua-windows/tests/desktop-smoke.mjs | 285 ++++ .../cua-windows/tests/desktop-tool.spec.ts | 71 + .../cua-windows/tests/native-build.spec.ts | 61 + .../cua-windows/tests/native-runtime.spec.ts | 448 ++++++ .../tests/native-transport.spec.ts | 29 + .../cua-windows/tests/protocol.spec.ts | 30 + .../tests/provider-lifecycle.spec.ts | 108 ++ .../cua-windows/tests/windows-host.spec.ts | 66 + .../experimental/cua-windows/tsconfig.json | 30 + packages/experimental/cua/src/access-types.ts | 4 +- packages/experimental/cua/src/access.ts | 2 +- .../cua/src/client/PermissionPanel.tsx | 12 +- packages/experimental/cua/src/guidance.ts | 2 +- .../cua/tests/panel.client.spec.tsx | 6 +- pnpm-lock.yaml | 115 ++ scripts/check-workspace-constraints.ts | 1 + scripts/experimental-package-policy.ts | 1 + scripts/release/families.spec.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 2 + 84 files changed, 7626 insertions(+), 34 deletions(-) create mode 100644 packages/experimental/cua-windows/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/README.md create mode 100644 packages/experimental/cua-windows/README.zh.md create mode 100644 packages/experimental/cua-windows/native/.gitignore create mode 100644 packages/experimental/cua-windows/native/.npmignore create mode 100644 packages/experimental/cua-windows/native/CuaWindows.csproj create mode 100644 packages/experimental/cua-windows/native/Directory.Build.props create mode 100644 packages/experimental/cua-windows/native/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs create mode 100644 packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/README.zh.md create mode 100644 packages/experimental/cua-windows/native/capture-probe/app.manifest create mode 100644 packages/experimental/cua-windows/native/capture-probe/run.ps1 create mode 100644 packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj create mode 100644 packages/experimental/cua-windows/native/desktop-tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/generate-protocol.ts create mode 100644 packages/experimental/cua-windows/native/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/protocol.schema.json create mode 100644 packages/experimental/cua-windows/native/protocol/AccessibilityText.cs create mode 100644 packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj create mode 100644 packages/experimental/cua-windows/native/protocol/KeyChord.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs create mode 100644 packages/experimental/cua-windows/native/protocol/NativeRequest.cs create mode 100644 packages/experimental/cua-windows/native/protocol/TextSelection.cs create mode 100644 packages/experimental/cua-windows/native/protocol/packages.lock.json create mode 100644 packages/experimental/cua-windows/native/src/Accessibility.cs create mode 100644 packages/experimental/cua-windows/native/src/AccessibilityActions.cs create mode 100644 packages/experimental/cua-windows/native/src/Applications.cs create mode 100644 packages/experimental/cua-windows/native/src/CaptureAdmission.cs create mode 100644 packages/experimental/cua-windows/native/src/ClipboardPaste.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopExecutor.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopSession.cs create mode 100644 packages/experimental/cua-windows/native/src/DesktopWindows.cs create mode 100644 packages/experimental/cua-windows/native/src/Dispatchers.cs create mode 100644 packages/experimental/cua-windows/native/src/GlobalUsings.cs create mode 100644 packages/experimental/cua-windows/native/src/Input.cs create mode 100644 packages/experimental/cua-windows/native/src/LaunchEntries.cs create mode 100644 packages/experimental/cua-windows/native/src/NativeServer.cs create mode 100644 packages/experimental/cua-windows/native/src/Program.cs create mode 100644 packages/experimental/cua-windows/native/src/SharedRuntime.cs create mode 100644 packages/experimental/cua-windows/native/src/ShellBroker.cs create mode 100644 packages/experimental/cua-windows/native/src/Win32.cs create mode 100644 packages/experimental/cua-windows/native/src/WindowCapture.cs create mode 100644 packages/experimental/cua-windows/native/src/Windows.cs create mode 100644 packages/experimental/cua-windows/native/tests/Program.cs create mode 100644 packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj create mode 100644 packages/experimental/cua-windows/native/tests/packages.lock.json create mode 100644 packages/experimental/cua-windows/package.json create mode 100644 packages/experimental/cua-windows/src/guidance.ts create mode 100644 packages/experimental/cua-windows/src/index.ts create mode 100644 packages/experimental/cua-windows/src/native-build.ts create mode 100644 packages/experimental/cua-windows/src/native-runtime.ts create mode 100644 packages/experimental/cua-windows/src/native-transport.ts create mode 100644 packages/experimental/cua-windows/src/windows-host.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/desktop-smoke.mjs create mode 100644 packages/experimental/cua-windows/tests/desktop-tool.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-build.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-runtime.spec.ts create mode 100644 packages/experimental/cua-windows/tests/native-transport.spec.ts create mode 100644 packages/experimental/cua-windows/tests/protocol.spec.ts create mode 100644 packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts create mode 100644 packages/experimental/cua-windows/tests/windows-host.spec.ts create mode 100644 packages/experimental/cua-windows/tsconfig.json diff --git a/package.json b/package.json index 37b86b60d5..d50b670493 100644 --- a/package.json +++ b/package.json @@ -301,6 +301,7 @@ "@deepseek-ai/dsh-experimental-worktree": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*", "@deepseek-ai/dsh-experimental-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*", "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", diff --git a/packages/experimental/cua-bundle/README.i18n.yaml b/packages/experimental/cua-bundle/README.i18n.yaml index b561f27e44..a04d2cf4b4 100644 --- a/packages/experimental/cua-bundle/README.i18n.yaml +++ b/packages/experimental/cua-bundle/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/experimental/cua-bundle/README.md /: - en: cc518dcd97629a96 - zh: 465e999011282dc3 + en: 0df5d6f2b9e2ac15 + zh: d0a9bd1f4e172d25 /deepseek-ai-dsh-cua-bundle: en: 9084fb48d0f6489c zh: ce692972d91cf663 /deepseek-ai-dsh-cua-bundle/summary: - en: 0d93f44a8ce7404c - zh: 6a73ed42d0efc9ea + en: f9f318c0ddc27bff + zh: 8a0c5ec31a63eb05 /deepseek-ai-dsh-cua-bundle/table-of-contents: en: b563e4ec4727d0de zh: d0228da978238e05 /deepseek-ai-dsh-cua-bundle/use-this-package: - en: 5c025a58990bb2eb - zh: c3d1280ccbdfe214 + en: f22a10946cefc2d8 + zh: 430d5f0cfc244ef0 /deepseek-ai-dsh-cua-bundle/understand-the-implementation: - en: b1011db52cfc17cd - zh: 6fa8798fedc5c0b6 + en: acb42fb7b181194b + zh: 6961f4cb732560e9 /deepseek-ai-dsh-cua-bundle/further-exploration: en: 9f15d56b5b16e1ca zh: 75eb08e8828c8877 diff --git a/packages/experimental/cua-bundle/README.md b/packages/experimental/cua-bundle/README.md index 50109f1066..9c19ccbbb1 100644 --- a/packages/experimental/cua-bundle/README.md +++ b/packages/experimental/cua-bundle/README.md @@ -1,5 +1,5 @@ --- -description: "Enable optional macOS Computer Use and its permission page." +description: "Enable optional Computer Use on macOS and Windows with its permission page." kind: "package-bundle" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Enable macOS Computer Use from Plugins for existing and new PTC sessions. Windows support is in development. This bundle remains in `experimental` until that support is complete, then moves to the `computer-use` group. It ships with DSH switched off and appears in the Experimental plugins list on macOS Hosts; disabled profiles prepare no native components and register neither CUA tools nor their model guidance. +Enable Computer Use from Plugins on macOS and Windows for existing and new PTC sessions. The bundle ships with DSH switched off and appears in the Experimental plugins list on supported Hosts. Each Host loads its platform's native provider and the shared permission page. Disabled profiles prepare no native components and register neither CUA tools nor their model guidance. ## Table of Contents @@ -24,7 +24,11 @@ Enable macOS Computer Use from Plugins for existing and new PTC sessions. Window ## Use this package -On macOS, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. The bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Open its details, choose PTC if needed, and grant Accessibility and Screen Recording to `DSH Computer Use.app`. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. For source Web, run these commands from the repository root: +On macOS or Windows, open **Plugins → More** and switch on **Computer use** in the Experimental plugins list. Open its details and choose PTC if needed. An enabled bundle also appears in the main plugin list; switching it off returns it to the Experimental plugins list only. + +On macOS, the bundle ships with DSH and updates with it, so enabling it downloads nothing. Published packages contain the signed and notarized helper; users need no compiler. Source Web and development Desktop prepare an ad-hoc helper when enabled. Grant Accessibility and Screen Recording to `DSH Computer Use.app`. + +Native preparation and access requirements belong to the [macOS provider](../cua-macos/README.md) and [Windows provider](../cua-windows/README.md). For source Web, run these commands from the repository root: ```sh pnpm run build @@ -37,7 +41,7 @@ The switch saves bundle selection in the profile’s `package.json`. Computer Us Disabling unloads the provider and withdraws CUA tools from its Agent scopes. Runtime configuration, the new-session default and saved grants remain. -Computer Use is available only on a macOS DSH Host. The native provider is an optional dependency installed only on macOS; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported Mac Host. +The bundle supports macOS and native Windows DSH Hosts; it does not enable Windows Computer Use from WSL. Native providers are optional dependencies, and each Host loads only its matching provider; shared CUA and Client packages remain in the installation. Other Hosts hide the bundle from default plugin lists and model recommendations and refuse enablement before saving settings. Explicit profile dependencies and saved selections remain visible for management. An already selected bundle is skipped at startup with a diagnostic and remains available for deselection; saved user settings remain. A browser on another operating system can connect to a supported DSH Host. If preparation fails, the saved selection remains and CUA operations stay unavailable. Refresh or reopen the plugin page to read the component diagnostic, correct its cause, then restart DSH. @@ -51,7 +55,7 @@ Explicit activation runs a read-only permission check, which may start a helper
Maintainer details -The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level condition skips the optional macOS provider on other Hosts. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal. +The bundle patch mounts the native provider and permission UI with `agentPreset: ptc`. Using the exported `cordis.patch.yml` directly as an overlay bypasses bundle admission; its row-level conditions load the macOS provider only on macOS and the Windows provider only on native Windows. Shared entries alone do not provide computer control. Existing Agent scopes register the tools without changing preset documents. The detail-page action uses the existing settings form to save `agent-preset-registry.selectedDefault: ptc` only when clicked. [CUA](../cua/README.md) owns registration and disposal.
diff --git a/packages/experimental/cua-bundle/README.zh.md b/packages/experimental/cua-bundle/README.zh.md index b7d8804e91..2318aeb313 100644 --- a/packages/experimental/cua-bundle/README.zh.md +++ b/packages/experimental/cua-bundle/README.zh.md @@ -1,5 +1,5 @@ --- -description: "开启可选 macOS Computer Use 及权限页面。" +description: "在 macOS 和 Windows 上开启可选 Computer Use 及权限页面。" kind: "package-bundle" --- @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -从插件页为已有和新建 PTC 会话开启 macOS Computer Use。Windows 支持正在开发中。本组合包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。随 DSH 提供且默认关闭,在 macOS Host 的实验性插件列表中显示;关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 +在 macOS 和 Windows 的插件页为已有和新建 PTC 会话开启 Computer Use。组合包随 DSH 提供且默认关闭,在受支持 Host 的实验性插件列表中显示。各 Host 加载对应平台的原生提供方和共享权限页面。关闭时不准备本机组件、不注册 CUA 工具或添加其模型指引。 ## 目录 @@ -24,7 +24,11 @@ kind: "package-bundle" ## 使用本包 -在 macOS 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。打开它的详情,按需设置 PTC,并为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。源码 Web 在仓库根目录运行以下命令: +在 macOS 或 Windows 上打开“插件 → 更多”,在实验性插件列表中开启 Computer Use。打开详情,按需设置 PTC。开启后组合包也会出现在插件主列表中,关闭后只留在实验性插件列表。 + +在 macOS 上,组合包随 DSH 提供并随之升级,开启时无需下载。发布包包含已签名和公证的 helper,用户无需编译工具。源码 Web 和开发 Desktop 在开启时准备临时签名的 helper。请为 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 + +各平台的原生准备和访问要求分别见 [macOS 提供方](../cua-macos/README.zh.md)和 [Windows 提供方](../cua-windows/README.zh.md)。源码 Web 在仓库根目录运行以下命令: ```sh pnpm run build @@ -37,7 +41,7 @@ pnpm dsh web 关闭会卸载提供方,并从其 Agent 作用域中撤回 CUA 工具。执行器配置、新会话默认值和已保存的授权保留。 -Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的可选依赖,共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 Mac Host。 +组合包支持 macOS 和原生 Windows DSH Host,不在 WSL 中启用 Windows Computer Use。原生提供方作为可选依赖提供,各 Host 只加载对应平台的提供方;共享 CUA 和 Client 包仍随安装提供。其他 Host 默认不在插件列表和模型推荐中展示此组合包,并在保存设置前拒绝启用。profile 显式安装的依赖和已保存的选择仍保留管理入口。已选中的组合包会在启动时跳过并报告原因,仍可取消选择;已保存的用户设置保留。其他操作系统上的浏览器可以连接受支持的 DSH Host。 准备失败时,已保存的选择保留,CUA 操作不可用。刷新或重新打开插件页查看组件诊断,修复后重启 DSH。 @@ -51,7 +55,7 @@ Computer Use 仅支持 macOS DSH Host。原生提供方是仅在 macOS 安装的
维护者说明 -组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件会在其他 Host 上跳过可选的 macOS 提供方。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。 +组合包 patch 通过 `agentPreset: ptc` 挂载原生提供方和权限界面。直接将导出的 `cordis.patch.yml` 用作覆盖层时不会经过组合包准入;行级条件确保 macOS 提供方仅在 macOS 加载,Windows 提供方仅在原生 Windows 加载。仅加载共享条目不能提供计算机控制。工具通过现有 Agent 作用域注册,preset 文档保持不变。详情页按钮复用现有设置表单,仅在点击后保存 `agent-preset-registry.selectedDefault: ptc`。[CUA](../cua/README.zh.md)负责注册和销毁。
diff --git a/packages/experimental/cua-bundle/cordis.patch.yml b/packages/experimental/cua-bundle/cordis.patch.yml index 5d5fb48b6f..82d3d0960f 100644 --- a/packages/experimental/cua-bundle/cordis.patch.yml +++ b/packages/experimental/cua-bundle/cordis.patch.yml @@ -6,5 +6,10 @@ disabled: !!js process.platform !== 'darwin' config: agentPreset: ptc + - id: cua-windows + name: '@deepseek-ai/dsh-cua-windows' + disabled: !!js process.platform !== 'win32' + config: + agentPreset: ptc - id: ui-cua name: '@deepseek-ai/dsh-cua' diff --git a/packages/experimental/cua-bundle/package.json b/packages/experimental/cua-bundle/package.json index f9ba508721..699b5bae93 100644 --- a/packages/experimental/cua-bundle/package.json +++ b/packages/experimental/cua-bundle/package.json @@ -40,7 +40,8 @@ "bundle": { "patch": "./cordis.patch.yml", "platforms": [ - "darwin" + "darwin", + "win32" ] } }, @@ -58,6 +59,7 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:~" }, "optionalDependencies": { - "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" + "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*", + "@deepseek-ai/dsh-cua-windows": "workspace:*" } } diff --git a/packages/experimental/cua-bundle/tests/platform.spec.ts b/packages/experimental/cua-bundle/tests/platform.spec.ts index 4230e4f406..912e2c56b9 100644 --- a/packages/experimental/cua-bundle/tests/platform.spec.ts +++ b/packages/experimental/cua-bundle/tests/platform.spec.ts @@ -6,7 +6,7 @@ import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' import { load } from 'js-yaml' import { expect, it, vi } from 'vitest' -it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and imports the native provider only on Darwin', async (platform) => { +it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s and selects its native provider', async (platform) => { const patch = load(await readFile(new URL('../cordis.patch.yml', import.meta.url), 'utf8'), { schema: entryListSchema, }) as { insert: EntryOptions[] }[] @@ -28,6 +28,7 @@ it.each(['darwin', 'win32', 'linux'])('loads the exported patch directly on %s a expect(imports).toContain('@deepseek-ai/dsh-cua') expect(imports).toContain('@deepseek-ai/dsh-computer-use') expect(imports.includes('@deepseek-ai/dsh-experimental-cua-macos')).toBe(platform === 'darwin') + expect(imports.includes('@deepseek-ai/dsh-cua-windows')).toBe(platform === 'win32') } finally { await ctx.fiber.dispose() imported.mockRestore() diff --git a/packages/experimental/cua-windows/README.i18n.yaml b/packages/experimental/cua-windows/README.i18n.yaml new file mode 100644 index 0000000000..30b2eb4f1f --- /dev/null +++ b/packages/experimental/cua-windows/README.i18n.yaml @@ -0,0 +1,10 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/cua-windows/README.md +/: + en: 74cec3b0e35e9bf4 + zh: 8c7eb35b11ada2b5 +/deepseek-ai-dsh-cua-windows: + en: f31869d4398aa0ae + zh: b94122bb2bc53a53 diff --git a/packages/experimental/cua-windows/README.md b/packages/experimental/cua-windows/README.md new file mode 100644 index 0000000000..40a31c5e3f --- /dev/null +++ b/packages/experimental/cua-windows/README.md @@ -0,0 +1,12 @@ +--- +description: "TODO: Windows Computer Use documentation." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +English | [中文](README.zh.md) + +TODO: Document the migrated provider after the interface is finalized. + +TODO: Expose the retained native Shell/UWP discovery and launch operations. diff --git a/packages/experimental/cua-windows/README.zh.md b/packages/experimental/cua-windows/README.zh.md new file mode 100644 index 0000000000..9f118ebe6f --- /dev/null +++ b/packages/experimental/cua-windows/README.zh.md @@ -0,0 +1,12 @@ +--- +description: "TODO:Windows Computer Use 文档。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-cua-windows + +[English](README.md) | 中文 + +TODO:接口定稿后统一补齐迁移后提供方的文档。 + +TODO:暴露保留的 native Shell/UWP 发现和启动操作。 diff --git a/packages/experimental/cua-windows/native/.gitignore b/packages/experimental/cua-windows/native/.gitignore new file mode 100644 index 0000000000..d519714059 --- /dev/null +++ b/packages/experimental/cua-windows/native/.gitignore @@ -0,0 +1,3 @@ +**/bin/ +**/obj/ +.build/ diff --git a/packages/experimental/cua-windows/native/.npmignore b/packages/experimental/cua-windows/native/.npmignore new file mode 100644 index 0000000000..6fd41ce451 --- /dev/null +++ b/packages/experimental/cua-windows/native/.npmignore @@ -0,0 +1,3 @@ +obj/ +protocol/bin/ +tests/bin/ diff --git a/packages/experimental/cua-windows/native/CuaWindows.csproj b/packages/experimental/cua-windows/native/CuaWindows.csproj new file mode 100644 index 0000000000..0cc65b6907 --- /dev/null +++ b/packages/experimental/cua-windows/native/CuaWindows.csproj @@ -0,0 +1,26 @@ + + + Exe + net10.0-windows10.0.19041.0 + true + true + true + false + enable + enable + true + dsh-cua-windows + app.manifest + true + win-x64;win-arm64 + true + true + none + false + + + + + + + diff --git a/packages/experimental/cua-windows/native/Directory.Build.props b/packages/experimental/cua-windows/native/Directory.Build.props new file mode 100644 index 0000000000..b4fbcbc808 --- /dev/null +++ b/packages/experimental/cua-windows/native/Directory.Build.props @@ -0,0 +1,6 @@ + + + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/bin/ + $(MSBuildThisFileDirectory).build/$(MSBuildProjectName)/obj/ + + diff --git a/packages/experimental/cua-windows/native/app.manifest b/packages/experimental/cua-windows/native/app.manifest new file mode 100644 index 0000000000..a2e299ca4e --- /dev/null +++ b/packages/experimental/cua-windows/native/app.manifest @@ -0,0 +1,13 @@ + + + + + + + + + PerMonitorV2 + true + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs new file mode 100644 index 0000000000..6f118d63ae --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.cs @@ -0,0 +1,221 @@ +// Private .NET Framework experiment. Each blocking capture runs in a disposable child process. +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using System.Windows.Automation; +using System.Windows.Forms; + +internal static class CaptureProbe +{ + private static readonly JavaScriptSerializer Json = new JavaScriptSerializer(); + private static readonly string[] Methods = { "screen", "window-dc", "print", "print-full" }; + + [STAThread] + private static int Main(string[] args) + { + try + { + SetProcessDpiAwarenessContext(new IntPtr(-4)); + if (args.Length == 4 && args[0] == "--one") + { + Capture(new IntPtr(long.Parse(args[1])), args[2], args[3]); + return 0; + } + if (args.Length == 3 && args[0] == "--compare") + { + var output = NewOutput(args[2]); + Compare(new IntPtr(long.Parse(args[1])), output, "selected"); + return 0; + } + if (args.Length != 2 || args[0] != "--demo") + throw new ArgumentException("Expected --demo OUTPUT or --compare DECIMAL_HWND OUTPUT"); + var directory = NewOutput(args[1]); + Application.EnableVisualStyles(); + using (var target = new Form()) + using (var cover = new Form()) + { + target.Text = "DSH capture probe: owned target"; + target.StartPosition = cover.StartPosition = FormStartPosition.Manual; + target.Bounds = new Rectangle(100, 100, 520, 400); + target.BackColor = Color.FromArgb(20, 180, 60); + target.TopMost = true; + cover.Text = "DSH capture probe: owned cover"; + cover.Bounds = target.Bounds; + cover.BackColor = Color.Magenta; + cover.TopMost = true; + Exception failure = null; + target.Shown += async delegate + { + try + { + var hwnd = target.Handle; + var automation = await Task.Run(() => AutomationElement.FromHandle(hwnd).Current.Name); + Write(Path.Combine(directory, "runtime.json"), new + { + framework = Environment.Version.ToString(), + automationName = automation, + os = Environment.OSVersion.VersionString, + pointerBytes = IntPtr.Size + }); + target.Refresh(); + var center = new Point(target.Left + target.Width / 2, target.Top + target.Height / 2); + await WaitForPixel(center, target.BackColor); + await Task.Run(() => Compare(hwnd, directory, "visible")); + cover.Show(); + cover.Refresh(); + await WaitForPixel(center, cover.BackColor); + // A new marker distinguishes a fresh covered image from a cached visible image. + target.BackColor = Color.FromArgb(30, 90, 220); + target.Refresh(); + await Task.Run(() => Compare(hwnd, directory, "covered-updated")); + target.WindowState = FormWindowState.Minimized; + await Task.Run(() => Compare(hwnd, directory, "minimized")); + } + catch (Exception error) { failure = error; } + finally { cover.Close(); target.Close(); } + }; + Application.Run(target); + if (failure != null) throw failure; + } + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error); + return 1; + } + } + + private static string NewOutput(string path) + { + var result = Path.GetFullPath(path); + if (Directory.Exists(result)) throw new IOException("Use a new output directory for each experiment"); + Directory.CreateDirectory(result); + return result; + } + + private static async Task WaitForPixel(Point point, Color expected) + { + var clock = Stopwatch.StartNew(); + using (var sample = new Bitmap(1, 1)) + using (var graphics = Graphics.FromImage(sample)) + { + while (true) + { + graphics.CopyFromScreen(point.X, point.Y, 0, 0, sample.Size); + if (sample.GetPixel(0, 0).ToArgb() == expected.ToArgb()) return; + if (clock.ElapsedMilliseconds > 5000) throw new TimeoutException("The owned window marker is not visible"); + await Task.Delay(25); + } + } + } + + private static void Compare(IntPtr window, string directory, string scenario) + { + foreach (var method in Methods) + { + var prefix = Path.Combine(directory, scenario + "-" + method); + var start = new ProcessStartInfo(Application.ExecutablePath, + "--one " + window.ToInt64() + " " + method + " \"" + prefix + "\"") + { + UseShellExecute = false, + CreateNoWindow = true + }; + using (var process = Process.Start(start)) + { + if (!process.WaitForExit(5000)) + { + process.Kill(); + process.WaitForExit(); + Write(prefix + ".json", new { method, timeout = true }); + } + else if (process.ExitCode != 0) + throw new InvalidOperationException(method + " child exited " + process.ExitCode); + } + Console.WriteLine(File.ReadAllText(prefix + ".json")); + } + } + + private static void Capture(IntPtr window, string method, string prefix) + { + Rect bounds; + if (!GetWindowRect(window, out bounds)) throw new InvalidOperationException("Window no longer exists"); + var width = bounds.Right - bounds.Left; + var height = bounds.Bottom - bounds.Top; + if (width <= 0 || height <= 0 || (long)width * height > 40000000) + throw new InvalidOperationException("Window dimensions exceed the experiment limit"); + var foreground = GetForegroundWindow(); + var clock = Stopwatch.StartNew(); + using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) + { + bool returned; + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.Clear(Color.Yellow); + if (method == "screen") + { + graphics.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, new Size(width, height)); + returned = true; + } + else if (method == "window-dc") + { + var source = GetWindowDC(window); + if (source == IntPtr.Zero) throw new InvalidOperationException("Window DC is unavailable"); + try + { + var destination = graphics.GetHdc(); + try { returned = BitBlt(destination, 0, 0, width, height, source, 0, 0, 0x00CC0020); } + finally { graphics.ReleaseHdc(destination); } + } + finally { ReleaseDC(window, source); } + } + else + { + var dc = graphics.GetHdc(); + try { returned = PrintWindow(window, dc, method == "print-full" ? 2u : 0u); } + finally { graphics.ReleaseHdc(dc); } + } + } + clock.Stop(); + var markers = new Dictionary { { "green", 0 }, { "blue", 0 }, { "cover", 0 }, { "black", 0 } }; + for (var y = 0; y < height; y += 4) + for (var x = 0; x < width; x += 4) + { + var pixel = bitmap.GetPixel(x, y); + if (pixel.R == 20 && pixel.G == 180 && pixel.B == 60) markers["green"]++; + if (pixel.R == 30 && pixel.G == 90 && pixel.B == 220) markers["blue"]++; + if (pixel.R == 255 && pixel.G == 0 && pixel.B == 255) markers["cover"]++; + if (pixel.R == 0 && pixel.G == 0 && pixel.B == 0) markers["black"]++; + } + bitmap.Save(prefix + ".png", ImageFormat.Png); + Write(prefix + ".json", new + { + method, returned, width, height, elapsedMs = clock.ElapsedMilliseconds, markers, + minimized = IsIconic(window), foregroundChanged = foreground != GetForegroundWindow() + }); + } + } + + private static void Write(string path, object value) + { + File.WriteAllText(path, Json.Serialize(value) + Environment.NewLine); + } + + [StructLayout(LayoutKind.Sequential)] + private struct Rect { internal int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect); + [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr hwnd, IntPtr dc, uint flags); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hwnd); + [DllImport("user32.dll")] private static extern IntPtr GetWindowDC(IntPtr hwnd); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hwnd, IntPtr dc); + [DllImport("gdi32.dll")] private static extern bool BitBlt(IntPtr destination, int x, int y, int width, int height, + IntPtr source, int sourceX, int sourceY, uint operation); +} diff --git a/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config new file mode 100644 index 0000000000..6c3273cff7 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/CaptureProbe.exe.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml b/packages/experimental/cua-windows/native/capture-probe/README.i18n.yaml new file mode 100644 index 0000000000..29c76d358f --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/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 packages/experimental/cua-windows/native/capture-probe/README.md +/: + en: eeabe421bc58f08c + zh: decfb432f67c7a10 +/windows-capture-experiment: + en: 04636b80e16e9c77 + zh: 1939a876909a0728 +/windows-capture-experiment/summary: + en: b7d5300b63fbf75d + zh: 7ac6fff1d0e0ff39 +/windows-capture-experiment/table-of-contents: + en: 5fe6d5c7d6ef2980 + zh: 1b6c59a3a0dae8cd +/windows-capture-experiment/run-the-experiment: + en: 0a3af6cd49068299 + zh: 8efa8e90294c4f28 +/windows-capture-experiment/interpret-the-output: + en: aa765881c455c6c0 + zh: 6d76f02d287f5260 +/windows-capture-experiment/further-exploration: + en: e886759b879c9754 + zh: 0dfaea2ea703055f +/windows-capture-experiment/further-exploration/dev-note: + en: 8a4492cdafa89a70 + zh: b2d7be08c34a0b10 diff --git a/packages/experimental/cua-windows/native/capture-probe/README.md b/packages/experimental/cua-windows/native/capture-probe/README.md new file mode 100644 index 0000000000..737fe1306d --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.md @@ -0,0 +1,93 @@ +--- +description: "Run Windows capture comparisons with the installed .NET Framework and review the native runtime migration plan." +--- + +# Windows capture experiment + +English | [中文](README.zh.md) + +## Summary + +Compare screen copying, window DC copying, and PrintWindow without installing a .NET SDK or third-party library. The private experiment targets .NET Framework 4.8 and uses the compiler and assemblies installed with Windows. It does not replace the provider's capture implementation. + +## Table of Contents + +- [Run the experiment](#run-the-experiment) +- [Interpret the output](#interpret-the-output) +- [Further Exploration](#further-exploration) +- [Dev Note](#dev-note) + +----- + + +## Run the experiment + +On an interactive x64 Windows desktop, run this command from the repository root in Windows PowerShell. The demo creates two temporary windows, tests a visible green target, covers it while changing its content to blue, then minimizes it. It closes both windows on completion. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +The printed output directory contains PNGs and JSON measurements. The script compiles into a unique temporary directory and removes the executable afterward. A new output directory is required for every run. Compilation errors, unavailable windows, and failed captures produce a nonzero exit. + +To compare an application you select, pass its decimal top-level HWND and a new output directory. This mode captures its current state without changing focus, position, or visibility. Obtain the HWND with a window inspector; a PID is not a window handle. + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +Replace the example HWND and output directory. Repeat with the window covered, after its content changes, and after resizing. The screen-copy image includes whatever occupies those screen coordinates. Keep evidence local when other applications can appear there. + +----- + + +## Interpret the output + +Each capture runs in a separate process with a five-second deadline. A hung capture is terminated and recorded as a timeout. JSON records the API return value, image dimensions, elapsed capture time, sampled foreground change, and counts of known marker colors. A successful API return or a valid PNG does not establish that the image contains current target content. + +| Method | Windows facility | What to inspect | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | Whether another window replaces the target pixels. | +| `window-dc` | `GetWindowDC` and GDI `BitBlt` | Whether compositor-backed content is missing or stale. | +| `print` | `PrintWindow`, flags `0` | Whether the target handles print requests. | +| `print-full` | `PrintWindow`, `PW_RENDERFULLCONTENT` | Whether the complete, current client content appears. | + +The demo waits until its visible marker reaches the screen before comparing methods. It samples UI Automation from an MTA thread and records the result in `runtime.json`. Marker checks are intended for the owned fixture; other applications require visual comparison against their actual state. This experiment does not test WGC, clipboard restoration, input, service sharing, or ARM64 compatibility. + +----- + + +## Further Exploration + +- [Provider behavior and desktop acceptance](../../README.md) +- [PrintWindow and its synchronous execution](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK capture flags](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework system requirements](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack window capture source](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### Dev Note + +Research and proposed work below are non-authoritative; the production helper still targets .NET 10 and captures through WGC/Direct3D11. + +The Windows x64 machine used on 2026-10-20 has Framework release `533509` (4.8.1). The Framework-only probe compiled, queried the owned window through `System.Windows.Automation`, and captured images without NuGet dependencies. The current self-contained production helper is approximately 192 MiB; the probe is much smaller because it implements only this experiment. Its size is not an estimate of a complete port. + +For the painted WinForms fixture, all four methods captured the visible green content. After covering the window and changing it to blue, screen copying returned the magenta cover, while window DC copying and both PrintWindow variants returned the new blue content. After minimization, every API reported success but returned only a 314 × 50 image without the content marker. These observations do not establish behavior for other rendering engines or monitors. + +For an owned local HTML page in Edge, window DC copying and ordinary PrintWindow returned black images even while visible. Full-content PrintWindow captured the visible green page. After covering it, JavaScript changed the background to blue and updated the title; full-content PrintWindow captured the updated title with the old green client content. The fresh-content requirement remains unresolved for this case, including whether WGC behaves differently. This is a reason to compare rendering engines before replacing the backend. + +The capture decision must preserve background window observation. `CopyFromScreen` and desktop duplication observe the composed desktop, so they cannot substitute for covered-window capture. DWM thumbnails display another window in a destination window rather than directly returning PNG pixels. WGC supplies Direct3D11 frames by design; removing the Vortice wrapper does not remove that dependency from the API. + +Windows API Code Pack is useful reference material for Shell objects, links, common dialogs, and taskbar integration. Its `TabbedThumbnailScreenCapture` wraps GDI window DC copying and documents limitations for hidden or obstructed controls. It does not provide a general replacement for WGC or target-confirmed clipboard consumption. WinForms already provides ordinary clipboard access, drawing, images, and a message loop; UI Automation is also in the Framework. Add a Code Pack dependency only for a specific capability that removes more maintained code than it introduces. + +Proposed implementation order: + +1. Compare PrintWindow's full-content mode against WGC on Chromium/Electron, WPF, classic controls, changed covered content, mixed DPI, and a hung target. Keep the saved PNGs and observed state together. Select a production backend only after this comparison; do not silently fall back to screen pixels when a window capture fails. +2. Use .NET Framework 4.8 as the runtime port candidate for x64. Keep `System.Windows.Automation`, WinForms, `System.Drawing`, and Windows P/Invoke. Verify the ARM64 runtime and delivery requirements separately; this x64 experiment cannot establish them. +3. Port runtime APIs deliberately: pipe and mutex access control, cancellation and disposal, hashing, and JSON handling. Framework `JavaScriptSerializer` can emit the probe's JSON, but replacing `System.Text.Json` must preserve protocol validation, duplicate-property rejection, numeric limits, and escaping. `JsonSchema.Net` has a netstandard2.0 asset; the installed Vortice version has only modern .NET assets. Avoid introducing a handwritten JSON/schema framework merely to remove a package. +4. Run the owned desktop smoke and shared-service lifetime checks against the selected runtime, then update source preparation and packaging. Remove superseded implementations and dependencies after those checks pass. Keep the shared `cua` API and the macOS provider outside this Windows runtime change. + +The current desktop smoke exposed clipboard prefetch by the Remote Desktop client before the selected editor consumed the data. The pending fix identifies the requesting window's process and leaves the format delayed for other readers. Readers that open the clipboard without an HWND cannot be attributed and time out. The revised native binary cross-compiles, but Smart App Control blocked its execution on this machine. The branch is handed over for human-owned Windows acceptance with an approved signed build or test environment. Earlier smoke results must not be represented as validation of that binary. diff --git a/packages/experimental/cua-windows/native/capture-probe/README.zh.md b/packages/experimental/cua-windows/native/capture-probe/README.zh.md new file mode 100644 index 0000000000..cf07001498 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/README.zh.md @@ -0,0 +1,93 @@ +--- +description: "使用系统安装的 .NET Framework 对比 Windows 截图方案,并审阅原生运行时迁移计划。" +--- + +# Windows 截图实验 + +[English](README.md) | 中文 + +## 摘要 + +无需安装 .NET SDK 或第三方库,即可对比屏幕复制、窗口 DC 复制和 PrintWindow。此私有实验以 .NET Framework 4.8 为目标,使用 Windows 已安装的编译器和程序集。它不替换提供方的截图实现。 + +## 目录 + +- [运行实验](#run-the-experiment) +- [解读输出](#interpret-the-output) +- [延伸阅读](#further-exploration) +- [开发备注](#dev-note) + +----- + + +## 运行实验 + +在交互式 x64 Windows 桌面上,从仓库根目录使用 Windows PowerShell 运行以下命令。演示创建两个临时窗口,测试可见的绿色目标,在遮挡后将其内容改为蓝色,然后将其最小化。完成后关闭两个窗口。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 +``` + +打印的输出目录包含 PNG 和 JSON 测量结果。脚本在唯一临时目录中编译,运行后删除可执行文件。每次运行必须使用新的输出目录。编译错误、窗口不可用和截图失败均产生非零退出状态。 + +要对比自行选择的应用,传入其十进制顶层窗口 HWND 和新的输出目录。此模式捕获当前状态,不改变焦点、位置或可见性。可用窗口检查工具取得 HWND;PID 不是窗口句柄。 + +```powershell +powershell -NoProfile -File packages/experimental/cua-windows/native/capture-probe/run.ps1 -WindowHandle 123456 -OutputDirectory C:\Temp\cua-capture-example +``` + +替换示例中的 HWND 和输出目录。在窗口被遮挡、内容变化和尺寸变化后重复运行。屏幕复制的图片包含相应屏幕坐标上实际显示的内容;当其他应用可能出现在该位置时,证据应保留在本地。 + +----- + + +## 解读输出 + +每次截图在独立进程中执行,期限为五秒。卡住的截图会被终止,并记录为超时。JSON 记录 API 返回值、图片尺寸、截图耗时、采样到的前台变化以及已知标记颜色的数量。API 返回成功或生成有效 PNG,并不能证明图片包含目标的最新内容。 + +| 方法 | Windows 功能 | 检查内容 | +|---|---|---| +| `screen` | `System.Drawing.Graphics.CopyFromScreen` | 其他窗口是否替代了目标像素。 | +| `window-dc` | `GetWindowDC` 与 GDI `BitBlt` | 合成器承载的内容是否缺失或过时。 | +| `print` | `PrintWindow`,标志 `0` | 目标是否处理打印请求。 | +| `print-full` | `PrintWindow`,`PW_RENDERFULLCONTENT` | 是否包含完整、最新的客户区内容。 | + +演示等待可见标记实际显示到屏幕后,再比较各方法。它在 MTA 线程读取 UI Automation,并将结果记入 `runtime.json`。标记检查适用于自有测试窗口;其他应用需要与实际状态进行视觉比较。本实验不测试 WGC、剪贴板恢复、输入、服务共享或 ARM64 兼容性。 + +----- + + +## 延伸阅读 + +- [提供方行为与桌面验收](../../README.zh.md) +- [PrintWindow 及其同步执行](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow) +- [Windows SDK 截图标志](https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/um/WinUser.h) +- [Windows Graphics Capture](https://learn.microsoft.com/en-us/windows/apps/develop/media-authoring-processing/screen-capture) +- [.NET Framework 系统要求](https://learn.microsoft.com/en-us/dotnet/framework/get-started/system-requirements) +- [Code Pack 窗口截图源码](https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Taskbar/TabbedThumbnailScreenCapture.cs) + +----- + + +### 开发备注 + +以下调研和拟议工作不是正式约定;生产 helper 仍以 .NET 10 为目标,并通过 WGC/Direct3D11 截图。 + +2026-10-20 使用的 Windows x64 机器安装了 Framework 版本标识 `533509`(4.8.1)。仅依赖 Framework 的探针已完成编译,通过 `System.Windows.Automation` 查询自有窗口并截图,无需 NuGet 依赖。当前自包含生产 helper 约为 192 MiB;探针小得多,因为它只实现本实验。其大小不能用来估算完整移植的大小。 + +对于完成绘制的 WinForms 测试窗口,四种方法均捕获了可见的绿色内容。遮挡窗口并将内容改为蓝色后,屏幕复制返回紫红色遮挡窗口,窗口 DC 复制和两种 PrintWindow 模式则返回新的蓝色内容。最小化后,各 API 都报告成功,但仅返回不含内容标记的 314 × 50 图片。这些结果不能证明其他渲染引擎或显示器上的行为。 + +对于 Edge 中的自有本地 HTML 页面,窗口 DC 复制和普通 PrintWindow 即使在窗口可见时也返回黑图。完整内容模式的 PrintWindow 捕获了可见的绿色页面。遮挡后,JavaScript 将背景改为蓝色并更新标题;完整内容模式捕获了更新后的标题,但客户区仍为旧的绿色内容。此场景的内容新鲜度要求尚未解决,包括 WGC 是否有不同行为。这说明替换后端前需要比较不同渲染引擎。 + +截图选型必须保留后台窗口观察能力。`CopyFromScreen` 和桌面复制读取合成后的桌面,因此不能替代遮挡窗口截图。DWM 缩略图在目标窗口中显示另一窗口,而不直接返回 PNG 像素。WGC 的接口本身就提供 Direct3D11 帧;删除 Vortice 包装库并不能消除该 API 的此项依赖。 + +Windows API Code Pack 可用于参考 Shell 对象、链接、通用对话框和任务栏集成。其 `TabbedThumbnailScreenCapture` 封装了 GDI 窗口 DC 复制,并明确说明隐藏或遮挡控件的限制。它不提供 WGC 或确认目标消费剪贴板数据的通用替代品。WinForms 已提供普通剪贴板访问、绘图、图片和消息循环;UI Automation 也属于 Framework。只有在具体能力能删除更多自有维护代码时,才引入 Code Pack 依赖。 + +拟议实现顺序: + +1. 在 Chromium/Electron、WPF、传统控件、遮挡后的内容变化、混合 DPI 及卡死目标上,对比 PrintWindow 完整内容模式与 WGC。将保存的 PNG 与实际状态放在一起。完成对比后再选择生产后端;窗口截图失败时不得静默改用屏幕像素。 +2. 将 .NET Framework 4.8 作为 x64 运行时移植候选,保留 `System.Windows.Automation`、WinForms、`System.Drawing` 和 Windows P/Invoke。单独验证 ARM64 运行时及交付要求;本次 x64 实验不能证明它们。 +3. 明确迁移运行时 API:命名管道和互斥量访问控制、取消和释放、散列及 JSON 处理。Framework 的 `JavaScriptSerializer` 可以输出探针的 JSON,但替代 `System.Text.Json` 必须保留协议校验、重复属性拒绝、数字限制和转义行为。`JsonSchema.Net` 有 netstandard2.0 产物;当前 Vortice 版本只有现代 .NET 产物。避免仅为删除一个依赖包而手写 JSON/schema 框架。 +4. 在所选运行时上执行自有桌面验收和共享服务生命周期检查,再更新源码准备和打包。检查通过后删除被替代的实现与依赖。此 Windows 运行时改动不扩展到共享 `cua` API 或 macOS 提供方。 + +当前桌面验收发现远程桌面客户端会在选定编辑器消费前预读剪贴板。待验证的修复会确认请求窗口所属进程,并为其他读取方继续延迟提供该格式。未携带 HWND 打开剪贴板的读取方无法归属,将超时。修订后的原生二进制已通过交叉编译,但本机 Smart App Control 阻止了它执行。分支交由用户在已获准的签名构建或测试环境中完成 Windows 验收。不能把此前的验收结果视为对该二进制的验证。 diff --git a/packages/experimental/cua-windows/native/capture-probe/app.manifest b/packages/experimental/cua-windows/native/capture-probe/app.manifest new file mode 100644 index 0000000000..64eb2db51c --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/app.manifest @@ -0,0 +1,12 @@ + + + + + + + + + PerMonitorV2 + + + diff --git a/packages/experimental/cua-windows/native/capture-probe/run.ps1 b/packages/experimental/cua-windows/native/capture-probe/run.ps1 new file mode 100644 index 0000000000..4edba996d1 --- /dev/null +++ b/packages/experimental/cua-windows/native/capture-probe/run.ps1 @@ -0,0 +1,28 @@ +# Compile and run a private capture experiment using only the installed .NET Framework. +param( + [long]$WindowHandle = 0, + [string]$OutputDirectory = (Join-Path $env:TEMP ("dsh-capture-" + [guid]::NewGuid().ToString("N"))) +) +$ErrorActionPreference = "Stop" +$framework = Join-Path $env:WINDIR "Microsoft.NET\Framework64\v4.0.30319" +$build = Join-Path $PSScriptRoot ("..\..\.probe-build-" + [guid]::NewGuid().ToString("N")) +New-Item -ItemType Directory -Path $build | Out-Null +try { + $executable = Join-Path $build "CaptureProbe.exe" + $compilerArguments = @("/nologo", "/target:exe", "/platform:x64", "/out:$executable", + ("/win32manifest:" + (Join-Path $PSScriptRoot "app.manifest")), + "/r:System.Drawing.dll", "/r:System.Windows.Forms.dll", "/r:System.Web.Extensions.dll", + "/r:$framework\WPF\UIAutomationClient.dll", "/r:$framework\WPF\UIAutomationTypes.dll", + "/r:$framework\WPF\WindowsBase.dll", (Join-Path $PSScriptRoot "CaptureProbe.cs")) + $compiler = Start-Process (Join-Path $framework "csc.exe") -NoNewWindow -Wait -PassThru ` + -ArgumentList ($compilerArguments | ForEach-Object { '"' + $_ + '"' }) + if ($compiler.ExitCode -ne 0) { throw "Capture probe compilation failed: $($compiler.ExitCode)" } + Copy-Item (Join-Path $PSScriptRoot "CaptureProbe.exe.config") "$executable.config" + $probeArguments = if ($WindowHandle -eq 0) { @("--demo", $OutputDirectory) } + else { @("--compare", $WindowHandle, $OutputDirectory) } + $probe = Start-Process $executable -NoNewWindow -Wait -PassThru ` + -ArgumentList ($probeArguments | ForEach-Object { '"' + $_ + '"' }) + if ($probe.ExitCode -ne 0) { throw "Capture probe failed; inspect $OutputDirectory" } + Write-Output "Capture evidence: $OutputDirectory" +} +finally { Remove-Item -LiteralPath $build -Recurse -Force } diff --git a/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj new file mode 100644 index 0000000000..cb0fda00a0 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/DesktopFixture.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0-windows + true + true + enable + enable + dsh-cua-desktop-fixture + true + true + + diff --git a/packages/experimental/cua-windows/native/desktop-tests/Program.cs b/packages/experimental/cua-windows/native/desktop-tests/Program.cs new file mode 100644 index 0000000000..ed6948f482 --- /dev/null +++ b/packages/experimental/cua-windows/native/desktop-tests/Program.cs @@ -0,0 +1,95 @@ +// Private desktop fixture: commands inspect or arrange only the windows owned by this process. +using System.Runtime.InteropServices; +using System.Text.Json; +using System.Security.Cryptography; +using System.Text; + +internal sealed class FixtureForm : Form +{ + protected override bool ShowWithoutActivation => true; + internal readonly TextBox Editor = new() { Name = "editor", AccessibleName = "CUA test text", Multiline = true, Bounds = new(20, 20, 440, 100) }; + private readonly Button button = new() { Name = "submit", Text = "Record click", Bounds = new(20, 140, 180, 40) }; + private int clicks; + private readonly ToolTip tooltip = new(); + + internal FixtureForm(string title) + { + Text = title; + StartPosition = FormStartPosition.Manual; + Location = new(100, 100); + ClientSize = new(500, 300); + Controls.Add(Editor); + Controls.Add(button); + button.Click += (_, _) => clicks++; + tooltip.SetToolTip(button, "CUA hover is retained"); + } + + internal object Inspect() => new + { + text = Editor.Text, clicks, window = Handle.ToInt64(), foreground = GetForegroundWindow().ToInt64(), + cursor = new { x = Cursor.Position.X, y = Cursor.Position.Y }, + button = new { x = button.Left + button.Width / 2, y = button.Top + button.Height / 2 }, + selection = new { start = Editor.SelectionStart, length = Editor.SelectionLength }, + buttons = MouseButtons.ToString(), minimized = WindowState == FormWindowState.Minimized, visible = Visible, + }; + + protected override void Dispose(bool disposing) + { + if (disposing) tooltip.Dispose(); + base.Dispose(disposing); + } + + [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); +} + +internal static class Program +{ + private static void Write(object value) { Console.WriteLine(JsonSerializer.Serialize(value)); Console.Out.Flush(); } + + [STAThread] + private static void Main() + { + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + Application.EnableVisualStyles(); + using var form = new FixtureForm("DSH CUA owned test window"); + using var sibling = new FixtureForm("DSH CUA sibling test window"); + form.Shown += (_, _) => + { + Write(new { pid = Environment.ProcessId, state = form.Inspect() }); + _ = Task.Run(() => + { + while (Console.ReadLine() is { } command) + { + form.Invoke(() => + { + switch (command) + { + case "sibling": sibling.Show(); sibling.Activate(); sibling.Editor.Focus(); Write(sibling.Inspect()); break; + case "inspect": Write(form.Inspect()); break; + case "focus": form.Activate(); form.Editor.Focus(); Write(form.Inspect()); break; + case "minimize": form.WindowState = FormWindowState.Minimized; Write(form.Inspect()); break; + case "hide": form.Hide(); Write(form.Inspect()); break; + case "resize": form.Width += 50; Write(form.Inspect()); break; + case "clipboard-digest": + Write(new { digest = Convert.ToHexString(SHA256.HashData(Encoding.Unicode.GetBytes(Clipboard.GetText()))) }); + break; + case "close": form.Close(); break; + default: + if (command.StartsWith("allow:", StringComparison.Ordinal) && uint.TryParse(command[6..], out var pid)) + Write(new { allowed = AllowSetForegroundWindow(pid) }); + else Write(new { error = "Unknown fixture command" }); + break; + } + }); + if (command == "close") return; + } + if (!form.IsDisposed) form.BeginInvoke(form.Close); + }); + }; + Application.Run(form); + } + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AllowSetForegroundWindow(uint processId); +} diff --git a/packages/experimental/cua-windows/native/generate-protocol.ts b/packages/experimental/cua-windows/native/generate-protocol.ts new file mode 100644 index 0000000000..3a23f8140f --- /dev/null +++ b/packages/experimental/cua-windows/native/generate-protocol.ts @@ -0,0 +1,9 @@ +/** Generate Windows native admission from the shared CUA operation definitions. */ +import { readFile, writeFile } from 'node:fs/promises' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' + +const path = new URL('protocol.schema.json', import.meta.url) +const content = nativeProtocol().json +if (process.argv.includes('--check')) { + if (await readFile(path, 'utf8') !== content) throw new Error('Stale Windows CUA native request schema') +} else await writeFile(path, content) diff --git a/packages/experimental/cua-windows/native/packages.lock.json b/packages/experimental/cua-windows/native/packages.lock.json new file mode 100644 index 0000000000..dee2e0c44b --- /dev/null +++ b/packages/experimental/cua-windows/native/packages.lock.json @@ -0,0 +1,95 @@ +{ + "version": 1, + "dependencies": { + "net10.0-windows10.0.19041": { + "Microsoft.NET.ILLink.Tasks": { + "type": "Direct", + "requested": "[10.0.14, )", + "resolved": "10.0.14", + "contentHash": "YlTamXppEQls6DYWt7RdUuwWDb0lyw/vXCaGeQpLCpsLmfwGuCkOz/vIGgMTV7ECsJcavkCOkxZXv9s8rdAHkQ==" + }, + "Vortice.Direct3D11": { + "type": "Direct", + "requested": "[3.8.3, )", + "resolved": "3.8.3", + "contentHash": "JgFUswu2mgrSwcd0KRF2AnfeE5VbMEgcicmxPD1g2yXyomPIHbnX3wldBNHPOzzD0URC1WJ/pO1ymfi3imZwvg==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DXGI": "3.8.3" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "SharpGen.Runtime": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "niTtWAUov1F7wZGAlVeEvW+Tnqvg5yTmhI7rxmYu2Utoyu2TbC9tWWpUpMs0PQg5lu5svoYpCAztNjxCqMFP/w==" + }, + "SharpGen.Runtime.COM": { + "type": "Transitive", + "resolved": "2.4.2-beta", + "contentHash": "9lxDFMiepqo3lJQzMSjECCIONeCc2f3Drokgj6HtrTLZcJSftNgcLbD6/iXYj2iphkwgrZb1oLsDOZxoFZkawQ==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta" + } + }, + "Vortice.DirectX": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "nKwSavv0w5rDF7prSefqAVPDcTyqrfZxKFMVfttiXPfm62VdA/1d+b3PhCZpW4xO7jXczXDwjQdWgD1zGsvM8w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "SharpGen.Runtime.COM": "2.4.2-beta", + "Vortice.Mathematics": "2.1.0" + } + }, + "Vortice.DXGI": { + "type": "Transitive", + "resolved": "3.8.3", + "contentHash": "MbAUnTeQ6WD99ctAdrj5CQO2I7oaax0Kt2eVdWSUj0bYP9Ed0726+s7dIHe4+tqhpmINW/dcPt0mNtc72o+E0w==", + "dependencies": { + "SharpGen.Runtime": "2.4.2-beta", + "Vortice.DirectX": "3.8.3" + } + }, + "Vortice.Mathematics": { + "type": "Transitive", + "resolved": "2.1.0", + "contentHash": "KK+SjNSuKdP+zbavekubi+vaeb1Jo4k87ZF6CMkVWjr6RjJwc8peVtmgzXXDIMy4ZC3ZISyk3llY3q65ISOkBQ==" + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + }, + "net10.0-windows10.0.19041/win-arm64": {}, + "net10.0-windows10.0.19041/win-x64": {} + } +} \ No newline at end of file diff --git a/packages/experimental/cua-windows/native/protocol.schema.json b/packages/experimental/cua-windows/native/protocol.schema.json new file mode 100644 index 0000000000..c25c65c1e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol.schema.json @@ -0,0 +1,1414 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$comment": "Generated from the shared CUA operation schema. Do not edit.", + "title": "dsh-cua native request", + "description": "Host resource fields and private continuations are not model tool parameters. App handles and snapshots belong to one helper; coordinates use window-local native units.", + "oneOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getCapabilities" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listApps" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "findApps" + }, + "params": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "maxAppMatches": { + "type": "integer", + "minimum": 1, + "maximum": 1000 + } + }, + "required": [ + "query", + "maxAppMatches" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getApp" + }, + "params": { + "type": "object", + "properties": { + "selector": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "selector" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "activate" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "show" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listWindows" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "getState" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "includeMenus": { + "description": "Expand menu contents; omitted or false shows menu-bar entries only.", + "type": "boolean" + }, + "details": { + "description": "Include identifiers, global native bounds and complete action names.", + "type": "boolean" + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "listActions" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "performAction" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "action": { + "type": "string", + "minLength": 1 + }, + "argument": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "action" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:performAction" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "invoke" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "mouseMove" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "click" + }, + "params": { + "anyOf": [ + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "clickCount": { + "anyOf": [ + { + "type": "number", + "const": 1 + }, + { + "type": "number", + "const": 2 + } + ] + }, + "holdMs": { + "description": "Milliseconds between each mouse press and release; omitted for an ordinary click.", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "setValue" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "value": { + "$ref": "#/$defs/__schema0" + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "value" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + } + }, + "$id": "urn:deepseek-harness:cua:request:setValue" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "selectText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "elementId": { + "type": "string", + "minLength": 1, + "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "text": { + "type": "string", + "minLength": 1 + }, + "prefix": { + "type": "string" + }, + "suffix": { + "type": "string" + }, + "selectionType": { + "type": "string", + "enum": [ + "text", + "cursor_before", + "cursor_after" + ] + } + }, + "required": [ + "appHandle", + "snapshotId", + "elementId", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "typeText" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + } + }, + "required": [ + "appHandle", + "text" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "paste" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "text": { + "type": "string" + }, + "format": { + "type": "string", + "enum": [ + "text", + "html" + ] + }, + "maxClipboardBytes": { + "type": "integer", + "minimum": 1024, + "maximum": 9007199254740991 + }, + "pasteReadTimeoutMs": { + "type": "integer", + "minimum": 1, + "maximum": 2147483647 + }, + "maxElements": { + "type": "integer", + "minimum": 1, + "maximum": 10000 + }, + "maxDepth": { + "type": "integer", + "minimum": 1, + "maximum": 100 + } + }, + "required": [ + "appHandle", + "text", + "maxClipboardBytes", + "pasteReadTimeoutMs", + "maxElements", + "maxDepth" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "pressKey" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "modifiers": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "appHandle", + "key" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "sendKeyEvent" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "key": { + "type": "string", + "minLength": 1 + }, + "direction": { + "type": "string", + "enum": [ + "down", + "up" + ] + } + }, + "required": [ + "appHandle", + "key", + "direction" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "scroll" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "x": { + "type": "number", + "minimum": 0 + }, + "y": { + "type": "number", + "minimum": 0 + }, + "deltaLinesX": { + "type": "integer", + "minimum": -10, + "maximum": 10 + }, + "deltaLinesY": { + "type": "integer", + "minimum": -10, + "maximum": 10 + } + }, + "required": [ + "appHandle", + "windowId", + "x", + "y", + "deltaLinesX", + "deltaLinesY" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "drag" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + }, + "mouseButton": { + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "command", + "control", + "option", + "shift", + "fn" + ] + } + }, + "snapshotId": { + "type": "string", + "minLength": 1 + }, + "fromX": { + "type": "number", + "minimum": 0 + }, + "fromY": { + "type": "number", + "minimum": 0 + }, + "toX": { + "type": "number", + "minimum": 0 + }, + "toY": { + "type": "number", + "minimum": 0 + }, + "durationMs": { + "type": "integer", + "minimum": 1, + "maximum": 5000 + }, + "steps": { + "type": "integer", + "minimum": 1, + "maximum": 240 + } + }, + "required": [ + "appHandle", + "windowId", + "fromX", + "fromY", + "toX", + "toY", + "durationMs", + "steps" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "screenshot" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + }, + "windowId": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 4294967295 + } + }, + "required": [ + "appHandle", + "windowId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "launchApp" + }, + "params": { + "type": "object", + "properties": { + "appHandle": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "appHandle" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "permissionStatus" + }, + "params": { + "type": "object", + "properties": {}, + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "applicationIcons" + }, + "params": { + "type": "object", + "properties": { + "paths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "paths" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "requestPermission" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "openPermissionSettings" + }, + "params": { + "type": "object", + "properties": { + "permission": { + "type": "string", + "enum": [ + "accessibility", + "screenRecording" + ] + } + }, + "required": [ + "permission" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + } + ] +} diff --git a/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs new file mode 100644 index 0000000000..35c6acdb75 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/AccessibilityText.cs @@ -0,0 +1,74 @@ +// Formatting owns no native references or snapshot indices. +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public sealed record AccessibilityNode +{ + public required string Role { get; init; } + public string Name { get; init; } = ""; + public string? Subrole { get; init; } + public string? Help { get; init; } + public string? Identifier { get; init; } + public string? Value { get; init; } + public string? Placeholder { get; init; } + public bool HasValue { get; init; } + public bool? Enabled { get; init; } + public bool? Focused { get; init; } + public bool? Selected { get; init; } + public bool? Expanded { get; init; } + public string? ValueWritable { get; init; } + public bool? SelectionWritable { get; init; } + public bool HasSelection { get; init; } + public TextMatch? Selection { get; init; } + public string? SelectedText { get; init; } + public string[] Actions { get; init; } = []; + public (double X, double Y, double Width, double Height)? Bounds { get; init; } +} + +public static class AccessibilityText +{ + private static string Quote(string value) => JsonSerializer.Serialize(value, WireJson.Options); + + public static bool Retain(AccessibilityNode node) => node.Role is not ("AXGroup" or "AXScrollArea") + || node.Name.Length != 0 || !string.IsNullOrEmpty(node.Help) || node.HasValue || node.Actions.Length != 0 + || node.Enabled == false || node.Focused == true || node.Selected.HasValue || node.Expanded.HasValue; + + public static string Format(AccessibilityNode node, int? index, bool details) + { + var text = new StringBuilder("- "); + if (index is { } number) text.Append('[').Append(number).Append("] "); + text.Append(node.Role); + if (node.Subrole is { Length: > 0 } subrole) text.Append(" subrole=").Append(Quote(subrole)); + if (node.Enabled == false) text.Append(" disabled"); + if (node.Focused == true) text.Append(" focused"); + if (node.Selected is { } selected) text.Append(" selected=").Append(selected ? "true" : "false"); + if (node.Expanded is { } expanded) text.Append(" expanded=").Append(expanded ? "true" : "false"); + if (node.ValueWritable is { } writable) text.Append(" valueWritable=").Append(writable); + if (node.SelectionWritable is { } selectionWritable) text.Append(" selectionWritable=").Append(selectionWritable ? "true" : "false"); + if (node.Name.Length != 0) text.Append(' ').Append(Quote(node.Name)); + if (node.HasValue) text.Append(" = ").Append(node.Value is { } value ? Quote(value) : "unavailable"); + if (node.Placeholder is { } placeholder) text.Append(" placeholder=").Append(Quote(placeholder)); + if (node.Help is { Length: > 0 } help && help != node.Name) text.Append(" help=").Append(Quote(help)); + if (node.HasSelection) + { + if (node.Selection is { } range && node.Value is { } value && range.Start >= 0 && range.Length >= 0 + && range.Start <= value.Length - range.Length) + text.Append(" selection=[").Append(range.Start).Append(',').Append(range.Length).Append(']'); + else text.Append(" selection=unavailable"); + if (node.SelectedText is { Length: > 0 } selectedText) text.Append(" selectedText=").Append(Quote(selectedText)); + } + var actions = details ? node.Actions : node.Actions.Where(action => action is not ("Press" or "Pick" or "ScrollToVisible")).ToArray(); + if (actions.Length != 0) text.Append(" actions=[").Append(string.Join(", ", actions.Select(Quote))).Append(']'); + if (details) + { + if (!string.IsNullOrEmpty(node.Identifier)) text.Append(" id=").Append(Quote(node.Identifier)); + if (index.HasValue && node.Bounds is { } bounds) + text.Append(" bounds=[").Append(string.Join(',', new[] { bounds.X, bounds.Y, bounds.Width, bounds.Height } + .Select(number => number.ToString("G", CultureInfo.InvariantCulture)))).Append(']'); + } + return text.ToString(); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj new file mode 100644 index 0000000000..353ac1afa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/CuaProtocol.csproj @@ -0,0 +1,14 @@ + + + net10.0 + enable + enable + true + win-x64;win-arm64 + false + + + + + + diff --git a/packages/experimental/cua-windows/native/protocol/KeyChord.cs b/packages/experimental/cua-windows/native/protocol/KeyChord.cs new file mode 100644 index 0000000000..74d375ab35 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/KeyChord.cs @@ -0,0 +1,25 @@ +namespace DeepSeek.Cua.Protocol; + +public sealed record KeyChord(string Key, string[] Modifiers) +{ + public static KeyChord Parse(string text, IEnumerable extra) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key name is required"); + var plus = text == "+" || text.EndsWith("++", StringComparison.Ordinal); + var parts = plus ? text[..^1].TrimEnd('+').Split('+', StringSplitOptions.RemoveEmptyEntries) : text.Split('+'); + var key = plus ? "+" : parts[^1]; + if (key.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "A key chord must end with a key"); + var modifiers = (plus ? parts : parts[..^1]).Concat(extra).Select(NormalizeModifier).Distinct().ToArray(); + return new(key, modifiers); + } + + public static string NormalizeModifier(string value) => value.ToLowerInvariant() switch + { + "control" or "ctrl" => "control", + "shift" => "shift", + "option" or "alt" => "option", + "command" or "cmd" or "meta" or "win" or "windows" => "command", + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows has no general Fn-key injection; use an available application action"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs new file mode 100644 index 0000000000..fe3fe18efc --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeControlFrame.cs @@ -0,0 +1,23 @@ +// Connection controls never enter the model operation schema. +using System.Text.Json; + +namespace DeepSeek.Cua.Protocol; + +public enum NativeControl { Close, Cancel, CompletedCancel } + +/// Cancellation matches the latest request; a late cancellation after its completion is a no-op. +public static class NativeControlFrame +{ + public static NativeControl Parse(JsonElement value, string? requestId, bool completed = false) + { + if (value.ValueKind != JsonValueKind.Object || !value.TryGetProperty("type", out var type) + || type.ValueKind != JsonValueKind.String) + throw new NativeFailure("INVALID_REQUEST", "Expected a native connection control"); + if (type.GetString() == "close" && value.EnumerateObject().Count() == 1) return NativeControl.Close; + if (type.GetString() == "cancel" && value.EnumerateObject().Count() == 2 + && value.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.String + && !string.IsNullOrEmpty(requestId) && id.GetString() == requestId) + return completed ? NativeControl.CompletedCancel : NativeControl.Cancel; + throw new NativeFailure("INVALID_REQUEST", "Cancellation requires a matching request; close accepts no fields"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/NativeRequest.cs b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs new file mode 100644 index 0000000000..8cdd6a3293 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/NativeRequest.cs @@ -0,0 +1,99 @@ +// Strict JSONL admission shares the TypeScript operation schema with the macOS provider. +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using Json.Schema; + +namespace DeepSeek.Cua.Protocol; + +/// A native refusal whose code remains visible through the shared CUA client. +public sealed class NativeFailure(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} + +/// Wire encoding preserves readable task text and always emits one JSON value per line. +public static class WireJson +{ + public static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + public static readonly UTF8Encoding Utf8 = new(false, true); + + public static JsonElement Parse(string text) + { + using var document = JsonDocument.Parse(text); + RejectDuplicates(document.RootElement); + return document.RootElement.Clone(); + } + + private static void RejectDuplicates(JsonElement value) + { + if (value.ValueKind == JsonValueKind.Object) + { + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in value.EnumerateObject()) + { + if (!names.Add(property.Name)) throw new NativeFailure("INVALID_REQUEST", "Repeated JSON property"); + RejectDuplicates(property.Value); + } + } + else if (value.ValueKind == JsonValueKind.Array) + foreach (var item in value.EnumerateArray()) RejectDuplicates(item); + } +} + +/// Validated operation parameters. Resource fields are supplied only by the Host. +public sealed record NativeRequest(string Id, string Method, JsonElement Params) +{ + private static readonly JsonSchema Schema = LoadSchema(); + + private static JsonSchema LoadSchema() + { + using var stream = typeof(NativeRequest).Assembly.GetManifestResourceStream("DeepSeek.Cua.NativeRequestSchema.json") + ?? throw new InvalidOperationException("The native request schema is missing"); + using var reader = new StreamReader(stream, WireJson.Utf8); + return JsonSchema.FromText(reader.ReadToEnd()); + } + + public static NativeRequest Parse(JsonElement value) + { + if (!Schema.Evaluate(value, new EvaluationOptions { OutputFormat = OutputFormat.Flag }).IsValid) + throw new NativeFailure("INVALID_ARGUMENT", "The request does not match the CUA operation schema"); + return new(value.GetProperty("id").GetString()!, value.GetProperty("method").GetString()!, value.GetProperty("params")); + } +} + +/// Reads bounded UTF-8 frames without allowing an unterminated line to grow without limit. +public sealed class FrameReader(Stream stream) +{ + private readonly byte[] buffer = new byte[4096]; + private int start; + private int end; + + public async Task ReadAsync(int maximumBytes, CancellationToken cancellation) + { + using var line = new MemoryStream(); + while (true) + { + if (start == end) + { + end = await stream.ReadAsync(buffer, cancellation); + start = 0; + if (end == 0) + { + if (line.Length != 0) throw new NativeFailure("INVALID_REQUEST", "Native input ended inside a frame"); + return null; + } + } + var newline = Array.IndexOf(buffer, (byte)'\n', start, end - start); + var count = (newline < 0 ? end : newline + 1) - start; + if (line.Length + count > maximumBytes) throw new NativeFailure("NATIVE_REQUEST_LIMIT", "Request exceeded its byte limit"); + line.Write(buffer, start, count); + start += count; + if (newline >= 0) return WireJson.Utf8.GetString(line.GetBuffer(), 0, checked((int)line.Length - 1)); + } + } +} diff --git a/packages/experimental/cua-windows/native/protocol/TextSelection.cs b/packages/experimental/cua-windows/native/protocol/TextSelection.cs new file mode 100644 index 0000000000..251474b5ab --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/TextSelection.cs @@ -0,0 +1,49 @@ +// Literal selection and CF_HTML encoding are independent of Windows UI Automation. +using System.Globalization; +using System.Text; + +namespace DeepSeek.Cua.Protocol; + +public readonly record struct TextMatch(int Start, int Length); + +public static class TextSelection +{ + /// Find one literal UTF-16 range, with immediately adjacent optional context. + public static TextMatch Find(string value, string text, string? prefix, string? suffix) + { + if (text.Length == 0) throw new NativeFailure("INVALID_ARGUMENT", "Selection text must not be empty"); + TextMatch? selected = null; + for (var offset = 0; offset <= value.Length - text.Length;) + { + var start = value.IndexOf(text, offset, StringComparison.Ordinal); + if (start < 0) break; + var end = start + text.Length; + var before = prefix is null || (start >= prefix.Length && value.AsSpan(start - prefix.Length, prefix.Length).SequenceEqual(prefix)); + var after = suffix is null || (end + suffix.Length <= value.Length && value.AsSpan(end, suffix.Length).SequenceEqual(suffix)); + if (before && after) + { + if (selected is not null) throw new NativeFailure("AMBIGUOUS_TEXT", "Add immediately adjacent prefix or suffix text"); + selected = new(start, text.Length); + } + offset = start + 1; + } + return selected ?? throw new NativeFailure("TEXT_NOT_FOUND", "Read fresh state before selecting text"); + } +} + +public static class HtmlClipboard +{ + /// CF_HTML offsets count UTF-8 bytes, independently of UTF-16 selection offsets. + public static byte[] Encode(string fragment) + { + const string before = ""; + const string after = ""; + const string template = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\n"; + var headerSize = Encoding.UTF8.GetByteCount(string.Format(CultureInfo.InvariantCulture, template, 0, 0, 0, 0)); + var start = headerSize + Encoding.UTF8.GetByteCount(before); + var end = start + Encoding.UTF8.GetByteCount(fragment); + var header = string.Format(CultureInfo.InvariantCulture, template, headerSize, + end + Encoding.UTF8.GetByteCount(after), start, end); + return Encoding.UTF8.GetBytes(header + before + fragment + after + "\0"); + } +} diff --git a/packages/experimental/cua-windows/native/protocol/packages.lock.json b/packages/experimental/cua-windows/native/protocol/packages.lock.json new file mode 100644 index 0000000000..4118720b93 --- /dev/null +++ b/packages/experimental/cua-windows/native/protocol/packages.lock.json @@ -0,0 +1,37 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "JsonSchema.Net": { + "type": "Direct", + "requested": "[9.4.0, )", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + } + }, + "net10.0/win-arm64": {}, + "net10.0/win-x64": {} + } +} diff --git a/packages/experimental/cua-windows/native/src/Accessibility.cs b/packages/experimental/cua-windows/native/src/Accessibility.cs new file mode 100644 index 0000000000..f1068643f2 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Accessibility.cs @@ -0,0 +1,245 @@ +// One traversal owns both the disclosed indices and their retained UI Automation elements. +using System.Globalization; +using System.Text; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ElementReference(AutomationElement Element, WindowState Window); +internal sealed record Snapshot(string Id, uint Scope, WindowState[] Windows, IReadOnlyDictionary Elements); + +internal static class Accessibility +{ + private static readonly AutomationProperty[] Properties = [ + AutomationElement.ControlTypeProperty, AutomationElement.NameProperty, AutomationElement.HelpTextProperty, + AutomationElement.AutomationIdProperty, AutomationElement.ClassNameProperty, AutomationElement.IsEnabledProperty, + AutomationElement.HasKeyboardFocusProperty, AutomationElement.IsKeyboardFocusableProperty, AutomationElement.IsPasswordProperty, + AutomationElement.BoundingRectangleProperty, AutomationElement.IsInvokePatternAvailableProperty, + AutomationElement.IsValuePatternAvailableProperty, AutomationElement.IsRangeValuePatternAvailableProperty, + AutomationElement.IsTextPatternAvailableProperty, AutomationElement.IsSelectionItemPatternAvailableProperty, + AutomationElement.IsTogglePatternAvailableProperty, AutomationElement.IsExpandCollapsePatternAvailableProperty, + AutomationElement.IsScrollItemPatternAvailableProperty, ValuePattern.ValueProperty, ValuePattern.IsReadOnlyProperty, + RangeValuePattern.ValueProperty, RangeValuePattern.IsReadOnlyProperty, SelectionItemPattern.IsSelectedProperty, + TogglePattern.ToggleStateProperty, ExpandCollapsePattern.ExpandCollapseStateProperty, + ]; + + internal static object State(AppState app, uint selected, int maximumElements, int maximumDepth, + bool includeMenus, bool details, RequestContext context) + { + var all = Windows.Refresh(app, context); + var targets = new[] { all.SingleOrDefault(window => window.Id == selected) + ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window") }; + var rows = new List { "AX scope=window offsets=UTF-16" }; + var elements = new Dictionary(); + var observations = new List<(WindowState Window, WindowGeometry Geometry)>(); + var visited = new HashSet(StringComparer.Ordinal); + var cache = new CacheRequest { AutomationElementMode = AutomationElementMode.Full, TreeScope = TreeScope.Element }; + foreach (var property in Properties) cache.Add(property); + var truncated = false; + var count = 0; + var nextIndex = 0; + var bytes = Encoding.UTF8.GetByteCount(rows[0]); + void Add(string row) + { + bytes += Encoding.UTF8.GetByteCount(row) + 1; + if (bytes > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Accessibility text exceeds the response limit; select a narrower window or reduce traversal limits"); + rows.Add(row); + } + foreach (var window in targets) + { + if (count >= maximumElements) { truncated = true; break; } + var geometry = window.Geometry(app, context); + try + { + var root = context.Ax(() => AutomationElement.FromHandle(window.Handle).GetUpdatedCache(cache)); + Walk(root, window, geometry, 0, 0); + } + catch (ElementNotAvailableException) { throw new NativeFailure("STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state without repeating input"); } + var after = window.Geometry(app, context); + if (after.Pixels.Width != geometry.Pixels.Width || after.Pixels.Height != geometry.Pixels.Height || after.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during AX observation; read fresh state"); + observations.Add((window, after)); + } + if (truncated) Add($"[truncated: maxElements={maximumElements}, maxDepth={maximumDepth}]"); + DesktopSession.RequireInteractive(); + var scope = selected; + var snapshot = new Snapshot(Guid.NewGuid().ToString("N"), scope, targets, elements); + var result = new + { + appHandle = app.Handle, pid = 4, windowId = selected, + focusedWindowId = (uint?)Windows.Focused(app, all)?.Id, + snapshotId = snapshot.Id, tree = string.Join('\n', rows), windows = all.Select(window => window.Describe(app, context)).ToArray(), truncated, + }; + context.Check(); + app.Snapshots[scope] = snapshot; + foreach (var observation in observations) observation.Window.Observe(observation.Geometry); + return result; + + void Walk(AutomationElement element, WindowState window, WindowGeometry geometry, int depth, int indent) + { + context.Check(); + if (count >= maximumElements || depth >= maximumDepth) { truncated = true; return; } + count++; + if (!visited.Add(string.Join(',', context.Ax(element.GetRuntimeId)))) return; + var node = Read(element, window, geometry, context); + var retained = AccessibilityText.Retain(node); + if (retained) + { + int? index = null; + if (node.Enabled != false && (node.Actions.Length != 0 || node.ValueWritable == "true" || node.SelectionWritable == true)) + { + index = nextIndex++; + elements.Add(index.Value, new(element, window)); + } + Add(new string(' ', indent * 2) + AccessibilityText.Format(node, index, details)); + } + if (!includeMenus && node.Role == "AXMenu") + { + Add(new string(' ', (indent + 1) * 2) + "[menu contents omitted; includeMenus:true]"); + return; + } + var first = context.Ax(() => TreeWalker.ControlViewWalker.GetFirstChild(element, cache)); + if (first is not null && depth + 1 >= maximumDepth) { truncated = true; return; } + for (var child = first; child is not null; + child = context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache))) + { + Walk(child, window, geometry, depth + 1, indent + (retained ? 1 : 0)); + if (count >= maximumElements) + { + if (context.Ax(() => TreeWalker.ControlViewWalker.GetNextSibling(child, cache)) is not null) truncated = true; + break; + } + } + } + } + + private static object Property(AutomationElement element, AutomationProperty property) => element.GetCachedPropertyValue(property, true); + private static bool Flag(AutomationElement element, AutomationProperty property) => Property(element, property) is true; + private static string Text(AutomationElement element, AutomationProperty property) => Property(element, property) as string ?? ""; + + private static AccessibilityNode Read(AutomationElement element, WindowState window, WindowGeometry geometry, RequestContext context) + { + var type = Property(element, AutomationElement.ControlTypeProperty) as ControlType ?? ControlType.Custom; + var actions = new List(); + if (Flag(element, AutomationElement.IsInvokePatternAvailableProperty)) actions.Add("Press"); + if (Flag(element, AutomationElement.IsTogglePatternAvailableProperty)) actions.Add("Toggle"); + if (Flag(element, AutomationElement.IsSelectionItemPatternAvailableProperty)) actions.Add("Pick"); + if (Flag(element, AutomationElement.IsExpandCollapsePatternAvailableProperty)) { actions.Add("Expand"); actions.Add("Collapse"); } + if (Flag(element, AutomationElement.IsScrollItemPatternAvailableProperty)) actions.Add("ScrollToVisible"); + if (Flag(element, AutomationElement.IsKeyboardFocusableProperty)) actions.Add("Focus"); + if (type == ControlType.Window) actions.Add("Raise"); + var password = Flag(element, AutomationElement.IsPasswordProperty); + string? value = null; + var hasValue = false; + string? writable = type == ControlType.Edit || type == ControlType.Document ? "unknown" : null; + if (Flag(element, AutomationElement.IsValuePatternAvailableProperty)) + { + hasValue = true; + if (!password) value = Property(element, ValuePattern.ValueProperty) as string; + writable = Property(element, ValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Flag(element, AutomationElement.IsRangeValuePatternAvailableProperty)) + { + hasValue = true; + if (Property(element, RangeValuePattern.ValueProperty) is double number) value = number.ToString("G", CultureInfo.InvariantCulture); + writable = Property(element, RangeValuePattern.IsReadOnlyProperty) is bool readOnly ? readOnly ? "false" : "true" : "unknown"; + } + else if (Property(element, TogglePattern.ToggleStateProperty) is ToggleState toggle) + { + hasValue = true; value = toggle == ToggleState.Indeterminate ? "mixed" : toggle == ToggleState.On ? "true" : "false"; + } + bool? selectionWritable = null; + var hasSelection = false; + TextMatch? selection = null; + string? selectedText = null; + if (!password && Flag(element, AutomationElement.IsTextPatternAvailableProperty)) + { + var text = context.Ax(() => (TextPattern)element.GetCurrentPattern(TextPattern.Pattern)); + var document = context.Ax(() => text.DocumentRange); + value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + hasValue = true; + selectionWritable = context.Ax(() => text.SupportedTextSelection) != SupportedTextSelection.None; + hasSelection = true; + var ranges = context.Ax(text.GetSelection); + if (ranges.Length == 1) + { + var prefix = context.Ax(document.Clone); + context.Ax(() => { prefix.MoveEndpointByRange(TextPatternRangeEndpoint.End, ranges[0], TextPatternRangeEndpoint.Start); return true; }); + var start = context.Ax(() => prefix.GetText(context.Config.MaxResponseBytes)).Length; + selectedText = context.Ax(() => ranges[0].GetText(context.Config.MaxResponseBytes)); + selection = new(start, selectedText.Length); + } + } + var role = Role(type, password, value); + var bounds = Property(element, AutomationElement.BoundingRectangleProperty) is System.Windows.Rect rectangle && !rectangle.IsEmpty + ? ((double, double, double, double)?)(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height) : null; + var expanded = Property(element, ExpandCollapsePattern.ExpandCollapseStateProperty) is ExpandCollapseState state + ? state == ExpandCollapseState.Expanded ? true : state == ExpandCollapseState.Collapsed ? false : (bool?)null : null; + return new() + { + Role = role, Name = Text(element, AutomationElement.NameProperty), Help = Text(element, AutomationElement.HelpTextProperty), + Identifier = Text(element, AutomationElement.AutomationIdProperty), Subrole = type == ControlType.Custom ? Text(element, AutomationElement.ClassNameProperty) : null, + Value = value, HasValue = hasValue, ValueWritable = writable, + Enabled = Property(element, AutomationElement.IsEnabledProperty) as bool?, Focused = Property(element, AutomationElement.HasKeyboardFocusProperty) as bool?, + Selected = Property(element, SelectionItemPattern.IsSelectedProperty) as bool?, Expanded = expanded, + HasSelection = hasSelection, Selection = selection, SelectedText = selectedText, SelectionWritable = selectionWritable, + Actions = actions.ToArray(), Bounds = bounds, + }; + } + + private static string Role(ControlType type, bool password, string? value) + { + if (password) return "AXSecureTextField"; + if (type == ControlType.Edit) return value?.Contains('\n') == true ? "AXTextArea" : "AXTextField"; + if (type == ControlType.Document) return "AXTextArea"; + if (type == ControlType.Button) return "AXButton"; + if (type == ControlType.CheckBox) return "AXCheckBox"; + if (type == ControlType.RadioButton) return "AXRadioButton"; + if (type == ControlType.Text) return "AXStaticText"; + if (type == ControlType.Window) return "AXWindow"; + if (type == ControlType.MenuBar) return "AXMenuBar"; + if (type == ControlType.Menu) return "AXMenu"; + if (type == ControlType.MenuItem) return "AXMenuItem"; + if (type == ControlType.ComboBox) return "AXComboBox"; + if (type == ControlType.List) return "AXList"; + if (type == ControlType.ListItem) return "AXRow"; + if (type == ControlType.Tree) return "AXOutline"; + if (type == ControlType.TreeItem) return "AXRow"; + if (type == ControlType.Tab) return "AXTabGroup"; + if (type == ControlType.TabItem) return "AXRadioButton"; + if (type == ControlType.Slider) return "AXSlider"; + if (type == ControlType.Spinner) return "AXIncrementor"; + if (type == ControlType.ScrollBar) return "AXScrollBar"; + if (type == ControlType.Image) return "AXImage"; + if (type == ControlType.Hyperlink) return "AXLink"; + if (type == ControlType.Table || type == ControlType.DataGrid) return "AXTable"; + return "AXGroup"; + } + + internal static ElementReference Element(AppState app, string snapshotId, string elementId, RequestContext context) + { + if (!int.TryParse(elementId, NumberStyles.None, CultureInfo.InvariantCulture, out var index)) + throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + Windows.Refresh(app, context); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before using element identifiers"); + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId) + ?? throw new NativeFailure("STALE_SNAPSHOT", "Read fresh AX state before using element identifiers"); + if (snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != selected.Id) + throw new NativeFailure("STALE_SNAPSHOT", "Use an observation from the selected window"); + if (!snapshot.Elements.TryGetValue(index, out var element)) throw new NativeFailure("INVALID_ELEMENT", "Use an elementId from this snapshot"); + element.Window.Geometry(app, context); + if (!context.Ax(() => element.Element.Current.IsEnabled)) throw new NativeFailure("ELEMENT_DISABLED", "The element is disabled"); + return element; + } + + internal static void RequireSnapshot(AppState app, string snapshotId, uint windowId) + { + var selected = app.SelectedWindow; + var snapshot = app.Snapshots.Values.SingleOrDefault(value => value.Id == snapshotId); + if (snapshot is null || selected is null || selected.Id != windowId + || snapshot.Windows.Length != 1 || snapshot.Windows[0].Id != windowId) + throw new NativeFailure("STALE_SNAPSHOT", "Use a fresh observation from the selected window"); + } +} diff --git a/packages/experimental/cua-windows/native/src/AccessibilityActions.cs b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs new file mode 100644 index 0000000000..ae21c9610f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/AccessibilityActions.cs @@ -0,0 +1,163 @@ +// Actions use retained UIA references only after snapshot and window validation. +using System.Globalization; +using System.Text.Json; +using System.Windows.Automation; +using System.Windows.Automation.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class AccessibilityActions +{ + private static T Pattern(AutomationElement element, AutomationPattern pattern, RequestContext context) where T : BasePattern + { + object? value = null; + if (!context.Ax(() => element.TryGetCurrentPattern(pattern, out value))) + throw new NativeFailure("UNSUPPORTED", "The control does not expose this accessibility action"); + return (T)value!; + } + + internal static string[] Actions(ElementReference reference, RequestContext context) + { + var element = reference.Element; + var actions = new List(); + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out _))) actions.Add("Press"); + if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out _))) actions.Add("Toggle"); + if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out _))) actions.Add("Pick"); + if (context.Ax(() => element.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out _))) { actions.Add("Expand"); actions.Add("Collapse"); } + if (context.Ax(() => element.TryGetCurrentPattern(ScrollItemPattern.Pattern, out _))) actions.Add("ScrollToVisible"); + if (context.Ax(() => element.Current.IsKeyboardFocusable)) actions.Add("Focus"); + if (context.Ax(() => element.Current.ControlType) == ControlType.Window) actions.Add("Raise"); + return actions.ToArray(); + } + + internal static void Perform(AppState app, ElementReference reference, string action, JsonElement? argument, RequestContext context) + { + if (argument is { } value && value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + throw new NativeFailure("INVALID_ARGUMENT", "This accessibility action does not accept an argument"); + Secondary(app, reference, action, context); + } + + internal static bool Invoke(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else return false; + return true; + } + + internal static bool Click(ElementReference reference, RequestContext context) + { + object? pattern = null; + var element = reference.Element; + if (context.Ax(() => element.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))) + context.Ax(() => { ((InvokePattern)pattern!).Invoke(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))) + context.Ax(() => { ((SelectionItemPattern)pattern!).Select(); return true; }); + else if (context.Ax(() => element.TryGetCurrentPattern(TogglePattern.Pattern, out pattern))) + context.Ax(() => { ((TogglePattern)pattern!).Toggle(); return true; }); + else return false; + return true; + } + + internal static void SetValue(ElementReference reference, JsonElement value, RequestContext context) + { + if (value.ValueKind is not (JsonValueKind.String or JsonValueKind.Number) + || value.ValueKind == JsonValueKind.Number && (!value.TryGetDouble(out var numeric) || !double.IsFinite(numeric))) + throw new NativeFailure("INVALID_ARGUMENT", "The value must be a string or a finite number"); + object? pattern = null; + if (context.Ax(() => reference.Element.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))) + { + var setter = (ValuePattern)pattern!; + if (context.Ax(() => setter.Current.IsReadOnly)) throw new NativeFailure("UNSUPPORTED", "The control value is read-only"); + var text = value.ValueKind == JsonValueKind.String + ? value.GetString()! : value.GetDouble().ToString("G", CultureInfo.InvariantCulture); + context.Ax(() => { setter.SetValue(text); return true; }); + return; + } + var number = double.NaN; + if (value.ValueKind == JsonValueKind.Number) { if (!value.TryGetDouble(out number)) number = double.NaN; } + else if (!double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out number)) number = double.NaN; + if (!double.IsFinite(number)) throw new NativeFailure("INVALID_ARGUMENT", "This control requires a finite numeric value"); + var range = Pattern(reference.Element, RangeValuePattern.Pattern, context); + var current = context.Ax(() => range.Current); + if (current.IsReadOnly || number < current.Minimum || number > current.Maximum) + throw new NativeFailure("UNSUPPORTED", "The control cannot accept this value"); + context.Ax(() => { range.SetValue(number); return true; }); + } + + internal static void Secondary(AppState app, ElementReference reference, string action, RequestContext context) + { + switch (action.ToLowerInvariant()) + { + case "press": + context.Ax(() => { Pattern(reference.Element, InvokePattern.Pattern, context).Invoke(); return true; }); + break; + case "pick": + context.Ax(() => { Pattern(reference.Element, SelectionItemPattern.Pattern, context).Select(); return true; }); + break; + case "toggle": + context.Ax(() => { Pattern(reference.Element, TogglePattern.Pattern, context).Toggle(); return true; }); + break; + case "expand": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Expand(); return true; }); + break; + case "collapse": + context.Ax(() => { Pattern(reference.Element, ExpandCollapsePattern.Pattern, context).Collapse(); return true; }); + break; + case "scrolltovisible": + context.Ax(() => { Pattern(reference.Element, ScrollItemPattern.Pattern, context).ScrollIntoView(); return true; }); + break; + case "focus": + context.Ax(() => { reference.Element.SetFocus(); return true; }); + break; + case "raise": + if (context.Ax(() => reference.Element.Current.ControlType) != ControlType.Window) + throw new NativeFailure("UNSUPPORTED", "Raise is available only on the observed window element"); + Windows.Activate(app, reference.Window, context); + break; + default: throw new NativeFailure("UNSUPPORTED", "Use an action name from a fresh details:true observation"); + } + } + + internal static void SelectText(ElementReference reference, string text, string? prefix, string? suffix, + string selectionType, RequestContext context) + { + var pattern = Pattern(reference.Element, TextPattern.Pattern, context); + if (context.Ax(() => pattern.SupportedTextSelection) == SupportedTextSelection.None) + throw new NativeFailure("UNSUPPORTED", "The control does not support text selection"); + var document = context.Ax(() => pattern.DocumentRange); + var value = context.Ax(() => document.GetText(context.Config.MaxResponseBytes)); + var expected = TextSelection.Find(value, text, prefix, suffix); + var search = context.Ax(document.Clone); + TextPatternRange? selected = null; + while (true) + { + context.Check(); + var found = context.Ax(() => search.FindText(text, false, false)); + if (found is null) break; + var before = context.Ax(document.Clone); + context.Ax(() => { before.MoveEndpointByRange(TextPatternRangeEndpoint.End, found, TextPatternRangeEndpoint.Start); return true; }); + if (context.Ax(() => before.GetText(context.Config.MaxResponseBytes)).Length == expected.Start) { selected = found; break; } + var oldStart = context.Ax(search.Clone); + context.Ax(() => { search.MoveEndpointByRange(TextPatternRangeEndpoint.Start, found, TextPatternRangeEndpoint.Start); + search.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1); return true; }); + if (context.Ax(() => search.CompareEndpoints(TextPatternRangeEndpoint.Start, oldStart, TextPatternRangeEndpoint.Start)) <= 0) break; + } + if (selected is null || context.Ax(() => selected.GetText(context.Config.MaxResponseBytes)) != text) + throw new NativeFailure("SELECTION_CHANGED", "The control text changed; read fresh state before selecting"); + if (selectionType == "cursor_before") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.Start); return true; }); + else if (selectionType == "cursor_after") + context.Ax(() => { selected.MoveEndpointByRange(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.End); return true; }); + context.Ax(() => { selected.Select(); return true; }); + var actual = context.Ax(pattern.GetSelection); + if (actual.Length != 1 || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.Start, selected, TextPatternRangeEndpoint.Start)) != 0 + || context.Ax(() => actual[0].CompareEndpoints(TextPatternRangeEndpoint.End, selected, TextPatternRangeEndpoint.End)) != 0) + throw new NativeFailure("SELECTION_CHANGED", "The control did not retain the requested selection; read fresh state"); + } +} diff --git a/packages/experimental/cua-windows/native/src/Applications.cs b/packages/experimental/cua-windows/native/src/Applications.cs new file mode 100644 index 0000000000..eff65c0497 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Applications.cs @@ -0,0 +1,291 @@ +// Application consent identifies the executable before any launch or UI observation. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.Win32; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record ApplicationIdentity(string Id, string Name, string ExecutablePath, bool Persistable); +internal sealed record RunningApplication(int Pid, long Started, string Path, string Name); +internal sealed record InstalledApplication(string Name, string Path); + +internal sealed class AppState(string handle, ApplicationIdentity authorization, string digest, RunningApplication? process) : IDisposable +{ + internal string Handle { get; } = handle; + internal WindowState? SelectedWindow { get; set; } + internal ApplicationIdentity Authorization { get; } = authorization; + internal string Digest { get; } = digest; + internal RunningApplication? Process { get; set; } = process; + internal Dictionary Windows { get; } = []; + internal Dictionary Snapshots { get; } = []; + private uint nextWindowId; + private System.Diagnostics.Process? owner; + internal uint AllocateWindowId() + { + if (nextWindowId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Select the application again to allocate new window identifiers"); + return ++nextWindowId; + } + internal RunningApplication RequireProcess() + { + var selected = Process ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Application launch requires Host authorization"); + try + { + owner ??= System.Diagnostics.Process.GetProcessById(selected.Pid); + if (owner.HasExited || Applications.Started(owner) != selected.Started) + throw new NativeFailure("STALE_APP", "Select the application again after its process changes"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "Select the application again after it exits"); } + return selected; + } + public void Dispose() { owner?.Dispose(); Snapshots.Clear(); Windows.Clear(); } +} + +internal static class Applications +{ + internal static object Icons(JsonElement parameters, RequestContext context) + { + var paths = parameters.GetProperty("paths"); + if (paths.ValueKind != JsonValueKind.Array) + throw new NativeFailure("INVALID_ARGUMENT", "paths must be an array"); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var element in paths.EnumerateArray()) + { + context.Check(); + if (element.ValueKind != JsonValueKind.String || string.IsNullOrEmpty(element.GetString())) + throw new NativeFailure("INVALID_ARGUMENT", "paths must contain nonempty strings"); + var path = element.GetString()!; + try + { + using var icon = System.Drawing.Icon.ExtractAssociatedIcon(path); + if (icon is null) continue; + using var original = icon.ToBitmap(); + using var bitmap = new System.Drawing.Bitmap(original, new System.Drawing.Size(64, 64)); + using var stream = new MemoryStream(); + bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); + result[path] = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray()); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or ArgumentException + or System.ComponentModel.Win32Exception) + { + // Missing or unreadable executable metadata has no icon; application access is unchanged. + } + } + return result; + } + + private static readonly int SessionId = CurrentSession(); + private static int CurrentSession() { using var process = System.Diagnostics.Process.GetCurrentProcess(); return process.SessionId; } + internal static long Started(System.Diagnostics.Process process) + { + if (!Win32.GetProcessTimes(process.SafeHandle, out var created, out _, out _, out _)) + throw new NativeFailure("STALE_APP", "The process lifetime is unavailable; select the application again"); + return created; + } + internal static string CanonicalPath(string path) + { + using var handle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + var capacity = Win32.GetFinalPathNameByHandle(handle, new StringBuilder(), 0, 0); + if (capacity == 0) throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path could not be resolved"); + var text = new StringBuilder(checked((int)capacity + 1)); + if (Win32.GetFinalPathNameByHandle(handle, text, (uint)text.Capacity, 0) == 0) + throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The executable path changed during selection"); + var resolved = text.ToString(); + return resolved.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase) + ? @"\\" + resolved[8..] : resolved.StartsWith(@"\\?\", StringComparison.Ordinal) ? resolved[4..] : resolved; + } + + internal static string Digest(string path) + { + using var file = File.OpenRead(path); + return Convert.ToHexStringLower(SHA256.HashData(file)); + } + + private static string? VerifiedSigner(string path) + { + var file = new Win32.TrustFile { Size = (uint)Marshal.SizeOf(), Path = path }; + var memory = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(file, memory, false); + var data = new Win32.TrustData + { + Size = (uint)Marshal.SizeOf(), UiChoice = 2, UnionChoice = 1, + File = memory, StateAction = 1, ProviderFlags = 0x1000 | 0x80, + }; + var action = new Guid("00AAC56B-CD44-11D0-8CC2-00C04FC295EE"); + try + { + if (Win32.WinVerifyTrust(0, ref action, ref data) != 0) return null; + var provider = Win32.WTHelperProvDataFromStateData(data.StateData); + var signerPointer = provider == 0 ? 0 : Win32.WTHelperGetProvSignerFromChain(provider, 0, false, 0); + if (signerPointer == 0) return null; + var signer = Marshal.PtrToStructure(signerPointer); + if (signer.CertificateCount == 0 || signer.Certificates == 0) return null; + var certificate = Marshal.PtrToStructure(signer.Certificates); + if (certificate.Certificate == 0) return null; + var context = Marshal.PtrToStructure(certificate.Certificate); + if (context.Encoded == 0 || context.EncodedSize == 0 || context.EncodedSize > int.MaxValue) return null; + var bytes = new byte[(int)context.EncodedSize]; + Marshal.Copy(context.Encoded, bytes, 0, bytes.Length); + return Convert.ToHexStringLower(SHA256.HashData(bytes)); + } + catch (CryptographicException) { return null; } + finally + { + data.StateAction = 2; + Win32.WinVerifyTrust(0, ref action, ref data); + Marshal.DestroyStructure(memory); + Marshal.FreeHGlobal(memory); + } + } + + internal static (ApplicationIdentity Identity, string Digest) Identify(string path, string name, RunningApplication? process) + { + var canonical = CanonicalPath(path); + var digest = Digest(canonical); + var signer = VerifiedSigner(canonical); + var requirement = signer is not null ? "signed:" + signer + : process is null ? "pending:" + digest : $"process:{process.Pid}:{process.Started}:{digest}"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("win32\0" + canonical + "\0" + requirement))); + return (new(id, name, canonical, signer is not null), digest); + } + + internal static RunningApplication Running(int pid) + { + try + { + using var process = System.Diagnostics.Process.GetProcessById(pid); + if (process.SessionId != SessionId) + throw new NativeFailure("UNSUPPORTED_SESSION", "Select an application in this interactive desktop session"); + var path = process.MainModule?.FileName + ?? throw new NativeFailure("APP_IDENTITY_UNAVAILABLE", "The application executable is unavailable"); + return new(pid, Started(process), CanonicalPath(path), process.ProcessName); + } + catch (System.ComponentModel.Win32Exception) + { + throw new NativeFailure("PERMISSION_DENIED", "Windows refused the application identity; its privilege level may exceed the helper's"); + } + catch (ArgumentException) { throw new NativeFailure("STALE_APP", "The selected process has exited"); } + } + + internal static IReadOnlyList List() + { + var ids = new HashSet(); + Win32.EnumWindows((window, _) => + { + if (Win32.IsWindowVisible(window)) + { + Win32.GetWindowThreadProcessId(window, out var pid); + if (pid != 0 && pid <= int.MaxValue) ids.Add((int)pid); + } + return true; + }, 0); + var result = new List(); + foreach (var pid in ids.Order()) + { + try { result.Add(Running(pid)); } + catch (NativeFailure) { /* Processes can exit or deny metadata while the desktop is enumerated. */ } + catch (IOException) { /* A disappearing executable is not a selectable application. */ } + } + return result; + } + + internal static IReadOnlyList Find(string query, int maximum, bool exact = false) + { + var found = new Dictionary(StringComparer.Ordinal); + void Add(string name, string path) + { + if (exact ? !string.Equals(name, query, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetFileName(path), query, StringComparison.OrdinalIgnoreCase) + : !name.Contains(query, StringComparison.OrdinalIgnoreCase) && !Path.GetFileName(path).Contains(query, StringComparison.OrdinalIgnoreCase)) return; + if (!Path.IsPathFullyQualified(path) || !path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || !File.Exists(path)) return; + found.TryAdd(CanonicalPath(path), new(name, CanonicalPath(path))); + if (found.Count > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific application name or executable path"); + } + foreach (var app in List()) Add(app.Name, app.Path); + foreach (var hive in new[] { RegistryHive.CurrentUser, RegistryHive.LocalMachine }) + foreach (var view in new[] { RegistryView.Registry64, RegistryView.Registry32 }) + { + using var registry = RegistryKey.OpenBaseKey(hive, view); + using var paths = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"); + if (paths is null) continue; + foreach (var key in paths.GetSubKeyNames()) + { + using var app = paths.OpenSubKey(key); + if (app?.GetValue(null) is string path) Add(Path.GetFileNameWithoutExtension(key), Environment.ExpandEnvironmentVariables(path.Trim('"'))); + } + } + foreach (var directory in new[] { Environment.SpecialFolder.Programs, Environment.SpecialFolder.CommonPrograms }) + { + var root = Environment.GetFolderPath(directory); + if (!Directory.Exists(root)) continue; + foreach (var link in Directory.EnumerateFiles(root, "*.lnk", new EnumerationOptions + { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint })) + { + var name = Path.GetFileNameWithoutExtension(link); + if (!name.Contains(query, StringComparison.OrdinalIgnoreCase)) continue; + var target = ShellBroker.ShortcutTarget(link); + if (target is not null) Add(name, target); + } + } + return found.Values.OrderBy(app => app.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + } + + internal static AppState Select(string selector, IEnumerable retained) + { + RunningApplication? running = null; + string path, name; + if (int.TryParse(selector, out var pid)) + { + running = Running(pid); path = running.Path; name = running.Name; + } + else + { + var absolute = Path.IsPathFullyQualified(selector) ? CanonicalPath(selector) : null; + var matches = List().Where(app => absolute is not null ? string.Equals(app.Path, absolute, StringComparison.Ordinal) : string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase) + ).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Select one of the observed process IDs"); + if (matches.Length == 1) { running = matches[0]; path = running.Path; name = running.Name; } + else if (absolute is not null) { path = absolute; name = Path.GetFileNameWithoutExtension(path); } + else + { + var installed = Find(selector, 1, true).Where(app => string.Equals(app.Name, selector, StringComparison.OrdinalIgnoreCase) + || string.Equals(Path.GetFileName(app.Path), selector, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (installed.Length != 1) throw new NativeFailure(installed.Length == 0 ? "APP_NOT_FOUND" : "AMBIGUOUS_APP", "Use findApps, an executable path, or an observed PID"); + path = installed[0].Path; name = installed[0].Name; + } + } + if (!path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) throw new NativeFailure("UNSUPPORTED", "Select a Windows application executable"); + if (running is not null) + { + var previous = retained.FirstOrDefault(app => app.Process?.Pid == running.Pid && app.Process.Started == running.Started); + if (previous is not null) return previous; + } + var identity = Identify(path, name, running); + return new(Guid.NewGuid().ToString("N"), identity.Identity, identity.Digest, running); + } + + internal static async Task Launch(AppState app, RequestContext context) + { + if (app.Process is not null) { app.RequireProcess(); return; } + var identity = app.Authorization; + if (Digest(identity.ExecutablePath) != app.Digest) throw new NativeFailure("STALE_APP", "The selected executable changed before launch; select it again"); + context.Check(); + await context.Sta.Invoke(() => ShellBroker.Launch(identity.ExecutablePath), context.Cancellation); + while (true) + { + context.Check(); + var matches = List().Where(candidate => string.Equals(candidate.Path, identity.ExecutablePath, StringComparison.Ordinal)).ToArray(); + if (matches.Length > 1) throw new NativeFailure("AMBIGUOUS_APP", "Several matching processes started; select an observed PID"); + if (matches.Length == 1) + { + if (Digest(matches[0].Path) != app.Digest) throw new NativeFailure("STALE_APP", "The launched executable differs from the approved file"); + app.Process = matches[0]; + return; + } + await Task.Delay(context.Config.PollIntervalMs, context.Cancellation); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/CaptureAdmission.cs b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs new file mode 100644 index 0000000000..5014f34f85 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/CaptureAdmission.cs @@ -0,0 +1,34 @@ +// The native operation owns its capture slot until cleanup finishes, independently of the caller's await. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class CaptureAdmission +{ + private readonly object gate = new(); + private Task? pending; + + internal Task Start(Func> operation) + { + lock (gate) + { + if (pending is { IsCompleted: false }) + throw new NativeFailure("CAPTURE_BUSY", "The previous Windows capture is still releasing its resources; UIA and input remain available"); + pending = operation(); + _ = pending.ContinueWith(completed => { _ = completed.Exception; }, CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + return pending; + } + } + + internal async Task Join() + { + Task? active; + lock (gate) active = pending; + if (active is not null) + { + try { await active; } + catch (Exception error) { _ = error; /* The requesting connection owns the capture failure. */ } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/ClipboardPaste.cs b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs new file mode 100644 index 0000000000..6244fc9fa7 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ClipboardPaste.cs @@ -0,0 +1,183 @@ +// Delayed rendering waits for clipboard data consumption before restoring the previous formats. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClipboardPaste +{ + private sealed class Transaction(ServiceControl control, int targetPid, uint format, byte[] payload, List<(uint Format, byte[] Data)> previous, uint originalSequence) + { + internal readonly TaskCompletionSource Consumed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private uint sequence = originalSequence; + private bool replaced; + private bool restoring; + private bool changed; + private bool rendered; + + internal void Begin() + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) throw new NativeFailure("CLIPBOARD_CHANGED", "The clipboard changed before paste; it was not replaced"); + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard replacement"); + replaced = true; + control.ClipboardMessage = Message; + Marshal.SetLastPInvokeError(0); + Win32.SetClipboardData(format, 0); + var error = Marshal.GetLastPInvokeError(); + sequence = Win32.GetClipboardSequenceNumber(); + if (error != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused the temporary clipboard format"); + } + finally { Win32.CloseClipboard(); } + // CloseClipboard can add synthesized formats and advance the sequence. + sequence = Win32.GetClipboardSequenceNumber(); + } + + private bool Message(int message, nint parameter) + { + if (message == 0x0307 && !restoring) + { + changed = true; + Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer replaced the clipboard; observe before deciding on further input")); + return true; + } + if (message is not (0x0305 or 0x0306)) return false; + if (message == 0x0305 && (uint)parameter != format) return false; + if (message == 0x0305) + { + Win32.GetWindowThreadProcessId(Win32.GetOpenClipboardWindow(), out var readerPid); + // Clipboard monitors can request data before the target handles Control+V. + // Leave the format delayed until the selected application requests it. + if (readerPid != targetPid) return true; + } + var opened = false; + try + { + if (Win32.GetClipboardOwner() != control.Handle) return true; + if (message == 0x0306) + { + if (!Win32.OpenClipboard(control.Handle)) return true; + opened = true; + } + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + Publish(format, payload); + rendered = true; + sequence = Win32.GetClipboardSequenceNumber(); + if (changed) Consumed.TrySetException(new NativeFailure("CLIPBOARD_CHANGED", "Another writer changed the clipboard during paste")); + else if (message == 0x0305) Consumed.TrySetResult(); + } + catch (Exception error) { Consumed.TrySetException(error); } + finally { if (opened) Win32.CloseClipboard(); } + return true; + } + + internal bool Restore() + { + if (!replaced) return true; + if (Win32.GetClipboardOwner() != control.Handle) { control.ClipboardMessage = null; return true; } + if (!Win32.OpenClipboard(control.Handle)) return false; + try + { + if (Win32.GetClipboardSequenceNumber() != sequence) changed = true; + if (changed) + { + // A later writer keeps its data; fulfill any remaining promise before releasing its renderer. + if (!rendered) Publish(format, payload); + return true; + } + restoring = true; + if (!Win32.EmptyClipboard()) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard restoration"); + foreach (var original in previous) Publish(original.Format, original.Data); + return true; + } + finally { control.ClipboardMessage = null; Win32.CloseClipboard(); } + } + } + + private static void Publish(uint format, byte[] bytes) + { + var memory = Win32.GlobalAlloc(0x0002, (nuint)bytes.Length); + if (memory == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory allocation failed"); + try + { + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Clipboard memory could not be locked"); + try { Marshal.Copy(bytes, 0, pointer, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + if (Win32.SetClipboardData(format, memory) == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows refused clipboard data"); + memory = 0; + } + finally { if (memory != 0) Win32.GlobalFree(memory); } + } + + private static Transaction Prepare(ServiceControl control, int targetPid, string text, string format, int maximumBytes) + { + if (!Win32.OpenClipboard(control.Handle)) throw new NativeFailure("CLIPBOARD_BUSY", "Another application is using the clipboard"); + try + { + var previous = new List<(uint, byte[])>(); + long total = 0; + uint current = 0; + while (true) + { + Marshal.SetLastPInvokeError(0); + current = Win32.EnumClipboardFormats(current); + if (current == 0) + { + if (Marshal.GetLastPInvokeError() != 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The existing clipboard formats could not be enumerated"); + break; + } + if (current is 3 or 0x0083) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The clipboard contains a metafile with nested handles; paste left it unchanged"); + var memory = Win32.GetClipboardData(current); + var size = memory == 0 ? 0 : Win32.GlobalSize(memory); + if (size == 0 || size > int.MaxValue) + throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard includes a format that cannot be preserved as bytes; paste left it unchanged"); + total += (long)size; + if (total > maximumBytes) throw new NativeFailure("CLIPBOARD_LIMIT", "The existing clipboard exceeds maxClipboardBytes; it was not replaced"); + var pointer = Win32.GlobalLock(memory); + if (pointer == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "The current clipboard data could not be read; it was not replaced"); + var bytes = new byte[(int)size]; + try { Marshal.Copy(pointer, bytes, 0, bytes.Length); } + finally { Win32.GlobalUnlock(memory); } + previous.Add((current, bytes)); + } + var payload = format == "html" ? HtmlClipboard.Encode(text) : Encoding.Unicode.GetBytes(text + "\0"); + var nativeFormat = format == "html" ? Win32.RegisterClipboardFormat("HTML Format") : 13u; + if (nativeFormat == 0) throw new NativeFailure("CLIPBOARD_UNAVAILABLE", "Windows could not register the requested clipboard format"); + return new(control, targetPid, nativeFormat, payload, previous, Win32.GetClipboardSequenceNumber()); + } + finally { Win32.CloseClipboard(); } + } + + internal async Task Paste(AppState app, string text, string format, int maximumBytes, int readTimeoutMs, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var targetPid = app.RequireProcess().Pid; + var transaction = await context.Sta.Invoke(control => Prepare(control, targetPid, text, format, maximumBytes), context.Cancellation); + try + { + await context.Sta.Invoke(() => transaction.Begin(), context.Cancellation); + Input.Press(app, "v", ["control"], context); + try { await transaction.Consumed.Task.WaitAsync(TimeSpan.FromMilliseconds(readTimeoutMs), context.Cancellation); } + catch (TimeoutException) + { + throw new NativeFailure("PASTE_NOT_CONSUMED", "The target did not request clipboard data before pasteReadTimeoutMs; observe before deciding on further input"); + } + } + finally + { + var clock = Stopwatch.StartNew(); + while (!await context.Sta.Invoke(_ => transaction.Restore(), CancellationToken.None)) + { + if (clock.ElapsedMilliseconds >= context.Config.GraceMs) + NativeServer.Fatal("CLIPBOARD_CLEANUP", "Clipboard cleanup did not finish before the native grace deadline"); + await Task.Delay(context.Config.PollIntervalMs); + } + } + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopExecutor.cs b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs new file mode 100644 index 0000000000..7e9b33a9e0 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopExecutor.cs @@ -0,0 +1,264 @@ +// The shared Host policy authorizes handles before these platform operations execute. +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed class ClientState +{ + internal DesktopWindows Desktop { get; } = new(); + internal Dictionary Launches { get; } = new(StringComparer.Ordinal); + internal Dictionary Apps { get; } = new(StringComparer.Ordinal); + internal AppState App(string handle) => Apps.GetValueOrDefault(handle) + ?? throw new NativeFailure("STALE_APP", "Select the application again on this connection"); + internal void Clear() { foreach (var app in Apps.Values) app.Dispose(); Apps.Clear(); Launches.Clear(); } +} + +internal sealed class DesktopExecutor(MtaDispatcher mta, StaDispatcher sta, int graceMs) : IAsyncDisposable +{ + private readonly WindowCapture capture = new(); + private readonly ClipboardPaste clipboard = new(); + private readonly SemaphoreSlim queue = new(1); + + private static object ActionResult(nint before) => new + { + dispatched = true, + foregroundChanged = before == 0 || Win32.GetForegroundWindow() == 0 ? (bool?)null : before != Win32.GetForegroundWindow(), + }; + private static string String(JsonElement value, string key) => value.GetProperty(key).GetString()!; + private static string? OptionalString(JsonElement value, string key) => value.TryGetProperty(key, out var item) ? item.GetString() : null; + private static bool Flag(JsonElement value, string key) => value.TryGetProperty(key, out var item) && item.GetBoolean(); + private static uint? WindowId(JsonElement value) => value.TryGetProperty("windowId", out var id) ? id.GetUInt32() : null; + private static string[] Modifiers(JsonElement value) => value.TryGetProperty("modifiers", out var items) ? items.EnumerateArray().Select(item => item.GetString()!).ToArray() : []; + + // Window-scoped operations act only on the window authorized at getApp; the request must name it. + private static WindowState Selected(AppState app, JsonElement parameters, RequestContext context) + { + if (!parameters.TryGetProperty("windowId", out var raw)) + throw new NativeFailure("UNSUPPORTED", "This operation requires a window target; select a window with getApp and pass its windowId"); + if (!raw.TryGetUInt32(out var id)) + throw new NativeFailure("INVALID_ARGUMENT", "windowId must be a non-negative 32-bit identifier"); + var selected = app.SelectedWindow ?? throw new NativeFailure("APP_ACCESS_REQUIRED", "Select a window with getApp before this operation"); + if (selected.Id != id) + throw new NativeFailure("WINDOW_CHANGED", "The request targets another window; select that window with getApp"); + selected.Geometry(app, context); + return selected; + } + + private static (WindowState Window, double X, double Y) Coordinate(AppState app, JsonElement parameters, RequestContext context) + { + var window = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, window.Id); + return (window, parameters.GetProperty("x").GetDouble(), parameters.GetProperty("y").GetDouble()); + } + + internal async Task Execute(NativeRequest request, ClientState state, NativeConfig config, CancellationToken cancellation) + { + if (request.Method == "screenshot") + { + var context = new RequestContext(config, cancellation, mta, sta); + AppState app; + WindowState window; + await queue.WaitAsync(cancellation); + try + { + DesktopSession.RequireInteractive(); + app = state.App(String(request.Params, "appHandle")); + window = Selected(app, request.Params, context); + } + finally { queue.Release(); } + return await capture.Capture(app, window, context); + } + await queue.WaitAsync(cancellation); + try + { + var context = new RequestContext(config, cancellation, mta, sta); + context.Check(); + var parameters = request.Params; + if (request.Method == "permissionStatus") return DesktopSession.Status(await capture.IsSupported(cancellation)); + if (request.Method == "applicationIcons") return await sta.Invoke(_ => Applications.Icons(parameters, context), cancellation); + if (request.Method == "getCapabilities") + { + var locked = DesktopSession.Locked(); + return new { permissions = new { accessibility = locked == false, + screenRecording = locked == false && await capture.IsSupported(cancellation) }, + sessionLocked = locked }; + } + if (request.Method is "requestPermission" or "openPermissionSettings") + throw new NativeFailure("UNSUPPORTED", "Windows desktop access has no macOS permission switches; inspect the Windows session status"); + DesktopSession.RequireInteractive(); + if (request.Method == "listApps") return state.Desktop.ListApps(context); + if (request.Method == "findApps") + throw new NativeFailure("UNSUPPORTED", "Windows discovers selectable windows with listApps; installed launch entries are not part of this selection"); + if (request.Method == "getApp") + { + var selected = state.Desktop.Select(String(parameters, "selector"), context); + state.Apps[selected.Handle] = selected; + return new { appHandle = selected.Handle, pid = 4, name = selected.Authorization.Name, + running = true, authorization = selected.Authorization }; + } + if (request.Method == "launchApp") + throw new NativeFailure("UNSUPPORTED", "A selected Windows window cannot be launched; select an observed window from listApps"); + var app = state.App(String(parameters, "appHandle")); + app.RequireProcess(); + var foreground = Win32.GetForegroundWindow(); + switch (request.Method) + { + case "listWindows": return Windows.Refresh(app, context).Select(window => window.Describe(app, context)).ToArray(); + case "getState": + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => Accessibility.State(app, target.Id, parameters.GetProperty("maxElements").GetInt32(), + parameters.GetProperty("maxDepth").GetInt32(), Flag(parameters, "includeMenus"), Flag(parameters, "details"), context), cancellation); + } + case "activate": Windows.Activate(app, null, context); return ActionResult(foreground); + case "show": return Windows.Show(app, WindowId(parameters), context); + case "typeText": + Selected(app, parameters, context); + await Input.Type(app, String(parameters, "text"), context); + return ActionResult(foreground); + case "pressKey": + Selected(app, parameters, context); + Input.Press(app, String(parameters, "key"), Modifiers(parameters), context); + return ActionResult(foreground); + case "sendKeyEvent": + throw new NativeFailure("UNSUPPORTED", "Held key events are not supported on current platform."); + case "paste": + Selected(app, parameters, context); + await clipboard.Paste(app, String(parameters, "text"), OptionalString(parameters, "format") ?? "text", + parameters.GetProperty("maxClipboardBytes").GetInt32(), parameters.GetProperty("pasteReadTimeoutMs").GetInt32(), context); + return ActionResult(foreground); + case "mouseMove": + { + if (parameters.TryGetProperty("elementId", out _)) + { + var target = Selected(app, parameters, context); + return await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + return Input.MouseMove(app, element.Window, (bounds.X + bounds.Width / 2 - geometry.Pixels.Left), + (bounds.Y + bounds.Height / 2 - geometry.Pixels.Top), context); + }, cancellation); + } + var pointed = Coordinate(app, parameters, context); + return Input.MouseMove(app, pointed.Window, pointed.X, pointed.Y, context); + } + case "scroll": + { + var target = Coordinate(app, parameters, context); + Input.Scroll(app, target.Window, target.X, target.Y, parameters.GetProperty("deltaLinesX").GetInt32(), + parameters.GetProperty("deltaLinesY").GetInt32(), context); + return ActionResult(foreground); + } + case "drag": + { + var target = Selected(app, parameters, context); + if (OptionalString(parameters, "snapshotId") is { } snapshot) Accessibility.RequireSnapshot(app, snapshot, target.Id); + await Input.Drag(app, target, parameters.GetProperty("fromX").GetDouble(), + parameters.GetProperty("fromY").GetDouble(), parameters.GetProperty("toX").GetDouble(), parameters.GetProperty("toY").GetDouble(), + OptionalString(parameters, "mouseButton") ?? "left", Modifiers(parameters), parameters.GetProperty("durationMs").GetInt32(), + parameters.GetProperty("steps").GetInt32(), context); + return ActionResult(foreground); + } + case "click": + { + var target = Selected(app, parameters, context); + int? hold = null; + if (parameters.TryGetProperty("holdMs", out var duration)) + { + if (!duration.TryGetInt32(out var value) || value > config.MaxClickHoldMs) + throw new NativeFailure("INVALID_ARGUMENT", "The requested click exceeds maxClickHoldMs"); + hold = value; + } + var button = OptionalString(parameters, "mouseButton") ?? "left"; + var count = parameters.TryGetProperty("clickCount", out var clickCount) ? clickCount.GetInt32() : 1; + var modifiers = Modifiers(parameters); + (WindowState Window, double X, double Y)? pointer = null; + if (parameters.TryGetProperty("elementId", out _)) + { + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + if (element.Window.Id != target.Id) throw new NativeFailure("WINDOW_CHANGED", "The element belongs to another window"); + if (!hold.HasValue && button == "left" && count == 1 && modifiers.Length == 0 && AccessibilityActions.Click(element, context)) return true; + var bounds = context.Ax(() => element.Element.Current.BoundingRectangle); + if (bounds.IsEmpty) throw new NativeFailure("UNSUPPORTED", "The element has no pointer bounds"); + var geometry = element.Window.RequireObservation(app, context); + pointer = (element.Window, bounds.X + bounds.Width / 2 - geometry.Pixels.Left, + bounds.Y + bounds.Height / 2 - geometry.Pixels.Top); + return true; + }, cancellation); + } + else pointer = Coordinate(app, parameters, context); + if (pointer is { } targetPoint) + { + if (hold is { } held) await Input.HoldClick(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, held, context); + else Input.Click(app, targetPoint.Window, targetPoint.X, targetPoint.Y, button, count, modifiers, context); + } + return ActionResult(foreground); + } + case "listActions": + { + Selected(app, parameters, context); + return await mta.Invoke(() => AccessibilityActions.Actions( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + } + case "performAction": + { + Selected(app, parameters, context); + var argument = parameters.TryGetProperty("argument", out var raw) ? raw : (JsonElement?)null; + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.Perform(app, element, String(parameters, "action"), argument, context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "invoke": + { + Selected(app, parameters, context); + var dispatched = await mta.Invoke(() => AccessibilityActions.Invoke( + Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context), context), cancellation); + return new { dispatched }; + } + case "setValue": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SetValue(element, parameters.GetProperty("value"), context); + return true; + }, cancellation); + return ActionResult(foreground); + } + case "selectText": + { + Selected(app, parameters, context); + await mta.Invoke(() => + { + var element = Accessibility.Element(app, String(parameters, "snapshotId"), String(parameters, "elementId"), context); + AccessibilityActions.SelectText(element, String(parameters, "text"), OptionalString(parameters, "prefix"), OptionalString(parameters, "suffix"), + OptionalString(parameters, "selectionType") ?? "text", context); + return true; + }, cancellation); + return ActionResult(foreground); + } + default: throw new NativeFailure("UNSUPPORTED", "Unknown native CUA operation"); + } + } + finally { queue.Release(); } + } + + public async ValueTask DisposeAsync() + { + try { await capture.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { NativeServer.Fatal("NATIVE_CLEANUP", "The idle desktop service could not release capture resources"); } + queue.Dispose(); + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopSession.cs b/packages/experimental/cua-windows/native/src/DesktopSession.cs new file mode 100644 index 0000000000..d9969a3a56 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopSession.cs @@ -0,0 +1,45 @@ +// Observations stop when the interactive input desktop is unavailable. +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class DesktopSession +{ + internal static bool? Locked() + { + using var process = Process.GetCurrentProcess(); + if (!Win32.WTSQuerySessionInformation(0, process.SessionId, 8, out var state, out var bytes)) return null; + try { if (bytes < sizeof(int) || Marshal.ReadInt32(state) != 0) return true; } + finally { Win32.WTSFreeMemory(state); } + var desktop = Win32.OpenInputDesktop(0, false, 1); + if (desktop == 0) return Marshal.GetLastWin32Error() == 5 ? true : null; + try + { + var name = new StringBuilder(256); + if (!Win32.GetUserObjectInformation(desktop, 2, name, name.Capacity * sizeof(char), out _)) return null; + return !string.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase); + } + finally { Win32.CloseDesktop(desktop); } + } + + internal static void RequireInteractive() + { + if (Locked() != false) throw new NativeFailure("SESSION_LOCKED", "Unlock Windows and return to an interactive desktop before observing or sending input"); + } + + internal static object Status(bool captureAvailable) + { + using var identity = WindowsIdentity.GetCurrent(); + return new + { + platform = "windows", sessionLocked = Locked(), + captureAvailable, + elevated = new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator), + helper = new { pid = 4, path = Environment.ProcessPath, name = "dsh-cua-windows" }, + }; + } +} diff --git a/packages/experimental/cua-windows/native/src/DesktopWindows.cs b/packages/experimental/cua-windows/native/src/DesktopWindows.cs new file mode 100644 index 0000000000..e70b1b1d1e --- /dev/null +++ b/packages/experimental/cua-windows/native/src/DesktopWindows.cs @@ -0,0 +1,109 @@ +// Discovery IDs are connection-owned and never reused for another HWND lifetime. +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record DiscoveredWindow(WindowState Window, RunningApplication Process, string Selector); + +internal sealed class DesktopWindows +{ + private readonly Dictionary windows = []; + private uint nextId; + + internal object[] ListApps(RequestContext context) + { + var result = new List(); + foreach (var entry in Discover(context)) + { + context.Check(); + try + { + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(new { pid = 4, name = owner.Authorization.Name, id = entry.Selector }); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing window cannot remain selectable from this connection. + windows.Remove(entry.Window.Handle); + } + } + return result.ToArray(); + } + + internal AppState Select(string selector, RequestContext context) + { + if (string.IsNullOrEmpty(selector)) throw new NativeFailure("INVALID_ARGUMENT", "A window selector from listApps is required"); + Discover(context); + var entry = windows.Values.SingleOrDefault(value => string.Equals(value.Selector, selector, StringComparison.Ordinal)) + ?? throw new NativeFailure("WINDOW_CHANGED", "Discover applications again; this window selector belongs to another connection or an expired window"); + var app = Owner(entry, true, context); + try { entry.Window.Geometry(app, context); return app; } + catch { app.Dispose(); throw; } + } + + private List Discover(RequestContext context) + { + var current = new List(); + Win32.EnumWindows((handle, _) => + { + var extended = Win32.GetWindowLongPtr(handle, -20).ToInt64(); + if (Win32.IsWindowVisible(handle) && (extended & 0x80) == 0 + && Win32.GetWindowRect(handle, out var bounds) && bounds.Width > 0 && bounds.Height > 0) + current.Add(handle); + return true; + }, 0); + var result = new List(); + foreach (var handle in current) + { + context.Check(); + try + { + Win32.GetWindowThreadProcessId(handle, out var pid); + var process = Applications.Running(checked((int)pid)); + var epoch = context.Sta.WindowEpoch(handle); + if (!windows.TryGetValue(handle, out var entry) || entry.Process.Pid != process.Pid + || entry.Process.Started != process.Started || entry.Window.Epoch != epoch) + { + if (nextId == uint.MaxValue) throw new NativeFailure("NATIVE_LIMIT", "Reconnect before discovering more windows"); + entry = new(new(++nextId, handle, epoch), process, Guid.NewGuid().ToString("N")); + windows[handle] = entry; + } + using var owner = Owner(entry, false, context); + entry.Window.Geometry(owner, context); + result.Add(entry); + } + catch (NativeFailure error) when (error.Code is "STALE_APP" or "PERMISSION_DENIED" or "APP_IDENTITY_UNAVAILABLE" or "UNSUPPORTED_SESSION" or "WINDOW_CHANGED") + { + // A disappearing or inaccessible window cannot be selected from this discovery. + windows.Remove(handle); + } + } + foreach (var handle in windows.Keys.Where(handle => !current.Contains(handle)).ToArray()) windows.Remove(handle); + return result; + } + + private static AppState Owner(DiscoveredWindow entry, bool authorize, RequestContext context) + { + var window = entry.Window; + var process = entry.Process; + var length = Win32.GetWindowTextLength(window.Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "Window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(window.Handle, title, title.Capacity); + var name = $"Window: {title} ({process.Name})"; + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes( + $"window\0{process.Pid}\0{process.Started}\0{window.Handle}\0{window.Epoch}"))); + var identity = new ApplicationIdentity(id, name, process.Path, false); + var app = new AppState(Guid.NewGuid().ToString("N"), identity, "", process); + if (authorize) + { + var selected = new WindowState(window.Id, window.Handle, window.Epoch); + app.SelectedWindow = selected; + app.Windows.Add(window.Handle, selected); + } + return app; + } +} diff --git a/packages/experimental/cua-windows/native/src/Dispatchers.cs b/packages/experimental/cua-windows/native/src/Dispatchers.cs new file mode 100644 index 0000000000..3bc7785457 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Dispatchers.cs @@ -0,0 +1,178 @@ +// UI Automation and clipboard COM objects each stay on their owning apartment. +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Text.Json; +using DeepSeek.Cua.Protocol; +using Forms = System.Windows.Forms; +using Timer = System.Threading.Timer; + +namespace DeepSeek.Cua.Windows; + +internal sealed record NativeConfig(int MaxRequestBytes, int MaxResponseBytes, int AxTimeoutMs, + double TextEventIntervalMs, int ScreenshotTimeoutMs, int TimeoutMs, int GraceMs, int PollIntervalMs, int MaxClickHoldMs) +{ + internal static NativeConfig Parse(JsonElement value) + { + string[] fields = ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "screenshotTimeoutMs", "timeoutMs", "graceMs", "pollIntervalMs", "maxClickHoldMs"]; + if (value.ValueKind != JsonValueKind.Object || value.EnumerateObject().Any(item => !fields.Contains(item.Name)) + || fields.Any(field => !value.TryGetProperty(field, out _))) throw new NativeFailure("INVALID_CONFIG", "Expected explicit native resource limits"); + int Positive(string field) + { + if (!value.GetProperty(field).TryGetInt32(out var number) || number <= 0) throw new NativeFailure("INVALID_CONFIG", field + " must be a positive Int32"); + return number; + } + var interval = value.GetProperty("textEventIntervalMs").GetDouble(); + if (!double.IsFinite(interval) || interval < 0 || interval > 1000) throw new NativeFailure("INVALID_CONFIG", "Invalid text event interval"); + return new(Positive("maxRequestBytes"), Positive("maxResponseBytes"), Positive("axTimeoutMs"), interval, + Positive("screenshotTimeoutMs"), Positive("timeoutMs"), Positive("graceMs"), Positive("pollIntervalMs"), Positive("maxClickHoldMs")); + } +} + +internal sealed class MtaDispatcher : IAsyncDisposable +{ + private readonly BlockingCollection queue = new(); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Thread thread; + + internal MtaDispatcher() + { + thread = new Thread(() => + { + var initialized = false; + try + { + Marshal.ThrowExceptionForHR(Win32.RoInitialize(1)); + initialized = true; + Win32.SetThreadDpiAwarenessContext(-4); + ready.SetResult(); + foreach (var work in queue.GetConsumingEnumerable()) work(); + } + catch (Exception error) { ready.TrySetException(error); } + finally { if (initialized) Win32.RoUninitialize(); stopped.TrySetResult(); } + }) { IsBackground = true, Name = "dsh-cua-uia" }; + thread.SetApartmentState(ApartmentState.MTA); + thread.Start(); + } + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + queue.Add(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(); cancellation.ThrowIfCancellationRequested(); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + public async ValueTask DisposeAsync() + { + queue.CompleteAdding(); + await stopped.Task; + queue.Dispose(); + } +} + +internal sealed class ServiceControl : Forms.Control +{ + internal Func? ClipboardMessage; + protected override Forms.CreateParams CreateParams + { + get { var value = base.CreateParams; value.Parent = -3; return value; } + } + protected override void WndProc(ref Forms.Message message) + { + if (ClipboardMessage?.Invoke(message.Msg, message.WParam) == true) return; + base.WndProc(ref message); + } +} + +internal sealed class StaDispatcher : IAsyncDisposable +{ + private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly TaskCompletionSource stopped = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly ConcurrentDictionary epochs = new(); + private readonly Thread thread; + private Win32.WinEvent? windowEvents; + + internal StaDispatcher() + { + thread = new Thread(() => + { + nint hook = 0; + try + { + Win32.SetThreadDpiAwarenessContext(-4); + using var control = new ServiceControl(); + _ = control.Handle; + windowEvents = (_, eventType, window, objectId, childId, _, _) => + { + if (eventType == 0x8001 && objectId == 0 && childId == 0 && epochs.TryGetValue(window, out var epoch)) + epochs.TryUpdate(window, epoch + 1, epoch); + }; + hook = Win32.SetWinEventHook(0x8001, 0x8001, 0, windowEvents, 0, 0, 0); + if (hook == 0) throw new NativeFailure("NATIVE_STARTUP", "Window lifecycle observation could not start"); + ready.SetResult(control); + Forms.Application.Run(); + } + catch (Exception error) { ready.TrySetException(error); } + finally + { + if (hook != 0) Win32.UnhookWinEvent(hook); + stopped.TrySetResult(); + } + }) { IsBackground = true, Name = "dsh-cua-clipboard" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + internal long WindowEpoch(nint window) => epochs.GetOrAdd(window, 0); + + internal async Task Invoke(Func work, CancellationToken cancellation) + { + var control = await ready.Task.WaitAsync(cancellation); + var result = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + control.BeginInvoke(() => + { + try { cancellation.ThrowIfCancellationRequested(); var value = work(control); result.TrySetResult(value); } + catch (OperationCanceledException) { result.TrySetCanceled(cancellation); } + catch (Exception error) { result.TrySetException(error); } + }); + return await result.Task; + } + + internal Task Invoke(Action work, CancellationToken cancellation) => Invoke(_ => { work(); return true; }, cancellation); + + public async ValueTask DisposeAsync() + { + try { await ready.Task; } + catch (Exception error) { _ = error; await stopped.Task; return; } + await Invoke(() => Forms.Application.ExitThread(), CancellationToken.None); + await stopped.Task; + } +} + +internal sealed class RequestContext(NativeConfig config, CancellationToken cancellation, MtaDispatcher mta, StaDispatcher sta) +{ + internal NativeConfig Config { get; } = config; + internal CancellationToken Cancellation { get; } = cancellation; + internal MtaDispatcher Mta { get; } = mta; + internal StaDispatcher Sta { get; } = sta; + internal void Check() => Cancellation.ThrowIfCancellationRequested(); + + internal T Ax(Func call) + { + Check(); + var completed = 0; + using var timer = new Timer(_ => + { + if (Interlocked.Exchange(ref completed, 1) == 0) + NativeServer.Fatal("AX_TIMEOUT", "A Windows accessibility call did not return within its configured deadline"); + }, null, Config.AxTimeoutMs, Timeout.Infinite); + try { var result = call(); Cancellation.ThrowIfCancellationRequested(); return result; } + finally { Interlocked.Exchange(ref completed, 1); } + } +} diff --git a/packages/experimental/cua-windows/native/src/GlobalUsings.cs b/packages/experimental/cua-windows/native/src/GlobalUsings.cs new file mode 100644 index 0000000000..30f1415d24 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/GlobalUsings.cs @@ -0,0 +1 @@ +global using System.IO; diff --git a/packages/experimental/cua-windows/native/src/Input.cs b/packages/experimental/cua-windows/native/src/Input.cs new file mode 100644 index 0000000000..ec6570591d --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Input.cs @@ -0,0 +1,263 @@ +// Global key and pointer injection requires an explicitly foregrounded target. +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Input +{ + private static readonly int[] ModifierKeys = [0x10, 0x11, 0x12, 0x5B, 0x5C]; + private static ushort Modifier(string name) => name switch + { + "shift" => 0x10, "control" => 0x11, "option" => 0x12, + "command" => throw new NativeFailure("UNSUPPORTED", "Windows-key shortcuts act outside the selected application; use Control for application shortcuts"), + "fn" => throw new NativeFailure("UNSUPPORTED", "Windows does not expose a portable Fn input event"), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown key modifier"), + }; + private static Win32.Input Keyboard(ushort key, ushort scan = 0, uint flags = 0) => new() + { Type = 1, Data = new() { Keyboard = new() { Key = key, Scan = scan, Flags = flags } } }; + private static Win32.Input Mouse(uint flags, int x = 0, int y = 0, uint data = 0) => new() + { Type = 0, Data = new() { Mouse = new() { X = x, Y = y, Data = data, Flags = flags } } }; + + private static void Send(params Win32.Input[] events) + { + if (Win32.SendInput((uint)events.Length, events, Marshal.SizeOf()) != events.Length) + throw new NativeFailure("INPUT_BLOCKED", "Windows did not dispatch all input; privileges or user input may have intervened. Observe before retrying"); + } + + private static void Release(Win32.Input input) => Win32.SendInput(1, [input], Marshal.SizeOf()); + + private static void RequireIdleModifiers() + { + if (ModifierKeys.Concat([0x01, 0x02, 0x04, 0x05, 0x06]).Any(key => (Win32.GetAsyncKeyState(key) & 0x8000) != 0)) + throw new NativeFailure("INPUT_BUSY", "A modifier or mouse button is already held; wait for the user to release it before sending input"); + } + + private static void WithModifiers(IEnumerable modifiers, Action action) + { + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + action(); + } + finally { foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); } + } + + private static (ushort Key, bool Extended, string[] Modifiers) ResolveKey(string name, AppState app) + { + var key = name.ToLowerInvariant(); + if (key.StartsWith("kp_", StringComparison.Ordinal)) + { + var keypad = key[3..]; + if (keypad.Length == 1 && char.IsAsciiDigit(keypad[0])) return ((ushort)(0x60 + keypad[0] - '0'), false, []); + return keypad switch + { + "enter" => (0x0D, true, []), "add" or "plus" => (0x6B, false, []), "subtract" or "minus" => (0x6D, false, []), + "multiply" => (0x6A, false, []), "divide" => (0x6F, true, []), "decimal" or "period" => (0x6E, false, []), + _ => throw new NativeFailure("UNSUPPORTED", "Unknown numeric-keypad key"), + }; + } + if (key.Length > 1 && key[0] == 'f' && int.TryParse(key[1..], out var function) && function is >= 1 and <= 24) + return ((ushort)(0x70 + function - 1), false, []); + ushort named = key switch + { + "enter" or "return" => 0x0D, "tab" => 0x09, "escape" or "esc" => 0x1B, "backspace" => 0x08, + "delete" or "forwarddelete" => 0x2E, "insert" => 0x2D, "home" => 0x24, "end" => 0x23, + "pageup" => 0x21, "pagedown" => 0x22, "left" or "arrowleft" => 0x25, "up" or "arrowup" => 0x26, + "right" or "arrowright" => 0x27, "down" or "arrowdown" => 0x28, "space" => 0x20, + "capslock" => 0x14, "numlock" => 0x90, "scrolllock" => 0x91, "printscreen" => 0x2C, + _ => 0, + }; + if (named != 0) return (named, named is >= 0x21 and <= 0x2E || named == 0x90, []); + var character = key == "plus" ? '+' : name.Length == 1 ? char.IsAsciiLetter(name[0]) ? char.ToLowerInvariant(name[0]) : name[0] : '\0'; + if (character == '\0') throw new NativeFailure("UNSUPPORTED", "Unknown key name; use typeText for text input"); + var foreground = Win32.GetForegroundWindow(); + var thread = Win32.GetWindowThreadProcessId(foreground, out _); + var mapped = Win32.VkKeyScanEx(character, Win32.GetKeyboardLayout(thread)); + if (mapped == -1) throw new NativeFailure("UNSUPPORTED", "This character has no key in the target keyboard layout; use typeText"); + var modifiers = new List(); + if ((mapped & 0x100) != 0) modifiers.Add("shift"); + if ((mapped & 0x200) != 0) modifiers.Add("control"); + if ((mapped & 0x400) != 0) modifiers.Add("option"); + return ((ushort)(mapped & 0xFF), false, modifiers.ToArray()); + } + + internal static void Press(AppState app, string key, string[] modifiers, RequestContext context) + { + Windows.RequireForeground(app, null, context); + var chord = new KeyChord(key, modifiers.Select(KeyChord.NormalizeModifier).Distinct().ToArray()); + var name = chord.Key.ToLowerInvariant(); + if (name == "printscreen" || chord.Modifiers.Contains("option") && name is "tab" or "escape" or "esc" + || chord.Modifiers.Contains("control") && name is "escape" or "esc" + || chord.Modifiers.Contains("control") && chord.Modifiers.Contains("option") && name == "delete") + throw new NativeFailure("UNSUPPORTED", "This shortcut acts on the system rather than the selected application"); + var resolved = ResolveKey(chord.Key, app); + WithModifiers(chord.Modifiers.Concat(resolved.Modifiers), () => + { + Windows.RequireForeground(app, null, context); + var flags = resolved.Extended ? 1u : 0; + try { Send(Keyboard(resolved.Key, flags: flags), Keyboard(resolved.Key, flags: flags | 2)); } + catch { Release(Keyboard(resolved.Key, flags: flags | 2)); throw; } + }); + } + + internal static async Task Type(AppState app, string text, RequestContext context) + { + if (text.Contains('\0')) throw new NativeFailure("INVALID_ARGUMENT", "Text input cannot contain NUL"); + RequireIdleModifiers(); + for (var index = 0; index < text.Length; index++) + { + Windows.RequireForeground(app, null, context); + RequireIdleModifiers(); + var character = text[index]; + if (character is '\r' or '\n' or '\t') + { + if (character == '\r' && index + 1 < text.Length && text[index + 1] == '\n') index++; + Press(app, character == '\t' ? "Tab" : "Enter", [], context); + } + else + { + try { Send(Keyboard(0, character, 4), Keyboard(0, character, 6)); } + catch { Release(Keyboard(0, character, 6)); throw; } + } + if (context.Config.TextEventIntervalMs > 0) + await Task.Delay(TimeSpan.FromMilliseconds(context.Config.TextEventIntervalMs * 2), context.Cancellation); + } + } + + private static Win32.Input Move(Win32.Point point) + { + int left = Win32.GetSystemMetrics(76), top = Win32.GetSystemMetrics(77); + int width = Win32.GetSystemMetrics(78), height = Win32.GetSystemMetrics(79); + if (width <= 1 || height <= 1) throw new NativeFailure("SESSION_LOCKED", "The virtual desktop has no usable bounds"); + return Mouse(0x8000 | 0x4000 | 0x0001, + (int)Math.Round((point.X - left) * 65535d / (width - 1)), (int)Math.Round((point.Y - top) * 65535d / (height - 1))); + } + + private static (uint Down, uint Up) Button(string button) => button switch + { + "left" => (0x0002, 0x0004), "right" => (0x0008, 0x0010), "middle" => (0x0020, 0x0040), + _ => throw new NativeFailure("INVALID_ARGUMENT", "Unknown mouse button"), + }; + + private static void Hit(AppState app, WindowState window, Win32.Point point, RequestContext context) + { + Windows.RequireForeground(app, window, context); + if (Win32.GetAncestor(Win32.WindowFromPoint(point), 2) != window.Handle) + throw new NativeFailure("WINDOW_OBSCURED", "Another window covers the target coordinate; restore or raise the selected window and observe again"); + } + + internal static object MouseMove(AppState app, WindowState window, double x, double y, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + if (!Win32.GetCursorPos(out var before)) throw new NativeFailure("INPUT_UNAVAILABLE", "The current pointer position is unavailable"); + Send(Move(point)); + return new { dispatched = true, hoverRoute = "system-pointer", systemPointerMoved = before.X != point.X || before.Y != point.Y }; + } + + internal static void Click(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var geometry = window.RequireObservation(app, context); + var point = WindowState.Point(geometry, x, y); + var flags = Button(button); + Hit(app, window, point, context); + WithModifiers(modifiers, () => + { + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + var events = new List { Move(point) }; + for (var click = 0; click < count; click++) { events.Add(Mouse(flags.Down)); events.Add(Mouse(flags.Up)); } + try { Send(events.ToArray()); } catch { Release(Mouse(flags.Up)); throw; } + }); + } + + internal static async Task HoldClick(AppState app, WindowState window, double x, double y, string button, int count, string[] modifiers, int holdMs, RequestContext context) + { + if (button != "left" && count != 1) throw new NativeFailure("UNSUPPORTED", "Only left clicks support double-click"); + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + Hit(app, window, point, context); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key)); } + point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + Send(Move(point)); + for (var click = 0; click < count; click++) + { + Hit(app, window, point, context); + buttonAttempted = true; + Send(Mouse(flags.Down)); + await Task.Delay(holdMs, context.Cancellation); + Windows.RequireForeground(app, window, context); + Send(Mouse(flags.Up)); + buttonAttempted = false; + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2)); + } + } + + internal static void Scroll(AppState app, WindowState window, double x, double y, int deltaX, int deltaY, RequestContext context) + { + var point = WindowState.Point(window.RequireObservation(app, context), x, y); + Hit(app, window, point, context); + RequireIdleModifiers(); + uint lines = 1, columns = 1; + if (deltaY != 0 && (!Win32.SystemParametersInfo(0x0068, 0, out lines, 0) || lines == uint.MaxValue || lines == 0) + || deltaX != 0 && (!Win32.SystemParametersInfo(0x006C, 0, out columns, 0) || columns == 0)) + throw new NativeFailure("UNSUPPORTED", "Windows wheel scrolling does not currently use line/character units"); + var events = new List { Move(point) }; + if (deltaY != 0) events.Add(Mouse(0x0800, data: unchecked((uint)(int)Math.Round(deltaY * 120d / lines)))); + if (deltaX != 0) events.Add(Mouse(0x1000, data: unchecked((uint)(int)Math.Round(-deltaX * 120d / columns)))); + Send(events.ToArray()); + } + + internal static async Task Drag(AppState app, WindowState window, double fromX, double fromY, double toX, double toY, + string button, string[] modifiers, int durationMs, int steps, RequestContext context) + { + var geometry = window.RequireObservation(app, context); + var from = WindowState.Point(geometry, fromX, fromY); + _ = WindowState.Point(geometry, toX, toY); + Hit(app, window, from, context); + var flags = Button(button); + var keys = modifiers.Select(KeyChord.NormalizeModifier).Select(Modifier).Distinct().ToArray(); + RequireIdleModifiers(); + var attempted = new List(); + var buttonAttempted = false; + try + { + foreach (var key in keys) { attempted.Add(key); Send(Keyboard(key, flags: key == 0x5B ? 1u : 0)); } + geometry = window.RequireObservation(app, context); + from = WindowState.Point(geometry, fromX, fromY); + Hit(app, window, from, context); + buttonAttempted = true; + Send(Move(from), Mouse(flags.Down)); + for (var step = 1; step <= steps; step++) + { + await Task.Delay(TimeSpan.FromMilliseconds(durationMs / (double)steps), context.Cancellation); + geometry = window.RequireObservation(app, context); + Windows.RequireForeground(app, window, context); + Send(Move(WindowState.Point(geometry, fromX + (toX - fromX) * step / steps, fromY + (toY - fromY) * step / steps))); + } + } + finally + { + if (buttonAttempted) Release(Mouse(flags.Up)); + foreach (var key in attempted.AsEnumerable().Reverse()) Release(Keyboard(key, flags: 2u | (key == 0x5B ? 1u : 0))); + } + } +} diff --git a/packages/experimental/cua-windows/native/src/LaunchEntries.cs b/packages/experimental/cua-windows/native/src/LaunchEntries.cs new file mode 100644 index 0000000000..cc97dfd8bf --- /dev/null +++ b/packages/experimental/cua-windows/native/src/LaunchEntries.cs @@ -0,0 +1,88 @@ +// Shell namespace enumeration and activation run on the existing STA dispatcher. +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal sealed record LaunchEntry(string Id, string DisplayName, string Kind, string? Path); +internal sealed class PreparedLaunch(LaunchEntry entry, ApplicationIdentity authorization, string? digest) +{ + internal string Handle { get; } = Guid.NewGuid().ToString("N"); + internal ApplicationIdentity Authorization { get; } = authorization; + private bool dispatched; + + internal void Dispatch() + { + if (dispatched) throw new NativeFailure("LAUNCH_ALREADY_DISPATCHED", "Discover windows before deciding whether another launch is needed"); + if (entry.Kind == "executable") + { + if (Applications.CanonicalPath(entry.Id) != entry.Id || Applications.Digest(entry.Id) != digest) + throw new NativeFailure("STALE_APP", "The approved executable changed; select it again"); + } + else if (!LaunchEntries.All().Any(current => current.Id == entry.Id)) + throw new NativeFailure("STALE_APP", "The Shell entry disappeared; discover launch entries again"); + // Dispatch may succeed even if Explorer subsequently reports a failure. Never replay this selection. + dispatched = true; + ShellBroker.Launch(entry.Id, show: 1); + } +} + +internal static class LaunchEntries +{ + internal static LaunchEntry[] All() + { + var owned = new List(); + object Own(object value) { owned.Add(value); return value; } + try + { + dynamic shell = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("13709620-C279-11CE-A49E-444553540000"), true)!)!); + dynamic folder = Own((object)shell.NameSpace("shell:AppsFolder")); + dynamic items = Own((object)folder.Items()); + var result = new List(); + for (var index = 0; index < (int)items.Count; index++) + { + dynamic item = Own((object)items.Item(index)); + string parsingName = item.Path; + string name = item.Name; + if (string.IsNullOrWhiteSpace(parsingName) || string.IsNullOrWhiteSpace(name)) continue; + var target = parsingName.StartsWith("::", StringComparison.Ordinal) ? parsingName : "shell:AppsFolder\\" + parsingName; + result.Add(new(target, name, "shell", null)); + } + return result.DistinctBy(entry => entry.Id, StringComparer.OrdinalIgnoreCase).ToArray(); + } + catch (Exception error) when (error is COMException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("APP_DISCOVERY_FAILED", "Windows Shell could not enumerate AppsFolder; retry discovery after Explorer is available"); + } + finally + { + foreach (var item in owned.AsEnumerable().Reverse()) + if (Marshal.IsComObject(item)) Marshal.ReleaseComObject(item); + } + } + + internal static LaunchEntry[] Find(string query, int maximum) + { + var matches = All().Where(entry => entry.DisplayName.Contains(query, StringComparison.OrdinalIgnoreCase) + || entry.Id.Contains(query, StringComparison.OrdinalIgnoreCase)).OrderBy(entry => entry.DisplayName, StringComparer.OrdinalIgnoreCase).ToArray(); + if (matches.Length > maximum) throw new NativeFailure("TOO_MANY_APPS", "Use a more specific launch entry name"); + return matches; + } + + internal static PreparedLaunch Prepare(string target) + { + if (Path.IsPathFullyQualified(target) && target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + var path = Applications.CanonicalPath(target); + var name = Path.GetFileNameWithoutExtension(path); + var identity = Applications.Identify(path, "Launch: " + name, null); + return new(new(path, name, "executable", path), identity.Identity with { Persistable = false }, identity.Digest); + } + var shell = All().SingleOrDefault(entry => string.Equals(entry.Id, target, StringComparison.OrdinalIgnoreCase)) + ?? throw new NativeFailure("APP_NOT_FOUND", "Use an ID from findApps or a user-specified absolute executable path"); + var id = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("launch\0" + shell.Id))); + return new(shell, new(id, "Launch: " + shell.DisplayName, shell.Id, false), null); + } +} diff --git a/packages/experimental/cua-windows/native/src/NativeServer.cs b/packages/experimental/cua-windows/native/src/NativeServer.cs new file mode 100644 index 0000000000..866cc0588b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/NativeServer.cs @@ -0,0 +1,196 @@ +// The per-user service serves isolated Agent connections and Host leases on a private named pipe. +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.IO.Pipes; +using System.Security.Cryptography; +using System.Text.Json; +using System.Windows.Automation; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class NativeServer +{ + [DoesNotReturn] + internal static void Fatal(string code, string message) + { + Console.Error.WriteLine($"{code}: {message}; native handles are no longer usable"); + Environment.Exit(70); + throw new InvalidOperationException("Process exit returned"); + } + + internal static async Task Run(string instance, string expectedRuntime, int connectTimeoutMs, int graceMs) + { + if (!Guid.TryParseExact(instance, "N", out _)) throw new NativeFailure("INVALID_ARGUMENT", "A Host instance identifier is required"); + var executable = Environment.ProcessPath ?? throw new NativeFailure("NATIVE_STARTUP", "The executable identity is unavailable"); + using var source = File.OpenRead(executable); + var runtime = Convert.ToHexStringLower(SHA256.HashData(source)); + if (runtime != expectedRuntime) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + var pipeName = SharedRuntime.PipeName(runtime); + using var lifetime = new CancellationTokenSource(); + lifetime.CancelAfter(connectTimeoutMs); + await using var mta = new MtaDispatcher(); + await using var sta = new StaDispatcher(); + await sta.Invoke(() => { }, lifetime.Token); + await mta.Invoke(() => true, lifetime.Token); + await using var executor = new DesktopExecutor(mta, sta, graceMs); + var clients = new ConcurrentDictionary(); + NamedPipeServerStream? listener = NewPipe(pipeName); + var membership = new object(); + var connections = 0; + try + { + while (!lifetime.IsCancellationRequested) + { + await listener.WaitForConnectionAsync(lifetime.Token); + var connected = listener; + lock (membership) + { + lifetime.Token.ThrowIfCancellationRequested(); + connections++; + lifetime.CancelAfter(Timeout.Infinite); + } + listener = NewPipe(pipeName); + var task = Serve(connected, executor, instance, runtime, connectTimeoutMs, lifetime.Token); + clients.TryAdd(task, 0); + _ = task.ContinueWith(completed => + { + clients.TryRemove(completed, out _); + if (completed.IsFaulted) { _ = completed.Exception; Console.Error.WriteLine("NATIVE_CONNECTION: Connection cleanup failed"); } + lock (membership) { if (--connections == 0) lifetime.Cancel(); } + }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + catch (OperationCanceledException error) when (lifetime.IsCancellationRequested) { _ = error; /* Host shutdown cancels the pending read. */ } + finally + { + lifetime.Cancel(); + listener?.Dispose(); + await Task.WhenAll(clients.Keys); + } + } + + private static NamedPipeServerStream NewPipe(string name) => new(name, PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + + private static async Task Serve(NamedPipeServerStream pipe, DesktopExecutor executor, + string instance, string runtime, int connectTimeoutMs, CancellationToken serverLifetime) + { + using (pipe) + using (var lifetime = CancellationTokenSource.CreateLinkedTokenSource(serverLifetime)) + using (var writer = new SemaphoreSlim(1)) + { + var state = new ClientState(); + Task? active = null; + CancellationTokenSource? cancellation = null; + string? latestRequestId = null; + var closeRequested = false; + var cleanupTimeoutMs = connectTimeoutMs; + try + { + var reader = new FrameReader(pipe); + string? line; + using (var greeting = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token)) + { + greeting.CancelAfter(connectTimeoutMs); + line = await reader.ReadAsync(8192, greeting.Token) ?? throw new NativeFailure("INVALID_REQUEST", "A native hello is required"); + } + var hello = WireJson.Parse(line); + if (hello.ValueKind == JsonValueKind.Object && hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["runtimeKey", "type"]) + && hello.GetProperty("type").GetString() == "lease" && hello.GetProperty("runtimeKey").GetString() == runtime) + { + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, + 8192, connectTimeoutMs, lifetime.Token); + if (await reader.ReadAsync(8192, lifetime.Token) is not null) throw new NativeFailure("INVALID_REQUEST", "A service lease cannot send desktop operations"); + return; + } + if (hello.ValueKind != JsonValueKind.Object || hello.EnumerateObject().Select(item => item.Name).Order().SequenceEqual(["config", "protocol", "runtimeKey", "type"]) == false + || hello.GetProperty("type").GetString() != "hello" || hello.GetProperty("protocol").GetInt32() != 1 || hello.GetProperty("runtimeKey").GetString() != runtime) + throw new NativeFailure("INVALID_REQUEST", "The native handshake did not match this helper"); + var config = NativeConfig.Parse(hello.GetProperty("config")); + cleanupTimeoutMs = config.GraceMs; + await Write(pipe, writer, new { type = "ready", protocol = 1, runtimeKey = runtime, pid = Environment.ProcessId, instanceId = instance }, 8192, config.GraceMs, lifetime.Token); + while ((line = await reader.ReadAsync(config.MaxRequestBytes, lifetime.Token)) is not null) + { + var value = WireJson.Parse(line); + if (value.ValueKind == JsonValueKind.Object && value.TryGetProperty("type", out _)) + { + var control = NativeControlFrame.Parse(value, latestRequestId, active?.IsCompleted != false); + if (control == NativeControl.Close) { closeRequested = true; break; } + if (control == NativeControl.Cancel) cancellation!.Cancel(); + continue; + } + var request = NativeRequest.Parse(value); + if (active is { IsCompleted: false }) throw new NativeFailure("NATIVE_BUSY", "Native requests must be sequential"); + if (active is not null) await active; + cancellation?.Dispose(); + cancellation = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); + cancellation.CancelAfter(request.Method == "screenshot" ? Math.Min(config.TimeoutMs, config.ScreenshotTimeoutMs) : config.TimeoutMs); + latestRequestId = request.Id; + active = Dispatch(request, state, executor, config, pipe, writer, cancellation.Token, lifetime.Token); + } + } + catch (Exception error) + { + if (error is not (IOException or OperationCanceledException)) Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); + } + finally + { + lifetime.Cancel(); + cancellation?.Cancel(); + if (active is not null) + { + try { await active; } + catch (Exception error) { Console.Error.WriteLine($"NATIVE_CONNECTION: {error.GetType().Name}"); } + } + cancellation?.Dispose(); + state.Clear(); + if (closeRequested) + await Write(pipe, writer, new { type = "closed" }, 8192, cleanupTimeoutMs, CancellationToken.None); + } + } + } + + private static async Task Dispatch(NativeRequest request, ClientState state, DesktopExecutor executor, NativeConfig config, + Stream pipe, SemaphoreSlim writer, CancellationToken cancellation, CancellationToken connection) + { + var operation = executor.Execute(request, state, config, cancellation); + using var monitorStop = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + var monitor = WatchOperation(operation, monitorStop.Token, config.GraceMs); + object response; + try { response = new { id = request.Id, result = await operation }; } + catch (OperationCanceledException) { response = Failure(request.Id, "NATIVE_CANCELLED", "Native operation cancelled; observe before deciding on further input"); } + catch (NativeFailure error) { response = Failure(request.Id, error.Code, error.Message); } + catch (ElementNotAvailableException) { response = Failure(request.Id, "STALE_SNAPSHOT", "An accessibility element disappeared; read fresh state"); } + catch (ElementNotEnabledException) { response = Failure(request.Id, "ELEMENT_DISABLED", "The selected control is disabled"); } + catch (UnauthorizedAccessException) { response = Failure(request.Id, "PERMISSION_DENIED", "Windows refused access to the selected application"); } + catch (Exception error) { response = Failure(request.Id, "NATIVE_OPERATION", $"Windows operation failed (0x{error.HResult:X8}); observe before retrying"); } + finally { monitorStop.Cancel(); await monitor; } + var bytes = JsonSerializer.SerializeToUtf8Bytes(response, WireJson.Options); + if (bytes.Length + 1 > config.MaxResponseBytes) response = Failure(request.Id, "NATIVE_RESPONSE_LIMIT", "Native response exceeded its configured byte limit"); + await Write(pipe, writer, response, config.MaxResponseBytes, config.GraceMs, connection); + } + + private static object Failure(string id, string code, string message) => new { id, error = new { code, message } }; + + private static async Task WatchOperation(Task operation, CancellationToken cancellation, int graceMs) + { + await Task.WhenAny(operation, Task.Delay(Timeout.Infinite, cancellation)); + if (operation.IsCompleted) return; + try { await operation.WaitAsync(TimeSpan.FromMilliseconds(graceMs)); } + catch (TimeoutException) { Fatal("NATIVE_CLEANUP", "A cancelled desktop operation did not stop before the grace deadline"); } + catch (Exception error) when (operation.IsCompleted) { _ = error; /* Dispatch owns the operation result. */ } + } + + private static async Task Write(Stream pipe, SemaphoreSlim writer, object value, int maximum, int timeoutMs, CancellationToken cancellation) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(value, WireJson.Options); + if (bytes.Length + 1 > maximum) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The native frame exceeds its byte limit"); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation); + deadline.CancelAfter(timeoutMs); + await writer.WaitAsync(deadline.Token); + try { await pipe.WriteAsync(bytes, deadline.Token); await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); await pipe.FlushAsync(deadline.Token); } + finally { writer.Release(); } + } +} diff --git a/packages/experimental/cua-windows/native/src/Program.cs b/packages/experimental/cua-windows/native/src/Program.cs new file mode 100644 index 0000000000..d46db4479c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Program.cs @@ -0,0 +1,35 @@ +// The executable is a private helper launched by the dsh Windows provider. +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class Program +{ + private static int Main(string[] args) + { + try + { + if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041)) throw new NativeFailure("UNSUPPORTED", "Windows CUA requires Windows 10 build 19041 or later"); + var server = args.Length == 7 && args[0] == "--shared-server"; + var bridge = args.Length == 7 && args[0] == "--bridge"; + var connector = args.Length == 9 && args[0] == "--serve" && args[1] == "--instance-id" && Guid.TryParseExact(args[2], "N", out _); + var offset = server || bridge ? 1 : 3; + if ((!server && !connector && !bridge) || args[offset] != "--runtime-key" || args[offset + 2] != "--connect-timeout-ms" + || args[offset + 4] != "--grace-ms" + || !int.TryParse(args[offset + 3], out var connectTimeoutMs) || connectTimeoutMs <= 0 + || !int.TryParse(args[offset + 5], out var graceMs) || graceMs <= 0) + throw new NativeFailure("INVALID_ARGUMENT", "The helper must be launched by the dsh Windows provider"); + var runtime = Applications.Digest(Environment.ProcessPath!); + if (runtime != args[offset + 1]) throw new NativeFailure("NATIVE_STARTUP", "The helper executable changed before startup"); + if (server) SharedRuntime.Serve(runtime, connectTimeoutMs, graceMs); + else if (bridge) SharedRuntime.Bridge(runtime, connectTimeoutMs).GetAwaiter().GetResult(); + else SharedRuntime.Connect(args[2], runtime, connectTimeoutMs, graceMs).GetAwaiter().GetResult(); + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error is NativeFailure failure ? $"{failure.Code}: {failure.Message}" : $"NATIVE_STARTUP: {error.Message}"); + return 1; + } + } +} diff --git a/packages/experimental/cua-windows/native/src/SharedRuntime.cs b/packages/experimental/cua-windows/native/src/SharedRuntime.cs new file mode 100644 index 0000000000..974adf160b --- /dev/null +++ b/packages/experimental/cua-windows/native/src/SharedRuntime.cs @@ -0,0 +1,110 @@ +// A managed Host connector leases an Explorer-launched service outside the Host's kill-on-close Job. +using System.Diagnostics; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using System.Text.Json; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class SharedRuntime +{ + internal static string PipeName(string runtime) + { + using var identity = WindowsIdentity.GetCurrent(); + using var process = Process.GetCurrentProcess(); + var user = identity.User?.Value ?? throw new NativeFailure("NATIVE_STARTUP", "The Windows user identity is unavailable"); + var scope = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes($"{user}:{process.SessionId}"))); + return $"dsh-cua-{scope}-{runtime}"; + } + + internal static async Task Connect(string launcherId, string runtime, int timeoutMs, int graceMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + try { pipe.Connect(0); } + catch (TimeoutException) + { + await using var sta = new StaDispatcher(); + var executable = Environment.ProcessPath!; + await sta.Invoke(() => ShellBroker.Launch(executable, + $"--shared-server --runtime-key {runtime} --connect-timeout-ms {timeoutMs} --grace-ms {graceMs}", 0), deadline.Token); + await pipe.ConnectAsync(deadline.Token); + } + var pid = VerifyServer(pipe, runtime); + var hello = JsonSerializer.SerializeToUtf8Bytes(new { type = "lease", runtimeKey = runtime }, WireJson.Options); + await pipe.WriteAsync(hello, deadline.Token); + await pipe.WriteAsync("\n"u8.ToArray(), deadline.Token); + var reader = new FrameReader(pipe); + var line = await reader.ReadAsync(8192, deadline.Token) + ?? throw new NativeFailure("NATIVE_EOF", "The shared service exited during connection"); + var ready = WireJson.Parse(line); + if (ready.GetProperty("runtimeKey").GetString() != runtime || ready.GetProperty("pid").GetInt32() != pid) + throw new NativeFailure("NATIVE_PROTOCOL", "The shared service returned a different process identity"); + Console.WriteLine(JsonSerializer.Serialize(new + { + type = "ready", protocol = 1, runtimeKey = runtime, pid, + instanceId = ready.GetProperty("instanceId").GetString(), launcherId, endpoint = @"\\.\pipe\" + PipeName(runtime), + }, WireJson.Options)); + await Console.Out.FlushAsync(); + // Console.In's synchronized reader can block before it returns an asynchronous result. + var parent = Task.Run(() => Console.In.ReadLine()); + var stopped = reader.ReadAsync(8192, CancellationToken.None); + if (await Task.WhenAny(parent, stopped) == stopped) + throw new NativeFailure("NATIVE_EXITED", "The shared desktop service stopped; select applications again"); + await parent; + } + + // Windows owns the named pipe; WSL forwards the unchanged protocol over standard streams. + internal static async Task Bridge(string runtime, int timeoutMs) + { + using var deadline = new CancellationTokenSource(timeoutMs); + using var pipe = new NamedPipeClientStream(".", PipeName(runtime), PipeDirection.InOut, + PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + await pipe.ConnectAsync(deadline.Token); + VerifyServer(pipe, runtime); + using var input = Console.OpenStandardInput(); + using var output = Console.OpenStandardOutput(); + // Inherited standard-input handles can be synchronous; never block pipe output on their reads. + var upload = Task.Run(() => input.CopyToAsync(pipe)); + var download = pipe.CopyToAsync(output); + try + { + var completed = await Task.WhenAny(upload, download); + await completed; + await output.FlushAsync(); + } + finally + { + // Process exit ends a pending synchronous stdin read; it must not delay pipe cleanup. + pipe.Dispose(); + } + } + + private static uint VerifyServer(NamedPipeClientStream pipe, string runtime) + { + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var pid)) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe server identity is unavailable"); + var server = Applications.Running(checked((int)pid)); + if (Applications.Digest(server.Path) != runtime) + throw new NativeFailure("NATIVE_PROTOCOL", "The Windows pipe belongs to another executable"); + return pid; + } + + internal static void Serve(string runtime, int timeoutMs, int graceMs) + { + using var mutex = new Mutex(false, PipeName(runtime), new NamedWaitHandleOptions { CurrentUserOnly = true, CurrentSessionOnly = true }); + bool acquired; + try { acquired = mutex.WaitOne(0); } + catch (AbandonedMutexException) { acquired = true; } + if (!acquired) return; + try { NativeServer.Run(Guid.NewGuid().ToString("N"), runtime, timeoutMs, graceMs).GetAwaiter().GetResult(); } + finally { mutex.ReleaseMutex(); } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverProcessId); +} diff --git a/packages/experimental/cua-windows/native/src/ShellBroker.cs b/packages/experimental/cua-windows/native/src/ShellBroker.cs new file mode 100644 index 0000000000..291833ac1c --- /dev/null +++ b/packages/experimental/cua-windows/native/src/ShellBroker.cs @@ -0,0 +1,111 @@ +// Explorer owns user-launched applications, independently of the helper's managed process Job. +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal static class ShellBroker +{ + internal static void Launch(string path, string arguments = "", int show = 4) + { + var owned = new List(); + T Own(T value) where T : class { owned.Add(value); return value; } + try + { + dynamic windows = Own(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39"), true)!)!); + object location = 0, root = null!; + int handle; + object desktop = Own((object)windows.FindWindowSW(ref location, ref root, 8, out handle, 1)); + var service = new Guid("4C96BE40-915C-11CF-99D3-00AA004AE837"); + var browserId = typeof(IShellBrowser).GUID; + Marshal.ThrowExceptionForHR(((IServiceProvider)desktop).QueryService(ref service, ref browserId, out var rawBrowser)); + var browser = (IShellBrowser)Own(rawBrowser); + Marshal.ThrowExceptionForHR(browser.QueryActiveShellView(out var view)); + Own(view); + var dispatchId = new Guid("00020400-0000-0000-C000-000000000046"); + Marshal.ThrowExceptionForHR(view.GetItemObject(0, ref dispatchId, out var folder)); + Own(folder); + var shell = Own(folder.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, folder, null)!); + shell.GetType().InvokeMember("ShellExecute", BindingFlags.InvokeMethod, null, shell, + [path, arguments, Path.IsPathFullyQualified(path) ? Path.GetDirectoryName(path)! : "", "open", show]); + } + catch (Exception error) when (error is COMException or TargetInvocationException or Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) + { + throw new NativeFailure("LAUNCH_FAILED", "Windows Explorer could not launch this executable; open the application and select its observed PID"); + } + finally + { + var released = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var value in owned.AsEnumerable().Reverse()) + if (released.Add(value) && Marshal.IsComObject(value)) Marshal.FinalReleaseComObject(value); + } + } + + internal static string? ShortcutTarget(string path) + { + object? instance = null; + try + { + instance = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true)!); + ((IPersistFile)instance!).Load(path, 0); + var target = new StringBuilder(32768); + ((IShellLink)instance).GetPath(target, target.Capacity, 0, 4); + return target.Length == 0 ? null : Environment.ExpandEnvironmentVariables(target.ToString()); + } + catch (COMException) { return null; } + finally { if (instance is not null) Marshal.FinalReleaseComObject(instance); } + } + + [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IServiceProvider + { + [PreserveSig] int QueryService(ref Guid service, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellBrowser + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int InsertMenusSB(nint menu, nint widths); + [PreserveSig] int SetMenuSB(nint menu, nint holemenu, nint active); + [PreserveSig] int RemoveMenusSB(nint menu); + [PreserveSig] int SetStatusTextSB([MarshalAs(UnmanagedType.LPWStr)] string text); + [PreserveSig] int EnableModelessSB([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int TranslateAcceleratorSB(nint message, ushort command); + [PreserveSig] int BrowseObject(nint list, uint flags); + [PreserveSig] int GetViewStateStream(uint mode, out nint stream); + [PreserveSig] int GetControlWindow(uint id, out nint window); + [PreserveSig] int SendControlMsg(uint id, uint message, nuint wparam, nint lparam, out nint result); + [PreserveSig] int QueryActiveShellView(out IShellView view); + [PreserveSig] int OnViewWindowActive(IShellView view); + [PreserveSig] int SetToolbarItems(nint buttons, uint count, uint flags); + } + + [ComImport, Guid("000214E3-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellView + { + [PreserveSig] int GetWindow(out nint window); + [PreserveSig] int ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool enter); + [PreserveSig] int TranslateAccelerator(nint message); + [PreserveSig] int EnableModeless([MarshalAs(UnmanagedType.Bool)] bool enable); + [PreserveSig] int UIActivate(uint state); + [PreserveSig] int Refresh(); + [PreserveSig] int CreateViewWindow(nint previous, nint settings, nint browser, nint bounds, out nint window); + [PreserveSig] int DestroyViewWindow(); + [PreserveSig] int GetCurrentInfo(nint settings); + [PreserveSig] int AddPropertySheetPages(uint reserved, nint callback, nint parameter); + [PreserveSig] int SaveViewState(); + [PreserveSig] int SelectItem(nint list, uint flags); + [PreserveSig] int GetItemObject(uint item, ref Guid id, [MarshalAs(UnmanagedType.Interface)] out object value); + } + + [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellLink + { + void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int capacity, nint findData, uint flags); + } +} diff --git a/packages/experimental/cua-windows/native/src/Win32.cs b/packages/experimental/cua-windows/native/src/Win32.cs new file mode 100644 index 0000000000..957e3bcb98 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Win32.cs @@ -0,0 +1,136 @@ +// Native desktop operations keep physical pixels and process identity at the Windows edge. +using System.Runtime.InteropServices; +using System.Text; + +namespace DeepSeek.Cua.Windows; + +internal static class Win32 +{ + [DllImport("combase.dll")] internal static extern int RoInitialize(uint initialization); + [DllImport("combase.dll")] internal static extern void RoUninitialize(); + [DllImport("user32.dll", EntryPoint = "GetWindowLongPtrW")] internal static extern nint GetWindowLongPtr(nint window, int index); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(out Point point); + internal delegate bool WindowVisitor(nint window, nint parameter); + internal delegate void WinEvent(nint hook, uint eventType, nint window, int objectId, int childId, uint threadId, uint time); + + [StructLayout(LayoutKind.Sequential)] internal struct Point { internal int X, Y; } + [StructLayout(LayoutKind.Sequential)] internal struct Rect + { + internal int Left, Top, Right, Bottom; + internal int Width => Right - Left; + internal int Height => Bottom - Top; + } + [StructLayout(LayoutKind.Sequential)] internal struct GuiThreadInfo + { + internal uint Size, Flags; + internal nint Active, Focus, Capture, MenuOwner, MoveSize, Caret; + internal Rect CaretRect; + } + [StructLayout(LayoutKind.Sequential)] internal struct Input { internal uint Type; internal InputData Data; } + [StructLayout(LayoutKind.Explicit)] internal struct InputData + { + [FieldOffset(0)] internal MouseInput Mouse; + [FieldOffset(0)] internal KeyboardInput Keyboard; + } + [StructLayout(LayoutKind.Sequential)] internal struct MouseInput + { + internal int X, Y; + internal uint Data, Flags, Time; + internal nuint Extra; + } + [StructLayout(LayoutKind.Sequential)] internal struct KeyboardInput + { + internal ushort Key, Scan; + internal uint Flags, Time; + internal nuint Extra; + } + + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EnumWindows(WindowVisitor visitor, nint parameter); + [DllImport("user32.dll")] internal static extern uint GetWindowThreadProcessId(nint window, out uint processId); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsWindowVisible(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsIconic(nint window); + [DllImport("user32.dll")] internal static extern nint GetForegroundWindow(); + [DllImport("user32.dll")] internal static extern nint GetAncestor(nint window, uint flags); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowText(nint window, StringBuilder text, int maximum); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetWindowTextLength(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowRect(nint window, out Rect rectangle); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out Rect rectangle, int size); + [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(nint window, int attribute, out int value, int size); + [DllImport("user32.dll")] internal static extern uint GetDpiForWindow(nint window); + [DllImport("user32.dll")] internal static extern nint SetThreadDpiAwarenessContext(nint context); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetForegroundWindow(nint window); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ShowWindowAsync(nint window, int command); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetGUIThreadInfo(uint thread, ref GuiThreadInfo info); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, Input[] inputs, int size); + [DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key); + [DllImport("user32.dll")] internal static extern nint GetKeyboardLayout(uint thread); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern short VkKeyScanEx(char character, nint layout); + [DllImport("user32.dll")] internal static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] internal static extern nint WindowFromPoint(Point point); + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SystemParametersInfo(uint action, uint parameter, out uint value, uint flags); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint OpenInputDesktop(uint flags, [MarshalAs(UnmanagedType.Bool)] bool inherit, uint access); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseDesktop(nint desktop); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetUserObjectInformation(nint handle, int index, StringBuilder value, int length, out int needed); + [DllImport("wtsapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WTSQuerySessionInformation(nint server, int session, int information, out nint buffer, out int bytes); + [DllImport("wtsapi32.dll")] internal static extern void WTSFreeMemory(nint memory); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetWinEventHook(uint minimum, uint maximum, nint module, WinEvent callback, uint process, uint thread, uint flags); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnhookWinEvent(nint hook); + + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenClipboard(nint owner); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseClipboard(); + [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EmptyClipboard(); + [DllImport("user32.dll")] internal static extern nint GetClipboardOwner(); + [DllImport("user32.dll")] internal static extern nint GetOpenClipboardWindow(); + [DllImport("user32.dll")] internal static extern uint GetClipboardSequenceNumber(); + [DllImport("user32.dll", SetLastError = true)] internal static extern uint EnumClipboardFormats(uint previous); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint GetClipboardData(uint format); + [DllImport("user32.dll", SetLastError = true)] internal static extern nint SetClipboardData(uint format, nint data); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterClipboardFormat(string name); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalAlloc(uint flags, nuint bytes); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nint GlobalLock(nint memory); + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GlobalUnlock(nint memory); + [DllImport("kernel32.dll", SetLastError = true)] internal static extern nuint GlobalSize(nint memory); + [DllImport("kernel32.dll")] internal static extern nint GlobalFree(nint memory); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint GetFinalPathNameByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, StringBuilder path, uint length, uint flags); + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetProcessTimes(Microsoft.Win32.SafeHandles.SafeProcessHandle process, out long created, out long exited, out long kernel, out long user); + [DllImport("wintrust.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int WinVerifyTrust(nint window, ref Guid action, ref TrustData data); + [DllImport("wintrust.dll")] internal static extern nint WTHelperProvDataFromStateData(nint state); + [DllImport("wintrust.dll")] internal static extern nint WTHelperGetProvSignerFromChain(nint provider, uint signer, [MarshalAs(UnmanagedType.Bool)] bool counterSigner, uint counter); + + [StructLayout(LayoutKind.Sequential)] internal struct ProviderSigner + { + internal uint Size, VerifyTimeLow, VerifyTimeHigh, CertificateCount; + internal nint Certificates; + } + [StructLayout(LayoutKind.Sequential)] internal struct ProviderCertificate + { + internal uint Size; + internal nint Certificate; + } + [StructLayout(LayoutKind.Sequential)] internal struct CertificateContext + { + internal uint Encoding; + internal nint Encoded; + internal uint EncodedSize; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TrustFile + { + internal uint Size; + [MarshalAs(UnmanagedType.LPWStr)] internal string Path; + internal nint Handle, Subject; + } + [StructLayout(LayoutKind.Sequential)] internal struct TrustData + { + internal uint Size; + internal nint PolicyCallback, SipClient; + internal uint UiChoice, RevocationChecks, UnionChoice; + internal nint File; + internal uint StateAction; + internal nint StateData, UrlReference; + internal uint ProviderFlags, UiContext; + internal nint SignatureSettings; + } +} diff --git a/packages/experimental/cua-windows/native/src/WindowCapture.cs b/packages/experimental/cua-windows/native/src/WindowCapture.cs new file mode 100644 index 0000000000..b72a219b3f --- /dev/null +++ b/packages/experimental/cua-windows/native/src/WindowCapture.cs @@ -0,0 +1,243 @@ +// Windows Graphics Capture returns the selected window even when another window covers it. +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using DeepSeek.Cua.Protocol; +using Vortice.Direct3D; +using Vortice.Direct3D11; +using Vortice.DXGI; +using WinRT; +using global::Windows.Graphics.Capture; +using global::Windows.Graphics.DirectX; +using global::Windows.Graphics.DirectX.Direct3D11; + +namespace DeepSeek.Cua.Windows; + +internal sealed class WindowCapture : IAsyncDisposable +{ + private readonly MtaDispatcher dispatcher = new(); + private readonly CaptureAdmission admission = new(); + private ID3D11Device? device; + private ID3D11DeviceContext? immediate; + private IDirect3DDevice? captureDevice; + + internal Task IsSupported(CancellationToken cancellation) + => dispatcher.Invoke(GraphicsCaptureSession.IsSupported, cancellation); + + private void EnsureDevice() + { + if (device is not null) return; + var created = D3D11.D3D11CreateDevice(DriverType.Hardware, DeviceCreationFlags.BgraSupport); + try + { + using var dxgi = created.QueryInterface(); + Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi.NativePointer, out var pointer)); + try { captureDevice = MarshalInterface.FromAbi(pointer); } + finally { Marshal.Release(pointer); } + immediate = created.ImmediateContext; + device = created; + } + catch { created.Dispose(); throw; } + } + + internal async Task Capture(AppState app, WindowState window, RequestContext context) + { + if (!await IsSupported(context.Cancellation)) throw new NativeFailure("UNSUPPORTED", "Windows Graphics Capture is unavailable on this desktop"); + var geometry = window.Geometry(app, context); + if (!window.IsOnScreen()) throw new NativeFailure("WINDOW_NOT_VISIBLE", "Restore the selected window with show and observe again before capturing"); + try + { + var operation = admission.Start(() => CaptureOwned(window.Handle, geometry, context)); + var data = await operation.WaitAsync(context.Cancellation); + var current = window.Geometry(app, context); + if (current.Pixels.Width != geometry.Pixels.Width || current.Pixels.Height != geometry.Pixels.Height || current.Dpi != geometry.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window changed during capture; observe again"); + DesktopSession.RequireInteractive(); + window.Observe(current); + return new { mimeType = "image/png", data = Convert.ToBase64String(data), pixelWidth = geometry.Pixels.Width, + pixelHeight = geometry.Pixels.Height, windowId = window.Id, bounds = current.Bounds, coordinateSpace = "window-pixels" }; + } + catch (COMException error) + { + throw new NativeFailure(error.HResult == unchecked((int)0x80070005) ? "PERMISSION_DENIED" : "CAPTURE_FAILED", + $"Windows refused the selected window capture (0x{error.HResult:X8}); restore the window and read fresh state"); + } + } + + private async Task CaptureOwned(nint window, WindowGeometry geometry, RequestContext context) + { + CaptureRequest? request = null; + try + { + await dispatcher.Invoke(() => + { + EnsureDevice(); + request = new CaptureRequest(this, window, geometry, context); + return true; + }, context.Cancellation); + return await request!.Result.WaitAsync(context.Cancellation); + } + finally + { + if (request is not null) await dispatcher.Invoke(() => { request.Dispose(); return true; }, CancellationToken.None); + } + } + + private sealed class CaptureRequest : IDisposable + { + private readonly object gate = new(); + private readonly TaskCompletionSource result = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly WindowCapture owner; + private readonly WindowGeometry geometry; + private readonly RequestContext context; + private readonly GraphicsCaptureItem item; + private Direct3D11CaptureFramePool? pool; + private GraphicsCaptureSession? session; + private bool disposed; + + internal Task Result => result.Task; + + internal CaptureRequest(WindowCapture owner, nint window, WindowGeometry geometry, RequestContext context) + { + this.owner = owner; this.geometry = geometry; this.context = context; + item = ItemForWindow(window); + if (item.Size.Width != geometry.Pixels.Width || item.Size.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "Windows capture bounds differ from the observed window; restore it and observe again"); + try + { + pool = Direct3D11CaptureFramePool.CreateFreeThreaded(owner.captureDevice!, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); + pool.FrameArrived += Frame; + item.Closed += Closed; + session = pool.CreateCaptureSession(item); + session.IsCursorCaptureEnabled = false; + session.StartCapture(); + } + catch { Dispose(); throw; } + } + + private void Closed(GraphicsCaptureItem sender, object args) => result.TrySetException(new NativeFailure("WINDOW_CHANGED", "The selected window closed during capture")); + + private void Frame(Direct3D11CaptureFramePool sender, object args) + { + lock (gate) + { + if (disposed || result.Task.IsCompleted) return; + try + { + context.Check(); + using var frame = sender.TryGetNextFrame(); + if (frame is null) return; + if (frame.ContentSize.Width != geometry.Pixels.Width || frame.ContentSize.Height != geometry.Pixels.Height) + throw new NativeFailure("WINDOW_CHANGED", "The capture frame dimensions changed"); + result.TrySetResult(owner.Encode(frame.Surface, geometry.Pixels.Width, geometry.Pixels.Height, context)); + } + catch (Exception error) { result.TrySetException(error); } + } + } + + public void Dispose() + { + lock (gate) + { + if (disposed) return; + disposed = true; + item.Closed -= Closed; + if (pool is not null) pool.FrameArrived -= Frame; + } + // Native disposal can wait for callbacks; queued callbacks must be able to observe disposed. + session?.Dispose(); + pool?.Dispose(); + } + } + + private byte[] Encode(IDirect3DSurface surface, int width, int height, RequestContext context) + { + var access = surface.As(); + var textureId = typeof(ID3D11Texture2D).GUID; + Marshal.ThrowExceptionForHR(access.GetInterface(ref textureId, out var pointer)); + using var texture = new ID3D11Texture2D(pointer); + if (texture.Description.Width != width || texture.Description.Height != height || texture.Description.Format != Format.B8G8R8A8_UNorm) + throw new NativeFailure("WINDOW_CHANGED", "The captured texture differs from the selected window geometry"); + var description = new Texture2DDescription(Format.B8G8R8A8_UNorm, (uint)width, (uint)height, + mipLevels: 1, bindFlags: BindFlags.None, usage: ResourceUsage.Staging, cpuAccessFlags: CpuAccessFlags.Read); + using var staging = device!.CreateTexture2D(description); + immediate!.CopyResource(staging, texture); + var mapped = immediate.Map(staging, 0, MapMode.Read); + using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + try + { + var pixels = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + try + { + var row = new byte[checked(width * 4)]; + for (var y = 0; y < height; y++) + { + context.Check(); + Marshal.Copy(mapped.DataPointer + checked(y * (int)mapped.RowPitch), row, 0, row.Length); + Marshal.Copy(row, 0, pixels.Scan0 + y * pixels.Stride, row.Length); + } + } + finally { bitmap.UnlockBits(pixels); } + } + finally { immediate.Unmap(staging, 0); } + context.Check(); + using var output = new MemoryStream(); + bitmap.Save(output, ImageFormat.Png); + if (output.Length * 4 / 3 > context.Config.MaxResponseBytes) + throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The screenshot exceeds the response byte limit"); + return output.ToArray(); + } + + private static GraphicsCaptureItem ItemForWindow(nint window) + { + const string className = "Windows.Graphics.Capture.GraphicsCaptureItem"; + Marshal.ThrowExceptionForHR(WindowsCreateString(className, className.Length, out var name)); + nint factoryPointer = 0; + object? factory = null; + try + { + var factoryId = typeof(IGraphicsCaptureItemInterop).GUID; + Marshal.ThrowExceptionForHR(RoGetActivationFactory(name, ref factoryId, out factoryPointer)); + factory = Marshal.GetObjectForIUnknown(factoryPointer); + var itemId = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); + Marshal.ThrowExceptionForHR(((IGraphicsCaptureItemInterop)factory).CreateForWindow(window, ref itemId, out var item)); + try { return MarshalInterface.FromAbi(item); } + finally { Marshal.Release(item); } + } + finally + { + if (factory is not null) Marshal.FinalReleaseComObject(factory); + if (factoryPointer != 0) Marshal.Release(factoryPointer); + WindowsDeleteString(name); + } + } + + public async ValueTask DisposeAsync() + { + await admission.Join(); + await dispatcher.Invoke(() => + { + captureDevice?.Dispose(); + immediate?.Dispose(); + device?.Dispose(); + return true; + }, CancellationToken.None); + await dispatcher.DisposeAsync(); + } + + [ComImport, Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IGraphicsCaptureItemInterop + { + [PreserveSig] int CreateForWindow(nint window, ref Guid id, out nint item); + [PreserveSig] int CreateForMonitor(nint monitor, ref Guid id, out nint item); + } + [ComImport, Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IDirect3DDxgiInterfaceAccess + { + [PreserveSig] int GetInterface(ref Guid id, out nint value); + } + [DllImport("d3d11.dll", ExactSpelling = true)] private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint device, out nint result); + [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern int WindowsCreateString(string source, int length, out nint value); + [DllImport("combase.dll")] private static extern int WindowsDeleteString(nint value); + [DllImport("combase.dll")] private static extern int RoGetActivationFactory(nint name, ref Guid id, out nint value); +} diff --git a/packages/experimental/cua-windows/native/src/Windows.cs b/packages/experimental/cua-windows/native/src/Windows.cs new file mode 100644 index 0000000000..08ec60d145 --- /dev/null +++ b/packages/experimental/cua-windows/native/src/Windows.cs @@ -0,0 +1,176 @@ +// Public window IDs never expose or revive a reused HWND. +using System.Runtime.InteropServices; +using System.Text; +using DeepSeek.Cua.Protocol; + +namespace DeepSeek.Cua.Windows; + +internal readonly record struct Bounds(double X, double Y, double Width, double Height); +internal readonly record struct WindowGeometry(Win32.Rect Pixels, uint Dpi) +{ + internal Bounds Bounds => new(Pixels.Left, Pixels.Top, Pixels.Width, Pixels.Height); +} + +internal sealed class WindowState(uint id, nint handle, long epoch) +{ + internal uint Id { get; } = id; + internal nint Handle { get; } = handle; + internal long Epoch { get; } = epoch; + private WindowGeometry? observation; + + internal WindowGeometry Geometry(AppState app, RequestContext context) + { + context.Check(); + var process = app.RequireProcess(); + Win32.GetWindowThreadProcessId(Handle, out var pid); + if (!Win32.IsWindow(Handle) || pid != process.Pid || context.Sta.WindowEpoch(Handle) != Epoch) + throw new NativeFailure("WINDOW_CHANGED", "The selected window was destroyed or replaced; read fresh application state"); + if (Win32.DwmGetWindowAttribute(Handle, 9, out Win32.Rect rectangle, Marshal.SizeOf()) != 0 + && !Win32.GetWindowRect(Handle, out rectangle)) throw new NativeFailure("WINDOW_CHANGED", "The selected window geometry is unavailable"); + var dpi = Win32.GetDpiForWindow(Handle); + if (dpi == 0 || rectangle.Width <= 0 || rectangle.Height <= 0) + throw new NativeFailure("WINDOW_CHANGED", "The selected window has no usable bounds"); + return new(rectangle, dpi); + } + + internal void Observe(WindowGeometry value) => observation = value; + + internal WindowGeometry RequireObservation(AppState app, RequestContext context) + { + var current = Geometry(app, context); + if (observation is not { } previous) throw new NativeFailure("OBSERVATION_REQUIRED", "Read AX state or capture this window before using coordinates"); + if (current.Pixels.Width != previous.Pixels.Width || current.Pixels.Height != previous.Pixels.Height || current.Dpi != previous.Dpi) + throw new NativeFailure("WINDOW_CHANGED", "The window size or display scale changed; read fresh state before input"); + return current; + } + + internal static Win32.Point Point(WindowGeometry geometry, double x, double y) + { + if (!double.IsFinite(x) || !double.IsFinite(y) || x < 0 || y < 0 || x >= geometry.Bounds.Width || y >= geometry.Bounds.Height) + throw new NativeFailure("INVALID_ARGUMENT", "Coordinates must be inside the observed window"); + return new() + { + X = geometry.Pixels.Left + Math.Min(geometry.Pixels.Width - 1, (int)Math.Round(x)), + Y = geometry.Pixels.Top + Math.Min(geometry.Pixels.Height - 1, (int)Math.Round(y)), + }; + } + + internal object Describe(AppState app, RequestContext context) + { + var geometry = Geometry(app, context); + var length = Win32.GetWindowTextLength(Handle); + if (length > context.Config.MaxResponseBytes) throw new NativeFailure("NATIVE_RESPONSE_LIMIT", "The window title exceeds the response limit"); + var title = new StringBuilder(length + 1); + Win32.GetWindowText(Handle, title, title.Capacity); + return new + { + windowId = Id, pid = 4, appName = app.RequireProcess().Name, + title = title.ToString(), bounds = geometry.Bounds, isOnScreen = IsOnScreen(), onCurrentSpace = (bool?)null, + }; + } + + internal bool IsOnScreen() => Win32.IsWindowVisible(Handle) && !Win32.IsIconic(Handle) + && (Win32.DwmGetWindowAttribute(Handle, 14, out int cloaked, sizeof(int)) != 0 || cloaked == 0); +} + +internal static class Windows +{ + internal static WindowState[] Refresh(AppState app, RequestContext context) + { + var process = app.RequireProcess(); + if (app.SelectedWindow is { } selected) { selected.Geometry(app, context); return [selected]; } + var handles = new List(); + Win32.EnumWindows((window, _) => + { + Win32.GetWindowThreadProcessId(window, out var pid); + var style = Win32.GetWindowLongPtr(window, -16).ToInt64(); + var extended = Win32.GetWindowLongPtr(window, -20).ToInt64(); + if (pid == process.Pid && (extended & 0x80) == 0 + && (Win32.IsWindowVisible(window) || (style & 0x00C00000) == 0x00C00000) + && Win32.GetWindowRect(window, out var bounds) && bounds.Width > 0 && bounds.Height > 0) handles.Add(window); + return true; + }, 0); + foreach (var pair in app.Windows.ToArray()) + { + if (handles.Contains(pair.Key) && pair.Value.Epoch == context.Sta.WindowEpoch(pair.Key)) continue; + app.Windows.Remove(pair.Key); + foreach (var scope in app.Snapshots.Where(item => item.Value.Windows.Any(window => window.Id == pair.Value.Id)).Select(item => item.Key).ToArray()) + app.Snapshots.Remove(scope); + } + foreach (var handle in handles) + { + if (!app.Windows.ContainsKey(handle)) + { + app.Windows.Add(handle, new(app.AllocateWindowId(), handle, context.Sta.WindowEpoch(handle))); + } + } + return handles.Select(handle => app.Windows[handle]).ToArray(); + } + + internal static WindowState Resolve(AppState app, uint id, RequestContext context) => Refresh(app, context) + .SingleOrDefault(window => window.Id == id) ?? throw new NativeFailure("WINDOW_CHANGED", "Select a current window from getWindows"); + + internal static WindowState? Focused(AppState app, WindowState[] windows) + { + var foreground = Win32.GetAncestor(Win32.GetForegroundWindow(), 2); + var front = windows.FirstOrDefault(window => window.Handle == foreground); + if (front is not null) return front; + var roots = new HashSet(); + foreach (var thread in windows.Select(window => Win32.GetWindowThreadProcessId(window.Handle, out _)).Distinct()) + { + var info = new Win32.GuiThreadInfo { Size = (uint)Marshal.SizeOf() }; + if (Win32.GetGUIThreadInfo(thread, ref info)) + { + var focused = Win32.GetAncestor(info.Focus != 0 ? info.Focus : info.Active, 2); + if (focused != 0) roots.Add(focused); + } + } + var matches = windows.Where(window => roots.Contains(window.Handle)).ToArray(); + return matches.Length == 1 ? matches[0] : null; + } + + internal static WindowState? Default(AppState app, WindowState[] windows) + { + var visible = windows.Where(window => window.IsOnScreen()).ToArray(); + var focused = Focused(app, visible); + if (focused is not null) return focused; + if (visible.Length == 1) return visible[0]; + if (visible.Length == 0 && windows.Length <= 1) return windows.SingleOrDefault(); + throw new NativeFailure("AMBIGUOUS_WINDOW", "Select a window explicitly from getWindows"); + } + + internal static object Show(AppState app, uint? id, RequestContext context) + { + var target = id is { } selected ? Resolve(app, selected, context) : Default(app, Refresh(app, context)); + var before = Win32.GetForegroundWindow(); + if (target is not null) + { + target.Geometry(app, context); + if (!Win32.ShowWindowAsync(target.Handle, 4)) throw new NativeFailure("UNSUPPORTED", "Windows refused background restoration; explicitly activate the application if needed"); + } + var after = Win32.GetForegroundWindow(); + return new { dispatched = true, windowId = (uint?)target?.Id, + foregroundChanged = before == 0 || after == 0 ? (bool?)null : before != after }; + } + + internal static void Activate(AppState app, WindowState? target, RequestContext context) + { + target ??= Default(app, Refresh(app, context)) ?? throw new NativeFailure("WINDOW_NOT_FOUND", "The application has no window to activate"); + target.Geometry(app, context); + if (Win32.IsIconic(target.Handle)) Win32.ShowWindowAsync(target.Handle, 9); + if (Win32.GetForegroundWindow() != target.Handle && !Win32.SetForegroundWindow(target.Handle)) + throw new NativeFailure("FOREGROUND_DENIED", "Windows refused foreground access; ask the user to focus the target window"); + } + + internal static void RequireForeground(AppState app, WindowState? target, RequestContext context) + { + context.Check(); + DesktopSession.RequireInteractive(); + target ??= app.SelectedWindow; + target?.Geometry(app, context); + var foreground = Win32.GetForegroundWindow(); + Win32.GetWindowThreadProcessId(foreground, out var pid); + if (pid != app.RequireProcess().Pid || target is not null && Win32.GetAncestor(foreground, 2) != target.Handle) + throw new NativeFailure("FOREGROUND_REQUIRED", "This input needs the target in front; explain why, explicitly activate or raise it, then observe again"); + } +} diff --git a/packages/experimental/cua-windows/native/tests/Program.cs b/packages/experimental/cua-windows/native/tests/Program.cs new file mode 100644 index 0000000000..b12458997a --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Program.cs @@ -0,0 +1,96 @@ +// Portable checks exercise admission, framing, text offsets, and model-visible formatting. +using System.Text; +using DeepSeek.Cua.Protocol; +using DeepSeek.Cua.Windows; + +var checks = 0; +void Check(bool condition, string message) +{ + if (!condition) throw new Exception(message); + checks++; +} +void Refuses(Action action, string code) +{ + try { action(); throw new Exception("Expected refusal: " + code); } + catch (NativeFailure failure) { Check(failure.Code == code, "Unexpected refusal: " + failure.Code); } +} + +var request = NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":20,"maxDepth":5}}""")); +Check(request.Method == "getState" && request.Id == "one", "Valid requests retain correlation and method"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"click","params":{"appHandle":"app","windowId":1,"x":-1,"y":2}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"getState","params":{"appHandle":"app","maxElements":0,"maxDepth":5}}""")), "INVALID_ARGUMENT"); +Refuses(() => NativeRequest.Parse(WireJson.Parse("""{"id":"one","method":"typeText","params":{"appHandle":"app","text":"hello","unowned":1}}""")), "INVALID_ARGUMENT"); +Refuses(() => WireJson.Parse("""{"id":"one","id":"two"}"""), "INVALID_REQUEST"); +Refuses(() => WireJson.Parse("""{"params":{"x":1,"x":2}}"""), "INVALID_REQUEST"); +Check(NativeRequest.Parse(WireJson.Parse("""{"id":"launch","method":"launchApp","params":{"appHandle":"pending"}}""")).Method == "launchApp", "Host launch continuation remains admitted"); + +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"close"}"""), null) == NativeControl.Close, "Connection close needs no active operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one") == NativeControl.Cancel, "Cancellation matches the live operation"); +Check(NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), "one", completed: true) == NativeControl.CompletedCancel, + "Cancellation arriving after the matching response is a no-op"); +foreach (var frame in new[] { "null", "[]", "{}", "{\"type\":1}", + "{\"type\":\"close\",\"extra\":1}", "{\"type\":\"cancel\"}", + "{\"type\":\"cancel\",\"id\":null}", "{\"type\":\"cancel\",\"id\":1}", + "{\"type\":\"cancel\",\"id\":\"other\"}", "{\"type\":\"cancel\",\"id\":\"one\",\"extra\":1}" }) + Refuses(() => NativeControlFrame.Parse(WireJson.Parse(frame), "one"), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":null}"""), null), "INVALID_REQUEST"); +Refuses(() => NativeControlFrame.Parse(WireJson.Parse("""{"type":"cancel","id":"one"}"""), null), "INVALID_REQUEST"); + +var bytes = Encoding.UTF8.GetBytes("你好\nnext\n"); +var reader = new FrameReader(new MemoryStream(bytes)); +Check(await reader.ReadAsync(7, CancellationToken.None) == "你好", "Frame limits count UTF-8 bytes including newline"); +Check(await reader.ReadAsync(5, CancellationToken.None) == "next", "Buffered next frames remain readable"); +Check(await reader.ReadAsync(1, CancellationToken.None) is null, "Clean EOF is distinct from a partial frame"); +try { await new FrameReader(new MemoryStream(bytes)).ReadAsync(6, CancellationToken.None); throw new Exception("Oversized frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "NATIVE_REQUEST_LIMIT", "Oversized UTF-8 frames fail before parsing"); } +try { await new FrameReader(new MemoryStream("partial"u8.ToArray())).ReadAsync(20, CancellationToken.None); throw new Exception("Partial frame accepted"); } +catch (NativeFailure failure) { Check(failure.Code == "INVALID_REQUEST", "Partial EOF is rejected"); } +try { await new FrameReader(new MemoryStream([0xff, 0x0a])).ReadAsync(2, CancellationToken.None); throw new Exception("Invalid UTF-8 accepted"); } +catch (DecoderFallbackException) { checks++; } + +Check(TextSelection.Find("😀 first repeat; second repeat", "repeat", "second ", null) == new TextMatch(24, 6), "Offsets use UTF-16 including surrogate pairs"); +Refuses(() => TextSelection.Find("repeat repeat", "repeat", null, null), "AMBIGUOUS_TEXT"); +Refuses(() => TextSelection.Find("repeat", "other", null, null), "TEXT_NOT_FOUND"); +Refuses(() => TextSelection.Find("text", "", null, null), "INVALID_ARGUMENT"); +Check(TextSelection.Find("aaaa", "aa", "aa", null) == new TextMatch(2, 2), "Overlapping literal matches retain adjacent context"); + +var html = HtmlClipboard.Encode("你好😀"); +var header = Encoding.UTF8.GetString(html); +int Offset(string name) => int.Parse(header.Split('\n').Single(line => line.StartsWith(name + ':')).Split(':')[1].Trim()); +Check(Encoding.UTF8.GetString(html, Offset("StartFragment"), Offset("EndFragment") - Offset("StartFragment")) == "你好😀", "CF_HTML byte offsets preserve Unicode"); +Check(Offset("EndHTML") == html.Length - 1, "CF_HTML excludes the terminating NUL"); + +Check(KeyChord.Parse("ctrl++", []).Key == "+", "Plus key remains a key after chord parsing"); +Check(KeyChord.Parse("+", []).Modifiers.Length == 0, "Bare plus has no modifier"); +Check(KeyChord.Parse("Control+a", ["ctrl"]).Modifiers.SequenceEqual(["control"]), "Equivalent modifiers deduplicate"); +Refuses(() => KeyChord.Parse("ctrl+", []), "INVALID_ARGUMENT"); +Refuses(() => KeyChord.Parse("fn+a", []), "UNSUPPORTED"); + +var node = new AccessibilityNode { Role = "AXTextField", Name = "Title", Value = "", HasValue = true, Placeholder = "Title", ValueWritable = "true", Actions = ["Press", "Focus"] }; +var text = AccessibilityText.Format(node, 3, false); +Check(text.Contains("= \"\" placeholder=\"Title\""), "Empty values and placeholders remain distinct"); +Check(!text.Contains("\"Press\"") && text.Contains("\"Focus\""), "Common actions compact without hiding secondary actions"); +Check(AccessibilityText.Format(node, 3, true).Contains("\"Press\""), "Details retain complete action names"); +Check(!AccessibilityText.Retain(new() { Role = "AXGroup" }), "Empty structural containers can collapse"); +Check(AccessibilityText.Retain(new() { Role = "AXGroup", Actions = ["Copy"] }), "Actionable containers retain their row"); +Check(AccessibilityText.Format(new() { Role = "AXTextArea", Value = "abc", HasValue = true, HasSelection = true, Selection = new(2, 5) }, 0, false) + .Contains("selection=unavailable"), "Out-of-range selections do not describe valid text"); +var captures = new CaptureAdmission(); +var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); +var ownedCapture = captures.Start(() => cleanup.Task); +using var cancelled = new CancellationTokenSource(); +cancelled.Cancel(); +try { await ownedCapture.WaitAsync(cancelled.Token); throw new Exception("Cancelled capture caller remained attached"); } +catch (OperationCanceledException) { checks++; } +Refuses(() => captures.Start(() => Task.FromResult(new byte[] { 2 })), "CAPTURE_BUSY"); +var joined = captures.Join(); +Check(!joined.IsCompleted, "Native cleanup retains ownership after its caller stops waiting"); +cleanup.SetResult([1]); +await joined; +Check((await captures.Start(() => Task.FromResult(new byte[] { 2 })))[0] == 2, "Completed cleanup admits a fresh capture"); +var failed = captures.Start(() => Task.FromException(new NativeFailure("CAPTURE_FAILED", "device lost"))); +try { await failed; throw new Exception("Capture error disappeared"); } +catch (NativeFailure failure) { Check(failure.Code == "CAPTURE_FAILED", "Capture failure remains attached to its requesting connection"); } +await captures.Join(); +Check((await captures.Start(() => Task.FromResult(new byte[] { 3 })))[0] == 3, "A settled capture failure does not reserve a permanent slot"); +Console.WriteLine($"{checks} portable CUA checks passed"); diff --git a/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj new file mode 100644 index 0000000000..9ad2abfcee --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/Protocol.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + true + + + + diff --git a/packages/experimental/cua-windows/native/tests/packages.lock.json b/packages/experimental/cua-windows/native/tests/packages.lock.json new file mode 100644 index 0000000000..f693fbd9af --- /dev/null +++ b/packages/experimental/cua-windows/native/tests/packages.lock.json @@ -0,0 +1,40 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Humanizer.Core": { + "type": "Transitive", + "resolved": "3.0.10", + "contentHash": "yZIhtw8sYuvsONzQbZxWpR60tMWYHXoo0DL6nyOqSFiU5POjBTSEyWFpTQtJEZuy+oqiYTXKXY/Mjx7KnqIQFw==" + }, + "Json.More.Net": { + "type": "Transitive", + "resolved": "3.0.1", + "contentHash": "fRctF2J2SILYG6wqP21drmeEODmCVkVQ/b3MndDu2fT1swfySyUgq7ePCk+aENGlDcIm05fyfjh9vcuqDEfv3w==" + }, + "JsonPointer.Net": { + "type": "Transitive", + "resolved": "7.0.2", + "contentHash": "oClYHv2ooeRrtPZyC9sb/Za/ie5pGhjTbNHlAyFg4XOCyU+606FdoZKS7UdaWvtsPlrF+U2w0Ja3TRvn5+spyA==", + "dependencies": { + "Humanizer.Core": "3.0.10", + "Json.More.Net": "3.0.1" + } + }, + "JsonSchema.Net": { + "type": "Transitive", + "resolved": "9.4.0", + "contentHash": "muE4nPuzbD9x5XA1mkXJNqX4mhz47oF3EY8qFLY1pyUY7lhXFKq65t/dSKIHeNSLBV17zwZuq24MD1em90rMNg==", + "dependencies": { + "JsonPointer.Net": "7.0.2" + } + }, + "cuaprotocol": { + "type": "Project", + "dependencies": { + "JsonSchema.Net": "[9.4.0, )" + } + } + } + } +} diff --git a/packages/experimental/cua-windows/package.json b/packages/experimental/cua-windows/package.json new file mode 100644 index 0000000000..b2779ebe25 --- /dev/null +++ b/packages/experimental/cua-windows/package.json @@ -0,0 +1,95 @@ +{ + "name": "@deepseek-ai/dsh-cua-windows", + "description": "Windows C# computer use through shared application and window objects", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/cua-windows" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*" + }, + "dependencies": { + "zod": "4.6.6", + "@deepseek-ai/dsh-cua": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-native-command": "workspace:*", + "@deepseek-ai/dsh-atomic-write": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek": "workspace:*", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-sandbox-local": "workspace:*", + "@deepseek-ai/dsh-sandbox-policy": "workspace:*", + "sharp": "^0.35.3", + "@deepseek-ai/dsh-ptc-runtime": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*", + "@deepseek-ai/dsh-settings": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", + "@deepseek-ai/dsh-config-editor": "workspace:*", + "@deepseek-ai/dsh-hmr": "workspace:*", + "@deepseek-ai/cordis-plugin-timer": "workspace:~" + }, + "files": [ + "lib/index.js", + "native/bin", + "native/CuaWindows.csproj", + "native/Directory.Build.props", + "native/app.manifest", + "native/src", + "native/protocol", + "native/protocol.schema.json", + "native/packages.lock.json", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "scripts": { + "build:native": "dotnet publish native/CuaWindows.csproj --configuration Release --runtime win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableWindowsTargeting=true" + }, + "os": [ + "win32", + "linux" + ] +} diff --git a/packages/experimental/cua-windows/src/guidance.ts b/packages/experimental/cua-windows/src/guidance.ts new file mode 100644 index 0000000000..7c844eb1a0 --- /dev/null +++ b/packages/experimental/cua-windows/src/guidance.ts @@ -0,0 +1,2 @@ +/** TODO: Windows platform guidance after the interface migration. */ +export const GUIDANCE = 'TODO: Windows Computer Use guidance.' diff --git a/packages/experimental/cua-windows/src/index.ts b/packages/experimental/cua-windows/src/index.ts new file mode 100644 index 0000000000..f74f61b539 --- /dev/null +++ b/packages/experimental/cua-windows/src/index.ts @@ -0,0 +1,91 @@ +/** Windows C# provider for the shared Computer Use application and window API. */ +import { isAbsolute, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import Schema from '@deepseek-ai/schemastery' +import { CuaConfig, installCua, type CuaStartupCapabilities } from '@deepseek-ai/dsh-cua' +import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' +import { prepareNativeExecutable, nativeHostArchitecture } from './native-build.ts' +import { WindowsNativeRuntime } from './native-runtime.ts' +import { GUIDANCE } from './guidance.ts' +import { windowsHost, prepareWsl, retainWslHelper } from './windows-host.ts' + +const CAPABILITIES: CuaStartupCapabilities = { + platform: 'windows', + methods: [ + 'getCapabilities', 'listApps', 'getApp', 'activate', 'show', 'listWindows', 'getState', + 'listActions', 'performAction', 'invoke', 'mouseMove', 'click', 'setValue', 'selectText', + 'typeText', 'paste', 'pressKey', 'scroll', 'drag', 'screenshot', + ], + appLevelAccessibility: false, + keyboard: ['window'], + browser: false, + coordinateSpace: 'screenshot-pixels', +} + +/** Loader identity of the Windows provider. */ +export const name = 'cua-windows' +/** Services required by shared CUA execution and managed native preparation. */ +export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'agents'] + +/** Windows compiler and native waiting policy, alongside shared CUA resource limits. */ +export interface Config extends CuaConfig { + /** .NET SDK executable used for source preparation; installed payloads do not require it. */ + dotnetPath: string + /** Windows PowerShell executable used to query WSL interoperation and the Windows architecture. */ + windowsPowerShellPath: string + /** Milliseconds between application-readiness and clipboard-release observations. */ + pollIntervalMs: number +} + +/** Validate platform configuration before launching the compiler or helper. */ +export const Config = Schema.object({ + ...CuaConfigFields, + connectTimeoutMs: CuaConfigFields.connectTimeoutMs.default(30_000), + dotnetPath: Schema.string().min(1).default('dotnet'), + windowsPowerShellPath: Schema.string().min(1).default('powershell.exe'), + pollIntervalMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(25), + textEventIntervalMs: CuaConfigFields.textEventIntervalMs.default(0), + maxRequestBytes: CuaConfigFields.maxRequestBytes.max(2 ** 31 - 1), + maxResponseBytes: CuaConfigFields.maxResponseBytes.max(2 ** 31 - 1), + maxClipboardBytes: CuaConfigFields.maxClipboardBytes.max(2 ** 31 - 1), +}) satisfies Schema, Config> + +/** + * Prepare the Windows payload and install the shared authorized operation pipeline. + * @param ctx - Owning provider context. + * @param config - Validated compiler, operation bounds, and application grants. + * @returns Completion after preparation and reversible registrations. + */ +export async function apply(ctx: Context, config: Config): Promise { + const host = windowsHost() + if (config.helperPath !== undefined && !isAbsolute(config.helperPath)) throw new Error('Windows CUA helperPath must be absolute') + const controller = new AbortController() + const prepare = async () => { + const wsl = host === 'wsl' ? await prepareWsl({ subprocess: ctx.subprocess, signal: controller.signal, + timeoutMs: config.connectTimeoutMs, graceMs: config.graceMs, powershellPath: config.windowsPowerShellPath }) : undefined + let helperPath = config.helperPath + if (helperPath === undefined) { + const architecture = wsl?.architecture ?? nativeHostArchitecture(process.platform, process.arch) + helperPath = await prepareNativeExecutable({ + packageRoot: resolve(fileURLToPath(new URL('..', import.meta.url))), architecture, dotnetPath: config.dotnetPath, + subprocess: ctx.subprocess, signal: controller.signal, timeoutMs: config.buildTimeoutMs, graceMs: config.graceMs, + }) + } + return wsl ? retainWslHelper(helperPath, wsl.cacheDirectory, controller.signal) : helperPath + } + const prepared = prepare() + ctx.effect(() => async () => { + controller.abort() + // Activation owns preparation failures; disposal joins the same operation. + await prepared.catch(() => {}) + }, 'cua-windows.native-preparation') + const helperPath = await prepared + controller.signal.throwIfAborted() + const runtime = new WindowsNativeRuntime(ctx, config.pollIntervalMs, host === 'wsl' ? 'stdio' : 'pipe') + ctx.effect(() => () => runtime.dispose(), 'cua-windows.native-runtime') + installCua(ctx, config, { + helperPath, createChannel: (_owner, native) => runtime.connect(native), guidance: GUIDANCE, capabilities: CAPABILITIES, + permissionParameters: (_method, permission) => ({ permission }), + }) +} diff --git a/packages/experimental/cua-windows/src/native-build.ts b/packages/experimental/cua-windows/src/native-build.ts new file mode 100644 index 0000000000..f87e93390f --- /dev/null +++ b/packages/experimental/cua-windows/src/native-build.ts @@ -0,0 +1,73 @@ +/** Source compilation and installed Windows C# helper resolution. */ +import { constants } from 'node:fs' +import { access } from 'node:fs/promises' +import { join } from 'node:path' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable as compileExecutable, sourceNativePackage } from '@deepseek-ai/dsh-cua/native-build' + +/** Architectures supported by the Windows helper payload. */ +export type NativeArchitecture = 'arm64' | 'x64' + +/** Compiler invocation and resource ownership for one Windows payload. */ +export interface NativeBuildSpec { + packageRoot: string + architecture: NativeArchitecture + dotnetPath: string + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number +} + +/** + * Validate the runtime host before preparing Windows native code. + * @param platform - Node host platform. + * @param architecture - Node process architecture. + * @returns Supported Windows architecture. + */ +export function nativeHostArchitecture(platform: string, architecture: string): NativeArchitecture { + if (platform !== 'win32' || (architecture !== 'arm64' && architecture !== 'x64')) + throw new Error('The Windows Computer Use provider requires Windows on x64 or ARM64') + return architecture +} + +/** + * Locate the package-owned Windows executable. + * @param packageRoot - Directory containing the Windows provider manifest. + * @param architecture - Architecture of the process running the helper. + * @returns Absolute payload path. + */ +export function nativeExecutablePath(packageRoot: string, architecture: NativeArchitecture): string { + return join(packageRoot, 'native', 'bin', `win-${architecture}`, 'dsh-cua-windows.exe') +} + +/** + * Publish a self-contained C# executable; the build can run on macOS with Windows targeting enabled. + * @param spec - SDK command, target, compiler ownership, and deadlines. + * @returns Immutable content-addressed executable after compiler cleanup. + */ +export function buildNativeExecutable(spec: NativeBuildSpec): Promise { + const native = join(spec.packageRoot, 'native') + const output = join(native, '.build', `win-${spec.architecture}`) + return compileExecutable({ ...spec, + argv: [spec.dotnetPath, 'publish', join(native, 'CuaWindows.csproj'), '--configuration', 'Release', + '--runtime', `win-${spec.architecture}`, '--self-contained', 'true', '--output', output, + '-p:EnableWindowsTargeting=true'], + outputPath: join(output, 'dsh-cua-windows.exe'), executablePath: nativeExecutablePath(spec.packageRoot, spec.architecture), + lockPath: join(native, '.build', 'publish'), + retainedDirectory: join(native, '.build', 'prepared', spec.architecture), binaryName: 'dsh-cua-windows.exe', + }) +} + +/** + * Compile only source checkouts; installed packages require their packaged native payload. + * @param spec - Source build and runtime target inputs. + * @returns The ready executable path. + */ +export async function prepareNativeExecutable(spec: NativeBuildSpec): Promise { + if (await sourceNativePackage(spec.packageRoot, 'packages/experimental/cua-windows')) return buildNativeExecutable(spec) + const executable = nativeExecutablePath(spec.packageRoot, spec.architecture) + await access(executable, constants.X_OK) + spec.signal.throwIfAborted() + return executable +} diff --git a/packages/experimental/cua-windows/src/native-runtime.ts b/packages/experimental/cua-windows/src/native-runtime.ts new file mode 100644 index 0000000000..bf5da9aff3 --- /dev/null +++ b/packages/experimental/cua-windows/src/native-runtime.ts @@ -0,0 +1,354 @@ +/** Host-owned connector and independently disposable Agent connections to a shared Windows helper. */ +import { createHash, randomUUID } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { addAbortListener } from 'node:events' +import { realpath } from 'node:fs/promises' +import { PassThrough, Writable, type Readable, type Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeChannel, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { z } from 'zod' +import { connectWindowsPipe, type WindowsConnection, type WindowsTransport } from './native-transport.ts' + +const Ready = z.object({ + type: z.literal('ready'), protocol: z.literal(1), runtimeKey: z.string(), instanceId: z.string().min(1), +}).strict() +const Started = Ready.extend({ endpoint: z.string().min(1), launcherId: z.string().min(1) }).strict() +// Private transport control frames have fixed encoding; operation replies pass through unchanged. +const closedFrame = Buffer.from('{"type":"closed"}\n') +type Owner = { subprocess: Pick } + +function failure(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)) } + +async function interruptible(operation: Promise, signal: AbortSignal): Promise { + const cancelled = Promise.withResolvers() + using _listener = addAbortListener(signal, () => { cancelled.reject(signal.reason) }) + return await Promise.race([operation, cancelled.promise]) +} + +function firstFrame(stream: Readable, signal: AbortSignal): Promise<{ value: unknown; rest: Buffer }> { + signal.throwIfAborted() + return new Promise((resolve, reject) => { + let bytes = Buffer.alloc(0) + const clean = () => { + stream.off('data', data).off('error', rejectFrame).off('end', ended).off('close', ended) + signal.removeEventListener('abort', aborted) + } + const rejectFrame = (error: Error) => { clean(); reject(error) } + const ended = () => { rejectFrame(new NativeError('NATIVE_EOF', 'Helper ended before native readiness')) } + const aborted = () => { rejectFrame(failure(signal.reason)) } + const data = (chunk: Buffer) => { + const newline = chunk.indexOf(10) + const size = newline < 0 ? chunk.length : newline + 1 + if (bytes.length + size > 8192) { rejectFrame(new NativeError('NATIVE_PROTOCOL', 'Native readiness exceeded its byte limit')); return } + bytes = Buffer.concat([bytes, chunk.subarray(0, size)]) + if (newline < 0) return + stream.pause() + clean() + try { + resolve({ value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, -1))), rest: chunk.subarray(size) }) + } catch (error) { reject(new NativeError('NATIVE_PROTOCOL', 'Invalid native readiness frame', { cause: error })) } + } + stream.on('data', data).on('error', rejectFrame).on('end', ended).on('close', ended) + signal.addEventListener('abort', aborted, { once: true }) + }) +} + +class WindowsHelper { + readonly ready: Promise> + readonly done: Promise + readonly sockets = new Set() + private readonly readiness = Promise.withResolvers>() + private readonly startup = new AbortController() + private handle: SubprocessHandle | undefined + private phase: 'starting' | 'ready' | 'closing' | 'closed' = 'starting' + private stopTimer: ReturnType | undefined + private error: Error | undefined + + constructor(private readonly owner: Owner, private readonly config: NativeClientConfig) { + this.ready = this.readiness.promise + void this.ready.catch(() => {}) + this.done = this.run() + void this.done.catch(() => {}) + } + + get ended(): boolean { return this.phase === 'closing' || this.phase === 'closed' } + + async stop(): Promise { + if (!this.ended) { + this.phase = 'closing' + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Computer Use is shutting down')) + this.handle?.stdin?.end() + this.stopTimer = setTimeout(() => { this.handle?.terminate() }, this.config.graceMs) + } + await this.done + } + + private async run(): Promise { + const startupTimer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows helper did not become ready before connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, this.config.connectTimeoutMs) + try { + const helperPath = await realpath(this.config.helperPath) + const digest = createHash('sha256') + for await (const chunk of createReadStream(helperPath, { signal: this.startup.signal })) digest.update(chunk as Buffer) + const runtimeKey = digest.digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + this.startup.signal.throwIfAborted() + const handle = this.owner.subprocess.spawn({ + argv: [helperPath, '--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(this.config.connectTimeoutMs), '--grace-ms', String(this.config.graceMs)], + cwd: this.config.cwd, graceMs: this.config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + this.handle = handle + assert(handle.stdin && handle.stdout, 'The helper requested piped control and readiness streams') + handle.stdout.on('error', (error: Error) => { this.error ??= error; this.startup.abort(error) }) + const exit = handle.done.then((outcome) => { + const diagnostic = handle.collected.stderr?.readFrom(0).text.trim() || 'no diagnostic output' + throw new NativeError('NATIVE_EXITED', + `Windows helper exited before readiness (${String(outcome.exitCode)}): ${diagnostic}. Check Windows application-control policy and helper signing.`) + }) + let frame: Awaited> + try { frame = await Promise.race([firstFrame(handle.stdout, this.startup.signal), exit]) } catch (error) { + // EOF can precede process settlement and its final collected stderr. + if (error instanceof NativeError && error.code === 'NATIVE_EOF') await interruptible(exit, this.startup.signal) + throw error + } + const ready = Started.parse(frame.value) + if (ready.runtimeKey !== runtimeKey || ready.launcherId !== instanceId || frame.rest.length !== 0) + throw new NativeError('NATIVE_PROTOCOL', 'Windows helper readiness has another identity or unexpected output') + this.startup.signal.throwIfAborted() + handle.stdout.on('data', () => { + this.error ??= new NativeError('NATIVE_PROTOCOL', 'Windows helper wrote unsolicited readiness data') + void this.stop().catch((error: unknown) => { this.error ??= failure(error) }) + }) + handle.stdout.resume() + clearTimeout(startupTimer) + this.phase = 'ready' + this.readiness.resolve(ready) + const outcome = await handle.done + if (!this.ended) this.error ??= new NativeError('NATIVE_EXITED', + `Windows helper stopped (${String(outcome.exitCode)}, ${String(outcome.signal)}); select applications again`) + } catch (error) { this.error ??= failure(error) } + finally { + clearTimeout(startupTimer) + this.phase = 'closing' + const error = this.error ?? new NativeError('NATIVE_CLOSED', 'Windows helper closed; select applications again') + for (const socket of this.sockets) socket.destroy(error) + const handle = this.handle + try { + if (handle) { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, this.config.graceMs) + try { + await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows helper process range did not exit') + } finally { clearTimeout(timer) } + } + } finally { + clearTimeout(this.stopTimer) + this.phase = 'closed' + this.readiness.reject(error) + } + } + } +} + +class WindowsChannel implements NativeChannel { + readonly stdout = new PassThrough() + readonly stdin: Writable + readonly done: Promise + private readonly startup = new AbortController() + private readonly readiness = Promise.withResolvers() + private readonly closed: PromiseWithResolvers = Promise.withResolvers() + private socket: Duplex | undefined + private closing = false + private closeTimer: ReturnType | undefined + + constructor(helper: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport) { + this.stdin = new Writable({ + write: (chunk: Buffer, _encoding, callback) => { + void this.readiness.promise.then((socket) => { + if (this.closing) { callback(new NativeError('NATIVE_CLOSED', 'Native connection is closing')); return } + socket.write(chunk, callback) + }, callback) + }, + final: (callback) => { this.close(); callback() }, + destroy: (error, callback) => { this.close(); callback(error) }, + }) + for (const stream of [this.stdin, this.stdout]) stream.on('error', () => {}) + void this.readiness.promise.catch(() => {}) + void this.closed.promise.catch(() => {}) + this.done = this.run(helper, config, pollIntervalMs, owner, transport) + void this.done.catch(() => {}) + } + + close(): void { + if (this.closing) return + this.closing = true + this.startup.abort(new NativeError('NATIVE_CLOSED', 'Native connection closed before readiness')) + if (this.socket && !this.socket.destroyed) this.socket.write('{"type":"close"}\n') + } + + waitForClose(): Promise { return this.closed.promise } + + private async run(helperPromise: Promise, config: NativeClientConfig, pollIntervalMs: number, + owner: Owner, transport: WindowsTransport): Promise { + let helper: WindowsHelper | undefined + let connection: WindowsConnection | undefined + let closed: Promise | undefined + let caught: Error | undefined + let admitted = false + const observation = { acknowledged: false } + const timer = setTimeout(() => { + this.startup.abort(new NativeError('NATIVE_CONNECT_TIMEOUT', 'Windows native connection exceeded connectTimeoutMs; check helper diagnostics and Windows application-control policy')) + }, config.connectTimeoutMs) + try { + helper = await interruptible(helperPromise, this.startup.signal) + const ready = await interruptible(helper.ready, this.startup.signal) + this.startup.signal.throwIfAborted() + connection = connectWindowsPipe(owner.subprocess, config, ready.endpoint, ready.runtimeKey, transport) + const socket = connection.stream + this.socket = socket + helper.sockets.add(socket) + let socketError: Error | undefined + closed = new Promise((resolve, reject) => { + socket.on('error', (error: Error) => { socketError = error }) + socket.on('close', () => { + if (socketError) reject(socketError) + else if (!observation.acknowledged) reject(new NativeError('NATIVE_EOF', 'Windows pipe closed without cleanup acknowledgement')) + else resolve() + }) + }) + void closed.catch(() => {}) + const abort = () => { socket.destroy(failure(this.startup.signal.reason)) } + this.startup.signal.addEventListener('abort', abort, { once: true }) + try { + const frame = firstFrame(socket, this.startup.signal) + void frame.catch(() => {}) + await connection.connected + this.startup.signal.throwIfAborted() + { + const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, + screenshotTimeoutMs, timeoutMs, graceMs, maxClickHoldMs } = config + socket.write(JSON.stringify({ type: 'hello', protocol: 1, runtimeKey: ready.runtimeKey, + config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs, pollIntervalMs, maxClickHoldMs } }) + '\n') + } + const response = await frame + const accepted = Ready.parse(response.value) + if (accepted.runtimeKey !== ready.runtimeKey || accepted.instanceId !== ready.instanceId || accepted.pid !== ready.pid) + throw new NativeError('NATIVE_PROTOCOL', 'Windows pipe belongs to another helper instance') + this.startup.signal.throwIfAborted() + admitted = true + this.startup.signal.removeEventListener('abort', abort) + clearTimeout(timer) + const close = () => { + this.closeTimer ??= setTimeout(() => { socket.destroy(new NativeError('NATIVE_CLEANUP', 'Windows pipe did not acknowledge cleanup')) }, config.graceMs) + } + this.startup.signal.addEventListener('abort', close, { once: true }) + let prefix: Buffer | undefined = Buffer.alloc(0) + const receive = (chunk: Buffer) => { + let offset = 0 + while (offset < chunk.length) { + const newline = chunk.indexOf(10, offset) + const end = newline < 0 ? chunk.length : newline + 1 + const piece = chunk.subarray(offset, end) + if (prefix !== undefined) prefix = prefix.length + piece.length <= closedFrame.length + ? Buffer.concat([prefix, piece]) : undefined + if (newline >= 0) { + if (prefix?.equals(closedFrame)) { + if (!this.closing) { + socket.destroy(new NativeError('NATIVE_PROTOCOL', 'Unexpected Windows cleanup acknowledgement')) + return + } + observation.acknowledged = true + } + prefix = Buffer.alloc(0) + } + offset = end + } + if (!this.closing) this.stdout.write(chunk) + } + socket.on('data', receive) + if (response.rest.length !== 0) receive(response.rest) + socket.resume() + this.readiness.resolve(socket) + try { await closed } finally { this.startup.signal.removeEventListener('abort', close) } + } finally { this.startup.signal.removeEventListener('abort', abort) } + } catch (error) { + const cause = failure(error) + if (!this.closing || admitted) caught = cause + this.readiness.reject(cause) + } + finally { + clearTimeout(timer) + clearTimeout(this.closeTimer) + this.closing = true + this.socket?.destroy() + if (closed) { + try { await closed } catch (error) { if (admitted) caught ??= failure(error) } + } + if (this.socket) helper?.sockets.delete(this.socket) + let cleanupError: Error | undefined + try { await connection?.dispose() } catch (error) { cleanupError = failure(error); caught ??= cleanupError } + if (admitted && !observation.acknowledged) { + cleanupError = new NativeError('NATIVE_CLEANUP', 'Windows pipe ended without native cleanup acknowledgement') + } + this.stdin.destroy() + if (caught) this.stdout.destroy(caught) + else this.stdout.end() + if (cleanupError) this.closed.reject(cleanupError) + else this.closed.resolve() + } + if (caught) throw caught + } +} + +/** One provider owns a service lease; Agent connections own only their application and snapshot state. */ +export class WindowsNativeRuntime { + private helper: WindowsHelper | undefined + private disposal: Promise | undefined + private readonly channels = new Set() + + /** + * @param owner Managed subprocess provider. + * @param pollIntervalMs Clipboard and application-readiness polling interval. + * @param transport Resolved native Windows or WSL connection method. + */ + constructor(private readonly owner: Owner, private readonly pollIntervalMs: number, private readonly transport: WindowsTransport = 'pipe') {} + + /** + * Connect one Agent without transferring process ownership to that Agent. + * @param config Executable identity and per-connection limits. + * @returns The byte stream used by the shared native request client. + */ + connect(config: NativeClientConfig): NativeChannel { + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + const acquire = async () => { + if (this.helper?.ended) await this.helper.done + if (this.disposal) throw new NativeError('NATIVE_CLOSED', 'Windows Computer Use is disposed') + if (!this.helper || this.helper.ended) this.helper = new WindowsHelper(this.owner, config) + return this.helper + } + const channel = new WindowsChannel(acquire(), config, this.pollIntervalMs, this.owner, this.transport) + this.channels.add(channel) + void channel.done.then(() => this.channels.delete(channel), () => this.channels.delete(channel)) + return channel + } + + /** Close Agent pipes and join this Host's connector; other Hosts retain their service leases. */ + dispose(): Promise { + return this.disposal ??= (async () => { + for (const channel of this.channels) channel.close() + const channels = await Promise.allSettled([...this.channels].map(channel => channel.waitForClose())) + let processError: unknown + try { await this.helper?.stop() } catch (error) { processError = error } + const errors: unknown[] = [] + for (const result of channels) { if (result.status === 'rejected') errors.push(result.reason) } + if (processError !== undefined) errors.push(processError) + if (errors.length) throw new AggregateError(errors, 'Windows Computer Use cleanup failed') + })() + } +} diff --git a/packages/experimental/cua-windows/src/native-transport.ts b/packages/experimental/cua-windows/src/native-transport.ts new file mode 100644 index 0000000000..d72b47b4eb --- /dev/null +++ b/packages/experimental/cua-windows/src/native-transport.ts @@ -0,0 +1,65 @@ +/** Direct Windows pipes and WSL subprocess streams for the same native protocol. */ +import { Socket } from 'node:net' +import { Duplex } from 'node:stream' +import assert from 'node:assert/strict' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { NativeError, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' + +/** Transport selected from the resolved Host environment. */ +export type WindowsTransport = 'pipe' | 'stdio' + +/** One connection owns its stream and, for WSL, a Windows bridge process. */ +export interface WindowsConnection { + stream: Duplex + connected: Promise + dispose(): Promise +} + +/** + * Connect to a Windows desktop service without exposing a network listener. + * @param subprocess Managed process owner for the WSL bridge. + * @param config Helper executable and connection/cleanup limits. + * @param endpoint Named pipe reported by the verified service lease. + * @param runtimeKey Expected executable digest, verified again by the Windows bridge. + * @param transport Native pipe or standard streams through WSL interoperation. + * @returns Owned connection; disposal joins the bridge process after stream closure. + */ +export function connectWindowsPipe(subprocess: Pick, config: NativeClientConfig, + endpoint: string, runtimeKey: string, transport: WindowsTransport): WindowsConnection { + if (transport === 'pipe') { + const stream = new Socket() + const connected = new Promise((resolve, reject) => { + stream.once('connect', resolve) + stream.once('error', reject) + }) + void connected.catch(() => {}) + stream.connect(endpoint) + return { stream, connected, dispose: async () => {} } + } + const handle = subprocess.spawn({ + argv: [config.helperPath, '--bridge', '--runtime-key', runtimeKey, + '--connect-timeout-ms', String(config.connectTimeoutMs), '--grace-ms', String(config.graceMs)], + cwd: config.cwd, graceMs: config.graceMs, + stdio: { stdin: 'pipe', stdout: 'pipe', stderr: { maxBytes: 65_536 } }, + }) + assert(handle.stdin && handle.stdout, 'The Windows bridge requires standard input and output') + const stream = Duplex.from({ readable: handle.stdout, writable: handle.stdin }) + stream.once('end', () => { stream.end() }) + void handle.done.then((outcome) => { + if (outcome.exitCode !== 0 || outcome.signal !== null) + stream.destroy(new NativeError('NATIVE_EXITED', `Windows bridge failed: ${handle.collected.stderr?.readFrom(0).text ?? String(outcome.exitCode)}`)) + }, (error: unknown) => { stream.destroy(error instanceof Error ? error : new Error(String(error))) }) + return { + stream, connected: Promise.resolve(), + async dispose() { + handle.stdin?.end() + const timer = setTimeout(() => { handle.terminate() }, config.graceMs) + try { + const outcome = await handle.done + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows bridge process did not exit') + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('NATIVE_CLEANUP', `Windows bridge exited unsuccessfully (${String(outcome.exitCode)}, ${String(outcome.signal)})`) + } finally { clearTimeout(timer) } + }, + } +} diff --git a/packages/experimental/cua-windows/src/windows-host.ts b/packages/experimental/cua-windows/src/windows-host.ts new file mode 100644 index 0000000000..584b53f2d1 --- /dev/null +++ b/packages/experimental/cua-windows/src/windows-host.ts @@ -0,0 +1,93 @@ +/** Windows desktop execution from native Windows or a WSL process. */ +import { createHash } from 'node:crypto' +import { mkdir, readFile } from 'node:fs/promises' +import { join, win32 } from 'node:path' +import { isWsl, type HostEnvironmentFacts } from '@deepseek-ai/dsh-native-command' +import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' +import { NativeError } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { z } from 'zod' +import type { NativeArchitecture } from './native-build.ts' + +/** DSH execution environment, independently of the Windows desktop it controls. */ +export type WindowsHost = 'windows' | 'wsl' + +/** + * Resolve the Host before compiling or launching native code. + * @param facts Process and kernel facts; omitted fields use the current Host. + * @returns Native Windows or WSL; ordinary Linux has no Windows desktop provider. + */ +export function windowsHost(facts: HostEnvironmentFacts = {}): WindowsHost { + if ((facts.platform ?? process.platform) === 'win32') return 'windows' + if (isWsl(facts)) return 'wsl' + throw new NativeError('UNSUPPORTED', 'Windows Computer Use requires native Windows or WSL; ordinary Linux is unsupported') +} + +/** Managed command lifetime for WSL capability and path queries. */ +export interface WslPreparation { + subprocess: Pick + signal: AbortSignal + timeoutMs: number + graceMs: number + powershellPath: string +} + +async function command(spec: WslPreparation, argv: string[]): Promise { + spec.signal.throwIfAborted() + const signal = AbortSignal.any([spec.signal, AbortSignal.timeout(spec.timeoutMs)]) + const handle = spec.subprocess.spawn({ argv, cwd: process.cwd(), signal, graceMs: spec.graceMs, + stdio: { stdin: 'ignore', stdout: { maxBytes: 8192 }, stderr: { maxBytes: 8192 } } }) + try { + const outcome = await handle.done + signal.throwIfAborted() + if (outcome.exitCode !== 0 || outcome.signal !== null) + throw new NativeError('WSL_INTEROP', `Windows interoperation failed: ${handle.collected.stderr?.readFrom(0).text ?? outcome.exitCode}`) + return handle.collected.stdout?.readFrom(0).text.trim() ?? '' + } finally { + handle.terminate() + if (!await handle.waitForExit()) throw new NativeError('NATIVE_CLEANUP', 'Windows preparation process did not exit') + } +} + +/** + * Verify that WSL can start Windows programs and resolve the Windows runtime architecture. + * @param spec Managed process policy and Windows PowerShell executable. + * @returns Windows architecture and a WSL-visible cache directory on the Windows filesystem. + */ +export async function prepareWsl(spec: WslPreparation): Promise<{ architecture: NativeArchitecture; cacheDirectory: string }> { + const script = "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); @{ architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant(); cache = [IO.Path]::Combine([Environment]::GetFolderPath('LocalApplicationData'), 'DeepSeekHarness', 'cua') } | ConvertTo-Json -Compress" + try { + const output = await command(spec, [spec.powershellPath, '-NoProfile', '-NonInteractive', '-Command', script]) + const result = z.object({ architecture: z.enum(['x64', 'arm64']), cache: z.string().refine(value => win32.isAbsolute(value)) }).strict().parse(JSON.parse(output)) + const cacheDirectory = await command(spec, ['wslpath', '-u', result.cache]) + if (!cacheDirectory.startsWith('/')) throw new NativeError('WSL_INTEROP', 'wslpath did not return an absolute cache directory') + return { architecture: result.architecture, cacheDirectory } + } catch (error) { + spec.signal.throwIfAborted() + throw new NativeError('WSL_INTEROP', 'WSL cannot prepare Windows Computer Use; check Windows interoperation and windowsPowerShellPath', { cause: error }) + } +} + +/** + * Retain the helper on the Windows filesystem so Explorer can launch the shared desktop service. + * @param helperPath Absolute executable path visible to WSL. + * @param cacheDirectory Windows user cache translated to a WSL path. + * @param signal Provider preparation lifetime. + * @returns Content-addressed executable path, without modifying the source payload. + */ +export async function retainWslHelper(helperPath: string, cacheDirectory: string, signal: AbortSignal): Promise { + const bytes = await readFile(helperPath, { signal }) + const digest = createHash('sha256').update(bytes).digest('hex') + const directory = join(cacheDirectory, digest) + const retained = join(directory, 'dsh-cua-windows.exe') + await mkdir(directory, { recursive: true }) + let existing: Buffer | undefined + try { existing = await readFile(retained, { signal }) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + signal.throwIfAborted() + if (existing && !existing.equals(bytes)) throw new NativeError('NATIVE_STARTUP', 'The cached Windows helper does not match its executable digest') + if (!existing) await writeFileAtomic(retained, bytes, { mode: 0o755 }) + signal.throwIfAborted() + return retained +} diff --git a/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts new file mode 100644 index 0000000000..369fd2f546 --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-runtime.spec.ts @@ -0,0 +1,22 @@ +/** Opt-in real desktop admission through the shipped managed subprocess provider. */ +import { Context } from '@deepseek-ai/cordis' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it, onTestFinished } from 'vitest' +import { Config } from '../src/index.ts' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +it.skipIf(!helperPath)('admits Windows desktop requests through managed WSL or native Windows processes', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(LocalSubprocessRuntime) + const runtime = new WindowsNativeRuntime(ctx, 25, process.platform === 'win32' ? 'pipe' : 'stdio') + onTestFinished(() => runtime.dispose()) + const client = new NativeClient(ctx, { ...Config({}), helperPath: helperPath!, cwd: process.cwd() }, + (_owner, config) => runtime.connect(config)) + onTestFinished(() => client.dispose()) + expect(await client.request('getCapabilities', {}, new AbortController().signal)).toMatchObject({ + permissions: { accessibility: expect.any(Boolean), screenRecording: expect.any(Boolean) }, + }) +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/desktop-smoke.mjs b/packages/experimental/cua-windows/tests/desktop-smoke.mjs new file mode 100644 index 0000000000..2a476cc65d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-smoke.mjs @@ -0,0 +1,285 @@ +/** Real Windows acceptance against private fixture windows; no existing document is modified. */ +// TODO: migrate this old window-RPC smoke (discoverWindows/prepareWindows/prepareLaunch) to the listApps/getApp facade before running it again. +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { createHash, randomUUID } from 'node:crypto' +import { readFile, writeFile } from 'node:fs/promises' +import { createConnection } from 'node:net' +import { Duplex } from 'node:stream' +import { release } from 'node:os' +import { createInterface } from 'node:readline' +import { once } from 'node:events' +import { resolve } from 'node:path' +import { setTimeout as delay } from 'node:timers/promises' + +const wsl = process.platform === 'linux' && (process.env.WSL_DISTRO_NAME || release().toLowerCase().includes('microsoft')) +assert(process.platform === 'win32' || wsl, 'Run with native Windows Node or WSL on an interactive Windows desktop') +const [helperFile, fixtureFile, outputFile] = process.argv.slice(2).map(path => resolve(path)) +assert(helperFile && fixtureFile && outputFile, 'Expected helper, fixture, and evidence file paths') +const resources = [] +const results = [] + +function lines(stream) { + const reader = createInterface({ input: stream }) + const iterator = reader[Symbol.asyncIterator]() + return async () => { + const result = await iterator.next() + assert(!result.done, 'The native stream ended before a response') + return JSON.parse(result.value) + } +} + +function child(file, args = []) { + const process = spawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) + const exit = once(process, 'exit') + const read = args.includes('--bridge') ? undefined : lines(process.stdout) + process.stderr.pipe(globalThis.process.stderr) + const resource = { process, exit, read } + resources.push(resource) + return resource +} + +async function checked(name, operation) { + const start = performance.now() + const detail = await operation() + results.push({ name, elapsedMs: Math.round(performance.now() - start), detail }) + console.log(JSON.stringify(results.at(-1))) + return detail +} + +const deadline = setTimeout(() => { + console.error('Desktop smoke exceeded its 90-second deadline') + process.exitCode = 1 + for (const resource of resources) resource.process.kill() +}, 90_000) +let socket +let bridge +try { + const fixture = child(fixtureFile) + const initial = await fixture.read() + const inspect = async command => { fixture.process.stdin.write(command + '\n'); return await fixture.read() } + const sentinel = child(fixtureFile) + const sentinelReady = await sentinel.read() + const cover = async () => { + await inspect(`allow:${sentinelReady.pid}`) + sentinel.process.stdin.write('focus\n') + const focused = await sentinel.read() + assert.equal(focused.foreground, focused.window, 'The sentinel needs foreground access') + return await inspect('inspect') + } + await cover() + const runtimeKey = createHash('sha256').update(await readFile(helperFile)).digest('hex') + const instanceId = randomUUID().replaceAll('-', '') + const helper = child(helperFile, ['--serve', '--instance-id', instanceId, '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const other = child(helperFile, ['--serve', '--instance-id', randomUUID().replaceAll('-', ''), '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + const [ready] = await checked('Concurrent Host connectors share one desktop service', async () => { + const pair = await Promise.all([helper.read(), other.read()]) + assert.equal(pair[0].pid, pair[1].pid) + assert.equal(pair[0].instanceId, pair[1].instanceId) + return pair + }) + assert.equal(ready.runtimeKey, runtimeKey) + if (wsl) { + bridge = child(helperFile, ['--bridge', '--runtime-key', runtimeKey, '--connect-timeout-ms', '10000', '--grace-ms', '3000']) + socket = Duplex.from({ readable: bridge.process.stdout, writable: bridge.process.stdin }) + socket.once('end', () => { socket?.end() }) + } else { + socket = createConnection(ready.endpoint) + await once(socket, 'connect') + } + const read = lines(socket) + const exchange = async value => { socket.write(JSON.stringify(value) + '\n'); return await read() } + const hello = await exchange({ type: 'hello', protocol: 1, runtimeKey, config: { + maxRequestBytes: 1_048_576, maxResponseBytes: 33_554_432, axTimeoutMs: 5000, textEventIntervalMs: 0, + screenshotTimeoutMs: 10000, timeoutMs: 15000, graceMs: 3000, pollIntervalMs: 25, maxClickHoldMs: 1000, + } }) + assert.equal(hello.instanceId, ready.instanceId) + other.process.stdin.end() + assert.deepEqual(await other.exit, [0, null]) + let sequence = 0 + const request = async (method, params = {}) => { + const response = await exchange({ id: String(++sequence), method, params }) + if (response.error) throw Object.assign(new Error(response.error.message), { code: response.error.code }) + return response.result + } + await checked('AppsFolder discovery and launch reach the Settings window', async () => { + const entries = await request('findApps', { query: 'immersivecontrolpanel', maxAppMatches: 20 }) + const entry = entries.find(entry => entry.kind === 'shell') + assert(entry, 'AppsFolder must expose the system Settings entry') + const prepared = await request('prepareLaunch', { target: entry.id }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + await assert.rejects(request('dispatchLaunch', { appHandle: prepared.appHandle }), { code: 'LAUNCH_ALREADY_DISPATCHED' }) + const until = performance.now() + 10000 + let target + do { + target = (await request('discoverWindows')).find(window => window.title === entry.displayName) + assert(performance.now() < until, 'Settings did not expose a selectable window') + if (!target) await delay(25) + } while (!target) + const [selected] = await request('prepareWindows', { ids: [target.windowId] }) + const observed = await request('getState', { appHandle: selected.appHandle, windowId: target.windowId, maxElements: 100, maxDepth: 20 }) + assert.equal(observed.windowId, target.windowId) + assert(observed.tree.length > 0) + return { entry: entry.id, window: target.title, axLength: observed.tree.length } + }) + await checked('An explicit executable path dispatches independently of Shell discovery', async () => { + const prepared = await request('prepareLaunch', { target: 'C:\\Windows\\System32\\notepad.exe' }) + assert.equal(prepared.authorization.persistable, false) + assert.deepEqual(await request('dispatchLaunch', { appHandle: prepared.appHandle }), { dispatched: true, verified: false }) + return { target: prepared.authorization.executablePath } + }) + const windows = await request('discoverWindows') + const selected = windows.filter(window => window.pid === initial.pid && window.title === 'DSH CUA owned test window') + assert.equal(selected.length, 1) + assert.equal(selected[0].appName, 'dsh-cua-desktop-fixture') + const windowId = selected[0].windowId + const [app] = await request('prepareWindows', { ids: [windowId] }) + const appHandle = app.appHandle + const state = () => request('getState', { appHandle, windowId, maxElements: 100, maxDepth: 20, details: true }) + const baseline = await cover() + let observation = await checked('UIA observation without foreground change', async () => { + const result = await state() + const after = await inspect('inspect') + assert.equal(after.foreground, baseline.foreground) + assert.deepEqual(after.cursor, baseline.cursor) + return result + }) + const index = (text) => { + const row = observation.tree.split('\n').find(row => row.includes(text)) + assert(row, `Missing UIA row for ${text}`) + const match = row.match(/\[(\d+)\]/) + assert(match, `Missing actionable index for ${text}`) + return Number(match[1]) + } + await checked('Background UIA value and invoke affect the target', async () => { + const valueResult = await request('setValue', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('CUA test text'), value: '你好 😀 Windows' }) + const valued = await inspect('inspect') + assert.equal(typeof valueResult.foregroundChanged, 'boolean') + const clickResult = await request('click', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + const after = await inspect('inspect') + assert.equal(after.text, '你好 😀 Windows') + assert.equal(after.clicks, 1) + // UIA providers can activate after dispatch returns; later observations are separate samples. + assert.equal(typeof clickResult.foregroundChanged, 'boolean') + assert.deepEqual(after.cursor, baseline.cursor) + return { valueResult, clickResult, foregroundBefore: baseline.foreground, foregroundAfterValue: valued.foreground, after } + }) + for (const command of ['minimize', 'hide']) { + await checked(`show restores a ${command} window without activation`, async () => { + const foreground = (await cover()).foreground + const hidden = await inspect(command) + assert(command === 'minimize' ? hidden.minimized : !hidden.visible) + const restored = await request('show', { appHandle, windowId }) + assert.equal(restored.windowId, windowId) + const until = performance.now() + 5000 + let current + do { + current = await inspect('inspect') + assert(performance.now() < until, 'show did not restore the window') + } while (current.minimized || !current.visible) + assert.equal(current.foreground, foreground) + observation = await state() + return { restored, state: current } + }) + } + const covered = await cover() + await checked('Window capture without foreground change', async () => { + const capture = await request('screenshot', { appHandle, windowId }) + const after = await inspect('inspect') + assert.equal(after.foreground, covered.foreground) + assert.deepEqual(after.cursor, covered.cursor) + assert(capture.pixelWidth > 0 && capture.pixelHeight > 0) + assert(Buffer.from(capture.data, 'base64').subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) + return { width: capture.pixelWidth, height: capture.pixelHeight, bounds: capture.bounds } + }) + await checked('Background global input refuses before typing', async () => { + const before = await inspect('inspect') + assert.notEqual(before.foreground, before.window, 'Fixture must be in the background for this check') + await assert.rejects(request('typeText', { appHandle, text: 'MUST NOT TYPE' }), { code: 'FOREGROUND_REQUIRED' }) + assert.equal((await inspect('inspect')).text, before.text) + }) + await checked('Explicit fixture focus permits Unicode input', async () => { + sentinel.process.stdin.write(`allow:${initial.pid}\n`) + assert.equal((await sentinel.read()).allowed, true) + const focused = await inspect('focus') + assert.equal(focused.foreground, focused.window) + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('typeText', { appHandle, text: '实机 😀\r\nsecond line' }) + assert.equal((await inspect('inspect')).text, '实机 😀\r\nsecond line') + }) + await checked('Paste waits for consumption and updates the focused editor', async () => { + const previousClipboard = await inspect('clipboard-digest') + await request('pressKey', { appHandle, key: 'Control+a' }) + await request('paste', { appHandle, text: '剪贴板 😀', format: 'text', maxClipboardBytes: 4_194_304, + pasteReadTimeoutMs: 1000, maxElements: 100, maxDepth: 20 }) + // Clipboard consumption can precede the editor applying the retrieved text. + const until = performance.now() + 5000 + while ((await inspect('inspect')).text !== '剪贴板 😀') { + assert(performance.now() < until, 'The editor did not apply the pasted text') + await delay(25) + } + assert.deepEqual(await inspect('clipboard-digest'), previousClipboard, 'Paste must restore the prior clipboard text') + }) + observation = await state() + await checked('Hover remains in place through observation and capture', async () => { + const result = await request('hover', { appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click') }) + assert.equal(result.hoverRoute, 'system-pointer') + const hovered = await inspect('inspect') + await state() + await request('screenshot', { appHandle, windowId }) + assert.deepEqual((await inspect('inspect')).cursor, hovered.cursor) + }) + observation = await state() + await checked('Cancelled timed click releases its button before replying', async () => { + const id = String(++sequence) + socket.write(JSON.stringify({ id, method: 'click', params: { + appHandle, snapshotId: observation.snapshotId, elementIndex: index('Record click'), holdMs: 1000, + } }) + '\n') + const until = performance.now() + 5000 + while ((await inspect('inspect')).buttons !== 'Left') { + assert(performance.now() < until, 'Timed click never pressed its button') + } + socket.write(JSON.stringify({ type: 'cancel', id }) + '\n') + const cancelled = await read() + assert.equal(cancelled.error?.code, 'NATIVE_CANCELLED') + assert.equal((await inspect('inspect')).buttons, 'None') + }) + await checked('A sibling window in the same process cannot borrow the selected window grant', async () => { + const sibling = await inspect('sibling') + assert.equal(sibling.foreground, sibling.window) + await assert.rejects(request('typeText', { appHandle, text: 'must not arrive' }), { code: 'FOREGROUND_REQUIRED' }) + const entries = await request('discoverWindows') + const otherWindow = entries.find(window => window.pid === initial.pid && window.title === 'DSH CUA sibling test window') + assert(otherWindow) + await assert.rejects(request('getState', { appHandle, windowId: otherWindow.windowId, maxElements: 100, maxDepth: 20 }), { code: 'WINDOW_CHANGED' }) + await inspect('focus') + return { siblingWindowId: otherWindow.windowId, selectedWindowId: windowId } + }) + await checked('Resize invalidates coordinates before pointer input', async () => { + await inspect('resize') + await assert.rejects(request('click', { appHandle, windowId, x: 20, y: 20 }), { code: 'WINDOW_CHANGED' }) + }) + const closed = once(socket, 'close') + await checked('Agent cleanup returns an explicit acknowledgement before EOF', async () => { + assert.deepEqual(await exchange({ type: 'close' }), { type: 'closed' }) + await closed + if (bridge) assert.deepEqual(await bridge.exit, [0, null]) + }) + socket = undefined + helper.process.stdin.end() + assert.deepEqual(await helper.exit, [0, null]) + fixture.process.stdin.write('close\n') + assert.deepEqual(await fixture.exit, [0, null]) + sentinel.process.stdin.write('close\n') + assert.deepEqual(await sentinel.exit, [0, null]) +} finally { + socket?.destroy() + for (const resource of resources) { + resource.process.stdin.end() + if (resource.process.exitCode === null && resource.process.signalCode === null) resource.process.kill() + } + await Promise.allSettled(resources.map(resource => resource.exit)) + clearTimeout(deadline) + await writeFile(outputFile, JSON.stringify({ platform: process.platform, environment: wsl ? 'wsl' : 'windows', results }, null, 2) + '\n') +} diff --git a/packages/experimental/cua-windows/tests/desktop-tool.spec.ts b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts new file mode 100644 index 0000000000..5fcb5c3c6d --- /dev/null +++ b/packages/experimental/cua-windows/tests/desktop-tool.spec.ts @@ -0,0 +1,71 @@ +/** Opt-in desktop screenshots through the actual CUA tool and attachment store. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use' +import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' +import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import { LlmAdapter, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { expect, it, onTestFinished } from 'vitest' +import { createCuaApi } from '@deepseek-ai/dsh-cua/api' +import sharp from 'sharp' +import * as Provider from '../src/index.ts' + +class ImageAdapter extends LlmAdapter { + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) + } + stream(): AsyncIterable { throw new Error('Desktop tests do not request model generation') } +} +const helperPath = process.env.DSH_CUA_DESKTOP_TEST_HELPER +const selector = process.env.DSH_CUA_DESKTOP_TEST_APP +it.skipIf(!helperPath || !selector)('admits real application screenshots through the CUA tool', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-cua-desktop-tool-')) + const ctx = new Context() + onTestFinished(async () => { try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } }) + await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestHarness(ctx) + await ctx.plugin(ComputerUseRegistry) + await ctx.plugin(SubprocessLocal) + await ctx.plugin(LocalAttachmentStore, { dshHome: root }) + await ctx.plugin(UserQuestions) + ctx.on('user-questions/request', async () => ({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] })) + await ctx.plugin(Provider, { helperPath: helperPath!, agentPreset: false }) + ctx.llm.registerAdapter(['desktop-test'], new ImageAdapter()) + const owner = await ctx.agents.create({ sessionId: SessionId('desktop-screenshot'), agentOptions: { provider: 'desktop-test', model: 'vision' } }) + let sequence = 0 + const dispatch: Parameters[0] = async (operation) => { + const batch = await ctx.tools.execute({ agent: owner.agent, signal: new AbortController().signal, + calls: [{ type: 'tool-call', id: ToolCallId(`desktop-${++sequence}`), name: 'cua', arguments: JSON.stringify(operation) }] }) + expect(batch.results).toHaveLength(1) + const result = batch.results[0]!.result + expect(result.isError, JSON.stringify(result.content)).toBe(false) + return result.value! + } + const emitted: string[] = [] + const api = createCuaApi(dispatch, { + text: (text) => { emitted.push(text) }, + image: (image) => { expect(image.bytes.byteLength).toBeGreaterThan(0) }, + }) + const discovered = (await api.listApps({ emit: false })).find(app => + app.id === selector || app.displayName.toLowerCase() === selector?.toLowerCase()) + expect(discovered).toBeDefined() + const app = await api.getApp(discovered!.id) + const target = (await app.getWindows({ emit: false })).find(window => + window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) + expect(target).toBeDefined() + const window = await app.getWindow(target!.windowId) + expect(emitted).toEqual([]) + await window.getAccessibilityTree() + expect(emitted).toHaveLength(1) + for (let i = 0; i < 5; ++i) { + const screenshot = await window.getScreenshot() + const decoded = await sharp(screenshot.bytes).raw().toBuffer({ resolveWithObject: true }) + expect(decoded.info.width).toBe(screenshot.pixelWidth) + expect(decoded.info.height).toBe(screenshot.pixelHeight) + } +}, 60_000) diff --git a/packages/experimental/cua-windows/tests/native-build.spec.ts b/packages/experimental/cua-windows/tests/native-build.spec.ts new file mode 100644 index 0000000000..9c9eb60aa9 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-build.spec.ts @@ -0,0 +1,61 @@ +/** The Windows compiler publishes one immutable executable and installed packages need no SDK. */ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { buildNativeExecutable, nativeExecutablePath, nativeHostArchitecture, prepareNativeExecutable } from '../src/native-build.ts' + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), 'cua-windows-build-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const packageRoot = join(root, 'packages/experimental/cua-windows') + await mkdir(packageRoot, { recursive: true }) + const bytes = Buffer.from('MZ Windows executable fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => ({ + stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, collected: {}, + done: (async () => { + const output = request.argv[request.argv.indexOf('--output') + 1]! + await mkdir(output, { recursive: true }) + await writeFile(join(output, 'dsh-cua-windows.exe'), bytes) + return { exitCode: 0, signal: null } + })(), + terminate: vi.fn(), waitForExit: async () => true, + })) + const spec = { packageRoot, architecture: 'x64' as const, dotnetPath: 'fixture-dotnet', subprocess: { spawn }, + signal: new AbortController().signal, timeoutMs: 60_000, graceMs: 1000 } + return { root, spec, spawn, bytes } +} + +it.each(['x64', 'arm64'])('accepts the Windows %s process target', (architecture) => { + expect(nativeHostArchitecture('win32', architecture)).toBe(architecture) +}) +it.each([['darwin', 'arm64'], ['linux', 'x64'], ['win32', 'ia32']])('rejects unsupported %s/%s runtime targets', (platform, architecture) => { + expect(() => nativeHostArchitecture(platform, architecture)).toThrow('requires Windows') +}) + +it('passes an explicit Windows RID and SDK to the managed compiler and retains the bytes', async () => { + const f = await fixture() + const output = await buildNativeExecutable(f.spec) + expect(await readFile(output)).toEqual(f.bytes) + expect(await readFile(nativeExecutablePath(f.spec.packageRoot, 'x64'))).toEqual(f.bytes) + expect(f.spawn.mock.calls[0]![0].argv).toEqual(expect.arrayContaining([ + 'fixture-dotnet', '--runtime', 'win-x64', '--self-contained', 'true', '-p:EnableWindowsTargeting=true', + ])) + expect(await buildNativeExecutable(f.spec)).toBe(output) +}) + +it('compiles a recognized source package and resolves an installed payload without a compiler', async () => { + const f = await fixture() + await writeFile(join(f.root, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-root' })) + expect(await prepareNativeExecutable(f.spec)).toContain('prepared') + expect(f.spawn).toHaveBeenCalledOnce() + await rm(join(f.root, 'package.json')) + expect(await prepareNativeExecutable(f.spec)).toBe(nativeExecutablePath(f.spec.packageRoot, 'x64')) + expect(f.spawn).toHaveBeenCalledOnce() + const controller = new AbortController() + controller.abort() + await expect(prepareNativeExecutable({ ...f.spec, signal: controller.signal })).rejects.toThrow() + await rm(nativeExecutablePath(f.spec.packageRoot, 'x64')) + await expect(prepareNativeExecutable(f.spec)).rejects.toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/native-runtime.spec.ts b/packages/experimental/cua-windows/tests/native-runtime.spec.ts new file mode 100644 index 0000000000..b3eb03caf2 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-runtime.spec.ts @@ -0,0 +1,448 @@ +/** Real local pipes exercise Host ownership, Agent isolation, cancellation, and startup admission. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createConnection, createServer, type Socket } from 'node:net' +import { PassThrough } from 'node:stream' +import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { NativeClient, type NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import { WindowsNativeRuntime } from '../src/native-runtime.ts' + +interface Frame { type?: string; id?: string; method?: string; runtimeKey?: string; config?: Record } +interface FixtureOptions { + transport?: 'pipe' | 'stdio' + startupDiagnostic?: string + startup?: 'wrong-runtime' | 'wrong-instance' | 'extra' | 'malformed' | 'oversized' | 'invalid-utf8' | 'exit' | 'silent' | 'stdout-error' | 'stdout-close' + handshake?: 'wrong-instance' | 'wrong-pid' | 'extra' | 'malformed' | 'oversized' | 'silent' | 'initial-result' + ignoreClose?: boolean + eofOnClose?: boolean + connectionCleanup?: Promise + ignoreParent?: boolean + processCleanup?: false | 'reject' + cleanupGate?: Promise + onSpawn?: () => void + split?: boolean +} + +async function fixture(options: FixtureOptions = {}) { + const directory = await mkdtemp(join(tmpdir(), 'cua-windows-pipes-')) + const clients: NativeClient[] = [] + const generations: Array<{ stop: () => Promise; stdout: PassThrough; received: Frame[]; peers: Set; endpoint: string }> = [] + const resources: { runtime?: WindowsNativeRuntime } = {} + onTestFinished(async () => { + await Promise.allSettled(clients.map(client => client.dispose())) + try { await resources.runtime?.dispose().catch(() => {}) } finally { + await Promise.all(generations.map(generation => generation.stop())) + await rm(directory, { recursive: true, force: true }) + } + }) + const helperPath = join(directory, 'helper.exe') + await writeFile(helperPath, 'Windows helper identity fixture') + const spawn = vi.fn((request: SubprocessSpawnSpec): SubprocessHandle => { + if (request.argv.includes('--bridge')) { + const socket = createConnection(generations.at(-1)!.endpoint) + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + stdin.pipe(socket).pipe(stdout) + socket.on('error', (error) => { stdout.destroy(error) }) + socket.on('close', () => { done.resolve({ exitCode: 0, signal: null }) }) + return { stdin, stdout, stderr: undefined, control: undefined, collected: {}, done: done.promise, + terminate: () => { socket.destroy() }, waitForExit: async () => { await done.promise; return true } } + } + const instanceId = request.argv[request.argv.indexOf('--instance-id') + 1]! + const runtimeKey = request.argv[request.argv.indexOf('--runtime-key') + 1]! + const endpoint = process.platform === 'win32' ? `\\\\.\\pipe\\cua-test-${randomUUID()}` : join(directory, `${generations.length}.sock`) + const pid = 100 + generations.length + const stdin = new PassThrough(), stdout = new PassThrough() + const exited = Promise.withResolvers() + const ready: PromiseWithResolvers = Promise.withResolvers() + const peers = new Set() + const received: Frame[] = [] + let stopped: Promise | undefined + let diagnostic = '' + let nextConnection = 0 + const server = createServer({ allowHalfOpen: true }, (socket) => { + peers.add(socket) + socket.on('end', () => { socket.end() }) + const connection = ++nextConnection + socket.on('error', () => {}) + socket.on('close', () => { peers.delete(socket) }) + let buffered = '' + socket.on('data', (chunk: Buffer) => { + buffered += chunk.toString('utf8') + for (;;) { + const newline = buffered.indexOf('\n') + if (newline < 0) return + const frame = JSON.parse(buffered.slice(0, newline)) as Frame + buffered = buffered.slice(newline + 1) + received.push(frame) + if (frame.type === 'hello') { + if (options.handshake === 'silent') return + const response = { type: 'ready', protocol: 1, runtimeKey, instanceId: options.handshake === 'wrong-instance' ? 'other' : instanceId, + pid: options.handshake === 'wrong-pid' ? pid + 1 : pid, ...options.handshake === 'extra' ? { extra: true } : {} } + const text = options.handshake === 'malformed' ? '{bad}\n' : options.handshake === 'oversized' ? 'x'.repeat(8193) : JSON.stringify(response) + '\n' + if (options.split) { socket.write(text.slice(0, 4)); socket.write(text.slice(4)) } + else socket.write(text + (options.handshake === 'initial-result' ? '{"id":"early","result":true}\n' : '')) + } else if (frame.type === 'close') { + if (!options.ignoreClose) void (async () => { + await options.connectionCleanup + if (!options.eofOnClose) { + if (options.split) { socket.write('{"type":'); socket.write('"closed"}\n') } + else socket.write('{"type":"closed"}\n') + } + socket.end() + })() + } else if (frame.type === 'cancel') socket.write(JSON.stringify({ id: frame.id, error: { code: 'NATIVE_CANCELLED', message: 'Cancelled' } }) + '\n') + else if (frame.method !== 'hold') socket.write(JSON.stringify({ id: frame.id, result: { connection, pid, method: frame.method } }) + '\n') + } + }) + }) + const stop = (): Promise => stopped ??= (async () => { + await ready.promise + const closedPeers = [...peers].map(peer => once(peer, 'close')) + for (const peer of peers) peer.destroy() + await Promise.all(closedPeers) + await new Promise((resolve, reject) => server.close((error) => { if (error) reject(error); else resolve() })) + const ended = options.startup === 'exit' ? once(stdout, 'end') : undefined + stdout.end() + await ended + diagnostic = options.startupDiagnostic ?? '' + exited.resolve({ exitCode: options.startup === 'exit' ? 1 : 0, signal: null }) + })() + stdin.on('finish', () => { if (!options.ignoreParent) void stop() }) + server.on('error', (error) => { ready.reject(error); exited.reject(error) }) + server.listen(endpoint, () => { + ready.resolve() + if (options.startup === 'silent') return + if (options.startup === 'stdout-error') { stdout.destroy(new Error('readiness IO failure')); return } + if (options.startup === 'stdout-close') { stdout.end(); return } + if (options.startup === 'exit') { void stop(); return } + const response = { type: 'ready', protocol: 1, endpoint, pid, + runtimeKey: options.startup === 'wrong-runtime' ? 'other' : runtimeKey, + instanceId, launcherId: options.startup === 'wrong-instance' ? 'other' : instanceId } + const text = options.startup === 'malformed' ? '{bad}\n' : options.startup === 'oversized' ? 'x'.repeat(8193) + : JSON.stringify(response) + '\n' + (options.startup === 'extra' ? 'extra' : '') + if (options.startup === 'invalid-utf8') stdout.write(Buffer.from([255, 10])) + else if (options.split) { stdout.write(text.slice(0, 5)); stdout.write(text.slice(5)) } + else stdout.write(text) + }) + generations.push({ stop, stdout, received, peers, endpoint }) + options.onSpawn?.() + return { stdin, stdout, stderr: undefined, control: undefined, + collected: { stderr: { readFrom: () => ({ text: diagnostic, nextOffset: Buffer.byteLength(diagnostic), lossy: false }) } }, + done: exited.promise, + terminate: () => { void stop() }, waitForExit: async () => { await exited.promise; await options.cleanupGate; if (options.processCleanup === 'reject') throw new Error('cleanup failed'); return options.processCleanup !== false } } + }) + const owner = { subprocess: { spawn } } + const runtime = new WindowsNativeRuntime(owner, 25, options.transport) + resources.runtime = runtime + const activeRuntime = runtime + const config: NativeClientConfig = { helperPath, cwd: directory, timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const client = () => { + const value = new NativeClient(owner, config, (_owner, native) => activeRuntime.connect(native)) + clients.push(value) + return value + } + return { directory, config, spawn, generations, runtime, client } +} + +it('shares one Host helper while closing only the selected Agent connection', async () => { + const f = await fixture({ split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('one', {}, signal)).toMatchObject({ connection: 1, pid: 100 }) + expect(await b.request('two', {}, signal)).toMatchObject({ connection: 2, pid: 100 }) + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.generations[0]!.received[0]?.config?.pollIntervalMs).toBe(25) + await a.dispose() + expect(await b.request('after-close', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await vi.waitFor(() => { expect(f.generations[0]!.peers.size).toBe(0) }) + await f.runtime.dispose() + expect(() => f.runtime.connect(f.config)).toThrow('disposed') +}) + +it('cancels a request without replacing the connection or replaying input', async () => { + const f = await fixture() + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const refused = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await refused + expect(client.disposed).toBe(false) + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('starts a fresh helper after process loss and makes the old client unusable', async () => { + const f = await fixture(), signal = new AbortController().signal + const first = f.client() + await first.request('first', {}, signal) + await f.generations[0]!.stop() + await vi.waitFor(() => { expect(first.disposed).toBe(true) }) + await expect(first.dispose()).rejects.toThrow('cleanup acknowledgement') + const next = f.client() + expect(await next.request('fresh', {}, signal)).toMatchObject({ pid: 101, connection: 1 }) + expect(f.spawn).toHaveBeenCalledTimes(2) +}) + +it.each(['wrong-runtime', 'wrong-instance', 'extra', 'malformed', 'oversized', 'invalid-utf8', 'exit'] as const)( + 'rejects %s startup before sending any desktop request', async (startup) => { + const f = await fixture({ startup }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it.each(['wrong-instance', 'wrong-pid', 'extra', 'malformed', 'oversized'] as const)( + 'rejects a %s Agent handshake before dispatch', async (handshake) => { + const f = await fixture({ handshake }) + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.filter(frame => frame.method)).toEqual([]) + }, +) + +it('reports the helper exit diagnostic when stdout ends before process settlement', async () => { + const f = await fixture({ startup: 'exit', startupDiagnostic: 'Application-control policy refused the executable' }) + const pending = f.client().request('getCapabilities', {}, new AbortController().signal) + await expect(pending).rejects.toMatchObject({ code: 'NATIVE_EXITED' }) + await expect(pending).rejects.toThrow('Application-control policy refused the executable') + expect(f.generations[0]!.received).toEqual([]) + await f.runtime.dispose() +}) + +it('joins a connection closed before helper readiness', async () => { + const f = await fixture() + const client = f.client() + await client.dispose() + expect(client.disposed).toBe(true) + await f.runtime.dispose() +}) + +it('settles a queued write when its connection is closed before readiness', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const written = new Promise(resolve => channel.stdin.write('input\n', resolve)) + channel.close() + expect(await written).toBeInstanceOf(Error) + await channel.waitForClose() +}) + +it('ends the native connection when its writable stream is finalized', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + channel.stdin.end() + await channel.done + await channel.waitForClose() +}) + +it('rejects unsolicited process output and closes the admitted Agent', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('closes all active Agent connections when the Host unloads', async () => { + const f = await fixture() + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await f.runtime.dispose() + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) +}) + +it.each(['silent', 'stdout-error', 'stdout-close'] as const)('settles %s process startup and joins cleanup', async (startup) => { + const f = await fixture({ startup }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() + expect(f.generations[0]!.received).toEqual([]) +}) + +it('bounds a silent Agent handshake without sending desktop input', async () => { + const f = await fixture({ handshake: 'silent' }) + f.config.connectTimeoutMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + expect(f.generations[0]!.received.map(frame => frame.type)).toEqual(['hello']) +}) + +it('preserves bytes after pipe readiness for the request parser', async () => { + const f = await fixture({ handshake: 'initial-result' }) + const channel = f.runtime.connect(f.config) + const data = new Promise(resolve => channel.stdout.once('data', (chunk) =>{ resolve(String(chunk)) })) + expect(await data).toContain('"id":"early"') + channel.close() + await channel.waitForClose() +}) + +it('rejects a connection cleanup deadline and stops the Host process', async () => { + const f = await fixture({ ignoreClose: true, ignoreParent: true }) + f.config.graceMs = 100 + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') + await expect(channel.done).rejects.toThrow('cleanup') + await expect(channel.waitForClose()).rejects.toThrow('cleanup acknowledgement') +}) + +it.each([false, 'reject'] as const)('reports unsuccessful process-range cleanup: %s', async (processCleanup) => { + const f = await fixture({ processCleanup }) + await f.client().request('one', {}, new AbortController().signal) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('refuses writes after a ready connection starts closing', async () => { + const f = await fixture() + const channel = f.runtime.connect(f.config) + const response = new Promise(resolve => channel.stdout.once('data', () =>{ resolve() })) + channel.stdin.write('{"id":"one","method":"probe"}\n') + await response + channel.close() + const error = await new Promise(resolve => channel.stdin.write('late\n', resolve)) + expect(error?.message).toContain('closing') + await channel.waitForClose() +}) + +it('joins shutdown requested synchronously while the subprocess is being acquired', async () => { + const options: FixtureOptions = {} + const f = await fixture(options) + let closing: Promise | undefined + options.onSpawn = () => { closing = f.runtime.dispose() } + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await closing +}) + +it('reports an untyped subprocess rejection as a request failure', async () => { + const f = await fixture() + f.spawn.mockImplementationOnce(() => { throw 'subprocess failure' }) + const channel = f.runtime.connect(f.config) + await expect(channel.done).rejects.toThrow('subprocess failure') + await channel.waitForClose() +}) + +it('forces a helper that ignores parent closure to stop after malformed readiness', async () => { + const f = await fixture({ startup: 'malformed', ignoreParent: true }) + f.config.graceMs = 100 + await expect(f.client().request('input', {}, new AbortController().signal)).rejects.toThrow() + await f.runtime.dispose() +}) + +it('contains a cleanup failure after unsolicited process output', async () => { + const f = await fixture({ processCleanup: 'reject' }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + f.generations[0]!.stdout.write('unexpected\n') + await vi.waitFor(() =>{ expect(client.disposed).toBe(true) }) + await expect(f.runtime.dispose()).rejects.toThrow('cleanup failed') +}) + +it('does not restart a stopped helper while the Host is unloading', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + onTestFinished(() =>{ release.resolve() }) + const f = await fixture({ cleanupGate: release.promise }) + await f.client().request('ready', {}, new AbortController().signal) + await f.generations[0]!.stop() + await vi.waitFor(() =>{ expect(f.generations[0]!.stdout.readableEnded).toBe(true) }) + const channel = f.runtime.connect(f.config) + const done = expect(channel.done).resolves.toBeUndefined() + const closing = f.runtime.dispose() + release.resolve() + await Promise.all([done, closing]) + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('waits for the native cleanup frame even after an operation has completed', async () => { + const release: PromiseWithResolvers = Promise.withResolvers() + const f = await fixture({ connectionCleanup: release.promise }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + let settled = false + const closing = client.dispose().then(() => { settled = true }) + try { + await vi.waitFor(() => { expect(f.generations[0]!.received.some(frame => frame.type === 'close')).toBe(true) }) + expect(settled).toBe(false) + } finally { release.resolve() } + await closing + expect(settled).toBe(true) +}) + +it('refuses EOF as evidence that native connection cleanup completed', async () => { + const f = await fixture({ eofOnClose: true }) + const client = f.client() + await client.request('one', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('rejects an unsolicited cleanup frame while an Agent is still active', async () => { + const f = await fixture() + const client = f.client() + await client.request('one', {}, new AbortController().signal) + for (const peer of f.generations[0]!.peers) peer.write('{"type":"closed"}\n') + await vi.waitFor(() => { expect(client.disposed).toBe(true) }) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) + +it('recognizes fragmented cleanup controls without buffering operation payloads', async () => { + const f = await fixture({ ignoreClose: true }) + const channel = f.runtime.connect(f.config) + const ready = once(channel.stdout, 'data') + channel.stdin.write('{"id":"one","method":"probe"}\n') + await ready + const peer = [...f.generations[0]!.peers][0]! + const send = async (part: string) => { + const received = once(channel.stdout, 'data') + peer.write(part) + expect(String((await received)[0])).toBe(part) + } + await send('{"id":') + await send('"two","result":"a long ') + await send('fragmented operation payload') + await send('"}\n') + channel.close() + peer.write('{"type":') + peer.end('"closed"}\n') + await channel.waitForClose() +}) + + +it('joins WSL bridge EOF after cleanup while keeping other Agents usable', async () => { + const f = await fixture({ transport: 'stdio', split: true }) + const a = f.client(), b = f.client(), signal = new AbortController().signal + expect(await a.request('first', {}, signal)).toMatchObject({ connection: 1 }) + expect(await b.request('second', {}, signal)).toMatchObject({ connection: 2 }) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--serve'))).toHaveLength(1) + expect(f.spawn.mock.calls.filter(([spec]) => spec.argv.includes('--bridge'))).toHaveLength(2) + await a.dispose() + expect(await b.request('still-open', {}, signal)).toMatchObject({ connection: 2 }) + await b.dispose() + await f.runtime.dispose() + expect(f.generations[0]!.peers.size).toBe(0) +}) + +it('forwards cancellation over WSL without replaying the request', async () => { + const f = await fixture({ transport: 'stdio' }) + const client = f.client(), controller = new AbortController() + const pending = client.request('hold', {}, controller.signal) + const rejected = expect(pending).rejects.toThrow('cancelled') + await vi.waitFor(() => { expect(f.generations[0]?.received.some(frame => frame.method === 'hold')).toBe(true) }) + controller.abort() + await rejected + expect(await client.request('next', {}, new AbortController().signal)).toMatchObject({ connection: 1 }) + expect(f.generations[0]!.received.filter(frame => frame.method === 'hold')).toHaveLength(1) +}) + +it('rejects WSL EOF without a desktop cleanup acknowledgement', async () => { + const f = await fixture({ transport: 'stdio', eofOnClose: true }) + const client = f.client() + await client.request('ready', {}, new AbortController().signal) + await expect(client.dispose()).rejects.toThrow('cleanup acknowledgement') +}) diff --git a/packages/experimental/cua-windows/tests/native-transport.spec.ts b/packages/experimental/cua-windows/tests/native-transport.spec.ts new file mode 100644 index 0000000000..276b5ad786 --- /dev/null +++ b/packages/experimental/cua-windows/tests/native-transport.spec.ts @@ -0,0 +1,29 @@ +/** WSL bridge exit is part of native connection cleanup, independently of protocol EOF. */ +import { PassThrough } from 'node:stream' +import { expect, it, onTestFinished } from 'vitest' +import type { NativeClientConfig } from '@deepseek-ai/dsh-cua/native-client' +import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess' +import { connectWindowsPipe } from '../src/native-transport.ts' + +it.each([ + { exitCode: 0, signal: null, joined: true, error: undefined }, + { exitCode: 1, signal: null, joined: true, error: 'exited unsuccessfully' }, + { exitCode: 0, signal: null, joined: false, error: 'did not exit' }, +] as const)('joins bridge exit $exitCode with process cleanup $joined', async ({ exitCode, signal, joined, error }) => { + const stdin = new PassThrough(), stdout = new PassThrough() + const done = Promise.withResolvers() + const handle: SubprocessHandle = { stdin, stdout, stderr: undefined, control: undefined, collected: {}, + done: done.promise, terminate: () => { done.resolve({ exitCode: null, signal: 'SIGTERM' }) }, + waitForExit: async () => joined } + const config: NativeClientConfig = { helperPath: '/fixture.exe', cwd: '/', timeoutMs: 30_000, connectTimeoutMs: 5000, + screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1_048_576, maxResponseBytes: 1_048_576, + graceMs: 3000, textEventIntervalMs: 0, maxClickHoldMs: 10_000 } + const connection = connectWindowsPipe({ spawn: () => handle }, config, 'pipe', 'digest', 'stdio') + connection.stream.on('error', () => {}) + onTestFinished(() => { connection.stream.destroy(); stdin.destroy(); stdout.destroy() }) + const closing = connection.dispose() + expect(stdin.writableEnded).toBe(true) + done.resolve({ exitCode, signal }) + if (error) await expect(closing).rejects.toThrow(error) + else await closing +}) diff --git a/packages/experimental/cua-windows/tests/protocol.spec.ts b/packages/experimental/cua-windows/tests/protocol.spec.ts new file mode 100644 index 0000000000..0064d22ccb --- /dev/null +++ b/packages/experimental/cua-windows/tests/protocol.spec.ts @@ -0,0 +1,30 @@ +/** Both native languages admit the same generated model and Host operation fields. */ +import { readFile } from 'node:fs/promises' +import { expect, it } from 'vitest' +import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' +import { ActionResult, NativeScreenshotResult } from '@deepseek-ai/dsh-cua/protocol' +import { Config } from '../src/index.ts' + +it('keeps the C# admission schema identical to the shared generated schema', async () => { + expect(await readFile(new URL('../native/protocol.schema.json', import.meta.url), 'utf8')).toBe(nativeProtocol().json) +}) + +it('preserves Windows physical capture units and observed foreground changes', () => { + const image = { mimeType: 'image/png', data: 'AAAA', pixelWidth: 1200, pixelHeight: 800, windowId: 1, + bounds: { x: -1200, y: 0, width: 1200, height: 800 }, coordinateSpace: 'window-pixels' } + expect(NativeScreenshotResult.parse(image).coordinateSpace).toBe('window-pixels') + expect(() => NativeScreenshotResult.parse({ ...image, coordinateSpace: 'screen-pixels' })).toThrow() + expect(ActionResult.parse({ dispatched: true, verified: false, foregroundChanged: true })).toEqual({ + dispatched: true, foregroundChanged: true, + }) +}) + +it('resolves Windows compiler and input defaults while rejecting unsupported numeric limits', () => { + const resolved = Config({}) + expect(resolved.dotnetPath).toBe('dotnet') + expect(resolved.pollIntervalMs).toBe(25) + expect(resolved.textEventIntervalMs).toBe(0) + expect(() => Config({ dotnetPath: '' })).toThrow() + expect(() => Config({ pollIntervalMs: 0 })).toThrow() + expect(() => Config({ maxResponseBytes: 2 ** 31 })).toThrow() +}) diff --git a/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts new file mode 100644 index 0000000000..4b1f2bf622 --- /dev/null +++ b/packages/experimental/cua-windows/tests/provider-lifecycle.spec.ts @@ -0,0 +1,108 @@ +/** Provider preparation must finish before installation and join cancellation on unload. */ +import { resolve } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { WslPreparation } from '../src/windows-host.ts' +import type { NativeBuildSpec } from '../src/native-build.ts' +import type { installCua } from '@deepseek-ai/dsh-cua' +import { beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { apply, Config } from '../src/index.ts' +import { GUIDANCE } from '../src/guidance.ts' + +const native = vi.hoisted(() => ({ + prepare: vi.fn<(spec: NativeBuildSpec) => Promise>(), + host: vi.fn<() => 'windows' | 'wsl'>(() => 'windows'), + wsl: vi.fn<(spec: WslPreparation) => Promise<{ architecture: 'arm64'; cacheDirectory: string }>>(), + retain: vi.fn<(path: string, cache: string, signal: AbortSignal) => Promise>(), + architecture: vi.fn(() => 'x64' as const), + install: vi.fn(), connect: vi.fn(), dispose: vi.fn(), construct: vi.fn(), +})) +vi.mock('../src/windows-host.ts', () => ({ windowsHost: native.host, prepareWsl: native.wsl, retainWslHelper: native.retain })) +vi.mock('../src/native-build.ts', async original => ({ + ...await original(), + prepareNativeExecutable: native.prepare, nativeHostArchitecture: native.architecture, +})) +vi.mock('@deepseek-ai/dsh-cua', async original => ({ + ...await original(), installCua: native.install, +})) +vi.mock('../src/native-runtime.ts', () => ({ WindowsNativeRuntime: class { + constructor(...args: unknown[]) { native.construct(...args) } + connect = native.connect + dispose = native.dispose +} })) +beforeEach(() => { vi.clearAllMocks(); native.host.mockReturnValue('windows'); native.prepare.mockResolvedValue(resolve('prepared-helper')); native.dispose.mockResolvedValue(undefined) }) +function owner() { const ctx = new Context(); onTestFinished(() => ctx.fiber.dispose()); return ctx } + +it('rejects relative overrides before installing a native provider', async () => { + await expect(apply(owner(), Config({ helperPath: 'relative.exe' }))).rejects.toThrow('must be absolute') + expect(native.install).not.toHaveBeenCalled() +}) +it('uses an absolute fixture without compiling and disposes the Host runtime', async () => { + const ctx = owner(), config = Config({ helperPath: resolve('fixture.exe'), pollIntervalMs: 13 }) + await apply(ctx, config) + expect(native.prepare).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 13, 'pipe') + const backend = native.install.mock.calls[0]![2] + expect(backend.guidance).toBe(GUIDANCE) + expect(backend.capabilities).toMatchObject({ platform: 'windows', appLevelAccessibility: false, keyboard: ['window'] }) + const channel = { marker: 'native stream' } + native.connect.mockReturnValue(channel) + const options = { ...config, helperPath: backend.helperPath, cwd: process.cwd() } + expect(backend.createChannel(ctx, options)).toBe(channel) + expect(native.connect).toHaveBeenCalledWith(options) + await ctx.fiber.dispose() + expect(native.dispose).toHaveBeenCalledOnce() +}) +it('prepares before installation and aborts the completed preparation scope on unload', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + native.prepare.mockReturnValueOnce(prepared.promise) + const pending = apply(ctx, Config({})) + expect(native.install).not.toHaveBeenCalled() + prepared.resolve(resolve('compiled.exe')) + await pending + expect(native.install.mock.calls[0]![2].helperPath).toBe(resolve('compiled.exe')) + await ctx.fiber.dispose() + expect(native.prepare.mock.calls[0]![0].signal.aborted).toBe(true) +}) +it('reports compiler failure without installing tool registrations', async () => { + native.prepare.mockRejectedValueOnce(new Error('compiler unavailable')) + const ctx = owner() + await expect(apply(ctx, Config({}))).rejects.toThrow('compiler unavailable') + await ctx.fiber.dispose() + expect(native.install).not.toHaveBeenCalled() +}) +it('joins canceled preparation and rejects its late success', async () => { + const ctx = owner(), prepared = Promise.withResolvers() + onTestFinished(() =>{ prepared.resolve(resolve('late.exe')) }) + native.prepare.mockReturnValueOnce(prepared.promise) + const starting = apply(ctx, Config({})) + const rejected = expect(starting).rejects.toThrow() + const signal = native.prepare.mock.calls[0]![0].signal + const aborted = new Promise((resolve) =>{ signal.addEventListener('abort', () =>{ resolve() }, { once: true }) }) + let closed = false + const closing = ctx.fiber.dispose().then(() => { closed = true }) + await aborted + expect(closed).toBe(false) + prepared.resolve(resolve('late.exe')) + await Promise.all([rejected, closing]) + expect(native.install).not.toHaveBeenCalled() +}) + +it('prepares the Windows architecture and stdio transport for WSL', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockResolvedValue({ architecture: 'arm64', cacheDirectory: '/mnt/c/cache' }) + native.retain.mockResolvedValue('/mnt/c/cache/helper.exe') + const ctx = owner() + await apply(ctx, Config({})) + expect(native.prepare.mock.calls[0]![0].architecture).toBe('arm64') + expect(native.architecture).not.toHaveBeenCalled() + expect(native.construct).toHaveBeenCalledWith(ctx, 25, 'stdio') + expect(native.install.mock.calls[0]![2].helperPath).toBe('/mnt/c/cache/helper.exe') +}) + +it('does not compile or register CUA when WSL interoperation fails', async () => { + native.host.mockReturnValue('wsl') + native.wsl.mockRejectedValue(new Error('Windows interoperation unavailable')) + await expect(apply(owner(), Config({}))).rejects.toThrow('interoperation unavailable') + expect(native.prepare).not.toHaveBeenCalled() + expect(native.install).not.toHaveBeenCalled() +}) diff --git a/packages/experimental/cua-windows/tests/windows-host.spec.ts b/packages/experimental/cua-windows/tests/windows-host.spec.ts new file mode 100644 index 0000000000..3d27b5d1dc --- /dev/null +++ b/packages/experimental/cua-windows/tests/windows-host.spec.ts @@ -0,0 +1,66 @@ +/** WSL classification is independent of Windows interoperation and executable preparation. */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { prepareWsl, retainWslHelper, windowsHost } from '../src/windows-host.ts' + +it('distinguishes Windows Node, WSL Linux Node, and ordinary Linux', () => { + expect(windowsHost({ platform: 'win32', env: { WSL_DISTRO_NAME: 'Ubuntu' } })).toBe('windows') + expect(windowsHost({ platform: 'linux', env: {}, osRelease: '6.6.87-microsoft-standard-WSL2' })).toBe('wsl') + expect(() => windowsHost({ platform: 'linux', env: {}, osRelease: '6.8.0-generic' })).toThrow('ordinary Linux') +}) + +function fixture(output = '{"architecture":"arm64","cache":"C:\\\\Users\\\\test user\\\\AppData\\\\Local\\\\DeepSeekHarness\\\\cua"}', exitCode = 0) { + const terminate = vi.fn(), waitForExit = vi.fn(async () => true) + const spawn = vi.fn((spec: SubprocessSpawnSpec): SubprocessHandle => { + const text = spec.argv[0] === 'wslpath' ? '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua\n' : output + return { stdin: undefined, stdout: undefined, stderr: undefined, control: undefined, + collected: { stdout: { readFrom: () => ({ text, nextOffset: Buffer.byteLength(text), lossy: false }) } }, + done: Promise.resolve({ exitCode, signal: null }), terminate, waitForExit } + }) + return { spec: { subprocess: { spawn }, signal: new AbortController().signal, timeoutMs: 10_000, graceMs: 1000, powershellPath: 'powershell.exe' }, spawn, terminate, waitForExit } +} + +it('uses the Windows architecture and translates the cache without shell interpolation', async () => { + const f = fixture() + expect(await prepareWsl(f.spec)).toEqual({ architecture: 'arm64', cacheDirectory: '/mnt/c/Users/test user/AppData/Local/DeepSeekHarness/cua' }) + expect(f.spawn.mock.calls[1]![0].argv).toEqual(['wslpath', '-u', 'C:\\Users\\test user\\AppData\\Local\\DeepSeekHarness\\cua']) + expect(f.waitForExit).toHaveBeenCalledTimes(2) +}) + +it.each(['not json', '{"architecture":"ia32","cache":"C:\\\\cache"}', '{"architecture":"x64","cache":"relative"}'])( + 'rejects invalid Windows capability output %s before using it as a path', async (output) => { + const f = fixture(output) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() + expect(f.waitForExit).toHaveBeenCalledOnce() + }, +) + +it('reports unavailable interoperation and does not launch path conversion', async () => { + const f = fixture('', 1) + await expect(prepareWsl(f.spec)).rejects.toThrow('WSL cannot prepare') + expect(f.spawn).toHaveBeenCalledOnce() +}) + +it('rejects canceled preparation before starting a Windows command', async () => { + const f = fixture(), controller = new AbortController() + controller.abort(new Error('provider unloaded')) + await expect(prepareWsl({ ...f.spec, signal: controller.signal })).rejects.toThrow('provider unloaded') + expect(f.spawn).not.toHaveBeenCalled() +}) + +it('retains exact helper bytes once and rejects a changed cached executable', async () => { + const directory = await mkdtemp(join(tmpdir(), 'cua-wsl-cache-')) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const helper = join(directory, 'source.exe'), signal = new AbortController().signal + const bytes = Buffer.from('signed payload bytes') + await writeFile(helper, bytes) + const result = await retainWslHelper(helper, join(directory, 'cache'), signal) + expect(await readFile(result)).toEqual(bytes) + expect(await retainWslHelper(helper, join(directory, 'cache'), signal)).toBe(result) + await writeFile(result, 'changed') + await expect(retainWslHelper(helper, join(directory, 'cache'), signal)).rejects.toThrow('digest') +}) diff --git a/packages/experimental/cua-windows/tsconfig.json b/packages/experimental/cua-windows/tsconfig.json new file mode 100644 index 0000000000..0d2d829073 --- /dev/null +++ b/packages/experimental/cua-windows/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../cua/tsconfig.host.json" + }, + { + "path": "../../subprocess/subprocess" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/native-command" + }, + { + "path": "../../util/atomic-write" + } + ] +} diff --git a/packages/experimental/cua/src/access-types.ts b/packages/experimental/cua/src/access-types.ts index 4679f7ba14..0a587124d4 100644 --- a/packages/experimental/cua/src/access-types.ts +++ b/packages/experimental/cua/src/access-types.ts @@ -10,7 +10,7 @@ export interface CuaPermissionProcess { path?: string | undefined name?: string | undefined } -/** Native access observations tagged with Node platform identifiers; distinct from model capability platform names. */ +/** Native access observations tagged with the provider's CUA platform; distinct from Node process.platform values. */ export type CuaSystemPermissionState = { platform: 'darwin' accessibility: boolean @@ -20,7 +20,7 @@ export type CuaSystemPermissionState = { /** Application macOS reports as responsible for the helper, captured at startup; absent when it cannot be identified. */ launchApplication?: { name: string; path: string; icon?: string | undefined } | undefined } | { - platform: 'win32' + platform: 'windows' sessionLocked: boolean | null captureAvailable: boolean elevated: boolean diff --git a/packages/experimental/cua/src/access.ts b/packages/experimental/cua/src/access.ts index 35fe5a60a1..535bfe84fb 100644 --- a/packages/experimental/cua/src/access.ts +++ b/packages/experimental/cua/src/access.ts @@ -24,7 +24,7 @@ const systemPermissions = z.discriminatedUnion('platform', [z.object({ platform: z.literal('darwin'), accessibility: z.boolean(), screenRecording: z.boolean(), helper: permissionProcess, parent: permissionProcess, launchApplication: z.object({ name: z.string().min(1), path: z.string().min(1), icon: ApplicationIcon.optional() }).optional(), }), z.object({ - platform: z.literal('win32'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), + platform: z.literal('windows'), sessionLocked: z.boolean().nullable(), captureAvailable: z.boolean(), elevated: z.boolean(), helper: permissionProcess, })]) diff --git a/packages/experimental/cua/src/client/PermissionPanel.tsx b/packages/experimental/cua/src/client/PermissionPanel.tsx index 699fd8b413..fdc43b5e7c 100644 --- a/packages/experimental/cua/src/client/PermissionPanel.tsx +++ b/packages/experimental/cua/src/client/PermissionPanel.tsx @@ -142,7 +142,7 @@ function UnknownStatus({ loading, t }: Pick & { loading: b } function WindowsStatus({ system, uncertain, t }: Pick & { - system: Extract + system: Extract uncertain: boolean }) { const unlocked = system.sessionLocked === false @@ -161,7 +161,7 @@ function WindowsStatus({ system, uncertain, t }: Pick & { function systemReady(system: CuaSystemPermissionState): boolean { switch (system.platform) { case 'darwin': return system.accessibility && system.screenRecording - case 'win32': return system.sessionLocked === false && system.captureAvailable + case 'windows': return system.sessionLocked === false && system.captureAvailable /* v8 ignore next -- Native permission responses validate the closed platform union. */ default: return assertNever(system) } @@ -195,7 +195,7 @@ export function PermissionPanel(props: PermissionPanelProps) { } {observed === null ? - : observed.platform === 'win32' ? + : observed.platform === 'windows' ? : (['accessibility', 'screenRecording'] as const).map(permission =>
@@ -207,7 +207,7 @@ export function PermissionPanel(props: PermissionPanelProps) { busy={busy} request={props.request} openSettings={props.openSettings} t={t} />
)}
-

{observed?.platform === 'win32' +

{observed?.platform === 'windows' ? <>{t('windowsInstructions')} {t(observed.elevated ? 'elevated' : 'standardPrivileges')} : t('permissionHint')}

@@ -241,12 +241,12 @@ export function PermissionSetup({ t, refresh, useCuaPermissions, onDismiss, onOp && systemReady(state.value) useEffect(() => { if (ready && !state.busy) onDismiss() }, [ready, state.busy, onDismiss]) return }> -

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'win32' ? 'setupBody' +

{t(state.error !== null ? 'setupQueryFailed' : state.value?.platform !== 'windows' ? 'setupBody' : state.value.sessionLocked === null ? 'windowsSessionUnknown' : state.value.sessionLocked ? 'windowsSetupBody' : 'windowsCaptureUnavailable')}

diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 93947ad32c..df935f6525 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -4,7 +4,7 @@ export const COMMON_GUIDANCE = `Use cua to observe and operate native applicatio In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes. -Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid. +Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. diff --git a/packages/experimental/cua/tests/panel.client.spec.tsx b/packages/experimental/cua/tests/panel.client.spec.tsx index 6558fd06d4..613f24fce3 100644 --- a/packages/experimental/cua/tests/panel.client.spec.tsx +++ b/packages/experimental/cua/tests/panel.client.spec.tsx @@ -439,7 +439,7 @@ it('retains a known read-only configuration and query failure throughout managem it.each([true, false, null] as const)('shows Windows desktop access for lock state %s without macOS permission actions', (sessionLocked) => { const f = fixture() - f.publish({ ...observe(value), system: { value: { platform: 'win32', sessionLocked, captureAvailable: true, + f.publish({ ...observe(value), system: { value: { platform: 'windows', sessionLocked, captureAvailable: true, elevated: false, helper: { pid: 9, path: 'C:\\helper.exe' } }, error: null, busy: false } }) render() const desktop = screen.getByRole('group', { name: en.windowsDesktop }) @@ -451,7 +451,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta expect(screen.queryByRole('button', { name: en.request })).toBeNull() expect(screen.queryByRole('button', { name: en.granted })).toBeNull() expect(screen.queryByText('C:\\helper.exe')).toBeNull() - f.publish({ system: { value: { platform: 'win32', sessionLocked: false, captureAvailable: false, + f.publish({ system: { value: { platform: 'windows', sessionLocked: false, captureAvailable: false, elevated: true, helper: { pid: 9 } }, error: null, busy: false } }) expect(within(capture).getByText(en.unavailable)).toBeTruthy() expect(screen.getByText(en.elevated, { exact: false })).toBeTruthy() @@ -461,7 +461,7 @@ it.each([true, false, null] as const)('shows Windows desktop access for lock sta it.each([[true, true], [false, true], [false, false], [null, true]] as const)('offers Windows setup for lock=%s and capture=%s', (sessionLocked, captureAvailable) => { const f = fixture(), onDismiss = vi.fn() - f.publish({ system: { value: { platform: 'win32', sessionLocked, captureAvailable, + f.publish({ system: { value: { platform: 'windows', sessionLocked, captureAvailable, elevated: false, helper: { pid: 9 } }, error: null, busy: false } }) render() const needsSetup = sessionLocked !== false || !captureAvailable diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..f910604ac9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,6 +45,9 @@ importers: '@deepseek-ai/dsh-cua-bundle': specifier: workspace:* version: link:packages/experimental/cua-bundle + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:packages/experimental/cua-windows '@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp': specifier: workspace:* version: link:packages/experimental/browser-use-chrome-devtools-mcp @@ -9965,6 +9968,9 @@ importers: specifier: ^4.2.0 version: 4.3.2 optionalDependencies: + '@deepseek-ai/dsh-cua-windows': + specifier: workspace:* + version: link:../cua-windows '@deepseek-ai/dsh-experimental-cua-macos': specifier: workspace:* version: link:../cua-macos @@ -10093,6 +10099,115 @@ importers: specifier: ^0.35.3 version: 0.35.5(@types/node@22.20.1) + packages/experimental/cua-windows: + dependencies: + '@deepseek-ai/dsh-atomic-write': + specifier: workspace:* + version: link:../../util/atomic-write + '@deepseek-ai/dsh-cua': + specifier: workspace:* + version: link:../cua + '@deepseek-ai/dsh-native-command': + specifier: workspace:* + version: link:../../util/native-command + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: ^4.4.3 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/cordis-plugin-timer': + specifier: workspace:~ + version: link:../../../vendor/timer + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:* + version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:* + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-app-boot': + specifier: workspace:* + version: link:../../boot/app-boot + '@deepseek-ai/dsh-attachment': + specifier: workspace:* + version: link:../../attachment/attachment + '@deepseek-ai/dsh-attachment-local': + specifier: workspace:* + version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-computer-use': + specifier: workspace:* + version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-config-editor': + specifier: workspace:* + version: link:../../boot/config-editor + '@deepseek-ai/dsh-fs-local': + specifier: workspace:* + version: link:../../fs/fs-local + '@deepseek-ai/dsh-hmr': + specifier: workspace:* + version: link:../../boot/hmr + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:* + version: link:../../llm/llm-deepseek + '@deepseek-ai/dsh-ptc-runtime': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime + '@deepseek-ai/dsh-ptc-runtime-node': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime-node + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:* + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:* + version: link:../../sandbox/sandbox-policy + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-settings': + specifier: workspace:* + version: link:../../settings/settings + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-user-questions': + specifier: workspace:* + version: link:../../interaction/user-questions + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory + sharp: + specifier: ^0.35.3 + version: 0.35.5(@types/node@22.20.1) + packages/experimental/forge: dependencies: '@deepseek-ai/dsh-brand': diff --git a/scripts/check-workspace-constraints.ts b/scripts/check-workspace-constraints.ts index f759eca7ec..a9ec59f11b 100644 --- a/scripts/check-workspace-constraints.ts +++ b/scripts/check-workspace-constraints.ts @@ -190,6 +190,7 @@ const packageFileExtras: Readonly> = { // CUA publishes its client API and attributed native source for local macOS builds. '@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'], '@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'], + '@deepseek-ai/dsh-cua-windows': ['native/bin', 'native/CuaWindows.csproj', 'native/Directory.Build.props', 'native/app.manifest', 'native/src', 'native/protocol', 'native/protocol.schema.json', 'native/packages.lock.json'], '@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'], // Liveshare publishes its built Relay gateway entry and the shared runtime // chunk that entry imports. Its `./types` export is a type-only module, so diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index df85af1620..705eab4ec0 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -8,6 +8,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly> = { 'packages/experimental/cua': '@deepseek-ai/dsh-cua', 'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle', + 'packages/experimental/cua-windows': '@deepseek-ai/dsh-cua-windows', 'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query', 'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm', 'packages/experimental/tool-terminal': '@deepseek-ai/dsh-tool-terminal', diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index feed57673f..1f15a4de89 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -72,6 +72,7 @@ describe('release families', () => { '@deepseek-ai/dsh-creation-recommendations', '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-cua-macos', + '@deepseek-ai/dsh-cua-windows', '@deepseek-ai/dsh-cua', '@deepseek-ai/dsh-experimental-forge-bundle', '@deepseek-ai/dsh-experimental-forge-github', diff --git a/tsconfig.base.json b/tsconfig.base.json index cfecbdc02b..ba550bee2d 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -113,6 +113,7 @@ "@deepseek-ai/dsh-computer-use/brand": ["./packages/computer-use/computer-use/src/brand.ts"], "@deepseek-ai/dsh-experimental-computer-use-cua-driver-mcp": ["./packages/experimental/computer-use-cua-driver-mcp/src/index.ts"], "@deepseek-ai/dsh-experimental-cua-macos": ["./packages/experimental/cua-macos/src/index.ts"], + "@deepseek-ai/dsh-cua-windows": ["./packages/experimental/cua-windows/src/index.ts"], "@deepseek-ai/dsh-cua/config": ["./packages/experimental/cua/src/config.ts"], "@deepseek-ai/dsh-cua/native-schema": ["./packages/experimental/cua/src/native-schema.ts"], "@deepseek-ai/dsh-cua/native-build": ["./packages/experimental/cua/src/native-build.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index ea675b53ba..e82ffd9f53 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -251,6 +251,7 @@ "benchmarks/**/*.ts", "packages/*/*/tests/**/*.ts", "packages/experimental/cua-macos/native/generate-protocol.ts", + "packages/experimental/cua-windows/native/generate-protocol.ts", "packages/experimental/claude-code-mods/examples/*/index.ts", "packages/experimental/inspector/scripts/**/*.ts", "packages/llm/llm-pi-ai/scripts/**/*.ts", @@ -322,6 +323,7 @@ { "path": "./packages/experimental/cua/tsconfig.host.json" }, { "path": "./packages/experimental/cua-bundle" }, { "path": "./packages/experimental/cua-macos" }, + { "path": "./packages/experimental/cua-windows" }, { "path": "./packages/client/ui-sidebar-documentpreview/tsconfig.host.json" }, { "path": "./packages/client/ui-sidebar-browser/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, From fda29f726da9c2d23269d4a3638eef296a830f61 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 18:02:08 +0800 Subject: [PATCH 019/205] 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 020/205] 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 021/205] 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 8a5ebd2351a1d1b58fff676fe5be576411f07e83 Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 18:07:56 +0800 Subject: [PATCH 022/205] refactor(cua): derive NativeError from HarnessError Use the shared coded-error base while preserving the NativeError constructor, name, code, message and cause. Add the error dependency, compiler reference and error-type assertions. --- packages/experimental/cua/package.json | 2 ++ packages/experimental/cua/src/native-client.ts | 8 ++++---- packages/experimental/cua/tests/native-client.spec.ts | 3 +++ packages/experimental/cua/tsconfig.host.json | 3 +++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..c74c702566 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -96,6 +96,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", @@ -119,6 +120,7 @@ "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "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/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index 25c93e15ce..25b5f4e5a9 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -1,6 +1,7 @@ /** Agent-scoped JSONL requests over a connection to the shared native helper. */ import { randomUUID } from 'node:crypto' import assert from 'node:assert/strict' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' @@ -19,15 +20,14 @@ const ScreenshotDiagnostic = z.object({ const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })]) /** Native refusal or transport failure with a stable machine-readable code. */ -export class NativeError extends Error { +export class NativeError extends HarnessError { /** * @param code - Native error code or a transport-owned NATIVE_* code. * @param message - Actionable diagnostic, without its code prefix. * @param options - Original failure when available. */ - constructor(readonly code: string, message: string, options?: ErrorOptions) { - super(`${code}: ${message}`, options) - this.name = 'NativeError' + constructor(code: string, message: string, options?: ErrorOptions) { + super(`${code}: ${message}`, code, options) } } diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index f7a9007f42..b23f4bb48c 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -1,5 +1,6 @@ /** Controlled connection streams exercise the platform-independent native protocol client. */ import { PassThrough, Writable } from 'node:stream' +import { HarnessError } from '@deepseek-ai/dsh-error' import { ToolCallId } from '@deepseek-ai/dsh-llm' import type { NativeChannel } from '../src/native-client.ts' import { describe, expect, it, onTestFinished, vi } from 'vitest' @@ -391,6 +392,8 @@ describe('native helper transport', () => { it('keeps native codes available to callers and in the model-visible diagnostic', () => { const error = new NativeError('PERMISSION_DENIED', 'Enable Accessibility') + expect(error).toBeInstanceOf(HarnessError) + expect(error.name).toBe('NativeError') expect(error.code).toBe('PERMISSION_DENIED') expect(error.message).toBe('PERMISSION_DENIED: Enable Accessibility') }) diff --git a/packages/experimental/cua/tsconfig.host.json b/packages/experimental/cua/tsconfig.host.json index 2386f83640..91b18de2b9 100644 --- a/packages/experimental/cua/tsconfig.host.json +++ b/packages/experimental/cua/tsconfig.host.json @@ -36,6 +36,9 @@ { "path": "../../util/brand" }, + { + "path": "../../util/error" + }, { "path": "../../util/atomic-write" }, From 3aee25862d5d9b1681a15998cb9086c448a7224f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 18:15:52 +0800 Subject: [PATCH 023/205] 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 = /