From f87efaaff9ac62effe59c36494cd9540ba89322a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:32:37 +0800 Subject: [PATCH 001/438] fix(cua): include floating windows in application observations --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 12 +- .../experimental/cua-macos/native/README.md | 6 +- .../cua-macos/native/README.zh.md | 6 +- .../native/Sources/CuaNative/AXWorker.swift | 4 +- .../Sources/CuaNative/NativePlatform.swift | 20 +- .../native/tests/FloatingWindowFixture.swift | 82 ++++++ .../native/tests/floating_windows_e2e.py | 119 +++++++++ .../cua-macos/native/upstream.json | 2 +- .../experimental/cua-macos/src/guidance.ts | 2 +- packages/experimental/cua/tests/api.spec.ts | 19 ++ .../session/cua-native/replay.override.json | 233 +++++++++++++++++- .../cua-native/workspace/native-helper.mjs | 13 +- 14 files changed, 497 insertions(+), 25 deletions(-) create mode 100644 packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift create mode 100644 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index e55c6a2f6b..e44dcfafcf 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -159,7 +159,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 5a63638f44..780bd63e55 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -159,7 +159,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index b25c409fb1..07a247a03b 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,14 +18,14 @@ en: 02b25ac1126b6094 zh: 3995a1f46354531b /dsh-cua-native-helper/request-protocol: - en: c8ad13843989b314 - zh: 2a42acb2faee8803 + en: 0fcf99df88166563 + zh: 71b7c3958e91d676 /dsh-cua-native-helper/observation-and-input: - en: c527eedc3a0ee968 - zh: ce8cc12d5a62e8ae + en: 968679773d0d8d33 + zh: 7796e6f76eda961f /dsh-cua-native-helper/verification: - en: a2ac6f2d581a1e8b - zh: f82c7d0c13539421 + en: abc45c2899d7c2bb + zh: bafb1f071d0bc2b2 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b44d6a65f4..9e8702619b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -48,7 +48,7 @@ Successful `activate` and `performSecondaryAction` AXRaise results include `fore | `findApps` | Installed matches `{id, displayName, path, isRunning, pid?}` from standard application directories or an absolute application path; discovery never launches them. | | `getApp` | `{appHandle, pid, name, bundleId, authorization}` selected by exact name, bundle ID, decimal PID or application path. A stopped selection has `pid: null` and waits for Host consent. Ambiguous names fail. | | `launchApp` | Host-only continuation after consent; starts the selected application without requesting activation, waits for launch completion and binds the handle to its verified process identity. | -| `listWindows` | Owned normal windows with `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | +| `listWindows` | Owned windows across all layers, including independent floating panels and menus, with `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include index, role, title, value, description, identifier, bounds, actions, and enabled state. Element bounds are null or [x, y, width, height] in screen points; window input uses local points. These structured element diagnostics are retained by native checks and omitted by the model tool projection. Unavailable optional descriptive properties are null, and an unavailable action list is empty; permission, communication and window-discovery failures still reject the observation. | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` records native dispatch. Read fresh state to verify the intended application change. | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`. PNG pixel dimensions can differ from window point dimensions on Retina displays. | @@ -67,7 +67,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Element actions require the exact snapshot ID. Native references never cross JSON. An optional snapshot ID on coordinate actions must belong to that window or an app-wide observation. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. Its window inventory matches `listWindows`; scoped observations register the selected floating window for coordinate input. Screenshots capture the selected window separately, so a main-window capture does not include independent floating panels. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Element actions require the exact snapshot ID. Native references never cross JSON. An optional snapshot ID on coordinate actions must belong to that window or an app-wide observation. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Element clicks without holdMs prefer advertised AX actions and otherwise use pointer delivery. Coordinate click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Modified element clicks use pointer delivery. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. No implicit fallback sends global desktop input. @@ -107,6 +107,8 @@ Run `python3 packages/experimental/cua-macos/native/tests/shared_helper_e2e.py - Run `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py --helper /absolute/helper` in a GUI login session to verify a Launch Services application that starts a nested GUI launcher and then the helper. The helper identifies the outer responsible application and retains its name and icon after the launchers exit. This check owns both applications and the helper, cleans up its Launch Services registrations, and does not request Accessibility or Screen Recording access. +Run `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py` after building to verify a nonactivating floating panel: discovery, Space metadata, scoped AX, separate main/panel screenshots, received clicks across inventory refreshes, and resize/close rejection. The check requires existing Accessibility and Screen Recording grants and owns its AppKit application. `--helper` selects an existing helper for comparison. + Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after building and unlocking the Mac to verify an owned window whose application removes and later restores its AX roots. The check requires existing Accessibility/Screen Recording grants, rejects stale element indices, captures the AXless window, verifies a coordinate click in the fixture state file, and checks restoration. It never changes system permission settings. Run `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence` to compare complete observations of the same owned AppKit window with 35 and 400 synthetic rows. Each helper receives one warmup and three alternating measured requests. All result fields must match except helper-generated app and snapshot IDs. The report keeps raw timings, byte counts, hashes and replies; it sets no CI speed threshold and makes no memory claim. Fixture startup can activate the application. Run without other desktop automation or compilation jobs. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index ecefb9c879..f24f3f43e5 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -48,7 +48,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 | `findApps` | 从标准应用目录或绝对应用路径返回已安装匹配项 `{id, displayName, path, isRunning, pid?}`;发现过程不启动应用。 | | `getApp` | 按精确名称、bundle ID、十进制 PID 或应用路径选择,返回 `{appHandle, pid, name, bundleId, authorization}`。未运行的选择具有 `pid: null`,等待 Host 授权。名称歧义会失败。 | | `launchApp` | 授权后的 Host 专用续接操作;不请求激活,等待应用启动完成后将句柄绑定到已核实的进程身份。 | -| `listWindows` | 应用所属普通窗口,包含 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | +| `listWindows` | 应用所属各层级窗口,包括独立浮层和菜单,包含 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含 index、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` 记录原生分派。需要读取新状态以核实预期的应用变化。 | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`。Retina 显示器上 PNG 像素尺寸可能不同于窗口 point 尺寸。 | @@ -67,7 +67,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。 窗口清单与 `listWindows` 一致,窗口级观察会登记所选浮层的坐标信息。截图单独捕获所选窗口,因此主窗口截图不包含独立浮层。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 未指定 holdMs 的元素点击优先使用声明的 AX 动作,否则通过鼠标事件发送。坐标点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。带修饰键的元素点击使用鼠标输入。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 @@ -107,6 +107,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 在 GUI 登录会话中运行 `python3 packages/experimental/cua-macos/native/tests/launcher_identity_e2e.py --helper /absolute/helper`,验证由 Launch Services 启动的应用先启动另一个 GUI 启动器,再启动 helper。helper 识别外层责任应用,并在启动器退出后保留其名称和图标。检查只使用测试自建的两个应用和 helper,结束后清理对应的 Launch Services 注册,不申请辅助功能或屏幕录制权限。 +构建后运行 `python3 packages/experimental/cua-macos/native/tests/floating_windows_e2e.py`,验证不获取焦点的浮层:窗口发现、Space 信息、窗口级 AX、主窗口与浮层分别截图、刷新窗口清单后的实际点击,以及尺寸变化和关闭后的拒绝行为。检查需要已有辅助功能和屏幕录制权限,AppKit 应用由测试创建和清理。`--helper` 可指定已有 helper 作比较。 + 构建并解锁 Mac 后运行 `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py`,验证应用移除并恢复 AX 根节点的窗口。检查需要已有辅助功能/屏幕录制权限,会拒绝过期元素索引,捕获无 AX 窗口,通过 fixture 状态文件核实坐标点击,并检查恢复。不会修改系统权限设置。 运行 `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence`,对比同一自建 AppKit 窗口中 35 行和 400 行合成内容的完整观察。每个 helper 先预热一次,再交替测量三次。除 helper 生成的应用和快照 ID 外,结果字段必须一致。报告保留原始耗时、字节数、哈希和回复,不设置 CI 性能阈值,也不声称内存表现。fixture 启动可能激活应用。运行时避免其他桌面自动化或编译任务。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index c11c78dc2e..4ac4c96a98 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -250,7 +250,7 @@ actor AXWorker { } let identity = try validateIdentity(handle) if method == "listWindows" { - let windows = NativePlatform.windows().filter { $0.pid == identity.pid } + let windows = NativePlatform.applicationWindows(identity.pid) // Remove closed window scopes using the current WindowServer identity set. let ids = Set(windows.map(\.windowID)) snapshots = snapshots.filter { key, _ in key.appHandle != handle || (key.windowID.map { ids.contains($0) } ?? true) } @@ -299,7 +299,7 @@ actor AXWorker { try NativePlatform.requireAccessibility() if let window { _ = try NativePlatform.ownedWindow(identity.pid, window) } try cancellation.check() - let observedWindows = NativePlatform.windows().filter { $0.pid == identity.pid } + let observedWindows = NativePlatform.applicationWindows(identity.pid) let id = try identifier("snapshot") let scope = SnapshotScope(appHandle: handle, windowID: window) snapshots[scope] = NativeSnapshot(id: id, scope: scope, elements: projection.indexed) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift index e4dcfe354e..b4a1859c5f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift @@ -110,12 +110,22 @@ enum NativePlatform { guard CGPreflightScreenCaptureAccess() else { throw NativeFailure(code: "PERMISSION_DENIED", message: "Screen Recording permission is required for the responsible host/helper") } } static func windows(allLayers: Bool = false) -> [WindowInfo] { - guard let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] else { return [] } - let memberships = allLayers ? [:] : WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value }) + let rows = windowRows().filter { allLayers || (($0[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0) == 0 } + return windowInfo(rows, includeSpaces: !allLayers) + } + /// App observations include floating panels and menus, with the same Space metadata as normal windows. + static func applicationWindows(_ pid: Int32) -> [WindowInfo] { + let rows = windowRows().filter { ($0[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == pid } + return windowInfo(rows, includeSpaces: true) + } + private static func windowRows() -> [[String: Any]] { + CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] + } + private static func windowInfo(_ rows: [[String: Any]], includeSpaces: Bool) -> [WindowInfo] { + let memberships = includeSpaces + ? WindowSpaces().memberships(windowIDs: rows.compactMap { ($0[kCGWindowNumber as String] as? NSNumber)?.uint32Value }) : [:] return rows.compactMap { row in - let layer = (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0 - guard allLayers || layer == 0, - let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, + guard let id = (row[kCGWindowNumber as String] as? NSNumber)?.uint32Value, let pid = (row[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value else { return nil } let raw = row[kCGWindowBounds as String] as? [String: NSNumber] ?? [:] let bounds = WindowBounds(x: raw["X"]?.doubleValue ?? 0, y: raw["Y"]?.doubleValue ?? 0, diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift new file mode 100644 index 0000000000..a95a8dfb94 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -0,0 +1,82 @@ +import AppKit +import Darwin + +final class FloatingPanel: NSPanel { + override var canBecomeKey: Bool { false } +} + +/// Publishes actual window geometry and received actions independently of the helper. +final class FloatingWindowFixture: NSObject, NSApplicationDelegate { + let statePath: String + var main: NSWindow! + var panel: FloatingPanel! + var button: NSButton! + var panelID = 0 + var count = 0 + var resized = false + var closed = false + var controls: [DispatchSourceSignal] = [] + var observer: Timer? + + init(statePath: String) { self.statePath = statePath } + func applicationDidFinishLaunching(_ notification: Notification) { + main = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 420, height: 300), + styleMask: [.titled, .closable], backing: .buffered, defer: false) + main.title = "Floating fixture main" + panel = FloatingPanel(contentRect: NSRect(x: 220, y: 250, width: 240, height: 140), + styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false) + panel.title = "Floating fixture panel" + panel.level = .floating + panel.hidesOnDeactivate = false + for window in [main!, panel!] { + window.isReleasedWhenClosed = false + window.animationBehavior = .none + window.collectionBehavior = [.canJoinAllApplications, .stationary] + } + button = NSButton(title: "Increment floating panel", target: self, action: #selector(increment)) + button.frame = NSRect(x: 20, y: 45, width: 200, height: 40) + panel.contentView!.addSubview(button) + main.makeKeyAndOrderFront(nil) + NSApplication.shared.activate(ignoringOtherApps: true) + panel.orderFrontRegardless() + panelID = panel.windowNumber + for number in [SIGUSR1, SIGUSR2] { + signal(number, SIG_IGN) + let control = DispatchSource.makeSignalSource(signal: number, queue: .main) + control.setEventHandler { [weak self] in + guard let self else { return } + if number == SIGUSR1 { self.panel.close(); self.closed = true } + else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } + self.persist() + } + control.resume() + controls.append(control) + } + // WindowServer visibility and frame updates settle after AppKit requests return. + observer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in self?.persist() } + persist() + print("READY") + fflush(stdout) + } + @objc func increment() { count += 1; persist() } + func persist() { + let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] + let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } + let rect = button.convert(button.bounds, to: nil) + let data = try! JSONSerialization.data(withJSONObject: [ + "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, + "panelLayer": row?[kCGWindowLayer as String] ?? -1, + "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, + "panelSize": [panel.frame.width, panel.frame.height], + "buttonPoint": [rect.midX, panel.frame.height - rect.midY], + "count": count, "resized": resized, "closed": closed, + ]) + try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) + } +} + +let app = NSApplication.shared +app.setActivationPolicy(.regular) +let fixture = FloatingWindowFixture(statePath: CommandLine.arguments[1]) +app.delegate = fixture +app.run() diff --git a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py new file mode 100644 index 0000000000..a3988509b6 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -0,0 +1,119 @@ +"""Discover, capture and operate an owned nonactivating floating panel on macOS.""" +import argparse +import base64 +import json +import os +from pathlib import Path +import plistlib +import signal +import subprocess +import tempfile +import time + +from native_test_support import ROOT, NativeHelper, line, run_cleanup, stop + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--helper', type=Path, help='Existing native helper executable') + args = parser.parse_args() + if os.uname().sysname != 'Darwin': + raise RuntimeError('This check requires macOS') + helper = NativeHelper([], args.helper) + fixture = None + try: + capabilities = helper.call('getCapabilities', {}) + if capabilities['sessionLocked'] is not False or capabilities['permissions'] != {'accessibility': True, 'screenRecording': True}: + raise RuntimeError('An unlocked Mac with Accessibility and Screen Recording grants is required') + with tempfile.TemporaryDirectory(prefix='dsh-floating-window-') as directory: + root = Path(directory) + contents = root / 'FloatingFixture.app/Contents' + (contents / 'MacOS').mkdir(parents=True) + (contents / 'Info.plist').write_bytes(plistlib.dumps({ + 'CFBundleIdentifier': 'org.deepseek-harness.' + root.name, + 'CFBundleExecutable': 'fixture', 'CFBundleName': 'Floating fixture', 'CFBundlePackageType': 'APPL', + })) + binary = contents / 'MacOS/fixture' + subprocess.run(['swiftc', str(ROOT / 'tests/FloatingWindowFixture.swift'), '-o', str(binary)], check=True) + state_path = root / 'state.json' + fixture = subprocess.Popen([str(binary), str(state_path)], stdout=subprocess.PIPE, text=True) + try: + assert line(fixture).strip() == 'READY' + + def wait_state(predicate): + deadline = time.monotonic() + 10 + while True: + state = json.loads(state_path.read_text()) + assert state['pid'] == fixture.pid, state + if predicate(state): + return state + if time.monotonic() >= deadline: + raise AssertionError('Fixture state did not settle: ' + json.dumps(state)) + time.sleep(0.025) + + actual = wait_state(lambda value: value['panelOnScreen'] and value['panelLayer'] > 0) + app = helper.call('getApp', {'selector': str(fixture.pid)}) + owner = {'appHandle': app['appHandle']} + panel_id = actual['panelWindowId'] + params = {**owner, 'maxElements': 100, 'maxDepth': 15} + panel = {**params, 'windowId': panel_id} + windows = helper.call('listWindows', owner) + assert panel_id in [window['windowId'] for window in windows], windows + assert all(window['pid'] == fixture.pid for window in windows), windows + listed = next(window for window in windows if window['windowId'] == panel_id) + assert listed['onCurrentSpace'] is True, listed + application = helper.call('getState', params) + assert application['focusedWindowId'] == actual['mainWindowId'], application + assert panel_id in [window['windowId'] for window in application['windows']], application + observed = helper.call('getState', panel) + assert 'Increment floating panel' in observed['tree'], observed + assert panel_id in [window['windowId'] for window in observed['windows']], observed + x, y = actual['buttonPoint'] + target = {**owner, 'windowId': panel_id, 'snapshotId': observed['snapshotId'], 'x': x, 'y': y} + helper.call('click', target) + wait_state(lambda value: value['count'] == 1) + main_capture = helper.call('screenshot', {**owner, 'windowId': actual['mainWindowId']}) + capture = helper.call('screenshot', {**owner, 'windowId': panel_id}) + assert capture['windowId'] == panel_id and main_capture['windowId'] == actual['mainWindowId'] + assert [capture['bounds']['width'], capture['bounds']['height']] == actual['panelSize'], capture + assert capture['bounds'] != main_capture['bounds'], (capture['bounds'], main_capture['bounds']) + assert base64.b64decode(capture['data'], validate=True).startswith(b'\x89PNG\r\n\x1a\n') + helper.call('click', target) + wait_state(lambda value: value['count'] == 2) + helper.call('listWindows', owner) + helper.call('click', target) + wait_state(lambda value: value['count'] == 3) + helper.call('getState', params) + helper.call('click', target) + wait_state(lambda value: value['count'] == 4) + os.kill(fixture.pid, signal.SIGUSR2) + actual = wait_state(lambda value: value['resized'] and value['panelSize'] != actual['panelSize']) + helper.call('click', target, 'WINDOW_CHANGED') + fresh = helper.call('getState', panel) + helper.call('click', target, 'STALE_SNAPSHOT') + x, y = actual['buttonPoint'] + target = {**target, 'snapshotId': fresh['snapshotId'], 'x': x, 'y': y} + helper.call('click', target) + wait_state(lambda value: value['count'] == 5) + os.kill(fixture.pid, signal.SIGUSR1) + wait_state(lambda value: value['closed'] and not value['panelOnScreen']) + deadline = time.monotonic() + 10 + while panel_id in [window['windowId'] for window in helper.call('listWindows', owner)]: + if time.monotonic() >= deadline: + raise AssertionError('Closed panel remains in WindowServer inventory') + time.sleep(0.025) + helper.call('click', target, 'STALE_SNAPSHOT') + helper.call('getState', panel, 'WINDOW_UNAVAILABLE') + helper.call('screenshot', {**owner, 'windowId': panel_id}, 'WINDOW_UNAVAILABLE') + helper.eof() + print('PASS: floating discovery, Space metadata, scoped AX, distinct captures, five received clicks, refresh, resize and close') + finally: + stop(fixture) + fixture.stdout.close() + fixture = None + finally: + run_cleanup(lambda: stop(fixture) if fixture is not None else None, helper.stop) + + +if __name__ == '__main__': + main() diff --git a/packages/experimental/cua-macos/native/upstream.json b/packages/experimental/cua-macos/native/upstream.json index df84ce4dbb..969c3c7273 100644 --- a/packages/experimental/cua-macos/native/upstream.json +++ b/packages/experimental/cua-macos/native/upstream.json @@ -33,7 +33,7 @@ { "local": "Sources/CuaNative/NativePlatform.swift", "upstream": "libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs", - "changes": "Reimplement application and window discovery using Swift AppKit/CoreGraphics, preserve process-lifetime checks, and isolate AppKit access on the main actor." + "changes": "Reimplement application and window discovery using Swift AppKit/CoreGraphics, preserve process-lifetime checks, and isolate AppKit access on the main actor. Enumerate app-owned windows across all layers with Space metadata while retaining normal-window queries for foreground diagnostics." } ], "localFiles": [ diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 6a4392ee9d..3c5d0dd53a 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -4,7 +4,7 @@ export const GUIDANCE = `Use cua with method getCapabilities and params {} to in Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index 6d1f4278cf..35d44a35e8 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -334,6 +334,25 @@ describe('application and window observations', () => { expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) }) + it('captures and clicks an explicitly selected floating panel while the main window keeps focus', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + const windows = [windowInfo(23), { ...windowInfo(24), title: 'Floating panel' }] + f.setWindowRecords(windows) + expect(await app.getWindows({ emit: false })).toEqual(windows) + f.dispatch.mockResolvedValueOnce(state({ windowId: 24, focusedWindowId: 23, windows })) + const panel = await app.getWindow(24) + await panel.getScreenshot() + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) + await app.getWindows({ emit: false }) + await panel.click([10, 20]) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'click', params: { + appHandle: 'app-17', snapshotId: 'changed', windowId: 24, x: 10, y: 20, mouseButton: 'left', clickCount: 1, + } }) + await app.getScreenshot() + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) + }) + it('does not select a focused window absent from the application observation', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/snapshots/session/cua-native/replay.override.json b/snapshots/session/cua-native/replay.override.json index 2fefba26f5..8c0531f14b 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -1649,6 +1649,237 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-open", + "name": "cua", + "arguments": "{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-list", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-observe", + "name": "cua", + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-screenshot", + "name": "cua", + "arguments": "{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-refresh", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-click", + "name": "cua", + "arguments": "{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-verify", + "name": "cua", + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -1827,7 +2058,7 @@ "index": 0, "block": { "type": "text", - "text": "Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested." + "text": "Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window." } }, { diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 2bbaa83188..ec52fe6f1e 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -38,7 +38,7 @@ function serve() { } const instanceId = randomUUID() const sockets = new Set() - const application = { count: 0, value: '', visualCount: 0, hovering: false, frontPid: 42, frontWindowId: 99 } + const application = { count: 0, value: '', visualCount: 0, floatingCount: 0, floating: false, hovering: false, frontPid: 42, frontWindowId: 99 } const captureBroker = { pendingCapture: false } let started = false let hadClient = false @@ -113,6 +113,7 @@ function createApplicationState(socket, record, application, captureBroker, conn const bounds = { x: 40, y: 60, width: 320, height: 200 } const window = { windowId: 7, pid: 9, appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } const axlessWindow = { ...window, windowId: 8, title: 'AXless canvas' } + const floatingWindow = { ...window, windowId: 10, title: 'Floating panel', bounds: { x: 100, y: 120, width: 240, height: 140 } } const transformedWindow = { ...window, windowId: 9, title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } const screenshotConfig = new URL('./fixture-screenshot.json', import.meta.url) const customScreenshot = existsSync(screenshotConfig) ? JSON.parse(readFileSync(screenshotConfig, 'utf8')) : undefined @@ -159,7 +160,7 @@ function createApplicationState(socket, record, application, captureBroker, conn before, after, activationRequested, raiseRequested: false, } } } - if (method === 'listWindows') return [window, axlessWindow] + if (method === 'listWindows') return [window, axlessWindow, ...application.floating ? [floatingWindow] : []] if (method === 'getState') { snapshots.delete(params.windowId ?? null) if (observationChanged) { @@ -170,6 +171,9 @@ function createApplicationState(socket, record, application, captureBroker, conn const axless = params.windowId === 8 const snapshotId = `${scope}-snapshot-${generation}` snapshots.set(params.windowId ?? null, { snapshotId, windowId: params.windowId ?? null, axless }) + if (params.windowId === 10 && application.floating) return { appHandle: app.appHandle, pid: 9, windowId: 10, + snapshotId, focusedWindowId: 7, tree: `AX scope=window offsets=UTF-16\n- AXWindow "Floating panel"\n - [0] AXButton "Increment floating panel"\n - AXStaticText "Floating count: ${application.floatingCount}"`, + elements: [], windows: [window, axlessWindow, floatingWindow], truncated: false } if (axless) return { appHandle: app.appHandle, pid: 9, windowId: 8, snapshotId, tree: '', elements: [], windows: [axlessWindow], truncated: false } return { appHandle: app.appHandle, pid: 9, windowId: params.windowId ?? null, @@ -193,7 +197,8 @@ function createApplicationState(socket, record, application, captureBroker, conn ? { pixelWidth: customScreenshot.pixelWidth, pixelHeight: customScreenshot.pixelHeight, bounds: customScreenshot.bounds, windowId: params.windowId, mimeType: 'image/png', coordinateSpace: 'window-points', data: readFileSync(new URL(customScreenshot.file, import.meta.url)).toString('base64') } - : { windowId: params.windowId, mimeType: 'image/png', data: png, pixelWidth: 1, pixelHeight: 1, bounds, coordinateSpace: 'window-points' } + : { windowId: params.windowId, mimeType: 'image/png', data: png, pixelWidth: 1, pixelHeight: 1, + bounds: params.windowId === 10 ? floatingWindow.bounds : bounds, coordinateSpace: 'window-points' } if (method === 'click' || method === 'setValue' || method === 'hover') { const observed = params.snapshotId === undefined && params.elementIndex === undefined ? snapshots.get(params.windowId) ?? snapshots.get(null) @@ -202,6 +207,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', 'Snapshot belongs to another window') if (observed.axless && params.elementIndex !== undefined) refuse('INVALID_ARGUMENT', 'Element index is absent from the selected snapshot') if (method === 'hover') application.hovering = params.elementIndex === 0 || (params.x >= 20 && params.x <= 40) + else if (method === 'click' && params.windowId === 10) application.floatingCount++ else if (method === 'click' && params.windowId === 8) application.visualCount++ else if (method === 'click') application.count++ else application.value = params.value @@ -209,6 +215,7 @@ function createApplicationState(socket, record, application, captureBroker, conn return { dispatched: true, verified: false, ...method === 'hover' ? { hoverRoute: 'accessibility', systemPointerMoved: false } : {} } } if (method === 'pressKey' && params.key === 'Return') observationChanged = true + if (method === 'pressKey' && params.key === 'F8') application.floating = true // Fixture-only keys simulate a pending system callback and its eventual completion. if (method === 'pressKey' && params.key === 'F11') captureBroker.pendingCapture = true if (method === 'pressKey' && params.key === 'F10') captureBroker.pendingCapture = false From fdb975ba9b413f9f8e0cc55e6aa6d48eefdf243f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:36:10 +0800 Subject: [PATCH 002/438] test(cua): record floating panel workflow and destroy closed fixture window --- .../native/tests/FloatingWindowFixture.swift | 19 +- packages/experimental/cua/tests/api.spec.ts | 2 + snapshots/session/cua-native/session.v4.jsonl | 167 +++++++++++------- .../cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- 5 files changed, 120 insertions(+), 72 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift index a95a8dfb94..6348ab27fe 100644 --- a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -15,6 +15,8 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { var count = 0 var resized = false var closed = false + var panelSize: [CGFloat] = [] + var buttonPoint: [CGFloat] = [] var controls: [DispatchSourceSignal] = [] var observer: Timer? @@ -45,7 +47,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { let control = DispatchSource.makeSignalSource(signal: number, queue: .main) control.setEventHandler { [weak self] in guard let self else { return } - if number == SIGUSR1 { self.panel.close(); self.closed = true } + if number == SIGUSR1 { + self.panel.close() + // Releasing the retained panel destroys its WindowServer window instead of only hiding it. + self.panel = nil + self.button = nil + self.closed = true + } else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } self.persist() } @@ -62,13 +70,16 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { func persist() { let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } - let rect = button.convert(button.bounds, to: nil) + if let panel, let button { + let rect = button.convert(button.bounds, to: nil) + panelSize = [panel.frame.width, panel.frame.height] + buttonPoint = [rect.midX, panel.frame.height - rect.midY] + } let data = try! JSONSerialization.data(withJSONObject: [ "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, "panelLayer": row?[kCGWindowLayer as String] ?? -1, "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, - "panelSize": [panel.frame.width, panel.frame.height], - "buttonPoint": [rect.midX, panel.frame.height - rect.midY], + "panelSize": panelSize, "buttonPoint": buttonPoint, "count": count, "resized": resized, "closed": closed, ]) try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index 35d44a35e8..eeed87c861 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -340,6 +340,8 @@ describe('application and window observations', () => { const windows = [windowInfo(23), { ...windowInfo(24), title: 'Floating panel' }] f.setWindowRecords(windows) expect(await app.getWindows({ emit: false })).toEqual(windows) + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: 23, windows })) + await app.getAXState() f.dispatch.mockResolvedValueOnce(state({ windowId: 24, focusedWindowId: 23, windows })) const panel = await app.getWindow(24) await panel.getScreenshot() diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index e7587237ab..d47ce2e40e 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -12,281 +12,316 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947688973,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947688973,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564511530,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564511530,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"platform\":\"macos\",\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"methods\":[\"getCapabilities\",\"listApps\",\"getApp\",\"activate\",\"show\",\"listWindows\",\"getState\",\"hover\",\"click\",\"setValue\",\"typeText\",\"paste\",\"pressKey\",\"scroll\",\"drag\",\"screenshot\"],\"coordinateSpace\":\"screenshot-pixels\",\"browser\":false}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689573,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689573,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512128,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512128,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689596,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689596,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512153,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512153,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512153,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512154,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689615,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689615,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512173,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512173,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-2"},"toolCallId":"cua-native-2","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689657,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689657,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689683,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689683,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":7,"callId":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-4"},"toolCallId":"cua-native-4","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689706,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689706,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512265,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512266,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":8,"callId":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689729,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689729,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512288,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512288,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":9,"callId":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-6"},"toolCallId":"cua-native-6","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:21}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689792,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689792,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512368,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512368,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":10,"callId":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689834,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689834,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512388,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512388,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":11,"callId":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} {"type":"step/start","data":{"turn":1,"step":12}} -{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689861,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689861,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":12,"callId":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-9"},"toolCallId":"cua-native-9","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":8,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:27}}"}},"sourceEventSeqs":[69],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":12}} {"type":"step/start","data":{"turn":1,"step":13}} -{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689896,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689896,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512445,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512445,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":13,"callId":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-10"},"toolCallId":"cua-native-10","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:29}}"}},"sourceEventSeqs":[74],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":13}} {"type":"step/start","data":{"turn":1,"step":14}} -{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689918,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689918,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":14,"callId":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":14}} {"type":"step/start","data":{"turn":1,"step":15}} -{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689940,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689940,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512484,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512484,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":15,"callId":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":15,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-show"},"toolCallId":"cua-native-show","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"windowId\":7,\"foregroundChanged\":false}"}],"isError":false,"id":"{{message:33}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":15}} {"type":"step/start","data":{"turn":1,"step":16}} -{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689961,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689961,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512511,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512511,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":16,"callId":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":16,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-first"},"toolCallId":"cua-native-activate-first","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-first\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:35}}"}},"sourceEventSeqs":[89],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":16}} {"type":"step/start","data":{"turn":1,"step":17}} -{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689983,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689983,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":17,"callId":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":17,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-repeat"},"toolCallId":"cua-native-activate-repeat","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-repeat\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":false,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:37}}"}},"sourceEventSeqs":[94],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":17}} {"type":"step/start","data":{"turn":1,"step":18}} -{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690002,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690002,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512552,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512552,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":18,"callId":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}} {"type":"tool/result","data":{"turn":1,"step":18,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-transition"},"toolCallId":"cua-native-transition","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:39}}"}},"sourceEventSeqs":[99],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":18}} {"type":"step/start","data":{"turn":1,"step":19}} -{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690019,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690019,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512570,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512570,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAXState"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} -{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690040,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690040,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} -{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690064,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690064,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512616,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512616,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":21,"callId":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":21,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-other-window"},"toolCallId":"cua-native-other-window","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:45}}"}},"sourceEventSeqs":[114],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":21}} {"type":"step/start","data":{"turn":1,"step":22}} -{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690087,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690087,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":22,"callId":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":22}} {"type":"step/start","data":{"turn":1,"step":23}} -{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690111,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690111,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512654,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512654,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":23,"callId":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":23,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-click"},"toolCallId":"cua-native-fresh-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:49}}"}},"sourceEventSeqs":[124],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":23}} {"type":"step/start","data":{"turn":1,"step":24}} -{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690141,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690141,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512675,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512675,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":24,"callId":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":24}} {"type":"step/start","data":{"turn":1,"step":25}} -{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690162,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690162,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":25,"callId":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":25}} {"type":"step/start","data":{"turn":1,"step":26}} -{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690186,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690186,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512716,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512716,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} -{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} -{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690248,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690248,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512755,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512755,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} -{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690267,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690267,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512781,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512781,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} -{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690294,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690294,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":30,"callId":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":30,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-ax"},"toolCallId":"cua-native-geometry-ax","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:63}}"}},"sourceEventSeqs":[159],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":30}} {"type":"step/start","data":{"turn":1,"step":31}} -{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":31,"callId":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":31}} {"type":"step/start","data":{"turn":1,"step":32}} -{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690340,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690340,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512855,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512855,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":32,"callId":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}} {"type":"tool/result","data":{"turn":1,"step":32,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-arm"},"toolCallId":"cua-capture-busy-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:67}}"}},"sourceEventSeqs":[169],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":32}} {"type":"step/start","data":{"turn":1,"step":33}} -{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690365,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690365,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512882,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512882,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} -{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690394,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690394,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":34,"callId":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":34}} {"type":"step/start","data":{"turn":1,"step":35}} -{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690414,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690414,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512942,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512942,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":35,"callId":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}} {"type":"tool/result","data":{"turn":1,"step":35,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-callback"},"toolCallId":"cua-capture-callback","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:73}}"}},"sourceEventSeqs":[184],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":35}} {"type":"step/start","data":{"turn":1,"step":36}} -{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512970,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512970,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":36,"callId":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":36,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-recovered"},"toolCallId":"cua-capture-recovered","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:75}}"}},"sourceEventSeqs":[189],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":36}} {"type":"step/start","data":{"turn":1,"step":37}} -{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690466,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690466,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513023,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513024,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":37,"callId":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":37,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-enter"},"toolCallId":"cua-hover-enter","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:77}}"}},"sourceEventSeqs":[194],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":37}} {"type":"step/start","data":{"turn":1,"step":38}} -{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690495,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690495,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513075,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513075,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":38,"callId":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":38}} {"type":"step/start","data":{"turn":1,"step":39}} -{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690517,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690517,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513125,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513125,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":39,"callId":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":39,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-capture"},"toolCallId":"cua-hover-capture","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:81}}"}},"sourceEventSeqs":[204],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":39}} {"type":"step/start","data":{"turn":1,"step":40}} -{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690565,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690565,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513163,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513163,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":40,"callId":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":40,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-popup"},"toolCallId":"cua-hover-popup","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:83}}"}},"sourceEventSeqs":[209],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":40}} {"type":"step/start","data":{"turn":1,"step":41}} -{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513183,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513183,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":41,"callId":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":41,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-click"},"toolCallId":"cua-hover-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:85}}"}},"sourceEventSeqs":[214],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":41}} {"type":"step/start","data":{"turn":1,"step":42}} -{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690613,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690613,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513205,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513205,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":42,"callId":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":42,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-exit"},"toolCallId":"cua-hover-exit","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:87}}"}},"sourceEventSeqs":[219],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":42}} {"type":"step/start","data":{"turn":1,"step":43}} -{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690633,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690633,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513224,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513224,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} -{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690653,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690653,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513244,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513244,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} {"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":44}} {"type":"step/start","data":{"turn":1,"step":45}} -{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690672,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690672,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513264,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513264,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":45}} {"type":"step/start","data":{"turn":1,"step":46}} -{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513290,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513290,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":46}} {"type":"step/start","data":{"turn":1,"step":47}} -{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690714,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690714,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":47}} {"type":"step/start","data":{"turn":1,"step":48}} -{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513332,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513332,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} -{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690757,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690757,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513353,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513353,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":49}} {"type":"step/start","data":{"turn":1,"step":50}} -{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690778,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690778,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513374,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513374,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":50}} {"type":"step/start","data":{"turn":1,"step":51}} -{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690801,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690801,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-open"},"toolCallId":"cua-floating-open","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":51}} {"type":"step/start","data":{"turn":1,"step":52}} -{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690821,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690821,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513415,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513415,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":52}} {"type":"step/start","data":{"turn":1,"step":53}} -{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690852,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690852,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":53}} {"type":"step/start","data":{"turn":1,"step":54}} -{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691022,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513453,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513453,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-screenshot"},"toolCallId":"cua-floating-screenshot","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":10,\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":54}} {"type":"step/start","data":{"turn":1,"step":55}} -{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691192,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691192,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513493,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513493,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} -{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691212,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1791947691212,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513513,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513513,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} +{"type":"step/start","data":{"turn":1,"step":57}} +{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":57}} +{"type":"step/start","data":{"turn":1,"step":58}} +{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513564,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513564,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":58}} +{"type":"step/start","data":{"turn":1,"step":59}} +{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513582,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513582,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":59}} +{"type":"step/start","data":{"turn":1,"step":60}} +{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513611,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513611,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":60}} +{"type":"step/start","data":{"turn":1,"step":61}} +{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513776,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513776,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":61}} +{"type":"step/start","data":{"turn":1,"step":62}} +{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513949,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513949,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":62}} +{"type":"step/start","data":{"turn":1,"step":63}} +{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513967,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792564513967,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":63}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index d51551ecbe..5fd3c14a9d 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 15b7b997fb..af955c1c45 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. From 1e183c1fcd7f45386c39b952fa1c0137a680603e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 21 Oct 2026 14:41:28 +0800 Subject: [PATCH 003/438] test(cua): close floating fixture through its main window --- .../native/tests/FloatingWindowFixture.swift | 41 +++++++++++-------- .../native/tests/floating_windows_e2e.py | 5 ++- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift index 6348ab27fe..46e524886f 100644 --- a/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift +++ b/packages/experimental/cua-macos/native/tests/FloatingWindowFixture.swift @@ -11,13 +11,14 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { var main: NSWindow! var panel: FloatingPanel! var button: NSButton! + var closeButton: NSButton! var panelID = 0 var count = 0 var resized = false var closed = false var panelSize: [CGFloat] = [] var buttonPoint: [CGFloat] = [] - var controls: [DispatchSourceSignal] = [] + var resizeControl: DispatchSourceSignal? var observer: Timer? init(statePath: String) { self.statePath = statePath } @@ -25,6 +26,9 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { main = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 420, height: 300), styleMask: [.titled, .closable], backing: .buffered, defer: false) main.title = "Floating fixture main" + closeButton = NSButton(title: "Close panel", target: self, action: #selector(closePanel)) + closeButton.frame = NSRect(x: 280, y: 30, width: 120, height: 35) + main.contentView!.addSubview(closeButton) panel = FloatingPanel(contentRect: NSRect(x: 220, y: 250, width: 240, height: 140), styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false) panel.title = "Floating fixture panel" @@ -42,24 +46,16 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { NSApplication.shared.activate(ignoringOtherApps: true) panel.orderFrontRegardless() panelID = panel.windowNumber - for number in [SIGUSR1, SIGUSR2] { - signal(number, SIG_IGN) - let control = DispatchSource.makeSignalSource(signal: number, queue: .main) - control.setEventHandler { [weak self] in - guard let self else { return } - if number == SIGUSR1 { - self.panel.close() - // Releasing the retained panel destroys its WindowServer window instead of only hiding it. - self.panel = nil - self.button = nil - self.closed = true - } - else { self.panel.setContentSize(NSSize(width: 280, height: 180)); self.resized = true } - self.persist() - } - control.resume() - controls.append(control) + signal(SIGUSR2, SIG_IGN) + let control = DispatchSource.makeSignalSource(signal: SIGUSR2, queue: .main) + control.setEventHandler { [weak self] in + guard let self else { return } + self.panel.setContentSize(NSSize(width: 280, height: 180)) + self.resized = true + self.persist() } + control.resume() + resizeControl = control // WindowServer visibility and frame updates settle after AppKit requests return. observer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in self?.persist() } persist() @@ -67,6 +63,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { fflush(stdout) } @objc func increment() { count += 1; persist() } + @objc func closePanel() { + panel.close() + panel = nil + button = nil + closed = true + persist() + } func persist() { let rows = CGWindowListCopyWindowInfo(.excludeDesktopElements, kCGNullWindowID) as? [[String: Any]] ?? [] let row = rows.first { ($0[kCGWindowNumber as String] as? NSNumber)?.intValue == panelID } @@ -75,11 +78,13 @@ final class FloatingWindowFixture: NSObject, NSApplicationDelegate { panelSize = [panel.frame.width, panel.frame.height] buttonPoint = [rect.midX, panel.frame.height - rect.midY] } + let closeRect = closeButton.convert(closeButton.bounds, to: nil) let data = try! JSONSerialization.data(withJSONObject: [ "pid": getpid(), "mainWindowId": main.windowNumber, "panelWindowId": panelID, "panelLayer": row?[kCGWindowLayer as String] ?? -1, "panelOnScreen": row?[kCGWindowIsOnscreen as String] ?? false, "panelSize": panelSize, "buttonPoint": buttonPoint, + "closePoint": [closeRect.midX, main.frame.height - closeRect.midY], "count": count, "resized": resized, "closed": closed, ]) try! data.write(to: URL(fileURLWithPath: statePath), options: .atomic) diff --git a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py index a3988509b6..62aa14fa53 100644 --- a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -95,7 +95,10 @@ def main(): target = {**target, 'snapshotId': fresh['snapshotId'], 'x': x, 'y': y} helper.call('click', target) wait_state(lambda value: value['count'] == 5) - os.kill(fixture.pid, signal.SIGUSR1) + # AppKit's current mouse event retains its target window. Closing from the main + # window replaces that event so the floating window can actually be destroyed. + close_x, close_y = actual['closePoint'] + helper.call('click', {**owner, 'windowId': actual['mainWindowId'], 'x': close_x, 'y': close_y}) wait_state(lambda value: value['closed'] and not value['panelOnScreen']) deadline = time.monotonic() + 10 while panel_id in [window['windowId'] for window in helper.call('listWindows', owner)]: From 1f4cfad6562914cbdb11107bc8f7e8174a8a9906 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Wed, 4 Nov 2026 20:48:40 +0800 Subject: [PATCH 004/438] fix(agent): close input admission and drain work after cancellation failures --- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- docs/event-producer-consumer.md | 22 +- docs/event-producer-consumer.zh.md | 22 +- docs/subsystems/core.md | 7 +- docs/subsystems/core.zh.md | 7 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 24 +- packages/core/agent-loop/src/index.ts | 9 +- packages/core/agent-loop/tests/cancel.spec.ts | 12 +- .../tests/fixtures/serial-created.mjs | 37 +- .../agent-loop/tests/input-lifecycle.spec.ts | 151 ++++++ .../agent-loop/tests/request-freeze.spec.ts | 6 +- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/closed-error.ts | 15 + packages/core/agent/src/index.ts | 1 + packages/core/agent/src/runtime-types.ts | 7 +- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 4 +- scripts/smoke-python-runtime.py | 1 + .../advanced/result.json | 460 ++++++++++++++++-- .../advanced/session.1.v4.jsonl | 24 +- .../advanced/session.2.v4.jsonl | 24 +- snapshots/sdk/serial-created/session.v4.jsonl | 21 +- 31 files changed, 762 insertions(+), 124 deletions(-) create mode 100644 packages/core/agent-loop/tests/input-lifecycle.spec.ts create mode 100644 packages/core/agent/src/closed-error.ts diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 19453e15a9..83a62a5480 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -21,8 +21,8 @@ en: 20ef882e44b06a10 zh: c10c3934ed5570e9 /deepseek-harness-architecture/events: - en: ddebac7cfd41ec73 - zh: 51e6d0866a9e7839 + en: 9a7297518f6b7bdf + zh: 883364ea3f1ac82b /deepseek-harness-architecture/turn-flow: en: 1a79a70b62c04cdb zh: c86d765e21430405 diff --git a/docs/architecture.md b/docs/architecture.md index 446c50e5bd..95eeab1b42 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,7 @@ Events provide extension points in three domains. Subagent Activations own runtime tree membership. -AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; unload retains resources through teardown ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). +AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown closes input admission, cancels and waits for admitted work despite queue-cleanup failures, then releases resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). [Event producers and consumers](event-producer-consumer.md). diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 275e1c863d..936a6493ff 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -76,7 +76,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 Subagent Activation 拥有运行时树成员关系。 -AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;卸载在 teardown 期间保留所需资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭先停止接收输入,在队列清理失败时仍取消并等待已接纳工作,然后释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 [事件生产者与消费者](event-producer-consumer.zh.md)。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e9172cc37..a32683e672 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 326beb8853..ff27d132ae 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,17 +14,17 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 40264ec898..7b8503cb1a 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -78,6 +78,7 @@ interface Agent { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -97,7 +98,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -112,6 +113,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -119,6 +121,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -128,6 +131,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -138,6 +142,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index ff1d3b579e..9f0bf51061 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -82,6 +82,7 @@ interface Agent { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -101,7 +102,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -116,6 +117,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -123,6 +125,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -132,6 +135,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -142,6 +146,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 08e35ca2a9..9c73797cbb 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: ec2bf804bd1a5439 zh: 316e767507e859ef /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: e2cb7b6101f20425 - zh: a056c43886207083 + en: e66e878db8193219 + zh: 11a79267958b2f51 /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: 3b48a480036bd5df zh: 28cea2036b0dccee diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 03fc5b2e16..c021ad2513 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. The caller Context owns the transaction and live handle; delegation services bind their runtime relationships during setup. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. +The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. New input is rejected when teardown begins; queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles. ### Persistence integration diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 977911bbbe..394130f0c4 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。调用方 Context 拥有事务和存活句柄;委派服务在 setup 期间绑定自己的运行时关系。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 +loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。teardown 开始后拒绝新输入;清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。 ### 持久化集成 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index c4daa50c47..c23cc401e3 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -18,7 +18,7 @@ import type { PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { LlmError, @@ -141,6 +141,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, projections: LoopProjections, lastTurn: number, + private readonly lifetimeSignal: AbortSignal, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) @@ -168,6 +169,7 @@ export class ReactLoopAgent implements Agent { } send(message: UserMessage, target: InboxTarget, wakeup: boolean): void { + this.assertOpen() // Waking input cannot join an aborted activity, so it starts the next turn. // Captured before the insertion so a reentrant cancel from a splice observer cannot reclassify it. const wakingAfterAbort = wakeup && this.phase.kind !== 'idle' && this.phase.abort.signal.aborted @@ -189,14 +191,19 @@ export class ReactLoopAgent implements Agent { } cancel(cause: AgentCancelCause, options: CancelOptions = {}): void { - if (!options.keepInbox) { - this.inbox.clear() - if (this.phase.kind !== 'idle') this.phase.wakeRequested = false + try { + if (!options.keepInbox) this.inbox.clear() + } finally { + // Queue persistence must not prevent cancellation of admitted work. + if (this.phase.kind !== 'idle') { + if (!options.keepInbox) this.phase.wakeRequested = false + this.phase.abort.abort(cause) + } } - if (this.phase.kind !== 'idle') this.phase.abort.abort(cause) } runMaintenance(job: (signal: AbortSignal) => Promise): Promise { + this.assertOpen() if (this.phase.kind !== 'idle') throw new Error(`agent "${this.id}" already has active work`) const done = Promise.withResolvers() const maintenance: Phase = { @@ -228,6 +235,7 @@ export class ReactLoopAgent implements Agent { * the inbox insertion so a reentrant cancel cannot reclassify it. */ private wakeDriver(wakeAfterAbort = false): void { + if (this.lifetimeSignal.aborted) return if (this.phase.kind !== 'idle') { // Maintenance and aborted drivers cannot deliver the wake: latch it for // replay at convergence. Live drivers claim queued work themselves; @@ -257,6 +265,12 @@ export class ReactLoopAgent implements Agent { } while (activity !== this.activityDone) } + private assertOpen(): void { + if (this.lifetimeSignal.aborted) { + throw new AgentClosedError(this.id, { cause: this.lifetimeSignal.reason }) + } + } + /** Report one failure at its live boundary, then preserve it for driver containment. */ private throwError(error: unknown): never { const turn = this.phase.kind === 'running' ? this.phase.turn : this.phase.lastTurn diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 22b3192588..a0b02d4eee 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -514,7 +514,12 @@ export class AgentLoop extends Service implements AgentFactory { if (machine === undefined) await machineReady.promise /* v8 ignore next -- setup failure untracks this disposer before resolving without a machine. */ if (machine !== undefined) { - machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + try { + machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + } catch (error: unknown) { + failures.push(error) + } + // A failed queue write must not release resources underneath work. await machine.whenIdle() } } catch (error: unknown) { @@ -573,6 +578,7 @@ export class AgentLoop extends Service implements AgentFactory { loopCtx, id, agentOptions, session, projections, lastTurn, + abort.signal, ) machineReady.resolve() // Adopt the scope on its original fiber so it cannot unload before teardown. @@ -636,6 +642,7 @@ export class AgentLoop extends Service implements AgentFactory { await loopCtx.agents.announce(agent, source, abort.signal) assertLive() ready = true + callerSignal?.removeEventListener('abort', onCallerAbort) return { agent, dispose } } catch (error: unknown) { // Failed initialization must not release queued input into a new turn. diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index c702b64e89..2ca5eb0299 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -16,7 +16,7 @@ import SessionStore, { Session, SessionId, SessionLogOffset, TurnEndReason } fro import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import AgentRegistry, { type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { AgentClosedError, type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts' @@ -319,14 +319,12 @@ describe('Agent.cancel()', () => { }) const agent = handle.agent + const streaming = Promise.withResolvers() + ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streaming.resolve(undefined) }) send(agent, 'active') - await new Promise(resolve => setTimeout(resolve, 30)) - - // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the - // abort-to-idle window must not latch, so `whenIdle()` does not wait on - // a model turn over the session being torn down. + await streaming.promise const disposal = handle.dispose() - setTimeout(() => { send(agent, 'late wake') }, 10) + expect(() =>{ send(agent, 'late wake') }).toThrow(AgentClosedError) await disposal expect(adapter.requests).toHaveLength(1) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 8cc624caae..138fd7d4b6 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,7 +6,42 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx) { +export function apply(ctx, config = {}) { + const checkedCancellation = new WeakSet() + ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { + if (checkedCancellation.has(agent) + || (config.checkRootCancellation === false && agent.session.header.origin !== 'subagent')) return next() + checkedCancellation.add(agent) + const pending = { + id: randomUUID(), role: 'user', + content: [{ type: 'text', text: 'Cancellation checkpoint probe.' }], + source: { kind: `plugin:${name}` }, + } + agent.inject(pending) + const failure = new Error('fixture queue-clear refusal') + const stopRejecting = ctx.on('internal/dispatch', (_mode, eventName, args) => { + if (eventName !== 'session/event') return + const [session, event] = args + if (session === agent.session && event.type === 'agent/inbox/spliced' + && event.data.outcome === 'canceled' && (event.data.removedCount ?? 0) > 0) throw failure + }) + try { + try { agent.cancel({ kind: 'user' }) } + catch (error) { if (error !== failure) throw error } + } finally { + stopRejecting() + } + if (!signal.aborted) throw new Error('queue-clear failure prevented cancellation') + agent.inbox.remove(pending.id) + for (const message of messages) { + const ordinary = message.source.kind === 'user' + const restored = message.source.kind === `plugin:${name}` + ? { ...message, content: [{ type: 'text', text: message.content[0].text + ' Queue-clear failures still cancel active work.' }] } + : message + agent.send(restored, ordinary ? 'next-turn' : 'next-step', ordinary) + } + return next() + }) const ready = new WeakSet() ctx.on('agent/created', async ({ agent }) => { await setImmediate() diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts new file mode 100644 index 0000000000..2e87517e1f --- /dev/null +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -0,0 +1,151 @@ +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { afterEach, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry, { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as CheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import { MockAdapter, textResponse } from './mock-adapter.ts' + +const fixtures: { ctx: Context; agent?: Agent; root: string }[] = [] +afterEach(async () => { + for (const fixture of fixtures.splice(0)) { + try { + fixture.agent?.cancel({ kind: 'disposed' }, { keepInbox: true }) + await fixture.agent?.whenIdle() + await fixture.ctx.fiber.dispose() + } finally { + await rm(fixture.root, { recursive: true, force: true }) + } + } +}) + +const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } }) + +async function harness() { + const ctx = new Context() + const root = await mkdtemp(join(tmpdir(), 'dsh-input-atomicity-')) + const fixture: { ctx: Context; agent?: Agent; root: string } = { ctx, root } + fixtures.push(fixture) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(NativeToolExecutor) + await ctx.plugin(AgentRegistry) + await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' }) + await ctx.plugin(CheckpointPolicy) + await ctx.plugin(AgentLoop, { agents: [] }) + const adapter = new MockAdapter(Array.from({ length: 5 }, () => textResponse('ok'))) + ctx.llm.registerAdapter(['mock'], adapter) + const handle = await ctx.agents.create({ sessionId: SessionId('diagnostic'), agentOptions: { provider: 'mock', model: 'mock' } }) + fixture.agent = handle.agent + return { ctx, root, adapter, handle, agent: handle.agent } +} + + +it('cancellation still aborts the running request when queue clearing fails', async () => { + const { ctx, agent } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() }) + let stopRejecting = () => {} + try { + agent.followup(input('running')) + const signal = await entered.promise + agent.inject(input('steering')) + const queued = input('queued') + agent.followup(queued) + stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn' + && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure') + }) + expect(() =>{ agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') + expect(signal.aborted).toBe(true) + } finally { + stopRejecting() + hold() + agent.cancel({ kind: 'disposed' }, { keepInbox: true }) + release.resolve(undefined) + await agent.whenIdle() + } +}) + + +it('an Agent still in the registry rejects new input while its owner is closing', async () => { + const { ctx, agent, handle } = await harness() + const release = Promise.withResolvers() + const aborted = Promise.withResolvers() + const work = agent.runMaintenance(async (signal) => { + signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) + await release.promise + }) + const closing = handle.dispose() + try { + await aborted.promise + expect(ctx.agents.get(agent.id)).toBe(agent) + const message = input('during closing') + for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {})]) { + expect(submit).toThrow(AgentClosedError) + } + const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) + expect(pending).toBe(false) + } finally { + release.resolve(undefined) + await work + await closing + } +}) + + + +it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { + const { ctx, agent, handle } = await harness() + const release = Promise.withResolvers() + const waiting = Promise.withResolvers<'waiting'>() + const disposed = Promise.withResolvers<'disposed'>() + let scopeDisposed = false + agent.ctx.effect(() => () => { scopeDisposed = true; disposed.resolve('disposed') }) + const work = agent.runMaintenance(async () => { + await release.promise + agent.session.append('request/context', { provider: 'mock', model: 'mock' }) + }) + agent.inject(input('pending')) + const stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) { + throw new Error('queue clear failed') + } + }) + const whenIdle = agent.whenIdle.bind(agent) + const spy = vi.spyOn(agent, 'whenIdle').mockImplementation(() => { waiting.resolve('waiting'); return whenIdle() }) + const closing = handle.dispose().then(() => undefined, (error: unknown) => error) + try { + expect(await Promise.race([waiting.promise, disposed.promise])).toBe('waiting') + expect(scopeDisposed).toBe(false) + expect(ctx.sessions.get(agent.id)).toBe(agent.session) + release.resolve(undefined) + await work + expect(await closing).toEqual(new Error('queue clear failed')) + expect(scopeDisposed).toBe(true) + expect(agent.session.snapshotEvents().at(-1)?.type).toBe('request/context') + } finally { + stopRejecting() + spy.mockRestore() + release.resolve(undefined) + await work + await closing + } +}) diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index 8ed1c4d138..f4ef29eea3 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -79,7 +79,8 @@ describe('loop-owned request freezing', () => { const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition) const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition) const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { agent.cancel({ kind: 'disposed' }) await agent.whenIdle() @@ -129,7 +130,8 @@ describe('loop-owned request freezing', () => { expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1) expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1) const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { resumed.cancel({ kind: 'disposed' }) await resumed.whenIdle() diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 358d56ae02..df3e29c8a9 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -24,8 +24,8 @@ en: 85b0ff72a187110f zh: 3f61c1568d27b8bc /deepseek-ai-dsh-agent/use-this-package/drive-an-agent-s-conversation: - en: 71e258897e2e7d73 - zh: abf0991012faa17e + en: ff2b530bb20bcfe2 + zh: 4f9024c4881a4ba5 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: en: 2594a1e02adea801 zh: cae8860369728efb diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index c84ac3d237..9772578fcc 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -55,7 +55,7 @@ For scoped switch notices, call `installModelSelection(agentCtx)` from `dsh-agen ### Drive an agent's conversation -The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. +The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. Disposal rejects new input and maintenance with `AgentClosedError` before mutation. A queue-write failure during cancellation still aborts active work and propagates to the caller. ```text handle.agent.followup({ diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index a2fae55b56..b5b2af52d4 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -55,7 +55,7 @@ await handle.dispose() // stops the loop, unregisters, removes the session, un ### 驱动 agent 的对话 -句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。 +句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。释放开始后,新输入和维护任务会在修改状态前抛出 `AgentClosedError`。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。 ```text handle.agent.followup({ diff --git a/packages/core/agent/src/closed-error.ts b/packages/core/agent/src/closed-error.ts new file mode 100644 index 0000000000..abcb335320 --- /dev/null +++ b/packages/core/agent/src/closed-error.ts @@ -0,0 +1,15 @@ +/** Rejection of new work after an Agent starts closing. @module @deepseek-ai/dsh-agent/closed-error */ + +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** An Agent has stopped accepting new input and maintenance work. */ +export class AgentClosedError extends Error { + /** + * @param agentId - closing Agent identity. + * @param options - original lifecycle cancellation, when available. + */ + constructor(readonly agentId: SessionId, options?: ErrorOptions) { + super(`agent "${agentId}" is closing`, options) + this.name = 'AgentClosedError' + } +} diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 374be30180..35fbdd6b1d 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -19,6 +19,7 @@ import type { AgentOptions, SessionStartSource } from './runtime-types.ts' import { turnBoundaryProjectionDefinition } from './projection.ts' export * from './runtime-types.ts' +export { AgentClosedError } from './closed-error.ts' export * from './types.ts' export { AgentModel, modelSelectionProjectionDefinition, installModelSelection } from './model-selection.ts' export type { ModelSelectionProjectionState } from './model-selection.ts' diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 2b1698e39c..aa5efe6d0a 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -206,6 +206,7 @@ declare module './types.ts' { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -225,7 +226,7 @@ declare module './types.ts' { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -240,6 +241,7 @@ declare module './types.ts' { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -247,6 +249,7 @@ declare module './types.ts' { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -256,6 +259,7 @@ declare module './types.ts' { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -266,6 +270,7 @@ declare module './types.ts' { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4ff564cb25..3b160b2782 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 9543250098033347 - zh: 3721af3e31409a32 + en: 152d969b7214b4cd + zh: 2ba2a43599b009d9 /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index b8fd869989..c3da369bed 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. An Agent that has begun closing ends the local settlement observer rather than retrying maintenance admission. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e0f8f35bda..ed72da6c0a 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,本地结算观察器会结束,不再重试维护准入。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index db6f04b019..e1b0bc6e68 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -11,6 +11,7 @@ import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -991,7 +992,8 @@ export class SubagentManager { done = this.close(activation, () => this.finishDisposal(activation, false)) return Promise.resolve() }) - } catch (_error: unknown) { + } catch (error: unknown) { + if (error instanceof AgentClosedError) return Promise.resolve('closed') // Another activity already owns the Agent's idle phase. return Promise.resolve('retry') } diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 311fa10ff6..49dca3772a 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -1787,6 +1787,7 @@ def smoke_sdk_snapshot_mode( {"insert": [{ "id": "serial-created-fixture", "name": str(Path(__file__).resolve().parents[1] / "packages/core/agent-loop/tests/fixtures/serial-created.mjs"), + "config": {"checkRootCancellation": False}, }]}, ]) with DeepSeekHarness( diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 47c767ccd9..68401cbcf2 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -2880,11 +2880,205 @@ "payload": { "sessionId": "{{child-1}}", "event": { - "type": "step/start", + "type": "agent/inbox/spliced", "seq": 9, "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Cancellation checkpoint probe." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 10, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [], + "outcome": "canceled" + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 11, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 12, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "inserted": [ + { + "content": [ + { + "type": "text", + "text": "Reply with exactly DIRECT_CHILD_OK and nothing else." + }, + { + "type": "text", + "text": "Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message." + } + ], + "source": { + "kind": "user" + }, + "role": "user", + "id": "{{messageId}}" + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "turn/end", + "seq": 13, + "time": 0, "data": { "turn": 1, + "reason": { + "kind": "aborted", + "reason": { + "kind": "user" + } + } + } + } + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-1}}", + "status": "idle" + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-1}}", + "status": "running" + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "turn/start", + "seq": 14, + "time": 0, + "data": { + "turn": 2 + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 15, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 16, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "step/start", + "seq": 17, + "time": 0, + "data": { + "turn": 2, "step": 1 } } @@ -2896,10 +3090,10 @@ "sessionId": "{{child-1}}", "event": { "type": "system/message", - "seq": 10, + "seq": 18, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "system", @@ -2925,7 +3119,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 11, + "seq": 19, "time": 0, "data": { "id": "{{messageId}}", @@ -2933,7 +3127,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed." + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." } ], "source": { @@ -2950,7 +3144,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 12, + "seq": 20, "time": 0, "data": { "content": [ @@ -2979,7 +3173,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 13, + "seq": 21, "time": 0, "data": { "content": [ @@ -3027,7 +3221,7 @@ "sessionId": "{{child-1}}", "event": { "type": "request/header", - "seq": 14, + "seq": 22, "time": 0, "data": { "header": { @@ -3063,7 +3257,7 @@ "sessionId": "{{child-1}}", "event": { "type": "request/context", - "seq": 15, + "seq": 23, "time": 0, "data": { "provider": "deepseek-official", @@ -3079,12 +3273,12 @@ "sessionId": "{{child-1}}", "event": { "type": "session/title", - "seq": 16, + "seq": 24, "time": 0, "data": { "title": "Reply with exactly DIRECT_CHILD_OK and", "messageSeqs": [ - 12 + 20 ], "source": { "kind": "fallback" @@ -3099,12 +3293,12 @@ "sessionId": "{{child-1}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 17, + "seq": 25, "time": 0, "data": { "sessionId": "{{child-1}}", "sessionFormatVersion": 4, - "throughSeq": 16 + "throughSeq": 24 } } } @@ -3115,10 +3309,10 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/message", - "seq": 18, + "seq": 26, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "assistant", @@ -3229,10 +3423,10 @@ "sessionId": "{{child-1}}", "event": { "type": "step/end", - "seq": 19, + "seq": 27, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1 } } @@ -3244,10 +3438,10 @@ "sessionId": "{{child-1}}", "event": { "type": "turn/end", - "seq": 20, + "seq": 28, "time": 0, "data": { - "turn": 1, + "turn": 2, "reason": { "kind": "completed" } @@ -3712,11 +3906,201 @@ "payload": { "sessionId": "{{child-2}}", "event": { - "type": "step/start", + "type": "agent/inbox/spliced", "seq": 9, "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Cancellation checkpoint probe." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 10, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [], + "outcome": "canceled" + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 11, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 12, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "inserted": [ + { + "content": [ + { + "type": "text", + "text": "Reply with exactly WORKFLOW_CHILD_OK and nothing else." + } + ], + "source": { + "kind": "user" + }, + "role": "user", + "id": "{{messageId}}" + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "turn/end", + "seq": 13, + "time": 0, "data": { "turn": 1, + "reason": { + "kind": "aborted", + "reason": { + "kind": "user" + } + } + } + } + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-2}}", + "status": "idle" + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-2}}", + "status": "running" + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "turn/start", + "seq": 14, + "time": 0, + "data": { + "turn": 2 + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 15, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 16, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "step/start", + "seq": 17, + "time": 0, + "data": { + "turn": 2, "step": 1 } } @@ -3728,10 +4112,10 @@ "sessionId": "{{child-2}}", "event": { "type": "system/message", - "seq": 10, + "seq": 18, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "system", @@ -3757,7 +4141,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 11, + "seq": 19, "time": 0, "data": { "id": "{{messageId}}", @@ -3765,7 +4149,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed." + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." } ], "source": { @@ -3782,7 +4166,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 12, + "seq": 20, "time": 0, "data": { "content": [ @@ -3807,7 +4191,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 13, + "seq": 21, "time": 0, "data": { "content": [ @@ -3855,7 +4239,7 @@ "sessionId": "{{child-2}}", "event": { "type": "request/header", - "seq": 14, + "seq": 22, "time": 0, "data": { "header": { @@ -3891,7 +4275,7 @@ "sessionId": "{{child-2}}", "event": { "type": "request/context", - "seq": 15, + "seq": 23, "time": 0, "data": { "provider": "deepseek-official", @@ -3907,12 +4291,12 @@ "sessionId": "{{child-2}}", "event": { "type": "session/title", - "seq": 16, + "seq": 24, "time": 0, "data": { "title": "Reply with exactly WORKFLOW_CHILD_OK and", "messageSeqs": [ - 12 + 20 ], "source": { "kind": "fallback" @@ -3927,12 +4311,12 @@ "sessionId": "{{child-2}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 17, + "seq": 25, "time": 0, "data": { "sessionId": "{{child-2}}", "sessionFormatVersion": 4, - "throughSeq": 16 + "throughSeq": 24 } } } @@ -3943,10 +4327,10 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/message", - "seq": 18, + "seq": 26, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "assistant", @@ -4057,10 +4441,10 @@ "sessionId": "{{child-2}}", "event": { "type": "step/end", - "seq": 19, + "seq": 27, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1 } } @@ -4072,10 +4456,10 @@ "sessionId": "{{child-2}}", "event": { "type": "turn/end", - "seq": 20, + "seq": 28, "time": 0, "data": { - "turn": 1, + "turn": 2, "reason": { "kind": "completed" } diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl index 46fbdba75d..e15e79f377 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl @@ -8,15 +8,23 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":16}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl index 9c7213f1fd..817f66b355 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl @@ -8,15 +8,23 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":16}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/snapshots/sdk/serial-created/session.v4.jsonl b/snapshots/sdk/serial-created/session.v4.jsonl index 93cc0348f2..5109ba2c62 100644 --- a/snapshots/sdk/serial-created/session.v4.jsonl +++ b/snapshots/sdk/serial-created/session.v4.jsonl @@ -7,15 +7,12 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} -{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} -{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[11],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":15}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1788943826008,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788943826008,"index":0,"dt":[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788943826009,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:3}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"aborted","reason":{"kind":"disposed"}}}} From 5a537ce4865b130badf25163ceda875977540345 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Wed, 4 Nov 2026 21:42:43 +0800 Subject: [PATCH 005/438] test(sdk): keep root snapshot runs active through completion --- .../tests/fixtures/serial-created.mjs | 2 +- snapshots/sdk/serial-created/session.v4.jsonl | 21 +++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 138fd7d4b6..1295611023 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -10,7 +10,7 @@ export function apply(ctx, config = {}) { const checkedCancellation = new WeakSet() ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { if (checkedCancellation.has(agent) - || (config.checkRootCancellation === false && agent.session.header.origin !== 'subagent')) return next() + || (config.checkRootCancellation !== true && agent.session.header.origin !== 'subagent')) return next() checkedCancellation.add(agent) const pending = { id: randomUUID(), role: 'user', diff --git a/snapshots/sdk/serial-created/session.v4.jsonl b/snapshots/sdk/serial-created/session.v4.jsonl index 5109ba2c62..93cc0348f2 100644 --- a/snapshots/sdk/serial-created/session.v4.jsonl +++ b/snapshots/sdk/serial-created/session.v4.jsonl @@ -7,12 +7,15 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:3}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"}]}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} -{"type":"turn/start","data":{"turn":2}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"turn/end","data":{"turn":2,"reason":{"kind":"aborted","reason":{"kind":"disposed"}}}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[11],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":15}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1788943826008,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788943826008,"index":0,"dt":[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788943826009,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 6e1eebe215583a08d87225c328e834c307983e50 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 03:11:46 +0800 Subject: [PATCH 006/438] fix(subagent): settle activations after agent factory unload --- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 5 +- .../subagent/tests/factory-settlement.spec.ts | 50 +++++++++++++++++++ 5 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 packages/subagent/subagent/tests/factory-settlement.spec.ts diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 3b160b2782..4248dbcefa 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 152d969b7214b4cd - zh: 2ba2a43599b009d9 + en: e8b2853fe4a5105d + zh: fb0fdeeefee852ce /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index c3da369bed..a2012acd79 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. An Agent that has begun closing ends the local settlement observer rather than retrying maintenance admission. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When an Agent has begun closing, the manager settles its Activation through the shared close transaction without retrying maintenance admission. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index ed72da6c0a..b5159612d0 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,本地结算观察器会结束,不再重试维护准入。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,管理器通过共享关闭事务结算其 Activation,不再重试维护准入。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index e1b0bc6e68..ba0b8f4c29 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -993,7 +993,10 @@ export class SubagentManager { return Promise.resolve() }) } catch (error: unknown) { - if (error instanceof AgentClosedError) return Promise.resolve('closed') + if (error instanceof AgentClosedError) { + done = this.close(activation, () => this.finishDisposal(activation, false)) + return Promise.resolve({ done }) + } // Another activity already owns the Agent's idle phase. return Promise.resolve('retry') } diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts new file mode 100644 index 0000000000..6b5bb37324 --- /dev/null +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -0,0 +1,50 @@ +import { expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { SessionId } from '@deepseek-ai/dsh-session' +import SubagentRuntime from '../src/index.ts' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' +import { managerState } from './manager-internals.ts' +import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' + +it('settles an activation when its factory unloads during the final flush', async () => { + const ctx = new Context() + const release = Promise.withResolvers() + const flushing = Promise.withResolvers() + try { + await mountAgentLoopTestDependencies(ctx) + const loop = await ctx.plugin(AgentLoop, { agents: [] }) + await mountWorkingDirectoryFixture(ctx) + await ctx.plugin(SubagentRuntime) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('answer')])) + const parent = await ctx.agentLoop.create(SessionId('factory-unload-parent'), { provider: 'mock', model: 'mock' }) + ctx.on('session/flush', async (session) => { + if (session.header.origin !== 'subagent') return + flushing.resolve(undefined) + await release.promise + }) + const started = await ctx.subagents.startActivation({ + provider: 'spawn', label: 'child', prompt: [{ type: 'text', text: 'task' }], + parent, signal: new AbortController().signal, delivery: 'caller', + }) + await flushing.promise + const state = managerState(ctx) + const activation = state.resident.get(started.childId)! + const released = vi.spyOn(activation, 'releaseSlot') + const ended = vi.fn() + ctx.on('subagent/end', ended) + await loop.dispose() + expect(ctx.agents.get(started.childId)).toBeUndefined() + release.resolve(undefined) + await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) + expect(await started.result).toMatchObject({ stopReason: 'completed' }) + expect(released).toHaveBeenCalledTimes(1) + expect(ended).toHaveBeenCalledTimes(1) + } finally { + release.resolve(undefined) + await ctx.fiber.dispose() + } +}) From 2718245916266aa27156d011ebc3690dd73fd4fc Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 14:42:06 +0800 Subject: [PATCH 007/438] 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 008/438] 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 009/438] 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 010/438] 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 2c9d2f46495a7aa720274e90c95a4150eca4e16d Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:13:26 +0800 Subject: [PATCH 011/438] fix(cua): keep hidden windows and auxiliary layers out of default targeting --- .../cua-window-discovery/guide.i18n.yaml | 16 +++++++++ .../v0.2.2-rc.1/cua-window-discovery/guide.md | 17 +++++++++ .../cua-window-discovery/guide.zh.md | 17 +++++++++ .../experimental/cua-macos/README.i18n.yaml | 8 ++--- packages/experimental/cua-macos/README.md | 8 ++--- packages/experimental/cua-macos/README.zh.md | 8 ++--- .../cua-macos/native/README.i18n.yaml | 6 ++-- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 4 +-- .../Sources/CuaNative/NativePlatform.swift | 2 +- .../native/Sources/CuaNative/Protocol.swift | 7 ++-- .../cua-macos/native/generate-protocol.ts | 5 ++- .../native/tests/floating_windows_e2e.py | 1 + .../native/tests/swift/ProtocolTests.swift | 2 +- .../tests/swift/WindowCaptureTests.swift | 2 +- .../tests/swift/WindowGeometryTests.swift | 2 +- .../experimental/cua-macos/src/guidance.ts | 4 +-- .../tests/provider-lifecycle.spec.ts | 27 ++++++++++++++ packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/api.ts | 10 +++--- packages/experimental/cua/src/index.ts | 10 ++++-- packages/experimental/cua/src/protocol.ts | 4 +-- packages/experimental/cua/src/types.ts | 10 +++--- packages/experimental/cua/src/windows.ts | 11 ++++++ packages/experimental/cua/tests/api.spec.ts | 29 ++++++++++++++- .../session/cua-native/replay.override.json | 35 ++++++++++++++++++- .../cua-native/workspace/native-helper.mjs | 12 ++++--- 29 files changed, 216 insertions(+), 51 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md create mode 100644 packages/experimental/cua/src/windows.ts diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml new file mode 100644 index 0000000000..3c660cca16 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md +/: + en: 38fff752f1aa0555 + zh: 154a5b6fd4d10dbf +/finding-hidden-cua-windows: + en: 730a25d76910c44b + zh: 39502d2efdafc9a4 +/finding-hidden-cua-windows/change: + en: b5f962e340aa46ea + zh: 0899c0c6aebbf3f6 +/finding-hidden-cua-windows/migration: + en: b4f23d4f6a5d6309 + zh: 65d0993292b7d2dc diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md new file mode 100644 index 0000000000..6012d7bc1c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "CUA window discovery omits offscreen and zero-size windows by default." +--- + +# Finding hidden CUA windows + +English | [中文](guide.zh.md) + +## Change + +`listWindows`, `app.getWindows()` and the window list in `getState` now show positive-size, onscreen windows on the current desktop. A scoped observation also retains its explicitly selected window. Scripts that find minimized, hidden or other-Space windows through default discovery can miss their target. + +## Migration + +1. Call `app.getWindows({ includeHidden: true })`, or pass `includeHidden: true` with the app handle to the raw `listWindows` operation. +2. Find the target by its window ID in the full result. Use `app.getWindow(windowId)` to select it and `show()` if restoration is required. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md new file mode 100644 index 0000000000..4a8875de31 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-window-discovery/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "CUA 默认窗口清单省略离屏和尺寸为零的窗口。" +--- + +# 查找隐藏的 CUA 窗口 + +[English](guide.md) | 中文 + +## 变更 + +`listWindows`、`app.getWindows()` 和 `getState` 的窗口清单默认只显示当前桌面上尺寸大于零的在屏窗口。窗口级观察还会保留显式选中的窗口。通过默认枚举查找最小化、隐藏或位于其他 Space 的窗口时,脚本可能找不到目标。 + +## 迁移 + +1. 调用 `app.getWindows({ includeHidden: true })`,或在原始 `listWindows` 操作中同时传入应用句柄和 `includeHidden: true`。 +2. 在完整清单中确认目标窗口的 ID,调用 `app.getWindow(windowId)` 选中它,需要恢复窗口时调用 `show()`。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 5ec1b9b13d..c8abe22672 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: a6006411c8240e1a zh: 4c0129caa37b087d /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 786b8fd630b11e5f - zh: 55143f15486afce8 + en: c9dea62ef5876665 + zh: 462faf1b6b9047fd /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 8b9ec208ca057a4a zh: e8dbb45891ad15b8 @@ -39,8 +39,8 @@ en: 2dbc22ffd1f8a717 zh: d4458872e75305d9 /deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/token-effect: - en: ab52b46d874fa8b9 - zh: e87d3620ef77cb06 + en: c02724742dd596a3 + zh: 01ee49dce76e1815 /deepseek-ai-dsh-experimental-cua-macos/model-experience/native-application-operations/kv-cache-effect: en: a2c9acb5a4320dda zh: e8d1586af60215c4 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index b162fdb179..8ffdd9fe4a 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -109,7 +109,7 @@ void await app.getScreenshot() Use app methods directly for single-window tasks. `getApp` reads initial AX state, so a screenshot needs no window enumeration or additional AX read. Use `app.getWindows()` and `app.getWindow(windowId)` when the task needs a particular window or default selection is ambiguous; choose by the observed title and bounds. -`getWindow` emits its initial AX tree. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Window objects retain separate snapshots, so reading one window does not invalidate another. Re-reading the same scope invalidates old indices. An AX node removed during observation rejects the read with `STALE_SNAPSHOT` and publishes no partial tree; read again without repeating the preceding input. App-scoped screenshots and coordinates reuse the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not query current focus again; read `app.getAXState()` to follow a focus change. Explicit window objects retain their selected target. Keyboard methods stay on `app` because input follows the app’s current focus. +`getWindow` emits its initial AX tree. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Window objects retain separate snapshots, so reading one window does not invalidate another. Re-reading the same scope invalidates old indices. An AX node removed during observation rejects the read with `STALE_SNAPSHOT` and publishes no partial tree; read again without repeating the preceding input. App-scoped screenshots and coordinates reuse the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not query current focus again; read `app.getAXState()` to follow a focus change. Explicit window objects retain their selected target. Keyboard methods stay on `app` because input follows the app’s current focus. `hover(target)` first reveals advertised AX alternate UI without moving the system cursor. Entering a revealed descendant preserves its parent UI, and leaving restores the default UI. When unavailable, hover moves the visible system cursor to an AX element center or window-local point without pressing a button, including over disabled controls. It requires the selected app to be foreground and the target point unobscured; otherwise `FOREGROUND_REQUIRED` requires explicit activation or raising and a fresh observation. Completion, AX reads and screenshots do not restore the previous point. Wait for the application’s hover delay, observe the revealed content, then hover into it and click; successive calls can visit intermediate points. Other input or application changes can interrupt the interaction. [Continuous-interaction rationale](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md). @@ -174,7 +174,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -186,7 +186,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result @@ -216,7 +216,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq #### Token effect -Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Retained objects are not serialized into prompts by this package. +Enabling the plugin adds a fixed schema and guidance. AX observations, operation results and admitted images add model input. Default window metadata includes only visible windows and the explicitly observed target. Requesting the complete list adds one record per owned window, including hidden auxiliary windows. #### KV Cache effect diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 435e3b5336..e891d67d51 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -109,7 +109,7 @@ void await app.getScreenshot() 单窗口任务直接使用 app 方法。`getApp` 已读取初始 AX,截图不需要枚举窗口或额外读取 AX。任务需要指定窗口或默认选窗存在歧义时,再调用 `app.getWindows()` 和 `app.getWindow(windowId)`,根据观察到的标题与位置选择目标。 -`getWindow` 会输出初始 AX 树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。不同窗口分别保留快照,读取一个窗口不会使另一个窗口失效;重新读取同一范围会使旧索引失效。观察期间节点被移除时,该次读取返回 `STALE_SNAPSHOT`,不发布部分树;可以重新读取,但不要重复此前的输入。应用级截图和坐标操作复用最近一次 AX 观察:优先使用其中在屏幕上且尺寸非零的焦点窗口,否则要求只有一个符合条件的窗口。它们不会重新查询即时焦点;需要跟随焦点变化时,先读取 `app.getAXState()`。显式窗口对象保持选定的目标。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 +`getWindow` 会输出初始 AX 树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。不同窗口分别保留快照,读取一个窗口不会使另一个窗口失效;重新读取同一范围会使旧索引失效。观察期间节点被移除时,该次读取返回 `STALE_SNAPSHOT`,不发布部分树;可以重新读取,但不要重复此前的输入。应用级截图和坐标操作复用最近一次 AX 观察:优先使用其中在屏幕上且尺寸非零的焦点窗口,否则要求只有一个可见的普通层窗口。它们不会重新查询即时焦点;需要跟随焦点变化时,先读取 `app.getAXState()`。显式窗口对象保持选定的目标。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 `hover(target)` 优先通过控件声明的 AX 动作展开替代界面,不移动系统鼠标。进入展开区域的子控件时保持父控件展开,离开后恢复默认界面。没有这条路径时,再将可见系统鼠标移到 AX 元素中心或窗口内坐标,不按鼠标按钮,也可用于禁用控件。所选应用必须在前台,且目标点未被遮挡,否则返回 `FOREGROUND_REQUIRED`,调用方需显式激活或抬起窗口并重新观察。调用结束、AX 读取和截图不恢复先前的位置。等待应用的悬停延迟后,观察出现的内容,再移入并点击;连续调用可经过中间位置。其他输入或应用自身变化可能中断交互。[连续交互的设计理由](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)。 @@ -174,7 +174,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -186,7 +186,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result @@ -216,7 +216,7 @@ Use selectText only on controls advertising selectionWritable. It selects a uniq #### Token 影响 -启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。本包不将保留的对象序列化进提示。 +启用插件会增加固定参数定义和指导文本。AX 观察、操作结果和已接入的图片会增加模型输入。默认窗口清单只列出可见窗口和显式观察的目标。请求完整清单时,每个窗口都会增加一条记录,包括隐藏的辅助窗口。 #### KV Cache 影响 diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index c5ae58f7b1..1de8edda81 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,11 +18,11 @@ en: 1435672513328c05 zh: 11e7a1e672410c10 /dsh-cua-native-helper/request-protocol: - en: f255df742509459a - zh: 99605a3712c8b8d4 + en: cc296f843e622f8d + zh: a0f69119bf98d720 /dsh-cua-native-helper/observation-and-input: en: 4912c5317dd0dafa - zh: 5be17a0c776959a5 + zh: 86db5a1c0c5b4555 /dsh-cua-native-helper/verification: en: 6d5444d4907e0a2b zh: 65bf25758bafb358 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 65ec51c060..da92c70cd9 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -74,7 +74,7 @@ Successful `activate` and `performSecondaryAction` AXRaise results include `fore | `findApps` | Installed matches `{id, displayName, path, isRunning, pid?}` from standard application directories or an absolute application path; discovery never launches them. | | `getApp` | `{appHandle, pid, name, bundleId, authorization}` selected by exact name, bundle ID, decimal PID or application path. A stopped selection has `pid: null` and waits for Host consent. Ambiguous names fail. | | `launchApp` | Host-only continuation after consent; starts the selected application without requesting activation, waits for launch completion and binds the handle to its verified process identity. | -| `listWindows` | Owned windows across all layers, including independent floating panels and menus, with `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | +| `listWindows` | All WindowServer layers owned by the selected process (including offscreen windows, panels, menus, tooltips and status items). Nonzero levels include a numeric `layer` alongside `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`. Space membership can be null. | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include index, role, title, value, description, identifier, bounds, actions, and enabled state. Element bounds are null or [x, y, width, height] in screen points; window input uses local points. These structured element diagnostics are retained by native checks and omitted by the model tool projection. Unavailable optional descriptive properties are null, and an unavailable action list is empty; permission, communication and window-discovery failures still reject the observation. | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` records native dispatch. Read fresh state to verify the intended application change. | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`. PNG pixel dimensions can differ from window point dimensions on Retina displays. | diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 2f9c7302d2..5182fbee2a 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -74,7 +74,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 | `findApps` | 从标准应用目录或绝对应用路径返回已安装匹配项 `{id, displayName, path, isRunning, pid?}`;发现过程不启动应用。 | | `getApp` | 按精确名称、bundle ID、十进制 PID 或应用路径选择,返回 `{appHandle, pid, name, bundleId, authorization}`。未运行的选择具有 `pid: null`,等待 Host 授权。名称歧义会失败。 | | `launchApp` | 授权后的 Host 专用续接操作;不请求激活,等待应用启动完成后将句柄绑定到已核实的进程身份。 | -| `listWindows` | 应用所属各层级窗口,包括独立浮层和菜单,包含 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | +| `listWindows` | 所选进程在 WindowServer 中的全部窗口,包括离屏窗口、面板、菜单、工具提示和状态栏图标。非零层级另含数字字段 `layer`。窗口字段包括 `{windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace}`。Space 归属可为 null。 | | `getState` | `{appHandle, pid, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含 index、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 | | `hover`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: true, verified: false}` 记录原生分派。需要读取新状态以核实预期的应用变化。 | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`。Retina 显示器上 PNG 像素尺寸可能不同于窗口 point 尺寸。 | @@ -93,7 +93,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。 窗口清单与 `listWindows` 一致,窗口级观察会登记所选浮层的坐标信息。截图单独捕获所选窗口,因此主窗口截图不包含独立浮层。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。窗口清单与 `listWindows` 一致,窗口级观察会登记所选浮层的坐标信息。截图单独捕获所选窗口,因此主窗口截图不包含独立浮层。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。元素动作要求精确的快照 ID,原生引用不跨 JSON 传递。坐标动作的可选快照 ID 必须属于该窗口或应用级观察。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 未指定 holdMs 的元素点击优先使用声明的 AX 动作,否则通过鼠标事件发送。坐标点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。带修饰键的元素点击使用鼠标输入。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift index 81a599639d..16ad44be07 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativePlatform.swift @@ -158,7 +158,7 @@ enum NativePlatform { return WindowInfo(windowID: id, pid: pid, appName: row[kCGWindowOwnerName as String] as? String ?? "", title: row[kCGWindowName as String] as? String ?? "", bounds: bounds, isOnScreen: (row[kCGWindowIsOnscreen as String] as? NSNumber)?.boolValue ?? false, - onCurrentSpace: memberships[id]?.onCurrentSpace) + onCurrentSpace: memberships[id]?.onCurrentSpace, layer: (row[kCGWindowLayer as String] as? NSNumber)?.intValue ?? 0) } } static func frontPID() -> Int32? { WindowSpaces().frontPID() } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift index 762ecaea49..22e30ee776 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift @@ -138,12 +138,15 @@ struct WindowInfo: Sendable { let bounds: WindowBounds let isOnScreen: Bool let onCurrentSpace: Bool? + let layer: Int var json: JSONValue { - .object([ + var fields: [String: JSONValue] = [ "windowId": .number(Double(windowID)), "pid": .number(Double(pid)), "appName": .string(appName), "title": .string(title), "bounds": bounds.json, "isOnScreen": .bool(isOnScreen), "onCurrentSpace": onCurrentSpace.map(JSONValue.bool) ?? .null, - ]) + ] + if layer != 0 { fields["layer"] = .number(Double(layer)) } + return .object(fields) } } diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 1374c6fdfa..232441e758 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -37,7 +37,10 @@ export function renderNativeProtocol(): { json: string; swift: string } { const extension = resources.get(method) for (const variant of variants(params)) { // The Host resolves image pixels and relative coordinates before native dispatch. - if (variant.properties) delete variant.properties.relative + if (variant.properties) { + delete variant.properties.relative + if (method === 'listWindows') delete variant.properties.includeHidden + } if (variant.required) variant.required = variant.required.filter(name => name !== 'relative') if (extension !== undefined) { const extra = z.toJSONSchema(extension) diff --git a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py index 62aa14fa53..9d8dc464d8 100644 --- a/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py +++ b/packages/experimental/cua-macos/native/tests/floating_windows_e2e.py @@ -61,6 +61,7 @@ def main(): assert panel_id in [window['windowId'] for window in windows], windows assert all(window['pid'] == fixture.pid for window in windows), windows listed = next(window for window in windows if window['windowId'] == panel_id) + assert listed['layer'] == actual['panelLayer'], listed assert listed['onCurrentSpace'] is True, listed application = helper.call('getState', params) assert application['focusedWindowId'] == actual['mainWindowId'], application diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index 611fa6786c..f9626c250f 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -43,7 +43,7 @@ func refusesInvalidRequestEnvelopes(_ source: String) { let window = WindowInfo( windowID: 7, pid: 42, appName: "Fixture", title: "Canvas", bounds: WindowBounds(x: -100, y: 40, width: 320, height: 200), - isOnScreen: true, onCurrentSpace: nil + isOnScreen: true, onCurrentSpace: nil, layer: 0 ) let encoded = try JSONEncoder().encode(window.json) let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) diff --git a/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift b/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift index da0b2a8546..9655640147 100644 --- a/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/WindowCaptureTests.swift @@ -34,7 +34,7 @@ private final class HeldCapture: @unchecked Sendable { let worker = AXWorker(cancellation: cancellation, axTimeout: 1, textEventInterval: 0, maxClickHoldMs: 5000) let target = CaptureTarget(appHandle: "fixture", process: ProcessIdentity(pid: 1, startedSeconds: 1, startedMicroseconds: 0), window: WindowInfo(windowID: 1, pid: 1, appName: "fixture", title: "fixture", - bounds: WindowBounds(x: 0, y: 0, width: 1, height: 1), isOnScreen: true, onCurrentSpace: true)) + bounds: WindowBounds(x: 0, y: 0, width: 1, height: 1), isOnScreen: true, onCurrentSpace: true, layer: 0)) func request() -> Task { Task { try await scheduler.perform(cancellation: cancellation) { diff --git a/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift b/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift index 33362e80a4..8a4b686097 100644 --- a/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/WindowGeometryTests.swift @@ -70,7 +70,7 @@ private let geometryOwner = ProcessIdentity(pid: 42, startedSeconds: 1, startedM private func geometryWindow(_ bounds: WindowBounds) -> WindowInfo { WindowInfo(windowID: 7, pid: geometryOwner.pid, appName: "Fixture", title: "Fixture", bounds: bounds, - isOnScreen: true, onCurrentSpace: true) + isOnScreen: true, onCurrentSpace: true, layer: 0) } @Test func resolveDetectsMovementDuringTheAXQueryEvenWhenTheFinalFramesMatch() { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 3c5d0dd53a..15e9bf0c44 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -4,7 +4,7 @@ export const GUIDANCE = `Use cua with method getCapabilities and params {} to in Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -16,7 +16,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index bb45e394c9..82ab6ac682 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -427,6 +427,33 @@ it('keeps native element diagnostics out of model-visible state and structured t expect(JSON.parse(content.text)).toEqual(visible) }) +it('omits hidden windows from model output without forgetting their observed coordinates', async () => { + const f = await setup() + await selectApplication(f) + const params = { appHandle: 'app-one' } + const main = { windowId: 7, pid: 17, appName: 'Fixture', title: 'Main', + bounds: { x: 0, y: 0, width: 10, height: 10 }, isOnScreen: true, onCurrentSpace: true } + const panel = { ...main, windowId: 8, layer: 3, onCurrentSpace: null } + const hidden = { ...panel, windowId: 9, isOnScreen: false } + const all = [main, panel, hidden, { ...main, windowId: 10, onCurrentSpace: false }, + { ...main, windowId: 11, bounds: { ...main.bounds, width: 0 } }] + for (const [includeHidden, expected] of [[false, [main, panel]], [true, all]] as const) { + native.request.mockResolvedValueOnce(all) + const result = await f.execute('listWindows', { ...params, includeHidden }) + expect(result.value).toEqual(expected) + expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(expected) }]) + } + for (const windowId of [null, 9]) { + native.request.mockResolvedValueOnce({ ...params, pid: 17, windowId, windows: all, snapshotId: 's', tree: '', truncated: false }) + const result = await f.execute('getState', windowId === null ? params : { ...params, windowId }) + expect(result.value).toMatchObject({ windows: windowId === null ? [main, panel] : [main, panel, hidden] }) + } + native.request.mockResolvedValueOnce(all) + await f.execute('listWindows', params) + native.request.mockResolvedValueOnce({ dispatched: true, verified: false }) + expect((await f.execute('click', { ...params, windowId: 9, x: 500, y: 500, relative: true })).isError).toBe(false) +}) + it('preserves screenshot attachments and invalidates pixel coordinates when window listings observe a resize', async () => { const f = await setup({ provider: 'image-fixture', model: 'vision' }) await selectApplication(f) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 7adacc3f3c..1de10158b5 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ed736a45140a6d56 - zh: 8dc89373a0a88fcc + en: 0f7ca6b5ab4303d9 + zh: db753aeccd0c9c07 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 7dd223645d..a2fd06f2e7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -29,7 +29,7 @@ Application consent supplies English, Chinese, and Japanese display text from `s Mount the [macOS provider](../cua-macos/README.md) to enable native operations. External PTC hosts import `connectCua` from `@deepseek-ai/dsh-cua/bridge` and supply the current `tools.cua` binding. Source compositions and native preparation belong to the provider. -Use App methods for a single-window task. `getApp` reads initial accessibility state; `getWindows` and `getWindow` select an explicit window when needed. Re-reading one app/window scope replaces its element indices without invalidating another window's snapshot. Keyboard input follows the application's focus. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. +Use App methods for a single-window task. `getApp` reads initial accessibility state; `getWindows` and `getWindow` select an explicit window when needed. Re-reading one app/window scope replaces its element indices without invalidating another window's snapshot. Keyboard input follows the application's focus. Invalid request arguments reject before dispatch with a readable method, parameter and requirement. Default discovery returns visible windows; use `getWindows({ includeHidden: true })` for the complete inventory. Observation methods emit and return their result. Use `void await app.getAXState()` for one visible copy, or use `emit:false` and print the returned text once. Screenshots return `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index dda0f716bf..7f89ee6463 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 挂载 [macOS 提供方](../cua-macos/README.zh.md)以启用原生操作。外部 PTC 宿主从 `@deepseek-ai/dsh-cua/bridge` 导入 `connectCua`,并提供当前 `tools.cua` 绑定。源码组合与原生组件准备由提供方负责。 -单窗口任务直接使用 App 方法。`getApp` 读取初始辅助功能状态;需要指定窗口时使用 `getWindows` 和 `getWindow`。重新读取一个应用或窗口范围会替换其中的元素编号,不使其他窗口的快照失效。键盘输入跟随应用焦点。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。 +单窗口任务直接使用 App 方法。`getApp` 读取初始辅助功能状态;需要指定窗口时使用 `getWindows` 和 `getWindow`。重新读取一个应用或窗口范围会替换其中的元素编号,不使其他窗口的快照失效。键盘输入跟随应用焦点。请求参数校验失败时,在分派前返回包含方法、参数和要求的可读消息。默认只列出可见窗口,需要完整清单时使用 `getWindows({ includeHidden: true })`。 观察方法会输出并返回结果。使用 `void await app.getAXState()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。截图返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 9a3dfb7a12..a4d6d35314 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -4,6 +4,7 @@ import type { z } from 'zod' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' import type { CuaApi, CuaApp, CuaAppHandle, CuaDispatch, CuaObservationOptions, CuaObservationSink, CuaOperation, CuaScreenshot, CuaSurface, CuaWindow } from './types.ts' +import { isVisibleWindow } from './windows.ts' export type * from './types.ts' function requestIssueMessage(issues: readonly z.core.$ZodIssue[], parent: readonly PropertyKey[] = []): string { @@ -69,11 +70,12 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): } function windowId(): number { if (selectedWindow !== undefined) return selectedWindow - const windows = observed?.windows.filter(window => window.isOnScreen && window.bounds.width > 0 && window.bounds.height > 0) + const windows = observed?.windows.filter(isVisibleWindow) const focused = windows?.find(window => window.windowId === observed?.focusedWindowId) if (focused) return focused.windowId - const first = windows?.[0] - if (!first || windows.length !== 1) throw new Error('Select a window with app.getWindows() and app.getWindow(windowId) before this operation') + const ordinary = windows?.filter(window => !window.layer) + const first = ordinary?.[0] + if (!first || ordinary.length !== 1) throw new Error('Select a window with app.getWindows() and app.getWindow(windowId) before this operation') return first.windowId } const result: CuaSurface = { @@ -194,7 +196,7 @@ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): ...surface(appHandle, pid), pid, appHandle, async activate() { return action('activate', { appHandle }) }, async getWindows(options) { - const windows = WindowsResult.parse(await call('listWindows', { appHandle })) + const windows = WindowsResult.parse(await call('listWindows', { appHandle, ...options?.includeHidden === undefined ? {} : { includeHidden: options.includeHidden } })) if (windows.some(window => window.pid !== pid)) throw new Error('Native windows belong to another application') await emit(windows, options) return windows diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index c776941a7b..db13b4fa8a 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -18,6 +18,7 @@ import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' import type { CuaAppHandle, CuaOperation } from './types.ts' import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, ScreenshotResult, StateResult, WindowsResult } from './protocol.ts' +import { isVisibleWindow } from './windows.ts' import { CuaCoordinates } from './coordinates.ts' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import type {} from '@deepseek-ai/dsh-agent-preset-registry' @@ -229,6 +230,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const callNative = async (request: CuaOperation, execution: Readonly) => { const { method, params: parsedParams } = request const params = execution.coordinates.parameters(request) + if (method === 'listWindows') delete params.includeHidden const agent = execution.agent const signal = execution.signal signal.throwIfAborted() @@ -282,9 +284,13 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) if (method === 'getState') { const state = StateResult.parse(result) execution.coordinates.observe(state.appHandle, state.windows, state.windowId ?? undefined) - return state + return { ...state, windows: state.windows.filter(window => window.windowId === state.windowId || isVisibleWindow(window)) } + } + if (method === 'listWindows') { + const windows = WindowsResult.parse(result) + execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, windows) + return parsedParams.includeHidden ? windows : windows.filter(isVisibleWindow) } - if (method === 'listWindows') execution.coordinates.observe(parsedParams.appHandle as CuaAppHandle, WindowsResult.parse(result)) return result } const tool: ToolDefinition = { diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 2918014fac..e39b6a4270 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -37,7 +37,7 @@ export const Request = z.discriminatedUnion('method', [ operation('getApp', { selector: z.string().min(1) }), operation('activate', app), operation('show', { ...app, windowId: id.optional() }), - operation('listWindows', app), + operation('listWindows', { ...app, includeHidden: z.boolean().optional().describe('Include offscreen and zero-size windows for explicit selection or restoration.') }), operation('getState', { ...app, windowId: id.optional(), includeMenus: z.boolean().optional().describe('Expand menu contents; omitted or false shows menu-bar entries only.'), details: z.boolean().optional().describe('Include identifiers, global-point bounds and complete action names.'), @@ -101,7 +101,7 @@ export const FoundAppsResult = z.array(z.intersection(z.object({ id: z.string(). /** Current windows and their global point bounds. */ export const WindowsResult = z.array(z.object({ windowId: id, pid, appName: z.string(), title: z.string(), bounds, - isOnScreen: z.boolean(), onCurrentSpace: z.boolean().nullable(), + isOnScreen: z.boolean(), onCurrentSpace: z.boolean().nullable(), layer: z.number().int().optional(), })) /** Observed state with window and process identity for stale-target rejection. */ export const StateResult = z.object({ diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index ac0c16e90b..5c4422f482 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -49,7 +49,7 @@ export type CuaAppInfo = Pick, 'id export type CuaFoundAppInfo = z.output[number] /** Window bounds in global macOS points. Local operations use an origin of [0,0]. */ export type CuaBounds = CuaWindowInfo['bounds'] -/** Observed window metadata; identifiers are valid only while the window exists, and null Space membership is unknown. */ +/** Window IDs expire on destruction. An omitted layer is normal level zero; null Space membership is unknown. */ export type CuaWindowInfo = z.output[number] /** Successful input dispatch; application outcome still requires observation. */ export type CuaActionResult = z.output @@ -175,7 +175,7 @@ export interface CuaWindow extends CuaSurface { readonly windowId: number } /** * Native app handle supporting direct observations and actions without window enumeration. * Screenshots and coordinates reuse the latest AX observation's focused on-screen, - * nonzero-size window, or require exactly one such window. Read fresh AX to follow + * nonzero-size window, or the sole visible normal-layer window. Read fresh AX to follow * focus changes; explicit window objects retain their selected target. */ export interface CuaApp extends CuaSurface { @@ -187,11 +187,11 @@ export interface CuaApp extends CuaSurface { */ activate(): Promise /** - * Enumerate current windows. - * @param options - output options. + * Enumerate visible windows, including independent panels and menus. + * @param options - Output options; includeHidden returns the complete inventory for explicit selection. * @returns current window records. */ - getWindows(options?: CuaObservationOptions): Promise + getWindows(options?: CuaObservationOptions & { includeHidden?: boolean }): Promise /** * Observe a specific window. * @param windowId - ID obtained from getWindows. diff --git a/packages/experimental/cua/src/windows.ts b/packages/experimental/cua/src/windows.ts new file mode 100644 index 0000000000..0e499e7ad2 --- /dev/null +++ b/packages/experimental/cua/src/windows.ts @@ -0,0 +1,11 @@ +/** WindowServer visibility used for model observations and app-level target selection. */ +import type { CuaWindowInfo } from './types.ts' + +/** + * Whether the window can appear in default discovery on the current desktop. + * @param window - WindowServer record; unavailable Space membership remains unknown. + * @returns Whether a positive-size window is on screen and not known to be on another Space. + */ +export function isVisibleWindow(window: CuaWindowInfo): boolean { + return window.isOnScreen && window.onCurrentSpace !== false && window.bounds.width > 0 && window.bounds.height > 0 +} diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index eeed87c861..f66c19deda 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -299,7 +299,8 @@ describe('application and window observations', () => { ] f.setWindowRecords(windows) const app = await f.api.getApp('Editor') - expect(await app.getWindows({ emit: false })).toEqual(windows) + expect(await app.getWindows({ emit: false, includeHidden: true })).toEqual(windows) + expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'listWindows', params: { appHandle: 'app-17', includeHidden: true } }) await app.getScreenshot() expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 23 } }) await app.click([10, 20]) @@ -334,6 +335,32 @@ describe('application and window observations', () => { expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'screenshot', params: { appHandle: 'app-17', windowId: 24 } }) }) + it('uses only the sole ordinary window as a fallback without AX focus', async () => { + const f = fixture() + const app = await f.api.getApp('Editor') + const panel = { ...windowInfo(24), layer: 3 } + const status = { ...windowInfo(25), layer: 25 } + for (const [windows, target] of [ + [[panel, status, windowInfo(23)], 23], + [[panel, status], null], + [[windowInfo(23), status, windowInfo(26)], null], + ] as const) { + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: null, windows: [...windows] })) + await app.getAXState() + if (target === null) { + await expect(app.getScreenshot()).rejects.toThrow('Select a window') + await expect(app.click([0, 0])).rejects.toThrow('Select a window') + } else { + expect((await app.getScreenshot()).windowId).toBe(target) + await app.click([0, 0]) + expect(f.dispatch.mock.lastCall?.[0].params).toMatchObject({ windowId: target }) + } + } + f.dispatch.mockResolvedValueOnce(state({ focusedWindowId: 24, windows: [panel, status, windowInfo(23)] })) + await app.getAXState() + expect((await app.getScreenshot()).windowId).toBe(24) + }) + it('captures and clicks an explicitly selected floating panel while the main window keeps focus', async () => { const f = fixture() const app = await f.api.getApp('Editor') diff --git a/snapshots/session/cua-native/replay.override.json b/snapshots/session/cua-native/replay.override.json index 8c0531f14b..39f083c44d 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -1781,6 +1781,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-floating-complete-list", + "name": "cua", + "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ @@ -1796,7 +1829,7 @@ "type": "tool-call", "id": "cua-floating-refresh", "name": "cua", - "arguments": "{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}" + "arguments": "{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}" } }, { diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index ec52fe6f1e..7be762e166 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -113,8 +113,10 @@ function createApplicationState(socket, record, application, captureBroker, conn const bounds = { x: 40, y: 60, width: 320, height: 200 } const window = { windowId: 7, pid: 9, appName: 'Fixture', title: 'CUA fixture', bounds, isOnScreen: true, onCurrentSpace: true } const axlessWindow = { ...window, windowId: 8, title: 'AXless canvas' } - const floatingWindow = { ...window, windowId: 10, title: 'Floating panel', bounds: { x: 100, y: 120, width: 240, height: 140 } } + const floatingWindow = { ...window, windowId: 10, layer: 3, title: 'Floating panel', bounds: { x: 100, y: 120, width: 240, height: 140 } } const transformedWindow = { ...window, windowId: 9, title: 'Transformed window', bounds: { x: 16, y: 512, width: 131, height: 145 } } + const inventory = () => [window, axlessWindow, transformedWindow, ...application.floating + ? [floatingWindow, { ...floatingWindow, windowId: 11, title: 'Cached panel', isOnScreen: false }] : []] const screenshotConfig = new URL('./fixture-screenshot.json', import.meta.url) const customScreenshot = existsSync(screenshotConfig) ? JSON.parse(readFileSync(screenshotConfig, 'utf8')) : undefined const snapshots = new Map() @@ -160,7 +162,7 @@ function createApplicationState(socket, record, application, captureBroker, conn before, after, activationRequested, raiseRequested: false, } } } - if (method === 'listWindows') return [window, axlessWindow, ...application.floating ? [floatingWindow] : []] + if (method === 'listWindows') return inventory() if (method === 'getState') { snapshots.delete(params.windowId ?? null) if (observationChanged) { @@ -173,14 +175,14 @@ function createApplicationState(socket, record, application, captureBroker, conn snapshots.set(params.windowId ?? null, { snapshotId, windowId: params.windowId ?? null, axless }) if (params.windowId === 10 && application.floating) return { appHandle: app.appHandle, pid: 9, windowId: 10, snapshotId, focusedWindowId: 7, tree: `AX scope=window offsets=UTF-16\n- AXWindow "Floating panel"\n - [0] AXButton "Increment floating panel"\n - AXStaticText "Floating count: ${application.floatingCount}"`, - elements: [], windows: [window, axlessWindow, floatingWindow], truncated: false } + elements: [], windows: inventory(), truncated: false } if (axless) return { appHandle: app.appHandle, pid: 9, windowId: 8, snapshotId, - tree: '', elements: [], windows: [axlessWindow], truncated: false } + tree: '', elements: [], focusedWindowId: 7, windows: inventory(), truncated: false } return { appHandle: app.appHandle, pid: 9, windowId: params.windowId ?? null, snapshotId: `${scope}-snapshot-${generation}`, tree: `AX scope=${params.windowId === undefined ? 'application' : 'window'} offsets=UTF-16${params.details ? ' bounds=global-points' : ''}\n- [0] AXButton "Increment"${params.details ? ' id="increment" actions=["AXPress"] bounds=[60,80,100,20]' : ''}\n- [1] AXTextField valueWritable=true selectionWritable=true value=${JSON.stringify(application.value)} placeholder="Fixture text"\n- AXStaticText "Count: ${application.count}"${application.hovering ? '\n- AXStaticText "Hover information"' : ''}\n- [2] AXMenuBarItem "File"${params.includeMenus ? '\n - [3] AXMenuItem "Fixture command"' : '\nMenu contents omitted; request includeMenus=true to expand.'}`, elements: [{ index: 0, role: 'AXButton', title: 'Increment', value: null, description: null, identifier: null, bounds: [60, 80, 100, 20], actions: ['AXPress'], enabled: true }], - windows: [params.windowId === 9 ? transformedWindow : window], truncated: false } + focusedWindowId: 7, windows: inventory(), truncated: false } } if (params.windowId === 9 && ['screenshot', 'hover', 'click', 'scroll', 'drag'].includes(method) && params.elementIndex === undefined) { refuse('WINDOW_CHANGED', 'Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input') From a11de46bfd0f33efe211a392926c8440aa447461 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:16:47 +0800 Subject: [PATCH 012/438] fix(agent): guard inbox admission and settle disposed activations --- packages/core/agent-loop/src/agent.ts | 6 +++--- packages/core/agent-loop/src/inbox.ts | 12 ++++++++++++ .../agent-loop/tests/input-lifecycle.spec.ts | 19 ++++++++++++++++++- packages/subagent/subagent/src/manager.ts | 7 +++++++ .../subagent/tests/factory-settlement.spec.ts | 16 ++++++++++++++-- 5 files changed, 54 insertions(+), 6 deletions(-) diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 76b2c2b80e..12464720ae 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -148,7 +148,7 @@ export class ReactLoopAgent implements Agent { this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx this.model = new AgentModel(projections.modelSelection, session, options) - this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => this.assertOpen()) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) @@ -606,13 +606,13 @@ export class ReactLoopAgent implements Agent { maxParallelToolCalls, toolSet: decision.toolSet, }) for (const context of result.additionalContexts) { - this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) + this.inbox.retainContext(context) } return result.concluded ? { kind: 'completed' } : null } catch (error: unknown) { if (!(error instanceof ToolBatchExecutionError)) throw error for (const context of error.partial.additionalContexts) { - this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) + this.inbox.retainContext(context) } throw error.cause } diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index affe0c6b2f..8972667b10 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -69,12 +69,14 @@ export const inboxProjectionDefinition = { * @param readState - reader for the live Inbox projection state. * @param session - session whose durable events store pending input. * @param dispatch - agent-scoped notifications for Inbox lifecycle events. + * @param assertAdmission - rejects public insertions and replacements after admission closes. */ export class ReactLoopInbox implements InboxContract { constructor( private readonly readState: () => InboxState, private readonly session: Session, private readonly dispatch: AgentEventDispatch, + private readonly assertAdmission: () => void = () => {}, ) {} /** Prompts awaiting individual turns. */ @@ -137,6 +139,7 @@ export class ReactLoopInbox implements InboxContract { * @returns whether the message was still pending. */ replace(messageId: MessageId, newMessage: UserMessage): boolean { + this.assertAdmission() const location = this.locate(messageId) if (location === undefined) return false this.splice(location.target, location.index, 1, [newMessage]) @@ -169,9 +172,18 @@ export class ReactLoopInbox implements InboxContract { deleteCount: number, inserted: UserMessage[], ): UserMessage[] { + if (inserted.length > 0) this.assertAdmission() return this.mutate(target, start, deleteCount, inserted, true) } + /** + * Retain context finalized by admitted work, including during shutdown. + * @param message - context produced by the active driver. + */ + retainContext(message: UserMessage): void { + this.mutate('next-step', this.nextStep.length, 0, [message], true) + } + /** Locate one pending identity across both owned lists. */ private locate(messageId: MessageId): { target: InboxTarget; index: number } | undefined { const state = this.readState() diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 2e87517e1f..3cdb06da2c 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -96,7 +96,7 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') - for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {})]) { + for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => agent.inbox.append('next-turn', message), () => agent.inbox.prepend('next-step', message), () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) @@ -149,3 +149,20 @@ it('waits for admitted maintenance after a queue-clear failure before releasing await closing } }) + +it('does not start a driver when an inbox observer closes its owner during admission', async () => { + const { ctx, agent, handle, adapter } = await harness() + let closing: Promise | undefined + const stop = ctx.on('agent/inbox/inserted', ({ message }) => { + if (message.source.kind === 'user') closing = handle.dispose() + }) + try { + agent.followup(input('close during admission')) + expect(closing).toBeDefined() + await closing + expect(adapter.requests).toHaveLength(0) + } finally { + stop() + await closing + } +}) diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index ba0b8f4c29..f4a2a3d652 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -174,6 +174,12 @@ export class SubagentManager { }, session => host.identityOf(session)) ctx.on('agent/disposed', ({ agent }) => { this.closingRoots.delete(agent) + const activation = this.resident.get(agent.id) + if (activation?.kind === 'local' && activation.handle.agent === agent) { + void this.close(activation, () => this.finishDisposal(activation, false)).catch((error: unknown) => { + this.reportTeardownFailure(activation, error) + }) + } }) ctx.effect(function* (this: SubagentManager) { yield scope.dispose @@ -1127,6 +1133,7 @@ export class SubagentManager { } this.sendWaking(parent, message, parent.status === 'idle' ? 'queue' : 'steer') } catch (error: unknown) { + if (error instanceof AgentClosedError) return this.ctx.logger.warn( `subagent "${activation.childId}" settlement notice was not delivered to its parent: ` + errorChain(error), diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index 6b5bb37324..ed339efca6 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -2,14 +2,15 @@ import { expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import { SessionId } from '@deepseek-ai/dsh-session' +import { SessionId, type Session, type SessionEvent } from '@deepseek-ai/dsh-session' import SubagentRuntime from '../src/index.ts' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' import { managerState } from './manager-internals.ts' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' -it('settles an activation when its factory unloads during the final flush', async () => { +it.each([false, true])('settles an activation after factory unload with queue-clear failure=%s', async (rejectQueueClear) => { const ctx = new Context() const release = Promise.withResolvers() const flushing = Promise.withResolvers() @@ -36,7 +37,18 @@ it('settles an activation when its factory unloads during the final flush', asyn const released = vi.spyOn(activation, 'releaseSlot') const ended = vi.fn() ctx.on('subagent/end', ended) + const child = ctx.agents.get(started.childId)! + if (rejectQueueClear) child.inject(createUserMessage({ content: [{ type: 'text', text: 'pending' }], source: { kind: 'user' } })) + const rejectClear = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (rejectQueueClear && session === child.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) { + throw new Error('queue clear rejected') + } + }) await loop.dispose() + expect(child.inbox.hasPending).toBe(rejectQueueClear) + rejectClear() expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) From c14c53ad84cca8ba62ceb07cb3a1a7f8e12bfdaf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:16:48 +0800 Subject: [PATCH 013/438] test(cua): record visible and complete window inventories --- snapshots/session/cua-native/session.v4.jsonl | 197 +++++++++--------- .../cua-native/system-prompt.expected.md | 4 +- .../cua-native/tool-schemas.expected.json | 4 + snapshots/session/cua-ptc/session.v4.jsonl | 2 +- .../session/cua-ptc/system-prompt.expected.md | 4 +- 5 files changed, 110 insertions(+), 101 deletions(-) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 153095ab8a..0530baf8ac 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -12,316 +12,321 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564511530,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564511530,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564511530,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866514904,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866514904,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1793866514904,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866514904,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"platform\":\"macos\",\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"methods\":[\"getCapabilities\",\"listApps\",\"getApp\",\"activate\",\"show\",\"listWindows\",\"getState\",\"hover\",\"click\",\"setValue\",\"typeText\",\"paste\",\"pressKey\",\"scroll\",\"drag\",\"screenshot\"],\"coordinateSpace\":\"screenshot-pixels\",\"browser\":false}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512128,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512128,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512128,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515470,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515470,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515470,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515470,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512153,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512153,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512153,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512154,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515486,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515486,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515486,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515486,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512173,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512173,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512173,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515501,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515501,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515501,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515501,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515518,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515518,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1793866515518,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515518,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-2"},"toolCallId":"cua-native-2","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515553,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515553,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1793866515553,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515553,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}} -{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512246,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512246,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512246,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515571,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515571,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1793866515571,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515571,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":7,"callId":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementIndex\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-4"},"toolCallId":"cua-native-4","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512265,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512266,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512266,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515589,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515589,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515589,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515589,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":8,"callId":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512288,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512288,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512288,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515606,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515606,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515606,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515606,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":9,"callId":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-6"},"toolCallId":"cua-native-6","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:21}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512368,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512368,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512368,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515685,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515685,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515685,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515685,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":10,"callId":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512388,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512388,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512388,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515702,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515702,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515702,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515702,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":11,"callId":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} -{"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} {"type":"step/start","data":{"turn":1,"step":12}} -{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515725,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515725,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515725,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515725,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":12,"callId":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-9"},"toolCallId":"cua-native-9","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":8,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:27}}"}},"sourceEventSeqs":[69],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":12}} {"type":"step/start","data":{"turn":1,"step":13}} -{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512445,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512445,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512445,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515765,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515765,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1793866515765,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515765,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":13,"callId":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-10"},"toolCallId":"cua-native-10","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:29}}"}},"sourceEventSeqs":[74],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":13}} {"type":"step/start","data":{"turn":1,"step":14}} -{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512464,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512464,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512464,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515782,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515782,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793866515782,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515782,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":14,"callId":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} -{"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":8,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":14}} {"type":"step/start","data":{"turn":1,"step":15}} -{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512484,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512484,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512484,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":15,"callId":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":15,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-show"},"toolCallId":"cua-native-show","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"windowId\":7,\"foregroundChanged\":false}"}],"isError":false,"id":"{{message:33}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":15}} {"type":"step/start","data":{"turn":1,"step":16}} -{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512511,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512511,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512511,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515816,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515816,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515816,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515816,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":16,"callId":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":16,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-first"},"toolCallId":"cua-native-activate-first","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-first\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:35}}"}},"sourceEventSeqs":[89],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":16}} {"type":"step/start","data":{"turn":1,"step":17}} -{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866515832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":17,"callId":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":17,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-repeat"},"toolCallId":"cua-native-activate-repeat","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-native-activate-repeat\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":false,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:37}}"}},"sourceEventSeqs":[94],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":17}} {"type":"step/start","data":{"turn":1,"step":18}} -{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512552,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512552,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512552,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515848,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515848,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1793866515848,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515848,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":18,"callId":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}} {"type":"tool/result","data":{"turn":1,"step":18,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-transition"},"toolCallId":"cua-native-transition","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:39}}"}},"sourceEventSeqs":[99],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":18}} {"type":"step/start","data":{"turn":1,"step":19}} -{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512570,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512570,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512570,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515864,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515864,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515864,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515864,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAXState"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} -{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515881,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515881,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515881,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515881,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} -{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512616,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512616,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512616,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515897,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515897,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1793866515897,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515897,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":21,"callId":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":21,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-other-window"},"toolCallId":"cua-native-other-window","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:45}}"}},"sourceEventSeqs":[114],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":21}} {"type":"step/start","data":{"turn":1,"step":22}} -{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":22,"callId":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":22}} {"type":"step/start","data":{"turn":1,"step":23}} -{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512654,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512654,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512654,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515929,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515929,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866515929,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515929,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":23,"callId":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":23,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-click"},"toolCallId":"cua-native-fresh-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:49}}"}},"sourceEventSeqs":[124],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":23}} {"type":"step/start","data":{"turn":1,"step":24}} -{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512675,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512675,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512675,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515945,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515945,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866515945,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515945,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":24,"callId":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":24}} {"type":"step/start","data":{"turn":1,"step":25}} -{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515962,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515962,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866515962,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515962,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":25,"callId":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":25}} {"type":"step/start","data":{"turn":1,"step":26}} -{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512716,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512716,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512716,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515979,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515979,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866515979,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515979,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} -{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866515995,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866515995,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1793866515995,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866515995,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} -{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512755,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512755,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512755,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516013,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516013,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1793866516013,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516013,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} -{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512781,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512781,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512781,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516030,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516030,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1793866516030,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516030,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} -{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512800,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512800,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512800,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516047,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516047,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866516047,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516047,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":30,"callId":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":30,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-ax"},"toolCallId":"cua-native-geometry-ax","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:63}}"}},"sourceEventSeqs":[159],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":30}} {"type":"step/start","data":{"turn":1,"step":31}} -{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512832,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512832,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512832,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516063,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516063,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793866516063,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516063,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":31,"callId":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} -{"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":9,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":31}} {"type":"step/start","data":{"turn":1,"step":32}} -{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512855,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512855,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512855,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516079,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516079,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1793866516079,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516079,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":32,"callId":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}} {"type":"tool/result","data":{"turn":1,"step":32,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-arm"},"toolCallId":"cua-capture-busy-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:67}}"}},"sourceEventSeqs":[169],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":32}} {"type":"step/start","data":{"turn":1,"step":33}} -{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512882,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512882,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512882,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516095,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516095,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516095,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516095,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} -{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512913,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512913,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512913,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516113,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516113,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516113,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516113,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":34,"callId":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":34}} {"type":"step/start","data":{"turn":1,"step":35}} -{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512942,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512942,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512942,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516130,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516130,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1793866516130,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516130,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":35,"callId":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}} {"type":"tool/result","data":{"turn":1,"step":35,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-callback"},"toolCallId":"cua-capture-callback","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:73}}"}},"sourceEventSeqs":[184],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":35}} {"type":"step/start","data":{"turn":1,"step":36}} -{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564512970,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564512970,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564512970,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516146,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516146,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516146,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516146,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":36,"callId":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":36,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-recovered"},"toolCallId":"cua-capture-recovered","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:75}}"}},"sourceEventSeqs":[189],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":36}} {"type":"step/start","data":{"turn":1,"step":37}} -{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513023,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513024,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513024,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516194,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516194,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}}},{"type":"chunk","time":1793866516194,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516194,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":37,"callId":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementIndex\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":37,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-enter"},"toolCallId":"cua-hover-enter","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:77}}"}},"sourceEventSeqs":[194],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":37}} {"type":"step/start","data":{"turn":1,"step":38}} -{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513075,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513075,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513075,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516210,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516210,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516210,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516210,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":38,"callId":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":38}} {"type":"step/start","data":{"turn":1,"step":39}} -{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513125,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513125,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513125,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516231,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516231,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516231,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516231,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":39,"callId":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":39,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-capture"},"toolCallId":"cua-hover-capture","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:81}}"}},"sourceEventSeqs":[204],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":39}} {"type":"step/start","data":{"turn":1,"step":40}} -{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513163,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513163,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513163,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516262,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516262,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516262,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516262,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":40,"callId":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":40,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-popup"},"toolCallId":"cua-hover-popup","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:83}}"}},"sourceEventSeqs":[209],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":40}} {"type":"step/start","data":{"turn":1,"step":41}} -{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513183,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513183,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513183,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516292,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516292,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516292,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516292,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":41,"callId":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":41,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-click"},"toolCallId":"cua-hover-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:85}}"}},"sourceEventSeqs":[214],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":41}} {"type":"step/start","data":{"turn":1,"step":42}} -{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513205,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513205,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513205,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516317,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516317,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793866516317,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516317,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":42,"callId":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"hover\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":42,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-exit"},"toolCallId":"cua-hover-exit","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:87}}"}},"sourceEventSeqs":[219],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":42}} {"type":"step/start","data":{"turn":1,"step":43}} -{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513224,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513224,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513224,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516338,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516338,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516338,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516338,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} -{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513244,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513244,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513244,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516355,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516355,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1793866516355,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516355,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} {"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":44}} {"type":"step/start","data":{"turn":1,"step":45}} -{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513264,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513264,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513264,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516372,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516372,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793866516372,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516372,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":45}} {"type":"step/start","data":{"turn":1,"step":46}} -{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513290,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513290,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513290,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516389,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516389,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516389,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516389,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":46}} {"type":"step/start","data":{"turn":1,"step":47}} -{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516406,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516406,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516406,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516406,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"operation\":\"activate\",\"targetPid\":9,\"targetWindowId\":null,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true,\"raiseRequested\":false}}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":47}} {"type":"step/start","data":{"turn":1,"step":48}} -{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513332,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513332,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513332,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516424,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516424,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516424,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516424,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} -{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513353,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513353,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513353,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516449,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516449,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793866516449,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516449,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} {"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":49}} {"type":"step/start","data":{"turn":1,"step":50}} -{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513374,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513374,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513374,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516466,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516466,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516466,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516466,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":50}} {"type":"step/start","data":{"turn":1,"step":51}} -{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513395,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513395,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513395,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516483,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516483,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}}},{"type":"chunk","time":1793866516483,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516483,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-floating-open","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F8\"}}"}} {"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-open"},"toolCallId":"cua-floating-open","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":51}} {"type":"step/start","data":{"turn":1,"step":52}} -{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513415,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513415,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513415,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516499,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516499,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516499,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516499,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-floating-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-list"},"toolCallId":"cua-floating-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}]"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":52}} {"type":"step/start","data":{"turn":1,"step":53}} -{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516515,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516515,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516515,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516515,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-floating-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} -{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-observe"},"toolCallId":"cua-floating-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-15\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 0\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":53}} {"type":"step/start","data":{"turn":1,"step":54}} -{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513453,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513453,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513453,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516531,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516531,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516531,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516531,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-floating-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} {"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-screenshot"},"toolCallId":"cua-floating-screenshot","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":10,\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":54}} {"type":"step/start","data":{"turn":1,"step":55}} -{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513493,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513493,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513493,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-complete-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516569,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516569,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-complete-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}"}}},{"type":"chunk","time":1793866516569,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516569,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-floating-complete-list","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\",\"includeHidden\":true}}"}} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-complete-list"},"toolCallId":"cua-floating-complete-list","content":[{"type":"text","text":"[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3},{\"windowId\":11,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Cached panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":false,\"onCurrentSpace\":true,\"layer\":3}]"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} -{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513513,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513513,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513513,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} -{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516586,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516586,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793866516586,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516586,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-floating-refresh","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-refresh"},"toolCallId":"cua-floating-refresh","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":null,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=application offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} {"type":"step/start","data":{"turn":1,"step":57}} -{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513535,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513535,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} -{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-16\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516603,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516603,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1793866516603,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516603,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":57,"callId":"cua-floating-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10,\"snapshotId\":\"fixture-snapshot-15\",\"x\":0,\"y\":0}}"}} +{"type":"tool/result","data":{"turn":1,"step":57,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-click"},"toolCallId":"cua-floating-click","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:117}}"}},"sourceEventSeqs":[294],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":57}} {"type":"step/start","data":{"turn":1,"step":58}} -{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513564,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513564,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513564,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":58,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:118}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516619,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516619,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}}},{"type":"chunk","time":1793866516619,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516619,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":58,"callId":"cua-floating-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":10}}"}} +{"type":"tool/result","data":{"turn":1,"step":58,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-floating-verify"},"toolCallId":"cua-floating-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":10,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-17\",\"tree\":\"AX scope=window offsets=UTF-16\\n- AXWindow \\\"Floating panel\\\"\\n - [0] AXButton \\\"Increment floating panel\\\"\\n - AXStaticText \\\"Floating count: 1\\\"\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":10,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Floating panel\",\"bounds\":{\"x\":100,\"y\":120,\"width\":240,\"height\":140},\"isOnScreen\":true,\"onCurrentSpace\":true,\"layer\":3}],\"truncated\":false}"}],"isError":false,"id":"{{message:119}}"}},"sourceEventSeqs":[299],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":58}} {"type":"step/start","data":{"turn":1,"step":59}} -{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513582,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513582,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513582,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":59,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:120}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516635,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516635,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1793866516635,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516635,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":59,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":59,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true,\"verified\":false}"}],"isError":false,"id":"{{message:121}}"}},"sourceEventSeqs":[304],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":59}} {"type":"step/start","data":{"turn":1,"step":60}} -{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513611,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513611,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513611,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":60,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:122}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516651,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516651,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793866516651,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516651,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":60,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":60,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:123}}"}},"sourceEventSeqs":[309],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":60}} {"type":"step/start","data":{"turn":1,"step":61}} -{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513776,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513776,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513776,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":61,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:124}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516670,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516670,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1793866516670,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516670,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":61,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":61,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:125}}"}},"sourceEventSeqs":[314],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":61}} {"type":"step/start","data":{"turn":1,"step":62}} -{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513949,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792564513949,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513949,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":62,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:126}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516810,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516810,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1793866516810,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516810,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":62,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":62,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"pid\":17,\"name\":\"Revocable Fixture\"}"}],"isError":false,"id":"{{message:127}}"}},"sourceEventSeqs":[319],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":62}} {"type":"step/start","data":{"turn":1,"step":63}} -{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1792564513967,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1792564513967,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1792564513967,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":63,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:128}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516960,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793866516960,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1793866516960,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516960,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":63,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":63,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:129}}"}},"sourceEventSeqs":[324],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":63}} +{"type":"step/start","data":{"turn":1,"step":64}} +{"type":"assistant/message","data":{"turn":1,"step":64,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:130}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793866516975,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1793866516975,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested. The separately captured floating panel received one click after its window list was refreshed; keyboard focus stayed in the main window."}}},{"type":"chunk","time":1793866516975,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793866516975,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":64}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 5542f1e18d..1f0a2ecc89 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -37,7 +37,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -49,7 +49,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 658035fe87..68cfa13e7e 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -264,6 +264,10 @@ "appHandle": { "type": "string", "minLength": 1 + }, + "includeHidden": { + "description": "Include offscreen and zero-size windows for explicit selection or restoration.", + "type": "boolean" } }, "required": [ diff --git a/snapshots/session/cua-ptc/session.v4.jsonl b/snapshots/session/cua-ptc/session.v4.jsonl index 78309a521e..346715c359 100644 --- a/snapshots/session/cua-ptc/session.v4.jsonl +++ b/snapshots/session/cua-ptc/session.v4.jsonl @@ -17,7 +17,7 @@ {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:1","name":"cua","arguments":{"method":"getApp","params":{"selector":"test.fixture"}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"name\":\"Fixture\",\"bundleId\":\"test.fixture\"}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}}}} -{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} +{"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:2","name":"cua","arguments":{"method":"getState","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"pid\":9,\"windowId\":7,\"focusedWindowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":9,\"pid\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}]}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:3","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}}}} {"type":"tool/ptc-dispatch","data":{"rootCallId":"cua-ptc-native-result","parentCallId":"cua-ptc-native-result","subCallId":"cua-ptc-native-result:ptc:3","name":"cua","arguments":{"method":"screenshot","params":{"appHandle":"fixture-app","windowId":7}},"isError":false,"content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}]}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-ptc-native-result"},"toolCallId":"cua-ptc-native-result","content":[{"type":"text","text":"{\n \"appHandle\": \"fixture-app\",\n \"hasIncrement\": true,\n \"pngBytes\": 90,\n \"signature\": \"89504e470d0a1a0a\",\n \"imageWidth\": 1,\n \"imageHeight\": 1\n}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 83a083cf45..23e211d6a4 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -39,7 +39,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Independent floating panels have their own window IDs. After opening one, refresh app.getWindows() and select its window for AX, screenshots and input; a panel may leave keyboard focus in the main window. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -51,7 +51,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result From 261a86a1087c94aab090e87861443a605263c0b1 Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 16:17:02 +0800 Subject: [PATCH 014/438] 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 1e90c99c48cb9e6bc2f3fafbfbea85ec122de9fa Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:17:45 +0800 Subject: [PATCH 015/438] test(subagent): inspect pending input through public Inbox fields --- packages/subagent/subagent/tests/factory-settlement.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index ed339efca6..0228655cc5 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -47,7 +47,7 @@ it.each([false, true])('settles an activation after factory unload with queue-cl } }) await loop.dispose() - expect(child.inbox.hasPending).toBe(rejectQueueClear) + expect(child.inbox.nextStep.length + child.inbox.nextTurn.length > 0).toBe(rejectQueueClear) rejectClear() expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) From 477ca41b357b1a05d0d11f79f7c838f4004bab80 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:23:44 +0800 Subject: [PATCH 016/438] fix(ci): use block bodies for void admission callbacks --- packages/core/agent-loop/src/agent.ts | 2 +- packages/core/agent-loop/tests/input-lifecycle.spec.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 12464720ae..874739d7e1 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -148,7 +148,7 @@ export class ReactLoopAgent implements Agent { this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx this.model = new AgentModel(projections.modelSelection, session, options) - this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => this.assertOpen()) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => { this.assertOpen() }) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 3cdb06da2c..e3f095da28 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -71,7 +71,7 @@ it('cancellation still aborts the running request when queue clearing fails', as if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn' && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure') }) - expect(() =>{ agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') + expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') expect(signal.aborted).toBe(true) } finally { stopRejecting() @@ -96,7 +96,7 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') - for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => agent.inbox.append('next-turn', message), () => agent.inbox.prepend('next-step', message), () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { + for (const submit of [() => { agent.followup(message) }, () => { agent.steer(message) }, () => { agent.inject(message) }, () => { agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => { agent.inbox.append('next-turn', message) }, () => { agent.inbox.prepend('next-step', message) }, () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) From 7faa643f4674653f492141ff86d36b78eb8a85ae Mon Sep 17 00:00:00 2001 From: creatixchu Date: Thu, 5 Nov 2026 16:28:00 +0800 Subject: [PATCH 017/438] test(cua): refresh the retained script prompt for window discovery --- .../session/ptc-script-retained/system-prompt.expected.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 6f5b16bfa1..c7bf71c48f 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -39,7 +39,7 @@ Use cua with method getCapabilities and params {} to inspect permissions and ses Initialize the object API once in persistent PTC. Reuse its variables in later calls; put temporary declarations inside { ... } blocks to avoid redeclaration errors. All object methods are async. getAXState returns text, not a structured state object. Its text separates values and placeholders, and reports subroles, help, URLs, disabled/focused/selected/expanded state and UTF-16 selection ranges when available. Writability is true, false or unknown on relevant controls; omitted state fields do not assert false. selection=unavailable means the reported range exceeds the observed text. Compact output omits ordinary Press/Pick (click), ShowMenu (right click) and ScrollToVisible actions; details=true lists every available action. Use the displayed action name with performSecondaryAction; ambiguous aliases require the complete name from details=true. Truncation reports the reached provider limit. Narrow the window or increase that provider limit before reading again. -Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole such window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. +Use app methods directly for single-window tasks; getApp already reads initial AX state. Call app.getWindows() and await app.getWindow(windowId) only to target a particular window or resolve ambiguous window selection. App screenshots and coordinate actions use the latest AX observation: its focused on-screen, nonzero-size window, otherwise the sole visible normal-layer window. They do not refresh focus automatically. Read app.getAXState() to follow changed focus. Visible panels, menus, tooltips and status items can have their own window IDs. Select a panel from app.getWindows() for its AX, screenshot and input even if the main window retains focus. Use includeHidden:true in listWindows or app.getWindows({includeHidden:true}) to list offscreen and zero-size windows. CuaScreenshot contains { bytes: Uint8Array, mimeType: "image/png" | "image/jpeg" | "image/webp" | "image/gif", pixelWidth: number, pixelHeight: number, windowId: number }. Use mimeType to choose a file extension or declare an image; do not assume PNG. @@ -51,7 +51,7 @@ Object API signatures (options default to { emit: true }): - cua.getState(options?) -> { apps, browsers: [] } - cua.getApp(selector: string) -> App - app.activate() -> { dispatched: true, verified: false } -- app.getWindows(options?) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace }> +- app.getWindows(options?: { emit?: boolean, includeHidden?: boolean }) -> Array<{ windowId, pid, appName, title, bounds, isOnScreen, onCurrentSpace, layer? }> - app.getWindow(windowId: number) -> Window - app.typeText(text: string), app.pressKey(chord: string) -> action result - app.paste(text: string, options?: { format?: "text" | "html" }) -> action result From 7512ac4ce4ad63c8cdf940a8141308abd8f247d6 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:29:26 +0800 Subject: [PATCH 018/438] test(subagent): cover closure before settlement maintenance --- .../subagent/tests/continuation.spec.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..627f0f085e 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -8,7 +8,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { liveConfig } from '../../../settings/settings/tests/live-config.ts' import type { Agent } from '@deepseek-ai/dsh-agent' -import { agentEvents } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' @@ -2570,6 +2570,22 @@ describe('continuable review regressions', () => { expect(managerState(ctx).resident.get(started.childId)).toBeUndefined() }) + it('settles when Agent admission closes before settlement maintenance starts', async () => { + const release = Promise.withResolvers() + const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) + const { ctx, parent } = await setupWith(adapter) + const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + const child = ctx.agents.get(started.childId)! + const maintenance = vi.spyOn(child, 'runMaintenance').mockImplementation(() => { + throw new AgentClosedError(child.id) + }) + release.resolve(undefined) + await waitNoActivation(ctx, started.childId) + expect(maintenance).toHaveBeenCalledTimes(1) + expect(await started.result).toMatchObject({ stopReason: 'completed' }) + }) + it('keeps a maintenance task that claimed the idle phase after whenIdle resolved', async () => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) From fe57dfce386d35c61ab1001722ec78f3dc0fe921 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:40:17 +0800 Subject: [PATCH 019/438] test(agent): cover quiescence failure during disposal --- .../core/agent-loop/tests/input-lifecycle.spec.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index e3f095da28..9a61005689 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -166,3 +166,16 @@ it('does not start a driver when an inbox observer closes its owner during admis await closing } }) + +it('reports a quiescence failure while releasing the Agent and Session', async () => { + const { ctx, agent, handle } = await harness() + const failure = new Error('injected quiescence failure') + const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure) + try { + await expect(handle.dispose()).rejects.toThrow('injected quiescence failure') + expect(ctx.agents.get(agent.id)).toBeUndefined() + expect(ctx.sessions.get(agent.id)).toBeUndefined() + } finally { + idle.mockRestore() + } +}) From e530b606e5a0c3f2d92a15f7a1c8e4c23120be5d Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:45:56 +0800 Subject: [PATCH 020/438] test(agent): retain resources through interrupted creation listeners --- .../agent-loop/tests/input-lifecycle.spec.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 9a61005689..560fea3ca1 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -179,3 +179,30 @@ it('reports a quiescence failure while releasing the Agent and Session', async ( idle.mockRestore() } }) + +it('keeps creation resources alive until an interrupted creation listener finishes', async () => { + const { ctx } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const signal = new AbortController() + const id = SessionId('interrupted-announcement') + const stop = ctx.on('agent/created', async ({ agent }) => { + if (agent.id !== id) return + entered.resolve(agent) + await release.promise + }) + const creation = ctx.agents.create({ sessionId: id, agentOptions: { provider: 'mock', model: 'mock' }, signal: signal.signal }) + .then(handle => handle.dispose(), (error: unknown) => error) + try { + const agent = await entered.promise + signal.abort(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBe(agent.session) + release.resolve(undefined) + expect(await creation).toEqual(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBeUndefined() + } finally { + release.resolve(undefined) + await creation + stop() + } +}) From 9dc9f76702eef1dbd0474908591acf75567f7cb8 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 17:06:51 +0800 Subject: [PATCH 021/438] test(session): refresh terminal panel runtime context reminder --- snapshots/session/terminal-panel-tools/session.v4.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapshots/session/terminal-panel-tools/session.v4.jsonl b/snapshots/session/terminal-panel-tools/session.v4.jsonl index 01574413c3..290e17f9f6 100644 --- a/snapshots/session/terminal-panel-tools/session.v4.jsonl +++ b/snapshots/session/terminal-panel-tools/session.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"My tests fail in my terminal. What does it say?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"session/title","data":{"title":"My tests fail in my","messageSeqs":[8],"source":{"kind":"fallback"}}} From e9591154b4919682faf539e5ea48951d189b3eae Mon Sep 17 00:00:00 2001 From: Turtle Date: Thu, 5 Nov 2026 17:57:11 +0800 Subject: [PATCH 022/438] 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 023/438] 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 8fb05c7f79552ec2442c060ce7760d3eadf5b656 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Thu, 5 Nov 2026 22:53:30 +0800 Subject: [PATCH 024/438] test(ci): remove two flaky-test causes in gh fixture and Web e2e The fake gh `sleep` case ran sleep as a child of /bin/sh. execa's deadline killed only the shell, and the orphaned sleep held stdout/stderr open, so execa waited about 5s for close and the 5000ms Vitest case timed out. Exec the sleep so the killed process is the one holding the pipes. The fresh round trip e2e read the pre-accept composer state one frame after dispatching Enter, racing the Host's acceptance of the prompt POST under load. Hold /api/session/prompt at the browser boundary, read and compare the snapshot, then release the POST and assert the accepted state. --- apps/web/tests/replay-round-trip.e2e.ts | 29 ++++++++++++++----- .../forge-github/tests/gh.spec.ts | 2 +- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 82f436c837..adfea25d10 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -124,14 +124,24 @@ describe('web e2e: fresh round trip through the real assembly', () => { let accepted = false try { await input.fill(PROMPT) + // Hold the prompt POST at the browser boundary so the Host cannot accept + // the message before the pre-accept snapshot is read. + const promptSent = Promise.withResolvers() + const releasePrompt = Promise.withResolvers() + const holdPrompt = async (route: Route): Promise => { + promptSent.resolve(undefined) + await releasePrompt.promise + await route.continue() + } + await page.route('**/api/session/prompt', holdPrompt, { times: 1 }) const admitted = page.waitForResponse('**/api/session/prompt') - const [echoSnapshot, response] = await Promise.all([ - input.evaluate(async (element, prompt) => { + try { + const echoCapture = input.evaluate(async (element, prompt) => { element.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true, })) - // sendSession registered its paint yield first. This frame observes the - // composer holding the message while the Host has not accepted it yet. + // sendSession registered its paint yield first; this frame observes the + // composer holding the message while the POST is still held. await new Promise((resolve) => { requestAnimationFrame(() => { resolve() }) }) const echo = document.querySelector('[data-submission-echo]') return [ @@ -139,12 +149,15 @@ describe('web e2e: fresh round trip through the real assembly', () => { `composer: ${JSON.stringify(element.textContent ?? '')}`, `contenteditable: ${element.getAttribute('contenteditable')}`, ].join('\n') - }, PROMPT), - admitted, - ]) + }, PROMPT) + await promptSent.promise + await compareOrRefreshGolden(ECHO_EXPECTED, await echoCapture, MODE) + } finally { + releasePrompt.resolve(undefined) + } + const response = await admitted expect(await response.json()).toMatchObject({ result: { ok: true, value: { accepted: true } } }) accepted = true - await compareOrRefreshGolden(ECHO_EXPECTED, echoSnapshot, MODE) // Acceptance publishes the echo and clears the composer; maintenance keeps the Turn from starting. await page.locator('[data-submission-echo]', { hasText: PROMPT }).waitFor() await expect.poll(() => input.textContent()).toBe('') diff --git a/packages/experimental/forge-github/tests/gh.spec.ts b/packages/experimental/forge-github/tests/gh.spec.ts index 84246e36ac..e732b009d5 100644 --- a/packages/experimental/forge-github/tests/gh.spec.ts +++ b/packages/experimental/forge-github/tests/gh.spec.ts @@ -24,7 +24,7 @@ async function fakeGh(): Promise { ' echo) printf "%s|" "$@"; printf "\\nprompt=%s token=%s pager=[%s]\\n" "$GH_PROMPT_DISABLED" "${GH_TOKEN:-unset}" "$GH_PAGER" ;;', ' input) cat ;;', ' fail) echo oops >&2; exit 3 ;;', - ' sleep) sleep 5 ;;', + ' sleep) exec sleep 5 ;;', ' big) head -c 5000 /dev/zero | tr "\\0" x ;;', 'esac', '', From 4e4b4eb9b6e67942b866a637f64a0e9165eb7aef Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:28:29 +0800 Subject: [PATCH 025/438] feat(fs): classify host errno failures as FsError dsh-fs gains fsErrorFromErrno, which classifies a host errno failure: ENOENT/ENOTDIR -> FS_NOT_FOUND, EACCES/EPERM -> FS_PERMISSION_DENIED, EISDIR -> FS_NOT_REGULAR_FILE, other errno -> FS_IO_ERROR, keeping the original error as cause. fs-local uses it for resolution, metadata, reads, and listing, and fs-sandbox for its containment check, so tool results persist error.info instead of a raw Node error. FsError assigns its literal name, and FS_ERROR_CODES gains FS_ALREADY_EXISTS for create-only commands. --- docs/subsystems/filesystem.i18n.yaml | 4 +- docs/subsystems/filesystem.md | 2 +- docs/subsystems/filesystem.zh.md | 2 +- packages/fs/fs-local/README.i18n.yaml | 4 +- packages/fs/fs-local/README.md | 2 +- packages/fs/fs-local/README.zh.md | 2 +- packages/fs/fs-local/src/fsio.ts | 59 ++++++++----------- packages/fs/fs-local/tests/fsio.spec.ts | 41 +++++++++++++ packages/fs/fs-sandbox/src/containment.ts | 6 +- .../fs/fs-sandbox/tests/containment.spec.ts | 8 +++ packages/fs/fs/README.i18n.yaml | 8 +-- packages/fs/fs/README.md | 3 +- packages/fs/fs/README.zh.md | 3 +- packages/fs/fs/src/errno.ts | 33 +++++++++++ packages/fs/fs/src/index.ts | 1 + packages/fs/fs/src/types.ts | 2 + packages/fs/fs/tests/errno.spec.ts | 30 ++++++++++ 17 files changed, 157 insertions(+), 53 deletions(-) create mode 100644 packages/fs/fs/src/errno.ts create mode 100644 packages/fs/fs/tests/errno.spec.ts diff --git a/docs/subsystems/filesystem.i18n.yaml b/docs/subsystems/filesystem.i18n.yaml index 03d12b8456..09a886a568 100644 --- a/docs/subsystems/filesystem.i18n.yaml +++ b/docs/subsystems/filesystem.i18n.yaml @@ -30,8 +30,8 @@ en: 7b462db42ab89b10 zh: 968219ded2b55d69 /filesystem/error-taxonomy-provider-contract: - en: ca206569d4e2528d - zh: e36d70ad39a73570 + en: dbab88fbb60fcb8f + zh: f90be1352b1e05f8 /filesystem/no-timeouts-on-file-io: en: ae18af906f3f7e50 zh: 24a1aa6f903fe08d diff --git a/docs/subsystems/filesystem.md b/docs/subsystems/filesystem.md index fcbbec29cd..f19f09ab43 100644 --- a/docs/subsystems/filesystem.md +++ b/docs/subsystems/filesystem.md @@ -375,7 +375,7 @@ import { FS_ERROR_CODES } from '@deepseek-ai/dsh-fs' type FsErrorCode = typeof FS_ERROR_CODES[number] ``` -`FS_NOT_DIRECTORY`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR` are used by directory listing to distinguish an existing non-directory target, a denied listing, and an unexpected backend I/O failure. `FS_SANDBOX_DENIED` is a POLICY refusal from a sandbox-enforcing backend (`dsh-fs-sandbox`) — the mode fence denied a mutation — distinct from `FS_PERMISSION_DENIED` (the host kernel refusing). `FS_NOT_OBSERVED` means the policy plugin has no prior-observation record for this owner (or a `createIfAbsent` hit an existing file). `FS_NOT_FOUND` also represents an edit rejected from confirmed absence. `FS_STALE_VERSION` means the backend version no longer matches the observed one (or the provider itself receives an edit for a missing target). Freshness authorization has no partial/full distinction, so there is no `FS_PARTIAL_OBSERVATION`. +`FS_NOT_DIRECTORY`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR` are used by directory listing to distinguish an existing non-directory target, a denied listing, and an unexpected backend I/O failure. `FS_SANDBOX_DENIED` is a POLICY refusal from a sandbox-enforcing backend (`dsh-fs-sandbox`) — the mode fence denied a mutation — distinct from `FS_PERMISSION_DENIED` (the host kernel refusing). `FS_NOT_OBSERVED` means the policy plugin has no prior-observation record for this owner (or a `createIfAbsent` hit an existing file). `FS_NOT_FOUND` also represents an edit rejected from confirmed absence. `FS_STALE_VERSION` means the backend version no longer matches the observed one (or the provider itself receives an edit for a missing target). Freshness authorization has no partial/full distinction, so there is no `FS_PARTIAL_OBSERVATION`. `FS_ALREADY_EXISTS` means a create-only tool command found an existing target; the caller chooses another path or edits the existing file. `dsh-fs-local` and the `dsh-fs-sandbox` containment check classify errno failures from resolution, metadata, reads, and listing with the `dsh-fs` function `fsErrorFromErrno`: `ENOENT` and `ENOTDIR` report `FS_NOT_FOUND`, `EACCES` and `EPERM` report `FS_PERMISSION_DENIED`, `EISDIR` reports `FS_NOT_REGULAR_FILE`, and other errno values report `FS_IO_ERROR`, each with the Node error as `cause`. ## No timeouts on file IO diff --git a/docs/subsystems/filesystem.zh.md b/docs/subsystems/filesystem.zh.md index 22f59a7884..8de900b9bd 100644 --- a/docs/subsystems/filesystem.zh.md +++ b/docs/subsystems/filesystem.zh.md @@ -375,7 +375,7 @@ import { FS_ERROR_CODES } from '@deepseek-ai/dsh-fs' type FsErrorCode = typeof FS_ERROR_CODES[number] ``` -目录列表使用 `FS_NOT_DIRECTORY`、`FS_PERMISSION_DENIED` 与 `FS_IO_ERROR` 区分已存在但并非目录的目标、被拒绝的列表操作和意外的后端 I/O 失败。`FS_SANDBOX_DENIED` 是强制执行沙箱的后端(`dsh-fs-sandbox`)所作的策略拒绝——模式边界拒绝了变更——与 `FS_PERMISSION_DENIED`(宿主内核拒绝)不同。`FS_NOT_OBSERVED` 表示策略插件没有此所有者的先前观测记录(或 `createIfAbsent` 遇到了现有文件)。`FS_NOT_FOUND` 也表示策略因确认缺失而拒绝 edit。`FS_STALE_VERSION` 表示后端版本不再与观测到的版本匹配(或提供方本身收到针对缺失目标的 edit)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。 +目录列表使用 `FS_NOT_DIRECTORY`、`FS_PERMISSION_DENIED` 与 `FS_IO_ERROR` 区分已存在但并非目录的目标、被拒绝的列表操作和意外的后端 I/O 失败。`FS_SANDBOX_DENIED` 是强制执行沙箱的后端(`dsh-fs-sandbox`)所作的策略拒绝——模式边界拒绝了变更——与 `FS_PERMISSION_DENIED`(宿主内核拒绝)不同。`FS_NOT_OBSERVED` 表示策略插件没有此所有者的先前观测记录(或 `createIfAbsent` 遇到了现有文件)。`FS_NOT_FOUND` 也表示策略因确认缺失而拒绝 edit。`FS_STALE_VERSION` 表示后端版本不再与观测到的版本匹配(或提供方本身收到针对缺失目标的 edit)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。`FS_ALREADY_EXISTS` 表示仅创建的工具命令遇到了已存在的目标;调用方应换一个路径或编辑现有文件。`dsh-fs-local` 与 `dsh-fs-sandbox` 的包含性检查用 `dsh-fs` 的函数 `fsErrorFromErrno` 分类解析、元数据、读取与目录列表中的 errno 失败:`ENOENT` 与 `ENOTDIR` 报告 `FS_NOT_FOUND`,`EACCES` 与 `EPERM` 报告 `FS_PERMISSION_DENIED`,`EISDIR` 报告 `FS_NOT_REGULAR_FILE`,其他 errno 报告 `FS_IO_ERROR`,均以 Node 错误为 `cause`。 ## 文件 IO 不设超时 diff --git a/packages/fs/fs-local/README.i18n.yaml b/packages/fs/fs-local/README.i18n.yaml index ca5f575769..4c9e8ec1ef 100644 --- a/packages/fs/fs-local/README.i18n.yaml +++ b/packages/fs/fs-local/README.i18n.yaml @@ -24,8 +24,8 @@ en: ca0cfe83eca367c0 zh: 9d3a6d61952f180e /deepseek-ai-dsh-fs-local/use-this-package/what-you-can-do: - en: 04b6889eec28bd96 - zh: e94e2787de0ba704 + en: 0f05ec25037a6d39 + zh: d67d80a04c148f3b /deepseek-ai-dsh-fs-local/understand-the-implementation: en: 6ffc93e09381bd3d zh: 57c3192c26a080ef diff --git a/packages/fs/fs-local/README.md b/packages/fs/fs-local/README.md index 132dc626e6..f2846682d7 100644 --- a/packages/fs/fs-local/README.md +++ b/packages/fs/fs-local/README.md @@ -52,7 +52,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a Read regular UTF-8 files whole or as streams, read bounded bytes, and list one directory level. Writes, literal edits, patches, and deletions serialize per target. Moves lock both targets in lexical order. `patchText` checks the version before calling `applyHunks`; `deleteFile` removes only a regular file. Missing sources use `FS_STALE_VERSION`, unmatched hunks use `FS_PATCH_MISMATCH`, and identical move targets use `FS_SAME_TARGET`. -Patch and move text is LF-normalized internally and restored using the source line-ending style; outcome text uses LF. Delete bases and overwritten destination bases follow `diffBasisMaxBytes`. A move checks cancellation before staging the destination, then completes both effects; a source-removal failure returns the published destination with `sourceDeleted: false`. Atomic write failures map denied directory or staging creation to `FS_PERMISSION_DENIED` and other Node I/O errors to `FS_IO_ERROR`. +Patch and move text is LF-normalized internally and restored using the source line-ending style; outcome text uses LF. Delete bases and overwritten destination bases follow `diffBasisMaxBytes`. A move checks cancellation before staging the destination, then completes both effects; a source-removal failure returns the published destination with `sourceDeleted: false`. Atomic write failures map denied directory or staging creation to `FS_PERMISSION_DENIED` and other Node I/O errors to `FS_IO_ERROR`. Resolution, metadata, read, and listing failures pass through `fsErrorFromErrno` from `dsh-fs`, so every errno becomes an `FsError` code; a thrown value without an errno code is a defect and propagates unchanged. Read, listing, and mutation failures are typed `FsError`s with stable codes — `FS_NOT_FOUND`, `FS_NOT_TEXT` (binary content), `FS_STALE_VERSION` (changed since observation), `FS_EDIT_NOT_FOUND` or `FS_AMBIGUOUS_EDIT` (no unique literal match), and others — so callers branch on the code, never on message text. A missing target on an edit reports `FS_STALE_VERSION` whether or not the version guard is supplied. diff --git a/packages/fs/fs-local/README.zh.md b/packages/fs/fs-local/README.zh.md index edbf6a7da1..d1abde6841 100644 --- a/packages/fs/fs-local/README.zh.md +++ b/packages/fs/fs-local/README.zh.md @@ -52,7 +52,7 @@ kind: "package-reference" 完整或流式读取普通 UTF-8 文件、读取有界字节,并列出一层目录。写入、字面量编辑、补丁和删除按目标串行化。移动按字典序锁定两端。`patchText` 在调用 `applyHunks` 前检查版本;`deleteFile` 只删除普通文件。源缺失使用 `FS_STALE_VERSION`,hunk 不匹配使用 `FS_PATCH_MISMATCH`,移动两端相同使用 `FS_SAME_TARGET`。 -补丁与移动的文本在内存中规范化为 LF,写回时还原源文件的行尾风格;结果文本使用 LF。删除基线和被覆盖目标的基线遵循 `diffBasisMaxBytes`。移动在暂存目标前检查取消,随后完成两个效果;源删除失败返回已发布目标及 `sourceDeleted: false`。原子写入失败时,目录或临时目录创建被拒绝映射为 `FS_PERMISSION_DENIED`,其他 Node I/O 错误映射为 `FS_IO_ERROR`。 +补丁与移动的文本在内存中规范化为 LF,写回时还原源文件的行尾风格;结果文本使用 LF。删除基线和被覆盖目标的基线遵循 `diffBasisMaxBytes`。移动在暂存目标前检查取消,随后完成两个效果;源删除失败返回已发布目标及 `sourceDeleted: false`。原子写入失败时,目录或临时目录创建被拒绝映射为 `FS_PERMISSION_DENIED`,其他 Node I/O 错误映射为 `FS_IO_ERROR`。解析、元数据、读取与目录列表失败经由 `dsh-fs` 的 `fsErrorFromErrno` 分类,因此每个 errno 都变为 `FsError` 错误码;不带 errno 码的抛出值属于缺陷,原样传播。 读取、列出与变更操作的失败是携带稳定错误码的类型化 `FsError`——`FS_NOT_FOUND`、`FS_NOT_TEXT`(二进制内容)、`FS_STALE_VERSION`(自观察以来已变化)、`FS_EDIT_NOT_FOUND` 或 `FS_AMBIGUOUS_EDIT`(无唯一字面量匹配)等——因此调用方依据错误码分支,绝不解析消息文本。编辑遇到缺失目标时,无论是否提供版本防护,都报告 `FS_STALE_VERSION`。 diff --git a/packages/fs/fs-local/src/fsio.ts b/packages/fs/fs-local/src/fsio.ts index a6e3da2bba..63da0a95f0 100644 --- a/packages/fs/fs-local/src/fsio.ts +++ b/packages/fs/fs-local/src/fsio.ts @@ -12,7 +12,7 @@ import type { BigIntStats, Dirent, Stats } from 'node:fs' import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path' import { TextDecoder, promisify } from 'node:util' import { homedir } from 'node:os' -import { FsError, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs' +import { FsError, FsTargetKey, FsVersion, fsErrorFromErrno } from '@deepseek-ai/dsh-fs' import { copyFileDaclWin32, replaceFileWin32 } from './win32.ts' const BINARY_SAMPLE_BYTES = 8192 @@ -62,13 +62,13 @@ function throwIfAborted(signal: AbortSignal | undefined, verb: string): void { * `readFile` with a bare `AbortError`, which would otherwise escape the seam's * error taxonomy — the streaming/write paths translate it the same way). */ -async function readFileAbortable(absolutePath: string, verb: 'read' | 'edit', signal?: AbortSignal): Promise { +async function readFileAbortable(absolutePath: string, displayPath: string, verb: 'read' | 'edit', signal?: AbortSignal): Promise { try { return await readFile(absolutePath, signal ? { signal } : {}) } catch (error: unknown) { - /* v8 ignore next 2 -- a non-abort readFile rejection needs a permission/IO fault racing an open file. */ - if (!isAbortError(error)) throw error - throw new FsError(`${verb} aborted`, 'FS_ABORTED') + /* v8 ignore next 2 -- a non-abort rejection needs a permission fault after a successful stat; POSIX covers it. */ + if (isAbortError(error)) throw new FsError(`${verb} aborted`, 'FS_ABORTED') + throw fsErrorFromErrno(verb, displayPath, error) } } @@ -188,8 +188,7 @@ export async function resolveLocalTarget(cwd: string, path: string): Promise( // ENOENT (no such file) and ENOTDIR (a parent segment is a file) both mean // the target is absent; any other metadata failure is a real permission/IO // fault. - /* v8 ignore next -- a non-ENOENT/ENOTDIR metadata failure needs a permission/IO fault; surface it. */ - if (!isENOENT(error) && !isENOTDIR(error)) throw error + if (!isENOENT(error) && !isENOTDIR(error)) throw fsErrorFromErrno('stat', absolutePath, error) return null } } @@ -291,16 +289,6 @@ export async function probeNoFollow(absolutePath: string): Promise { const identity = await resolveLocalTarget(parent.targetKey, name) return { displayPath: localDisplayPath(parent.displayPath, name), targetKey: identity.targetKey } @@ -320,7 +308,7 @@ export async function listDirectory(target: LocalTarget, signal?: AbortSignal): try { info = await probe(target.targetKey) } catch (error: unknown) { - throw listingIoError(target.displayPath, error) + throw fsErrorFromErrno('list', target.displayPath, error) } if (!info) throw new FsError(`cannot list "${target.displayPath}": not found`, 'FS_NOT_FOUND') if (info.type !== 'directory') throw new FsError(`cannot list "${target.displayPath}": not a directory`, 'FS_NOT_DIRECTORY') @@ -330,7 +318,7 @@ export async function listDirectory(target: LocalTarget, signal?: AbortSignal): entries = await readdir(target.targetKey, { withFileTypes: true, encoding: 'utf8' }) } catch (error: unknown) { /* v8 ignore next -- requires permission/kernel failure from readdir after a successful directory stat. */ - throw listingIoError(target.displayPath, error) + throw fsErrorFromErrno('list', target.displayPath, error) } throwIfAborted(signal, 'list') @@ -348,7 +336,7 @@ export async function listDirectory(target: LocalTarget, signal?: AbortSignal): ...(childInfo?.type === 'file' ? { size: childInfo.size } : {}), }) } catch (error: unknown) { - throw listingIoError(localDisplayPath(target.displayPath, entry.name), error) + throw fsErrorFromErrno('list', localDisplayPath(target.displayPath, entry.name), error) } throwIfAborted(signal, 'list') } @@ -392,9 +380,7 @@ async function statRegularFile(target: LocalTarget, verb: 'read', signal?: Abort try { info = await stat(target.targetKey) } catch (error: unknown) { - /* v8 ignore next 2 -- a non-ENOENT stat failure needs a permission/IO fault; only the not-found path is reachable in tests. */ - if (!isENOENT(error)) throw error - throw new FsError(`cannot ${verb} "${target.displayPath}": not found`, 'FS_NOT_FOUND') + throw fsErrorFromErrno(verb, target.displayPath, error) } if (!info.isFile()) throw new FsError(`cannot ${verb} "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE') return info @@ -409,7 +395,7 @@ async function statRegularFile(target: LocalTarget, verb: 'read', signal?: Abort */ export async function readWholeText(target: LocalTarget, signal?: AbortSignal): Promise { await statRegularFile(target, 'read', signal) - const raw = await readFileAbortable(target.targetKey, 'read', signal) + const raw = await readFileAbortable(target.targetKey, target.displayPath, 'read', signal) throwIfAborted(signal, 'read') if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) { throw new FsError(`cannot read "${target.displayPath}": binary file`, 'FS_NOT_TEXT') @@ -454,9 +440,9 @@ export async function readWholeBytes( chunks.push(chunk) } } catch (error: unknown) { - /* v8 ignore next 2 -- a mid-stream abort needs cancellation racing an active read; pre-abort is deterministic. */ + /* v8 ignore next -- a mid-stream abort needs cancellation racing an active read; pre-abort is deterministic. */ if (isAbortError(error)) throw new FsError('read aborted', 'FS_ABORTED') - throw error + throw fsErrorFromErrno('read', target.displayPath, error) } return Buffer.concat(chunks, bytes) } @@ -491,10 +477,10 @@ export async function readByteWindow( bytes += chunk.length } } catch (error: unknown) { - /* v8 ignore next 2 -- a mid-stream abort needs cancellation racing an active read; pre-abort is deterministic. */ + /* v8 ignore next -- a mid-stream abort needs cancellation racing an active read; pre-abort is deterministic. */ if (isAbortError(error)) throw new FsError('read aborted', 'FS_ABORTED') - /* v8 ignore next -- any other stream failure needs an I/O fault after a successful stat. */ - throw error + /* v8 ignore next -- needs a permission fault after a successful stat; Windows chmod cannot deny reads, POSIX covers it. */ + throw fsErrorFromErrno('read', target.displayPath, error) } return Buffer.concat(chunks, bytes) } @@ -529,9 +515,10 @@ export async function* streamWholeText(target: LocalTarget, signal?: AbortSignal } yield decodeUtf8Stream(decoder, undefined, 'read', target.displayPath) } catch (error: unknown) { - /* v8 ignore next 4 -- mid-stream errors need an abort/IO fault racing the loop; pre-abort is caught by throwIfAborted. */ + /* v8 ignore next -- a mid-stream abort needs cancellation racing an active read; pre-abort is caught by throwIfAborted. */ if (isAbortError(error)) throw new FsError('read aborted', 'FS_ABORTED') - throw error + /* v8 ignore next -- needs a permission fault after a successful stat; Windows chmod cannot deny reads, POSIX covers it. */ + throw fsErrorFromErrno('read', target.displayPath, error) } } @@ -776,7 +763,7 @@ export async function readForEdit( signal?: AbortSignal, ): Promise<{ content: string; lineEndings: LineEndings }> { throwIfAborted(signal, 'edit') - const buffer = await readFileAbortable(absolutePath, 'edit', signal) + const buffer = await readFileAbortable(absolutePath, displayPath, 'edit', signal) throwIfAborted(signal, 'edit') if (buffer.includes(0)) throw new FsError(`cannot edit "${displayPath}": binary file`, 'FS_NOT_TEXT') const raw = decodeUtf8(buffer, 'edit', displayPath) diff --git a/packages/fs/fs-local/tests/fsio.spec.ts b/packages/fs/fs-local/tests/fsio.spec.ts index e53e1e4b37..980f7a722c 100644 --- a/packages/fs/fs-local/tests/fsio.spec.ts +++ b/packages/fs/fs-local/tests/fsio.spec.ts @@ -15,8 +15,10 @@ import { listDirectory, probe, probeNoFollow, + readByteWindow, readForEdit, readTextForDiff, + readWholeBytes, readWholeText, resolveLocalTarget, restoreLineEndings, @@ -1035,3 +1037,42 @@ describe('atomic write failures', () => { }, ) }) + +describe('Node errno classification', () => { + it('classifies metadata, resolution, and read faults on a symlink loop', async () => { + const loop = join(dir, 'loop') + await symlink(loop, loop) + const ioError = { name: 'FsError', code: 'FS_IO_ERROR' } + await expect(probe(loop)).rejects.toMatchObject(ioError) + await expect(resolveLocalTarget(dir, 'loop')).rejects.toMatchObject(ioError) + await expect(readWholeText(localTarget(loop))).rejects.toMatchObject(ioError) + }) + + it('classifies a regular file replaced by a directory after the raw-read stat', async () => { + const file = join(dir, 'swap.bin') + await writeFile(file, 'bytes') + const failure = await readWholeBytes(localTarget(file), undefined, 1024, { + inspectReadBytesAfterStat: async () => { + await unlink(file) + await mkdir(file) + }, + }).then(() => undefined, (caught: unknown) => caught) + expect(failure).toBeInstanceOf(FsError) + expect(['FS_NOT_REGULAR_FILE', 'FS_IO_ERROR']).toContain((failure as FsError).code) + }) + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('maps unreadable file content to FS_PERMISSION_DENIED', async () => { + const file = join(dir, 'locked.txt') + await writeFile(file, 'secret') + await chmod(file, 0o000) + try { + const denied = { name: 'FsError', code: 'FS_PERMISSION_DENIED', message: `cannot read "${file}": permission denied` } + await expect(readWholeText(localTarget(file))).rejects.toMatchObject(denied) + await expect(collect(streamWholeText(localTarget(file)))).rejects.toMatchObject(denied) + await expect(readByteWindow(localTarget(file), { offset: 0, length: 4 })).rejects.toMatchObject(denied) + await expect(readForEdit(file, file)).rejects.toMatchObject({ code: 'FS_PERMISSION_DENIED', message: `cannot edit "${file}": permission denied` }) + } finally { + await chmod(file, 0o600) + } + }) +}) diff --git a/packages/fs/fs-sandbox/src/containment.ts b/packages/fs/fs-sandbox/src/containment.ts index 41b9bdd08a..d3706c3b9d 100644 --- a/packages/fs/fs-sandbox/src/containment.ts +++ b/packages/fs/fs-sandbox/src/containment.ts @@ -8,6 +8,7 @@ import type { BigIntStats } from 'node:fs' import { stat } from 'node:fs/promises' import { dirname, sep } from 'node:path' +import { fsErrorFromErrno } from '@deepseek-ai/dsh-fs' const MISSING_CODES: ReadonlySet = new Set(['ENOENT', 'ENOTDIR']) @@ -32,10 +33,8 @@ async function statIfPresent(path: string): Promise { try { return await stat(path, { bigint: true }) } catch (error: unknown) { - /* v8 ignore else -- a non-missing stat failure requires a host permission or I/O fault after resolve reached this ancestor. */ if (isMissing(error)) return undefined - /* v8 ignore next -- requires a host permission or I/O fault after resolve already reached this ancestor. */ - throw error + throw fsErrorFromErrno('stat', path, error) } } @@ -54,6 +53,7 @@ function sameIdentity(left: BigIntStats, right: BigIntStats): boolean { * @param caseSensitive - whether lexical comparison preserves case; defaults * to the host filesystem convention used by supported platforms. * @returns whether the target is the root or a descendant of it. + * @throws FsError when an ancestor or the root cannot be inspected, coded by the Node errno. */ export async function isPathUnder( path: string, diff --git a/packages/fs/fs-sandbox/tests/containment.spec.ts b/packages/fs/fs-sandbox/tests/containment.spec.ts index 35dc52029b..c77fbcf4d2 100644 --- a/packages/fs/fs-sandbox/tests/containment.spec.ts +++ b/packages/fs/fs-sandbox/tests/containment.spec.ts @@ -54,4 +54,12 @@ describe('filesystem sandbox containment', () => { await writeFile(blocker, 'not a directory') expect(await isPathUnder(join(blocker, 'child.txt'), allowed)).toBe(false) }) + + it('classifies an ancestor inspection fault as a filesystem error', async () => { + const root = join(base, 'root') + const loop = join(base, 'loop') + await mkdir(root) + await symlink(loop, loop) + await expect(isPathUnder(loop, root)).rejects.toMatchObject({ name: 'FsError', code: 'FS_IO_ERROR' }) + }) }) diff --git a/packages/fs/fs/README.i18n.yaml b/packages/fs/fs/README.i18n.yaml index 7e3bfe3472..8f15755d9e 100644 --- a/packages/fs/fs/README.i18n.yaml +++ b/packages/fs/fs/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8e2f904a21ba4dfb zh: 76d9ce7503c84a5c /deepseek-ai-dsh-fs/use-this-package/what-the-service-lets-you-do: - en: 637fc69ab6f6d19f - zh: 0fceafe5b38a06a1 + en: 5781e5a173192374 + zh: a3fa379ea951921d /deepseek-ai-dsh-fs/understand-the-implementation: en: 7e13d669ecc96d59 zh: b5fe7ae65812d926 @@ -30,8 +30,8 @@ en: 955232f787df6d64 zh: ab572b040ab3554e /deepseek-ai-dsh-fs/understand-the-implementation/source-map: - en: 9507d7d9259fc89e - zh: aa500435e02e6de3 + en: 8ab63fdfa9f95759 + zh: bb88918900d7458b /deepseek-ai-dsh-fs/understand-the-implementation/how-a-call-flows: en: 3cefede64907731c zh: 529ef3851c2fb5c1 diff --git a/packages/fs/fs/README.md b/packages/fs/fs/README.md index 949a453d2c..e2fe18a41c 100644 --- a/packages/fs/fs/README.md +++ b/packages/fs/fs/README.md @@ -33,7 +33,7 @@ Pick [`fs-local`](../fs-local/README.md) for ordinary host files or [`fs-sandbox ### What the service lets you do -Through `ctx.fs`, resolve paths, read text or bounded bytes, list direct children, and perform guarded mutations. `patchText` applies parsed hunks under the same lock as its version check. `deleteFile` removes a regular file. `moveFile` locks both targets, optionally patches the source text, publishes the destination, then removes the source. Guards are optional: omission mutates the current state unconditionally. Failures carry stable `FsError` codes from the runtime `FS_ERROR_CODES` list, which transport validators reuse. +Through `ctx.fs`, resolve paths, read text or bounded bytes, list direct children, and perform guarded mutations. `patchText` applies parsed hunks under the same lock as its version check. `deleteFile` removes a regular file. `moveFile` locks both targets, optionally patches the source text, publishes the destination, then removes the source. Guards are optional: omission mutates the current state unconditionally. Failures carry stable `FsError` codes from the runtime `FS_ERROR_CODES` list, which transport validators reuse. Host-backed providers, currently `dsh-fs-local` and the `dsh-fs-sandbox` containment check, classify errno failures with `fsErrorFromErrno`: `ENOENT` and `ENOTDIR` become `FS_NOT_FOUND`, `EACCES` and `EPERM` become `FS_PERMISSION_DENIED`, `EISDIR` where a file is required becomes `FS_NOT_REGULAR_FILE`, and other errno values become `FS_IO_ERROR`, with the original error as `cause`. `watch(target, changed, signal)` reports invalidations for one file or a directory's direct entries. It resolves once observation is ready with an asynchronous close function that the caller must await. The signal cancels initialization; unsupported providers reject without polling. @@ -62,6 +62,7 @@ The contract is built on one separation and three commitments: |---|---| | [`src/index.ts`](src/index.ts) | Service definition: the abstract `FileSystem` class, the `ctx.fs` declaration, and the `fs/*` event vocabulary | | [`src/types.ts`](src/types.ts) | Vocabulary: `FsTarget`/`FsTargetKey`, `FsVersion`, `FsObservation`, `FsWriteIntent`, `FsError` and its codes | +| [`src/errno.ts`](src/errno.ts) | `fsErrorFromErrno`: errno classification into `FsError` codes | ### How a call flows diff --git a/packages/fs/fs/README.zh.md b/packages/fs/fs/README.zh.md index 90118d2ecf..5056198f1b 100644 --- a/packages/fs/fs/README.zh.md +++ b/packages/fs/fs/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" ### 服务能做什么 -通过 `ctx.fs` 可解析路径、读取文本或有界字节、列出直接子项并执行受防护变更。`patchText` 在版本检查的同一把锁内应用解析后的 hunk。`deleteFile` 删除普通文件。`moveFile` 锁定两端,按需修改源文本,发布目标后再删除源。防护是可选的:省略时无条件修改当前状态。失败携带运行时列表 `FS_ERROR_CODES` 中的稳定 `FsError` 错误码,传输校验器复用该列表。 +通过 `ctx.fs` 可解析路径、读取文本或有界字节、列出直接子项并执行受防护变更。`patchText` 在版本检查的同一把锁内应用解析后的 hunk。`deleteFile` 删除普通文件。`moveFile` 锁定两端,按需修改源文本,发布目标后再删除源。防护是可选的:省略时无条件修改当前状态。失败携带运行时列表 `FS_ERROR_CODES` 中的稳定 `FsError` 错误码,传输校验器复用该列表。基于宿主文件系统的提供方(目前是 `dsh-fs-local` 与 `dsh-fs-sandbox` 的包含性检查)用 `fsErrorFromErrno` 分类 errno 失败:`ENOENT` 与 `ENOTDIR` 变为 `FS_NOT_FOUND`,`EACCES` 与 `EPERM` 变为 `FS_PERMISSION_DENIED`,需要文件却遇到目录的 `EISDIR` 变为 `FS_NOT_REGULAR_FILE`,其他 errno 变为 `FS_IO_ERROR`,原错误作为 `cause`。 `watch(target, changed, signal)` 报告单个文件或目录直接子项的失效通知。观察就绪后,它返回调用方必须等待完成的异步关闭函数。signal 取消初始化;不支持监听的提供方直接拒绝,不使用轮询。 @@ -62,6 +62,7 @@ kind: "package-reference" |---|---| | [`src/index.ts`](src/index.ts) | 服务定义:抽象 `FileSystem` 类、`ctx.fs` 声明与 `fs/*` 事件词汇 | | [`src/types.ts`](src/types.ts) | 词汇:`FsTarget`/`FsTargetKey`、`FsVersion`、`FsObservation`、`FsWriteIntent`、`FsError` 及其错误码 | +| [`src/errno.ts`](src/errno.ts) | `fsErrorFromErrno`:把 errno 分类为 `FsError` 错误码 | ### 调用流程 diff --git a/packages/fs/fs/src/errno.ts b/packages/fs/fs/src/errno.ts new file mode 100644 index 0000000000..5378ef58bd --- /dev/null +++ b/packages/fs/fs/src/errno.ts @@ -0,0 +1,33 @@ +/** + * Classification of host errno failures into the shared filesystem codes. + * @module @deepseek-ai/dsh-fs/errno + */ + +import { FsError } from './types.ts' + +/** + * Classify a host filesystem rejection by its errno `code`: ENOENT and ENOTDIR become `FS_NOT_FOUND`, + * EACCES and EPERM `FS_PERMISSION_DENIED`, EISDIR (a directory where a file is required) + * `FS_NOT_REGULAR_FILE`, and any other errno `FS_IO_ERROR`, each with the original error as `cause`. + * Callers that give an errno a narrower meaning, such as absence during a probe, test for it first. + * @param operation - verb shown in the diagnostic, such as `read`, `stat`, or `list`. + * @param displayPath - caller-facing path shown in the diagnostic. + * @param error - the caught value. + * @returns the classified error; an `FsError` and a value without a string errno `code` (a defect) are returned unchanged. + */ +export function fsErrorFromErrno(operation: string, displayPath: string, error: unknown): unknown { + if (error instanceof FsError || !(error instanceof Error) || !('code' in error) || typeof error.code !== 'string') return error + const failure = `cannot ${operation} "${displayPath}"` + switch (error.code) { + case 'ENOENT': + case 'ENOTDIR': + return new FsError(`${failure}: not found`, 'FS_NOT_FOUND', { cause: error }) + case 'EACCES': + case 'EPERM': + return new FsError(`${failure}: permission denied`, 'FS_PERMISSION_DENIED', { cause: error }) + case 'EISDIR': + return new FsError(`${failure}: not a regular file`, 'FS_NOT_REGULAR_FILE', { cause: error }) + default: + return new FsError(`${failure}: ${error.message}`, 'FS_IO_ERROR', { cause: error }) + } +} diff --git a/packages/fs/fs/src/index.ts b/packages/fs/fs/src/index.ts index a49e7ff0e2..8baff464f9 100644 --- a/packages/fs/fs/src/index.ts +++ b/packages/fs/fs/src/index.ts @@ -27,6 +27,7 @@ import type { FsWriteOutcome, } from './types.ts' +export { fsErrorFromErrno } from './errno.ts' export { FS_ERROR_CODES, FsError, diff --git a/packages/fs/fs/src/types.ts b/packages/fs/fs/src/types.ts index 6ece2c04e4..ecc8b182e5 100644 --- a/packages/fs/fs/src/types.ts +++ b/packages/fs/fs/src/types.ts @@ -203,6 +203,7 @@ export const FS_ERROR_CODES = [ 'FS_ABORTED', 'FS_PATCH_MISMATCH', 'FS_SAME_TARGET', + 'FS_ALREADY_EXISTS', ] as const /** One machine-routable filesystem failure code from FS_ERROR_CODES. */ @@ -219,6 +220,7 @@ export class FsError extends HarnessError { constructor(message: string, code: FsErrorCode, options?: ErrorOptions) { super(message, code, options) + this.name = 'FsError' this.code = code } } diff --git a/packages/fs/fs/tests/errno.spec.ts b/packages/fs/fs/tests/errno.spec.ts new file mode 100644 index 0000000000..be52ee66ed --- /dev/null +++ b/packages/fs/fs/tests/errno.spec.ts @@ -0,0 +1,30 @@ +/** Errno classification into the shared filesystem codes. */ +import { describe, expect, it } from 'vitest' +import { FsError, fsErrorFromErrno } from '@deepseek-ai/dsh-fs' + +describe('fsErrorFromErrno', () => { + const errno = (code: string): Error => Object.assign(new Error(`${code}: injected`), { code }) + + it.each([ + ['ENOENT', 'FS_NOT_FOUND', 'not found'], + ['ENOTDIR', 'FS_NOT_FOUND', 'not found'], + ['EACCES', 'FS_PERMISSION_DENIED', 'permission denied'], + ['EPERM', 'FS_PERMISSION_DENIED', 'permission denied'], + ['EISDIR', 'FS_NOT_REGULAR_FILE', 'not a regular file'], + ['ELOOP', 'FS_IO_ERROR', 'ELOOP: injected'], + ])('maps %s to %s with the Node error as cause', (code, fsCode, detail) => { + const cause = errno(code) + expect(fsErrorFromErrno('read', '~/a', cause)).toMatchObject({ + name: 'FsError', code: fsCode, message: `cannot read "~/a": ${detail}`, cause, + }) + }) + + it.each([ + new FsError('already typed', 'FS_TOO_LARGE'), + new Error('defect'), + Object.assign(new Error('numeric code'), { code: 1 }), + 'not an error', + ])('returns typed failures and defects unchanged: %s', (value) => { + expect(fsErrorFromErrno('read', 'a', value)).toBe(value) + }) +}) From 36d45eca9cd87f4ef05f9527c02e2bb5b9283e16 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:28:43 +0800 Subject: [PATCH 026/438] feat(str-replace-editor): give argument and create failures error codes Hand-checked argument failures (relative or empty path, missing command parameters, invalid view_range, out-of-range insert_line, null new_str) throw ToolArgsError (INVALID_ARGS), and create on an existing path throws FsError FS_ALREADY_EXISTS, so tool results persist error.info. --- .../tool-str-replace-editor/README.i18n.yaml | 4 +- packages/fs/tool-str-replace-editor/README.md | 2 +- .../fs/tool-str-replace-editor/README.zh.md | 2 +- .../fs/tool-str-replace-editor/src/index.ts | 36 +++++------ .../tests/tools.spec.ts | 60 ++++++++++--------- 5 files changed, 54 insertions(+), 50 deletions(-) diff --git a/packages/fs/tool-str-replace-editor/README.i18n.yaml b/packages/fs/tool-str-replace-editor/README.i18n.yaml index 7bd12ad505..b1cc3a78da 100644 --- a/packages/fs/tool-str-replace-editor/README.i18n.yaml +++ b/packages/fs/tool-str-replace-editor/README.i18n.yaml @@ -27,8 +27,8 @@ en: 554e8446946fbd96 zh: 3af12627c19a0111 /deepseek-ai-dsh-tool-str-replace-editor/use-this-package/failures-and-recovery: - en: 2b249fcb0b5621aa - zh: d172b3de43c337c4 + en: 68d14f5993c734d5 + zh: 36eab11474947735 /deepseek-ai-dsh-tool-str-replace-editor/understand-the-implementation: en: b0b36a22cd4421eb zh: db47ef5b71dd51df diff --git a/packages/fs/tool-str-replace-editor/README.md b/packages/fs/tool-str-replace-editor/README.md index f1880a5217..563ddf6ce1 100644 --- a/packages/fs/tool-str-replace-editor/README.md +++ b/packages/fs/tool-str-replace-editor/README.md @@ -52,7 +52,7 @@ A backend, optionally the policy plugin, then the tool; the editor composes with ### Failures and recovery -A metadata miss from `view`, `str_replace`, or `insert` records confirmed absence before returning `FS_NOT_FOUND`, so a later `create` can recover an externally deleted path through the mounted policy's guarded-create flow; absence never authorizes `str_replace` or `insert`. Guarded mutations inherit the policy plugin's codes and remedies — `FS_NOT_OBSERVED` (read the file, then retry), `FS_STALE_VERSION` (re-read, then retry) — and sandbox denials surface as the `[sandbox: file access denied under mode]` marker. Paths must be absolute; a relative path is refused with a hint. +A metadata miss from `view`, `str_replace`, or `insert` records confirmed absence before returning `FS_NOT_FOUND`, so a later `create` can recover an externally deleted path through the mounted policy's guarded-create flow; absence never authorizes `str_replace` or `insert`. Guarded mutations inherit the policy plugin's codes and remedies — `FS_NOT_OBSERVED` (read the file, then retry), `FS_STALE_VERSION` (re-read, then retry) — and sandbox denials surface as the `[sandbox: file access denied under mode]` marker. Paths must be absolute; a relative path is refused with a hint. Argument mistakes the schema cannot express, such as a relative path, a missing command parameter, or an out-of-range `view_range` or `insert_line`, throw `ToolArgsError` with `INVALID_ARGS`; `create` on an existing path reports `FS_ALREADY_EXISTS`. ----- diff --git a/packages/fs/tool-str-replace-editor/README.zh.md b/packages/fs/tool-str-replace-editor/README.zh.md index 9c69505356..5182960718 100644 --- a/packages/fs/tool-str-replace-editor/README.zh.md +++ b/packages/fs/tool-str-replace-editor/README.zh.md @@ -52,7 +52,7 @@ kind: "package-reference" ### 失败与恢复 -`view`、`str_replace` 或 `insert` 发生元数据未命中时,工具会在返回 `FS_NOT_FOUND` 前记录确认缺失,因此后续 `create` 可以通过已挂载策略的防护创建流程恢复外部删除的路径;缺失状态绝不会授权 `str_replace` 或 `insert`。防护变更继承策略插件的错误码与恢复指令——`FS_NOT_OBSERVED`(先读取文件再重试)、`FS_STALE_VERSION`(先重新读取再重试)——沙箱拒绝则表现为 `[sandbox: file access denied under mode]` 标记。路径必须是绝对路径;相对路径会被拒绝并给出提示。 +`view`、`str_replace` 或 `insert` 发生元数据未命中时,工具会在返回 `FS_NOT_FOUND` 前记录确认缺失,因此后续 `create` 可以通过已挂载策略的防护创建流程恢复外部删除的路径;缺失状态绝不会授权 `str_replace` 或 `insert`。防护变更继承策略插件的错误码与恢复指令——`FS_NOT_OBSERVED`(先读取文件再重试)、`FS_STALE_VERSION`(先重新读取再重试)——沙箱拒绝则表现为 `[sandbox: file access denied under mode]` 标记。路径必须是绝对路径;相对路径会被拒绝并给出提示。参数模式无法表达的参数错误,例如相对路径、缺少命令参数或 `view_range`、`insert_line` 越界,抛出 `ToolArgsError`,错误码为 `INVALID_ARGS`;对已存在路径执行 `create` 报告 `FS_ALREADY_EXISTS`。 ----- diff --git a/packages/fs/tool-str-replace-editor/src/index.ts b/packages/fs/tool-str-replace-editor/src/index.ts index 3542ee1770..099d1a6d73 100644 --- a/packages/fs/tool-str-replace-editor/src/index.ts +++ b/packages/fs/tool-str-replace-editor/src/index.ts @@ -12,7 +12,7 @@ import { truncateWithoutSplittingSurrogatePair } from '@deepseek-ai/dsh-output-r import { sandboxDenialMarker } from '@deepseek-ai/dsh-sandbox' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { ToolCallView, ToolRunContext } from '@deepseek-ai/dsh-tools' const TRUNCATED_MESSAGE = 'To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.' @@ -92,9 +92,9 @@ async function resolveTarget( path: string, signal: AbortSignal, ): Promise { - if (path.trim().length === 0) throw new Error('path must be a non-empty string') + if (path.trim().length === 0) throw new ToolArgsError(['path must be a non-empty string']) if (!isAbsolute(path)) { - throw new Error(`The path ${path} is not an absolute path, it should start with \`/\`. Maybe you meant /${path}?`) + throw new ToolArgsError([`The path ${path} is not an absolute path, it should start with \`/\`. Maybe you meant /${path}?`]) } return ctx.fs.resolve(path, { signal }) } @@ -128,9 +128,9 @@ function requiredForCommand( command: string, allowEmpty = true, ): string { - if (value === undefined) throw new Error(`Parameter \`${parameter}\` is required for command: ${command}`) + if (value === undefined) throw new ToolArgsError([`Parameter \`${parameter}\` is required for command: ${command}`]) if (!allowEmpty && value.length === 0) { - throw new Error(`Parameter \`${parameter}\` is empty for command: ${command}`) + throw new ToolArgsError([`Parameter \`${parameter}\` is empty for command: ${command}`]) } return value } @@ -154,24 +154,24 @@ function formatFileView( || requestedFinalLine === undefined || !viewRange.every(Number.isInteger) ) { - throw new Error('Invalid `view_range`. It should be a list of two integers.') + throw new ToolArgsError(['Invalid `view_range`. It should be a list of two integers.']) } initialLine = requestedInitialLine finalLine = requestedFinalLine if (initialLine < 1 || initialLine > allLines.length) { - throw new Error( + throw new ToolArgsError([ `Invalid \`view_range\`: [${viewRange.join(', ')}]. Its first element \`${initialLine}\` should be within the range of lines of the file: [1, ${allLines.length}]`, - ) + ]) } if (finalLine > allLines.length) { - throw new Error( + throw new ToolArgsError([ `Invalid \`view_range\`: [${viewRange.join(', ')}]. Its second element \`${finalLine}\` should be smaller than the number of lines in the file: \`${allLines.length}\``, - ) + ]) } if (finalLine !== -1 && finalLine < initialLine) { - throw new Error( + throw new ToolArgsError([ `Invalid \`view_range\`: [${viewRange.join(', ')}]. Its second element \`${finalLine}\` should be larger or equal than its first \`${initialLine}\``, - ) + ]) } lines = finalLine === -1 ? allLines.slice(initialLine - 1) @@ -226,7 +226,7 @@ async function viewPath( const info = await statExisting(ctx, target, 'view', exec) if (info.type === 'directory') { if (viewRange !== undefined) { - throw new Error('The `view_range` parameter is not allowed when `path` points to a directory.') + throw new ToolArgsError(['The `view_range` parameter is not allowed when `path` points to a directory.']) } return listDirectory(ctx, target, maxOutputChars, exec) } @@ -249,7 +249,7 @@ async function createFile( const sandboxPolicy = policy.resolve(exec) const target = await resolveTarget(ctx, path, exec.signal) if (await ctx.fs.stat(target, exec.signal) !== undefined) { - throw new Error(`File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`) + throw new FsError(`File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`, 'FS_ALREADY_EXISTS') } const intent = await ctx.waterfall( 'fs/write-intent', @@ -282,7 +282,7 @@ async function replaceInFile( exec: ToolRunContext, ): Promise { if (newStr === null) { - throw new Error('Parameter `new_str` must be omitted or contain a string for command: str_replace') + throw new ToolArgsError(['Parameter `new_str` must be omitted or contain a string for command: str_replace']) } const sandboxPolicy = policy.resolve(exec) const target = await resolveTarget(ctx, path, exec.signal) @@ -335,7 +335,7 @@ async function insertInFile( newStr: string | undefined, exec: ToolRunContext, ): Promise { - if (insertLine === undefined) throw new Error('Parameter `insert_line` is required for command: insert') + if (insertLine === undefined) throw new ToolArgsError(['Parameter `insert_line` is required for command: insert']) const value = requiredForCommand(newStr, 'new_str', 'insert') const sandboxPolicy = policy.resolve(exec) const target = await resolveTarget(ctx, path, exec.signal) @@ -347,9 +347,9 @@ async function insertInFile( const before = await ctx.fs.readText(target, exec.signal) const lines = before.split('\n') if (!Number.isInteger(insertLine) || insertLine < 0 || insertLine > lines.length) { - throw new Error( + throw new ToolArgsError([ `Invalid \`insert_line\` parameter: ${insertLine}. It should be within the range of lines of the file: [0, ${lines.length}]`, - ) + ]) } const after = [ ...lines.slice(0, insertLine), diff --git a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts index 14de14c4cd..e08c539c59 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -460,6 +460,7 @@ describe('tool-str-replace-editor', () => { const relative = await call(ctx, owner, { command: 'view', path: 'ambiguous.txt' }) expect(relative.isError).toBe(true) expect(text(relative)).toContain('is not an absolute path') + expect(relative.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(await readFile(ambiguous, 'utf8')).toBe('alpha\nbeta\nmiddle\nalpha\nbeta') }) @@ -476,35 +477,38 @@ describe('tool-str-replace-editor', () => { await writeFile(threeLines, 'one\ntwo\nthree') await mkdir(directory) - const cases = [ - { command: null, path: ambiguous }, - { command: 'view', path: null }, - { command: 'view', path: '' }, - { command: 'view', path: join(root, 'missing.txt') }, - { command: 'view', path: ambiguous, view_range: [1] }, - { command: 'view', path: ambiguous, view_range: [0, 1] }, - { command: 'view', path: ambiguous, view_range: [1.5, 2] }, - { command: 'view', path: threeLines, view_range: [1, 99] }, - { command: 'view', path: threeLines, view_range: [2, 1] }, - { command: 'view', path: directory, view_range: [1, 1] }, - { command: 'create', path: join(root, 'new.txt') }, - { command: 'create', path: join(root, 'new.txt'), file_text: null }, - { command: 'create', path: ambiguous, file_text: 'overwrite' }, - { command: 'str_replace', path: ambiguous, new_str: 'x' }, - { command: 'str_replace', path: ambiguous, old_str: null, new_str: 'x' }, - { command: 'str_replace', path: ambiguous, old_str: 'same same', new_str: null }, - { command: 'str_replace', path: ambiguous, old_str: '', new_str: 'x' }, - { command: 'insert', path: ambiguous, new_str: 'x' }, - { command: 'insert', path: ambiguous, insert_line: null, new_str: 'x' }, - { command: 'insert', path: ambiguous, insert_line: 0, new_str: null }, - { command: 'insert', path: ambiguous, insert_line: -1, new_str: 'x' }, - { command: 'insert', path: ambiguous, insert_line: 1.5, new_str: 'x' }, - { command: 'insert', path: ambiguous, insert_line: 99, new_str: 'x' }, - { command: 'insert', path: empty, insert_line: 2, new_str: 'x' }, - { command: 'insert', path: directory, insert_line: 0, new_str: 'x' }, + const args = { name: 'ToolArgsError', code: 'INVALID_ARGS' } + const cases: [Record, { name: string; code: string }][] = [ + [{ command: null, path: ambiguous }, args], + [{ command: 'view', path: null }, args], + [{ command: 'view', path: '' }, args], + [{ command: 'view', path: join(root, 'missing.txt') }, { name: 'FsError', code: 'FS_NOT_FOUND' }], + [{ command: 'view', path: ambiguous, view_range: [1] }, args], + [{ command: 'view', path: ambiguous, view_range: [0, 1] }, args], + [{ command: 'view', path: ambiguous, view_range: [1.5, 2] }, args], + [{ command: 'view', path: threeLines, view_range: [1, 99] }, args], + [{ command: 'view', path: threeLines, view_range: [2, 1] }, args], + [{ command: 'view', path: directory, view_range: [1, 1] }, args], + [{ command: 'create', path: join(root, 'new.txt') }, args], + [{ command: 'create', path: join(root, 'new.txt'), file_text: null }, args], + [{ command: 'create', path: ambiguous, file_text: 'overwrite' }, { name: 'FsError', code: 'FS_ALREADY_EXISTS' }], + [{ command: 'str_replace', path: ambiguous, new_str: 'x' }, args], + [{ command: 'str_replace', path: ambiguous, old_str: null, new_str: 'x' }, args], + [{ command: 'str_replace', path: ambiguous, old_str: 'same same', new_str: null }, args], + [{ command: 'str_replace', path: ambiguous, old_str: '', new_str: 'x' }, args], + [{ command: 'insert', path: ambiguous, new_str: 'x' }, args], + [{ command: 'insert', path: ambiguous, insert_line: null, new_str: 'x' }, args], + [{ command: 'insert', path: ambiguous, insert_line: 0, new_str: null }, args], + [{ command: 'insert', path: ambiguous, insert_line: -1, new_str: 'x' }, args], + [{ command: 'insert', path: ambiguous, insert_line: 1.5, new_str: 'x' }, args], + [{ command: 'insert', path: ambiguous, insert_line: 99, new_str: 'x' }, args], + [{ command: 'insert', path: empty, insert_line: 2, new_str: 'x' }, args], + [{ command: 'insert', path: directory, insert_line: 0, new_str: 'x' }, { name: 'FsError', code: 'FS_NOT_REGULAR_FILE' }], ] - for (const args of cases) { - expect((await call(ctx, owner, args)).isError).toBe(true) + for (const [callArgs, info] of cases) { + const result = await call(ctx, owner, callArgs) + expect(result.isError).toBe(true) + expect({ args: callArgs, info: result.error?.info }).toEqual({ args: callArgs, info }) } expect(await readFile(ambiguous, 'utf8')).toBe('same same') From 7d6b1197ddf6d938c2583b0a6a037305ade2b335 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:28:43 +0800 Subject: [PATCH 027/438] feat(fs-search): report glob and grep argument failures as ToolArgsError Blank pattern or path and invalid include filters throw ToolArgsError (INVALID_ARGS) instead of a plain Error. --- packages/fs/tool-fs-search/README.i18n.yaml | 4 +-- packages/fs/tool-fs-search/README.md | 2 +- packages/fs/tool-fs-search/README.zh.md | 2 +- packages/fs/tool-fs-search/src/glob.ts | 10 +++---- packages/fs/tool-fs-search/src/grep.ts | 14 +++++----- .../fs/tool-fs-search/tests/tools.spec.ts | 27 ++++++++++++++----- 6 files changed, 36 insertions(+), 23 deletions(-) diff --git a/packages/fs/tool-fs-search/README.i18n.yaml b/packages/fs/tool-fs-search/README.i18n.yaml index b1c75185bb..df28d1dc0a 100644 --- a/packages/fs/tool-fs-search/README.i18n.yaml +++ b/packages/fs/tool-fs-search/README.i18n.yaml @@ -30,8 +30,8 @@ en: 4aa9b74deef586bc zh: f855f815829d4e1e /deepseek-ai-dsh-tool-fs-search/use-this-package/failures-and-recovery: - en: d7a59e296308b2bd - zh: 66243fcd932fe49a + en: ce6065aa8f2a04b6 + zh: bc862345e48e52d4 /deepseek-ai-dsh-tool-fs-search/understand-the-implementation: en: 7546db09c46181e0 zh: 3aae6dc6a773511c diff --git a/packages/fs/tool-fs-search/README.md b/packages/fs/tool-fs-search/README.md index 4c26ffa018..008741bb5d 100644 --- a/packages/fs/tool-fs-search/README.md +++ b/packages/fs/tool-fs-search/README.md @@ -76,7 +76,7 @@ Node deployments receive the `@vscode/ripgrep` platform package on supported mac ### Failures and recovery -Search failures carry the package-owned codes `SEARCH_INVALID_PATTERN` (ripgrep rejected the regex or glob), `SEARCH_FAILED` (a failed launch, inaccessible target, signal kill, or malformed `--json` output), `SEARCH_RAW_OUTPUT_OVERFLOW` (raw output over the cap), and `SEARCH_ABORTED` (cooperative timeout or caller cancellation). Exit 0 is success with results and exit 1 is a successful empty search; model argument mistakes stay ordinary tool argument errors. +Search failures carry the package-owned codes `SEARCH_INVALID_PATTERN` (ripgrep rejected the regex or glob), `SEARCH_FAILED` (a failed launch, inaccessible target, signal kill, or malformed `--json` output), `SEARCH_RAW_OUTPUT_OVERFLOW` (raw output over the cap), and `SEARCH_ABORTED` (cooperative timeout or caller cancellation). Exit 0 is success with results and exit 1 is a successful empty search; model argument mistakes throw `ToolArgsError` with `INVALID_ARGS`. ----- diff --git a/packages/fs/tool-fs-search/README.zh.md b/packages/fs/tool-fs-search/README.zh.md index 10cae42308..2f38854de2 100644 --- a/packages/fs/tool-fs-search/README.zh.md +++ b/packages/fs/tool-fs-search/README.zh.md @@ -76,7 +76,7 @@ Node 部署在受支持的 macOS、Linux 与 Windows 目标上获得 `@vscode/ri ### 失败与恢复 -搜索失败携带本包定义的错误码:`SEARCH_INVALID_PATTERN`(ripgrep 拒绝正则或 glob)、`SEARCH_FAILED`(启动失败、目标不可访问、信号终止或 `--json` 输出格式错误)、`SEARCH_RAW_OUTPUT_OVERFLOW`(原始输出超过上限)与 `SEARCH_ABORTED`(协作式超时或调用方取消)。退出 0 表示成功且有结果,退出 1 表示成功的空搜索;模型参数错误仍是普通工具参数错误。 +搜索失败携带本包定义的错误码:`SEARCH_INVALID_PATTERN`(ripgrep 拒绝正则或 glob)、`SEARCH_FAILED`(启动失败、目标不可访问、信号终止或 `--json` 输出格式错误)、`SEARCH_RAW_OUTPUT_OVERFLOW`(原始输出超过上限)与 `SEARCH_ABORTED`(协作式超时或调用方取消)。退出 0 表示成功且有结果,退出 1 表示成功的空搜索;模型参数错误抛出 `ToolArgsError`,错误码为 `INVALID_ARGS`。 ----- diff --git a/packages/fs/tool-fs-search/src/glob.ts b/packages/fs/tool-fs-search/src/glob.ts index 31df85aa53..99af2c5b75 100644 --- a/packages/fs/tool-fs-search/src/glob.ts +++ b/packages/fs/tool-fs-search/src/glob.ts @@ -11,7 +11,7 @@ import type { Context } from '@deepseek-ai/cordis' import { sep } from 'node:path' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { GenericCallView, SearchResultView, ToolResult } from '@deepseek-ai/dsh-tools' import type { SpillRef } from '@deepseek-ai/dsh-spill' import { runRipgrep, toWorkdirRelative, trySaveFormattedResult } from './search-core.ts' @@ -62,15 +62,15 @@ export interface GlobInput { /** * Validate value constraints the schema DSL can't express: a non-blank - * `pattern`, and a non-blank `path` when given. Throws a plain `Error` (an - * ordinary tool argument error) otherwise. + * `pattern`, and a non-blank `path` when given. Throws `ToolArgsError` + * (`INVALID_ARGS`) otherwise. * * @param args - the schema-validated `glob` arguments. * @returns the accepted input, unchanged. */ export function parseGlobArgs(args: { pattern: string; path?: string }): GlobInput { - if (args.pattern.trim().length === 0) throw new Error('pattern must be a non-empty string') - if (args.path !== undefined && args.path.trim().length === 0) throw new Error('path must be a non-empty string when given') + if (args.pattern.trim().length === 0) throw new ToolArgsError(['pattern must be a non-empty string']) + if (args.path !== undefined && args.path.trim().length === 0) throw new ToolArgsError(['path must be a non-empty string when given']) return { pattern: args.pattern, ...args.path !== undefined ? { path: args.path } : {} } } diff --git a/packages/fs/tool-fs-search/src/grep.ts b/packages/fs/tool-fs-search/src/grep.ts index e0246d6b76..1a6fd00bd8 100644 --- a/packages/fs/tool-fs-search/src/grep.ts +++ b/packages/fs/tool-fs-search/src/grep.ts @@ -12,7 +12,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { GenericCallView, SearchResultView, ToolResult } from '@deepseek-ai/dsh-tools' import type { RetainedItems } from '@deepseek-ai/dsh-output-retention' import type { SpillRef } from '@deepseek-ai/dsh-spill' @@ -65,14 +65,14 @@ export interface GrepInput { * group is fine — `*.{ts,tsx}` is one glob with alternation, not a list. */ function validateInclude(include: string): void { - if (include.trim().length === 0) throw new Error('include must be a non-empty glob when given') - if (include.startsWith('!')) throw new Error('include must be a positive glob filter; negated patterns ("!…") are not supported') + if (include.trim().length === 0) throw new ToolArgsError(['include must be a non-empty glob when given']) + if (include.startsWith('!')) throw new ToolArgsError(['include must be a positive glob filter; negated patterns ("!…") are not supported']) let braceDepth = 0 for (const char of include) { if (char === '{') braceDepth++ else if (char === '}') braceDepth = Math.max(0, braceDepth - 1) else if (char === ',' && braceDepth === 0) { - throw new Error('include must be one glob, not a comma-separated list (use {a,b} alternation instead)') + throw new ToolArgsError(['include must be one glob, not a comma-separated list (use {a,b} alternation instead)']) } } } @@ -82,14 +82,14 @@ function validateInclude(include: string): void { * `pattern` (whitespace is a legitimate regex), a non-blank `path` when given, * and a single positive `include` glob ({@link GrepInput}). An exact empty * `include` is treated as omitted; whitespace-only values remain invalid. - * Throws a plain `Error` (an ordinary tool argument error) otherwise. + * Throws `ToolArgsError` (`INVALID_ARGS`) otherwise. * * @param args - the schema-validated `grep` arguments. * @returns the accepted input with an empty `include` omitted. */ export function parseGrepArgs(args: { pattern: string; path?: string; include?: string }): GrepInput { - if (args.pattern.length === 0) throw new Error('pattern must be a non-empty string') - if (args.path !== undefined && args.path.trim().length === 0) throw new Error('path must be a non-empty string when given') + if (args.pattern.length === 0) throw new ToolArgsError(['pattern must be a non-empty string']) + if (args.path !== undefined && args.path.trim().length === 0) throw new ToolArgsError(['path must be a non-empty string when given']) const include = args.include === '' ? undefined : args.include if (include !== undefined) validateInclude(include) return { diff --git a/packages/fs/tool-fs-search/tests/tools.spec.ts b/packages/fs/tool-fs-search/tests/tools.spec.ts index 5763aacc15..529d93805a 100644 --- a/packages/fs/tool-fs-search/tests/tools.spec.ts +++ b/packages/fs/tool-fs-search/tests/tools.spec.ts @@ -754,8 +754,14 @@ describe('glob results', () => { it('validates arguments (blank pattern, blank path)', async () => { const { ctx } = await setup() - expect(text(await call(ctx, 'glob', { pattern: ' ' }))).toContain('pattern must be a non-empty string') - expect(text(await call(ctx, 'glob', { pattern: '*', path: ' ' }))).toContain('path must be a non-empty string') + for (const [args, message] of [ + [{ pattern: ' ' }, 'pattern must be a non-empty string'], + [{ pattern: '*', path: ' ' }, 'path must be a non-empty string'], + ] as const) { + const result = await call(ctx, 'glob', args) + expect(text(result)).toContain(message) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + } }) it('threads a valid path through to the spawn as the plain search root element', async () => { @@ -1100,16 +1106,23 @@ describe('grep results', () => { const result = await call(ctx, 'grep', args) expect(result.isError).toBe(true) expect(text(result)).toContain(message) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) expect(subprocess.spawns).toHaveLength(0) }) it('validates arguments (empty pattern, blank path, bad include)', async () => { const { ctx } = await setup() - expect(text(await call(ctx, 'grep', { pattern: '' }))).toContain('pattern must be a non-empty string') - expect(text(await call(ctx, 'grep', { pattern: 'x', path: ' ' }))).toContain('path must be a non-empty string') - expect(text(await call(ctx, 'grep', { pattern: 'x', include: ' ' }))).toContain('include must be a non-empty glob') - expect(text(await call(ctx, 'grep', { pattern: 'x', include: '!*.ts' }))).toContain('negated patterns') - expect(text(await call(ctx, 'grep', { pattern: 'x', include: '*.ts,*.js' }))).toContain('comma-separated list') + for (const [args, message] of [ + [{ pattern: '' }, 'pattern must be a non-empty string'], + [{ pattern: 'x', path: ' ' }, 'path must be a non-empty string'], + [{ pattern: 'x', include: ' ' }, 'include must be a non-empty glob'], + [{ pattern: 'x', include: '!*.ts' }, 'negated patterns'], + [{ pattern: 'x', include: '*.ts,*.js' }, 'comma-separated list'], + ] as const) { + const result = await call(ctx, 'grep', args) + expect(text(result)).toContain(message) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + } }) it('accepts a whitespace-only pattern (a legitimate regex) and brace alternation in include', async () => { From a0766d7573dff6789e3a8b8d303b64800215b22a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:28:44 +0800 Subject: [PATCH 028/438] feat(tool-fs): report read, write, and edit argument failures as ToolArgsError read offset/limit/file_path, write file_path, edit file_path/old_string checks, and an unsupported sandbox_permissions request throw ToolArgsError (INVALID_ARGS). Integration tests pin that host metadata and permission faults now reach read results as FsError codes. --- packages/fs/tool-fs/src/edit.ts | 8 +++---- packages/fs/tool-fs/src/read.ts | 8 +++---- packages/fs/tool-fs/src/sandbox.ts | 3 ++- packages/fs/tool-fs/src/write.ts | 4 ++-- packages/fs/tool-fs/tests/integration.spec.ts | 23 ++++++++++++++++++- packages/fs/tool-fs/tests/tools.spec.ts | 10 ++++++++ 6 files changed, 44 insertions(+), 12 deletions(-) diff --git a/packages/fs/tool-fs/src/edit.ts b/packages/fs/tool-fs/src/edit.ts index f927ccb1cb..8de03306ca 100644 --- a/packages/fs/tool-fs/src/edit.ts +++ b/packages/fs/tool-fs/src/edit.ts @@ -6,7 +6,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { DiffCallView, DiffResultView, ToolResult } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' import { computeHunkDiffs, diffsFromMeta } from './diff.ts' @@ -45,9 +45,9 @@ interface EditToolArgs { * @returns the camelCased input with `replace_all` defaulted to false. */ export function parseEditArgs(args: { file_path: string; old_string: string; new_string: string; replace_all?: boolean }): EditInput { - if (args.file_path.trim().length === 0) throw new Error('file_path must be a non-empty string') - if (args.old_string.length === 0) throw new Error('old_string must be a non-empty string') - if (args.old_string === args.new_string) throw new Error('old_string and new_string must differ') + if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string']) + if (args.old_string.length === 0) throw new ToolArgsError(['old_string must be a non-empty string']) + if (args.old_string === args.new_string) throw new ToolArgsError(['old_string and new_string must differ']) return { filePath: args.file_path, oldString: args.old_string, diff --git a/packages/fs/tool-fs/src/read.ts b/packages/fs/tool-fs/src/read.ts index 22c2dc52c9..fcd42c3e07 100644 --- a/packages/fs/tool-fs/src/read.ts +++ b/packages/fs/tool-fs/src/read.ts @@ -5,7 +5,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ReadResultView, ToolResult } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' import { buildWindow, formatReadOutput, langFromPath, readMetaFromMeta } from './read-render.ts' @@ -41,7 +41,7 @@ interface ReadInput { function parsePositiveInteger(value: number, name: string): number { if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) { - throw new Error(`${name} must be a positive integer`) + throw new ToolArgsError([`${name} must be a positive integer`]) } return value } @@ -53,10 +53,10 @@ function parsePositiveInteger(value: number, name: string): number { * @returns the validated input with `offset` defaulted to 1 and `limit` to `maxLimit`. */ export function parseReadArgs(args: { file_path: string; offset?: number; limit?: number }, maxLimit: number): ReadInput { - if (args.file_path.trim().length === 0) throw new Error('file_path must be a non-empty string') + if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string']) const offset = args.offset === undefined ? 1 : parsePositiveInteger(args.offset, 'offset') const limit = args.limit === undefined ? maxLimit : parsePositiveInteger(args.limit, 'limit') - if (limit > maxLimit) throw new Error(`limit must be less than or equal to ${maxLimit}`) + if (limit > maxLimit) throw new ToolArgsError([`limit must be less than or equal to ${maxLimit}`]) return { filePath: args.file_path, offset, limit } } diff --git a/packages/fs/tool-fs/src/sandbox.ts b/packages/fs/tool-fs/src/sandbox.ts index c962d6a147..08b776fd92 100644 --- a/packages/fs/tool-fs/src/sandbox.ts +++ b/packages/fs/tool-fs/src/sandbox.ts @@ -11,6 +11,7 @@ */ import type { Context } from '@deepseek-ai/cordis' +import { ToolArgsError } from '@deepseek-ai/dsh-tools' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' @@ -96,7 +97,7 @@ export class FsSandboxController { return standingPolicy } if (this.escalationModes.length === 0) { - throw new Error('sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)') + throw new ToolArgsError(['sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)']) } const policy = standingPolicy as SandboxExecutionPolicy const approvedMode = await approveEscalation( diff --git a/packages/fs/tool-fs/src/write.ts b/packages/fs/tool-fs/src/write.ts index 0745ffc98d..37d1263d20 100644 --- a/packages/fs/tool-fs/src/write.ts +++ b/packages/fs/tool-fs/src/write.ts @@ -6,7 +6,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, defineTool } from '@deepseek-ai/dsh-tools' import type { DiffCallView, DiffResultView, ToolResult } from '@deepseek-ai/dsh-tools' import type { FsWriteOutcome } from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-fs' @@ -23,7 +23,7 @@ import type { FsSandboxController } from './sandbox.ts' * @returns the camelCased input; `content` passes through untouched. */ export function parseWriteArgs(args: { file_path: string; content: string }): { filePath: string; content: string } { - if (args.file_path.trim().length === 0) throw new Error('file_path must be a non-empty string') + if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string']) return { filePath: args.file_path, content: args.content } } diff --git a/packages/fs/tool-fs/tests/integration.spec.ts b/packages/fs/tool-fs/tests/integration.spec.ts index 25d428c8e6..32d42fd4bb 100644 --- a/packages/fs/tool-fs/tests/integration.spec.ts +++ b/packages/fs/tool-fs/tests/integration.spec.ts @@ -10,7 +10,7 @@ import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' import { mountAgentLoopTestDependencies, provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' @@ -355,6 +355,27 @@ describe('bare provider (no dsh-fs-observation-policy)', () => { expect(text(result)).toContain('1: alpha') }) + it('reports a host metadata fault as a typed filesystem failure', async () => { + await symlink(join(dir, 'loop'), join(dir, 'loop')) + const result = await call('read', { file_path: 'loop' }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_IO_ERROR' }) + }) + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('reports unreadable content as FS_PERMISSION_DENIED', async () => { + const file = join(dir, 'locked.txt') + await writeFile(file, 'secret') + await chmod(file, 0o000) + try { + const result = await call('read', { file_path: 'locked.txt' }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' }) + expect(text(result)).toContain('permission denied') + } finally { + await chmod(file, 0o600) + } + }) + it('write unconditionally creates a new file', async () => { const result = await call('write', { file_path: 'new.txt', content: 'fresh' }) expect(result.isError).toBe(false) diff --git a/packages/fs/tool-fs/tests/tools.spec.ts b/packages/fs/tool-fs/tests/tools.spec.ts index 8ba5a105cd..f1082845f2 100644 --- a/packages/fs/tool-fs/tests/tools.spec.ts +++ b/packages/fs/tool-fs/tests/tools.spec.ts @@ -287,6 +287,7 @@ describe('read tool', () => { const result = await call(ctx, 'read', { file_path: 'a.txt', offset: 0 }) expect(result.isError).toBe(true) expect(text(result)).toContain('offset must be a positive integer') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a fractional offset and a zero/negative limit', async () => { @@ -299,6 +300,7 @@ describe('read tool', () => { const result = await call(ctx, 'read', args) expect(result.isError, JSON.stringify(args)).toBe(true) expect(text(result)).toMatch(/must be a positive integer/) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) } }) @@ -314,6 +316,7 @@ describe('read tool', () => { const result = await call(ctx, 'read', { file_path: 'a.txt', limit: 99999 }) expect(result.isError).toBe(true) expect(text(result)).toContain('less than or equal to 2000') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a blank file_path', async () => { @@ -321,6 +324,7 @@ describe('read tool', () => { const result = await call(ctx, 'read', { file_path: ' ' }) expect(result.isError).toBe(true) expect(text(result)).toContain('file_path must be a non-empty string') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('records observed state so a follow-up edit by the same session is authorized', async () => { @@ -456,6 +460,7 @@ describe('write tool', () => { const result = await call(ctx, 'write', { file_path: ' ', content: 'hi' }) expect(result.isError).toBe(true) expect(text(result)).toContain('file_path must be a non-empty string') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('propagates a backend FsError as an isError result carrying its code and remedy', async () => { @@ -494,6 +499,7 @@ describe('edit tool', () => { const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'x', new_string: 'x' }) expect(result.isError).toBe(true) expect(text(result)).toContain('must differ') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects an empty old_string', async () => { @@ -501,6 +507,7 @@ describe('edit tool', () => { const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: '', new_string: 'x' }) expect(result.isError).toBe(true) expect(text(result)).toContain('old_string must be a non-empty string') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('rejects a blank file_path', async () => { @@ -508,6 +515,7 @@ describe('edit tool', () => { const result = await call(ctx, 'edit', { file_path: ' ', old_string: 'a', new_string: 'b' }) expect(result.isError).toBe(true) expect(text(result)).toContain('file_path must be a non-empty string') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) it('propagates FS_NOT_OBSERVED when the file was never read (the gate decides)', async () => { @@ -788,6 +796,7 @@ describe('read caps are plugin config', () => { const overCap = await call(ctx, 'read', { file_path: 'a.txt', limit: 3 }) expect(overCap.isError).toBe(true) expect(text(overCap)).toContain('less than or equal to 2') + expect(overCap.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const readSchema = ctx.tools.schemas().find(s => s.name === 'read') expect(JSON.stringify(readSchema)).toContain('Defaults to 2.') }) @@ -1141,6 +1150,7 @@ describe('sandbox escalation API (write/edit)', () => { const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'workspace-write', justification: 'why' }, escalationAgent()) expect(result.isError).toBe(true) expect(text(result)).toContain('not available in this composition') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) }) }) From b605b3dab2d4e5138a96d65e27e1537af3fe1f5a Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:28:45 +0800 Subject: [PATCH 029/438] feat(present): give present failures structured error codes A missing agent Session or open turn throws ToolContextUnavailableError, an empty path or out-of-range file count throws ToolArgsError, and a directory or final symlink throws FsError FS_NOT_REGULAR_FILE. --- .../tool-present/README.i18n.yaml | 4 +-- packages/deliverables/tool-present/README.md | 2 +- .../deliverables/tool-present/README.zh.md | 2 +- .../deliverables/tool-present/src/index.ts | 14 +++++----- .../tool-present/tests/present.spec.ts | 26 ++++++++++++++++--- 5 files changed, 33 insertions(+), 15 deletions(-) diff --git a/packages/deliverables/tool-present/README.i18n.yaml b/packages/deliverables/tool-present/README.i18n.yaml index 7de5647086..d5b2ce4e60 100644 --- a/packages/deliverables/tool-present/README.i18n.yaml +++ b/packages/deliverables/tool-present/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-present/use-this-package: - en: d1a1e22686f9041d - zh: 8053a913199195fa + en: aecb160dd6ee85ba + zh: 148288a2e92236fa /deepseek-ai-dsh-tool-present/understand-the-implementation: en: 6e73ca41dddc096e zh: b59fdfa3f3cc47e1 diff --git a/packages/deliverables/tool-present/README.md b/packages/deliverables/tool-present/README.md index 7439bda570..031cf546d4 100644 --- a/packages/deliverables/tool-present/README.md +++ b/packages/deliverables/tool-present/README.md @@ -29,7 +29,7 @@ Shared output and file-link guidance comes from [`dsh-deliverable-file-reference `present` validates paths against the Session's current working directory and records absolute paths, so later directory changes do not redirect delivered files. -The `standard`, `ptc`, and `cordis` agent presets mount this plugin. Call `present` with `files: [{ path, description? }]` after creating the files. Files must be regular files accessible through the Session filesystem. Relative paths resolve against the Session working directory; absolute paths may name files outside it, including `/tmp` or Downloads. Missing files, directories, final symbolic links, and provider-denied paths fail the call. Files in a shell sandbox’s private `/tmp` must first be written somewhere the Session filesystem can access. +The `standard`, `ptc`, and `cordis` agent presets mount this plugin. Call `present` with `files: [{ path, description? }]` after creating the files. Files must be regular files accessible through the Session filesystem. Relative paths resolve against the Session working directory; absolute paths may name files outside it, including `/tmp` or Downloads. Missing files, directories, final symbolic links, and provider-denied paths fail the call with `FsError` codes such as `FS_NOT_FOUND`, `FS_NOT_REGULAR_FILE`, and `FS_PERMISSION_DENIED`; an empty path or a file count outside 1 to `maxFiles` reports `ToolArgsError` (`INVALID_ARGS`), and a call without an agent Session or open turn reports `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`). Files in a shell sandbox’s private `/tmp` must first be written somewhere the Session filesystem can access. Mount it in an agent's Cordis composition with `tools`, `fs`, and the `turnBoundary` Session projection available: diff --git a/packages/deliverables/tool-present/README.zh.md b/packages/deliverables/tool-present/README.zh.md index 40b81571aa..08410efe05 100644 --- a/packages/deliverables/tool-present/README.zh.md +++ b/packages/deliverables/tool-present/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" `present` 按 Session 的当前工作目录校验路径并记录绝对路径,因此后续目录切换不会让已交付文件指向其他位置。 -`standard`、`ptc` 与 `cordis` Agent preset 挂载本插件。创建文件后,以 `files: [{ path, description? }]` 调用 `present`。文件必须是 Session 文件系统可访问的普通文件。相对路径按 Session 工作目录解析;绝对路径可以指向工作区外的文件,包括 `/tmp` 或 Downloads。文件缺失、为目录、最终路径为符号链接或提供方拒绝访问时,调用失败。Shell 沙箱私有 `/tmp` 中的文件需要先写入 Session 文件系统可访问的位置。 +`standard`、`ptc` 与 `cordis` Agent preset 挂载本插件。创建文件后,以 `files: [{ path, description? }]` 调用 `present`。文件必须是 Session 文件系统可访问的普通文件。相对路径按 Session 工作目录解析;绝对路径可以指向工作区外的文件,包括 `/tmp` 或 Downloads。文件缺失、为目录、最终路径为符号链接或提供方拒绝访问时,调用以 `FsError` 失败,错误码如 `FS_NOT_FOUND`、`FS_NOT_REGULAR_FILE` 与 `FS_PERMISSION_DENIED`;路径为空或文件数量不在 1 到 `maxFiles` 之间时报告 `ToolArgsError`(`INVALID_ARGS`),缺少 agent Session 或打开的 turn 时报告 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)。Shell 沙箱私有 `/tmp` 中的文件需要先写入 Session 文件系统可访问的位置。 在 Agent 的 Cordis 组合中挂载,并提供 `tools`、`fs` 和 `turnBoundary` Session 投影: diff --git a/packages/deliverables/tool-present/src/index.ts b/packages/deliverables/tool-present/src/index.ts index 393a95d8c8..fac6ab0378 100644 --- a/packages/deliverables/tool-present/src/index.ts +++ b/packages/deliverables/tool-present/src/index.ts @@ -3,7 +3,7 @@ import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { FsError } from '@deepseek-ai/dsh-fs' -import { defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools' +import { ToolArgsError, ToolContextUnavailableError, defineTool, type ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-agent' import type { Session } from '@deepseek-ai/dsh-session' import type { PresentedFile } from './types.ts' @@ -76,21 +76,21 @@ export function apply(ctx: Context, config: Config): void { render: (_args, value) => [{ type: 'text', text: value.files.map(file => `Presented ${file.path}`).join('\n') }], }, async execute(args, exec) { - if (exec.agent === undefined) throw new Error('present requires an agent Session') + if (exec.agent === undefined) throw new ToolContextUnavailableError('present requires an agent Session') const boundary = ctx.agents.turnBoundaryOf(exec.agent.session) - if (boundary.openTurnStartSeq === null) throw new Error('present requires an open turn') - if (args.files.length === 0 || args.files.length > config.maxFiles) throw new Error(`present accepts 1 to ${config.maxFiles} files`) + if (boundary.openTurnStartSeq === null) throw new ToolContextUnavailableError('present requires an open turn') + if (args.files.length === 0 || args.files.length > config.maxFiles) throw new ToolArgsError([`present accepts 1 to ${config.maxFiles} files`]) const cwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal) const options = { cwd, signal: exec.signal } const files: PresentedFile[] = [] for (const file of args.files) { - if (file.path.trim().length === 0) throw new Error('present requires a non-empty file path') + if (file.path.trim().length === 0) throw new ToolArgsError(['present requires a non-empty file path']) const entry = await ctx.fs.lstat(file.path, { cwd }, exec.signal) - if (entry !== undefined && entry.type !== 'file') throw new Error(`Cannot present ${file.path}: not a regular file`) + if (entry !== undefined && entry.type !== 'file') throw new FsError(`Cannot present ${file.path}: not a regular file`, 'FS_NOT_REGULAR_FILE') const target = await ctx.fs.resolve(file.path, options) const info = await ctx.fs.stat(target, exec.signal) if (info === undefined) throw new FsError(`Cannot present ${file.path}: file not found. Check the path, create the file if needed, and retry.`, 'FS_NOT_FOUND') - if (info.type !== 'file') throw new Error(`Cannot present ${file.path}: not a regular file`) + if (info.type !== 'file') throw new FsError(`Cannot present ${file.path}: not a regular file`, 'FS_NOT_REGULAR_FILE') files.push({ ...file, path: ctx.fs.processPath(target) }) } exec.signal.throwIfAborted() diff --git a/packages/deliverables/tool-present/tests/present.spec.ts b/packages/deliverables/tool-present/tests/present.spec.ts index 18da272027..6492740c99 100644 --- a/packages/deliverables/tool-present/tests/present.spec.ts +++ b/packages/deliverables/tool-present/tests/present.spec.ts @@ -140,9 +140,19 @@ describe('present', () => { const { root, owner, execute } = await setup() await writeFile(join(root, 'large'), 'four') await symlink(tmpdir(), join(root, 'outside')) - for (const files of [[], [{ path: '' }], [{ path: 'missing' }], [{ path: '.' }], [{ path: 'outside' }], [{ path: 'large' }, { path: 'large' }, { path: 'large' }]]) { + const invalidArgs = { name: 'ToolArgsError', code: 'INVALID_ARGS' } + const notRegular = { name: 'FsError', code: 'FS_NOT_REGULAR_FILE' } + for (const [files, info] of [ + [[], invalidArgs], + [[{ path: '' }], invalidArgs], + [[{ path: 'missing' }], { name: 'FsError', code: 'FS_NOT_FOUND' }], + [[{ path: '.' }], notRegular], + [[{ path: 'outside' }], notRegular], + [[{ path: 'large' }, { path: 'large' }, { path: 'large' }], invalidArgs], + ] as const) { const result = await execute(files) expect(result.isError, JSON.stringify(files)).toBe(true) + expect(result.error?.info, JSON.stringify(files)).toEqual(info) } expect(owner.session.snapshotEvents().some(event => event.type === 'deliverables/presented')).toBe(false) }) @@ -163,9 +173,13 @@ it('validates deployment limits before registering the tool', async () => { it('requires an agent, an open turn, and a workspace', async () => { const { ctx, owner, execute } = await setup() const detached = await executeToolFixture(ctx, { signal: new AbortController().signal, callId: ToolCallId('detached'), name: 'present', arguments: { files: [{ path: 'a' }] } }) + const contextUnavailable = { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } expect(detached.isError).toBe(true) + expect(detached.error?.info).toEqual(contextUnavailable) owner.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - expect((await execute([{ path: 'a' }])).isError).toBe(true) + const closed = await execute([{ path: 'a' }]) + expect(closed.isError).toBe(true) + expect(closed.error?.info).toEqual(contextUnavailable) const noWorkspace = await agent(ctx, undefined) noWorkspace.session.append('turn/start', { turn: 1 }) const absent = await executeToolFixture(ctx, { signal: new AbortController().signal, callId: ToolCallId('no-workspace'), name: 'present', arguments: { files: [{ path: 'a' }] }, agent: noWorkspace }) @@ -188,7 +202,9 @@ it('refuses a final symlink to an ordinary file', async () => { const { root, execute } = await setup() await writeFile(join(root, 'source'), 'source') await symlink(join(root, 'source'), join(root, 'link')) - expect((await execute([{ path: 'link' }])).isError).toBe(true) + const result = await execute([{ path: 'link' }]) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_NOT_REGULAR_FILE' }) }) @@ -197,5 +213,7 @@ it('refuses a file replaced by a directory after inspecting its final component' await writeFile(join(root, 'source'), 'source') const directory = await ctx.fs.stat(await ctx.fs.resolve(root)) vi.spyOn(ctx.fs, 'stat').mockResolvedValueOnce(directory) - expect((await execute([{ path: 'source' }])).isError).toBe(true) + const result = await execute([{ path: 'source' }]) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_NOT_REGULAR_FILE' }) }) From ea2e1163c088292e25558527477cddff5bb63750 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:30:56 +0800 Subject: [PATCH 030/438] feat(tool-fs): add ImageInputError for read_image failures read_image refusals throw ImageInputError with a closed code list (IMAGE_UNSUPPORTED_MODEL, IMAGE_UNSUPPORTED_FORMAT, IMAGE_TYPE_MISMATCH, IMAGE_INVALID, IMAGE_TOO_LARGE, IMAGE_CONVERSION_FAILED, IMAGE_STORE_FAILED). Attachment-store rejections are classified at the tool boundary, keeping the AttachmentError as cause; HarnessError and AbortError pass through. An empty file_path throws ToolArgsError, and a missing model route or attachment service throws ToolContextUnavailableError. The README records that argument-check messages now carry the ToolArgsError "invalid arguments: " prefix. --- packages/fs/tool-fs/README.i18n.yaml | 12 +- packages/fs/tool-fs/README.md | 7 +- packages/fs/tool-fs/README.zh.md | 7 +- packages/fs/tool-fs/src/image-error.ts | 46 +++++ packages/fs/tool-fs/src/index.ts | 2 + packages/fs/tool-fs/src/read-image.ts | 144 ++++++++++------ packages/fs/tool-fs/tests/read-image.spec.ts | 163 +++++++++++++----- .../read-image-text-route/session.v4.jsonl | 2 +- 8 files changed, 274 insertions(+), 109 deletions(-) create mode 100644 packages/fs/tool-fs/src/image-error.ts diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index a421441ff4..15125f4f7e 100644 --- a/packages/fs/tool-fs/README.i18n.yaml +++ b/packages/fs/tool-fs/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9bddebaf4aff0a8d zh: fea0196162e3fcd1 /deepseek-ai-dsh-tool-fs/use-this-package/failures-and-recovery: - en: f7c7834de37e1ece - zh: ff08efcf7c08379a + en: 177d25a1e8f7afbd + zh: 0303980d6b2789c3 /deepseek-ai-dsh-tool-fs/understand-the-implementation: en: e30f7038c28e93f8 zh: a3868dbd90367b13 @@ -39,8 +39,8 @@ en: 1f4d7213aa3d0d60 zh: aa6573f96c8b5220 /deepseek-ai-dsh-tool-fs/understand-the-implementation/source-map: - en: 459b773aafc6c163 - zh: ccd729aded7d98ba + en: 791043de5ce46710 + zh: c5315d0195908f83 /deepseek-ai-dsh-tool-fs/understand-the-implementation/per-tool-flow: en: 35fbee1ef9811806 zh: 17c725e2b742c073 @@ -126,8 +126,8 @@ en: 2d4f2c8605eccab3 zh: 67f1f0218f73c6bf /deepseek-ai-dsh-tool-fs/model-experience/tool-errors/what-the-model-sees: - en: 4e8fac7bac8ced61 - zh: 7ba921dbcddc9f97 + en: 816a5ac724377eeb + zh: 6833892230a1264c /deepseek-ai-dsh-tool-fs/model-experience/tool-errors/token-effect: en: 681cadd5be7b8ac1 zh: 65e483f62fb819d9 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index aabec263d2..d7e519d577 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -83,7 +83,9 @@ With the policy plugin mounted, `write` and `edit` obtain their guard from the ` For `apply_patch`, syntax and preflight refusals throw with `isError: true` before any disk change. `FsError` preserves filesystem codes; `PatchToolError extends HarnessError` carries `PATCH_SYNTAX` and `PATCH_SYMLINK_SOURCE`. Once commit starts, the tool returns a value with `isError: false` even on failure or uncertainty, so known partial effects retain their diff metadata; a call cancelled during commit receives the tool registry's abort result like every other tool, and its completed changes remain visible through Review. `phase`, `cancelled`, ordered `operations` and `affectedPaths` describe the commit; each operation retains its index, kind, display paths, patch line, status, diagnostic and known changes. Full `before`/`after` text serves rendering and PTC; the Session stores the rendered result plus `meta.diffs` and `meta.stopped`. Creations store no diff, as for `write`; deletions and move sources store a removal diff only when the provider returned a bounded basis, using `newText: ''` because `FileDiff.newText` cannot be null. -Failures are normalized as `Error: ` with a structured code preserved for callers. Stable messages include `file_path must be a non-empty string`, `limit must be less than or equal to `, `cannot read "": not found`, `cannot read "": not a regular file`, and the image-route refusal `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. +`read_image` refusals throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model), `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file), `IMAGE_TYPE_MISMATCH` (rename or convert the file), `IMAGE_INVALID` (truncated or corrupt bytes), `IMAGE_TOO_LARGE` (downscale the image), `IMAGE_CONVERSION_FAILED` (a 16-bit PNG could not be normalized; convert it to 8-bit), and `IMAGE_STORE_FAILED` (any other attachment-store failure, kept as `cause`). An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; an `AbortError` or another `HarnessError` from the store passes through unchanged. + +Failures are normalized as `Error: ` with a structured code preserved for callers. Stable messages include the `ToolArgsError` (`INVALID_ARGS`) messages `invalid arguments: file_path must be a non-empty string` and `invalid arguments: limit must be less than or equal to `, `cannot read "": not found`, `cannot read "": not a regular file`, and the image-route refusal `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. ----- @@ -106,6 +108,7 @@ The tools are the executor; policy is an event gate. The tools inject no policy | [`src/index.ts`](src/index.ts) | Plugin entry: `Config`, tool composition, `read_image` attachments gate | | [`src/read.ts`](src/read.ts) | `read` executor: one stat, streaming decision, window build, observation | | [`src/read-image.ts`](src/read-image.ts) | `read_image` executor: route and media-type gates, bounded bytes, attachment save | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` and its closed `read_image` failure codes | | [`src/write.ts`](src/write.ts) | `write` executor: intent waterfall, atomic write, observation | | [`src/apply-patch.ts`](src/apply-patch.ts), [`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` registration, strict commit values and compact diagnostics | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | Pure call previews and known result diffs | @@ -246,7 +249,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Failures are normalized as `Error: `. This package's stable validation and read messages are `file_path must be a non-empty string`, `limit must be less than or equal to `, `old_string must be a non-empty string`, `old_string and new_string must differ`, `cannot read "": not found`, `cannot read "": not a regular file`, `offset is out of range for "" ( lines)`, `cannot read "": the extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`, `cannot read "": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`, `cannot read "": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`, `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`, and the mismatch repair `cannot read "": the extension declares , but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats` (an extension-less mismatch reports `cannot read "": the file signature claims , but the bytes decode as a different image format; the file may be corrupt`). A failed 16-bit conversion reports `cannot read "": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`. Provider and policy templates are quoted in their package READMEs. The model-facing error wrapper normalizes every `FS_NOT_OBSERVED` source to `cannot modify "": file has not been read — read the file, then retry`; `FS_STALE_VERSION` keeps the provider's reason and adds `— re-read the file, then retry`. Both retain the structured error code and original cause. After that reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. +Failures are normalized as `Error: `. This package's stable validation messages are `ToolArgsError` (`INVALID_ARGS`) messages prefixed with `invalid arguments: `: `file_path must be a non-empty string`, `limit must be less than or equal to `, `old_string must be a non-empty string`, and `old_string and new_string must differ`. Its stable read messages are `cannot read "": not found`, `cannot read "": not a regular file`, `offset is out of range for "" ( lines)`, `cannot read "": the extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`, `cannot read "": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`, `cannot read "": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`, `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`, and the mismatch repair `cannot read "": the extension declares , but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats` (an extension-less mismatch reports `cannot read "": the file signature claims , but the bytes decode as a different image format; the file may be corrupt`). A failed 16-bit conversion reports `cannot read "": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`. Provider and policy templates are quoted in their package READMEs. The model-facing error wrapper normalizes every `FS_NOT_OBSERVED` source to `cannot modify "": file has not been read — read the file, then retry`; `FS_STALE_VERSION` keeps the provider's reason and adds `— re-read the file, then retry`. Both retain the structured error code and original cause. After that reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. #### Token effect diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 2f5f153ed0..7e81223b57 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -83,7 +83,9 @@ kind: "package-reference" `apply_patch` 的语法与预检拒绝在磁盘变更前抛错,结果为 `isError: true`。`FsError` 保留文件系统错误码;`PatchToolError extends HarnessError` 携带 `PATCH_SYNTAX` 和 `PATCH_SYMLINK_SOURCE`。进入提交后,即使失败或结果不确定也返回 `isError: false` 的值,确保已知部分效果的 diff 元数据得以保留;提交期间被取消的调用与其他工具一样收到工具注册表的中止结果,已完成的变更仍可通过 Review 查看。`phase`、`cancelled`、有序 `operations` 与 `affectedPaths` 描述提交;每条操作保留索引、种类、展示路径、补丁行号、状态、诊断与已知变更。完整 `before`/`after` 文本供渲染和 PTC 使用;Session 保存渲染文本以及 `meta.diffs` 与 `meta.stopped`。新建与 `write` 一样不保存 diff;删除与移动源仅在提供方返回有界基线时保存删除 diff,并使用 `newText: ''`,因为 `FileDiff.newText` 不可为 null。 -失败被规范化为 `Error: `,并为调用方保留结构化错误码。稳定消息包括 `file_path must be a non-empty string`、`limit must be less than or equal to `、`cannot read "": not found`、`cannot read "": not a regular file`,以及图像路由拒绝 `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。 +`read_image` 的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)、`IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)、`IMAGE_TYPE_MISMATCH`(重命名或转换文件)、`IMAGE_INVALID`(字节被截断或损坏)、`IMAGE_TOO_LARGE`(缩小图像)、`IMAGE_CONVERSION_FAILED`(16 位 PNG 无法规范化;转换为 8 位)以及 `IMAGE_STORE_FAILED`(其他附件存储失败,原错误保留为 `cause`)。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的 `AbortError` 或其他 `HarnessError` 原样传递。 + +失败被规范化为 `Error: `,并为调用方保留结构化错误码。稳定消息包括 `ToolArgsError`(`INVALID_ARGS`)消息 `invalid arguments: file_path must be a non-empty string` 与 `invalid arguments: limit must be less than or equal to `、`cannot read "": not found`、`cannot read "": not a regular file`,以及图像路由拒绝 `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。 ----- @@ -106,6 +108,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 插件入口:`Config`、工具组合、`read_image` 附件门禁 | | [`src/read.ts`](src/read.ts) | `read` 执行器:一次 stat、流式决策、窗口构建、观察 | | [`src/read-image.ts`](src/read-image.ts) | `read_image` 执行器:路由与媒体类型门禁、有界字节、附件保存 | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` 及其封闭的 `read_image` 失败码 | | [`src/write.ts`](src/write.ts) | `write` 执行器:意图 waterfall、原子写入、观察 | | [`src/apply-patch.ts`](src/apply-patch.ts)、[`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` 注册、严格提交值与精简诊断 | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | 纯调用预览与已知结果 diff | @@ -246,7 +249,7 @@ Read a file before editing it unless you just created or edited it in this sessi #### 模型看到的内容 -失败会规范化为 `Error: `。本包稳定的校验和读取消息是 `file_path must be a non-empty string`、`limit must be less than or equal to `、`old_string must be a non-empty string`、`old_string and new_string must differ`、`cannot read "": not found`、`cannot read "": not a regular file`、`offset is out of range for "" ( lines)`、`cannot read "": the extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`、`cannot read "": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`、`cannot read "": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`、`cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`,以及类型不匹配的修复消息 `cannot read "": the extension declares , but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`(无扩展名路径的不匹配报告 `cannot read "": the file signature claims , but the bytes decode as a different image format; the file may be corrupt`)。16-bit 转换失败会报告 `cannot read "": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`。提供方和策略模板在各自包的 README 中逐字列出。模型侧错误包装把所有 `FS_NOT_OBSERVED` 来源规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。两者都保留结构化错误码和原始原因。该次重新读取确认缺失后,`edit` 会报告 `FS_NOT_FOUND`,而不会重复陈旧恢复指令;`write` 则使用带防护的创建。 +失败会规范化为 `Error: `。本包稳定的校验消息是带 `invalid arguments: ` 前缀的 `ToolArgsError`(`INVALID_ARGS`)消息:`file_path must be a non-empty string`、`limit must be less than or equal to `、`old_string must be a non-empty string` 与 `old_string and new_string must differ`。稳定的读取消息是 `cannot read "": not found`、`cannot read "": not a regular file`、`offset is out of range for "" ( lines)`、`cannot read "": the extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`、`cannot read "": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`、`cannot read "": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`、`cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`,以及类型不匹配的修复消息 `cannot read "": the extension declares , but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`(无扩展名路径的不匹配报告 `cannot read "": the file signature claims , but the bytes decode as a different image format; the file may be corrupt`)。16-bit 转换失败会报告 `cannot read "": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`。提供方和策略模板在各自包的 README 中逐字列出。模型侧错误包装把所有 `FS_NOT_OBSERVED` 来源规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。两者都保留结构化错误码和原始原因。该次重新读取确认缺失后,`edit` 会报告 `FS_NOT_FOUND`,而不会重复陈旧恢复指令;`write` 则使用带防护的创建。 #### Token 影响 diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts new file mode 100644 index 0000000000..102942e9c6 --- /dev/null +++ b/packages/fs/tool-fs/src/image-error.ts @@ -0,0 +1,46 @@ +/** Typed `read_image` failures. @module @deepseek-ai/dsh-tool-fs/src/image-error */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every machine-routable `read_image` failure code: + * + * - `IMAGE_UNSUPPORTED_MODEL`: the calling route does not declare image input; switch to an image-capable model. + * - `IMAGE_UNSUPPORTED_FORMAT`: the extension, the file signature, or the deployment's accepted media types + * exclude the format; convert the file to an accepted format or read another file. + * - `IMAGE_TYPE_MISMATCH`: the extension or file signature declares one format but the bytes decode as another; rename or convert the file. + * - `IMAGE_INVALID`: bytes in a supported format do not decode; the file is truncated or corrupt. + * - `IMAGE_TOO_LARGE`: a side, the decoded pixel count, or the stored byte budget exceeds the deployment limit; + * downscale the image and read the smaller copy. + * - `IMAGE_CONVERSION_FAILED`: a 16-bit PNG could not be normalized to 8-bit sRGB; convert it to an 8-bit format. + * - `IMAGE_STORE_FAILED`: the attachment store could not commit the image for another reason; report the cause + * instead of retrying unchanged. + */ +export const IMAGE_INPUT_ERROR_CODES = [ + 'IMAGE_UNSUPPORTED_MODEL', + 'IMAGE_UNSUPPORTED_FORMAT', + 'IMAGE_TYPE_MISMATCH', + 'IMAGE_INVALID', + 'IMAGE_TOO_LARGE', + 'IMAGE_CONVERSION_FAILED', + 'IMAGE_STORE_FAILED', +] as const + +/** One `read_image` failure code. */ +export type ImageInputErrorCode = typeof IMAGE_INPUT_ERROR_CODES[number] + +/** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */ +export class ImageInputError extends HarnessError { + override readonly code: ImageInputErrorCode + + /** + * @param message - model-facing refusal naming the path and the safe next step. + * @param code - stable failure code. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: ImageInputErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'ImageInputError' + this.code = code + } +} diff --git a/packages/fs/tool-fs/src/index.ts b/packages/fs/tool-fs/src/index.ts index 41e3be251c..9e3e3095d5 100644 --- a/packages/fs/tool-fs/src/index.ts +++ b/packages/fs/tool-fs/src/index.ts @@ -17,6 +17,8 @@ import { applyReadImageTool } from './read-image.ts' import { READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from './read-render.ts' import { FsSandboxController } from './sandbox.ts' +export { ImageInputError, type ImageInputErrorCode } from './image-error.ts' + /** Cordis plugin name used by loader diagnostics. */ export const name = 'tool-fs' diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 4a452e21c4..b8bacbcba4 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -16,9 +16,12 @@ import type { Context } from '@deepseek-ai/cordis' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { AttachmentStore, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { ImageInputError } from './image-error.ts' import { resolveRegularReadTarget } from './read-target.ts' /** Extensions `read_image` accepts; magic-byte validation at the attachment service stays authoritative. */ @@ -116,6 +119,8 @@ export function imageMediaTypeForPath(filePath: string): ImageMediaType | undefi * @param ctx - the plugin context used to resolve the optional `llm` service. * @param exec - the tool-execution context supplying the calling agent. * @param requestedPath - the raw, not-yet-resolved path rendered in refusal messages. + * @throws ToolContextUnavailableError when no Agent route or `llm` service is available. + * @throws ImageInputError `IMAGE_UNSUPPORTED_MODEL` when the route does not declare image input. */ export async function assertImageCapableRoute(ctx: Context, exec: ToolExecution, requestedPath: string): Promise { const routed = exec.agent?.session.requestHeader()?.config @@ -123,18 +128,21 @@ export async function assertImageCapableRoute(ctx: Context, exec: ToolExecution, const model = routed?.model ?? exec.agent?.options.model const llm = ctx.get('llm') if (provider === undefined || model === undefined || llm === undefined) { - throw new Error(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`) + throw new ToolContextUnavailableError(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`) } const active = await llm.resolveModelInfo(provider, model, exec.signal) if (active.inputModalities === undefined || !active.inputModalities.includes('image')) { - throw new Error(`cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`) + throw new ImageInputError( + `cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`, + 'IMAGE_UNSUPPORTED_MODEL', + ) } } /** Refuse a media type outside the deployment's accepted set, naming the offending path. */ function assertDeploymentAccepts(attachments: AttachmentStore, mediaType: ImageMediaType, displayPath: string): void { if (!attachments.imageLimits.mediaTypes.includes(mediaType)) { - throw new Error(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`) + throw new ImageInputError(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`, 'IMAGE_UNSUPPORTED_FORMAT') } } @@ -197,6 +205,72 @@ function imageReadContent(value: ImageReadValue): ContentBlock[] { ] } +/** Facts about one image read that a save-failure report names. */ +interface SaveFailureFacts { + displayPath: string + /** Lower-cased path extension; empty for an extension-less path. */ + extension: string + mediaType: ImageMediaType + /** Whether `mediaType` came from the file signature instead of the extension. */ + sniffed: boolean +} + +/** + * Classify one `saveImage` rejection as the error `read_image` throws. + * An `AbortError` and an already classified `HarnessError` pass through + * unchanged; attachment admission codes become {@link ImageInputError} codes, + * and every other failure becomes `IMAGE_STORE_FAILED` with the original as `cause`. + * @param error - the value `saveImage` rejected with. + * @param attachments - the store whose limits the refusal names. + * @param facts - the path and media-type facts the refusal names. + * @returns the error to throw from the tool body. + */ +function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFailureFacts): unknown { + if (error instanceof HarnessError || (error instanceof Error && error.name === 'AbortError')) return error + const { displayPath, extension, mediaType, sniffed } = facts + const refusal = (detail: string, code: ImageInputError['code']) => + new ImageInputError(`cannot read "${displayPath}": ${detail}`, code, { cause: error }) + const storeFailed = (detail: string) => refusal(`the attachment store could not save the image: ${detail}`, 'IMAGE_STORE_FAILED') + if (!(error instanceof AttachmentError)) return storeFailed(error instanceof Error ? error.message : String(error)) + // Size refusals stay recoverable tool errors: an oversized image must never + // enter durable history, where it would ride every later model request past + // provider-side dimension rejections. + switch (error.code) { + case 'IMAGE_DIMENSION_TOO_LARGE': + return refusal(`at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + case 'IMAGE_TOO_MANY_PIXELS': + return refusal(`the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + case 'IMAGE_TOO_LARGE': + case 'IMAGES_TOO_LARGE': + return refusal('the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy', 'IMAGE_TOO_LARGE') + case 'UNSUPPORTED_IMAGE_TYPE': + return refusal(`${mediaType} images are not accepted by this deployment`, 'IMAGE_UNSUPPORTED_FORMAT') + case 'INVALID_IMAGE': + return refusal('the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt', 'IMAGE_INVALID') + case 'IMAGE_TYPE_MISMATCH': + return sniffed + ? refusal(`the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, 'IMAGE_TYPE_MISMATCH') + : refusal(`the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, 'IMAGE_TYPE_MISMATCH') + case 'ATTACHMENT_WRITE_FAILED': + return /16-bit PNG/iu.test(error.message) + ? refusal('the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry', 'IMAGE_CONVERSION_FAILED') + : storeFailed(error.message) + case 'TOO_MANY_IMAGES': + case 'INVALID_IMAGE_BASE64': + case 'INVALID_FILE_BASE64': + case 'INVALID_ATTACHMENT_REF': + case 'ATTACHMENT_CORRUPT': + case 'ATTACHMENT_NOT_FOUND': + case 'ATTACHMENT_READ_FAILED': + case 'ATTACHMENT_PROJECTION_UNSUPPORTED': + case 'ATTACHMENT_FILES_UNSUPPORTED': + return storeFailed(error.message) + /* v8 ignore next -- Closed AttachmentErrorCode union; assertNever checks exhaustiveness at compile time. */ + default: + return assertNever(error.code) + } +} + /** * Register the `read_image` tool into the given context. The composing plugin * owns the attachments gate: `src/index.ts` calls this inside @@ -238,7 +312,7 @@ export function applyReadImageTool(ctx: Context): void { // of the same file cannot conflict. isConcurrencySafe: () => true, async execute(args, exec) { - if (args.file_path.trim().length === 0) throw new Error('file_path must be a non-empty string') + if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string']) // Every pre-read gate runs before any filesystem I/O so a refusal never // leaks partial reads or attachment writes. An extension-less path @@ -247,11 +321,14 @@ export function applyReadImageTool(ctx: Context): void { const extension = extname(args.file_path).toLowerCase() const declared = imageMediaTypeForPath(args.file_path) if (declared === undefined && extension !== '') { - throw new Error(`cannot read "${args.file_path}": the ${extension} extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`) + throw new ImageInputError( + `cannot read "${args.file_path}": the ${extension} extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`, + 'IMAGE_UNSUPPORTED_FORMAT', + ) } const attachments = ctx.get('attachments') if (attachments === undefined) { - throw new Error(`cannot read "${args.file_path}" as an image: no attachment service is mounted`) + throw new ToolContextUnavailableError(`cannot read "${args.file_path}" as an image: no attachment service is mounted`) } if (declared !== undefined) assertDeploymentAccepts(attachments, declared, args.file_path) await assertImageCapableRoute(ctx, exec, args.file_path) @@ -264,7 +341,10 @@ export function applyReadImageTool(ctx: Context): void { const data = await ctx.fs.readBytes(target, exec.signal, byteCap) const mediaType = declared ?? sniffImageMediaType(data) if (mediaType === undefined) { - throw new Error(`cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`) + throw new ImageInputError( + `cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`, + 'IMAGE_UNSUPPORTED_FORMAT', + ) } if (declared === undefined) assertDeploymentAccepts(attachments, mediaType, target.displayPath) // Persist before returning: the image block must reference a durably @@ -273,51 +353,9 @@ export function applyReadImageTool(ctx: Context): void { try { ref = await attachments.saveImage({ data, mediaType, name: basename(target.displayPath) }) } catch (error: unknown) { - if (!(error instanceof AttachmentError)) throw error - // Dimension refusals stay recoverable tool errors: an oversized image - // must never enter durable history, where it would ride every later - // model request past provider-side dimension rejections. - if (error.code === 'IMAGE_DIMENSION_TOO_LARGE') { - throw new Error( - `cannot read "${target.displayPath}": at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, - { cause: error }, - ) - } - if (error.code === 'IMAGE_TOO_MANY_PIXELS') { - throw new Error( - `cannot read "${target.displayPath}": the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, - { cause: error }, - ) - } - if (error.code === 'IMAGE_TOO_LARGE') { - throw new Error( - `cannot read "${target.displayPath}": the image cannot be stored within the deployment's byte limits; downscale the image and read the smaller copy`, - { cause: error }, - ) - } - if (error.code === 'ATTACHMENT_WRITE_FAILED' && /16-bit PNG/iu.test(error.message)) { - throw new Error( - `cannot read "${target.displayPath}": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`, - { cause: error }, - ) - } - if (error.code === 'INVALID_IMAGE' && declared === undefined) { - throw new Error( - `cannot read "${target.displayPath}": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`, - { cause: error }, - ) - } - if (error.code !== 'IMAGE_TYPE_MISMATCH') throw error - if (declared === undefined) { - throw new Error( - `cannot read "${target.displayPath}": the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, - { cause: error }, - ) - } - throw new Error( - `cannot read "${target.displayPath}": the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, - { cause: error }, - ) + throw saveFailure(error, attachments, { + displayPath: target.displayPath, extension, mediaType, sniffed: declared === undefined, + }) } ctx.emit('fs/observed', target, { kind: 'present', version: info.version }, exec) const value: ImageReadValue = { diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index 97087edf7e..6c2feac7a4 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -26,6 +26,7 @@ import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy' import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' import { AttachmentError, AttachmentId, AttachmentStore } from '@deepseek-ai/dsh-attachment' +import { FsError } from '@deepseek-ai/dsh-fs' import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, StoredImageAttachment } from '@deepseek-ai/dsh-attachment' import * as ToolFs from '@deepseek-ai/dsh-tool-fs' import { @@ -372,6 +373,7 @@ describe('extension-less paths', () => { const trailingDot = await readImage(ctx, { file_path: 'foo.' }, agentOn('vision-model')) expect(trailingDot.isError).toBe(true) expect(text(trailingDot)).toContain('cannot read "foo.": the . extension does not declare a supported image format') + expect(trailingDot.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_FORMAT' }) const dotfile = await readImage(ctx, { file_path: '.hidden' }, agentOn('vision-model')) expect(dotfile.isError).toBe(false) @@ -386,6 +388,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'notes' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain(`cannot read "${join(dir, 'notes')}": the file content is not a supported image format`) + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_FORMAT' }) }) it('explains extension-less bytes that sniff as an image but do not decode', async () => { @@ -394,6 +397,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'broken' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('do not decode as a supported PNG/JPEG/WebP/GIF image') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_INVALID' }) }) it('applies the deployment media-type policy to the sniffed format', async () => { @@ -426,6 +430,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'avatar' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('image/png images are not accepted by this deployment') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_FORMAT' }) }) it('names a signature/decoded-format disagreement on an extension-less path', async () => { @@ -458,6 +463,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'sniffed' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('the file signature claims image/png, but the bytes decode as a different image format') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) }) }) @@ -484,6 +490,7 @@ describe('strict image-modality gate', () => { const result = await readImage(ctx, { file_path: 'red.png' }, agentOn(model)) expect(result.isError).toBe(true) expect(text(result)).toContain('does not declare image input') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_MODEL' }) }) it('refuses when the route cannot be resolved (no agent, or no header and no options)', async () => { @@ -492,10 +499,12 @@ describe('strict image-modality gate', () => { const noAgent = await readImage(ctx, { file_path: 'red.png' }) expect(noAgent.isError).toBe(true) expect(text(noAgent)).toContain('route could not be resolved') + expect(noAgent.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) const noRoute = await readImage(ctx, { file_path: 'red.png' }, agentOn(undefined)) expect(noRoute.isError).toBe(true) expect(text(noRoute)).toContain('route could not be resolved') + expect(noRoute.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('refuses when no llm service is mounted', async () => { @@ -504,6 +513,7 @@ describe('strict image-modality gate', () => { const result = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('route could not be resolved') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) }) @@ -512,11 +522,13 @@ describe('argument and service preconditions', () => { const ctx = await setup() const empty = await readImage(ctx, { file_path: ' ' }, agentOn('vision-model')) expect(empty.isError).toBe(true) - expect(text(empty)).toContain('non-empty') + expect(text(empty)).toContain('file_path must be a non-empty string') + expect(empty.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const nonImage = await readImage(ctx, { file_path: 'notes.txt' }, agentOn('vision-model')) expect(nonImage.isError).toBe(true) expect(text(nonImage)).toContain('the .txt extension does not declare a supported image format') + expect(nonImage.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_FORMAT' }) }) it.each([{}, { toolFs: { read: false, write: false, edit: false } }] satisfies SetupOptions[]) @@ -537,6 +549,7 @@ describe('argument and service preconditions', () => { const result = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('no attachment service is mounted') + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) }) it('refuses a media type the deployment does not accept', async () => { @@ -568,6 +581,7 @@ describe('argument and service preconditions', () => { const result = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('image/png images are not accepted by this deployment') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_UNSUPPORTED_FORMAT' }) }) }) @@ -579,6 +593,7 @@ describe('image admission failures', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('the .jpg extension declares image/jpeg') expect(text(result)).toContain('rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) }) it('caps an extension-less read at maxImageBytes before format detection', async () => { @@ -587,6 +602,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'red' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('exceeds') + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_TOO_LARGE' }) }) it('honors the tighter per-message aggregate byte bound', async () => { @@ -595,6 +611,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('exceeds') + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_TOO_LARGE' }) }) it('surfaces the pixel limit from the attachment admission', async () => { @@ -603,6 +620,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'big.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('exceeds the 4-pixel decoded-size limit') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) @@ -612,61 +630,114 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'wide.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('at least one image side exceeds the 2px limit') + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) - it('passes storage faults and non-attachment failures through unchanged', async () => { - /** Store whose commit fails with a configurable error; admission itself passes. */ - class FailingStore extends AttachmentStore { - static failure: unknown - readonly imageLimits: ImageAttachmentLimits = Object.freeze({ - maxImageBytes: 1024, - maxImagesPerMessage: 1, - maxMessageImageBytes: 1024, - maxImagePixels: 100, - maxImageDimension: 2000, - mediaTypes: Object.freeze(['image/png'] as const), - }) + /** Store whose commit runs a configurable failure; admission itself passes. */ + class FailingStore extends AttachmentStore { + static failure: () => unknown = () => new Error('unset') + readonly imageLimits: ImageAttachmentLimits = Object.freeze({ + maxImageBytes: 1024, + maxImagesPerMessage: 1, + maxMessageImageBytes: 1024, + maxImagePixels: 100, + maxImageDimension: 2000, + mediaTypes: Object.freeze(['image/png'] as const), + }) - validateImage(_input: SaveImageAttachment): Promise { - return Promise.resolve() - } - - async saveImage(_input: SaveImageAttachment): Promise { - throw FailingStore.failure - } - - readImage(_ref: ImageAttachmentRef): Promise { - throw new Error('unreachable in this test') - } + validateImage(_input: SaveImageAttachment): Promise { + return Promise.resolve() } - await writeFile(join(dir, 'red.png'), PNG_1X1) + + async saveImage(_input: SaveImageAttachment): Promise { + throw FailingStore.failure() + } + + readImage(_ref: ImageAttachmentRef): Promise { + throw new Error('unreachable in this test') + } + } + + async function failingSave(failure: () => unknown, file = 'red.png', signal = testToolSignal) { + await writeFile(join(dir, file), PNG_1X1) const ctx = await setup({ attachments: false }) await ctx.plugin(FailingStore) + FailingStore.failure = failure + return executeToolFixture(ctx, { + signal, + callId: ToolCallId(`img-call-${++callCounter}`), + name: 'read_image', + arguments: { file_path: file }, + agent: agentOn('vision-model') as never, + }) + } - FailingStore.failure = new AttachmentError('Unable to persist image attachment.', 'ATTACHMENT_WRITE_FAILED') - const storageFault = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) - expect(storageFault.isError).toBe(true) - expect(text(storageFault)).toContain('Unable to persist image attachment.') + it.each([ + ['IMAGE_TOO_LARGE', 'Image cannot be encoded within the configured normalized-image byte cap.', 'IMAGE_TOO_LARGE', + 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], + ['IMAGES_TOO_LARGE', 'Image batch exceeds the configured aggregate image-byte limit.', 'IMAGE_TOO_LARGE', + 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], + ['UNSUPPORTED_IMAGE_TYPE', 'Image type image/png is not accepted by this deployment.', 'IMAGE_UNSUPPORTED_FORMAT', + 'image/png images are not accepted by this deployment'], + ['INVALID_IMAGE', 'Unsupported or malformed image data.', 'IMAGE_INVALID', + 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt'], + ['ATTACHMENT_WRITE_FAILED', 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', 'IMAGE_CONVERSION_FAILED', + 'the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry'], + ['ATTACHMENT_WRITE_FAILED', 'Unable to persist attachment.', 'IMAGE_STORE_FAILED', + 'the attachment store could not save the image: Unable to persist attachment.'], + ...([ + 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', 'ATTACHMENT_CORRUPT', + 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', 'ATTACHMENT_FILES_UNSUPPORTED', + ] as const).map(code => [code, 'Stored attachment failed.', 'IMAGE_STORE_FAILED', + 'the attachment store could not save the image: Stored attachment failed.'] as const), + ] as const)('classifies AttachmentError %s (%s) as %s', async (attachmentCode, message, code, detail) => { + const cause = new AttachmentError(message, attachmentCode) + const result = await failingSave(() => cause) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ImageInputError', code }) + expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": ${detail}`) + }) - FailingStore.failure = new AttachmentError( - 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', - 'ATTACHMENT_WRITE_FAILED', - ) - const sixteenBit = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) - expect(text(sixteenBit)).toContain( - `cannot read "${join(dir, 'red.png')}": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`, - ) + it('wraps a non-attachment save failure as IMAGE_STORE_FAILED', async () => { + const result = await failingSave(() => new Error('unrelated infrastructure failure')) + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) + expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": the attachment store could not save the image: unrelated infrastructure failure`) - FailingStore.failure = new AttachmentError('Image cannot be encoded within the configured normalized-image byte cap.', 'IMAGE_TOO_LARGE') - const overBudget = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) - expect(overBudget.isError).toBe(true) - expect(text(overBudget)).toContain('cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy') + const nonError = await failingSave(() => 'string failure') + expect(nonError.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) + expect(text(nonError)).toContain('the attachment store could not save the image: string failure') - FailingStore.failure = new Error('unrelated infrastructure failure') - const unrelated = await readImage(ctx, { file_path: 'red.png' }, agentOn('vision-model')) - expect(unrelated.isError).toBe(true) - expect(text(unrelated)).toContain('unrelated infrastructure failure') + }) + + it('passes a classified HarnessError and an AbortError through unchanged', async () => { + const fsFailure = await failingSave(() => new FsError('cannot read "x": permission denied', 'FS_PERMISSION_DENIED')) + expect(fsFailure.error?.info).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' }) + expect(text(fsFailure)).toBe('Error: cannot read "x": permission denied') + + const abort = await failingSave(() => new DOMException('store stopped', 'AbortError')) + expect(text(abort)).toContain('store stopped') + expect(text(abort)).not.toContain('cannot read') + }) + + it('lets the registry classify an AbortError thrown after caller cancellation', async () => { + const controller = new AbortController() + const result = await failingSave(() => { + controller.abort() + return new DOMException('save cancelled', 'AbortError') + }, 'red.png', controller.signal) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' }) + expect(text(result)).not.toContain('cannot read') + }) + + it('classifies a save failure that is not cancellation even after the caller aborts', async () => { + const controller = new AbortController() + const result = await failingSave(() => { + controller.abort() + return new AttachmentError('Unable to persist attachment.', 'ATTACHMENT_WRITE_FAILED') + }, 'red.png', controller.signal) + expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) }) it('reports a missing image file and a directory target through the fs vocabulary', async () => { @@ -677,11 +748,13 @@ describe('image admission failures', () => { const missing = await readImage(ctx, { file_path: 'absent.png' }, agentOn('vision-model')) expect(missing.isError).toBe(true) expect(text(missing)).toContain('not found') + expect(missing.error?.info).toEqual({ name: 'FsError', code: 'FS_NOT_FOUND' }) expect(observed).toEqual([{ path: join(dir, 'absent.png'), kind: 'absent' }]) const directory = await readImage(ctx, { file_path: 'folder.png' }, agentOn('vision-model')) expect(directory.isError).toBe(true) expect(text(directory)).toContain('not a regular file') + expect(directory.error?.info).toEqual({ name: 'FsError', code: 'FS_NOT_REGULAR_FILE' }) }) it('omits the display name when the store returns a reference without one', async () => { diff --git a/snapshots/session/read-image-text-route/session.v4.jsonl b/snapshots/session/read-image-text-route/session.v4.jsonl index bd46aa46ef..3c4c5b47e6 100644 --- a/snapshots/session/read-image-text-route/session.v4.jsonl +++ b/snapshots/session/read-image-text-route/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Use read_image on red.png in","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"read-image-refused","name":"read_image","arguments":"{\"file_path\":\"red.png\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788699420816,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1788699420816,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"read-image-refused","name":"read_image","arguments":"{\"file_path\":\"red.png\"}"}}},{"type":"chunk","time":1788699420816,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788699420816,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"read-image-refused","name":"read_image","arguments":"{\"file_path\":\"red.png\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"read-image-refused"},"toolCallId":"read-image-refused","content":[{"type":"text","text":"Error: cannot read \"red.png\" as an image: model \"deepseek-v4-flash\" does not declare image input; switch to an image-capable model to read images"}],"isError":true,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"read-image-refused"},"toolCallId":"read-image-refused","content":[{"type":"text","text":"Error: cannot read \"red.png\" as an image: model \"deepseek-v4-flash\" does not declare image input; switch to an image-capable model to read images"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"ImageInputError","code":"IMAGE_UNSUPPORTED_MODEL"}},"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":"UNAVAILABLE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1788699420834,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1788699420834,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"UNAVAILABLE"}}},{"type":"chunk","time":1788699420834,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1788699420834,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} From d17fad9b9ee150e5b1372af2f7c06776568fc726 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 14:43:56 +0800 Subject: [PATCH 031/438] fix(agent): classify closed admission and document migration --- docs/subsystems/core.i18n.yaml | 4 ++-- docs/subsystems/core.md | 12 +++++++----- docs/subsystems/core.zh.md | 12 +++++++----- .../agent-closed-admission/guide.i18n.yaml | 16 ++++++++++++++++ .../v0.2.2-rc.1/agent-closed-admission/guide.md | 17 +++++++++++++++++ .../agent-closed-admission/guide.zh.md | 17 +++++++++++++++++ packages/core/agent-loop/src/index.ts | 7 ++----- packages/core/agent-loop/tests/cancel.spec.ts | 2 +- .../tests/fixtures/serial-created.mjs | 9 +++------ .../agent-loop/tests/input-lifecycle.spec.ts | 17 ++++++++++++----- packages/core/agent/README.i18n.yaml | 4 ++-- packages/core/agent/README.md | 2 ++ packages/core/agent/README.zh.md | 2 ++ packages/core/agent/src/closed-error.ts | 8 ++++---- packages/core/agent/src/runtime-types.ts | 10 +++++----- packages/sdk/server/src/server.ts | 5 ++--- packages/subagent/subagent/src/manager.ts | 3 +-- scripts/smoke-python-runtime.py | 1 - .../python-sdk-single-exe/advanced/result.json | 8 ++++---- .../advanced/session.1.v4.jsonl | 4 ++-- .../advanced/session.2.v4.jsonl | 4 ++-- 21 files changed, 110 insertions(+), 54 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 363584a5fd..c3495dec81 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,8 +12,8 @@ en: d71c669c1a36bf52 zh: 9b335f90c84a894e /core/the-agent-handle: - en: 6ee15fec81bc0686 - zh: b6f3fcd48823ea75 + en: bb0aec7a50800c1e + zh: a58a3392368f644a /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 7b8503cb1a..7e86e6e0d1 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -98,7 +98,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -113,7 +113,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -121,7 +121,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -131,7 +131,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -142,7 +142,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -374,6 +374,8 @@ The cause is a TypeScript-enforced same-process input. An active cancellation ho The [event taxonomy](../architecture.md#events) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits. +`AgentClosedError` extends `HarnessError` with code `AGENT_CLOSED` and the affected `agentId`. Admission closes when the caller cancels creation, the Agent starts disposal, or its factory begins shutdown. The creation signal stops governing admission after creation succeeds. + ## Initiating Agent The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules. diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 9f0bf51061..c82be05f03 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -102,7 +102,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -117,7 +117,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -125,7 +125,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -135,7 +135,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -146,7 +146,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -380,6 +380,8 @@ cause 是由 TypeScript 强制约束的同进程输入。活跃的取消持有 +`AgentClosedError` 继承 `HarnessError`,包含错误码 `AGENT_CLOSED` 和受影响的 `agentId`。调用方取消创建、Agent 开始释放或工厂开始关闭时,Agent 停止接纳新工作。创建成功后,创建信号不再控制工作接纳。 + ## 发起 Agent `ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;[initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.zh.md)定义其生命周期和作用域规则。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml new file mode 100644 index 0000000000..83fa03b9c8 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md +/: + en: e4666ee6e813e7a3 + zh: ab68705b61d0da3c +/handle-agent-input-rejected-during-shutdown: + en: 5ec42a6575141728 + zh: a5174b0e04526c58 +/handle-agent-input-rejected-during-shutdown/change: + en: def59fb50e36f026 + zh: 91e79aad0ea758ad +/handle-agent-input-rejected-during-shutdown/migration: + en: e4c7ffd0e06c01bf + zh: 7fc1f43747209fb7 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md new file mode 100644 index 0000000000..7aaff2efc6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Agent input and maintenance methods throw AgentClosedError once the Agent stops accepting new work." +--- + +# Handle Agent input rejected during shutdown + +English | [中文](guide.zh.md) + +## Change + +In v0.2.2-rc.1, a retained `Agent` could accept input while teardown was in progress. The Agent now rejects new input and maintenance work with `AgentClosedError` as soon as its lifetime is aborted. It can still appear in the registry while admitted work settles. + +## Migration + +1. In extensions that call `Agent.send`, `followup`, `steer`, `inject`, or `runMaintenance`, handle the synchronous `AgentClosedError` from `@deepseek-ai/dsh-agent` at the call site. Treat code `AGENT_CLOSED` as an unavailable Agent and preserve handling for other failures. +2. Verify by disposing an Agent with a maintenance task still settling. A subsequent input call throws `AgentClosedError` without adding an inbox entry. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md new file mode 100644 index 0000000000..9ee1eb17a1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Agent 停止接纳新工作后,输入和维护方法会抛出 AgentClosedError。" +--- + +# 处理关闭期间被拒绝的 Agent 输入 + +[English](guide.md) | 中文 + +## 变更 + +在 v0.2.2-rc.1 中,调用方持有的 `Agent` 在清理过程中仍可能接收输入。现在,Agent 的生命周期信号一旦中止,就会以 `AgentClosedError` 拒绝新输入和维护工作。已接纳的工作收尾期间,注册表中仍可能找到该 Agent。 + +## 迁移 + +1. 若扩展调用 `Agent.send`、`followup`、`steer`、`inject` 或 `runMaintenance`,请在调用处处理从 `@deepseek-ai/dsh-agent` 导出的同步异常 `AgentClosedError`。收到 `AGENT_CLOSED` 时按 Agent 不可用处理,保留其他失败的处理逻辑。 +2. 在维护任务尚未结束时开始释放 Agent 以验证改动。之后调用输入方法应抛出 `AgentClosedError`,且不向 inbox 添加条目。 diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index a0b02d4eee..ecdafadb9d 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -469,11 +469,8 @@ export class AgentLoop extends Service implements AgentFactory { const id = session.id const loopCtx = this.runtime.ctx - // Deactivation fuses three owners, each with its own reason: the caller's - // cancellation signal, the owner fiber's unload, and factory teardown. - // It is registered BEFORE any resource exists, over mutable slots, so an - // unload arriving while the scope is still minting finds a working - // disposer instead of a leak. + // The caller's signal governs creation. Owner disposal and factory + // shutdown can end the Agent's lifetime both during and after creation. const abort = new AbortController() const onCallerAbort = (): void => { abort.abort(callerSignal?.reason instanceof Error diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 2ca5eb0299..434857afe9 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -324,7 +324,7 @@ describe('Agent.cancel()', () => { send(agent, 'active') await streaming.promise const disposal = handle.dispose() - expect(() =>{ send(agent, 'late wake') }).toThrow(AgentClosedError) + expect(() => { send(agent, 'late wake') }).toThrow(AgentClosedError) await disposal expect(adapter.requests).toHaveLength(1) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 1295611023..2b27a7f33b 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,11 +6,11 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx, config = {}) { +export function apply(ctx) { const checkedCancellation = new WeakSet() ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { if (checkedCancellation.has(agent) - || (config.checkRootCancellation !== true && agent.session.header.origin !== 'subagent')) return next() + || agent.session.header.origin !== 'subagent') return next() checkedCancellation.add(agent) const pending = { id: randomUUID(), role: 'user', @@ -35,10 +35,7 @@ export function apply(ctx, config = {}) { agent.inbox.remove(pending.id) for (const message of messages) { const ordinary = message.source.kind === 'user' - const restored = message.source.kind === `plugin:${name}` - ? { ...message, content: [{ type: 'text', text: message.content[0].text + ' Queue-clear failures still cancel active work.' }] } - : message - agent.send(restored, ordinary ? 'next-turn' : 'next-step', ordinary) + agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary) } return next() }) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 560fea3ca1..3e9bb2cf10 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import AgentRegistry, { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -52,7 +52,6 @@ async function harness() { return { ctx, root, adapter, handle, agent: handle.agent } } - it('cancellation still aborts the running request when queue clearing fails', async () => { const { ctx, agent } = await harness() const entered = Promise.withResolvers() @@ -73,6 +72,7 @@ it('cancellation still aborts the running request when queue clearing fails', as }) expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') expect(signal.aborted).toBe(true) + expect(agent.inbox.nextTurn).toEqual([queued]) } finally { stopRejecting() hold() @@ -82,7 +82,6 @@ it('cancellation still aborts the running request when queue clearing fails', as } }) - it('an Agent still in the registry rejects new input while its owner is closing', async () => { const { ctx, agent, handle } = await harness() const release = Promise.withResolvers() @@ -96,6 +95,16 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') + const error = vi.fn((failure: unknown) => failure) + try { + agent.followup(message) + } catch (failure) { + error(failure) + } + expect(error).toHaveBeenCalledWith(expect.objectContaining({ + name: 'AgentClosedError', code: 'AGENT_CLOSED', agentId: agent.id, + })) + expect(error.mock.calls[0]?.[0]).toBeInstanceOf(HarnessError) for (const submit of [() => { agent.followup(message) }, () => { agent.steer(message) }, () => { agent.inject(message) }, () => { agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => { agent.inbox.append('next-turn', message) }, () => { agent.inbox.prepend('next-step', message) }, () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } @@ -108,8 +117,6 @@ it('an Agent still in the registry rejects new input while its owner is closing' } }) - - it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { const { ctx, agent, handle } = await harness() const release = Promise.withResolvers() diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index df3e29c8a9..6c21a72d7d 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: ff2b530bb20bcfe2 zh: 4f9024c4881a4ba5 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: - en: 2594a1e02adea801 - zh: cae8860369728efb + en: cec57f2cb7ab3a5c + zh: 2896b42eb5310441 /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: en: 371511fb13093dd2 zh: 4be81d246cf299b2 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 9772578fcc..024f69aeef 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -73,6 +73,8 @@ await handle.agent.whenIdle() `Agent.ctx` is the agent's scoped context: registrations made through it (tools, prompt sections, variables, event listeners, restrictions) apply to that agent alone and unwind on disposal. The same mechanism is what agent presets use to give one session a different capability set without affecting its neighbors. +Input and maintenance methods reject closed Agents with `AgentClosedError` (`AGENT_CLOSED`). See [Agent lifetime and admission](../../../docs/subsystems/core.md#the-agent-handle) for the lifecycle rules. + ### Intercept or observe work in flight `agent/request` is deprecated and retained for existing listeners. Do not add new listeners. Provider, model, and optional explicit reasoning effort are fixed at step preparation; listeners must preserve all three, including an absent effort. `AgentOptions.maxTokens` sets the output cap. Other per-request control overrides have no replacement API. See the [migration guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.md) for affected callers. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index b5b2af52d4..693ad615ce 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -73,6 +73,8 @@ await handle.agent.whenIdle() `Agent.ctx` 是该 agent 的作用域上下文:通过它进行的注册(工具、提示词段、变量、事件监听器、限制)只对该 agent 生效,并在 dispose(资源释放)时全部撤销。同一机制也是 agent preset 用来让一个会话获得不同能力集、同时不影响其邻居的方式。 +输入和维护方法会以 `AgentClosedError`(`AGENT_CLOSED`)拒绝已停止接纳新工作的 Agent。生命周期规则见 [Agent 句柄](../../../docs/subsystems/core.zh.md#the-agent-handle)。 + ### 拦截或观察进行中的工作 `agent/request` 已弃用,仅为现有监听器保留。不要添加新监听器。提供方、模型和可选的显式推理强度在步骤准备时固定;监听器必须保留三者,包括未指定强度的状态。`AgentOptions.maxTokens` 设置输出上限。其他逐请求控制参数覆盖没有替代 API。受影响的调用方参见[迁移指南](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.zh.md)。 diff --git a/packages/core/agent/src/closed-error.ts b/packages/core/agent/src/closed-error.ts index abcb335320..a4ca452887 100644 --- a/packages/core/agent/src/closed-error.ts +++ b/packages/core/agent/src/closed-error.ts @@ -1,15 +1,15 @@ /** Rejection of new work after an Agent starts closing. @module @deepseek-ai/dsh-agent/closed-error */ +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' -/** An Agent has stopped accepting new input and maintenance work. */ -export class AgentClosedError extends Error { +/** An Agent has stopped accepting new input and maintenance work (`AGENT_CLOSED`). */ +export class AgentClosedError extends HarnessError { /** * @param agentId - closing Agent identity. * @param options - original lifecycle cancellation, when available. */ constructor(readonly agentId: SessionId, options?: ErrorOptions) { - super(`agent "${agentId}" is closing`, options) - this.name = 'AgentClosedError' + super(`agent "${agentId}" is closing`, 'AGENT_CLOSED', options) } } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index aa5efe6d0a..39b15064dc 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -226,7 +226,7 @@ declare module './types.ts' { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -241,7 +241,7 @@ declare module './types.ts' { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -249,7 +249,7 @@ declare module './types.ts' { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -259,7 +259,7 @@ declare module './types.ts' { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -270,7 +270,7 @@ declare module './types.ts' { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index bccfa6634e..46cda8d44b 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -263,9 +263,8 @@ export class HarnessSdkJsonRpcServer { if (!this.initialized) throw new Error('SDK server is not initialized') const rec = await this.getOrCreateSession(params.sessionId) this.lifetime.signal.throwIfAborted() - // An agent-loop-only reload disposes the loop's agents while this record - // survives; a retained agent accepts followup() silently, so validate the - // record against the live registry before delivery. + // An agent-loop reload can dispose the Agent while the SDK still retains + // this record. Reject stale records before admitting prompt attachments. this.assertLiveAgent(rec, params.sessionId) const content = await durablePromptContent(this.ctx, params.contentBlocks) this.lifetime.signal.throwIfAborted() diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index f4a2a3d652..1f9108edae 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -10,8 +10,7 @@ import { randomUUID } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' -import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' -import { AgentClosedError } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent, type AgentOptions, type CreateAgentOptions } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index d9baf1d7f9..92611f23bc 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -1787,7 +1787,6 @@ def smoke_sdk_snapshot_mode( {"insert": [{ "id": "serial-created-fixture", "name": str(Path(__file__).resolve().parents[1] / "packages/core/agent-loop/tests/fixtures/serial-created.mjs"), - "config": {"checkRootCancellation": False}, }]}, ]) with DeepSeekHarness( diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index c5568f5a18..8aaf44b0b6 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -2941,7 +2941,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -3127,7 +3127,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -3967,7 +3967,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -4149,7 +4149,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl index 1a64fcd142..ee9fbfd3cb 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} @@ -18,7 +18,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl index 7f4bf22ad4..6fb5ebae1f 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl @@ -10,7 +10,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} @@ -18,7 +18,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} From ad5fab1a1c57323920355b1280cfbe543517bb84 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 15:10:01 +0800 Subject: [PATCH 032/438] fix(agent): contain input rejection during shutdown --- .../goal/goal-round-driver/README.i18n.yaml | 4 ++-- packages/goal/goal-round-driver/README.md | 2 +- packages/goal/goal-round-driver/README.zh.md | 2 +- packages/goal/goal-round-driver/src/index.ts | 3 ++- .../tests/goal-round-driver.spec.ts | 16 +++++++++++++++- .../session/working-directory/README.i18n.yaml | 4 ++-- packages/session/working-directory/README.md | 2 +- .../session/working-directory/README.zh.md | 2 +- .../session/working-directory/src/index.ts | 3 ++- .../tests/working-directory.spec.ts | 18 ++++++++++++++++++ 10 files changed, 45 insertions(+), 11 deletions(-) diff --git a/packages/goal/goal-round-driver/README.i18n.yaml b/packages/goal/goal-round-driver/README.i18n.yaml index 19e3ebc68a..18af868300 100644 --- a/packages/goal/goal-round-driver/README.i18n.yaml +++ b/packages/goal/goal-round-driver/README.i18n.yaml @@ -24,8 +24,8 @@ en: a1312339977f1127 zh: 57450327ff7e7d83 /deepseek-ai-dsh-goal-round-driver/use-this-package/when-continuation-stops: - en: f3cb23a11176dc4f - zh: de7aa54d5c93445d + en: 7c4d150d79e55ba4 + zh: be24cd1956894787 /deepseek-ai-dsh-goal-round-driver/use-this-package/after-resume-fork-or-unload: en: 85d5470b1b330330 zh: e761f9046ba7af8a diff --git a/packages/goal/goal-round-driver/README.md b/packages/goal/goal-round-driver/README.md index 1302bc6fdc..2998c3f8fe 100644 --- a/packages/goal/goal-round-driver/README.md +++ b/packages/goal/goal-round-driver/README.md @@ -50,7 +50,7 @@ With an exact live agent idle, an active armed goal, and remaining capacity, the ### When continuation stops -A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. +A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. If Agent shutdown rejects a queued round, the goal stays active. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. ### After resume, fork, or unload diff --git a/packages/goal/goal-round-driver/README.zh.md b/packages/goal/goal-round-driver/README.zh.md index 05905c7043..65cc9c1b77 100644 --- a/packages/goal/goal-round-driver/README.zh.md +++ b/packages/goal/goal-round-driver/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" ### 何时停止续行 -Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 +Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 关闭期间拒绝轮次入队时,goal 保持 active。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 ### resume、fork 或卸载之后 diff --git a/packages/goal/goal-round-driver/src/index.ts b/packages/goal/goal-round-driver/src/index.ts index d3ddfda4cc..461a874f08 100644 --- a/packages/goal/goal-round-driver/src/index.ts +++ b/packages/goal/goal-round-driver/src/index.ts @@ -6,7 +6,7 @@ import { isDeepStrictEqual } from 'node:util' import { FiberState } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' -import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent' import type { GoalMessageSource, GoalRef, GoalView } from '@deepseek-ai/dsh-goal' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -208,6 +208,7 @@ export function apply(ctx: Context): void { agent.followup(message) } catch (error: unknown) { state.attempt = undefined + if (error instanceof AgentClosedError) return ctx.logger.warn(`goal-round-driver: could not queue round ${round} for agent "${agent.id}": ${renderThrown(error)}`) const latest = currentGoal(state) if (latest !== undefined && latest.id === goal.id && latest.revision === goal.revision diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index d9f97df07d..c9be135ea1 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' -import { agentEvents } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' @@ -727,6 +727,20 @@ describe('same-session goal driving', () => { expect(goal?.roundsStarted).toBe(1) }) + it('keeps the goal active when the Agent closes before queue admission', async () => { + const test = await harness([]) + const admission = Promise.withResolvers() + vi.spyOn(test.agent, 'followup').mockImplementation(() => { + admission.resolve(undefined) + throw new AgentClosedError(test.agent.id) + }) + test.ctx.goals.create(test.agent, { objective: 'resume after shutdown' }) + await admission.promise + + expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', roundsStarted: 0 }) + expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/blocked')).toBe(false) + }) + it('blocks the goal when a custom agent rejects the otherwise valid follow-up', async () => { const test = await harness([]) // Reject only the goal-sourced round follow-up, not the state-change injection diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index fd50066fe2..4ed48e75cc 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: e65405026debde7c zh: e12a648eb10ed16b /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: f0458147d29631b1 - zh: 6a288670dd084ffb + en: c0681d6879ece29d + zh: 42bf039fc1bbdaf5 /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 44ed9ba9dc..9506cfa788 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory. It warns unless the Agent is closing. The next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 9561d73972..1df1f5673b 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录。Agent 正在关闭时无需告警。下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 62c3750c2c..be0c9e5187 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -7,7 +7,7 @@ import { isAbsolute } from 'node:path' import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' @@ -217,6 +217,7 @@ export class WorkingDirectoryService extends Service { try { agent.inject(notice) } catch (error) { + if (error instanceof AgentClosedError) return this.ctx.logger.warn(`working-directory: committed ${JSON.stringify(directory)}, but could not queue its notice: ${String(error)}`) } } diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index 22fb99af47..d05bf06f10 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import WorkingDirectory, { type Config as WorkingDirectoryConfig } from '@deepseek-ai/dsh-working-directory' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -314,6 +315,23 @@ describe('Session working directories', () => { } }) + it('keeps the committed directory when the Agent closes before accepting its notice', async () => { + await using f = await fixture() + const child = join(f.root, 'child') + await mkdir(child) + const inject = vi.spyOn(f.agent, 'inject').mockImplementation(() => { throw new AgentClosedError(f.agent.id) }) + const warn = vi.spyOn(f.ctx.logger, 'warn') + try { + await expect(f.ctx.workingDirectory.set(f.agent, child)).resolves.toBe(child) + expect(f.ctx.workingDirectory.get(f.agent.session)).toBe(child) + expect(inject).toHaveBeenCalledOnce() + expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('could not queue its notice')) + } finally { + inject.mockRestore() + warn.mockRestore() + } + }) + it('returns committed state and warns when the notice cannot be queued', async () => { await using f = await fixture() const child = join(f.root, 'child') From 360216b089c5ca29f1bb25cadb8a64bdb02c8974 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:36:18 +0800 Subject: [PATCH 033/438] feat(lsp): give lsp tool failures structured error codes tool-lsp argument checks throw ToolArgsError. lsp-stdio keeps FsError codes from resolution and reads (adding the LSP operand to the message), reports a missing or non-directory workspace and an oversized source as FsError, and adds LspError codes for the stdio provider: LSP_FILE_OUTSIDE_WORKSPACE, LSP_UNSUPPORTED_ENCODING, LSP_SPAWN_FAILED, LSP_SERVER_EXITED, LSP_PROTOCOL_ERROR, LSP_MESSAGE_TOO_LARGE, and LSP_SERVER_ERROR (JSON-RPC code and text in the message), and LSP_NOT_INITIALIZED for a query that finds no negotiated capabilities after a successful handshake. A query failure whose teardown also fails keeps the query's name and code. LspError assigns its literal name; the LSP subsystem page documents every code. --- docs/subsystems/lsp.i18n.yaml | 7 +- docs/subsystems/lsp.md | 27 ++++- docs/subsystems/lsp.zh.md | 27 ++++- packages/lsp/lsp-stdio/README.i18n.yaml | 4 +- packages/lsp/lsp-stdio/README.md | 2 +- packages/lsp/lsp-stdio/README.zh.md | 2 +- packages/lsp/lsp-stdio/src/abort.ts | 7 +- packages/lsp/lsp-stdio/src/connection.ts | 74 +++++++++++--- packages/lsp/lsp-stdio/src/framing.ts | 28 ++++-- packages/lsp/lsp-stdio/src/host.ts | 34 +++++-- packages/lsp/lsp-stdio/src/index.ts | 32 +++++- packages/lsp/lsp-stdio/src/instance.ts | 16 +-- packages/lsp/lsp-stdio/src/protocol.ts | 5 - packages/lsp/lsp-stdio/src/translate.ts | 30 +++++- .../lsp/lsp-stdio/tests/connection.spec.ts | 93 +++++++++++++++-- packages/lsp/lsp-stdio/tests/framing.spec.ts | 12 +-- packages/lsp/lsp-stdio/tests/host.spec.ts | 79 ++++++++++++--- packages/lsp/lsp-stdio/tests/instance.spec.ts | 57 ++++++++++- .../lsp/lsp-stdio/tests/lifecycle.spec.ts | 99 ++++++++++++++++--- .../lsp/lsp-stdio/tests/translate.spec.ts | 6 +- packages/lsp/lsp/src/index.ts | 21 +++- packages/lsp/tool-lsp/README.i18n.yaml | 4 +- packages/lsp/tool-lsp/README.md | 2 +- packages/lsp/tool-lsp/README.zh.md | 2 +- packages/lsp/tool-lsp/src/render.ts | 10 +- .../lsp/tool-lsp/tests/integration.spec.ts | 13 +++ packages/lsp/tool-lsp/tests/render.spec.ts | 10 +- packages/lsp/tool-lsp/tests/tool-lsp.spec.ts | 31 +++++- 28 files changed, 608 insertions(+), 126 deletions(-) diff --git a/docs/subsystems/lsp.i18n.yaml b/docs/subsystems/lsp.i18n.yaml index cae4151b07..6d21e0fc70 100644 --- a/docs/subsystems/lsp.i18n.yaml +++ b/docs/subsystems/lsp.i18n.yaml @@ -15,5 +15,8 @@ en: d260facb7ad22440 zh: f4868aae5be01eb6 /lsp-navigation/provider-and-service: - en: 754b4f1a0c80e332 - zh: aaacbc912dd6337b + en: 9977196522f2d7e5 + zh: f971ba2c60beda68 +/lsp-navigation/failures: + en: 192bd5699c1a23af + zh: f221bff65286231a diff --git a/docs/subsystems/lsp.md b/docs/subsystems/lsp.md index 5a8adb24c1..275ba3b236 100644 --- a/docs/subsystems/lsp.md +++ b/docs/subsystems/lsp.md @@ -162,7 +162,32 @@ interface LspService { } ``` -`LspProviderId` is the seam's branded id (`Branded<'LspProviderId'>` from [dsh-brand](../../packages/util/brand)); `LspError` extends `HarnessError` with stable codes such as `LSP_INVALID_PROVIDER`, `LSP_CONFLICT`, `LSP_UNAVAILABLE`, `LSP_DISPOSED`, `LSP_UNSUPPORTED_OPERATION`, and `LSP_MALFORMED_RESPONSE`, which callers route on instead of parsing `message`. +`LspProviderId` is the seam's branded id (`Branded<'LspProviderId'>` from [dsh-brand](../../packages/util/brand)); `LspError` extends `HarnessError` with the stable codes listed under [Failures](#failures), which callers route on instead of parsing `message`. + + +## Failures + +Every expected failure of an `lsp` tool call is a `HarnessError` whose `name` and `code` the tool result keeps in `error.info`. `LspError` sets `name` to `LspError`; its `code` stays open because providers and consumers add codes, so consumers tolerate codes they do not know. Invalid tool arguments fail as `ToolArgsError` `INVALID_ARGS`, and caller cancellation as `AbortError`. Workspace and source reads keep the filesystem provider's `FsError` code, such as `FS_NOT_FOUND`, `FS_NOT_REGULAR_FILE`, or `FS_NOT_TEXT`, and prefix the LSP operand to its message; the stdio provider adds `FS_NOT_DIRECTORY` for a non-directory workspace and `FS_TOO_LARGE` for a source over `maxDocumentBytes`. A query failure whose server teardown also fails keeps the query failure's `name` and `code` and appends the teardown failure to its message. + +| Code | Raised by | Meaning | Consumer action | +|---|---|---|---| +| `LSP_INVALID_PROVIDER` | Seam | A registration has an empty id or language id, no extensions, or an invalid extension | Fix the registration | +| `LSP_CONFLICT` | Seam | The provider id or an extension is already registered | Remove the duplicate registration | +| `LSP_UNAVAILABLE` | Seam | No provider handles the file's extension | Query a supported file or add a provider | +| `LSP_WORKSPACE_REQUIRED` | `lsp` tool | The call has no Agent Session workspace | Call the tool from an Agent Session | +| `LSP_DISPOSED` | Provider | The provider or its server instance was disposed | Retry after the provider is mounted again | +| `LSP_UNSUPPORTED_OPERATION` | Provider | The server lacks the operation or transient open/close synchronization | Choose another operation or server | +| `LSP_MALFORMED_RESPONSE` | Provider | The server's `initialize` or query result violates the protocol | Report the server defect | +| `LSP_FILE_OUTSIDE_WORKSPACE` | Stdio provider | The source resolves outside the canonical workspace | Query a file inside the workspace | +| `LSP_UNSUPPORTED_ENCODING` | Stdio provider | The server negotiated a position encoding other than UTF-16 | Use a server that supports UTF-16 | +| `LSP_SPAWN_FAILED` | Stdio provider | The subprocess provider failed to launch or run the server; a provider `HarnessError` keeps its own `name` and `code` instead | Fix the server command or installation | +| `LSP_SERVER_EXITED` | Stdio provider | The server exited or closed its stdin; the message carries the retained stderr tail | Retry later; inspect the stderr tail when it repeats | +| `LSP_PROTOCOL_ERROR` | Stdio provider | The server's output broke base-protocol framing or JSON | Report the server defect | +| `LSP_MESSAGE_TOO_LARGE` | Stdio provider | A server message exceeded `maxMessageBytes` | Narrow the query or raise `maxMessageBytes` | +| `LSP_SERVER_ERROR` | Stdio provider | The server answered with a JSON-RPC error; the message carries its numeric code and text | Act on the server's message | +| `LSP_NOT_INITIALIZED` | Stdio provider | A query found the server instance without negotiated capabilities after its handshake succeeded; this is inconsistent internal state, not a server condition | Report the defect | + +After a transport failure (`LSP_SPAWN_FAILED`, `LSP_SERVER_EXITED`, `LSP_PROTOCOL_ERROR`, or `LSP_MESSAGE_TOO_LARGE`), the stdio provider retries the read-only query once on a fresh process when the failed process tears down cleanly. diff --git a/docs/subsystems/lsp.zh.md b/docs/subsystems/lsp.zh.md index e041217866..65612a8eac 100644 --- a/docs/subsystems/lsp.zh.md +++ b/docs/subsystems/lsp.zh.md @@ -162,7 +162,32 @@ interface LspService { } ``` -`LspProviderId` 是该 seam 的品牌化 id(来自 [dsh-brand](../../packages/util/brand) 的 `Branded<'LspProviderId'>`);`LspError` 扩展 `HarnessError`,提供 `LSP_INVALID_PROVIDER`、`LSP_CONFLICT`、`LSP_UNAVAILABLE`、`LSP_DISPOSED`、`LSP_UNSUPPORTED_OPERATION` 和 `LSP_MALFORMED_RESPONSE` 等稳定错误码,调用方应按错误码路由,而不是解析 `message`。 +`LspProviderId` 是该 seam 的品牌化 id(来自 [dsh-brand](../../packages/util/brand) 的 `Branded<'LspProviderId'>`);`LspError` 扩展 `HarnessError`,提供[失败](#failures)一节列出的稳定错误码,调用方应按错误码路由,而不是解析 `message`。 + + +## 失败 + +`lsp` 工具调用的每个预期失败都是 `HarnessError`,工具结果会把它的 `name` 和 `code` 保留在 `error.info` 中。`LspError` 把 `name` 设为 `LspError`;由于提供方和消费方会添加错误码,它的 `code` 保持开放,消费方须容忍未知错误码。无效的工具参数以 `ToolArgsError` `INVALID_ARGS` 失败,调用方取消以 `AbortError` 失败。工作区与源文件读取保留文件系统提供方的 `FsError` 错误码,例如 `FS_NOT_FOUND`、`FS_NOT_REGULAR_FILE` 或 `FS_NOT_TEXT`,并在其消息前加上 LSP 操作对象;stdio 提供方对非目录工作区使用 `FS_NOT_DIRECTORY`,对超过 `maxDocumentBytes` 的源文件使用 `FS_TOO_LARGE`。如果查询失败后服务器拆除也失败,错误保留查询失败的 `name` 和 `code`,并把拆除失败追加到消息中。 + +| 错误码 | 抛出方 | 含义 | 消费方操作 | +|---|---|---|---| +| `LSP_INVALID_PROVIDER` | Seam | 注册的 id 或语言 id 为空、没有扩展名,或扩展名无效 | 修正注册 | +| `LSP_CONFLICT` | Seam | 提供方 id 或某个扩展名已被注册 | 移除重复注册 | +| `LSP_UNAVAILABLE` | Seam | 没有提供方处理该文件扩展名 | 查询受支持的文件,或添加提供方 | +| `LSP_WORKSPACE_REQUIRED` | `lsp` 工具 | 调用没有 Agent Session 工作区 | 从 Agent Session 调用该工具 | +| `LSP_DISPOSED` | 提供方 | 提供方或其服务器实例已被释放 | 在提供方重新挂载后重试 | +| `LSP_UNSUPPORTED_OPERATION` | 提供方 | 服务器不支持该操作或临时打开/关闭同步 | 选择其他操作或服务器 | +| `LSP_MALFORMED_RESPONSE` | 提供方 | 服务器的 `initialize` 或查询结果违反协议 | 报告服务器缺陷 | +| `LSP_FILE_OUTSIDE_WORKSPACE` | stdio 提供方 | 源文件解析到规范工作区之外 | 查询工作区内的文件 | +| `LSP_UNSUPPORTED_ENCODING` | stdio 提供方 | 服务器协商了 UTF-16 以外的位置编码 | 使用支持 UTF-16 的服务器 | +| `LSP_SPAWN_FAILED` | stdio 提供方 | 子进程提供方未能启动或运行服务器;提供方的 `HarnessError` 则保留其自身的 `name` 和 `code` | 修正服务器命令或安装 | +| `LSP_SERVER_EXITED` | stdio 提供方 | 服务器已退出或关闭了 stdin;消息携带保留的 stderr 尾部 | 稍后重试;反复出现时检查 stderr 尾部 | +| `LSP_PROTOCOL_ERROR` | stdio 提供方 | 服务器输出破坏了基础协议分帧或 JSON | 报告服务器缺陷 | +| `LSP_MESSAGE_TOO_LARGE` | stdio 提供方 | 某条服务器消息超过 `maxMessageBytes` | 缩小查询范围或调大 `maxMessageBytes` | +| `LSP_SERVER_ERROR` | stdio 提供方 | 服务器以 JSON-RPC 错误应答;消息携带其数字错误码与文本 | 按服务器消息处理 | +| `LSP_NOT_INITIALIZED` | stdio 提供方 | 握手已成功,但查询时服务器实例没有已协商的能力;这是内部状态不一致,不是服务器的情况 | 报告该缺陷 | + +传输失败(`LSP_SPAWN_FAILED`、`LSP_SERVER_EXITED`、`LSP_PROTOCOL_ERROR` 或 `LSP_MESSAGE_TOO_LARGE`)后,如果失败的进程干净地完成拆除,stdio 提供方会在新进程上把只读查询重试一次。 diff --git a/packages/lsp/lsp-stdio/README.i18n.yaml b/packages/lsp/lsp-stdio/README.i18n.yaml index 1d00d484cc..369a475ea4 100644 --- a/packages/lsp/lsp-stdio/README.i18n.yaml +++ b/packages/lsp/lsp-stdio/README.i18n.yaml @@ -24,8 +24,8 @@ en: 41363baf8fdba020 zh: d1a6193b1aa813ba /deepseek-ai-dsh-lsp-stdio/use-this-package/observable-success-and-failures: - en: 57f3a82c014af107 - zh: 770fc617c1ab0eab + en: 27766a0ecd0f70fa + zh: 532bc93a8ce5e701 /deepseek-ai-dsh-lsp-stdio/use-this-package/security-boundary: en: f1f7fef771bcaa6d zh: f11dcf771a6fecfc diff --git a/packages/lsp/lsp-stdio/README.md b/packages/lsp/lsp-stdio/README.md index ddcfb78292..8f30301f48 100644 --- a/packages/lsp/lsp-stdio/README.md +++ b/packages/lsp/lsp-stdio/README.md @@ -68,7 +68,7 @@ On the first query for a workspace, the provider launches one server process for ### Observable success and failures -A successful navigation returns normalized locations, and hover returns normalized text or a no-hover notice; empty results are successful no-result responses. The query fails when the server does not support the operation or the transient open/close synchronization (`LSP_UNSUPPORTED_OPERATION`), when the source is missing, non-regular, non-UTF-8, oversized, or outside the canonical workspace (rejected before the server starts), or when the server returns a malformed payload (`LSP_MALFORMED_RESPONSE`). A hard-killed harness leaves servers running until they exit on their own — graceful shutdown happens only through service disposal. +A successful navigation returns normalized locations, and hover returns normalized text or a no-hover notice; empty results are successful no-result responses. Before the server starts, a missing, non-directory, non-regular, non-UTF-8, or oversized workspace or source fails with its `FsError` code, and a source outside the canonical workspace fails with `LSP_FILE_OUTSIDE_WORKSPACE`. The server then fails the query with `LSP_UNSUPPORTED_OPERATION` when it lacks the operation or the transient open/close synchronization, `LSP_UNSUPPORTED_ENCODING` for a non-UTF-16 position encoding, `LSP_MALFORMED_RESPONSE` for a malformed payload, and `LSP_SERVER_ERROR` for a JSON-RPC error response; a failed process or stream reports `LSP_SPAWN_FAILED`, `LSP_SERVER_EXITED`, `LSP_PROTOCOL_ERROR`, or `LSP_MESSAGE_TOO_LARGE`; a query that finds the instance without negotiated capabilities after a successful handshake reports `LSP_NOT_INITIALIZED`, which marks a provider defect. The [LSP navigation subsystem](../../../docs/subsystems/lsp.md#failures) gives each code's meaning and consumer action. A hard-killed harness leaves servers running until they exit on their own — graceful shutdown happens only through service disposal. ### Security boundary diff --git a/packages/lsp/lsp-stdio/README.zh.md b/packages/lsp/lsp-stdio/README.zh.md index aef549f4bf..f54eda31c1 100644 --- a/packages/lsp/lsp-stdio/README.zh.md +++ b/packages/lsp/lsp-stdio/README.zh.md @@ -68,7 +68,7 @@ kind: "package-reference" ### 可观察的成功与失败 -成功的导航返回规范化位置,悬停返回规范化文本或无可悬停提示;空结果是成功的无结果响应。当服务器不支持该操作或临时打开/关闭同步(`LSP_UNSUPPORTED_OPERATION`)、源文件缺失、非普通文件、非 UTF-8、过大或位于规范工作区之外(在服务器启动前被拒绝),或服务器返回格式错误的载荷(`LSP_MALFORMED_RESPONSE`)时,查询会失败。被强制杀死的 harness 会让服务器继续运行直到自行退出——优雅关闭只发生在服务释放时。 +成功的导航返回规范化位置,悬停返回规范化文本或无可悬停提示;空结果是成功的无结果响应。在服务器启动前,缺失、非目录、非普通文件、非 UTF-8 或过大的工作区或源文件以其 `FsError` 错误码失败,位于规范工作区之外的源文件以 `LSP_FILE_OUTSIDE_WORKSPACE` 失败。随后,服务器不支持该操作或临时打开/关闭同步时查询以 `LSP_UNSUPPORTED_OPERATION` 失败,非 UTF-16 位置编码以 `LSP_UNSUPPORTED_ENCODING` 失败,格式错误的载荷以 `LSP_MALFORMED_RESPONSE` 失败,JSON-RPC 错误响应以 `LSP_SERVER_ERROR` 失败;进程或流失败时报告 `LSP_SPAWN_FAILED`、`LSP_SERVER_EXITED`、`LSP_PROTOCOL_ERROR` 或 `LSP_MESSAGE_TOO_LARGE`;握手成功后查询却发现实例没有已协商的能力时报告 `LSP_NOT_INITIALIZED`,表示提供方存在缺陷。[LSP 导航子系统](../../../docs/subsystems/lsp.zh.md#failures)给出每个错误码的含义与消费方操作。被强制杀死的 harness 会让服务器继续运行直到自行退出——优雅关闭只发生在服务释放时。 ### 安全边界 diff --git a/packages/lsp/lsp-stdio/src/abort.ts b/packages/lsp/lsp-stdio/src/abort.ts index c6706fc8b8..be86684d5d 100644 --- a/packages/lsp/lsp-stdio/src/abort.ts +++ b/packages/lsp/lsp-stdio/src/abort.ts @@ -8,14 +8,17 @@ import { timeoutOf } from '@deepseek-ai/dsh-timeout' /** * Build an abort Error carrying the signal's reason and preserving timeout classification. * @param signal - the aborted signal whose reason to surface. - * @returns the timeout reason if present, else the Error reason, else a generic aborted Error. + * @returns the timeout reason if present, else the Error reason, else an `AbortError`-named Error + * whose `cause` is the non-Error reason, so tool cancellation classification still applies. */ export function abortError(signal: AbortSignal): Error { const timeout = timeoutOf(signal) if (timeout !== undefined) return timeout const reason: unknown = signal.reason if (reason instanceof Error) return reason - return new Error('LSP query aborted') + const aborted = new Error('LSP query aborted', { cause: reason }) + aborted.name = 'AbortError' + return aborted } /** diff --git a/packages/lsp/lsp-stdio/src/connection.ts b/packages/lsp/lsp-stdio/src/connection.ts index bdc4b3fb11..e910ac0a52 100644 --- a/packages/lsp/lsp-stdio/src/connection.ts +++ b/packages/lsp/lsp-stdio/src/connection.ts @@ -11,6 +11,8 @@ */ import type { Writable } from 'node:stream' +import { LspError } from '@deepseek-ai/dsh-lsp' +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { encodeMessage, MessageDecoder } from './framing.ts' @@ -39,6 +41,7 @@ export interface ConnectionSpec { } interface Pending { + method: string resolve: (value: unknown) => void reject: (error: Error) => void } @@ -62,7 +65,13 @@ const writeConnectionMessage: ConnectionWriter = (stdin, message, done) => { stdin.write(encodeMessage(message), done) } -/** A live JSON-RPC endpoint bound to one child process. */ +/** + * A live JSON-RPC endpoint bound to one child process. Request and write failures are `LspError`s: + * `LSP_SERVER_EXITED` when the process exits or its stdin fails, `LSP_SPAWN_FAILED` when the + * subprocess provider fails to start or run it (a provider `HarnessError` keeps its own identity), + * `LSP_PROTOCOL_ERROR` or `LSP_MESSAGE_TOO_LARGE` when its stdout breaks framing, and + * `LSP_SERVER_ERROR` when it answers a request with a JSON-RPC error. + */ export class LspConnection { private readonly handle: SubprocessHandle private readonly stdin: Writable @@ -70,6 +79,8 @@ export class LspConnection { private readonly pending = new Map() private nextId = 1 private closeReason: Error | undefined + /** The subprocess provider's launch or run failure; it supersedes the stdin failure it causes. */ + private launchFailure: Error | undefined /** Set once the process has fully exited; the instance awaits it during teardown. */ readonly closed: Promise @@ -110,7 +121,7 @@ export class LspConnection { this.stdin = this.handle.stdin this.closed = new Promise((resolve) => { const close = (): void => { - const reason = this.closeReason ?? new Error(this.exitMessage()) + const reason = this.closeReason ?? new LspError(this.exitMessage(), 'LSP_SERVER_EXITED') // Record the reason so any request issued AFTER close rejects immediately instead of hanging // (a closed process sends no further responses). this.closeReason = reason @@ -120,14 +131,16 @@ export class LspConnection { this.handle.done.then(close, (error: unknown) => { // A spawn-level failure never produces a close event; the rejection is // the fatal cause and the close boundary at once. - this.fail(asError(error)) + const failure = spawnFailure(error) + this.launchFailure = failure + this.fail(failure) close() }) }) // Child stdin can fail while the process itself remains alive (for example, a server closes fd // 0). Treat that as a fatal connection error so pending requests reject immediately instead of // waiting for a process-close event that may never arrive. - this.stdin.on('error', (error) => { this.fail(error) }) + this.stdin.on('error', (error) => { this.fail(this.stdinFailure(error)) }) this.handle.stdout.on('data', (chunk: Buffer) => { this.onStdout(chunk) }) } @@ -148,7 +161,18 @@ export class LspConnection { * @returns `true` only when this connection produced that exact failure. */ failedWith(error: unknown): boolean { - return this.closeReason === error + return this.closeReason === error || (this.launchFailure !== undefined && this.launchFailure === error) + } + + /** + * Report a transport failure by its authoritative cause once the process has settled. A failed + * launch usually surfaces first as a stdin write failure; after `done` rejects, that failure + * reports the launch failure instead. + * @param error - error caught by the instance after teardown. + * @returns the launch failure for this connection's transport failure, otherwise `error`. + */ + settledFailure(error: unknown): unknown { + return this.launchFailure !== undefined && this.failedWith(error) ? this.launchFailure : error } /** @@ -164,7 +188,7 @@ export class LspConnection { reject(this.closeReason) return } - this.pending.set(id, { resolve, reject }) + this.pending.set(id, { method, resolve, reject }) // `write()` records either synchronous or callback-delivered failures on the connection and // rejects every pending request. This handler only consumes the write promise itself. void this.write({ jsonrpc: '2.0', id, method, params }).catch(() => {}) @@ -266,8 +290,7 @@ export class LspConnection { this.pending.delete(id) const error = frame.error if (error !== null && typeof error === 'object') { - const record = error as Record - pending.reject(new Error(typeof record.message === 'string' ? record.message : 'LSP error response')) + pending.reject(responseError(pending.method, error as Record)) return } pending.resolve(frame.result) @@ -281,8 +304,9 @@ export class LspConnection { resolve() return } - this.fail(error) - reject(error) + const failure = this.stdinFailure(error) + this.fail(failure) + reject(failure) } try { this.writer(this.stdin, message, done) @@ -303,8 +327,20 @@ export class LspConnection { return tail === '' ? 'language server exited' : `language server exited; stderr: ${tail}` } + /** + * Convert a stdin failure to `LSP_SERVER_EXITED`. The stream reports one failure through both its + * `error` event and the write callback, so the second report reuses the first conversion and + * {@link failedWith} still recognizes the rejection. + */ + private stdinFailure(error: Error): Error { + const current = this.closeReason + if (current instanceof LspError && current.cause === error) return current + return new LspError(`language server stopped accepting input: ${error.message}`, 'LSP_SERVER_EXITED', { cause: error }) + } + private fail(error: Error): void { - /* v8 ignore next -- the second arm (closeReason already set) needs two fail() calls before close; defensive. */ + /* v8 ignore next -- the second arm needs a second failure before close, such as a launch failure after a stdin + failure; the subprocess provider does not fix that order, so coverage cannot rely on it. */ if (this.closeReason === undefined) this.closeReason = error this.failAll(error) } @@ -316,6 +352,22 @@ export class LspConnection { } } +/** + * Convert a subprocess `done` rejection to `LSP_SPAWN_FAILED`; a provider `HarnessError` already + * carries the classification and propagates unchanged. + */ +function spawnFailure(error: unknown): Error { + if (error instanceof HarnessError) return error + return new LspError(`language server process failed: ${asError(error).message}`, 'LSP_SPAWN_FAILED', { cause: error }) +} + +/** Convert a JSON-RPC error response, keeping its numeric code and message in `message`. */ +function responseError(method: string, error: Record): LspError { + const code = typeof error.code === 'number' ? ` ${error.code}` : '' + const detail = typeof error.message === 'string' ? error.message : 'no message' + return new LspError(`language server rejected ${method} with JSON-RPC error${code}: ${detail}`, 'LSP_SERVER_ERROR') +} + /** Coerce an unknown thrown value to an `Error`. */ function asError(value: unknown): Error { /* v8 ignore next -- the non-Error branch guards against a non-Error throw, which our paths never produce. */ diff --git a/packages/lsp/lsp-stdio/src/framing.ts b/packages/lsp/lsp-stdio/src/framing.ts index 7d7a44dad8..536d354875 100644 --- a/packages/lsp/lsp-stdio/src/framing.ts +++ b/packages/lsp/lsp-stdio/src/framing.ts @@ -5,6 +5,8 @@ * @module @deepseek-ai/dsh-lsp-stdio/framing */ +import { LspError } from '@deepseek-ai/dsh-lsp' + /** The header/body separator in the LSP base protocol. */ const HEADER_SEPARATOR = '\r\n\r\n' @@ -42,7 +44,8 @@ export class MessageDecoder { * Append a chunk and return every message body that is now complete. * @param chunk - raw bytes from the server's stdout. * @returns the parsed JSON bodies, in arrival order (possibly empty). - * @throws Error when a header is malformed or a body exceeds `maxMessageBytes`. + * @throws LspError `LSP_PROTOCOL_ERROR` when a header or body is malformed, or + * `LSP_MESSAGE_TOO_LARGE` when a body exceeds `maxMessageBytes`. */ push(chunk: Buffer): unknown[] { this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]) @@ -60,17 +63,20 @@ export class MessageDecoder { const separator = this.buffer.indexOf(HEADER_SEPARATOR) if (separator < 0) { if (this.buffer.length > MAX_HEADER_BYTES) { - throw new Error(`LSP header exceeded ${MAX_HEADER_BYTES} bytes without a terminator`) + throw protocolError(`LSP header exceeded ${MAX_HEADER_BYTES} bytes without a terminator`) } return { ready: false } } if (separator > MAX_HEADER_BYTES) { - throw new Error(`LSP header exceeded ${MAX_HEADER_BYTES} bytes`) + throw protocolError(`LSP header exceeded ${MAX_HEADER_BYTES} bytes`) } const headerText = this.buffer.toString('ascii', 0, separator) const contentLength = parseContentLength(headerText) if (contentLength > this.maxMessageBytes) { - throw new Error(`LSP message length ${contentLength} exceeds the ${this.maxMessageBytes}-byte limit`) + throw new LspError( + `LSP message length ${contentLength} exceeds the ${this.maxMessageBytes}-byte limit`, + 'LSP_MESSAGE_TOO_LARGE', + ) } const bodyStart = separator + HEADER_SEPARATOR.length const bodyEnd = bodyStart + contentLength @@ -81,7 +87,10 @@ export class MessageDecoder { return { ready: true, message: JSON.parse(body) } } catch (error) { /* v8 ignore next -- JSON.parse throws a SyntaxError (an Error); the String() fallback is defensive. */ - throw new Error(`LSP message body was not valid JSON: ${error instanceof Error ? error.message : String(error)}`) + throw protocolError( + `LSP message body was not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ) } } } @@ -94,9 +103,14 @@ function parseContentLength(headerText: string): number { if (line.slice(0, colon).trim().toLowerCase() !== 'content-length') continue const value = Number(line.slice(colon + 1).trim()) if (!Number.isInteger(value) || value < 0) { - throw new Error(`invalid Content-Length header: ${JSON.stringify(line)}`) + throw protocolError(`invalid Content-Length header: ${JSON.stringify(line)}`) } return value } - throw new Error(`LSP header block missing Content-Length: ${JSON.stringify(headerText)}`) + throw protocolError(`LSP header block missing Content-Length: ${JSON.stringify(headerText)}`) +} + +/** A framing failure: the server's byte stream no longer follows the LSP base protocol. */ +function protocolError(message: string, options?: ErrorOptions): LspError { + return new LspError(message, 'LSP_PROTOCOL_ERROR', options) } diff --git a/packages/lsp/lsp-stdio/src/host.ts b/packages/lsp/lsp-stdio/src/host.ts index ef4b56809d..d28561ea90 100644 --- a/packages/lsp/lsp-stdio/src/host.ts +++ b/packages/lsp/lsp-stdio/src/host.ts @@ -1,7 +1,9 @@ /** Filesystem-seam source access for the generic stdio LSP provider. */ import { Buffer } from 'node:buffer' +import { FsError } from '@deepseek-ai/dsh-fs' import type { FileSystem, FsTarget } from '@deepseek-ai/dsh-fs' +import { LspError } from '@deepseek-ai/dsh-lsp' import { throwIfAborted } from './abort.ts' /** A canonical workspace in the filesystem/subprocess execution world. */ @@ -28,6 +30,8 @@ export interface HostSource { * @param workspaceRoot - caller-supplied workspace path. * @param signal - optional cancellation around provider operations. * @returns stable identity plus process path and file URI. + * @throws FsError with the provider's code when resolution or `stat` fails, `FS_NOT_FOUND` when the + * workspace is missing, or `FS_NOT_DIRECTORY` when it is not a directory. */ export async function canonicalizeWorkspace( fs: FileSystem, @@ -40,7 +44,7 @@ export async function canonicalizeWorkspace( target = await fs.resolve(workspaceRoot, signal === undefined ? {} : { signal }) } catch (error: unknown) { throwIfAborted(signal) - throw new Error(`workspace root "${workspaceRoot}" cannot be resolved: ${messageOf(error)}`, { cause: error }) + rethrowWithFsContext(error, `workspace root "${workspaceRoot}" cannot be resolved`) } throwIfAborted(signal) const info = await fs.stat(target, signal).catch((error: unknown) => { @@ -48,8 +52,11 @@ export async function canonicalizeWorkspace( throw error }) throwIfAborted(signal) - if (info?.type !== 'directory') { - throw new Error(`workspace root "${workspaceRoot}" is not a directory`) + if (info === undefined) { + throw new FsError(`workspace root "${workspaceRoot}" does not exist`, 'FS_NOT_FOUND') + } + if (info.type !== 'directory') { + throw new FsError(`workspace root "${workspaceRoot}" is not a directory`, 'FS_NOT_DIRECTORY') } return { target, @@ -68,6 +75,9 @@ export async function canonicalizeWorkspace( * @param maxDocumentBytes - largest complete source accepted by this host. * @param signal - optional cancellation. * @returns canonical file URI and current text. + * @throws FsError with the provider's code when resolution or reading fails, or `FS_TOO_LARGE` when + * the source exceeds `maxDocumentBytes`; LspError `LSP_FILE_OUTSIDE_WORKSPACE` when the source + * resolves outside `workspace`. */ export async function readHostSource( fs: FileSystem, @@ -85,11 +95,11 @@ export async function readHostSource( }) } catch (error: unknown) { throwIfAborted(signal) - throw new Error(`source "${filePath}" cannot be resolved: ${messageOf(error)}`, { cause: error }) + rethrowWithFsContext(error, `source "${filePath}" cannot be resolved`) } throwIfAborted(signal) if (!fs.contains(workspace.target, target)) { - throw new Error(`source "${filePath}" resolves outside the workspace`) + throw new LspError(`source "${filePath}" resolves outside the workspace`, 'LSP_FILE_OUTSIDE_WORKSPACE') } const chunks: string[] = [] let bytes = 0 @@ -105,11 +115,12 @@ export async function readHostSource( } } catch (error: unknown) { throwIfAborted(signal) - throw new Error(`source "${filePath}" could not be read: ${messageOf(error)}`, { cause: error }) + rethrowWithFsContext(error, `source "${filePath}" could not be read`) } if (bytes > maxDocumentBytes) { - throw new Error( + throw new FsError( `source "${filePath}" exceeds the ${maxDocumentBytes}-byte limit; reading stopped after ${bytes} bytes`, + 'FS_TOO_LARGE', ) } throwIfAborted(signal) @@ -119,6 +130,11 @@ export async function readHostSource( } } -function messageOf(error: unknown): string { - return error instanceof Error ? error.message : String(error) +/** + * Prefix a filesystem provider failure with the LSP operand while keeping its `FsError` code; any + * other thrown value is a provider defect and propagates unchanged. + */ +function rethrowWithFsContext(error: unknown, context: string): never { + if (!(error instanceof FsError)) throw error + throw new FsError(`${context}: ${error.message}`, error.code, { cause: error }) } diff --git a/packages/lsp/lsp-stdio/src/index.ts b/packages/lsp/lsp-stdio/src/index.ts index bfe1974e38..1e7fe51591 100644 --- a/packages/lsp/lsp-stdio/src/index.ts +++ b/packages/lsp/lsp-stdio/src/index.ts @@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { LspError, LspProviderId } from '@deepseek-ai/dsh-lsp' +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { LspProvider, LspProviderQuery, @@ -116,6 +117,32 @@ function throwTeardownFailures(results: readonly PromiseSettledResult[], m if (failures.length > 1) throw new AggregateError(failures, message) } +/** + * A coded query failure whose instance teardown also failed. It keeps the query failure's `name` + * and `code` so tool results route on the query outcome; `cause` aggregates both failures. + */ +class LspQueryTeardownError extends HarnessError { + constructor(query: HarnessError, teardown: unknown, cause: AggregateError) { + super(`${query.message}; language server teardown also failed: ${messageOf(teardown)}`, query.code, { cause }) + this.name = query.name + } +} + +/** + * Combine a query failure with the teardown failure of its instance. A `HarnessError` query + * failure keeps its identity on the combined error; any other query failure has no identity to keep + * and both surface as an `AggregateError`. + */ +function queryAndTeardownFailure(query: unknown, teardown: unknown): Error { + const both = new AggregateError([query, teardown], 'LSP operation and teardown failed') + return query instanceof HarnessError ? new LspQueryTeardownError(query, teardown, both) : both +} + +/** Read a thrown value's message for a combined failure report. */ +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + /** * Register the configured stdio LSP providers. Resolves every executable at load (after credential * scrubbing) before publishing any provider; each process launches lazily on its first matching @@ -294,10 +321,7 @@ class LocalLspProvider implements LspProvider { } if (teardownOutcome?.status === 'rejected') { if (queryOutcome.status === 'rejected') { - throw new AggregateError( - [queryOutcome.reason, teardownOutcome.reason], - 'LSP operation and teardown failed', - ) + throw queryAndTeardownFailure(queryOutcome.reason, teardownOutcome.reason) } throw teardownOutcome.reason } diff --git a/packages/lsp/lsp-stdio/src/instance.ts b/packages/lsp/lsp-stdio/src/instance.ts index d86d484571..f72a892fd5 100644 --- a/packages/lsp/lsp-stdio/src/instance.ts +++ b/packages/lsp/lsp-stdio/src/instance.ts @@ -18,8 +18,9 @@ import { abortable, abortError } from './abort.ts' import { LspConnection } from './connection.ts' import type { ConnectionSpawner, ConnectionSpec, ConnectionWriter } from './connection.ts' import type { HostSource } from './host.ts' -import type { WireInitializeResult, WireServerCapabilities } from './protocol.ts' +import type { WireServerCapabilities } from './protocol.ts' import { + initializeCapabilities, negotiatePositionEncoding, normalizeHover, normalizeLocations, @@ -97,8 +98,9 @@ export class LspInstance { const run = abortable(this.queue, signal) .then(() => this.runQuery(request, source, signal)) .catch(async (error: unknown) => { - if (this.isTransportFailure(error)) await this.awaitTeardownAttempt() - throw error + if (!this.isTransportFailure(error)) throw error + await this.awaitTeardownAttempt() + throw this.connection.settledFailure(error) }) // Keep the tail alive regardless of this query's outcome so the next caller still serializes. The // tail follows the ACTUAL prior work (this.queue), not the abortable view, so a caller giving up @@ -116,8 +118,8 @@ export class LspInstance { workspaceFolders: [{ uri: this.spec.workspaceUri, name: 'workspace' }], capabilities: CLIENT_CAPABILITIES, initializationOptions: this.spec.initializationOptions, - }) as WireInitializeResult - const capabilities = initializeResult.capabilities + }) + const capabilities = initializeCapabilities(initializeResult) // An omitted encoding defaults to utf-16; any other value is a protocol error we reject here. negotiatePositionEncoding(capabilities.positionEncoding) this.capabilities = capabilities @@ -141,8 +143,8 @@ export class LspInstance { throw error } const capabilities = this.capabilities - /* v8 ignore next -- `ready` resolves only after capabilities are set, else it rejects above; defensive. */ - if (capabilities === undefined) throw new Error('LSP instance is not initialized') + // `ready` resolves only after capabilities are set; reaching this means instance state is inconsistent. + if (capabilities === undefined) throw new LspError('LSP instance is not initialized', 'LSP_NOT_INITIALIZED') if (!supportsOperation(capabilities, request.operation)) { throw new LspError(`server does not support ${request.operation}`, 'LSP_UNSUPPORTED_OPERATION') } diff --git a/packages/lsp/lsp-stdio/src/protocol.ts b/packages/lsp/lsp-stdio/src/protocol.ts index 96257678ed..e91e45ed5c 100644 --- a/packages/lsp/lsp-stdio/src/protocol.ts +++ b/packages/lsp/lsp-stdio/src/protocol.ts @@ -73,8 +73,3 @@ export interface WireServerCapabilities { readonly implementationProvider?: WireProviderCapability readonly hoverProvider?: WireProviderCapability } - -/** The `initialize` result envelope. */ -export interface WireInitializeResult { - readonly capabilities: WireServerCapabilities -} diff --git a/packages/lsp/lsp-stdio/src/translate.ts b/packages/lsp/lsp-stdio/src/translate.ts index a2de8ed419..8b26fc5d07 100644 --- a/packages/lsp/lsp-stdio/src/translate.ts +++ b/packages/lsp/lsp-stdio/src/translate.ts @@ -92,11 +92,31 @@ function isOpenCloseKind(kind: WireTextDocumentSyncKind): boolean { * other than `utf-16` is a protocol error this host does not support. * @param encoding - the server's advertised `positionEncoding`, if any. * @returns the string `'utf-16'`. - * @throws Error for any non-`utf-16` encoding. + * @throws LspError `LSP_UNSUPPORTED_ENCODING` for any non-`utf-16` encoding. */ export function negotiatePositionEncoding(encoding: string | undefined): 'utf-16' { if (encoding === undefined || encoding === 'utf-16') return 'utf-16' - throw new Error(`server negotiated unsupported position encoding "${encoding}"; this host requires utf-16`) + throw new LspError( + `server negotiated unsupported position encoding "${encoding}"; this host requires utf-16`, + 'LSP_UNSUPPORTED_ENCODING', + ) +} + +/** + * Read the server capabilities from an untrusted `initialize` result. + * @param result - the raw `initialize` response result. + * @returns the advertised capabilities object. + * @throws LspError `LSP_MALFORMED_RESPONSE` when the result or its `capabilities` is not an object. + */ +export function initializeCapabilities(result: unknown): WireServerCapabilities { + if (result === null || typeof result !== 'object') { + throw malformedResponse('LSP initialize result was not an object') + } + const capabilities = (result as Record).capabilities + if (capabilities === null || typeof capabilities !== 'object') { + throw malformedResponse('LSP initialize result had no capabilities object') + } + return capabilities } /** Convert a wire range to the seam's range (structurally identical, but re-shaped as `readonly`). */ @@ -141,7 +161,8 @@ function isProtocolCoordinate(value: unknown): value is number { * locations. `Location` maps directly; `LocationLink` maps `targetUri` + `targetSelectionRange`. * @param payload - the raw `textDocument/definition|references|implementation` result. * @returns the normalized locations (empty for `null`/`[]`). - * @throws Error when an element is neither a `Location` nor a `LocationLink`. + * @throws LspError `LSP_MALFORMED_RESPONSE` when the result is missing or an element is neither a + * `Location` nor a `LocationLink`. */ export function normalizeLocations(payload: unknown): LspLocation[] { if (payload === null) return [] @@ -178,7 +199,8 @@ function renderMarkedString(value: WireMarkedString): string { * joins its rendered parts with one blank line. The model-facing tool owns the complete result cap. * @param payload - the raw `textDocument/hover` result. * @returns the normalized hover, or `null` when there is no content. - * @throws Error when the payload is a non-null, non-object, or structurally invalid hover. + * @throws LspError `LSP_MALFORMED_RESPONSE` when the payload is a non-null, non-object, or + * structurally invalid hover. */ export function normalizeHover(payload: unknown): LspHover | null { if (payload === null) return null diff --git a/packages/lsp/lsp-stdio/tests/connection.spec.ts b/packages/lsp/lsp-stdio/tests/connection.spec.ts index 37a9ef84e6..9428db7ad7 100644 --- a/packages/lsp/lsp-stdio/tests/connection.spec.ts +++ b/packages/lsp/lsp-stdio/tests/connection.spec.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { fileURLToPath } from 'node:url' +import { HarnessError } from '@deepseek-ai/dsh-llm' import { LspConnection } from '@deepseek-ai/dsh-lsp-stdio' import type { ConnectionWriter } from '@deepseek-ai/dsh-lsp-stdio/src/connection.ts' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' @@ -62,7 +63,11 @@ describe('LspConnection', () => { it('rejects a request when the server replies with an error', async () => { const conn = connect({ LSP_FAKE_ERROR: '1' }) await conn.request('initialize', { capabilities: {} }) - await expect(conn.request('textDocument/hover', {})).rejects.toThrow(/server refused the request/) + await expect(conn.request('textDocument/hover', {})).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_ERROR', + message: 'language server rejected textDocument/hover with JSON-RPC error -32000: server refused the request', + }) }) it('treats terminating an already-closed child as a teardown race', async () => { @@ -124,7 +129,11 @@ describe('LspConnection', () => { await conn.request('initialize', { capabilities: {} }) conn.terminate() await conn.closed - await expect(conn.request('textDocument/hover', {})).rejects.toThrow(/exited|closed/) + await expect(conn.request('textDocument/hover', {})).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_EXITED', + message: expect.stringMatching(/^language server exited/) as string, + }) }) it('cancel is a no-op-safe write after close', async () => { @@ -171,13 +180,52 @@ describe('LspConnection edge behavior', () => { configuration: null, }, spawnSubprocess, () => Promise.resolve(null)) open.push(conn) - await expect(conn.request('initialize', {})).rejects.toThrow() + // The failed launch usually surfaces first as a stdin write failure; once the process settles, + // the connection reports the provider's launch failure for it. + const failure: unknown = await conn.request('initialize', {}).catch((error: unknown) => error) + expect(failure).toMatchObject({ name: 'LspError', code: expect.stringMatching(/^LSP_(SERVER_EXITED|SPAWN_FAILED)$/) as string }) + await conn.closed + expect(conn.failedWith(failure)).toBe(true) + expect(conn.settledFailure(failure)).toMatchObject({ + name: 'LspError', + code: 'LSP_SPAWN_FAILED', + message: expect.stringMatching(/^language server process failed: .*ENOENT/) as string, + cause: expect.any(Error) as Error, + }) + const unrelated = new Error('unrelated') + expect(conn.settledFailure(unrelated)).toBe(unrelated) + }) + + it('keeps a subprocess provider HarnessError as the spawn failure', async () => { + const providerFailure = new HarnessError('sandbox refused the launch', 'SANDBOX_DENIED') + const conn = new LspConnection({ + command: process.execPath, + args: ['-e', 'setInterval(()=>{}, 1000)'], + cwd: process.cwd(), + env: scrubbedParentEnv(), + maxMessageBytes: 1000, + maxStderrBytes: 1000, + killGraceMs: 3_000, + configuration: null, + }, (spec) => { + const handle = spawnSubprocess(spec) + return Object.assign(Object.create(handle) as typeof handle, { + done: handle.done.then(() => { throw providerFailure }), + }) + }, () => Promise.resolve(null)) + open.push(conn) + const failure: unknown = await Promise.all([ + conn.request('initialize', {}).catch((error: unknown) => error), + Promise.resolve().then(() => { conn.terminate() }), + ]).then(([error]) => error) + await conn.closed + expect(conn.settledFailure(failure)).toBe(providerFailure) }) it('kills the process and fails pending requests on a framing error', async () => { // Emit an invalid Content-Length header, corrupting the stream irrecoverably. const conn = connectScript('process.stdout.write("Content-Length: abc\\r\\n\\r\\n{}"); setInterval(()=>{}, 1000)') - await expect(conn.request('initialize', {})).rejects.toThrow() + await expect(conn.request('initialize', {})).rejects.toMatchObject({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR' }) }) it('ignores a framed non-object message', async () => { @@ -215,18 +263,25 @@ describe('LspConnection edge behavior', () => { expect(Buffer.byteLength(conn.stderrTail)).toBe(4) }) - it('rejects with a fallback message when the error response has no message string', async () => { + it.each([ + ['no message string', '{code:-1}', 'language server rejected initialize with JSON-RPC error -1: no message'], + ['no numeric code', '{message:"refused"}', 'language server rejected initialize with JSON-RPC error: refused'], + ])('rejects with LSP_SERVER_ERROR when the error response has %s', async (_label, error, message) => { const script = 'let b=Buffer.alloc(0);' + 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};' - + 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,error:{code:-1}})));});' + + `process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,error:${error}})));});` const conn = connectScript(script) - await expect(conn.request('initialize', {})).rejects.toThrow(/LSP error response/) + await expect(conn.request('initialize', {})).rejects.toMatchObject({ name: 'LspError', code: 'LSP_SERVER_ERROR', message }) }) it('rejects a pending request when the process exits mid-flight', async () => { // Never responds, then exits shortly: the pending request must reject on close. const conn = connectScript('setTimeout(()=>process.exit(0), 100)') - await expect(conn.request('initialize', {})).rejects.toThrow(/exited|closed/) + await expect(conn.request('initialize', {})).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_EXITED', + message: 'language server exited', + }) }) it('rejects a pending request when child stdin fails but the process stays alive', async () => { @@ -235,7 +290,27 @@ describe('LspConnection edge behavior', () => { queueMicrotask(() => { done(failure) }) } const conn = connectScript('setInterval(()=>{}, 1000)', 100_000, writer) - await expect(conn.request('initialize', {})).rejects.toThrow(/fixture stdin failure/) + await expect(conn.request('initialize', {})).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_EXITED', + message: 'language server stopped accepting input: fixture stdin failure', + cause: failure, + }) + }) + + it('reports one stdin failure from the error event and the write callback as one transport failure', async () => { + const failure = new Error('fixture stdin failure') + const writer: ConnectionWriter = (stdin, _message, done) => { + queueMicrotask(() => { + stdin.emit('error', failure) + done(failure) + }) + } + const conn = connectScript('setInterval(()=>{}, 1000)', 100_000, writer) + const rejection: unknown = await conn.request('initialize', {}).catch((error: unknown) => error) + expect(rejection).toMatchObject({ name: 'LspError', code: 'LSP_SERVER_EXITED', cause: failure }) + expect(conn.failedWith(rejection)).toBe(true) + await expect(conn.notify('initialized', {})).rejects.toBe(rejection) }) it('ignores a frame that is neither a valid request nor a numeric-id response', async () => { diff --git a/packages/lsp/lsp-stdio/tests/framing.spec.ts b/packages/lsp/lsp-stdio/tests/framing.spec.ts index 51763db0d4..3d82110d48 100644 --- a/packages/lsp/lsp-stdio/tests/framing.spec.ts +++ b/packages/lsp/lsp-stdio/tests/framing.spec.ts @@ -50,33 +50,33 @@ describe('MessageDecoder', () => { it('rejects a body over the size limit', () => { const decoder = new MessageDecoder(4) - expect(() => decoder.push(frame('{"big":true}'))).toThrow(/exceeds the 4-byte limit/) + expect(() => decoder.push(frame('{"big":true}'))).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_MESSAGE_TOO_LARGE', message: expect.stringMatching(/exceeds the 4-byte limit/) as string })) }) it('rejects a missing Content-Length header', () => { const decoder = new MessageDecoder(1_000) - expect(() => decoder.push(Buffer.from('X: 1\r\n\r\n{}', 'utf8'))).toThrow(/missing Content-Length/) + expect(() => decoder.push(Buffer.from('X: 1\r\n\r\n{}', 'utf8'))).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR', message: expect.stringMatching(/missing Content-Length/) as string })) }) it('rejects a non-numeric Content-Length', () => { const decoder = new MessageDecoder(1_000) - expect(() => decoder.push(Buffer.from('Content-Length: abc\r\n\r\n{}', 'utf8'))).toThrow(/invalid Content-Length/) + expect(() => decoder.push(Buffer.from('Content-Length: abc\r\n\r\n{}', 'utf8'))).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR', message: expect.stringMatching(/invalid Content-Length/) as string })) }) it('rejects a header block that never terminates', () => { const decoder = new MessageDecoder(1_000) const huge = Buffer.alloc((1 << 16) + 1, 0x41) - expect(() => decoder.push(huge)).toThrow(/exceeded .* bytes without a terminator/) + expect(() => decoder.push(huge)).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR', message: expect.stringMatching(/exceeded .* bytes without a terminator/) as string })) }) it('rejects an oversized header block that includes its terminator', () => { const decoder = new MessageDecoder(1_000) const huge = Buffer.from(`Content-Length: 2\r\nX-Fill: ${'a'.repeat(70_000)}\r\n\r\n{}`, 'ascii') - expect(() => decoder.push(huge)).toThrow(/header exceeded .* bytes/) + expect(() => decoder.push(huge)).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR', message: expect.stringMatching(/header exceeded .* bytes/) as string })) }) it('rejects a non-JSON body', () => { const decoder = new MessageDecoder(1_000) - expect(() => decoder.push(frame('not json'))).toThrow(/not valid JSON/) + expect(() => decoder.push(frame('not json'))).toThrow(expect.objectContaining({ name: 'LspError', code: 'LSP_PROTOCOL_ERROR', message: expect.stringMatching(/not valid JSON/) as string })) }) }) diff --git a/packages/lsp/lsp-stdio/tests/host.spec.ts b/packages/lsp/lsp-stdio/tests/host.spec.ts index d75e025af1..49400dbf07 100644 --- a/packages/lsp/lsp-stdio/tests/host.spec.ts +++ b/packages/lsp/lsp-stdio/tests/host.spec.ts @@ -7,6 +7,7 @@ import { execFile } from 'node:child_process' import { pathToFileURL } from 'node:url' import { promisify } from 'node:util' import { Context } from '@deepseek-ai/cordis' +import { FsError } from '@deepseek-ai/dsh-fs' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import { deadline } from '@deepseek-ai/dsh-timeout' import { canonicalizeWorkspace, readHostSource } from '@deepseek-ai/dsh-lsp-stdio' @@ -54,19 +55,38 @@ describe('canonicalizeWorkspace', () => { }) it('rejects a missing workspace', async () => { - await expect(canonicalizeWorkspace(fs, join(root, 'nope'))).rejects.toThrow(/not a directory/) + const missing = join(root, 'nope') + await expect(canonicalizeWorkspace(fs, missing)).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_FOUND', + message: `workspace root "${missing}" does not exist`, + }) }) - it('wraps a provider failure while resolving the workspace', async () => { + it('adds the workspace operand to a filesystem failure while keeping its code', async () => { + const providerFailure = new FsError('permission denied', 'FS_PERMISSION_DENIED') + fs.resolve = async () => { throw providerFailure } + await expect(canonicalizeWorkspace(fs, ws)).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_PERMISSION_DENIED', + message: `workspace root "${ws}" cannot be resolved: permission denied`, + cause: providerFailure, + }) + }) + + it('propagates a non-filesystem resolve failure unchanged', async () => { fs.resolve = async () => { throw 'raw workspace resolve failure' } - await expect(canonicalizeWorkspace(fs, ws)) - .rejects.toThrow(`workspace root "${ws}" cannot be resolved: raw workspace resolve failure`) + await expect(canonicalizeWorkspace(fs, ws)).rejects.toBe('raw workspace resolve failure') }) it('rejects a non-directory workspace', async () => { const file = join(root, 'file.txt') await writeFile(file, 'x') - await expect(canonicalizeWorkspace(fs, file)).rejects.toThrow(/not a directory/) + await expect(canonicalizeWorkspace(fs, file)).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_DIRECTORY', + message: `workspace root "${file}" is not a directory`, + }) }) it('normalizes workspace metadata cancellation and preserves other provider failures', async () => { @@ -111,29 +131,56 @@ describe('readHostSource', () => { const outside = join(root, 'outside.ts') await writeFile(outside, 'secret') await symlink(outside, join(ws, 'escape.ts')) - await expect(readSource('escape.ts')).rejects.toThrow(/outside the workspace/) + await expect(readSource('escape.ts')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_FILE_OUTSIDE_WORKSPACE', + message: 'source "escape.ts" resolves outside the workspace', + }) }) it('rejects an absolute source outside the workspace', async () => { const outside = join(root, 'out.ts') await writeFile(outside, 'x') - await expect(readSource(outside)).rejects.toThrow(/outside the workspace/) + await expect(readSource(outside)).rejects.toMatchObject({ name: 'LspError', code: 'LSP_FILE_OUTSIDE_WORKSPACE' }) }) it('rejects a missing source', async () => { - await expect(readSource('nope.ts')).rejects.toThrow(/not found/) + await expect(readSource('nope.ts')).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_FOUND', + message: expect.stringMatching(/^source "nope\.ts" could not be read: .*not found/) as string, + }) }) - it('wraps a provider failure while resolving the source', async () => { + it('adds the source operand to a resolve failure while keeping its code', async () => { const canonical = await workspace() + const providerFailure = new FsError('a parent path segment is not a directory', 'FS_NOT_FOUND') + fs.resolve = async () => { throw providerFailure } + await expect(readHostSource(fs, 'broken.ts', canonical, BIG)).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_FOUND', + message: 'source "broken.ts" cannot be resolved: a parent path segment is not a directory', + cause: providerFailure, + }) fs.resolve = async () => { throw 'raw resolve failure' } - await expect(readHostSource(fs, 'broken.ts', canonical, BIG)) - .rejects.toThrow('source "broken.ts" cannot be resolved: raw resolve failure') + await expect(readHostSource(fs, 'broken.ts', canonical, BIG)).rejects.toBe('raw resolve failure') + }) + + it('propagates a non-filesystem read failure unchanged', async () => { + await writeFile(join(ws, 'a.ts'), 'x') + const canonical = await workspace() + const providerFailure = new Error('stream defect') + fs.streamText = async () => { throw providerFailure } + await expect(readHostSource(fs, 'a.ts', canonical, BIG)).rejects.toBe(providerFailure) }) it('rejects a non-regular source (directory)', async () => { await mkdir(join(ws, 'dir')) - await expect(readSource('dir')).rejects.toThrow(/not a regular file/) + await expect(readSource('dir')).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_REGULAR_FILE', + message: expect.stringMatching(/^source "dir" could not be read: .*not a regular file/) as string, + }) }) // Windows has no filesystem FIFO; the directory case above pins non-regular rejection there. @@ -159,6 +206,8 @@ describe('readHostSource', () => { it('rejects an oversized source and reports the observed lower bound', async () => { await writeFile(join(ws, 'big.ts'), 'x'.repeat(100)) await expect(readSource('big.ts', 10)).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_TOO_LARGE', message: 'source "big.ts" exceeds the 10-byte limit; reading stopped after 100 bytes', }) }) @@ -171,7 +220,11 @@ describe('readHostSource', () => { it('rejects a non-UTF-8 source', async () => { await writeFile(join(ws, 'bin.ts'), Buffer.from([0xff, 0xfe, 0x00])) - await expect(readSource('bin.ts')).rejects.toThrow(/invalid UTF-8|binary file/) + await expect(readSource('bin.ts')).rejects.toMatchObject({ + name: 'FsError', + code: 'FS_NOT_TEXT', + message: expect.stringMatching(/invalid UTF-8|binary file/) as string, + }) }) it('keeps a valid U+FFFD replacement character in otherwise-valid UTF-8', async () => { diff --git a/packages/lsp/lsp-stdio/tests/instance.spec.ts b/packages/lsp/lsp-stdio/tests/instance.spec.ts index bcf2669fd4..10e0a783b1 100644 --- a/packages/lsp/lsp-stdio/tests/instance.spec.ts +++ b/packages/lsp/lsp-stdio/tests/instance.spec.ts @@ -255,7 +255,7 @@ describe('LspInstance query and abort', () => { shutdownTimeoutMs: 100, killGraceMs: 100, }, failingWriter('textDocument/didOpen')) - await expect(run(instance, 'goToDefinition')).rejects.toThrow() + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ name: 'LspError', code: 'LSP_SERVER_EXITED' }) expect(instance.dead).toBe(true) }) @@ -264,13 +264,32 @@ describe('LspInstance query and abort', () => { shutdownTimeoutMs: 100, killGraceMs: 100, }, failingWriter('textDocument/definition')) - await expect(run(instance, 'goToDefinition')).rejects.toThrow(/fixture textDocument\/definition failure/) + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_EXITED', + message: 'language server stopped accepting input: fixture textDocument/definition failure', + }) expect(instance.dead).toBe(true) }) it('rejects when the server lacks the operation capability', async () => { const instance = makeInstance({ LSP_FAKE_CAPS: JSON.stringify({ definitionProvider: false }), LSP_FAKE_DEF: 'null' }) - await expect(run(instance, 'goToDefinition')).rejects.toThrow(/does not support goToDefinition/) + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_OPERATION', + message: 'server does not support goToDefinition', + }) + }) + + it('reports inconsistent instance state as LSP_NOT_INITIALIZED', async () => { + const instance = makeInstance({ LSP_FAKE_DEF: 'null' }) + await expect(run(instance, 'goToDefinition')).resolves.toMatchObject({ kind: 'locations' }) + Reflect.set(instance, 'capabilities', undefined) + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_NOT_INITIALIZED', + message: 'LSP instance is not initialized', + }) }) it('propagates a server error response even when a signal is supplied (not an abort)', async () => { @@ -278,7 +297,11 @@ describe('LspInstance query and abort', () => { // without treating it as an abort. const instance = makeInstance({ LSP_FAKE_ERROR: '1' }) const controller = new AbortController() - await expect(run(instance, 'goToDefinition', controller.signal)).rejects.toThrow(/server refused/) + await expect(run(instance, 'goToDefinition', controller.signal)).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_ERROR', + message: 'language server rejected textDocument/definition with JSON-RPC error -32000: server refused the request', + }) }) it('keeps a settled result but awaits teardown when didClose cannot be written', async () => { @@ -293,6 +316,32 @@ describe('LspInstance query and abort', () => { expect(instance.dead).toBe(true) }) + it('reports the launch failure when the server executable cannot be spawned', async () => { + const instance = makeInstance({}, { command: join(root, 'missing-server') }) + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SPAWN_FAILED', + message: expect.stringMatching(/^language server process failed: .*ENOENT/) as string, + }) + expect(instance.dead).toBe(true) + }) + + it.each([ + ['a non-object result', 'null', 'LSP initialize result was not an object'], + ['no capabilities object', '{}', 'LSP initialize result had no capabilities object'], + ])('rejects an initialize result with %s', async (_label, result, message) => { + const script = 'let b=Buffer.alloc(0);' + + 'const fr=(s)=>{const x=Buffer.from(s);return Buffer.concat([Buffer.from(`Content-Length: ${x.length}\\r\\n\\r\\n`),x]);};' + + 'process.stdin.on("data",c=>{b=Buffer.concat([b,c]);const s=b.indexOf("\\r\\n\\r\\n");if(s<0)return;const len=Number(/(\\d+)/.exec(b.toString("ascii",0,s))[1]);const body=JSON.parse(b.toString("utf8",s+4,s+4+len));b=b.subarray(s+4+len);' + + `if(body.method==="initialize")process.stdout.write(fr(JSON.stringify({jsonrpc:"2.0",id:body.id,result:${result}})));});` + const instance = makeInstance({}, { args: ['-e', script], shutdownTimeoutMs: 100, killGraceMs: 100 }) + await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_MALFORMED_RESPONSE', + message, + }) + }) + }) describe('LspInstance disposal', () => { diff --git a/packages/lsp/lsp-stdio/tests/lifecycle.spec.ts b/packages/lsp/lsp-stdio/tests/lifecycle.spec.ts index 551d1ffe05..62961d01f1 100644 --- a/packages/lsp/lsp-stdio/tests/lifecycle.spec.ts +++ b/packages/lsp/lsp-stdio/tests/lifecycle.spec.ts @@ -153,7 +153,11 @@ describe('lsp-stdio end to end over a fake server', () => { LSP_FAKE_DEF: 'null', LSP_FAKE_EXIT_MARKER: marker, }) - await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toThrow(/unsupported position encoding/) + await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_ENCODING', + message: expect.stringMatching(/unsupported position encoding/) as string, + }) expect(await readFile(marker, 'utf8')).toBe('EXIT\nCLEAN\n') await ctx.fiber.dispose() }) @@ -168,8 +172,41 @@ describe('lsp-stdio end to end over a fake server', () => { await ctx.fiber.dispose() }) - it('preserves a query failure with final disposal failure and evicts the instance', async () => { - const teardownFailure = new Error('managed range observation failed') + it('combines a non-coded query failure with a final disposal failure', async () => { + const teardownFailure = 'managed range observation failed' + const controller = new AbortController() + const cancelled = new Error('caller cancelled') + const ctx = await mount( + { LSP_FAKE_HANG: '1' }, + { shutdownTimeoutMs: 100, killGraceMs: 100 }, + undefined, + (mounted) => { + const spawn = mounted.subprocess.spawn.bind(mounted.subprocess) + vi.spyOn(mounted.subprocess, 'spawn').mockImplementation((spec) => { + const handle = spawn(spec) + const waitForExit = handle.waitForExit.bind(handle) + vi.spyOn(handle, 'waitForExit').mockImplementation(async (signal) => { + await waitForExit(signal) + throw teardownFailure + }) + setTimeout(() => { controller.abort(cancelled) }, 0) + return handle + }) + }, + ) + const failure = await ctx.lsp.query(query('goToDefinition'), controller.signal).then( + () => undefined, + (error: unknown) => error, + ) + expect(failure).toBeInstanceOf(AggregateError) + expect((failure as AggregateError).errors).toEqual([cancelled, teardownFailure]) + await ctx.fiber.dispose() + }) + + it.each([ + ['an Error', new Error('managed range observation failed')], + ['a non-Error value', 'managed range observation failed'], + ])('preserves a query failure with final disposal failure (%s) and evicts the instance', async (_label, teardownFailure) => { let provider: LspProvider | undefined let firstSpawn = true let restoreFirstWait: (() => void) | undefined @@ -198,13 +235,20 @@ describe('lsp-stdio end to end over a fake server', () => { () => undefined, (error: unknown) => error, ) - expect(failure).toBeInstanceOf(AggregateError) - const errors = (failure as AggregateError).errors as unknown[] + expect(failure).toMatchObject({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_ENCODING', + message: expect.stringMatching( + /unsupported position encoding .*; language server teardown also failed: managed range observation failed$/, + ) as string, + }) + const cause = (failure as Error).cause + expect(cause).toBeInstanceOf(AggregateError) + const errors = (cause as AggregateError).errors as unknown[] expect(errors).toHaveLength(2) - expect(errors[0]).toBeInstanceOf(Error) - expect((errors[0] as Error).message).toContain('unsupported position encoding') + expect(errors[0]).toMatchObject({ name: 'LspError', code: 'LSP_UNSUPPORTED_ENCODING' }) expect(errors[1]).toBe(teardownFailure) - expect((failure as AggregateError).message).toBe('LSP operation and teardown failed') + expect((cause as AggregateError).message).toBe('LSP operation and teardown failed') restoreFirstWait?.() if (provider === undefined) throw new Error('expected lsp-stdio to register a provider') const instances = (provider as unknown as { readonly instances: ReadonlyMap }).instances @@ -262,7 +306,11 @@ describe('lsp-stdio end to end over a fake server', () => { it('rejects a server without transient-open sync (None)', async () => { const ctx = await mount({ LSP_FAKE_SYNC: '0', LSP_FAKE_DEF: 'null' }) - await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toThrow(/transient textDocument\/didOpen/) + await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_OPERATION', + message: expect.stringMatching(/transient textDocument\/didOpen/) as string, + }) await ctx.fiber.dispose() }) @@ -274,7 +322,11 @@ describe('lsp-stdio end to end over a fake server', () => { it('fails a query for an unsupported operation', async () => { const ctx = await mount({ LSP_FAKE_CAPS: JSON.stringify({ hoverProvider: false }), LSP_FAKE_DEF: 'null' }) - await expect(ctx.lsp.query(query('hover'))).rejects.toThrow(/does not support hover/) + await expect(ctx.lsp.query(query('hover'))).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_OPERATION', + message: 'server does not support hover', + }) await ctx.fiber.dispose() }) @@ -282,7 +334,10 @@ describe('lsp-stdio end to end over a fake server', () => { const outside = join(root, 'out.ts') await writeFile(outside, 'x') const ctx = await mount({ LSP_FAKE_DEF: 'null' }) - await expect(ctx.lsp.query({ ...query('goToDefinition'), filePath: outside })).rejects.toThrow(/outside the workspace/) + await expect(ctx.lsp.query({ ...query('goToDefinition'), filePath: outside })).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_FILE_OUTSIDE_WORKSPACE', + }) await ctx.fiber.dispose() }) @@ -363,6 +418,18 @@ describe('lsp-stdio end to end over a fake server', () => { await ctx.fiber.dispose() }) + it('names a non-Error abort reason as an AbortError', async () => { + const ctx = await mount({ LSP_FAKE_DEF: 'null' }) + const controller = new AbortController() + controller.abort('caller stopped') + await expect(ctx.lsp.query(query('goToDefinition'), controller.signal)).rejects.toMatchObject({ + name: 'AbortError', + message: 'LSP query aborted', + cause: 'caller stopped', + }) + await ctx.fiber.dispose() + }) + it('surfaces the server stderr tail in the exit error', async () => { // A server that writes to stderr then exits without answering: the query rejection carries the // retained stderr tail so the failure is diagnosable. @@ -370,7 +437,11 @@ describe('lsp-stdio end to end over a fake server', () => { command: process.execPath, args: ['-e', 'process.stderr.write("FATAL: boom\\n"); setTimeout(()=>process.exit(1), 50)'], }) - await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toThrow(/FATAL: boom/) + await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toMatchObject({ + name: 'LspError', + code: 'LSP_SERVER_EXITED', + message: expect.stringMatching(/^language server exited; stderr: FATAL: boom/) as string, + }) await ctx.fiber.dispose() }) @@ -383,9 +454,9 @@ describe('lsp-stdio end to end over a fake server', () => { it('fails the active query when the server crashes on open, and replaces it next query', async () => { const ctx = await mount({ LSP_FAKE_CRASH_ON_OPEN: '1', LSP_FAKE_DEF: 'null' }, { shutdownTimeoutMs: 100, killGraceMs: 100 }) - await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toThrow() + await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toMatchObject({ name: 'LspError', code: 'LSP_SERVER_EXITED' }) // A later query starts a fresh process; still crashes, but proves the slot was replaced (no hang). - await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toThrow() + await expect(ctx.lsp.query(query('goToDefinition'))).rejects.toMatchObject({ name: 'LspError', code: 'LSP_SERVER_EXITED' }) await ctx.fiber.dispose() }) diff --git a/packages/lsp/lsp-stdio/tests/translate.spec.ts b/packages/lsp/lsp-stdio/tests/translate.spec.ts index e38a9d140c..dc14808ac2 100644 --- a/packages/lsp/lsp-stdio/tests/translate.spec.ts +++ b/packages/lsp/lsp-stdio/tests/translate.spec.ts @@ -61,7 +61,11 @@ describe('negotiatePositionEncoding', () => { }) it('rejects any other encoding', () => { - expect(() => negotiatePositionEncoding('utf-8')).toThrow(/unsupported position encoding/) + expect(() => negotiatePositionEncoding('utf-8')).toThrow(expect.objectContaining({ + name: 'LspError', + code: 'LSP_UNSUPPORTED_ENCODING', + message: expect.stringMatching(/unsupported position encoding "utf-8"/) as string, + })) }) }) diff --git a/packages/lsp/lsp/src/index.ts b/packages/lsp/lsp/src/index.ts index 05e2cd3643..1c7028552c 100644 --- a/packages/lsp/lsp/src/index.ts +++ b/packages/lsp/lsp/src/index.ts @@ -42,12 +42,23 @@ declare module '@deepseek-ai/cordis' { } /** - * Structured LSP failure. Extends {@link HarnessError} with a stable `code` - * (`LSP_INVALID_PROVIDER`, `LSP_CONFLICT`, `LSP_UNAVAILABLE`, `LSP_DISPOSED`, - * `LSP_UNSUPPORTED_OPERATION`, `LSP_MALFORMED_RESPONSE`, …) that callers route on instead of - * parsing `message`. + * Structured LSP failure. Extends {@link HarnessError} with a stable `code` that callers route on + * instead of parsing `message`. The seam raises `LSP_INVALID_PROVIDER`, `LSP_CONFLICT`, and + * `LSP_UNAVAILABLE`; providers raise `LSP_DISPOSED`, `LSP_UNSUPPORTED_OPERATION`, and + * `LSP_MALFORMED_RESPONSE`. Providers and consumers add their own documented codes, so `code` + * stays open and consumers tolerate codes they do not know. */ -export class LspError extends HarnessError {} +export class LspError extends HarnessError { + /** + * @param message - actionable description of the failure. + * @param code - stable failure code. + * @param options - the underlying failure, when one exists. + */ + constructor(message: string, code: string, options?: ErrorOptions) { + super(message, code, options) + this.name = 'LspError' + } +} /** * Extract a file's final extension as a normalized, lowercase, leading-dot key (e.g. `Foo.TS` → diff --git a/packages/lsp/tool-lsp/README.i18n.yaml b/packages/lsp/tool-lsp/README.i18n.yaml index 15406bd1ed..e8f31cabd5 100644 --- a/packages/lsp/tool-lsp/README.i18n.yaml +++ b/packages/lsp/tool-lsp/README.i18n.yaml @@ -27,8 +27,8 @@ en: c6ca5869a35edefa zh: 65378aff80dfc93c /deepseek-ai-dsh-tool-lsp/use-this-package/failures-and-recovery: - en: b1f8b3bb52434cc6 - zh: a8c9643a754c4768 + en: 93aff7952acc564a + zh: f27835dfeeb726b7 /deepseek-ai-dsh-tool-lsp/understand-the-implementation: en: 6574e484bce0e60b zh: 75688d1f9dde8f48 diff --git a/packages/lsp/tool-lsp/README.md b/packages/lsp/tool-lsp/README.md index baa4804ace..72145adbc3 100644 --- a/packages/lsp/tool-lsp/README.md +++ b/packages/lsp/tool-lsp/README.md @@ -49,7 +49,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Failures and recovery -The tool requires an Agent Session; a non-agent call fails with `LSP_WORKSPACE_REQUIRED` before any query. The working-directory service supplies and validates its current root. When no provider handles the file's extension, the query fails with `LSP_UNAVAILABLE`; malformed provider payloads remain structured `LSP_MALFORMED_RESPONSE` errors. These surface to the model as error tool results it can read and route on. +An unknown operation, a blank `file_path`, or a coordinate that is not a positive integer fails with `ToolArgsError` `INVALID_ARGS` before any query. The tool requires an Agent Session; a non-agent call fails with `LSP_WORKSPACE_REQUIRED` before any query. The working-directory service supplies and validates its current root. When no provider handles the file's extension, the query fails with `LSP_UNAVAILABLE`; malformed provider payloads remain structured `LSP_MALFORMED_RESPONSE` errors. These and every provider failure surface to the model as error tool results that keep the failure's `name` and `code`; the [LSP navigation subsystem](../../../docs/subsystems/lsp.md#failures) lists the codes. ----- diff --git a/packages/lsp/tool-lsp/README.zh.md b/packages/lsp/tool-lsp/README.zh.md index db825eb415..15eab32136 100644 --- a/packages/lsp/tool-lsp/README.zh.md +++ b/packages/lsp/tool-lsp/README.zh.md @@ -49,7 +49,7 @@ kind: "package-reference" ### 失败与恢复 -该工具要求 Agent Session;非 Agent 调用会在任何查询前以 `LSP_WORKSPACE_REQUIRED` 失败。工作目录服务提供并校验当前根目录。当没有提供方处理该文件扩展名时,查询以 `LSP_UNAVAILABLE` 失败;格式错误的提供方载荷仍保持为结构化 `LSP_MALFORMED_RESPONSE` 错误。这些会呈现为模型可读、可路由的错误工具结果。 +未知操作、空白 `file_path` 或不是正整数的坐标会在任何查询前以 `ToolArgsError` `INVALID_ARGS` 失败。该工具要求 Agent Session;非 Agent 调用会在任何查询前以 `LSP_WORKSPACE_REQUIRED` 失败。工作目录服务提供并校验当前根目录。当没有提供方处理该文件扩展名时,查询以 `LSP_UNAVAILABLE` 失败;格式错误的提供方载荷仍保持为结构化 `LSP_MALFORMED_RESPONSE` 错误。这些失败以及所有提供方失败都会呈现为保留失败 `name` 与 `code` 的错误工具结果;[LSP 导航子系统](../../../docs/subsystems/lsp.zh.md#failures)列出了这些错误码。 ----- diff --git a/packages/lsp/tool-lsp/src/render.ts b/packages/lsp/tool-lsp/src/render.ts index ad77b2a6e2..59fd8b273b 100644 --- a/packages/lsp/tool-lsp/src/render.ts +++ b/packages/lsp/tool-lsp/src/render.ts @@ -6,6 +6,7 @@ * @module @deepseek-ai/dsh-tool-lsp/render */ +import { ToolArgsError } from '@deepseek-ai/dsh-tools' import type { GenericCallView } from '@deepseek-ai/dsh-tools' import type { LspHover, LspLocation, LspOperation, LspPosition } from '@deepseek-ai/dsh-lsp' import { posix, win32 } from 'node:path' @@ -41,13 +42,14 @@ export interface LspToolArgs { * positive one-based integers converted to the seam's zero-based position. * @param args - the schema-validated raw arguments. * @returns the validated input with a zero-based position. - * @throws Error when the operation is unknown or a coordinate is not a positive integer. + * @throws ToolArgsError (`INVALID_ARGS`) when the operation is unknown, `file_path` is blank, or a + * coordinate is not a positive integer. */ export function parseLspArgs(args: LspToolArgs): LspToolInput { if (!isOperation(args.operation)) { - throw new Error(`operation must be one of ${LSP_OPERATIONS.join(', ')}`) + throw new ToolArgsError([`operation must be one of ${LSP_OPERATIONS.join(', ')}`]) } - if (args.file_path.trim().length === 0) throw new Error('file_path must be a non-empty string') + if (args.file_path.trim().length === 0) throw new ToolArgsError(['file_path must be a non-empty string']) const line = oneBased(args.line, 'line') const character = oneBased(args.character, 'character') return { @@ -66,7 +68,7 @@ function isOperation(value: string): value is LspOperation { /** Validate a one-based coordinate is a positive integer. */ function oneBased(value: number, name: string): number { if (!Number.isInteger(value) || value < 1) { - throw new Error(`${name} must be a positive integer (one-based)`) + throw new ToolArgsError([`${name} must be a positive integer (one-based)`]) } return value } diff --git a/packages/lsp/tool-lsp/tests/integration.spec.ts b/packages/lsp/tool-lsp/tests/integration.spec.ts index a0ea788eff..fdde3f79ec 100644 --- a/packages/lsp/tool-lsp/tests/integration.spec.ts +++ b/packages/lsp/tool-lsp/tests/integration.spec.ts @@ -102,4 +102,17 @@ describe('tool-lsp integration', () => { expect(result.error?.info?.code).toBe('TOOL_TIMEOUT') await ctx.fiber.dispose() }, 30_000) + + it('keeps provider failure names and codes on tool results', async () => { + const outside = join(root, 'outside.ts') + await writeFile(outside, 'x') + const ctx = await mount(false) + const missing = await call(ctx, { operation: 'goToDefinition', file_path: 'missing.ts', line: 1, character: 1 }) + expect(missing.isError).toBe(true) + expect(missing.error?.info).toEqual({ name: 'FsError', code: 'FS_NOT_FOUND' }) + const escaped = await call(ctx, { operation: 'goToDefinition', file_path: outside, line: 1, character: 1 }) + expect(escaped.isError).toBe(true) + expect(escaped.error?.info).toEqual({ name: 'LspError', code: 'LSP_FILE_OUTSIDE_WORKSPACE' }) + await ctx.fiber.dispose() + }, 30_000) }) diff --git a/packages/lsp/tool-lsp/tests/render.spec.ts b/packages/lsp/tool-lsp/tests/render.spec.ts index 51fb6a5083..44a05f40b2 100644 --- a/packages/lsp/tool-lsp/tests/render.spec.ts +++ b/packages/lsp/tool-lsp/tests/render.spec.ts @@ -31,18 +31,18 @@ describe('parseLspArgs', () => { it('rejects an unknown operation', () => { expect(() => parseLspArgs({ operation: 'rename', file_path: 'a.ts', line: 1, character: 1 })) - .toThrow(/operation must be one of/) + .toThrow(expect.objectContaining({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringMatching(/operation must be one of/) as string })) }) it('rejects a blank file_path', () => { expect(() => parseLspArgs({ operation: 'hover', file_path: ' ', line: 1, character: 1 })) - .toThrow(/file_path/) + .toThrow(expect.objectContaining({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: 'invalid arguments: file_path must be a non-empty string' })) }) it('rejects non-positive or non-integer coordinates', () => { - expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 0, character: 1 })).toThrow(/line/) - expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 1, character: 0 })).toThrow(/character/) - expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 1.5, character: 1 })).toThrow(/line/) + expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 0, character: 1 })).toThrow(expect.objectContaining({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringMatching(/line must be a positive integer/) as string })) + expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 1, character: 0 })).toThrow(expect.objectContaining({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringMatching(/character must be a positive integer/) as string })) + expect(() => parseLspArgs({ operation: 'hover', file_path: 'a.ts', line: 1.5, character: 1 })).toThrow(expect.objectContaining({ name: 'ToolArgsError', code: 'INVALID_ARGS', message: expect.stringMatching(/line must be a positive integer/) as string })) }) }) diff --git a/packages/lsp/tool-lsp/tests/tool-lsp.spec.ts b/packages/lsp/tool-lsp/tests/tool-lsp.spec.ts index 4947c40379..5e52ba20f6 100644 --- a/packages/lsp/tool-lsp/tests/tool-lsp.spec.ts +++ b/packages/lsp/tool-lsp/tests/tool-lsp.spec.ts @@ -7,7 +7,7 @@ import { pathToFileURL } from 'node:url' import { Context } from '@deepseek-ai/cordis' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' -import Lsp, { LspProviderId, type LspProvider, type LspProviderQuery, type LspQueryResult } from '@deepseek-ai/dsh-lsp' +import Lsp, { LspError, LspProviderId, type LspProvider, type LspProviderQuery, type LspQueryResult } from '@deepseek-ai/dsh-lsp' import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import { DEFAULT_LSP_TOOL_TIMEOUT_MS, LSP_PROMPT_TEXT } from '@deepseek-ai/dsh-tool-lsp' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' @@ -196,21 +196,44 @@ describe('tool-lsp execution', () => { const { ctx } = await mount(stubProvider(() => okLocations)) const result = await call(ctx, { operation: 'goToDefinition', file_path: 'a.ts', line: 1, character: 1 }, null) expect(result.isError).toBe(true) - expect(result.error?.info?.code).toBe('LSP_WORKSPACE_REQUIRED') + expect(result.error?.info).toEqual({ name: 'LspError', code: 'LSP_WORKSPACE_REQUIRED' }) }) it('surfaces a structured LSP_UNAVAILABLE when no provider handles the file', async () => { const { ctx } = await mount(stubProvider(() => okLocations, { '.py': 'python' })) const result = await call(ctx, { operation: 'goToDefinition', file_path: 'a.ts', line: 1, character: 1 }, workspaceRoot) expect(result.isError).toBe(true) - expect(result.error?.info?.code).toBe('LSP_UNAVAILABLE') + expect(result.error?.info).toEqual({ name: 'LspError', code: 'LSP_UNAVAILABLE' }) }) it('returns a structured INVALID_ARGS on a bad operation', async () => { const { ctx } = await mount(stubProvider(() => okLocations)) const result = await call(ctx, { operation: 'rename', file_path: 'a.ts', line: 1, character: 1 }, workspaceRoot) expect(result.isError).toBe(true) - expect(result.error?.info?.code).toBe('INVALID_ARGS') + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + }) + + it.each([ + ['a blank file_path', { file_path: ' ', line: 1, character: 1 }, 'file_path must be a non-empty string'], + ['a zero line', { file_path: 'a.ts', line: 0, character: 1 }, 'line must be a positive integer (one-based)'], + ['a fractional character', { file_path: 'a.ts', line: 1, character: 1.5 }, 'character must be a positive integer (one-based)'], + ])('returns a structured INVALID_ARGS for %s', async (_label, args, violation) => { + const provider = stubProvider(() => okLocations) + const { ctx } = await mount(provider) + const result = await call(ctx, { operation: 'hover', ...args }, workspaceRoot) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) + expect(result.error?.message).toContain(violation) + expect(provider.seen).toHaveLength(0) + }) + + it('keeps a provider failure\'s name and code on the tool result', async () => { + const { ctx } = await mount(stubProvider(() => { + throw new LspError('language server exited', 'LSP_SERVER_EXITED') + })) + const result = await call(ctx, { operation: 'goToDefinition', file_path: 'a.ts', line: 1, character: 1 }, workspaceRoot) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'LspError', code: 'LSP_SERVER_EXITED' }) }) it('forwards exec.signal to the seam query', async () => { From e9ed6104d9a1b8908f7e85b6de6e5a3b378232e4 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:37:56 +0800 Subject: [PATCH 034/438] docs: regenerate config catalog and event graph source lines --- docs/config-catalog.md | 4 ++-- docs/config-catalog.zh.md | 4 ++-- docs/event-producer-consumer.md | 8 ++++---- docs/event-producer-consumer.zh.md | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7edf100e3d..527e193db9 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2341,7 +2341,7 @@ export type Config = Readonly> ## `@deepseek-ai/dsh-lsp-stdio` - `inject`: `fs` · `lsp` · `subprocess` -- `source`: [`packages/lsp/lsp-stdio/src/index.ts:82`](../packages/lsp/lsp-stdio/src/index.ts) +- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts) ```ts config-catalog /** Plugin configuration: provider id → local language-server configuration. */ @@ -4155,7 +4155,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c9ed22e1d4..76218f3d03 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -2343,7 +2343,7 @@ export type Config = Readonly> ## `@deepseek-ai/dsh-lsp-stdio` - `inject`: `fs` · `lsp` · `subprocess` -- `source`: [`packages/lsp/lsp-stdio/src/index.ts:82`](../packages/lsp/lsp-stdio/src/index.ts) +- `source`: [`packages/lsp/lsp-stdio/src/index.ts:83`](../packages/lsp/lsp-stdio/src/index.ts) ```ts config-catalog /** Plugin configuration: provider id → local language-server configuration. */ @@ -4157,7 +4157,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d6514e9585..5d1f5d9790 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -48,10 +48,10 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../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) | -| `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) | +| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../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) | +| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../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:67`](../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) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 38d90599f9..7c9a02987b 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -50,10 +50,10 @@ | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../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) | -| `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) | +| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:75`](../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) | +| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:93`](../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:67`](../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) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | From eee5c94a4170f861157c40338ed2d58d06792830 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 21:59:35 +0800 Subject: [PATCH 035/438] feat(attachment): make AttachmentError a HarnessError AttachmentError now extends HarnessError from the dependency-free dsh-error package, keeping its name and every ATTACHMENT_* and image admission code, so tool results record its name and code and adapter failures report the attachment code instead of UNKNOWN. An upgrade guide records the persisted code change. read_image classifies AttachmentError before the HarnessError pass-through so its ImageInputError codes stay unchanged. HarnessError imports this branch added in dsh-tool-fs and dsh-lsp-stdio now come from dsh-error, which both packages declare. --- docs/module-graph.md | 9 +++++--- docs/module-graph.zh.md | 9 +++++--- .../attachment-error-codes/guide.i18n.yaml | 16 +++++++++++++ .../attachment-error-codes/guide.md | 23 +++++++++++++++++++ .../attachment-error-codes/guide.zh.md | 23 +++++++++++++++++++ .../attachment/attachment/README.i18n.yaml | 4 ++-- packages/attachment/attachment/README.md | 2 +- packages/attachment/attachment/README.zh.md | 2 +- packages/attachment/attachment/package.json | 2 ++ packages/attachment/attachment/src/error.ts | 19 ++++++++------- .../attachment/attachment/tests/index.spec.ts | 10 ++++++++ packages/attachment/attachment/tsconfig.json | 3 ++- .../extensions/tool-cordis/src/api-catalog.ts | 6 ++++- packages/fs/tool-fs/package.json | 2 ++ packages/fs/tool-fs/src/image-error.ts | 2 +- packages/fs/tool-fs/src/read-image.ts | 15 +++++++----- packages/fs/tool-fs/tsconfig.json | 3 +++ packages/lsp/lsp-stdio/package.json | 2 ++ packages/lsp/lsp-stdio/src/connection.ts | 2 +- packages/lsp/lsp-stdio/src/index.ts | 2 +- .../lsp/lsp-stdio/tests/connection.spec.ts | 2 +- packages/lsp/lsp-stdio/tsconfig.json | 3 +++ pnpm-lock.yaml | 9 ++++++++ 23 files changed, 138 insertions(+), 32 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..883e28cd71 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -490,6 +490,7 @@ flowchart TD pkg_session --> pkg_scope pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand + pkg_attachment --> pkg_error pkg_app_boot --> pkg_home_paths pkg_app_boot --> pkg_launch_environment pkg_browser_use --> pkg_brand @@ -649,6 +650,7 @@ flowchart TD pkg_hook_protocol --> pkg_session pkg_hook_protocol --> pkg_shell pkg_lsp_stdio --> pkg_brand + pkg_lsp_stdio --> pkg_error pkg_lsp_stdio --> pkg_fs pkg_lsp_stdio --> pkg_llm pkg_lsp_stdio --> pkg_lsp @@ -861,6 +863,7 @@ flowchart TD pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools pkg_tool_fs --> pkg_attachment + pkg_tool_fs --> pkg_error pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_llm pkg_tool_fs --> pkg_sandbox @@ -1691,7 +1694,7 @@ flowchart TD | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | -| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | +| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | @@ -1761,7 +1764,7 @@ flowchart TD | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | | [`hook-protocol`](../packages/experimental/hook-protocol) | `experimental` | [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | -| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | @@ -1806,7 +1809,7 @@ flowchart TD | [`tool-executor-native`](../packages/core/tool-executor-native) | `core` | [`tools`](../packages/core/tools) | | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..c65ef9fdb4 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -492,6 +492,7 @@ flowchart TD pkg_session --> pkg_scope pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand + pkg_attachment --> pkg_error pkg_app_boot --> pkg_home_paths pkg_app_boot --> pkg_launch_environment pkg_browser_use --> pkg_brand @@ -651,6 +652,7 @@ flowchart TD pkg_hook_protocol --> pkg_session pkg_hook_protocol --> pkg_shell pkg_lsp_stdio --> pkg_brand + pkg_lsp_stdio --> pkg_error pkg_lsp_stdio --> pkg_fs pkg_lsp_stdio --> pkg_llm pkg_lsp_stdio --> pkg_lsp @@ -863,6 +865,7 @@ flowchart TD pkg_tool_goal --> pkg_system_prompt pkg_tool_goal --> pkg_tools pkg_tool_fs --> pkg_attachment + pkg_tool_fs --> pkg_error pkg_tool_fs --> pkg_fs pkg_tool_fs --> pkg_llm pkg_tool_fs --> pkg_sandbox @@ -1693,7 +1696,7 @@ flowchart TD | [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) | | [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | -| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | +| [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | @@ -1763,7 +1766,7 @@ flowchart TD | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | | [`hook-protocol`](../packages/experimental/hook-protocol) | `experimental` | [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | -| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | +| [`lsp-stdio`](../packages/lsp/lsp-stdio) | `lsp` | [`brand`](../packages/util/brand), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`bash-local`](../packages/shell/bash-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`pwsh-local`](../packages/shell/pwsh-local) | `shell` | [`shell`](../packages/shell/shell), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key) | `llm` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | @@ -1808,7 +1811,7 @@ flowchart TD | [`tool-executor-native`](../packages/core/tool-executor-native) | `core` | [`tools`](../packages/core/tools) | | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`tool-goal`](../packages/goal/tool-goal) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-fs`](../packages/fs/tool-fs) | `fs` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) | | [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml new file mode 100644 index 0000000000..07aac6cd05 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +/: + en: 8a0a1ff4ca3ad446 + zh: 4bd6cd51cbd791c2 +/attachment-failures-keep-their-codes: + en: 4f2b2f0db0646d3b + zh: 9467f41336a65c48 +/attachment-failures-keep-their-codes/change: + en: 1e5560d944ebe67d + zh: 235f3ec670b01ae2 +/attachment-failures-keep-their-codes/migration: + en: bceb35b3d8c551c4 + zh: e865e7752bec8d13 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md new file mode 100644 index 0000000000..8c416e5537 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "AttachmentError now extends HarnessError, so tool and model-request failures record attachment codes instead of losing them or reporting UNKNOWN." +--- + +# Attachment failures keep their codes + +English | [中文](guide.zh.md) + +## Change + +`AttachmentError` from `@deepseek-ai/dsh-attachment` now extends `HarnessError` from `@deepseek-ai/dsh-error`. Its `name` (`AttachmentError`) and every `ATTACHMENT_*` and image admission code are unchanged. Two persisted results change: + +- When a model request fails because an adapter could not read an image attachment, the failed turn's `turn/end` error previously recorded `code: 'UNKNOWN'`. It now records the attachment code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, or `ATTACHMENT_READ_FAILED`. +- A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` converts attachment failures to `ImageInputError` codes instead. + +`instanceof HarnessError` now matches `AttachmentError`. `isAttachmentError` is unchanged. + +## Migration + +1. If analytics or retry rules treat `UNKNOWN` model failures as a catch-all, add the attachment codes or route them by their `ATTACHMENT_` prefix. +2. If code catches `HarnessError` before `AttachmentError`, move the `AttachmentError` check first wherever the two need different handling. +3. Earlier Session logs keep `UNKNOWN`; readers that compare old and new logs should treat both as the same failure class for attachment reads. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md new file mode 100644 index 0000000000..3b9ab5145e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "AttachmentError 现在继承 HarnessError,工具失败与模型请求失败会记录附件错误码,不再丢失或报告为 UNKNOWN。" +--- + +# 附件失败保留其错误码 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-attachment` 的 `AttachmentError` 现在继承 `@deepseek-ai/dsh-error` 中的 `HarnessError`。其 `name`(`AttachmentError`)以及所有 `ATTACHMENT_*` 与图像准入错误码均保持不变。两类持久化结果会变化: + +- 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录附件错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT` 或 `ATTACHMENT_READ_FAILED`。 +- 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 则把附件失败转换为 `ImageInputError` 错误码。 + +`instanceof HarnessError` 现在会匹配 `AttachmentError`。`isAttachmentError` 不变。 + +## 迁移 + +1. 如果分析或重试规则把 `UNKNOWN` 模型失败当作兜底类别,请加入这些附件错误码,或按 `ATTACHMENT_` 前缀路由。 +2. 如果代码先捕获 `HarnessError` 再捕获 `AttachmentError`,在两者需要不同处理的地方把 `AttachmentError` 检查移到前面。 +3. 较早的 Session 日志仍保留 `UNKNOWN`;对比新旧日志的读取方应把附件读取的这两种记录视为同一类失败。 diff --git a/packages/attachment/attachment/README.i18n.yaml b/packages/attachment/attachment/README.i18n.yaml index 125d96125d..44c9125f4f 100644 --- a/packages/attachment/attachment/README.i18n.yaml +++ b/packages/attachment/attachment/README.i18n.yaml @@ -36,8 +36,8 @@ en: 25d9c7d6c0899d23 zh: ad8380d14810ff1c /deepseek-ai-dsh-attachment/understand-the-implementation/design-decisions: - en: 6315b2d1fb12f0ca - zh: c3f99f4c0850fb44 + en: bc4586bb4ce74464 + zh: 5ffd0a0e7261bc24 /deepseek-ai-dsh-attachment/understand-the-implementation/service-operations: en: b94d13fe133d8ce6 zh: dd4064d20d510afc diff --git a/packages/attachment/attachment/README.md b/packages/attachment/attachment/README.md index 0e0c2bc05f..075094dcc8 100644 --- a/packages/attachment/attachment/README.md +++ b/packages/attachment/attachment/README.md @@ -67,7 +67,7 @@ This section explains the design decisions behind the seam and the service opera - **Immutable and retention-neutral.** Objects are immutable once published; resumed and forked sessions may share them, so reference-aware garbage collection is deferred rather than tied to any one session's deletion. - **Verify on read.** Reads verify the immutable object against the supplied reference without consulting a Session. Optional display names and pre-normalization dimensions pass through as caller-supplied display information; the stored bytes do not verify these fields. - **Role-neutral image blocks.** The `ImageBlock` content block in `dsh-llm` carries an `ImageAttachmentRef`; provider adapters resolve it into deterministic request versions at an explicit route-chosen target size and byte target, while execution filesystems may map the immutable host object to a model-readable process path. -- **Error routing by code.** `AttachmentError` re-implements the `HarnessError` shape instead of extending it because the base lives in `dsh-llm`, which depends on this package; consumers use `isAttachmentError` and route on `code`, never on the prototype chain. +- **Error routing by code.** `AttachmentError` extends `HarnessError` from the dependency-free `dsh-error`, so tool results keep its `name` and `code`; consumers use `isAttachmentError`, which matches the code across duplicate installations, and route on `code`. - **Files are verbatim, images are normalized.** `saveFile` commits an existing byte array, `saveFileStream` commits bounded chunks with backpressure and cancellation, `readFileStream` verifies and returns bounded chunks, and `fileHostPath` locates the stored object for read-on-demand projection; neither file write path applies admission limits. The image path keeps its separate normalization, limits, and request-version pipeline. The `FileBlock` content block in `dsh-llm` carries a `FileAttachmentRef`, and request assembly projects it to deterministic handle text for every route. ### Service operations diff --git a/packages/attachment/attachment/README.zh.md b/packages/attachment/attachment/README.zh.md index 9c9d2c7fb5..400cc79c1e 100644 --- a/packages/attachment/attachment/README.zh.md +++ b/packages/attachment/attachment/README.zh.md @@ -67,7 +67,7 @@ kind: "package-reference" - **不可变且保留策略中立。** 对象一经发布即不可变;恢复和 fork 后的会话可能共享它们,因此引用感知的垃圾回收被推迟,而不是与任何单个会话的删除绑定。 - **读取时校验。** 读取会把不可变对象与传入引用比对,无需查询 Session。可选的显示名称和规范化前尺寸作为调用方提交的显示信息原样返回;存储字节不校验这两个字段。 - **角色无关的图片块。** `dsh-llm` 中的 `ImageBlock` 内容块携带 `ImageAttachmentRef`;提供方适配器按路由显式选定的目标尺寸与字节目标把引用解析为确定性请求版本,执行文件系统则可以把不可变宿主对象映射为模型可读的进程路径。 -- **按错误码路由。** `AttachmentError` 重新实现 `HarnessError` 的结构而不是继承它,因为基类位于 `dsh-llm`,而后者依赖本包;消费方用 `isAttachmentError` 识别错误并按 `code` 路由,绝不依赖原型链。 +- **按错误码路由。** `AttachmentError` 继承无依赖包 `dsh-error` 中的 `HarnessError`,因此工具结果保留其 `name` 与 `code`;消费方用 `isAttachmentError` 识别错误(它按错误码匹配,跨重复安装也有效),并按 `code` 路由。 - **文件原样,图片规范化。**`saveFile` 提交已有字节数组,`saveFileStream` 以背压和取消语义提交有界分块,`readFileStream` 校验并返回有界分块,`fileHostPath` 定位存储对象供按需读取投影;两种文件写入路径都不设准入限制。图片路径保留其独立的规范化、限额与请求版本流水线。`dsh-llm` 中的 `FileBlock` 内容块承载 `FileAttachmentRef`,请求组装会为每条路由将其投影为确定性的句柄文本。 ### 服务操作 diff --git a/packages/attachment/attachment/package.json b/packages/attachment/attachment/package.json index 79c35fd196..dc831253b1 100644 --- a/packages/attachment/attachment/package.json +++ b/packages/attachment/attachment/package.json @@ -23,10 +23,12 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~" } } diff --git a/packages/attachment/attachment/src/error.ts b/packages/attachment/attachment/src/error.ts index 0aed793f35..2a933daa08 100644 --- a/packages/attachment/attachment/src/error.ts +++ b/packages/attachment/attachment/src/error.ts @@ -1,5 +1,7 @@ /** Attachment failure class. @module @deepseek-ai/dsh-attachment/error */ +import { HarnessError } from '@deepseek-ai/dsh-error' + const IMAGE_ADMISSION_ERROR_CODES = [ 'TOO_MANY_IMAGES', 'IMAGES_TOO_LARGE', @@ -35,17 +37,14 @@ const IMAGE_ADMISSION_ERROR_CODE_SET: ReadonlySet = new Set(IMAGE_ADMISS const ATTACHMENT_ERROR_CODE_SET: ReadonlySet = new Set(ATTACHMENT_ERROR_CODES) /** - * Stable failures suitable for host RPC error mapping. - * - * Deliberately re-implements the `HarnessError` shape instead of extending it: - * the base lives in `@deepseek-ai/dsh-llm`, which itself depends on this - * package (`ImageBlock` references `ImageAttachmentRef`), so sharing the base - * would create a dependency cycle. Consumers route on `code`, never on the - * prototype chain, so the shapes stay interchangeable at the wire boundary. + * Stable failures suitable for host RPC error mapping. Extends {@link HarnessError}, so a tool + * result that fails with it records `name` `AttachmentError` and its `code`. Consumers that may + * receive an error from a duplicate package installation identify it with {@link isAttachmentError}, + * which matches the code instead of the prototype chain. */ -export class AttachmentError extends Error { +export class AttachmentError extends HarnessError { /** Stable machine-routing failure code. */ - readonly code: AttachmentErrorCode + override readonly code: AttachmentErrorCode /** * @param message - human-readable failure description without raw bytes or host paths. @@ -53,7 +52,7 @@ export class AttachmentError extends Error { * @param options - optional chained cause. */ constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions) { - super(message, options) + super(message, code, options) this.name = 'AttachmentError' this.code = code } diff --git a/packages/attachment/attachment/tests/index.spec.ts b/packages/attachment/attachment/tests/index.spec.ts index 9ce59d2d48..159dafd61f 100644 --- a/packages/attachment/attachment/tests/index.spec.ts +++ b/packages/attachment/attachment/tests/index.spec.ts @@ -1,5 +1,6 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-error' import AttachmentStore, { AttachmentError, AttachmentId, @@ -218,6 +219,15 @@ describe('isImageAdmissionError', () => { }) }) +describe('AttachmentError', () => { + it('is a HarnessError that keeps its literal name and attachment code', () => { + const cause = new Error('disk full') + const error = new AttachmentError('disk failed', 'ATTACHMENT_WRITE_FAILED', { cause }) + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ name: 'AttachmentError', code: 'ATTACHMENT_WRITE_FAILED', message: 'disk failed', cause }) + }) +}) + describe('isAttachmentError', () => { it('recognizes attachment failures from another package installation by code', () => { expect(isAttachmentError(new AttachmentError('bad base64', 'INVALID_FILE_BASE64'))).toBe(true) diff --git a/packages/attachment/attachment/tsconfig.json b/packages/attachment/attachment/tsconfig.json index 33e1dd58de..3efee044ab 100644 --- a/packages/attachment/attachment/tsconfig.json +++ b/packages/attachment/attachment/tsconfig.json @@ -5,6 +5,7 @@ "references": [ { "path": "../../../vendor/cosmokit" }, { "path": "../../../vendor/cordis" }, - { "path": "../../util/brand" } + { "path": "../../util/brand" }, + { "path": "../../util/error" } ] } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index c5d2a12f4a..b67d999481 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -5818,7 +5818,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'AttachmentError', - declaration: 'export class AttachmentError extends Error {\n readonly code: AttachmentErrorCode;\n constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions);\n}', + declaration: 'export class AttachmentError extends HarnessError {\n override readonly code: AttachmentErrorCode;\n constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions);\n}', }, { name: 'AttachmentErrorCode', @@ -6792,6 +6792,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}', diff --git a/packages/fs/tool-fs/package.json b/packages/fs/tool-fs/package.json index 331615dce5..7c33681fa8 100644 --- a/packages/fs/tool-fs/package.json +++ b/packages/fs/tool-fs/package.json @@ -39,6 +39,7 @@ "@deepseek-ai/dsh-util-values": "workspace:*" }, "peerDependencies": { + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", @@ -52,6 +53,7 @@ "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts index 102942e9c6..b9839110fc 100644 --- a/packages/fs/tool-fs/src/image-error.ts +++ b/packages/fs/tool-fs/src/image-error.ts @@ -1,6 +1,6 @@ /** Typed `read_image` failures. @module @deepseek-ai/dsh-tool-fs/src/image-error */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every machine-routable `read_image` failure code: diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index b8bacbcba4..159cb2409c 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -16,7 +16,7 @@ import type { Context } from '@deepseek-ai/cordis' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { AttachmentStore, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' @@ -217,21 +217,24 @@ interface SaveFailureFacts { /** * Classify one `saveImage` rejection as the error `read_image` throws. - * An `AbortError` and an already classified `HarnessError` pass through - * unchanged; attachment admission codes become {@link ImageInputError} codes, - * and every other failure becomes `IMAGE_STORE_FAILED` with the original as `cause`. + * Attachment admission codes become {@link ImageInputError} codes and other + * `AttachmentError` codes become `IMAGE_STORE_FAILED`; any other `HarnessError` + * and an `AbortError` pass through unchanged; every other failure becomes + * `IMAGE_STORE_FAILED`. Converted errors keep the original as `cause`. * @param error - the value `saveImage` rejected with. * @param attachments - the store whose limits the refusal names. * @param facts - the path and media-type facts the refusal names. * @returns the error to throw from the tool body. */ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFailureFacts): unknown { - if (error instanceof HarnessError || (error instanceof Error && error.name === 'AbortError')) return error const { displayPath, extension, mediaType, sniffed } = facts const refusal = (detail: string, code: ImageInputError['code']) => new ImageInputError(`cannot read "${displayPath}": ${detail}`, code, { cause: error }) const storeFailed = (detail: string) => refusal(`the attachment store could not save the image: ${detail}`, 'IMAGE_STORE_FAILED') - if (!(error instanceof AttachmentError)) return storeFailed(error instanceof Error ? error.message : String(error)) + if (!(error instanceof AttachmentError)) { + if (error instanceof HarnessError || (error instanceof Error && error.name === 'AbortError')) return error + return storeFailed(error instanceof Error ? error.message : String(error)) + } // Size refusals stay recoverable tool errors: an oversized image must never // enter durable history, where it would ride every later model request past // provider-side dimension rejections. diff --git a/packages/fs/tool-fs/tsconfig.json b/packages/fs/tool-fs/tsconfig.json index 69d7101ff5..8d4c6539b0 100644 --- a/packages/fs/tool-fs/tsconfig.json +++ b/packages/fs/tool-fs/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../util/error" + }, { "path": "../../../vendor/cosmokit" }, diff --git a/packages/lsp/lsp-stdio/package.json b/packages/lsp/lsp-stdio/package.json index 670566cf85..494db76732 100644 --- a/packages/lsp/lsp-stdio/package.json +++ b/packages/lsp/lsp-stdio/package.json @@ -32,6 +32,7 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", @@ -45,6 +46,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", diff --git a/packages/lsp/lsp-stdio/src/connection.ts b/packages/lsp/lsp-stdio/src/connection.ts index e910ac0a52..c0c1fa2a8c 100644 --- a/packages/lsp/lsp-stdio/src/connection.ts +++ b/packages/lsp/lsp-stdio/src/connection.ts @@ -12,7 +12,7 @@ import type { Writable } from 'node:stream' import { LspError } from '@deepseek-ai/dsh-lsp' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { SubprocessHandle, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { encodeMessage, MessageDecoder } from './framing.ts' diff --git a/packages/lsp/lsp-stdio/src/index.ts b/packages/lsp/lsp-stdio/src/index.ts index 1e7fe51591..eee4962849 100644 --- a/packages/lsp/lsp-stdio/src/index.ts +++ b/packages/lsp/lsp-stdio/src/index.ts @@ -14,7 +14,7 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { LspError, LspProviderId } from '@deepseek-ai/dsh-lsp' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import type { LspProvider, LspProviderQuery, diff --git a/packages/lsp/lsp-stdio/tests/connection.spec.ts b/packages/lsp/lsp-stdio/tests/connection.spec.ts index 9428db7ad7..d226e6e8e3 100644 --- a/packages/lsp/lsp-stdio/tests/connection.spec.ts +++ b/packages/lsp/lsp-stdio/tests/connection.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { fileURLToPath } from 'node:url' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { LspConnection } from '@deepseek-ai/dsh-lsp-stdio' import type { ConnectionWriter } from '@deepseek-ai/dsh-lsp-stdio/src/connection.ts' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' diff --git a/packages/lsp/lsp-stdio/tsconfig.json b/packages/lsp/lsp-stdio/tsconfig.json index d133816fda..8487fd28cf 100644 --- a/packages/lsp/lsp-stdio/tsconfig.json +++ b/packages/lsp/lsp-stdio/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../../util/error" + }, { "path": "../../../vendor/cosmokit" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cacf7aa38f..1eb0a0f5a9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1968,6 +1968,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error packages/attachment/attachment-local: dependencies: @@ -12272,6 +12275,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': specifier: workspace:* version: link:../fs @@ -13630,6 +13636,9 @@ importers: '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../util/brand + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs From 43b006af2a7eedfcedda8838a8bf2da844764fbe Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 15:17:46 +0800 Subject: [PATCH 036/438] test(goal): assert the durable blocking operation --- packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index c9be135ea1..35b2d0c3ee 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -738,7 +738,7 @@ describe('same-session goal driving', () => { await admission.promise expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', roundsStarted: 0 }) - expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/blocked')).toBe(false) + expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/change' && event.data.operation === 'block')).toBe(false) }) it('blocks the goal when a custom agent rejects the otherwise valid follow-up', async () => { From 1a3d59a0ff4d1b68a01514d3a9e6c5fe2e13e5eb Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:06:14 +0800 Subject: [PATCH 037/438] test(ui-theme): skip dot directories in the package scan The hover-styles contract walks packages/ for package.json files. Typert generator specs create temporary roots inside that tree with mkdtempSync(join(import.meta.dirname, '....')) and remove them in afterEach, so a concurrent scan can readdir one and then hit ENOENT when its owner deletes it. Dot directories hold VCS metadata and those transient roots, never shipped source, so skip them and let the helper walk an explicit root for the regression test. --- .../ui-theme/tests/stylesheet-scan.spec.ts | 23 +++++++++++++++++++ .../client/ui-theme/tests/stylesheet-scan.ts | 12 ++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 packages/client/ui-theme/tests/stylesheet-scan.spec.ts diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts new file mode 100644 index 0000000000..1614ee55a7 --- /dev/null +++ b/packages/client/ui-theme/tests/stylesheet-scan.spec.ts @@ -0,0 +1,23 @@ +/** Tests for the package-tree scan helpers that the stylesheet contracts range over. */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { packageFiles } from './stylesheet-scan.ts' + +const roots: string[] = [] + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +it('walks shipped package files and skips dot directories holding transient roots', () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-stylesheet-scan-')) + roots.push(root) + mkdirSync(join(root, 'pkg')) + writeFileSync(join(root, 'pkg', 'package.json'), '{}') + mkdirSync(join(root, '.typert-worker-failure-probe')) + writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') + + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) +}) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.ts b/packages/client/ui-theme/tests/stylesheet-scan.ts index 91311945bf..0ddb93e0f8 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.ts @@ -75,20 +75,24 @@ export function varReferences(value: string): string[] { * Every file shipped as package source whose name the predicate accepts, * excluding build output and installed dependencies. * @param accepts - filename predicate. - * @returns absolute paths under packages/, `/`-separated on every platform so + * @param root - tree to walk, the packages directory by default. + * @returns absolute paths under `root`, `/`-separated on every platform so * specs can match repo-relative suffixes verbatim. */ -export function packageFiles(accepts: (name: string) => boolean): string[] { +export function packageFiles(accepts: (name: string) => boolean, root: string = PACKAGES_DIR): string[] { const found: string[] = [] const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name) if (entry.isDirectory()) { - if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) + // Dot directories hold VCS metadata and per-test temporary roots (for + // example `.typert-worker-failure-*`), never shipped package source; a + // concurrent owner can remove one while a scan reads it. + if (!entry.name.startsWith('.') && entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path) } else if (accepts(entry.name)) found.push(path.replaceAll('\\', '/')) } } - walk(PACKAGES_DIR) + walk(root) return found } From c2fd342d33cb214a1fb04e619496d395d044580e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 16:19:10 +0800 Subject: [PATCH 038/438] fix(fs): address review feedback on read_image and create errors - read_image converts only AttachmentError rejections from saveImage; any other value is a store defect or cancellation and propagates unchanged instead of becoming IMAGE_STORE_FAILED. - ImageInputError is no longer exported from the dsh-tool-fs entry, and its JSDoc notes that two codes share AttachmentError spellings. - str_replace_editor create maps a guarded-creation collision (FS_NOT_OBSERVED after a concurrent create) to FS_ALREADY_EXISTS. - The fs-local directory-swap test asserts FS_NOT_REGULAR_FILE exactly. - The attachment upgrade guide lists the full AttachmentErrorCode set instead of an ATTACHMENT_ prefix. - dsh-error dependency entries sit in sorted position. --- docs/config-catalog.md | 4 ++-- docs/config-catalog.zh.md | 4 ++-- .../attachment-error-codes/guide.i18n.yaml | 8 ++++---- .../attachment-error-codes/guide.md | 4 ++-- .../attachment-error-codes/guide.zh.md | 4 ++-- packages/fs/fs-local/tests/fsio.spec.ts | 2 +- packages/fs/tool-fs/README.i18n.yaml | 4 ++-- packages/fs/tool-fs/README.md | 2 +- packages/fs/tool-fs/README.zh.md | 2 +- packages/fs/tool-fs/package.json | 4 ++-- packages/fs/tool-fs/src/image-error.ts | 6 +++++- packages/fs/tool-fs/src/index.ts | 2 -- packages/fs/tool-fs/src/read-image.ts | 12 ++++-------- packages/fs/tool-fs/tests/read-image.spec.ts | 15 +++++---------- .../fs/tool-str-replace-editor/src/index.ts | 11 ++++++++--- .../tests/tools.spec.ts | 18 ++++++++++++++++++ 16 files changed, 59 insertions(+), 43 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 527e193db9..81170e9d3d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4155,7 +4155,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4460,7 +4460,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-str-replace-editor` - `inject`: `tools` · `fs` -- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:506`](../packages/fs/tool-str-replace-editor/src/index.ts) +- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:511`](../packages/fs/tool-str-replace-editor/src/index.ts) ```ts config-catalog /** Configuration for the string-replacement editor tool. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 76218f3d03..53619fd6e7 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4157,7 +4157,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4462,7 +4462,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-str-replace-editor` - `inject`: `tools` · `fs` -- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:506`](../packages/fs/tool-str-replace-editor/src/index.ts) +- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:511`](../packages/fs/tool-str-replace-editor/src/index.ts) ```ts config-catalog /** Configuration for the string-replacement editor tool. */ diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml index 07aac6cd05..091cae83fa 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 4f2b2f0db0646d3b zh: 9467f41336a65c48 /attachment-failures-keep-their-codes/change: - en: 1e5560d944ebe67d - zh: 235f3ec670b01ae2 + en: daa5a93cf418a352 + zh: 3b391fbb4a87f2b1 /attachment-failures-keep-their-codes/migration: - en: bceb35b3d8c551c4 - zh: e865e7752bec8d13 + en: 8599ead7a17bc7eb + zh: 1120fd02065567f5 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md index 8c416e5537..263ddf5df8 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md @@ -11,13 +11,13 @@ English | [中文](guide.zh.md) `AttachmentError` from `@deepseek-ai/dsh-attachment` now extends `HarnessError` from `@deepseek-ai/dsh-error`. Its `name` (`AttachmentError`) and every `ATTACHMENT_*` and image admission code are unchanged. Two persisted results change: -- When a model request fails because an adapter could not read an image attachment, the failed turn's `turn/end` error previously recorded `code: 'UNKNOWN'`. It now records the attachment code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, or `ATTACHMENT_READ_FAILED`. +- When a model request fails because an adapter could not read an image attachment, the failed turn's `turn/end` error previously recorded `code: 'UNKNOWN'`. It now records the `AttachmentError` code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, `ATTACHMENT_READ_FAILED`, or an image admission code such as `INVALID_IMAGE` or `IMAGE_TOO_LARGE`. - A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` converts attachment failures to `ImageInputError` codes instead. `instanceof HarnessError` now matches `AttachmentError`. `isAttachmentError` is unchanged. ## Migration -1. If analytics or retry rules treat `UNKNOWN` model failures as a catch-all, add the attachment codes or route them by their `ATTACHMENT_` prefix. +1. If analytics or retry rules treat `UNKNOWN` model failures as a catch-all, add the codes of the exported `AttachmentErrorCode` type; in code, identify these failures with `isAttachmentError`. The codes do not share one prefix. 2. If code catches `HarnessError` before `AttachmentError`, move the `AttachmentError` check first wherever the two need different handling. 3. Earlier Session logs keep `UNKNOWN`; readers that compare old and new logs should treat both as the same failure class for attachment reads. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md index 3b9ab5145e..674f00805b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md @@ -11,13 +11,13 @@ description: "AttachmentError 现在继承 HarnessError,工具失败与模型 `@deepseek-ai/dsh-attachment` 的 `AttachmentError` 现在继承 `@deepseek-ai/dsh-error` 中的 `HarnessError`。其 `name`(`AttachmentError`)以及所有 `ATTACHMENT_*` 与图像准入错误码均保持不变。两类持久化结果会变化: -- 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录附件错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT` 或 `ATTACHMENT_READ_FAILED`。 +- 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录 `AttachmentError` 的错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT`、`ATTACHMENT_READ_FAILED`,或 `INVALID_IMAGE`、`IMAGE_TOO_LARGE` 等图像准入错误码。 - 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 则把附件失败转换为 `ImageInputError` 错误码。 `instanceof HarnessError` 现在会匹配 `AttachmentError`。`isAttachmentError` 不变。 ## 迁移 -1. 如果分析或重试规则把 `UNKNOWN` 模型失败当作兜底类别,请加入这些附件错误码,或按 `ATTACHMENT_` 前缀路由。 +1. 如果分析或重试规则把 `UNKNOWN` 模型失败当作兜底类别,请加入导出类型 `AttachmentErrorCode` 中的错误码;代码中用 `isAttachmentError` 识别这些失败。这些错误码没有统一前缀。 2. 如果代码先捕获 `HarnessError` 再捕获 `AttachmentError`,在两者需要不同处理的地方把 `AttachmentError` 检查移到前面。 3. 较早的 Session 日志仍保留 `UNKNOWN`;对比新旧日志的读取方应把附件读取的这两种记录视为同一类失败。 diff --git a/packages/fs/fs-local/tests/fsio.spec.ts b/packages/fs/fs-local/tests/fsio.spec.ts index 980f7a722c..4d4f9a3748 100644 --- a/packages/fs/fs-local/tests/fsio.spec.ts +++ b/packages/fs/fs-local/tests/fsio.spec.ts @@ -1058,7 +1058,7 @@ describe('Node errno classification', () => { }, }).then(() => undefined, (caught: unknown) => caught) expect(failure).toBeInstanceOf(FsError) - expect(['FS_NOT_REGULAR_FILE', 'FS_IO_ERROR']).toContain((failure as FsError).code) + expect(failure).toMatchObject({ name: 'FsError', code: 'FS_NOT_REGULAR_FILE', cause: expect.objectContaining({ code: 'EISDIR' }) as Error }) }) it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('maps unreadable file content to FS_PERMISSION_DENIED', async () => { diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index 15125f4f7e..e8c96ec826 100644 --- a/packages/fs/tool-fs/README.i18n.yaml +++ b/packages/fs/tool-fs/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9bddebaf4aff0a8d zh: fea0196162e3fcd1 /deepseek-ai-dsh-tool-fs/use-this-package/failures-and-recovery: - en: 177d25a1e8f7afbd - zh: 0303980d6b2789c3 + en: 06fe9bd1d49c1d53 + zh: a8a6963daae11267 /deepseek-ai-dsh-tool-fs/understand-the-implementation: en: e30f7038c28e93f8 zh: a3868dbd90367b13 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index d7e519d577..cf3ef031df 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -83,7 +83,7 @@ With the policy plugin mounted, `write` and `edit` obtain their guard from the ` For `apply_patch`, syntax and preflight refusals throw with `isError: true` before any disk change. `FsError` preserves filesystem codes; `PatchToolError extends HarnessError` carries `PATCH_SYNTAX` and `PATCH_SYMLINK_SOURCE`. Once commit starts, the tool returns a value with `isError: false` even on failure or uncertainty, so known partial effects retain their diff metadata; a call cancelled during commit receives the tool registry's abort result like every other tool, and its completed changes remain visible through Review. `phase`, `cancelled`, ordered `operations` and `affectedPaths` describe the commit; each operation retains its index, kind, display paths, patch line, status, diagnostic and known changes. Full `before`/`after` text serves rendering and PTC; the Session stores the rendered result plus `meta.diffs` and `meta.stopped`. Creations store no diff, as for `write`; deletions and move sources store a removal diff only when the provider returned a bounded basis, using `newText: ''` because `FileDiff.newText` cannot be null. -`read_image` refusals throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model), `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file), `IMAGE_TYPE_MISMATCH` (rename or convert the file), `IMAGE_INVALID` (truncated or corrupt bytes), `IMAGE_TOO_LARGE` (downscale the image), `IMAGE_CONVERSION_FAILED` (a 16-bit PNG could not be normalized; convert it to 8-bit), and `IMAGE_STORE_FAILED` (any other attachment-store failure, kept as `cause`). An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; an `AbortError` or another `HarnessError` from the store passes through unchanged. +`read_image` refusals throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model), `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file), `IMAGE_TYPE_MISMATCH` (rename or convert the file), `IMAGE_INVALID` (truncated or corrupt bytes), `IMAGE_TOO_LARGE` (downscale the image), `IMAGE_CONVERSION_FAILED` (a 16-bit PNG could not be normalized; convert it to 8-bit), and `IMAGE_STORE_FAILED` (any other attachment-store failure, kept as `cause`). An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any store failure other than an `AttachmentError`, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged. Failures are normalized as `Error: ` with a structured code preserved for callers. Stable messages include the `ToolArgsError` (`INVALID_ARGS`) messages `invalid arguments: file_path must be a non-empty string` and `invalid arguments: limit must be less than or equal to `, `cannot read "": not found`, `cannot read "": not a regular file`, and the image-route refusal `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 7e81223b57..09af000f07 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference" `apply_patch` 的语法与预检拒绝在磁盘变更前抛错,结果为 `isError: true`。`FsError` 保留文件系统错误码;`PatchToolError extends HarnessError` 携带 `PATCH_SYNTAX` 和 `PATCH_SYMLINK_SOURCE`。进入提交后,即使失败或结果不确定也返回 `isError: false` 的值,确保已知部分效果的 diff 元数据得以保留;提交期间被取消的调用与其他工具一样收到工具注册表的中止结果,已完成的变更仍可通过 Review 查看。`phase`、`cancelled`、有序 `operations` 与 `affectedPaths` 描述提交;每条操作保留索引、种类、展示路径、补丁行号、状态、诊断与已知变更。完整 `before`/`after` 文本供渲染和 PTC 使用;Session 保存渲染文本以及 `meta.diffs` 与 `meta.stopped`。新建与 `write` 一样不保存 diff;删除与移动源仅在提供方返回有界基线时保存删除 diff,并使用 `newText: ''`,因为 `FileDiff.newText` 不可为 null。 -`read_image` 的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)、`IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)、`IMAGE_TYPE_MISMATCH`(重命名或转换文件)、`IMAGE_INVALID`(字节被截断或损坏)、`IMAGE_TOO_LARGE`(缩小图像)、`IMAGE_CONVERSION_FAILED`(16 位 PNG 无法规范化;转换为 8 位)以及 `IMAGE_STORE_FAILED`(其他附件存储失败,原错误保留为 `cause`)。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的 `AbortError` 或其他 `HarnessError` 原样传递。 +`read_image` 的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)、`IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)、`IMAGE_TYPE_MISMATCH`(重命名或转换文件)、`IMAGE_INVALID`(字节被截断或损坏)、`IMAGE_TOO_LARGE`(缩小图像)、`IMAGE_CONVERSION_FAILED`(16 位 PNG 无法规范化;转换为 8 位)以及 `IMAGE_STORE_FAILED`(其他附件存储失败,原错误保留为 `cause`)。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的 `AttachmentError` 以外的失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。 失败被规范化为 `Error: `,并为调用方保留结构化错误码。稳定消息包括 `ToolArgsError`(`INVALID_ARGS`)消息 `invalid arguments: file_path must be a non-empty string` 与 `invalid arguments: limit must be less than or equal to `、`cannot read "": not found`、`cannot read "": not a regular file`,以及图像路由拒绝 `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。 diff --git a/packages/fs/tool-fs/package.json b/packages/fs/tool-fs/package.json index 7c33681fa8..e49dad494a 100644 --- a/packages/fs/tool-fs/package.json +++ b/packages/fs/tool-fs/package.json @@ -39,8 +39,8 @@ "@deepseek-ai/dsh-util-values": "workspace:*" }, "peerDependencies": { - "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", @@ -53,11 +53,11 @@ "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { - "@deepseek-ai/dsh-error": "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-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts index b9839110fc..a19a0b0f8d 100644 --- a/packages/fs/tool-fs/src/image-error.ts +++ b/packages/fs/tool-fs/src/image-error.ts @@ -29,7 +29,11 @@ export const IMAGE_INPUT_ERROR_CODES = [ /** One `read_image` failure code. */ export type ImageInputErrorCode = typeof IMAGE_INPUT_ERROR_CODES[number] -/** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */ +/** + * Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. `IMAGE_TOO_LARGE` and + * `IMAGE_TYPE_MISMATCH` share their spelling with `AttachmentError` codes, so consumers route on `name` + * and `code` together, and code-only predicates such as `isAttachmentError` do not identify this class. + */ export class ImageInputError extends HarnessError { override readonly code: ImageInputErrorCode diff --git a/packages/fs/tool-fs/src/index.ts b/packages/fs/tool-fs/src/index.ts index 9e3e3095d5..41e3be251c 100644 --- a/packages/fs/tool-fs/src/index.ts +++ b/packages/fs/tool-fs/src/index.ts @@ -17,8 +17,6 @@ import { applyReadImageTool } from './read-image.ts' import { READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from './read-render.ts' import { FsSandboxController } from './sandbox.ts' -export { ImageInputError, type ImageInputErrorCode } from './image-error.ts' - /** Cordis plugin name used by loader diagnostics. */ export const name = 'tool-fs' diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 159cb2409c..9f7d714ed6 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -16,7 +16,6 @@ import type { Context } from '@deepseek-ai/cordis' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { AttachmentStore, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import { HarnessError } from '@deepseek-ai/dsh-error' import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' @@ -218,9 +217,9 @@ interface SaveFailureFacts { /** * Classify one `saveImage` rejection as the error `read_image` throws. * Attachment admission codes become {@link ImageInputError} codes and other - * `AttachmentError` codes become `IMAGE_STORE_FAILED`; any other `HarnessError` - * and an `AbortError` pass through unchanged; every other failure becomes - * `IMAGE_STORE_FAILED`. Converted errors keep the original as `cause`. + * `AttachmentError` codes become `IMAGE_STORE_FAILED`, keeping the original as + * `cause`. The attachment store reports its own failures as `AttachmentError`, + * so any other value, including cancellation, passes through unchanged. * @param error - the value `saveImage` rejected with. * @param attachments - the store whose limits the refusal names. * @param facts - the path and media-type facts the refusal names. @@ -231,10 +230,7 @@ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFa const refusal = (detail: string, code: ImageInputError['code']) => new ImageInputError(`cannot read "${displayPath}": ${detail}`, code, { cause: error }) const storeFailed = (detail: string) => refusal(`the attachment store could not save the image: ${detail}`, 'IMAGE_STORE_FAILED') - if (!(error instanceof AttachmentError)) { - if (error instanceof HarnessError || (error instanceof Error && error.name === 'AbortError')) return error - return storeFailed(error instanceof Error ? error.message : String(error)) - } + if (!(error instanceof AttachmentError)) return error // Size refusals stay recoverable tool errors: an oversized image must never // enter durable history, where it would ride every later model request past // provider-side dimension rejections. diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index 6c2feac7a4..bced7b466e 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -699,18 +699,13 @@ describe('image admission failures', () => { expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": ${detail}`) }) - it('wraps a non-attachment save failure as IMAGE_STORE_FAILED', async () => { - const result = await failingSave(() => new Error('unrelated infrastructure failure')) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) - expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": the attachment store could not save the image: unrelated infrastructure failure`) + it('passes a store defect, a classified HarnessError, and an AbortError through unchanged', async () => { + const defect = await failingSave(() => new Error('unrelated infrastructure failure')) + expect(defect.isError).toBe(true) + expect(defect.error?.info).toBeUndefined() + expect(text(defect)).toBe('Error: unrelated infrastructure failure') - const nonError = await failingSave(() => 'string failure') - expect(nonError.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) - expect(text(nonError)).toContain('the attachment store could not save the image: string failure') - }) - - it('passes a classified HarnessError and an AbortError through unchanged', async () => { const fsFailure = await failingSave(() => new FsError('cannot read "x": permission denied', 'FS_PERMISSION_DENIED')) expect(fsFailure.error?.info).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' }) expect(text(fsFailure)).toBe('Error: cannot read "x": permission denied') diff --git a/packages/fs/tool-str-replace-editor/src/index.ts b/packages/fs/tool-str-replace-editor/src/index.ts index 099d1a6d73..fa3c5a74e6 100644 --- a/packages/fs/tool-str-replace-editor/src/index.ts +++ b/packages/fs/tool-str-replace-editor/src/index.ts @@ -248,9 +248,12 @@ async function createFile( const content = requiredForCommand(fileText, 'file_text', 'create') const sandboxPolicy = policy.resolve(exec) const target = await resolveTarget(ctx, path, exec.signal) - if (await ctx.fs.stat(target, exec.signal) !== undefined) { - throw new FsError(`File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`, 'FS_ALREADY_EXISTS') - } + const alreadyExists = (cause?: FsError) => new FsError( + `File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`, + 'FS_ALREADY_EXISTS', + cause === undefined ? undefined : { cause }, + ) + if (await ctx.fs.stat(target, exec.signal) !== undefined) throw alreadyExists() const intent = await ctx.waterfall( 'fs/write-intent', target, @@ -267,6 +270,8 @@ async function createFile( sandboxPolicy, ) } catch (error: unknown) { + // A file created after the absence check makes guarded creation report it as unread. + if (error instanceof FsError && error.code === 'FS_NOT_OBSERVED') throw alreadyExists(error) throw policy.mapError(error, sandboxPolicy) } ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec) diff --git a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts index e08c539c59..d780b856fb 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -632,6 +632,24 @@ describe('tool-str-replace-editor', () => { .rejects.toThrow('the mounted filesystem confines but ctx.sandboxPolicy is missing') }) + it('reports a file created after the absence check as FS_ALREADY_EXISTS', async () => { + const { ctx, root, owner } = await setup() + const path = join(root, 'raced.txt') + await writeFile(path, 'concurrent') + const stat = ctx.fs.stat.bind(ctx.fs) + let first = true + ctx.fs.stat = async (target, signal) => { + if (!first) return stat(target, signal) + first = false + return undefined + } + const result = await call(ctx, owner, { command: 'create', path, file_text: 'mine' }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_ALREADY_EXISTS' }) + expect(text(result)).toContain(`File already exists at: ${path}`) + expect(await readFile(path, 'utf8')).toBe('concurrent') + }) + it('maps unexpected backend write failures for replace and insert', async () => { const { ctx, root, owner } = await setup() const path = join(root, 'backend-error.txt') From e80eb062a14c838aeaee98e34537f8e5e9bf6879 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 16:19:12 +0800 Subject: [PATCH 039/438] fix(lsp): derive query capabilities from the handshake result The instance's ready promise now resolves to the negotiated server capabilities, so a query can no longer observe an instance without them; LSP_NOT_INITIALIZED and its private-state test are removed. The LSP failures page qualifies the teardown combination (uncoded query failures surface as AggregateError without error.info) and the stderr tail of LSP_SERVER_EXITED, and LspQueryTeardownError documents that it does not keep the query failure's class. --- docs/subsystems/lsp.i18n.yaml | 4 ++-- docs/subsystems/lsp.md | 5 ++--- docs/subsystems/lsp.zh.md | 5 ++--- packages/lsp/lsp-stdio/README.i18n.yaml | 4 ++-- packages/lsp/lsp-stdio/README.md | 2 +- packages/lsp/lsp-stdio/README.zh.md | 2 +- packages/lsp/lsp-stdio/package.json | 4 ++-- packages/lsp/lsp-stdio/src/index.ts | 3 ++- packages/lsp/lsp-stdio/src/instance.ts | 15 ++++++--------- packages/lsp/lsp-stdio/tests/instance.spec.ts | 11 ----------- 10 files changed, 20 insertions(+), 35 deletions(-) diff --git a/docs/subsystems/lsp.i18n.yaml b/docs/subsystems/lsp.i18n.yaml index 6d21e0fc70..a89df73725 100644 --- a/docs/subsystems/lsp.i18n.yaml +++ b/docs/subsystems/lsp.i18n.yaml @@ -18,5 +18,5 @@ en: 9977196522f2d7e5 zh: f971ba2c60beda68 /lsp-navigation/failures: - en: 192bd5699c1a23af - zh: f221bff65286231a + en: 50959870fd65acce + zh: 9f9e0c2b04572235 diff --git a/docs/subsystems/lsp.md b/docs/subsystems/lsp.md index 275ba3b236..647fd2920b 100644 --- a/docs/subsystems/lsp.md +++ b/docs/subsystems/lsp.md @@ -167,7 +167,7 @@ interface LspService { ## Failures -Every expected failure of an `lsp` tool call is a `HarnessError` whose `name` and `code` the tool result keeps in `error.info`. `LspError` sets `name` to `LspError`; its `code` stays open because providers and consumers add codes, so consumers tolerate codes they do not know. Invalid tool arguments fail as `ToolArgsError` `INVALID_ARGS`, and caller cancellation as `AbortError`. Workspace and source reads keep the filesystem provider's `FsError` code, such as `FS_NOT_FOUND`, `FS_NOT_REGULAR_FILE`, or `FS_NOT_TEXT`, and prefix the LSP operand to its message; the stdio provider adds `FS_NOT_DIRECTORY` for a non-directory workspace and `FS_TOO_LARGE` for a source over `maxDocumentBytes`. A query failure whose server teardown also fails keeps the query failure's `name` and `code` and appends the teardown failure to its message. +Every expected failure of an `lsp` tool call is a `HarnessError` whose `name` and `code` the tool result keeps in `error.info`. `LspError` sets `name` to `LspError`; its `code` stays open because providers and consumers add codes, so consumers tolerate codes they do not know. Invalid tool arguments fail as `ToolArgsError` `INVALID_ARGS`, and caller cancellation as `AbortError`. Workspace and source reads keep the filesystem provider's `FsError` code, such as `FS_NOT_FOUND`, `FS_NOT_REGULAR_FILE`, or `FS_NOT_TEXT`, and prefix the LSP operand to its message; the stdio provider adds `FS_NOT_DIRECTORY` for a non-directory workspace and `FS_TOO_LARGE` for a source over `maxDocumentBytes`. A coded query failure whose server teardown also fails keeps the query failure's `name` and `code` and appends the teardown failure to its message; a query failure without a code, such as a cancellation, surfaces with the teardown failure as an `AggregateError` without `error.info`. | Code | Raised by | Meaning | Consumer action | |---|---|---|---| @@ -181,11 +181,10 @@ Every expected failure of an `lsp` tool call is a `HarnessError` whose `name` an | `LSP_FILE_OUTSIDE_WORKSPACE` | Stdio provider | The source resolves outside the canonical workspace | Query a file inside the workspace | | `LSP_UNSUPPORTED_ENCODING` | Stdio provider | The server negotiated a position encoding other than UTF-16 | Use a server that supports UTF-16 | | `LSP_SPAWN_FAILED` | Stdio provider | The subprocess provider failed to launch or run the server; a provider `HarnessError` keeps its own `name` and `code` instead | Fix the server command or installation | -| `LSP_SERVER_EXITED` | Stdio provider | The server exited or closed its stdin; the message carries the retained stderr tail | Retry later; inspect the stderr tail when it repeats | +| `LSP_SERVER_EXITED` | Stdio provider | The server exited or closed its stdin; after an exit, the message carries the retained stderr tail | Retry later; inspect the stderr tail when it repeats | | `LSP_PROTOCOL_ERROR` | Stdio provider | The server's output broke base-protocol framing or JSON | Report the server defect | | `LSP_MESSAGE_TOO_LARGE` | Stdio provider | A server message exceeded `maxMessageBytes` | Narrow the query or raise `maxMessageBytes` | | `LSP_SERVER_ERROR` | Stdio provider | The server answered with a JSON-RPC error; the message carries its numeric code and text | Act on the server's message | -| `LSP_NOT_INITIALIZED` | Stdio provider | A query found the server instance without negotiated capabilities after its handshake succeeded; this is inconsistent internal state, not a server condition | Report the defect | After a transport failure (`LSP_SPAWN_FAILED`, `LSP_SERVER_EXITED`, `LSP_PROTOCOL_ERROR`, or `LSP_MESSAGE_TOO_LARGE`), the stdio provider retries the read-only query once on a fresh process when the failed process tears down cleanly. diff --git a/docs/subsystems/lsp.zh.md b/docs/subsystems/lsp.zh.md index 65612a8eac..7a6ef8d3c6 100644 --- a/docs/subsystems/lsp.zh.md +++ b/docs/subsystems/lsp.zh.md @@ -167,7 +167,7 @@ interface LspService { ## 失败 -`lsp` 工具调用的每个预期失败都是 `HarnessError`,工具结果会把它的 `name` 和 `code` 保留在 `error.info` 中。`LspError` 把 `name` 设为 `LspError`;由于提供方和消费方会添加错误码,它的 `code` 保持开放,消费方须容忍未知错误码。无效的工具参数以 `ToolArgsError` `INVALID_ARGS` 失败,调用方取消以 `AbortError` 失败。工作区与源文件读取保留文件系统提供方的 `FsError` 错误码,例如 `FS_NOT_FOUND`、`FS_NOT_REGULAR_FILE` 或 `FS_NOT_TEXT`,并在其消息前加上 LSP 操作对象;stdio 提供方对非目录工作区使用 `FS_NOT_DIRECTORY`,对超过 `maxDocumentBytes` 的源文件使用 `FS_TOO_LARGE`。如果查询失败后服务器拆除也失败,错误保留查询失败的 `name` 和 `code`,并把拆除失败追加到消息中。 +`lsp` 工具调用的每个预期失败都是 `HarnessError`,工具结果会把它的 `name` 和 `code` 保留在 `error.info` 中。`LspError` 把 `name` 设为 `LspError`;由于提供方和消费方会添加错误码,它的 `code` 保持开放,消费方须容忍未知错误码。无效的工具参数以 `ToolArgsError` `INVALID_ARGS` 失败,调用方取消以 `AbortError` 失败。工作区与源文件读取保留文件系统提供方的 `FsError` 错误码,例如 `FS_NOT_FOUND`、`FS_NOT_REGULAR_FILE` 或 `FS_NOT_TEXT`,并在其消息前加上 LSP 操作对象;stdio 提供方对非目录工作区使用 `FS_NOT_DIRECTORY`,对超过 `maxDocumentBytes` 的源文件使用 `FS_TOO_LARGE`。如果带错误码的查询失败后服务器拆除也失败,错误保留查询失败的 `name` 和 `code`,并把拆除失败追加到消息中;不带错误码的查询失败(例如取消)与拆除失败一起以 `AggregateError` 呈现,不带 `error.info`。 | 错误码 | 抛出方 | 含义 | 消费方操作 | |---|---|---|---| @@ -181,11 +181,10 @@ interface LspService { | `LSP_FILE_OUTSIDE_WORKSPACE` | stdio 提供方 | 源文件解析到规范工作区之外 | 查询工作区内的文件 | | `LSP_UNSUPPORTED_ENCODING` | stdio 提供方 | 服务器协商了 UTF-16 以外的位置编码 | 使用支持 UTF-16 的服务器 | | `LSP_SPAWN_FAILED` | stdio 提供方 | 子进程提供方未能启动或运行服务器;提供方的 `HarnessError` 则保留其自身的 `name` 和 `code` | 修正服务器命令或安装 | -| `LSP_SERVER_EXITED` | stdio 提供方 | 服务器已退出或关闭了 stdin;消息携带保留的 stderr 尾部 | 稍后重试;反复出现时检查 stderr 尾部 | +| `LSP_SERVER_EXITED` | stdio 提供方 | 服务器已退出或关闭了 stdin;进程退出时消息携带保留的 stderr 尾部 | 稍后重试;反复出现时检查 stderr 尾部 | | `LSP_PROTOCOL_ERROR` | stdio 提供方 | 服务器输出破坏了基础协议分帧或 JSON | 报告服务器缺陷 | | `LSP_MESSAGE_TOO_LARGE` | stdio 提供方 | 某条服务器消息超过 `maxMessageBytes` | 缩小查询范围或调大 `maxMessageBytes` | | `LSP_SERVER_ERROR` | stdio 提供方 | 服务器以 JSON-RPC 错误应答;消息携带其数字错误码与文本 | 按服务器消息处理 | -| `LSP_NOT_INITIALIZED` | stdio 提供方 | 握手已成功,但查询时服务器实例没有已协商的能力;这是内部状态不一致,不是服务器的情况 | 报告该缺陷 | 传输失败(`LSP_SPAWN_FAILED`、`LSP_SERVER_EXITED`、`LSP_PROTOCOL_ERROR` 或 `LSP_MESSAGE_TOO_LARGE`)后,如果失败的进程干净地完成拆除,stdio 提供方会在新进程上把只读查询重试一次。 diff --git a/packages/lsp/lsp-stdio/README.i18n.yaml b/packages/lsp/lsp-stdio/README.i18n.yaml index 369a475ea4..f4f7a2db0e 100644 --- a/packages/lsp/lsp-stdio/README.i18n.yaml +++ b/packages/lsp/lsp-stdio/README.i18n.yaml @@ -24,8 +24,8 @@ en: 41363baf8fdba020 zh: d1a6193b1aa813ba /deepseek-ai-dsh-lsp-stdio/use-this-package/observable-success-and-failures: - en: 27766a0ecd0f70fa - zh: 532bc93a8ce5e701 + en: 9b947af73dbe2305 + zh: e40b163f476deaf9 /deepseek-ai-dsh-lsp-stdio/use-this-package/security-boundary: en: f1f7fef771bcaa6d zh: f11dcf771a6fecfc diff --git a/packages/lsp/lsp-stdio/README.md b/packages/lsp/lsp-stdio/README.md index 8f30301f48..418e44520b 100644 --- a/packages/lsp/lsp-stdio/README.md +++ b/packages/lsp/lsp-stdio/README.md @@ -68,7 +68,7 @@ On the first query for a workspace, the provider launches one server process for ### Observable success and failures -A successful navigation returns normalized locations, and hover returns normalized text or a no-hover notice; empty results are successful no-result responses. Before the server starts, a missing, non-directory, non-regular, non-UTF-8, or oversized workspace or source fails with its `FsError` code, and a source outside the canonical workspace fails with `LSP_FILE_OUTSIDE_WORKSPACE`. The server then fails the query with `LSP_UNSUPPORTED_OPERATION` when it lacks the operation or the transient open/close synchronization, `LSP_UNSUPPORTED_ENCODING` for a non-UTF-16 position encoding, `LSP_MALFORMED_RESPONSE` for a malformed payload, and `LSP_SERVER_ERROR` for a JSON-RPC error response; a failed process or stream reports `LSP_SPAWN_FAILED`, `LSP_SERVER_EXITED`, `LSP_PROTOCOL_ERROR`, or `LSP_MESSAGE_TOO_LARGE`; a query that finds the instance without negotiated capabilities after a successful handshake reports `LSP_NOT_INITIALIZED`, which marks a provider defect. The [LSP navigation subsystem](../../../docs/subsystems/lsp.md#failures) gives each code's meaning and consumer action. A hard-killed harness leaves servers running until they exit on their own — graceful shutdown happens only through service disposal. +A successful navigation returns normalized locations, and hover returns normalized text or a no-hover notice; empty results are successful no-result responses. Before the server starts, a missing, non-directory, non-regular, non-UTF-8, or oversized workspace or source fails with its `FsError` code, and a source outside the canonical workspace fails with `LSP_FILE_OUTSIDE_WORKSPACE`. The server then fails the query with `LSP_UNSUPPORTED_OPERATION` when it lacks the operation or the transient open/close synchronization, `LSP_UNSUPPORTED_ENCODING` for a non-UTF-16 position encoding, `LSP_MALFORMED_RESPONSE` for a malformed payload, and `LSP_SERVER_ERROR` for a JSON-RPC error response; a failed process or stream reports `LSP_SPAWN_FAILED`, `LSP_SERVER_EXITED`, `LSP_PROTOCOL_ERROR`, or `LSP_MESSAGE_TOO_LARGE`. The [LSP navigation subsystem](../../../docs/subsystems/lsp.md#failures) gives each code's meaning and consumer action. A hard-killed harness leaves servers running until they exit on their own — graceful shutdown happens only through service disposal. ### Security boundary diff --git a/packages/lsp/lsp-stdio/README.zh.md b/packages/lsp/lsp-stdio/README.zh.md index f54eda31c1..e16e912cef 100644 --- a/packages/lsp/lsp-stdio/README.zh.md +++ b/packages/lsp/lsp-stdio/README.zh.md @@ -68,7 +68,7 @@ kind: "package-reference" ### 可观察的成功与失败 -成功的导航返回规范化位置,悬停返回规范化文本或无可悬停提示;空结果是成功的无结果响应。在服务器启动前,缺失、非目录、非普通文件、非 UTF-8 或过大的工作区或源文件以其 `FsError` 错误码失败,位于规范工作区之外的源文件以 `LSP_FILE_OUTSIDE_WORKSPACE` 失败。随后,服务器不支持该操作或临时打开/关闭同步时查询以 `LSP_UNSUPPORTED_OPERATION` 失败,非 UTF-16 位置编码以 `LSP_UNSUPPORTED_ENCODING` 失败,格式错误的载荷以 `LSP_MALFORMED_RESPONSE` 失败,JSON-RPC 错误响应以 `LSP_SERVER_ERROR` 失败;进程或流失败时报告 `LSP_SPAWN_FAILED`、`LSP_SERVER_EXITED`、`LSP_PROTOCOL_ERROR` 或 `LSP_MESSAGE_TOO_LARGE`;握手成功后查询却发现实例没有已协商的能力时报告 `LSP_NOT_INITIALIZED`,表示提供方存在缺陷。[LSP 导航子系统](../../../docs/subsystems/lsp.zh.md#failures)给出每个错误码的含义与消费方操作。被强制杀死的 harness 会让服务器继续运行直到自行退出——优雅关闭只发生在服务释放时。 +成功的导航返回规范化位置,悬停返回规范化文本或无可悬停提示;空结果是成功的无结果响应。在服务器启动前,缺失、非目录、非普通文件、非 UTF-8 或过大的工作区或源文件以其 `FsError` 错误码失败,位于规范工作区之外的源文件以 `LSP_FILE_OUTSIDE_WORKSPACE` 失败。随后,服务器不支持该操作或临时打开/关闭同步时查询以 `LSP_UNSUPPORTED_OPERATION` 失败,非 UTF-16 位置编码以 `LSP_UNSUPPORTED_ENCODING` 失败,格式错误的载荷以 `LSP_MALFORMED_RESPONSE` 失败,JSON-RPC 错误响应以 `LSP_SERVER_ERROR` 失败;进程或流失败时报告 `LSP_SPAWN_FAILED`、`LSP_SERVER_EXITED`、`LSP_PROTOCOL_ERROR` 或 `LSP_MESSAGE_TOO_LARGE`。[LSP 导航子系统](../../../docs/subsystems/lsp.zh.md#failures)给出每个错误码的含义与消费方操作。被强制杀死的 harness 会让服务器继续运行直到自行退出——优雅关闭只发生在服务释放时。 ### 安全边界 diff --git a/packages/lsp/lsp-stdio/package.json b/packages/lsp/lsp-stdio/package.json index 494db76732..4afa5b8d0d 100644 --- a/packages/lsp/lsp-stdio/package.json +++ b/packages/lsp/lsp-stdio/package.json @@ -32,9 +32,9 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-lsp": "workspace:*", @@ -46,9 +46,9 @@ "@deepseek-ai/schemastery": "workspace:~" }, "devDependencies": { - "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/lsp/lsp-stdio/src/index.ts b/packages/lsp/lsp-stdio/src/index.ts index eee4962849..7c42effa43 100644 --- a/packages/lsp/lsp-stdio/src/index.ts +++ b/packages/lsp/lsp-stdio/src/index.ts @@ -119,7 +119,8 @@ function throwTeardownFailures(results: readonly PromiseSettledResult[], m /** * A coded query failure whose instance teardown also failed. It keeps the query failure's `name` - * and `code` so tool results route on the query outcome; `cause` aggregates both failures. + * and `code` so tool results route on the query outcome; `cause` aggregates both failures. It does + * not keep the query failure's class, so route on `name` and `code`, not `instanceof`. */ class LspQueryTeardownError extends HarnessError { constructor(query: HarnessError, teardown: unknown, cause: AggregateError) { diff --git a/packages/lsp/lsp-stdio/src/instance.ts b/packages/lsp/lsp-stdio/src/instance.ts index f72a892fd5..30c5225468 100644 --- a/packages/lsp/lsp-stdio/src/instance.ts +++ b/packages/lsp/lsp-stdio/src/instance.ts @@ -45,7 +45,6 @@ export interface InstanceSpec extends ConnectionSpec { */ export class LspInstance { private readonly connection: LspConnection - private capabilities: WireServerCapabilities | undefined /** The serialization tail: each query awaits the prior one, so lifecycles never interleave. */ private queue: Promise = Promise.resolve() private disposed = false @@ -53,8 +52,8 @@ export class LspInstance { private teardownPromise: Promise | undefined /** Set once the process closes, so the pool can synchronously skip a dead instance. */ private processClosed = false - /** Populated once `initialize` succeeds; a failed handshake rejects every query. */ - private readonly ready: Promise + /** The server's negotiated capabilities once `initialize` succeeds; a failed handshake rejects every query. */ + private readonly ready: Promise /** * @param spec - the launch, initialize, and teardown parameters. @@ -109,7 +108,7 @@ export class LspInstance { return run } - private async initialize(): Promise { + private async initialize(): Promise { const initializeResult = await this.connection.request('initialize', { // A subprocess provider may run in another PID namespace or machine; // the host PID would let the server monitor an unrelated process. @@ -122,8 +121,8 @@ export class LspInstance { const capabilities = initializeCapabilities(initializeResult) // An omitted encoding defaults to utf-16; any other value is a protocol error we reject here. negotiatePositionEncoding(capabilities.positionEncoding) - this.capabilities = capabilities await this.connection.notify('initialized', {}) + return capabilities } private async runQuery(request: LspProviderQuery, source: HostSource, signal?: AbortSignal): Promise { @@ -134,17 +133,15 @@ export class LspInstance { // in failure — an abort on a still-pending handshake, OR `initialize` rejecting (utf-8 // negotiation, malformed result) without the process exiting — tear the instance down so a // permanently-rejecting/pending `ready` can't make every later query for this workspace fail. + let capabilities: WireServerCapabilities try { - await abortable(this.ready, signal) + capabilities = await abortable(this.ready, signal) } catch (error) { if (!this.dead) { await this.awaitTeardownAttempt() } throw error } - const capabilities = this.capabilities - // `ready` resolves only after capabilities are set; reaching this means instance state is inconsistent. - if (capabilities === undefined) throw new LspError('LSP instance is not initialized', 'LSP_NOT_INITIALIZED') if (!supportsOperation(capabilities, request.operation)) { throw new LspError(`server does not support ${request.operation}`, 'LSP_UNSUPPORTED_OPERATION') } diff --git a/packages/lsp/lsp-stdio/tests/instance.spec.ts b/packages/lsp/lsp-stdio/tests/instance.spec.ts index 10e0a783b1..e34366042d 100644 --- a/packages/lsp/lsp-stdio/tests/instance.spec.ts +++ b/packages/lsp/lsp-stdio/tests/instance.spec.ts @@ -281,17 +281,6 @@ describe('LspInstance query and abort', () => { }) }) - it('reports inconsistent instance state as LSP_NOT_INITIALIZED', async () => { - const instance = makeInstance({ LSP_FAKE_DEF: 'null' }) - await expect(run(instance, 'goToDefinition')).resolves.toMatchObject({ kind: 'locations' }) - Reflect.set(instance, 'capabilities', undefined) - await expect(run(instance, 'goToDefinition')).rejects.toMatchObject({ - name: 'LspError', - code: 'LSP_NOT_INITIALIZED', - message: 'LSP instance is not initialized', - }) - }) - it('propagates a server error response even when a signal is supplied (not an abort)', async () => { // A live signal is passed, but the request fails for a server reason; the catch must rethrow // without treating it as an abort. From 646e46e0afeb47bce742a1eae4e473b8d6f51a99 Mon Sep 17 00:00:00 2001 From: dsh-ci-bot Date: Fri, 6 Nov 2026 16:24:29 +0800 Subject: [PATCH 040/438] test(ui-theme): scope the package-scan spec to the client face packageFiles() reports '/'-separated paths on every platform, so the fixture's temporary root must be normalized before it forms the expectation; otherwise the Windows coverage lane fails. The spec also belongs to the client aggregate, because an unsuffixed spec file under packages/client is compiled by both aggregates. --- ...stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename packages/client/ui-theme/tests/{stylesheet-scan.spec.ts => stylesheet-scan.client.spec.ts} (82%) diff --git a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts similarity index 82% rename from packages/client/ui-theme/tests/stylesheet-scan.spec.ts rename to packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts index 1614ee55a7..312ee01382 100644 --- a/packages/client/ui-theme/tests/stylesheet-scan.spec.ts +++ b/packages/client/ui-theme/tests/stylesheet-scan.client.spec.ts @@ -19,5 +19,7 @@ it('walks shipped package files and skips dot directories holding transient root mkdirSync(join(root, '.typert-worker-failure-probe')) writeFileSync(join(root, '.typert-worker-failure-probe', 'package.json'), '{}') - expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root}/pkg/package.json`]) + // The helper reports `/`-separated paths on every platform, so the Windows + // temporary root's separators must not reach the expectation. + expect(packageFiles(name => name === 'package.json', root)).toEqual([`${root.replaceAll('\\', '/')}/pkg/package.json`]) }) From 4ef46e21b1ca0af4eab649670ffd0929d8124b11 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:41:02 +0800 Subject: [PATCH 041/438] feat(subprocess): add SubprocessError and make Win32Error a HarnessError The subprocess Service Definition exports SubprocessError with a closed SUBPROCESS_* code list, rebases SubprocessExecutableNotFoundError on it with the same name, and adds subprocessSpawnFailure() so consumers that report a spawn rejection classify ENOENT and other platform errors with the original as cause. subprocess-local codes empty argv, Windows Job runner failures, runner IPC failures, and an unloadable node-pty, and names its pre-aborted spawn error AbortError so the tool registry classifies it as cancellation. Win32Error now extends HarnessError with code WIN32_ERROR, keeping its name, api, and win32Code fields. Refs #7869 --- .../subprocess-local/README.i18n.yaml | 4 +- .../subprocess/subprocess-local/README.md | 2 +- .../subprocess/subprocess-local/README.zh.md | 2 +- .../subprocess/subprocess-local/src/index.ts | 19 +++- .../subprocess/subprocess-local/src/spawn.ts | 9 +- .../subprocess-local/src/windows-job.ts | 36 ++++++-- .../subprocess-local/tests/local.spec.ts | 30 +++++++ .../subprocess-local/tests/spawn.spec.ts | 11 +-- .../tests/windows-job.spec.ts | 14 ++- .../subprocess/subprocess/README.i18n.yaml | 8 +- packages/subprocess/subprocess/README.md | 3 +- packages/subprocess/subprocess/README.zh.md | 3 +- packages/subprocess/subprocess/package.json | 6 +- packages/subprocess/subprocess/src/error.ts | 87 +++++++++++++++++++ packages/subprocess/subprocess/src/index.ts | 19 ++-- .../subprocess/subprocess/tests/error.spec.ts | 48 ++++++++++ packages/subprocess/subprocess/tsconfig.json | 3 + .../subprocess/win32-process/README.i18n.yaml | 4 +- packages/subprocess/win32-process/README.md | 2 +- .../subprocess/win32-process/README.zh.md | 2 +- .../subprocess/win32-process/package.json | 6 +- .../subprocess/win32-process/src/errors.ts | 14 ++- .../win32-process/tests/ffi.spec.ts | 5 ++ .../subprocess/win32-process/tsconfig.json | 3 + pnpm-lock.yaml | 6 ++ 25 files changed, 292 insertions(+), 54 deletions(-) create mode 100644 packages/subprocess/subprocess/src/error.ts create mode 100644 packages/subprocess/subprocess/tests/error.spec.ts diff --git a/packages/subprocess/subprocess-local/README.i18n.yaml b/packages/subprocess/subprocess-local/README.i18n.yaml index e46cbba8b2..b81bef5b96 100644 --- a/packages/subprocess/subprocess-local/README.i18n.yaml +++ b/packages/subprocess/subprocess-local/README.i18n.yaml @@ -36,8 +36,8 @@ en: cd0b8a5dc61335a5 zh: ac5077a9ac277141 /deepseek-ai-dsh-subprocess-local/use-this-package/what-can-go-wrong: - en: 1e1ce532b004c92b - zh: ca7274b7a9207a5d + en: 8320b322423ed5a4 + zh: a32e769d2a351694 /deepseek-ai-dsh-subprocess-local/understand-the-implementation: en: 531a48766c666ea0 zh: b40df533a2fd7244 diff --git a/packages/subprocess/subprocess-local/README.md b/packages/subprocess/subprocess-local/README.md index 6d943b32e6..6ede37c8d1 100644 --- a/packages/subprocess/subprocess-local/README.md +++ b/packages/subprocess/subprocess-local/README.md @@ -69,7 +69,7 @@ Linux ordinary and terminal cancellation preserves the observed termination sign ### What can go wrong -An executable that cannot be resolved fails loud with a stable error. `done` rejects when spawn or provider failure prevents a direct outcome, and that rejection does not prove whether target execution began. `waitForExit()` rejects if the selected owner can no longer prove its range empty, and cleanup still attempts termination. A read past the retained tail is `lossy` and points at the spill file when one exists. A fallback process group or observed terminal session can miss a descendant that escapes before observation — see the limitations below. +An executable that cannot be resolved fails loud with a stable error. `done` rejects when spawn or provider failure prevents a direct outcome, and that rejection does not prove whether target execution began: a platform spawn error stays the original Node error, while a Windows Job runner that fails after it started or breaks its IPC channel rejects with `SubprocessError` `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`. A terminal request on a host where node-pty cannot load throws `SUBPROCESS_PTY_UNAVAILABLE`. `waitForExit()` rejects if the selected owner can no longer prove its range empty, and cleanup still attempts termination. A read past the retained tail is `lossy` and points at the spill file when one exists. A fallback process group or observed terminal session can miss a descendant that escapes before observation — see the limitations below. ----- diff --git a/packages/subprocess/subprocess-local/README.zh.md b/packages/subprocess/subprocess-local/README.zh.md index d82d971cdf..0240ea3c50 100644 --- a/packages/subprocess/subprocess-local/README.zh.md +++ b/packages/subprocess/subprocess-local/README.zh.md @@ -69,7 +69,7 @@ Linux 普通进程和终端进程即使在 bootstrap 消费启动请求前被取 ### 可能出错的地方 -无法解析的可执行文件会明确报出稳定错误。当 spawn 或提供方故障使 direct outcome 无法产生时,`done` 会 reject;该 rejection 不能证明 target 是否已经开始执行。若所选 owner 无法再证明其范围为空,`waitForExit()` 会 reject,清理仍会尝试终止。越过保留尾部的读取是 `lossy` 的,并在 spill 文件存在时指向它。fallback 进程组或已观察终端 session 可能遗漏在观察前逃逸的后代——见下文限制。 +无法解析的可执行文件会明确报出稳定错误。当 spawn 或提供方故障使 direct outcome 无法产生时,`done` 会 reject;该 rejection 不能证明 target 是否已经开始执行:平台 spawn 错误保持为原始 Node 错误,而 Windows Job runner 启动后失败或其 IPC 通道损坏时以 `SubprocessError` 的 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED` reject。在无法加载 node-pty 的主机上请求终端会抛出 `SUBPROCESS_PTY_UNAVAILABLE`。若所选 owner 无法再证明其范围为空,`waitForExit()` 会 reject,清理仍会尝试终止。越过保留尾部的读取是 `lossy` 的,并在 spill 文件存在时指向它。fallback 进程组或已观察终端 session 可能遗漏在观察前逃逸的后代——见下文限制。 ----- diff --git a/packages/subprocess/subprocess-local/src/index.ts b/packages/subprocess/subprocess-local/src/index.ts index be24927093..e9960d0f0b 100644 --- a/packages/subprocess/subprocess-local/src/index.ts +++ b/packages/subprocess/subprocess-local/src/index.ts @@ -17,7 +17,7 @@ import { Context } from '@deepseek-ai/cordis' import type * as NodePty from 'node-pty' import type { IPtyForkOptions, IWindowsPtyForkOptions } from 'node-pty' import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require' -import { SubprocessRuntime, SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess' +import { SubprocessRuntime, SubprocessError, SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess' import type { SubprocessHandle, SubprocessSpawnSpec, @@ -54,6 +54,19 @@ import { prepareShellActivity } from './shell-activity.ts' const requireNodePty = createLazyRequire('node-pty', import.meta.url) +/** Load node-pty, reporting a missing or unloadable native module as `SUBPROCESS_PTY_UNAVAILABLE`. */ +function loadNodePty(): typeof NodePty { + try { + return requireNodePty() + } catch (error) { + throw new SubprocessError( + `subprocess-local: terminals are unavailable because node-pty cannot be loaded: ${String(error)}`, + 'SUBPROCESS_PTY_UNAVAILABLE', + { cause: error }, + ) + } +} + /** * Local subprocess service: platform-selected managed ranges, Node-shaped stdio * dispositions (raw pipes, inherit, bounded tail-keep collection with spill @@ -290,7 +303,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime { async spawnTerminal(spec: SubprocessTerminalSpawnSpec): Promise { const file = spec.argv[0] if (file === undefined || file.length === 0) { - throw new Error('subprocess-local: terminal argv must contain a program') + throw new SubprocessError('subprocess-local: terminal argv must contain a program', 'SUBPROCESS_INVALID_ARGV') } spec.signal?.throwIfAborted() const inspector = this.terminalInspector ?? createProcessInspector() @@ -319,7 +332,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime { ? undefined : prepareLinuxTerminalScope(launch, { ...activity?.env ?? env, PWD: spec.cwd, TERM: spec.terminalType }, linuxScope.literalArgv) if (scope !== undefined) { options.cwd = scope.cwd; options.env = scope.env } - terminal = requireNodePty().spawn( + terminal = loadNodePty().spawn( scope?.command ?? file, scope?.args ?? [...launch.argv.slice(1)], options, diff --git a/packages/subprocess/subprocess-local/src/spawn.ts b/packages/subprocess/subprocess-local/src/spawn.ts index 8da083e6f5..e3a47ee818 100644 --- a/packages/subprocess/subprocess-local/src/spawn.ts +++ b/packages/subprocess/subprocess-local/src/spawn.ts @@ -11,7 +11,7 @@ import { type ChildProcess, type SpawnOptions, spawn, spawnSync } from 'node:child_process' import type { Readable } from 'node:stream' import { setTimeout as sleepMs } from 'node:timers/promises' -import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' +import { scrubbedParentEnv, SubprocessError } from '@deepseek-ai/dsh-subprocess' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { SubprocessCollect, @@ -172,11 +172,14 @@ export function validateSubprocessSpec(spec: SubprocessSpawnSpec): void { } catch { // Arbitrary caller-owned reasons cannot escape the stable Error boundary. } - throw new Error(`aborted before spawn: ${reason}`) + // Named as a cancellation so the tool registry classifies it as the caller's abort. + const error = new Error(`aborted before spawn: ${reason}`) + error.name = 'AbortError' + throw error } const [program] = spec.argv if (program === undefined || program.length === 0) { - throw new Error('invalid argv: expected a non-empty program name at argv[0]') + throw new SubprocessError('invalid argv: expected a non-empty program name at argv[0]', 'SUBPROCESS_INVALID_ARGV') } } diff --git a/packages/subprocess/subprocess-local/src/windows-job.ts b/packages/subprocess/subprocess-local/src/windows-job.ts index 57f7c46afc..34bfff74d5 100644 --- a/packages/subprocess/subprocess-local/src/windows-job.ts +++ b/packages/subprocess/subprocess-local/src/windows-job.ts @@ -5,6 +5,7 @@ import { spawn } from 'node:child_process' import { closeSync, openSync } from 'node:fs' import { devNull } from 'node:os' import type { Readable, Writable } from 'node:stream' +import { SubprocessError } from '@deepseek-ai/dsh-subprocess' import type { SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' import { loadWin32ProcessBindings, @@ -26,6 +27,16 @@ import { } from './runner-launch.ts' import type { RunnerInvocation } from './runner-launch.ts' +/** Classify a failure on the private runner channel, keeping an already coded failure. */ +function runnerIpcFailure(error: unknown): SubprocessError { + if (error instanceof SubprocessError) return error + return new SubprocessError( + `subprocess-local: Windows runner IPC failed: ${String(error)}`, + 'SUBPROCESS_RUNNER_IPC_FAILED', + { cause: error }, + ) +} + /** Test seams for runner launch and dynamic capability checks. */ export interface WindowsJobInternals { spawn?: typeof spawn @@ -171,8 +182,9 @@ export function launchWindowsJob( const status = signal !== null ? `signal ${signal}` : exitCode === null ? 'without an exit status' : `exit code ${String(exitCode)}` - failInfrastructure(new Error( + failInfrastructure(new SubprocessError( `subprocess-local: Windows Job runner exited with ${status} before proving its managed range empty`, + 'SUBPROCESS_RUNNER_FAILED', )) } @@ -184,7 +196,7 @@ export function launchWindowsJob( ) child.on('message', (value: unknown) => { if (directResultType !== undefined) { - const error = new Error('subprocess-local: Windows runner emitted more than one direct result') + const error = new SubprocessError('subprocess-local: Windows runner emitted more than one direct result', 'SUBPROCESS_RUNNER_IPC_FAILED') failInfrastructure(error) owner.terminateForHostExit() return @@ -193,7 +205,11 @@ export function launchWindowsJob( try { result = parseWindowsRunnerResult(value) } catch (error) { - failInfrastructure(error) + failInfrastructure(new SubprocessError( + `subprocess-local: Windows runner emitted a malformed result: ${String(error)}`, + 'SUBPROCESS_RUNNER_IPC_FAILED', + { cause: error }, + )) owner.terminateForHostExit() return } @@ -208,14 +224,16 @@ export function launchWindowsJob( child.once('spawn', () => { runnerSpawned = true try { - if (child.send === undefined) throw new Error('subprocess-local: Windows runner has no IPC channel') + if (child.send === undefined) { + throw new SubprocessError('subprocess-local: Windows runner has no IPC channel', 'SUBPROCESS_RUNNER_IPC_FAILED') + } child.send({ type: 'start', cwd: spec.cwd, env: targetEnv, ...spec.stdio.control === undefined ? {} : { control: spec.stdio.control } }, (error) => { if (error === null) return - failInfrastructure(error) + failInfrastructure(runnerIpcFailure(error)) owner.terminateForHostExit() }) } catch (error) { - failInfrastructure(error) + failInfrastructure(runnerIpcFailure(error)) owner.terminateForHostExit() } }) @@ -225,7 +243,11 @@ export function launchWindowsJob( rangeExit.resolve() return } - failInfrastructure(error) + failInfrastructure(new SubprocessError( + `subprocess-local: Windows Job runner failed after it started: ${String(error)}`, + 'SUBPROCESS_RUNNER_FAILED', + { cause: error }, + )) }) child.once('exit', (exitCode, signal) => { runnerExit = { exitCode, signal } diff --git a/packages/subprocess/subprocess-local/tests/local.spec.ts b/packages/subprocess/subprocess-local/tests/local.spec.ts index 2c4c0b2f67..3229c0837f 100644 --- a/packages/subprocess/subprocess-local/tests/local.spec.ts +++ b/packages/subprocess/subprocess-local/tests/local.spec.ts @@ -490,6 +490,36 @@ describe('LocalSubprocessRuntime', () => { } }) + it('reports an unloadable node-pty as SUBPROCESS_PTY_UNAVAILABLE', async () => { + const loadFailure = new Error('Cannot find module node-pty') + vi.resetModules() + mockWin32ForIsolatedRuntime() + vi.doMock('@deepseek-ai/dsh-lazy-require', () => ({ + createLazyRequire: () => () => { throw loadFailure }, + })) + vi.doMock('../src/linux-scope.ts', async importOriginal => ({ + ...await importOriginal(), + probeLinuxNative: () => undefined, + })) + try { + const { default: IsolatedLocalSubprocessRuntime } = await import('../src/index.ts') + const ctx = new Context() + const fiber = await ctx.plugin(IsolatedLocalSubprocessRuntime) + await expect(ctx.subprocess.spawnTerminal({ + argv: ['shell'], cwd: process.cwd(), rows: 24, cols: 80, terminalType: 'dumb', graceMs: 1, + })).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_PTY_UNAVAILABLE', cause: loadFailure }) + await expect(ctx.subprocess.spawnTerminal({ + argv: [''], cwd: process.cwd(), rows: 24, cols: 80, terminalType: 'dumb', graceMs: 1, + })).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_INVALID_ARGV' }) + await fiber.dispose() + } finally { + unmockLazyRequireForIsolatedRuntime() + vi.doUnmock('../src/linux-scope.ts') + unmockWin32ForIsolatedRuntime() + vi.resetModules() + } + }) + it('allocates Windows terminals through the console host node-pty ships', async () => { const exitListeners: ((event: { exitCode: number; signal?: number }) => void)[] = [] const terminal = { diff --git a/packages/subprocess/subprocess-local/tests/spawn.spec.ts b/packages/subprocess/subprocess-local/tests/spawn.spec.ts index 27e5ab93ac..1ba8c38dc5 100644 --- a/packages/subprocess/subprocess-local/tests/spawn.spec.ts +++ b/packages/subprocess/subprocess-local/tests/spawn.spec.ts @@ -352,7 +352,7 @@ describe('spawnSubprocess', () => { expect(result.signal).toBe(process.platform === 'win32' ? null : 'SIGTERM') }) - it('throws a stable Error when already aborted before spawn', () => { + it('throws a stable AbortError when already aborted before spawn', () => { for (const [reason, message] of [ ['too late', 'aborted before spawn: too late'], [null, 'aborted before spawn: aborted'], @@ -360,7 +360,7 @@ describe('spawnSubprocess', () => { const controller = new AbortController() controller.abort(reason) expect(() => { validateSubprocessSpec(spec('echo hi', { signal: controller.signal })) }) - .toThrow(new Error(message)) + .toThrow(expect.objectContaining({ name: 'AbortError', message })) } const controller = new AbortController() @@ -370,7 +370,7 @@ describe('spawnSubprocess', () => { }, }) expect(() => { validateSubprocessSpec(spec('echo hi', { signal: controller.signal })) }) - .toThrow(new Error('aborted before spawn: aborted')) + .toThrow(expect.objectContaining({ name: 'AbortError', message: 'aborted before spawn: aborted' })) }) it('rejects with a spawn error for a nonexistent cwd', async () => { @@ -1446,7 +1446,8 @@ describe('coverage seams 2', () => { describe('argv validation', () => { it('rejects an empty argv before spawning', () => { - expect(() => { validateSubprocessSpec({ ...spec('true'), argv: [] }) }).toThrow(/non-empty program name/) + expect(() => { validateSubprocessSpec({ ...spec('true'), argv: [] }) }) + .toThrow(expect.objectContaining({ name: 'SubprocessError', code: 'SUBPROCESS_INVALID_ARGV' })) }) it('rejects an empty program name before spawning', () => { @@ -1468,7 +1469,7 @@ describe('abort edge cases', () => { removeEventListener() {}, } as unknown as AbortSignal expect(() => { validateSubprocessSpec(spec('echo hi', { signal: bare })) }) - .toThrow(new Error('aborted before spawn: aborted')) + .toThrow(expect.objectContaining({ name: 'AbortError', message: 'aborted before spawn: aborted' })) }) it.skipIf(process.platform === 'win32')('reports the terminating signal of an externally self-killed command', async () => { diff --git a/packages/subprocess/subprocess-local/tests/windows-job.spec.ts b/packages/subprocess/subprocess-local/tests/windows-job.spec.ts index c2f30a682b..869f7b89b0 100644 --- a/packages/subprocess/subprocess-local/tests/windows-job.spec.ts +++ b/packages/subprocess/subprocess-local/tests/windows-job.spec.ts @@ -350,6 +350,7 @@ describe('Windows parent runner contract', () => { statusless.child.connected = false statusless.child.exit( null, null) await expect(statusless.result.direct).rejects.toThrow('without an exit status') + await expect(statusless.result.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED' }) }) it('fails closed on malformed/duplicate result, runner spawn error, and start-send error', async () => { @@ -357,6 +358,7 @@ describe('Windows parent runner contract', () => { malformed.child.emit('message', { type: 'target-exit', exitCode: -1 }) expect(malformed.child.killed).toEqual(['SIGKILL']) await expect(malformed.result.direct).rejects.toThrow('invalid target-exit') + await expect(malformed.result.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' }) await expect(malformed.result.owner.waitForExit()).rejects.toThrow('invalid target-exit') const duplicate = launch() @@ -364,6 +366,7 @@ describe('Windows parent runner contract', () => { duplicate.child.emit('message', { type: 'target-exit', exitCode: 0 }) await expect(duplicate.result.direct).resolves.toEqual({ exitCode: 0, signal: null }) await expect(duplicate.result.owner.waitForExit()).rejects.toThrow('more than one direct result') + await expect(duplicate.result.owner.waitForExit()).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' }) const errored = launch(new FakeChild(), spec, false) const spawnError = new Error('runner executable missing') @@ -375,8 +378,9 @@ describe('Windows parent runner contract', () => { const postSpawnError = launch() const infrastructureError = new Error('runner failed after spawn') postSpawnError.child.emit('error', infrastructureError) - await expect(postSpawnError.result.direct).rejects.toBe(infrastructureError) - await expect(postSpawnError.result.owner.waitForExit()).rejects.toBe(infrastructureError) + const runnerFailure = { name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED', cause: infrastructureError } + await expect(postSpawnError.result.direct).rejects.toMatchObject(runnerFailure) + await expect(postSpawnError.result.owner.waitForExit()).rejects.toMatchObject(runnerFailure) const sendFailedChild = new FakeChild() sendFailedChild.sendError = new Error('IPC send failed') @@ -389,14 +393,16 @@ describe('Windows parent runner contract', () => { Object.defineProperty(noIpc, 'send', { value: undefined }) const noIpcResult = launch(noIpc).result await expect(noIpcResult.direct).rejects.toThrow('has no IPC channel') + await expect(noIpcResult.direct).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED' }) await expect(noIpcResult.owner.waitForExit()).rejects.toThrow('has no IPC channel') const nonError = new FakeChild() nonError.throwOnSendCall = 1 nonError.sendThrown = 'start send failed' const nonErrorResult = launch(nonError).result - await expect(nonErrorResult.direct).rejects.toBe('start send failed') - await expect(nonErrorResult.owner.waitForExit()).rejects.toBe('start send failed') + const ipcFailure = { name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_IPC_FAILED', cause: 'start send failed' } + await expect(nonErrorResult.direct).rejects.toMatchObject(ipcFailure) + await expect(nonErrorResult.owner.waitForExit()).rejects.toMatchObject(ipcFailure) }) it('fails infrastructure and kills the runner when termination delivery fails', async () => { diff --git a/packages/subprocess/subprocess/README.i18n.yaml b/packages/subprocess/subprocess/README.i18n.yaml index f76390eb90..762893c5a0 100644 --- a/packages/subprocess/subprocess/README.i18n.yaml +++ b/packages/subprocess/subprocess/README.i18n.yaml @@ -39,8 +39,8 @@ en: 4d4cbb311575d071 zh: 7be2d265adb661bc /deepseek-ai-dsh-subprocess/use-this-package/what-can-go-wrong: - en: 51f2f43087a1ed18 - zh: 6d2ebb099b707df3 + en: 718494d6530da700 + zh: a41b7d48a9d12178 /deepseek-ai-dsh-subprocess/understand-the-implementation: en: 25cd344c959cfd9e zh: 045880776ab82d1e @@ -48,8 +48,8 @@ en: 07201ec2256c25f6 zh: 046109cfa92194f3 /deepseek-ai-dsh-subprocess/understand-the-implementation/source-map: - en: 85e3d2109f49356d - zh: 071ccfef37e8e33f + en: e56d6825d1b990a5 + zh: c70cabda3bfcd2ab /deepseek-ai-dsh-subprocess/understand-the-implementation/data-model-and-flow: en: 9998dc0a990fbcf1 zh: ba179617f60cb9bc diff --git a/packages/subprocess/subprocess/README.md b/packages/subprocess/subprocess/README.md index 4839a508e5..337afd9fba 100644 --- a/packages/subprocess/subprocess/README.md +++ b/packages/subprocess/subprocess/README.md @@ -81,7 +81,7 @@ Children never inherit the harness's ambient secrets: credential-shaped names an ### What can go wrong -An executable that cannot be resolved fails loudly with a stable error. A spawn that never starts rejects `done`; there is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced. +Coded failures are `SubprocessError` instances whose `code` is one of `SUBPROCESS_ERROR_CODES`: an empty argv is `SUBPROCESS_INVALID_ARGV`, an executable lookup miss is `SubprocessExecutableNotFoundError` (`SUBPROCESS_EXECUTABLE_NOT_FOUND`), a provider's private runner that fails or breaks its channel is `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`, and an unloadable terminal implementation is `SUBPROCESS_PTY_UNAVAILABLE`. A spawn requested on an already aborted signal throws an error named `AbortError`. A spawn that never starts rejects `done` with the platform's original error, so consumers can inspect its errno fields; a consumer that reports the rejection as its own failure converts it with `subprocessSpawnFailure()`, which yields `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` otherwise. There is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced. ----- @@ -103,6 +103,7 @@ The seam is built on one separation: the service owns process coordinates and li |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: abstract `SubprocessRuntime`, `ctx.subprocess` registration, the shared `scrubbedParentEnv` scrub | | [`src/types.ts`](src/types.ts) | Vocabulary: spawn spec, stdio modes, handles, readers, outcomes, `DSH_*` namespace | +| [`src/error.ts`](src/error.ts) | `SubprocessError`, its closed code list, and spawn-rejection classification | ### Data model and flow diff --git a/packages/subprocess/subprocess/README.zh.md b/packages/subprocess/subprocess/README.zh.md index 843dcdb568..da111f517a 100644 --- a/packages/subprocess/subprocess/README.zh.md +++ b/packages/subprocess/subprocess/README.zh.md @@ -81,7 +81,7 @@ const output = handle.collected.stdout?.readFrom(0) ### 可能出错的地方 -无法解析可执行文件时,服务会明确报出稳定的错误。从未启动成功的 spawn 会让 `done` reject;从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。 +带 code 的失败都是 `SubprocessError`,其 `code` 属于 `SUBPROCESS_ERROR_CODES`:argv 为空是 `SUBPROCESS_INVALID_ARGV`,可执行文件查找未命中是 `SubprocessExecutableNotFoundError`(`SUBPROCESS_EXECUTABLE_NOT_FOUND`),提供方私有 runner 失败或通道损坏是 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED`,终端实现无法加载是 `SUBPROCESS_PTY_UNAVAILABLE`。在已 abort 的 signal 上请求 spawn 会抛出名为 `AbortError` 的错误。从未启动成功的 spawn 会让 `done` 以平台原始错误 reject,便于消费者检查 errno 字段;把该 reject 报告为自身失败的消费者用 `subprocessSpawnFailure()` 转换,`ENOENT` 得到 `SUBPROCESS_SPAWN_NOT_FOUND`,其余得到 `SUBPROCESS_SPAWN_FAILED`。从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。 ----- @@ -103,6 +103,7 @@ const output = handle.collected.stdout?.readFrom(0) |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:抽象 `SubprocessRuntime`、`ctx.subprocess` 注册、共享的 `scrubbedParentEnv` 清除 | | [`src/types.ts`](src/types.ts) | 词汇:spawn spec、stdio 模式、句柄、读取器、结果、`DSH_*` 命名空间 | +| [`src/error.ts`](src/error.ts) | `SubprocessError`、其封闭 code 列表与 spawn reject 分类 | ### 数据模型与流程 diff --git a/packages/subprocess/subprocess/package.json b/packages/subprocess/subprocess/package.json index 9fb7353455..4d4968fbfb 100644 --- a/packages/subprocess/subprocess/package.json +++ b/packages/subprocess/subprocess/package.json @@ -36,11 +36,13 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-http-proxy": "workspace:*" + "@deepseek-ai/dsh-http-proxy": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-http-proxy": "workspace:*", - "@deepseek-ai/dsh-launch-environment": "workspace:*" + "@deepseek-ai/dsh-launch-environment": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" } } diff --git a/packages/subprocess/subprocess/src/error.ts b/packages/subprocess/subprocess/src/error.ts new file mode 100644 index 0000000000..064dc494ae --- /dev/null +++ b/packages/subprocess/subprocess/src/error.ts @@ -0,0 +1,87 @@ +/** Machine-routable subprocess failures shared by every `ctx.subprocess` provider and its consumers. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link SubprocessError} code: + * - `SUBPROCESS_INVALID_ARGV` — the request names no program; the caller fixes its argv. + * - `SUBPROCESS_EXECUTABLE_NOT_FOUND` — executable lookup found no executable file. + * - `SUBPROCESS_SPAWN_NOT_FOUND` — the platform reported `ENOENT` for the program or the working directory. + * - `SUBPROCESS_SPAWN_FAILED` — the platform refused the spawn for another reason; `cause` holds the original error. + * - `SUBPROCESS_RUNNER_FAILED` — the provider's private runner exited or reported a result before proving the process range empty. + * - `SUBPROCESS_RUNNER_IPC_FAILED` — the provider's private runner channel was missing or carried a malformed message. + * - `SUBPROCESS_PTY_UNAVAILABLE` — the host cannot load its terminal implementation. + */ +export const SUBPROCESS_ERROR_CODES = [ + 'SUBPROCESS_INVALID_ARGV', + 'SUBPROCESS_EXECUTABLE_NOT_FOUND', + 'SUBPROCESS_SPAWN_NOT_FOUND', + 'SUBPROCESS_SPAWN_FAILED', + 'SUBPROCESS_RUNNER_FAILED', + 'SUBPROCESS_RUNNER_IPC_FAILED', + 'SUBPROCESS_PTY_UNAVAILABLE', +] as const + +/** One code from {@link SUBPROCESS_ERROR_CODES}. */ +export type SubprocessErrorCode = typeof SUBPROCESS_ERROR_CODES[number] + +/** Subprocess failure carrying a stable {@link SubprocessErrorCode}. */ +export class SubprocessError extends HarnessError { + override readonly code: SubprocessErrorCode + + /** + * @param message - names the process operation and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining; foreign errno and Win32 codes stay there and in `message`. + */ + constructor(message: string, code: SubprocessErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'SubprocessError' + this.code = code + } +} + +/** Executable lookup completed without finding an executable file; `code` is `SUBPROCESS_EXECUTABLE_NOT_FOUND`. */ +export class SubprocessExecutableNotFoundError extends SubprocessError { + /** + * @param message - provider-specific lookup diagnostic. + * @param options - original provider failure, when available. + */ + constructor(message: string, options?: ErrorOptions) { + super(message, 'SUBPROCESS_EXECUTABLE_NOT_FOUND', options) + this.name = 'SubprocessExecutableNotFoundError' + } +} + +/** + * Classify a spawn rejection for a consumer that reports it as its own + * failure. Providers reject with the platform's original error so that + * consumers can inspect errno fields; the consumer that turns the rejection + * into a tool or service failure converts it here and keeps the original as + * `cause`. + * @param error - the provider's rejection value. + * @param program - the program the consumer asked to spawn, named in the message. + * @returns `error` unchanged when it is a `HarnessError` or a cancellation + * (`name === 'AbortError'`); otherwise a {@link SubprocessError} with + * `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` for + * any other value. + */ +export function subprocessSpawnFailure(error: unknown, program: string): unknown { + if (error instanceof HarnessError) return error + if (error instanceof Error && error.name === 'AbortError') return error + const errno = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined + let detail = 'unprintable failure' + try { + detail = error instanceof Error ? error.message : String(error) + } catch { + // A provider-owned rejection whose conversion throws still yields a coded failure. + } + if (errno === 'ENOENT') { + return new SubprocessError( + `cannot start ${JSON.stringify(program)}: the program or the working directory does not exist (${detail})`, + 'SUBPROCESS_SPAWN_NOT_FOUND', + { cause: error }, + ) + } + return new SubprocessError(`cannot start ${JSON.stringify(program)}: ${detail}`, 'SUBPROCESS_SPAWN_FAILED', { cause: error }) +} diff --git a/packages/subprocess/subprocess/src/index.ts b/packages/subprocess/subprocess/src/index.ts index 6dbbc62719..b134ffb6c1 100644 --- a/packages/subprocess/subprocess/src/index.ts +++ b/packages/subprocess/subprocess/src/index.ts @@ -15,6 +15,13 @@ import type { SubprocessHandle, SubprocessSpawnSpec } from './types.ts' import type { SubprocessTerminalEnvironment, SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from './types.ts' export { DSH_ENV_PREFIX } from './types.ts' +export { + SUBPROCESS_ERROR_CODES, + SubprocessError, + SubprocessExecutableNotFoundError, + subprocessSpawnFailure, + type SubprocessErrorCode, +} from './error.ts' export type { CollectedOutput, DshEnvironment, @@ -163,15 +170,3 @@ export abstract class SubprocessRuntime extends Service { } export default SubprocessRuntime - -/** Executable lookup completed without finding an executable file. */ -export class SubprocessExecutableNotFoundError extends Error { - /** - * @param message - provider-specific lookup diagnostic. - * @param options - original provider failure, when available. - */ - constructor(message: string, options?: ErrorOptions) { - super(message, options) - this.name = 'SubprocessExecutableNotFoundError' - } -} diff --git a/packages/subprocess/subprocess/tests/error.spec.ts b/packages/subprocess/subprocess/tests/error.spec.ts new file mode 100644 index 0000000000..ecdcb89a98 --- /dev/null +++ b/packages/subprocess/subprocess/tests/error.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { + SUBPROCESS_ERROR_CODES, + SubprocessError, + SubprocessExecutableNotFoundError, + subprocessSpawnFailure, +} from '../src/index.ts' + +describe('SubprocessError', () => { + it('carries a literal name and a code from the closed list', () => { + const cause = new Error('low level') + const error = new SubprocessError('runner failed', 'SUBPROCESS_RUNNER_FAILED', { cause }) + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_RUNNER_FAILED', cause }) + expect(SUBPROCESS_ERROR_CODES).toContain(error.code) + }) + + it('keeps the executable lookup miss as its own subclass', () => { + const error = new SubprocessExecutableNotFoundError('not on PATH') + expect(error).toBeInstanceOf(SubprocessError) + expect(error).toMatchObject({ name: 'SubprocessExecutableNotFoundError', code: 'SUBPROCESS_EXECUTABLE_NOT_FOUND' }) + }) +}) + +describe('subprocessSpawnFailure', () => { + it('classifies ENOENT and other spawn rejections, keeping the original as cause', () => { + const missing = Object.assign(new Error('spawn pwsh ENOENT'), { code: 'ENOENT', syscall: 'spawn pwsh' }) + expect(subprocessSpawnFailure(missing, 'pwsh')).toMatchObject({ + name: 'SubprocessError', + code: 'SUBPROCESS_SPAWN_NOT_FOUND', + cause: missing, + message: 'cannot start "pwsh": the program or the working directory does not exist (spawn pwsh ENOENT)', + }) + const denied = Object.assign(new Error('spawn bash EACCES'), { code: 'EACCES' }) + expect(subprocessSpawnFailure(denied, 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', cause: denied }) + expect(subprocessSpawnFailure('raw', 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', message: 'cannot start "bash": raw' }) + const unprintable = { [Symbol.toPrimitive]() { throw new Error('no') } } + expect(subprocessSpawnFailure(unprintable, 'bash')).toMatchObject({ message: 'cannot start "bash": unprintable failure' }) + }) + + it('returns coded errors and cancellations unchanged', () => { + const coded = new HarnessError('sandbox unavailable', 'SANDBOX_UNAVAILABLE') + expect(subprocessSpawnFailure(coded, 'bash')).toBe(coded) + const abort = new DOMException('aborted', 'AbortError') + expect(subprocessSpawnFailure(abort, 'bash')).toBe(abort) + }) +}) diff --git a/packages/subprocess/subprocess/tsconfig.json b/packages/subprocess/subprocess/tsconfig.json index e72e6a3dd7..a39b295358 100644 --- a/packages/subprocess/subprocess/tsconfig.json +++ b/packages/subprocess/subprocess/tsconfig.json @@ -19,6 +19,9 @@ }, { "path": "../../util/launch-environment" + }, + { + "path": "../../llm/llm" } ] } diff --git a/packages/subprocess/win32-process/README.i18n.yaml b/packages/subprocess/win32-process/README.i18n.yaml index 6cfa81bc6d..8c9fb0557c 100644 --- a/packages/subprocess/win32-process/README.i18n.yaml +++ b/packages/subprocess/win32-process/README.i18n.yaml @@ -15,8 +15,8 @@ en: a3450c8cdd5f5802 zh: 15eec66f42e42ce7 /deepseek-ai-dsh-win32-process/behavior: - en: 77806095cd7f781d - zh: 69d09cabc4d49185 + en: 9b81bbd4b1a16ddc + zh: b07fc32b41c3cc66 /deepseek-ai-dsh-win32-process/header-verification: en: 2b60a9001b480546 zh: 12a621e421c7d789 diff --git a/packages/subprocess/win32-process/README.md b/packages/subprocess/win32-process/README.md index af7cc79503..23ce6f94dd 100644 --- a/packages/subprocess/win32-process/README.md +++ b/packages/subprocess/win32-process/README.md @@ -24,7 +24,7 @@ This low-level Win32 process library is consumed by the Windows ACL sandbox and ## Behavior -- **One reusable ABI owner** — `abi.ts` owns the Win32 constants and x64 layout values consumed by both process paths. `ffi.ts` lazily loads `kernel32.dll` and `advapi32.dll`, verifies `STARTUPINFOW` and `PROCESS_INFORMATION`, exposes typed operations and error formatting, and lets sandbox policy bind its remaining APIs through the same loaded libraries. +- **One reusable ABI owner** — `abi.ts` owns the Win32 constants and x64 layout values consumed by both process paths. `ffi.ts` lazily loads `kernel32.dll` and `advapi32.dll`, verifies `STARTUPINFOW` and `PROCESS_INFORMATION`, exposes typed operations and error formatting, and lets sandbox policy bind its remaining APIs through the same loaded libraries. A failed checked call throws `Win32Error`, a `HarnessError` with code `WIN32_ERROR` whose `api` and `win32Code` fields name the call; callers that own the failing operation wrap it in their own coded error with the `Win32Error` as `cause`. - **Restricted-token creation** — `RestrictedProcessSpawnOptions` requires the sandbox's primary token and uses `CreateProcessAsUserW`. Piped and inherited-stdio paths share command-line quoting, cwd, the restricted-token null-environment policy, checked return values, and handle cleanup. - **Piped process primitive** — `spawnPipedProcess()` creates anonymous stdin/stdout/stderr pipes, closes stdin immediately, returns the two read ends, and leaves process waiting and pipe draining to the caller. Every partial failure closes the handles already owned by the operation, and every Koffi out-parameter or struct allocation is freed after its Win32 lifetime. - **Inherited-stdio Job primitive** — `spawnInheritedJobProcess()` creates one kill-on-close Job, temporarily marks the current stdio handles inheritable, creates the restricted child suspended, assigns it to the Job, and then resumes its initial thread. Target code cannot run before Job assignment; controlled assignment or resume failures terminate the suspended child or close the assigned Job before releasing every owned handle. diff --git a/packages/subprocess/win32-process/README.zh.md b/packages/subprocess/win32-process/README.zh.md index 7c5685b77a..c3df8aa576 100644 --- a/packages/subprocess/win32-process/README.zh.md +++ b/packages/subprocess/win32-process/README.zh.md @@ -24,7 +24,7 @@ kind: "package-library" ## 行为 -- **唯一可复用 ABI owner** — `abi.ts` 拥有两条 process 路径消费的 Win32 常量与 x64 布局值。`ffi.ts` 懒加载 `kernel32.dll` 与 `advapi32.dll`,核验 `STARTUPINFOW` 和 `PROCESS_INFORMATION`,提供带类型的操作与错误格式化,并让沙箱策略通过同一组已加载库绑定剩余 API。 +- **唯一可复用 ABI owner** — `abi.ts` 拥有两条 process 路径消费的 Win32 常量与 x64 布局值。`ffi.ts` 懒加载 `kernel32.dll` 与 `advapi32.dll`,核验 `STARTUPINFOW` 和 `PROCESS_INFORMATION`,提供带类型的操作与错误格式化,并让沙箱策略通过同一组已加载库绑定剩余 API。受检调用失败时抛出 `Win32Error`,它是 code 为 `WIN32_ERROR` 的 `HarnessError`,`api` 与 `win32Code` 字段标明失败的调用;拥有该操作的调用方再把它包装为自己的带 code 错误,并以 `Win32Error` 作为 `cause`。 - **restricted-token 创建** — `RestrictedProcessSpawnOptions` 要求沙箱的 primary token,并使用 `CreateProcessAsUserW`。pipe 与 inherited-stdio 路径共用命令行引号处理、cwd、restricted-token null 环境策略、返回值检查与句柄清理。 - **管道进程原语** — `spawnPipedProcess()` 创建匿名 stdin/stdout/stderr 管道,立即关闭 stdin,并返回两个读取端;调用方负责等待进程与排空管道。任一局部失败都会关闭该操作已经拥有的句柄,并在各自 Win32 生命周期结束后释放每个 Koffi 输出槽与结构体分配。 - **继承 stdio 的 Job 原语** — `spawnInheritedJobProcess()` 创建一个 kill-on-close Job,临时把当前 stdio 句柄设为可继承,以 suspended 状态创建 restricted child,把它分配给 Job,再恢复初始线程。目标代码不会在 Job 分配前运行;受控的分配或恢复失败会终止 suspended child,或在释放全部已拥有句柄前关闭已分配的 Job。 diff --git a/packages/subprocess/win32-process/package.json b/packages/subprocess/win32-process/package.json index 7f3d76d56f..7eae3438fc 100644 --- a/packages/subprocess/win32-process/package.json +++ b/packages/subprocess/win32-process/package.json @@ -30,13 +30,15 @@ ], "license": "MIT", "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-lazy-require": "workspace:*", "koffi": "3.1.1" }, "devDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-llm": "workspace:*" } } diff --git a/packages/subprocess/win32-process/src/errors.ts b/packages/subprocess/win32-process/src/errors.ts index f6e90805a1..d8cd4caa86 100644 --- a/packages/subprocess/win32-process/src/errors.ts +++ b/packages/subprocess/win32-process/src/errors.ts @@ -1,12 +1,22 @@ +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */ +export const WIN32_ERROR = 'WIN32_ERROR' + /** Win32 call failure with the exact API name and error code. */ -export class Win32Error extends Error { +export class Win32Error extends HarnessError { /** Win32 function whose checked result failed. */ readonly api: string /** Exact GetLastError value or direct Win32 API error code. */ readonly win32Code: number + /** + * @param api - Win32 function whose checked result failed. + * @param win32Code - exact GetLastError value or direct API error code. + * @param detail - optional subject, such as the path the call targeted. + */ constructor(api: string, win32Code: number, detail?: string) { - super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`) + super(`${api} failed (Win32 ${win32Code})${detail === undefined ? '' : `: ${detail}`}`, WIN32_ERROR) this.name = 'Win32Error' this.api = api this.win32Code = win32Code diff --git a/packages/subprocess/win32-process/tests/ffi.spec.ts b/packages/subprocess/win32-process/tests/ffi.spec.ts index efb4db205a..a202503369 100644 --- a/packages/subprocess/win32-process/tests/ffi.spec.ts +++ b/packages/subprocess/win32-process/tests/ffi.spec.ts @@ -1,6 +1,8 @@ import koffi from 'koffi' import { describe, expect, it, vi } from 'vitest' +import { HarnessError } from '@deepseek-ai/dsh-llm' import { + WIN32_ERROR, Win32Error, allocPtrSlot, decodePtr, @@ -35,6 +37,9 @@ describe('shared Win32 process ABI', () => { expect(errorText(api, 5)).toBe('access denied') expect(() => throwLastError(api, 'Probe')).toThrow(Win32Error) expect(new Win32Error('CloseHandle', 6).message).toBe('CloseHandle failed (Win32 6)') + const error = new Win32Error('CloseHandle', 6) + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ name: 'Win32Error', code: WIN32_ERROR, api: 'CloseHandle', win32Code: 6 }) }) it('decodes a pointer stored by Koffi', () => { diff --git a/packages/subprocess/win32-process/tsconfig.json b/packages/subprocess/win32-process/tsconfig.json index 93abec7c46..ac86e810e8 100644 --- a/packages/subprocess/win32-process/tsconfig.json +++ b/packages/subprocess/win32-process/tsconfig.json @@ -11,6 +11,9 @@ }, { "path": "../../util/lazy-require" + }, + { + "path": "../../llm/llm" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..1884575900 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16984,6 +16984,9 @@ importers: '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm packages/subprocess/subprocess-local: dependencies: @@ -17025,6 +17028,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm packages/team/agent-team: dependencies: From ac96c518fb2de7f4700db38531533f1815147164 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:31:24 +0800 Subject: [PATCH 042/438] 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 9626ccfae8c1d0ac626427d86823a42b48ad3381 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:51:19 +0800 Subject: [PATCH 043/438] feat(sandbox): code escalation outcomes and Windows ACL preparation failures The sandbox Service Definition adds SandboxEscalationError with SANDBOX_ESCALATION_INVALID_ARGUMENT, _UNAVAILABLE, _REJECTED, and _CANCELLED, thrown by validateEscalationArgs() and approveEscalation() with their existing messages. A cancelled approval for an aborted call rethrows the call's cancellation instead. It also adds SandboxPreparationError. sandbox-local wraps Windows ACL SID, grant, temp-directory, and path-resolution failures as SANDBOX_PREPARATION_FAILED with the Win32Error or Node error (or an AggregateError with cleanup failures) as cause, and reports a temp root inside the workspace as SANDBOX_INVALID_TEMP_ROOT. sandbox-windows-acl exports isTempRootInsideWorkspace() for that check. Refs #7869 --- docs/subsystems/sandbox.i18n.yaml | 4 +- docs/subsystems/sandbox.md | 2 +- docs/subsystems/sandbox.zh.md | 2 +- .../sandbox/sandbox-local/README.i18n.yaml | 4 +- packages/sandbox/sandbox-local/README.md | 2 +- packages/sandbox/sandbox-local/README.zh.md | 2 +- packages/sandbox/sandbox-local/src/index.ts | 65 ++++++++++++--- .../sandbox-local/tests/acl-grants.spec.ts | 83 ++++++++++++++++--- .../sandbox/sandbox-windows-acl/src/index.ts | 2 +- .../sandbox-windows-acl/src/path-boundary.ts | 15 +++- packages/sandbox/sandbox/README.i18n.yaml | 8 +- packages/sandbox/sandbox/README.md | 4 +- packages/sandbox/sandbox/README.zh.md | 4 +- packages/sandbox/sandbox/src/escalation.ts | 77 ++++++++++++++--- packages/sandbox/sandbox/src/index.ts | 42 +++++++++- .../sandbox/sandbox/tests/escalation.spec.ts | 42 +++++++++- .../sandbox/sandbox/tests/vocabulary.spec.ts | 13 ++- 17 files changed, 317 insertions(+), 54 deletions(-) diff --git a/docs/subsystems/sandbox.i18n.yaml b/docs/subsystems/sandbox.i18n.yaml index 3d2954b1c4..6f92d1861f 100644 --- a/docs/subsystems/sandbox.i18n.yaml +++ b/docs/subsystems/sandbox.i18n.yaml @@ -15,5 +15,5 @@ en: 2ba8930762e92e40 zh: 220f64da1a9e5d57 /process-sandbox/provider-and-fail-closed-errors: - en: a90a38fe4b11737c - zh: 2397768e48712617 + en: a1f9649b3cde0aca + zh: 6708348a70eb2451 diff --git a/docs/subsystems/sandbox.md b/docs/subsystems/sandbox.md index c530276e90..e5c3021503 100644 --- a/docs/subsystems/sandbox.md +++ b/docs/subsystems/sandbox.md @@ -161,7 +161,7 @@ The [local provider](../../packages/sandbox/sandbox-local/README.md) owns operat ## Provider and fail-closed errors -`await ctx.sandbox.confine(argv, policy, signal)` resolves policy paths and returns a `ConfinedArgv` from the execution world, or rejects with `SandboxUnavailableError` and code `SANDBOX_UNAVAILABLE` when no usable backend exists. The optional signal cancels resolution before launch. Consumers may also classify a failure while spawning or observing the returned argv; that attribution belongs to the consumer contract. Silent unconfined passthrough is never legal for a confined policy. +`await ctx.sandbox.confine(argv, policy, signal)` resolves policy paths and returns a `ConfinedArgv` from the execution world, or rejects with `SandboxUnavailableError` and code `SANDBOX_UNAVAILABLE` when no usable backend exists, or with `SandboxPreparationError` (`SANDBOX_PREPARATION_FAILED`, `SANDBOX_INVALID_TEMP_ROOT`) when the provider cannot prepare host state for the mode. The optional signal cancels resolution before launch. Consumers may also classify a failure while spawning or observing the returned argv; that attribution belongs to the consumer contract. Silent unconfined passthrough is never legal for a confined policy. Provider selection, probing, caching, and backend-specific enforcement reports belong to the [local provider](../../packages/sandbox/sandbox-local/README.md). diff --git a/docs/subsystems/sandbox.zh.md b/docs/subsystems/sandbox.zh.md index c3cfd0720e..10093b09e2 100644 --- a/docs/subsystems/sandbox.zh.md +++ b/docs/subsystems/sandbox.zh.md @@ -161,7 +161,7 @@ interface ConfinedArgv { ## 提供方与 fail-closed 错误 -`await ctx.sandbox.confine(argv, policy, signal)` 在执行环境中解析策略路径并返回 `ConfinedArgv`,没有可用后端时以 `SandboxUnavailableError`(错误码 `SANDBOX_UNAVAILABLE`)拒绝。可选信号可在启动前取消解析。消费方也可以在 spawn 或观察所返回的 argv 时对失败进行分类;该归因属于消费方约定。对于受限策略,静默的无隔离透传永远不合法。 +`await ctx.sandbox.confine(argv, policy, signal)` 在执行环境中解析策略路径并返回 `ConfinedArgv`,没有可用后端时以 `SandboxUnavailableError`(错误码 `SANDBOX_UNAVAILABLE`)拒绝,提供方无法为该模式准备主机状态时以 `SandboxPreparationError`(`SANDBOX_PREPARATION_FAILED`、`SANDBOX_INVALID_TEMP_ROOT`)拒绝。可选信号可在启动前取消解析。消费方也可以在 spawn 或观察所返回的 argv 时对失败进行分类;该归因属于消费方约定。对于受限策略,静默的无隔离透传永远不合法。 提供方选择、探测、缓存和后端特定的强制执行报告归[本地提供方](../../packages/sandbox/sandbox-local/README.zh.md)所有。 diff --git a/packages/sandbox/sandbox-local/README.i18n.yaml b/packages/sandbox/sandbox-local/README.i18n.yaml index b660d61a20..84b8ff94c7 100644 --- a/packages/sandbox/sandbox-local/README.i18n.yaml +++ b/packages/sandbox/sandbox-local/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7282c9ec77fd6f01 zh: 10e385a9489105e3 /deepseek-ai-dsh-sandbox-local/use-this-package/failures-and-recovery: - en: b1f9aeca3baf9561 - zh: a5681f4f49259468 + en: 3859a87c6122a1bf + zh: 55d7be15527f0347 /deepseek-ai-dsh-sandbox-local/understand-the-implementation: en: 15db6ec303151ccc zh: 91f62c1f64192f92 diff --git a/packages/sandbox/sandbox-local/README.md b/packages/sandbox/sandbox-local/README.md index 578caa7c63..55d5b9cfe8 100644 --- a/packages/sandbox/sandbox-local/README.md +++ b/packages/sandbox/sandbox-local/README.md @@ -56,7 +56,7 @@ With the provider mounted, a command runs under the mode you resolve per call. E An unsupported platform or an unusable runner fails closed: `confine()` rejects with `SANDBOX_UNAVAILABLE` and names the runner options for the platform, and the consumer surfaces that error rather than running the command unconfined. A runner that starts but refuses its profile is identified by its fatal stderr signature and exit code, so a broken sandbox is not mistaken for a denied command. The `runnerCommand` override is an operator assertion: it skips functional probes and assumes the configured runner implements the bwrap-compatible profile honestly. -Seatbelt, bwrap, and Landlock include the policy's explicit `additionalWritableRoots` under `workspace-write`. Read-only ignores those grants. Missing paths, non-directories, symlinked directories, and other inspection failures raise `SANDBOX_INVALID_ROOT` before the command starts. The Windows ACL backend does not inspect these extra roots and keeps workspace and private-temp access only. +Seatbelt, bwrap, and Landlock include the policy's explicit `additionalWritableRoots` under `workspace-write`. Read-only ignores those grants. Missing paths, non-directories, symlinked directories, and other inspection failures raise `SANDBOX_INVALID_ROOT` before the command starts. The Windows ACL backend does not inspect these extra roots and keeps workspace and private-temp access only. Its per-session preparation rejects with `SandboxPreparationError` before the command starts: `SANDBOX_INVALID_TEMP_ROOT` when the host temp root lies inside the workspace, and `SANDBOX_PREPARATION_FAILED` when a SID, ACL grant, or private temp directory cannot be created, with the `Win32Error` or Node error as `cause` and partial grants rolled back. ----- diff --git a/packages/sandbox/sandbox-local/README.zh.md b/packages/sandbox/sandbox-local/README.zh.md index 7787decc5b..69103da191 100644 --- a/packages/sandbox/sandbox-local/README.zh.md +++ b/packages/sandbox/sandbox-local/README.zh.md @@ -56,7 +56,7 @@ kind: "package-reference" 不受支持的平台或不可用的 runner 会拒绝执行:`confine()` 以 `SANDBOX_UNAVAILABLE` 拒绝 并列出该平台的 runner 选项,消费方会呈现该错误,而不是让命令不受限制地运行。启动后拒绝自身 profile 的 runner 由其致命 stderr 签名与退出码识别,因此损坏的沙箱不会被误认为被拒绝的命令。`runnerCommand` 覆盖是操作方断言:它跳过功能探测,并假定配置的 runner 诚实实现与 bwrap 兼容的 profile。 -Seatbelt、bwrap 和 Landlock 在 `workspace-write` 下包含策略显式指定的 `additionalWritableRoots`。只读模式忽略这些授权。不存在的路径、非目录、符号链接目录和其他检查失败会在命令启动前触发 `SANDBOX_INVALID_ROOT`。Windows ACL 后端不检查这些额外根目录,仅保留工作区与私有临时目录访问权限。 +Seatbelt、bwrap 和 Landlock 在 `workspace-write` 下包含策略显式指定的 `additionalWritableRoots`。只读模式忽略这些授权。不存在的路径、非目录、符号链接目录和其他检查失败会在命令启动前触发 `SANDBOX_INVALID_ROOT`。Windows ACL 后端不检查这些额外根目录,仅保留工作区与私有临时目录访问权限。其按 session 的准备阶段会在命令启动前以 `SandboxPreparationError` 拒绝:主机临时根目录位于工作区内时为 `SANDBOX_INVALID_TEMP_ROOT`;无法创建 SID、ACL 授权或私有临时目录时为 `SANDBOX_PREPARATION_FAILED`,以 `Win32Error` 或 Node 错误作为 `cause`,并回滚已创建的部分授权。 ----- diff --git a/packages/sandbox/sandbox-local/src/index.ts b/packages/sandbox/sandbox-local/src/index.ts index 52cea43d23..af8dae004f 100644 --- a/packages/sandbox/sandbox-local/src/index.ts +++ b/packages/sandbox/sandbox-local/src/index.ts @@ -34,13 +34,31 @@ import { } from '@deepseek-ai/node-addon-system/landlock-run' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { SandboxProvider, SandboxUnavailableError, canonicalPath } from '@deepseek-ai/dsh-sandbox' +import { SandboxPreparationError, SandboxProvider, SandboxUnavailableError, canonicalPath } from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox' import type { SessionId } from '@deepseek-ai/dsh-session' -import { AclWriteGrant, assertTempRootOutsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl' +import { AclWriteGrant, isTempRootInsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl' import { assertNever } from '@deepseek-ai/dsh-util-values' import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts' +/** + * Classify one failed Windows ACL preparation step; the platform failure, or an + * `AggregateError` of it and its cleanup failures, becomes the `cause`. + * @param step - the preparation step, as the message names it. + * @param error - the step's own failure, typically a `Win32Error` or Node errno error. + * @param cleanupFailures - rollback failures that followed it. + * @returns the coded preparation failure. + */ +function aclPreparationFailure(step: string, error: unknown, cleanupFailures: readonly unknown[] = []): SandboxPreparationError { + const failed = cleanupFailures.length === 0 ? `${step} failed` : `${step} failed and its cleanup also failed` + return new SandboxPreparationError( + `sandbox-local: windows-acl ${failed}: ${String(error)}. The command did not run; ` + + 'check that the current user can change permissions on the workspace and temp directories, or run with danger-full-access.', + 'SANDBOX_PREPARATION_FAILED', + { cause: cleanupFailures.length === 0 ? error : new AggregateError([error, ...cleanupFailures], `sandbox-local windows-acl ${failed}`) }, + ) +} + /** Plugin config. All optional — `static Config` supplies the defaults. */ export interface Config { /** @@ -397,16 +415,37 @@ export class LocalSandboxProvider extends SandboxProvider { * SID to enter it. A fresh provider always chooses a new path; crash * residue therefore cannot collide with or authorize a resumed session. * Fail-closed: a half-materialized temp grant is revoked and its directory - * removed before the error propagates. + * removed before the error propagates. A temp root inside the workspace + * throws `SandboxPreparationError` `SANDBOX_INVALID_TEMP_ROOT` before any ACL + * change; any other failure throws `SANDBOX_PREPARATION_FAILED` with the + * platform error as `cause`. * @param sessionId - the policy's calling-session identity. * @param workspaceRoot - the resolved policy root. * @returns the pair's private temp directory and write capability. */ private materializeAclGrant(sessionId: SessionId, workspaceRoot: string): AclTempCapability { - assertTempRootOutsideWorkspace(workspaceRoot, tmpdir()) + let tempInsideWorkspace: boolean + try { + tempInsideWorkspace = isTempRootInsideWorkspace(workspaceRoot, tmpdir()) + } catch (error) { + throw aclPreparationFailure('workspace and temp directory resolution', error) + } + if (tempInsideWorkspace) { + throw new SandboxPreparationError( + `sandbox-local: windows-acl temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tmpdir()}. ` + + 'A private temp directory there would inherit the workspace grant, so the command did not run. ' + + 'Set TEMP and TMP to a directory outside the workspace, or open a workspace that does not contain the temp directory.', + 'SANDBOX_INVALID_TEMP_ROOT', + ) + } const writeSid = workspaceWriteSid(workspaceRoot) if (!this.workspaceGrants.has(workspaceRoot)) { - const grant = AclWriteGrant.create(writeSid) + let grant: AclWriteGrant + try { + grant = AclWriteGrant.create(writeSid) + } catch (error) { + throw aclPreparationFailure('workspace grant', error) + } try { grant.add(workspaceRoot, true) } catch (error) { @@ -416,16 +455,21 @@ export class LocalSandboxProvider extends SandboxProvider { try { grant.dispose() } catch (cleanupError) { - throw new AggregateError([error, cleanupError], 'sandbox-local windows-acl workspace grant failed and its cleanup also failed') + throw aclPreparationFailure('workspace grant', error, [cleanupError]) } - throw error + throw aclPreparationFailure('workspace grant', error) } this.workspaceGrants.set(workspaceRoot, grant) } const key = JSON.stringify([String(sessionId), workspaceRoot]) const existing = this.tempCapabilities.get(key) if (existing !== undefined) return existing - const tempDir = mkdtempSync(join(tmpdir(), 'dsh-')) + let tempDir: string + try { + tempDir = mkdtempSync(join(tmpdir(), 'dsh-')) + } catch (error) { + throw aclPreparationFailure('private temp directory creation', error) + } const tempSid = tempWriteSid(tempDir) let grant: AclWriteGrant | undefined try { @@ -445,10 +489,7 @@ export class LocalSandboxProvider extends SandboxProvider { } catch (cleanupError) { cleanupFailures.push(cleanupError) } - if (cleanupFailures.length > 0) { - throw new AggregateError([error, ...cleanupFailures], 'sandbox-local windows-acl temp grant materialization failed and its cleanup also failed') - } - throw error + throw aclPreparationFailure('temp grant materialization', error, cleanupFailures) } const capability = { dir: tempDir, writeSid: tempSid, grant } this.tempCapabilities.set(key, capability) diff --git a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts index 7f69bc3ddf..c98fbf0eb9 100644 --- a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts +++ b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts @@ -5,7 +5,7 @@ * is mocked; native access checks live in sandbox-windows-acl's runner suite. */ -import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -21,6 +21,7 @@ const mockState = vi.hoisted(() => ({ /** Restrict an add failure to standing (workspace) or revocable (temp). */ addFailureStanding: undefined as boolean | undefined, createTempFailure: undefined as Error | undefined, + createWorkspaceFailure: undefined as Error | undefined, disposeFailure: undefined as Error | undefined, })) @@ -35,6 +36,7 @@ vi.mock('@deepseek-ai/dsh-sandbox-windows-acl', () => { } static create(writeSid: string): MockAclWriteGrant { if (writeSid.startsWith('TEMP:') && mockState.createTempFailure !== undefined) throw mockState.createTempFailure + if (!writeSid.startsWith('TEMP:') && mockState.createWorkspaceFailure !== undefined) throw mockState.createWorkspaceFailure return new MockAclWriteGrant(writeSid) } add(path: string, standing = false): void { @@ -52,12 +54,10 @@ vi.mock('@deepseek-ai/dsh-sandbox-windows-acl', () => { return { registerAclDiagnosisSkill: vi.fn(), AclWriteGrant: MockAclWriteGrant, - assertTempRootOutsideWorkspace: (workspaceRoot: string, tempRoot: string) => { + isTempRootInsideWorkspace: (workspaceRoot: string, tempRoot: string) => { const workspace = realpathSync.native(workspaceRoot) const temp = realpathSync.native(tempRoot) - if (temp === workspace || temp.startsWith(`${workspace}${process.platform === 'win32' ? '\\' : '/'}`)) { - throw new Error(`Windows ACL temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tempRoot}`) - } + return temp === workspace || temp.startsWith(`${workspace}${process.platform === 'win32' ? '\\' : '/'}`) }, workspaceWriteSid: () => 'S-1-4-42-42', tempWriteSid: (path: string) => `TEMP:${path}`, @@ -91,6 +91,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { mockState.addFailure = undefined mockState.addFailureStanding = undefined mockState.createTempFailure = undefined + mockState.createWorkspaceFailure = undefined mockState.disposeFailure = undefined }) @@ -250,25 +251,87 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { mockState.addFailure = new Error('workspace grant exploded') await expect(sandbox.confine(['true'], { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('workspace-fail'), - })).rejects.toThrow('workspace grant exploded') + })).rejects.toMatchObject({ + name: 'SandboxPreparationError', + code: 'SANDBOX_PREPARATION_FAILED', + cause: mockState.addFailure, + message: expect.stringContaining('workspace grant failed: Error: workspace grant exploded') as string, + }) expect(mockState.grants).toHaveLength(1) expect(mockState.grants[0]!.disposed).toBe(true) mockState.disposeFailure = new Error('workspace cleanup exploded') await expect(sandbox.confine(['true'], { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('workspace-cleanup-fail'), - })).rejects.toThrow(/workspace grant failed and its cleanup also failed/u) + })).rejects.toMatchObject({ + name: 'SandboxPreparationError', + code: 'SANDBOX_PREPARATION_FAILED', + message: expect.stringMatching(/workspace grant failed and its cleanup also failed/u) as string, + cause: expect.objectContaining({ errors: [mockState.addFailure, mockState.disposeFailure] }) as unknown, + }) expect(mockState.grants).toHaveLength(2) } finally { cleanup() } }) + it('codes a workspace SID allocation failure and an unresolvable workspace before any grant', async () => { + const { sandbox } = await setup() + try { + const ws = workspaceRoot() + scratch.push(ws) + mockState.createWorkspaceFailure = new Error('ConvertStringSidToSidW failed (Win32 1337)') + await expect(sandbox.confine(['true'], { + mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('sid-fail'), + })).rejects.toMatchObject({ name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', cause: mockState.createWorkspaceFailure }) + await expect(sandbox.confine(['true'], { + mode: 'workspace-write', workspaceRoot: join(ws, 'missing'), sessionId: SessionId('missing'), + })).rejects.toMatchObject({ + name: 'SandboxPreparationError', + code: 'SANDBOX_PREPARATION_FAILED', + message: expect.stringContaining('workspace and temp directory resolution failed') as string, + cause: expect.objectContaining({ code: 'ENOENT' }) as unknown, + }) + expect(mockState.grants).toHaveLength(0) + } finally { + cleanup() + } + }) + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('codes a private temp directory that cannot be created', async () => { + const { sandbox } = await setup() + const ws = workspaceRoot() + const lockedTemp = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-acl-locked-temp-'))) + scratch.push(ws, lockedTemp) + const previous = process.env.TMPDIR + chmodSync(lockedTemp, 0o500) + process.env.TMPDIR = lockedTemp + try { + await expect(sandbox.confine(['true'], { + mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('mkdtemp-fail'), + })).rejects.toMatchObject({ + name: 'SandboxPreparationError', + code: 'SANDBOX_PREPARATION_FAILED', + message: expect.stringContaining('private temp directory creation failed') as string, + cause: expect.objectContaining({ code: 'EACCES' }) as unknown, + }) + } finally { + if (previous === undefined) delete process.env.TMPDIR + else process.env.TMPDIR = previous + chmodSync(lockedTemp, 0o700) + cleanup() + } + }) + it('rejects a workspace containing the ambient temp root before any ACL mutation', async () => { const { sandbox } = await setup() await expect(sandbox.confine(['true'], { mode: 'workspace-write', workspaceRoot: realpathSync.native(tmpdir()), sessionId: SessionId('overlap'), - })).rejects.toThrow(/temp root must be outside the workspace/u) + })).rejects.toMatchObject({ + name: 'SandboxPreparationError', + code: 'SANDBOX_INVALID_TEMP_ROOT', + message: expect.stringMatching(/temp root must be outside the workspace/u) as string, + }) expect(mockState.grants).toHaveLength(0) }) @@ -281,7 +344,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { mockState.createTempFailure = new Error('temp SID creation exploded') await expect(sandbox.confine(['true'], { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('create-fail'), - })).rejects.toThrow('temp SID creation exploded') + })).rejects.toMatchObject({ code: 'SANDBOX_PREPARATION_FAILED', cause: mockState.createTempFailure }) expect(mockState.grants).toHaveLength(1) // workspace only; random temp was removed mockState.createTempFailure = undefined @@ -289,7 +352,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { mockState.addFailure = new Error('temp add exploded') await expect(sandbox.confine(['true'], { mode: 'workspace-write', workspaceRoot: ws, sessionId: SessionId('add-fail'), - })).rejects.toThrow('temp add exploded') + })).rejects.toMatchObject({ name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', cause: mockState.addFailure }) const failedTempGrant = mockState.grants.at(-1) expect(failedTempGrant?.disposed).toBe(true) expect(failedTempGrant?.added).toHaveLength(1) diff --git a/packages/sandbox/sandbox-windows-acl/src/index.ts b/packages/sandbox/sandbox-windows-acl/src/index.ts index 5de5d47b72..2af0d2d6c7 100644 --- a/packages/sandbox/sandbox-windows-acl/src/index.ts +++ b/packages/sandbox/sandbox-windows-acl/src/index.ts @@ -56,7 +56,7 @@ import { createRestrictedToken, findLogonSid, makeWellKnownSid, openCurrentProce import * as abi from './win32-abi.ts' export { AclWriteGrant } from './grant.ts' -export { assertTempRootOutsideWorkspace } from './path-boundary.ts' +export { assertTempRootOutsideWorkspace, isTempRootInsideWorkspace } from './path-boundary.ts' export { tempWriteSid, workspaceWriteSid } from './workspace-sid.ts' export { ACL_DIAGNOSIS_SKILL, registerAclDiagnosisSkill } from './acl-skill.ts' /** Construction options: the workspace/temp allowlists and their distinct SID identities. */ diff --git a/packages/sandbox/sandbox-windows-acl/src/path-boundary.ts b/packages/sandbox/sandbox-windows-acl/src/path-boundary.ts index 7c8dcb2596..c801bbb995 100644 --- a/packages/sandbox/sandbox-windows-acl/src/path-boundary.ts +++ b/packages/sandbox/sandbox-windows-acl/src/path-boundary.ts @@ -14,13 +14,24 @@ function containsDirectory(root: string, candidate: string): boolean { } /** - * Reject a temp parent that is inside the workspace: every child created + * Whether a temp parent is inside the workspace, where every child created * below it would inherit the standing workspace capability. * @param workspaceRoot - the canonical workspace root that receives the standing ACE. * @param tempRoot - the existing parent beneath which a private temp child would be created. + * @returns whether the canonical workspace contains the canonical temp root. + * @throws the filesystem error when either directory cannot be resolved. + */ +export function isTempRootInsideWorkspace(workspaceRoot: string, tempRoot: string): boolean { + return containsDirectory(workspaceRoot, tempRoot) +} + +/** + * Reject a temp parent that is inside the workspace (see {@link isTempRootInsideWorkspace}). + * @param workspaceRoot - the canonical workspace root that receives the standing ACE. + * @param tempRoot - the existing parent beneath which a private temp child would be created. */ export function assertTempRootOutsideWorkspace(workspaceRoot: string, tempRoot: string): void { - if (containsDirectory(workspaceRoot, tempRoot)) { + if (isTempRootInsideWorkspace(workspaceRoot, tempRoot)) { throw new Error(`Windows ACL temp root must be outside the workspace: workspace=${workspaceRoot}; temp=${tempRoot}`) } } diff --git a/packages/sandbox/sandbox/README.i18n.yaml b/packages/sandbox/sandbox/README.i18n.yaml index 9bdd154f3a..7cd5cd3e7c 100644 --- a/packages/sandbox/sandbox/README.i18n.yaml +++ b/packages/sandbox/sandbox/README.i18n.yaml @@ -27,11 +27,11 @@ en: d3c906ddb4c47cbc zh: d264b9103e3566d6 /deepseek-ai-dsh-sandbox/use-this-package/denied-calls-and-escalation: - en: 3960c33a1e322cf9 - zh: 4d85c962067fe7a1 + en: 0572a2aa3208873f + zh: 07e5d481a637a5af /deepseek-ai-dsh-sandbox/use-this-package/fail-closed-behavior: - en: 6bf240632a7a6bf5 - zh: ebf414f5cf435875 + en: b3d36b28566cadd4 + zh: 22cf905bf574865a /deepseek-ai-dsh-sandbox/understand-the-implementation: en: 7e13d669ecc96d59 zh: b5fe7ae65812d926 diff --git a/packages/sandbox/sandbox/README.md b/packages/sandbox/sandbox/README.md index 3bd771b271..3db483c834 100644 --- a/packages/sandbox/sandbox/README.md +++ b/packages/sandbox/sandbox/README.md @@ -63,11 +63,11 @@ Enforcement is reported per call: `full` means the backend governs every promise ### Denied calls and escalation -When a confined call is denied, the operation reports a denial marker naming the mode — `[sandbox: file access denied under mode]` — and, when the composition advertises escalation, an escalation hint. The model may retry the exact call once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a `justification`; the approval service obtains consent for the operation. The request retains its audit reason and supplies English, Chinese, and Japanese presentation copy from `src/locales.ts`, with the model's justification unchanged. Missing translations follow the locale service's fallback chain, ultimately English; requesters own their translated presentation text. A wider mode requires approval and applies to that one call only. Repeating the call's effective mode succeeds without approval; narrower targets remain invalid. +When a confined call is denied, the operation reports a denial marker naming the mode — `[sandbox: file access denied under mode]` — and, when the composition advertises escalation, an escalation hint. The model may retry the exact call once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a `justification`; the approval service obtains consent for the operation. The request retains its audit reason and supplies English, Chinese, and Japanese presentation copy from `src/locales.ts`, with the model's justification unchanged. Missing translations follow the locale service's fallback chain, ultimately English; requesters own their translated presentation text. A wider mode requires approval and applies to that one call only. Repeating the call's effective mode succeeds without approval; narrower targets remain invalid. An escalation that yields no grant throws `SandboxEscalationError` before anything runs: `SANDBOX_ESCALATION_INVALID_ARGUMENT` for unpaired fields, a blank justification, or a target that is not strictly wider; `SANDBOX_ESCALATION_UNAVAILABLE` when the composition has no sandboxing executor, approval service, calling Agent, or approval channel; `SANDBOX_ESCALATION_REJECTED` when the user declines; and `SANDBOX_ESCALATION_CANCELLED` when the approval request ends without a decision. If the call itself was cancelled, the call's cancellation propagates instead. ### Fail-closed behavior -When no backend can enforce the requested mode, the call fails with `SANDBOX_UNAVAILABLE` rather than running unconfined; the error text names the missing platform runner. A backend that fails after starting also reports a structured runner-failure signature, so a broken sandbox is distinguishable from a command failure. +When no backend can enforce the requested mode, the call fails with `SANDBOX_UNAVAILABLE` rather than running unconfined; the error text names the missing platform runner. A backend that fails after starting also reports a structured runner-failure signature, so a broken sandbox is distinguishable from a command failure. A provider that cannot prepare host state for an enforceable mode, such as a Windows ACL grant or private temp directory, rejects with `SandboxPreparationError`: `SANDBOX_PREPARATION_FAILED` carries the platform error as `cause`, and `SANDBOX_INVALID_TEMP_ROOT` reports a host temp root inside the workspace. ----- diff --git a/packages/sandbox/sandbox/README.zh.md b/packages/sandbox/sandbox/README.zh.md index f2757c7300..6e9710cde9 100644 --- a/packages/sandbox/sandbox/README.zh.md +++ b/packages/sandbox/sandbox/README.zh.md @@ -63,11 +63,11 @@ kind: "package-reference" ### 被拒绝的调用与升权 -受限调用被拒绝时,操作会报告指明模式的拒绝标记——`[sandbox: file access denied under mode]`——组合声明升权能力时还会给出升权提示。模型可以用 `sandbox_permissions`(足以放行的最窄更宽模式)加 `justification` 重试一次完全相同的调用;审批服务为操作取得同意。请求保留审计原因,同时从 `src/locales.ts` 提供英文、中文和日文展示文案,模型给出的理由保持原样。缺失的译文遵循语言服务的回退链,最终回退到英文;请求方负责自己的展示译文。更宽的模式需要审批,且只作用于该次调用。重复指定调用的生效模式无需审批即可成功;更窄的目标仍然无效。 +受限调用被拒绝时,操作会报告指明模式的拒绝标记——`[sandbox: file access denied under mode]`——组合声明升权能力时还会给出升权提示。模型可以用 `sandbox_permissions`(足以放行的最窄更宽模式)加 `justification` 重试一次完全相同的调用;审批服务为操作取得同意。请求保留审计原因,同时从 `src/locales.ts` 提供英文、中文和日文展示文案,模型给出的理由保持原样。缺失的译文遵循语言服务的回退链,最终回退到英文;请求方负责自己的展示译文。更宽的模式需要审批,且只作用于该次调用。重复指定调用的生效模式无需审批即可成功;更窄的目标仍然无效。未取得授权的升权会在任何命令运行前抛出 `SandboxEscalationError`:字段未配对、理由为空或目标并非严格更宽时为 `SANDBOX_ESCALATION_INVALID_ARGUMENT`;组合中没有受限执行器、审批服务、调用方 Agent 或审批通道时为 `SANDBOX_ESCALATION_UNAVAILABLE`;用户拒绝时为 `SANDBOX_ESCALATION_REJECTED`;审批请求未作决定即结束时为 `SANDBOX_ESCALATION_CANCELLED`。若调用本身已被取消,则改为传播该调用的取消。 ### 故障关闭行为 -没有后端能强制执行所请求的模式时,调用以 `SANDBOX_UNAVAILABLE` 失败,而不是不受限制地运行;错误文本会指明缺失的平台 runner。启动后失败的后端还会报告结构化的 runner 失败签名,因此损坏的沙箱可以与命令失败区分开。 +没有后端能强制执行所请求的模式时,调用以 `SANDBOX_UNAVAILABLE` 失败,而不是不受限制地运行;错误文本会指明缺失的平台 runner。启动后失败的后端还会报告结构化的 runner 失败签名,因此损坏的沙箱可以与命令失败区分开。提供方无法为可强制执行的模式准备主机状态(例如 Windows ACL 授权或私有临时目录)时,以 `SandboxPreparationError` 拒绝:`SANDBOX_PREPARATION_FAILED` 以平台错误作为 `cause`,`SANDBOX_INVALID_TEMP_ROOT` 表示主机临时根目录位于工作区内。 ----- diff --git a/packages/sandbox/sandbox/src/escalation.ts b/packages/sandbox/sandbox/src/escalation.ts index c912fdd080..84d5f49561 100644 --- a/packages/sandbox/sandbox/src/escalation.ts +++ b/packages/sandbox/sandbox/src/escalation.ts @@ -16,10 +16,45 @@ * @module dsh-sandbox/escalation */ +import { HarnessError } from '@deepseek-ai/dsh-llm' import { assertNever } from '@deepseek-ai/dsh-util-values' import { escalationDisplayReason } from './locales.ts' import type { SandboxMode } from './index.ts' +/** + * Every {@link SandboxEscalationError} code: + * - `SANDBOX_ESCALATION_INVALID_ARGUMENT` — the escalation fields are unpaired, the justification is blank, or the + * target is not strictly wider than the call's effective mode; the model corrects the request. + * - `SANDBOX_ESCALATION_UNAVAILABLE` — the composition cannot ask for approval: no sandboxing executor, no approval + * service, no calling Agent, or no approval channel. + * - `SANDBOX_ESCALATION_REJECTED` — the user declined the escalation; the operation stays denied. + * - `SANDBOX_ESCALATION_CANCELLED` — the approval request ended without a decision while the call itself was not cancelled. + */ +export const SANDBOX_ESCALATION_ERROR_CODES = [ + 'SANDBOX_ESCALATION_INVALID_ARGUMENT', + 'SANDBOX_ESCALATION_UNAVAILABLE', + 'SANDBOX_ESCALATION_REJECTED', + 'SANDBOX_ESCALATION_CANCELLED', +] as const + +/** One code from {@link SANDBOX_ESCALATION_ERROR_CODES}. */ +export type SandboxEscalationErrorCode = typeof SANDBOX_ESCALATION_ERROR_CODES[number] + +/** A `sandbox_permissions` request that did not produce a grant; nothing executed. */ +export class SandboxEscalationError extends HarnessError { + override readonly code: SandboxEscalationErrorCode + + /** + * @param message - the model-facing explanation and the safe next step. + * @param code - the failure class consumers route on. + */ + constructor(message: string, code: SandboxEscalationErrorCode) { + super(message, code) + this.name = 'SandboxEscalationError' + this.code = code + } +} + /** * The strictly-wider table: what a call whose effective mode is the key may * escalate TO. Checked at EXECUTION, never baked into a tool schema — the @@ -46,18 +81,19 @@ export const ESCALATION_TARGETS: readonly SandboxMode[] = ['workspace-write', 'd * `sandbox_permissions` and `justification` travel together — an approval * prompt without a reason, or a reason driving nothing, is a malformed ask — * and the justification must be a non-empty sentence. + * A violation throws {@link SandboxEscalationError} `SANDBOX_ESCALATION_INVALID_ARGUMENT`. * @param sandboxPermissions - the raw `sandbox_permissions` argument, if given. * @param justification - the raw `justification` argument, if given. */ export function validateEscalationArgs(sandboxPermissions: string | undefined, justification: string | undefined): void { if (sandboxPermissions !== undefined && justification === undefined) { - throw new Error('invalid escalation: sandbox_permissions requires a justification') + throw new SandboxEscalationError('invalid escalation: sandbox_permissions requires a justification', 'SANDBOX_ESCALATION_INVALID_ARGUMENT') } if (justification !== undefined && sandboxPermissions === undefined) { - throw new Error('invalid escalation: justification is only valid together with sandbox_permissions') + throw new SandboxEscalationError('invalid escalation: justification is only valid together with sandbox_permissions', 'SANDBOX_ESCALATION_INVALID_ARGUMENT') } if (justification !== undefined && justification.trim().length === 0) { - throw new Error('invalid justification: expected a non-empty sentence') + throw new SandboxEscalationError('invalid justification: expected a non-empty sentence', 'SANDBOX_ESCALATION_INVALID_ARGUMENT') } } @@ -164,7 +200,8 @@ export interface EscalationRequest { * effective mode returns it without approval. A strictly wider mode requires * approval and applies only to this call. Narrower or unsupported targets, * missing approval services or agents for widening, and non-grant outcomes - * throw before execution. + * throw {@link SandboxEscalationError} before execution; a `cancelled` + * outcome while `approval.signal` is aborted rethrows the signal's reason. * @param request - the escalation to judge (see {@link EscalationRequest}). * @param approval - the approval ingredients the tool holds (see {@link EscalationApproval}). * @returns the granted mode, consumed by the one call that asked. @@ -176,13 +213,22 @@ export async function approveEscalation(request: EscalationRequest, approv // deliberately not a schema constraint (the enum is the closed target // vocabulary; the effective mode is per-call truth). if (!(WIDER_MODES[effectiveMode] ?? []).includes(mode as SandboxMode)) { - throw new Error(`sandbox escalation to "${mode}" is not strictly wider than this call's current "${effectiveMode}" mode`) + throw new SandboxEscalationError( + `sandbox escalation to "${mode}" is not strictly wider than this call's current "${effectiveMode}" mode`, + 'SANDBOX_ESCALATION_INVALID_ARGUMENT', + ) } if (approval.approver === undefined) { - throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval service is composed`) + throw new SandboxEscalationError( + `sandbox escalation to "${mode}" requires approval, but no approval service is composed`, + 'SANDBOX_ESCALATION_UNAVAILABLE', + ) } if (approval.agent === undefined) { - throw new Error(`sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through`) + throw new SandboxEscalationError( + `sandbox escalation to "${mode}" requires approval, but the call has no agent to route it through`, + 'SANDBOX_ESCALATION_UNAVAILABLE', + ) } // Self-contained for the audit trail: approval/asked stores this reason, // and the target mode is part of the grant's identity. @@ -198,9 +244,20 @@ export async function approveEscalation(request: EscalationRequest, approv // The schema enum already pinned `mode` to the closed target vocabulary; // the check above proved it is strictly wider. case 'allowed-once': return mode as SandboxMode - case 'rejected': throw new Error(`the user rejected escalating this ${subject} to "${mode}"; it stays denied, so stop and explain instead of working around it`) - case 'cancelled': throw new Error(`approval for escalating to "${mode}" was cancelled`) - case 'unavailable': throw new Error(`sandbox escalation to "${mode}" requires approval, but no approval channel is available`) + case 'rejected': + throw new SandboxEscalationError( + `the user rejected escalating this ${subject} to "${mode}"; it stays denied, so stop and explain instead of working around it`, + 'SANDBOX_ESCALATION_REJECTED', + ) + case 'cancelled': + // A cancelled call keeps its own cancellation so the registry records it as aborted. + approval.signal?.throwIfAborted() + throw new SandboxEscalationError(`approval for escalating to "${mode}" was cancelled`, 'SANDBOX_ESCALATION_CANCELLED') + case 'unavailable': + throw new SandboxEscalationError( + `sandbox escalation to "${mode}" requires approval, but no approval channel is available`, + 'SANDBOX_ESCALATION_UNAVAILABLE', + ) default: return assertNever(outcome, 'EscalationOutcome') } } diff --git a/packages/sandbox/sandbox/src/index.ts b/packages/sandbox/sandbox/src/index.ts index bd22dcb5d6..69d9100f66 100644 --- a/packages/sandbox/sandbox/src/index.ts +++ b/packages/sandbox/sandbox/src/index.ts @@ -11,6 +11,8 @@ import type { SessionId } from '@deepseek-ai/dsh-session' export { ESCALATION_TARGETS, + SANDBOX_ESCALATION_ERROR_CODES, + SandboxEscalationError, WIDER_MODES, approveEscalation, escalationHintMarker, @@ -18,7 +20,13 @@ export { sandboxPermissionsDescription, validateEscalationArgs, } from './escalation.ts' -export type { EscalationApproval, EscalationApprover, EscalationOutcome, EscalationRequest } from './escalation.ts' +export type { + EscalationApproval, + EscalationApprover, + EscalationOutcome, + EscalationRequest, + SandboxEscalationErrorCode, +} from './escalation.ts' export { canonicalPath, workspaceWritableRoots, writableRoots, SandboxInvalidRootError } from './roots.ts' /** @@ -152,6 +160,38 @@ export class SandboxUnavailableError extends HarnessError { } } +/** + * Every {@link SandboxPreparationError} code: + * - `SANDBOX_PREPARATION_FAILED` — the provider could not set up host state the confined process needs, such as a + * Windows ACL grant or a private temp directory; `cause` holds the platform failure. + * - `SANDBOX_INVALID_TEMP_ROOT` — the host temp root lies inside the workspace, so a private temp directory would + * inherit the workspace grant; move the temp root or the workspace. + */ +export const SANDBOX_PREPARATION_ERROR_CODES = ['SANDBOX_PREPARATION_FAILED', 'SANDBOX_INVALID_TEMP_ROOT'] as const + +/** One code from {@link SANDBOX_PREPARATION_ERROR_CODES}. */ +export type SandboxPreparationErrorCode = typeof SANDBOX_PREPARATION_ERROR_CODES[number] + +/** + * Thrown by {@link SandboxProvider.confine} when host preparation for an + * enforceable mode fails. The provider rolls back what it prepared before + * throwing, and the command never runs. + */ +export class SandboxPreparationError extends HarnessError { + override readonly code: SandboxPreparationErrorCode + + /** + * @param message - names the preparation step and the safe next step. + * @param code - the failure class consumers route on. + * @param options - the platform failure, or an `AggregateError` with the cleanup failures, as `cause`. + */ + constructor(message: string, code: SandboxPreparationErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'SandboxPreparationError' + this.code = code + } +} + declare module '@deepseek-ai/cordis' { interface Context { sandbox: SandboxProvider diff --git a/packages/sandbox/sandbox/tests/escalation.spec.ts b/packages/sandbox/sandbox/tests/escalation.spec.ts index 987ac0105b..f485bbd1df 100644 --- a/packages/sandbox/sandbox/tests/escalation.spec.ts +++ b/packages/sandbox/sandbox/tests/escalation.spec.ts @@ -9,6 +9,7 @@ import { describe, expect, it } from 'vitest' import { ESCALATION_TARGETS, + SandboxEscalationError, WIDER_MODES, approveEscalation, escalationHintMarker, @@ -16,7 +17,20 @@ import { sandboxPermissionsDescription, validateEscalationArgs, } from '@deepseek-ai/dsh-sandbox' -import type { EscalationApprover, EscalationOutcome } from '@deepseek-ai/dsh-sandbox' +import type { EscalationApprover, EscalationOutcome, SandboxEscalationErrorCode } from '@deepseek-ai/dsh-sandbox' + +/** The structured identity a failed escalation records on `tool/result`. */ +const escalationError = (code: SandboxEscalationErrorCode): unknown => expect.objectContaining({ name: 'SandboxEscalationError', code }) + +/** The synchronous failure `run` throws. */ +function thrown(run: () => void): unknown { + try { + run() + } catch (error: unknown) { + return error + } + throw new Error('expected a throw') +} describe('the strictly-wider ladder', () => { it('read-only escalates to either wider mode; workspace-write only to full access', () => { @@ -40,6 +54,11 @@ describe('validateEscalationArgs', () => { expect(() => { validateEscalationArgs('workspace-write', undefined) }).toThrow(/requires a justification/) expect(() => { validateEscalationArgs(undefined, 'orphan reason') }).toThrow(/only valid together with sandbox_permissions/) expect(() => { validateEscalationArgs('workspace-write', ' ') }).toThrow(/non-empty sentence/) + for (const [mode, justification] of [['workspace-write', undefined], [undefined, 'orphan reason'], ['workspace-write', ' ']] as const) { + const error = thrown(() => { validateEscalationArgs(mode, justification) }) + expect(error).toBeInstanceOf(SandboxEscalationError) + expect(error).toEqual(escalationError('SANDBOX_ESCALATION_INVALID_ARGUMENT')) + } }) }) @@ -113,12 +132,16 @@ describe('approveEscalation', () => { .rejects.toThrow(/not strictly wider/) await expect(approveEscalation(req({ requestedMode: 'unknown-mode' }), spy)) .rejects.toThrow(/not strictly wider/) + await expect(approveEscalation(req({ requestedMode: 'unknown-mode' }), spy)) + .rejects.toEqual(escalationError('SANDBOX_ESCALATION_INVALID_ARGUMENT')) expect(seen).toEqual([]) }) it('a missing approval service and an agent-less call each fail closed with distinct text', async () => { await expect(approveEscalation(req(), ingredients({ approver: undefined }))).rejects.toThrow(/no approval service is composed/) await expect(approveEscalation(req(), ingredients({ agent: undefined }))).rejects.toThrow(/no agent to route it through/) + await expect(approveEscalation(req(), ingredients({ approver: undefined }))).rejects.toEqual(escalationError('SANDBOX_ESCALATION_UNAVAILABLE')) + await expect(approveEscalation(req(), ingredients({ agent: undefined }))).rejects.toEqual(escalationError('SANDBOX_ESCALATION_UNAVAILABLE')) }) it('maps each non-grant outcome to its distinct verbatim text (subject in the rejection)', async () => { @@ -130,6 +153,23 @@ describe('approveEscalation', () => { .rejects.toThrow('no approval channel is available') }) + it('codes each non-grant outcome', async () => { + await expect(approveEscalation(req(), ingredients({ approver: approver('rejected') }))) + .rejects.toEqual(escalationError('SANDBOX_ESCALATION_REJECTED')) + await expect(approveEscalation(req(), ingredients({ approver: approver('cancelled') }))) + .rejects.toEqual(escalationError('SANDBOX_ESCALATION_CANCELLED')) + await expect(approveEscalation(req(), ingredients({ approver: approver('unavailable') }))) + .rejects.toEqual(escalationError('SANDBOX_ESCALATION_UNAVAILABLE')) + }) + + it('a cancelled approval for an aborted call rethrows the call\'s cancellation', async () => { + const controller = new AbortController() + const reason = new DOMException('caller stopped', 'AbortError') + controller.abort(reason) + await expect(approveEscalation(req(), ingredients({ approver: approver('cancelled'), signal: controller.signal }))) + .rejects.toBe(reason) + }) + it('an outcome outside the closed union trips the exhaustiveness guard (defensive)', async () => { await expect(approveEscalation(req(), ingredients({ approver: approver('bogus' as never) }))).rejects.toThrow() }) diff --git a/packages/sandbox/sandbox/tests/vocabulary.spec.ts b/packages/sandbox/sandbox/tests/vocabulary.spec.ts index caba42b2a7..26db8fe796 100644 --- a/packages/sandbox/sandbox/tests/vocabulary.spec.ts +++ b/packages/sandbox/sandbox/tests/vocabulary.spec.ts @@ -7,7 +7,8 @@ */ import { describe, expect, it } from 'vitest' -import { SANDBOX_UNAVAILABLE, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { SANDBOX_PREPARATION_ERROR_CODES, SANDBOX_UNAVAILABLE, SandboxPreparationError, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' describe('SandboxUnavailableError', () => { it('carries the structured { name, code } identity consumers key on', () => { @@ -33,3 +34,13 @@ describe('SandboxUnavailableError', () => { expect(error.message).toContain('Runner failure: landlock-run: landlock is not enforced by this kernel') }) }) + +describe('SandboxPreparationError', () => { + it('carries a literal name, a closed code, and the platform failure as cause', () => { + const cause = new Error('SetNamedSecurityInfoW failed (Win32 5)') + const error = new SandboxPreparationError('cannot grant the workspace', 'SANDBOX_PREPARATION_FAILED', { cause }) + expect(error).toBeInstanceOf(HarnessError) + expect(error).toMatchObject({ name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', cause }) + expect(SANDBOX_PREPARATION_ERROR_CODES).toEqual(['SANDBOX_PREPARATION_FAILED', 'SANDBOX_INVALID_TEMP_ROOT']) + }) +}) From 45db11970ccdf4e4ad5643fc11e45b702ac125e7 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:59:51 +0800 Subject: [PATCH 044/438] feat(working-directory): add WorkingDirectoryError and code directory failures The working-directory service throws WorkingDirectoryError: WORKING_DIRECTORY_INVALID for an empty cd, WORKING_DIRECTORY_NOT_FOUND for a missing target, and WORKING_DIRECTORY_UNAVAILABLE when the current and original directories are both gone or the service was disposed. The working_directory tool reports a missing Agent as ToolContextUnavailableError and an empty cd as ToolArgsError. sandbox-policy reports a session cwd it cannot use as a workspace root as SandboxInvalidRootError (SANDBOX_INVALID_ROOT), whose constructor now names the role of the rejected path. Refs #7869 --- .../sandbox/sandbox-policy/README.i18n.yaml | 4 +-- packages/sandbox/sandbox-policy/README.md | 2 +- packages/sandbox/sandbox-policy/README.zh.md | 2 +- packages/sandbox/sandbox-policy/src/index.ts | 29 ++++++++++++---- .../sandbox-policy/tests/policy.spec.ts | 14 ++++++++ packages/sandbox/sandbox/src/roots.ts | 11 ++++-- .../tool-working-directory/README.i18n.yaml | 4 +-- .../session/tool-working-directory/README.md | 2 +- .../tool-working-directory/README.zh.md | 2 +- .../tool-working-directory/src/index.ts | 5 +-- .../working-directory/README.i18n.yaml | 4 +-- packages/session/working-directory/README.md | 2 +- .../session/working-directory/README.zh.md | 2 +- .../session/working-directory/src/error.ts | 34 +++++++++++++++++++ .../session/working-directory/src/index.ts | 33 +++++++++++++----- .../tests/working-directory.spec.ts | 21 +++++++++++- 16 files changed, 138 insertions(+), 33 deletions(-) create mode 100644 packages/session/working-directory/src/error.ts diff --git a/packages/sandbox/sandbox-policy/README.i18n.yaml b/packages/sandbox/sandbox-policy/README.i18n.yaml index a5cc96a557..9bef469d7d 100644 --- a/packages/sandbox/sandbox-policy/README.i18n.yaml +++ b/packages/sandbox/sandbox-policy/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6704447e52ec295b zh: 9ed812d9e29d5533 /deepseek-ai-dsh-sandbox-policy/use-this-package/minimal-configuration: - en: 0616478ef5bb0566 - zh: e3a5802aefcf8424 + en: 0b62eae224181946 + zh: 2e77e7f49bd074d4 /deepseek-ai-dsh-sandbox-policy/use-this-package/registering-a-session-s-writable-directory: en: 841ea47ef1ed7ee6 zh: cd573e67a67742e2 diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index 022ba841e4..0d26190122 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -45,7 +45,7 @@ Load the package with a default mode; the fail-safe default is `read-only`, and | Field | Default | Meaning | |---|---|---| | `mode` | `read-only` | The deployment default mode a session starts from, validated at load | -| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a cwd; relative values fail at load. Normal agent calls use the session's immutable cwd | +| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a cwd; relative values fail at load. Normal agent calls use the session's immutable cwd; a cwd containing a NUL byte fails the call with `SANDBOX_INVALID_ROOT` | | `additionalWritableRoots` | `[]` | Physical absolute directories also writable under `workspace-write`; Windows file tools honor them, Windows subprocesses ignore them, and `read-only` grants no access | For a linked Git worktree, the caller can grant its shared Git directory with `additionalWritableRoots`. The caller selects that directory explicitly; the policy does not inspect Git files or grant a parent checkout. These grants are deployment configuration shared by the composition's sessions, rather than saved Session permissions. Granting the entire Git directory also permits changes to hooks and configuration that a later host Git invocation can execute outside the sandbox; use that grant only for trusted tasks. Use physical absolute directory paths. The enforcing host rejects missing paths, non-directories, and symlinked directories on each call, including a directory replaced by a symlink between calls. Remote grants are validated on the remote host. diff --git a/packages/sandbox/sandbox-policy/README.zh.md b/packages/sandbox/sandbox-policy/README.zh.md index 49d976c7bf..a436f298d5 100644 --- a/packages/sandbox/sandbox-policy/README.zh.md +++ b/packages/sandbox/sandbox-policy/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" | 字段 | 默认值 | 含义 | |---|---|---| | `mode` | `read-only` | 会话起始的部署默认模式,加载时验证 | -| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有 cwd 的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的不可变 cwd | +| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有 cwd 的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的不可变 cwd;cwd 含 NUL 字节时调用以 `SANDBOX_INVALID_ROOT` 失败 | | `additionalWritableRoots` | `[]` | 在 `workspace-write` 下额外允许写入的物理绝对目录;Windows 文件工具执行这些授权,Windows 子进程忽略它们,`read-only` 不授予访问权限 | 对于关联的 Git worktree,调用方可通过 `additionalWritableRoots` 授予共享 Git 目录的写权限。调用方必须显式选择该目录;策略不会读取 Git 文件或授权父检出目录。这些授权是组合中所有会话共享的部署配置,而非保存的 Session 权限。授权整个 Git 目录也允许修改钩子和配置,后续主机 Git 调用可能在沙箱之外执行它们;仅对可信任务使用此授权。使用物理绝对目录路径。执行限制的主机在每次调用时拒绝不存在的路径、非目录和符号链接目录,包括两次调用之间被替换为符号链接的目录。远端授权在远端主机上验证。 diff --git a/packages/sandbox/sandbox-policy/src/index.ts b/packages/sandbox/sandbox-policy/src/index.ts index 2136e33f45..8f8d5023ac 100644 --- a/packages/sandbox/sandbox-policy/src/index.ts +++ b/packages/sandbox/sandbox-policy/src/index.ts @@ -27,6 +27,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import { z as zod } from 'zod' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' +import { SandboxInvalidRootError } from '@deepseek-ai/dsh-sandbox' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' @@ -34,10 +35,9 @@ import type {} from '@deepseek-ai/dsh-system-prompt' export { SANDBOX_MODES, setSandboxMode } from './session-mode.ts' -/** Preserve execution-world spelling; enforcing providers resolve filesystem identity on their host. */ -function resolveWorkspaceRoot(path: string): string { - if (!isAbsolute(path) || path.includes('\0')) throw new Error('sandbox-policy: workspace root must be an absolute execution-world path without NUL bytes') - return path +/** Whether a path is usable as an execution-world grant: absolute and free of NUL bytes. */ +function isExecutionWorldPath(path: string): boolean { + return isAbsolute(path) && !path.includes('\0') } /** @@ -160,7 +160,12 @@ export class SandboxPolicyService extends Service { // runtime fact. `workspaceRoot` has NO schema default, so its fallback to // the process cwd is real branching, resolved absolute either way. this.defaultMode = config.mode as SandboxMode - this.workspaceRoot = resolveWorkspaceRoot(config.workspaceRoot ?? process.cwd()) + // Execution-world spelling is preserved; enforcing providers resolve filesystem identity on their host. + const workspaceRoot = config.workspaceRoot ?? process.cwd() + if (!isExecutionWorldPath(workspaceRoot)) { + throw new Error('sandbox-policy: workspace root must be an absolute execution-world path without NUL bytes') + } + this.workspaceRoot = workspaceRoot this.additionalWritableRoots = resolveAdditionalWritableRoots(config.additionalWritableRoots) } @@ -197,6 +202,8 @@ export class SandboxPolicyService extends Service { * snapshotted together; existing operations and processes keep their policy. * @param request - optional session and approved mode override. * @returns the fully resolved per-call mode and absolute workspace root. + * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's recorded cwd is + * relative or contains a NUL byte. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy { const { session } = request @@ -206,12 +213,22 @@ export class SandboxPolicyService extends Service { : resolveAdditionalWritableRoots([...(this.additionalWritableRoots ?? []), ...registrations.values()]) return { mode: request.mode ?? (session === undefined ? undefined : this.overrideOf(session)) ?? this.defaultMode, - workspaceRoot: resolveWorkspaceRoot(session?.header.cwd ?? this.workspaceRoot), + workspaceRoot: this.sessionWorkspaceRoot(session), ...additionalWritableRoots === undefined ? {} : { additionalWritableRoots }, ...session === undefined ? {} : { sessionId: session.id }, } } + /** The session's recorded cwd, or the configured root, as the workspace-write boundary. */ + private sessionWorkspaceRoot(session: Session | undefined): string { + const cwd = session?.header.cwd + if (cwd === undefined) return this.workspaceRoot + if (!isExecutionWorldPath(cwd)) { + throw new SandboxInvalidRootError(cwd, 'the Session working directory must be an absolute execution-world path without NUL bytes', 'sandbox workspace root') + } + return cwd + } + /** * Permit writes under one directory in this Session's future workspace-write * operations. The calling context owns the effect; disposal removes only this diff --git a/packages/sandbox/sandbox-policy/tests/policy.spec.ts b/packages/sandbox/sandbox-policy/tests/policy.spec.ts index 1d4588f49e..954f789c02 100644 --- a/packages/sandbox/sandbox-policy/tests/policy.spec.ts +++ b/packages/sandbox/sandbox-policy/tests/policy.spec.ts @@ -67,6 +67,20 @@ describe('SandboxPolicyService', () => { } }) + it('rejects a session cwd containing a NUL byte with SANDBOX_INVALID_ROOT', async () => { + const cwd = '/invalid\0session' + const ctx = await mounted({ mode: 'workspace-write', workspaceRoot: '/ws' }) + try { + expect(() => ctx.sandboxPolicy.resolve({ session: session('sess-invalid-cwd', cwd) })).toThrow(expect.objectContaining({ + name: 'SandboxInvalidRootError', + code: 'SANDBOX_INVALID_ROOT', + message: `Invalid sandbox workspace root ${JSON.stringify(cwd)}: the Session working directory must be an absolute execution-world path without NUL bytes`, + })) + } finally { + await ctx.fiber.dispose() + } + }) + it('resolves the deployment policy for an agentless call', async () => { const ctx = await mounted({ mode: 'workspace-write', workspaceRoot: '/fallback' }) expect(ctx.sandboxPolicy.resolve()).toEqual({ diff --git a/packages/sandbox/sandbox/src/roots.ts b/packages/sandbox/sandbox/src/roots.ts index 726f3bbfdc..363469ae42 100644 --- a/packages/sandbox/sandbox/src/roots.ts +++ b/packages/sandbox/sandbox/src/roots.ts @@ -19,10 +19,15 @@ import { relative } from 'node:path' import { HarnessError } from '@deepseek-ai/dsh-llm' import type { SandboxExecutionPolicy } from './index.ts' -/** An explicit directory grant cannot be enforced without changing the caller's selected path. */ +/** A workspace root or explicit directory grant cannot be enforced without changing the caller's selected path. */ export class SandboxInvalidRootError extends HarnessError { - constructor(path: string, detail: string) { - super(`Invalid additional writable directory ${JSON.stringify(path)}: ${detail}`, 'SANDBOX_INVALID_ROOT') + /** + * @param path - the rejected path, as the caller spelled it. + * @param detail - why the path cannot be enforced. + * @param subject - the role of the path in the policy, as the message names it. + */ + constructor(path: string, detail: string, subject = 'additional writable directory') { + super(`Invalid ${subject} ${JSON.stringify(path)}: ${detail}`, 'SANDBOX_INVALID_ROOT') this.name = 'SandboxInvalidRootError' } } diff --git a/packages/session/tool-working-directory/README.i18n.yaml b/packages/session/tool-working-directory/README.i18n.yaml index 742c9ffb0a..9e45d5365a 100644 --- a/packages/session/tool-working-directory/README.i18n.yaml +++ b/packages/session/tool-working-directory/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 87d7d2dbd7777429 /deepseek-ai-dsh-tool-working-directory/use-this-package: - en: bb750522dbdb3fef - zh: 85586a5c2137afa9 + en: 83ab57140ebea28e + zh: 213c36a664a21f65 /deepseek-ai-dsh-tool-working-directory/understand-the-implementation: en: f361fe510916fce8 zh: a2127f768ef9ac95 diff --git a/packages/session/tool-working-directory/README.md b/packages/session/tool-working-directory/README.md index 8eadd039a3..379743d651 100644 --- a/packages/session/tool-working-directory/README.md +++ b/packages/session/tool-working-directory/README.md @@ -25,7 +25,7 @@ Read the Session’s current directory or enter an existing directory with the s ## Use this package -Mount alongside `tools` and `workingDirectory`. Call `working_directory({})` to read or `working_directory({ cd: "src" })` to change directory. The tool has no configuration fields. +Mount alongside `tools` and `workingDirectory`. Call `working_directory({})` to read or `working_directory({ cd: "src" })` to change directory. The tool has no configuration fields. A call without a calling Agent fails with `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), an empty `cd` with `ToolArgsError` (`INVALID_ARGS`), and a missing directory with the service's `WorkingDirectoryError` codes. ```yaml - name: '@deepseek-ai/dsh-tool-working-directory' diff --git a/packages/session/tool-working-directory/README.zh.md b/packages/session/tool-working-directory/README.zh.md index 50c4b638fb..5c8cc05bd6 100644 --- a/packages/session/tool-working-directory/README.zh.md +++ b/packages/session/tool-working-directory/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用此包 -与 `tools` 和 `workingDirectory` 一起挂载。调用 `working_directory({})` 读取目录,或调用 `working_directory({ cd: "src" })` 改变目录。此工具没有配置字段。 +与 `tools` 和 `workingDirectory` 一起挂载。调用 `working_directory({})` 读取目录,或调用 `working_directory({ cd: "src" })` 改变目录。此工具没有配置字段。没有调用方 Agent 的调用以 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)失败,`cd` 为空以 `ToolArgsError`(`INVALID_ARGS`)失败,目录不存在时使用服务的 `WorkingDirectoryError` code。 ```yaml - name: '@deepseek-ai/dsh-tool-working-directory' diff --git a/packages/session/tool-working-directory/src/index.ts b/packages/session/tool-working-directory/src/index.ts index f0aa8bc4f0..89022d3e57 100644 --- a/packages/session/tool-working-directory/src/index.ts +++ b/packages/session/tool-working-directory/src/index.ts @@ -4,7 +4,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-working-directory' /** Cordis plugin name. */ @@ -32,7 +32,8 @@ export function apply(ctx: Context): void { render: (_args, value) => [{ type: 'text', text: value.cwd }], }, async execute(args, exec) { - if (exec.agent === undefined) throw new Error('working_directory requires an agent Session') + if (exec.agent === undefined) throw new ToolContextUnavailableError('working_directory requires an agent Session') + if (args.cd === '') throw new ToolArgsError(['cd must not be empty; omit it to read the current directory']) const cwd = args.cd === undefined ? await ctx.workingDirectory.ensure(exec.agent, exec.signal) : await ctx.workingDirectory.set(exec.agent, args.cd, exec.signal) diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index fd50066fe2..3fd77f1c5c 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: e65405026debde7c zh: e12a648eb10ed16b /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: f0458147d29631b1 - zh: 6a288670dd084ffb + en: 82d7372a58bb75c5 + zh: e18ee833daa99581 /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 44ed9ba9dc..1a70cfbe8f 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. Failures are `WorkingDirectoryError` instances: `WORKING_DIRECTORY_INVALID` for an empty or malformed path, `WORKING_DIRECTORY_NOT_FOUND` when a requested change names no existing directory, and `WORKING_DIRECTORY_UNAVAILABLE` when neither the current directory nor the original project exists or the service has been disposed. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 9561d73972..b5f07d5577 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。失败均为 `WorkingDirectoryError`:路径为空或格式错误时为 `WORKING_DIRECTORY_INVALID`,请求切换到不存在的目录时为 `WORKING_DIRECTORY_NOT_FOUND`,当前目录与原始项目都不存在或服务已释放时为 `WORKING_DIRECTORY_UNAVAILABLE`。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 diff --git a/packages/session/working-directory/src/error.ts b/packages/session/working-directory/src/error.ts new file mode 100644 index 0000000000..ec2a2ef7a2 --- /dev/null +++ b/packages/session/working-directory/src/error.ts @@ -0,0 +1,34 @@ +/** Machine-routable Session working-directory failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-llm' + +/** + * Every {@link WorkingDirectoryError} code: + * - `WORKING_DIRECTORY_INVALID` — a requested directory is empty or otherwise malformed. + * - `WORKING_DIRECTORY_NOT_FOUND` — the requested directory does not exist or is not a directory; the caller picks another path. + * - `WORKING_DIRECTORY_UNAVAILABLE` — neither the current directory nor the original project exists, or the owning service was disposed. + */ +export const WORKING_DIRECTORY_ERROR_CODES = [ + 'WORKING_DIRECTORY_INVALID', + 'WORKING_DIRECTORY_NOT_FOUND', + 'WORKING_DIRECTORY_UNAVAILABLE', +] as const + +/** One code from {@link WORKING_DIRECTORY_ERROR_CODES}. */ +export type WorkingDirectoryErrorCode = typeof WORKING_DIRECTORY_ERROR_CODES[number] + +/** Working-directory failure carrying a stable {@link WorkingDirectoryErrorCode}. */ +export class WorkingDirectoryError extends HarnessError { + override readonly code: WorkingDirectoryErrorCode + + /** + * @param message - names the directory and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: WorkingDirectoryErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'WorkingDirectoryError' + this.code = code + } +} diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 62c3750c2c..7a0f66ede6 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -13,6 +13,9 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-system-prompt' +import { WorkingDirectoryError } from './error.ts' + +export { WORKING_DIRECTORY_ERROR_CODES, WorkingDirectoryError, type WorkingDirectoryErrorCode } from './error.ts' declare module '@deepseek-ai/cordis' { interface Events { @@ -125,7 +128,7 @@ export class WorkingDirectoryService extends Service { return assembly }, { prepend: true }) ctx.effect(() => async () => { - this.lifecycle.abort(new Error('working-directory service disposed')) + this.lifecycle.abort(new WorkingDirectoryError('working-directory service disposed', 'WORKING_DIRECTORY_UNAVAILABLE')) await Promise.allSettled(this.operations) }) } @@ -145,7 +148,8 @@ export class WorkingDirectoryService extends Service { * @param signal - cancellation for filesystem inspection. * @returns the existing directory; recovery is committed before fulfillment. * A notice failure is warned without reverting the committed state. - * @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_UNAVAILABLE` when the original project is also + * unavailable or the service is disposed, or the rejection of a `working-directory/access` listener. */ ensure(agent: Agent, signal?: AbortSignal): Promise { return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path: null, signal: control }, async () => { @@ -161,7 +165,10 @@ export class WorkingDirectoryService extends Service { return current } const original = agent.session.header.cwd ?? this.defaultDirectory - const restored = await this.directory(original, original, control) + const restored = await this.directory(original, original, control, () => new WorkingDirectoryError( + `working-directory: directory does not exist: ${JSON.stringify(original)}; the current working directory ${JSON.stringify(current)} is also unavailable`, + 'WORKING_DIRECTORY_UNAVAILABLE', + )) this.commit(agent, restored, true, control) return restored })) @@ -174,11 +181,13 @@ export class WorkingDirectoryService extends Service { * @param signal - cancellation before the durable change. * @returns the canonical absolute directory, committed before fulfillment. * A notice failure is warned; the next request still receives the committed directory. - * @throws when the requested path is not an existing directory. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_INVALID` for an empty path and + * `WORKING_DIRECTORY_NOT_FOUND` when the path is not an existing directory, or the rejection of a + * `working-directory/access` listener. */ set(agent: Agent, path: string, signal?: AbortSignal): Promise { return this.serialize(agent, signal, control => this.ctx.waterfall('working-directory/access', { agent, path, signal: control }, async () => { - if (path.length === 0) throw new Error('working-directory: cd must not be empty') + if (path.length === 0) throw new WorkingDirectoryError('working-directory: cd must not be empty', 'WORKING_DIRECTORY_INVALID') const directory = await this.directory(path, this.get(agent.session), control) this.commit(agent, directory, false, control) return directory @@ -189,13 +198,19 @@ export class WorkingDirectoryService extends Service { return `Current working directory: ${JSON.stringify(this.get(session))}.` } - private async directory(path: string, cwd: string, signal: AbortSignal): Promise { + private async directory( + path: string, + cwd: string, + signal: AbortSignal, + missing = (): WorkingDirectoryError => new WorkingDirectoryError( + `working-directory: directory does not exist: ${JSON.stringify(path)}`, + 'WORKING_DIRECTORY_NOT_FOUND', + ), + ): Promise { const target = await this.ctx.fs.resolve(path, { cwd, signal }) const info = await this.ctx.fs.stat(target, signal) signal.throwIfAborted() - if (info?.type !== 'directory') { - throw new Error(`working-directory: directory does not exist: ${JSON.stringify(path)}`) - } + if (info?.type !== 'directory') throw missing() return this.ctx.fs.processPath(target) } diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index 22fb99af47..d4769979cf 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -115,6 +115,11 @@ describe('Session working directories', () => { const agent = await f.harness.create(SessionId('removed-origin'), {}, { cwd: origin }) await rm(origin, { recursive: true }) await expect(f.ctx.workingDirectory.ensure(agent)).rejects.toThrow('directory does not exist') + await expect(f.ctx.workingDirectory.ensure(agent)).rejects.toMatchObject({ + name: 'WorkingDirectoryError', + code: 'WORKING_DIRECTORY_UNAVAILABLE', + message: expect.stringContaining('is also unavailable') as string, + }) await expect(f.ctx.workingDirectory.set(agent, f.root)).resolves.toBe(f.root) }) @@ -122,7 +127,9 @@ describe('Session working directories', () => { await using f = await fixture() await writeFile(join(f.root, 'file'), '') await expect(f.ctx.workingDirectory.set(f.agent, 'file')).rejects.toThrow('directory does not exist') + await expect(f.ctx.workingDirectory.set(f.agent, 'file')).rejects.toMatchObject({ name: 'WorkingDirectoryError', code: 'WORKING_DIRECTORY_NOT_FOUND' }) await expect(f.ctx.workingDirectory.set(f.agent, '')).rejects.toThrow('cd must not be empty') + await expect(f.ctx.workingDirectory.set(f.agent, '')).rejects.toMatchObject({ name: 'WorkingDirectoryError', code: 'WORKING_DIRECTORY_INVALID' }) const controller = new AbortController() controller.abort(new Error('cancelled directory change')) await expect(f.ctx.workingDirectory.set(f.agent, f.root, controller.signal)).rejects.toThrow('cancelled directory change') @@ -277,6 +284,7 @@ describe('Session working directories', () => { expect(f.agent.session.snapshotEvents().filter(event => event.type === 'working-directory/change')).toEqual([]) expect(f.harness.claim(f.agent, 'next-step', 1)).toEqual([]) await expect(directories.ensure(f.agent)).rejects.toThrow('working-directory service disposed') + await expect(directories.ensure(f.agent)).rejects.toMatchObject({ name: 'WorkingDirectoryError', code: 'WORKING_DIRECTORY_UNAVAILABLE' }) expect(probe).toHaveBeenCalledOnce() } finally { release.resolve(undefined) @@ -352,7 +360,18 @@ describe('Session working directories', () => { }) expect(await execute({})).toMatchObject({ value: { cwd: f.root }, isError: false }) expect(await execute({ cd: 'child' })).toMatchObject({ value: { cwd: join(f.root, 'child') }, isError: false }) - expect(await execute({}, false)).toMatchObject({ isError: true }) + expect(await execute({}, false)).toMatchObject({ + isError: true, + error: { info: { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } }, + }) + expect(await execute({ cd: '' })).toMatchObject({ + isError: true, + error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + }) + expect(await execute({ cd: 'missing' })).toMatchObject({ + isError: true, + error: { info: { name: 'WorkingDirectoryError', code: 'WORKING_DIRECTORY_NOT_FOUND' } }, + }) await fiber.dispose() expect(f.ctx.tools.schemas().some(tool => tool.name === 'working_directory')).toBe(false) }) From c14b6860b4ad7fa67a6e15c17a477f11b74d5e7f Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:09:13 +0800 Subject: [PATCH 045/438] feat(jobs): code registry refusals and job tool argument failures jobs-local throws JobError for a missing controller (JOB_CONTROLLER_UNAVAILABLE), the owner limit (JOB_LIMIT_REACHED), a dead owner (JOB_OWNER_NOT_LIVE), an unknown id (JOB_NOT_FOUND), and a foreign caller (JOB_FOREIGN_SESSION), and ToolContextUnavailableError for an owned registration without the agent registry. An aborted wait rejects with an error named AbortError, so the tool registry records it as ABORTED. job_output and job_kill report an empty job_id, and job_output a non-positive timeout_ms, as ToolArgsError. Refs #7869 --- packages/jobs/jobs-local/README.i18n.yaml | 4 +-- packages/jobs/jobs-local/README.md | 2 +- packages/jobs/jobs-local/README.zh.md | 2 +- packages/jobs/jobs-local/package.json | 6 ++-- packages/jobs/jobs-local/src/index.ts | 30 +++++++++++++------ packages/jobs/jobs-local/tests/jobs.spec.ts | 14 ++++++++- packages/jobs/jobs-local/tsconfig.json | 3 ++ packages/jobs/tool-jobs/src/index.ts | 13 ++++++-- .../jobs/tool-jobs/tests/tool-jobs.spec.ts | 13 ++++++-- pnpm-lock.yaml | 3 ++ 10 files changed, 68 insertions(+), 22 deletions(-) diff --git a/packages/jobs/jobs-local/README.i18n.yaml b/packages/jobs/jobs-local/README.i18n.yaml index dc37d78e1e..93045928da 100644 --- a/packages/jobs/jobs-local/README.i18n.yaml +++ b/packages/jobs/jobs-local/README.i18n.yaml @@ -33,8 +33,8 @@ en: ae926795d8aaa88f zh: 0e6ec0265eefccf7 /deepseek-ai-dsh-jobs-local/use-this-package/what-can-go-wrong: - en: e1f4511c458dff3b - zh: bea247c2a365a646 + en: 3737bc2cfa7f7012 + zh: 07bc090cbfa44584 /deepseek-ai-dsh-jobs-local/understand-the-implementation: en: f782557ca8da3138 zh: e8f0082b9692cacc diff --git a/packages/jobs/jobs-local/README.md b/packages/jobs/jobs-local/README.md index 3f0f80d296..1f753e7f93 100644 --- a/packages/jobs/jobs-local/README.md +++ b/packages/jobs/jobs-local/README.md @@ -64,7 +64,7 @@ Lifecycle facts are appended synchronously at the registration or settlement com ### What can go wrong -Starting work fails without a controller that serves the owner — loading `dsh-tool-jobs` attaches one, and `start()` otherwise refuses with a message naming it. A producer cancel that returns without settling `done` stays indistinguishable from a slow stop and can stall teardown while holding one capacity slot. Live registry records disappear when the harness process exits; persisted lifecycle events remain. +Starting work fails without a controller that serves the owner — loading `dsh-tool-jobs` attaches one, and `start()` otherwise refuses with a message naming it. Refusals are `JobError` instances: `JOB_CONTROLLER_UNAVAILABLE`, `JOB_LIMIT_REACHED`, `JOB_OWNER_NOT_LIVE`, `JOB_NOT_FOUND`, and `JOB_FOREIGN_SESSION`; an owned registration without the agent registry throws `ToolContextUnavailableError`. A wait whose signal aborts rejects with an error named `AbortError`. A producer cancel that returns without settling `done` stays indistinguishable from a slow stop and can stall teardown while holding one capacity slot. Live registry records disappear when the harness process exits; persisted lifecycle events remain. ----- diff --git a/packages/jobs/jobs-local/README.zh.md b/packages/jobs/jobs-local/README.zh.md index c00a6527d2..30dc26d3b0 100644 --- a/packages/jobs/jobs-local/README.zh.md +++ b/packages/jobs/jobs-local/README.zh.md @@ -64,7 +64,7 @@ kind: "package-reference" ### 可能出什么问题 -没有服务于所有者的控制器时无法启动工作——加载 `dsh-tool-jobs` 即附加一个,否则 `start()` 会以指出它的消息拒绝。返回但始终未结算 `done` 的生产方取消与缓慢停止无法区分,可能使销毁停滞并持续占用一个容量名额。运行期注册表记录会在 harness 进程退出时消失;已持久化的生命周期事件会保留。 +没有服务于所有者的控制器时无法启动工作——加载 `dsh-tool-jobs` 即附加一个,否则 `start()` 会以指出它的消息拒绝。拒绝均为 `JobError`:`JOB_CONTROLLER_UNAVAILABLE`、`JOB_LIMIT_REACHED`、`JOB_OWNER_NOT_LIVE`、`JOB_NOT_FOUND` 与 `JOB_FOREIGN_SESSION`;没有 agent 注册表时登记带所有者的 job 会抛出 `ToolContextUnavailableError`。signal 中止的等待以名为 `AbortError` 的错误拒绝。返回但始终未结算 `done` 的生产方取消与缓慢停止无法区分,可能使销毁停滞并持续占用一个容量名额。运行期注册表记录会在 harness 进程退出时消失;已持久化的生命周期事件会保留。 ----- diff --git a/packages/jobs/jobs-local/package.json b/packages/jobs/jobs-local/package.json index b635f6289d..b7e73d4753 100644 --- a/packages/jobs/jobs-local/package.json +++ b/packages/jobs/jobs-local/package.json @@ -36,7 +36,8 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -51,6 +52,7 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-tools": "workspace:*" } } diff --git a/packages/jobs/jobs-local/src/index.ts b/packages/jobs/jobs-local/src/index.ts index daa4ce0db3..4e1a0959f6 100644 --- a/packages/jobs/jobs-local/src/index.ts +++ b/packages/jobs/jobs-local/src/index.ts @@ -17,7 +17,8 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { ScopedLayers, scopeOf } from '@deepseek-ai/dsh-scope' import type { SessionId } from '@deepseek-ai/dsh-session' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' -import { JobRegistry, JobId } from '@deepseek-ai/dsh-jobs' +import { JobError, JobRegistry, JobId } from '@deepseek-ai/dsh-jobs' +import { ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { JobAppendOptions, JobEvent, JobEvents, JobHandle, JobKind, JobOutcome, JobOutputRead, JobOutputSource, JobRead, JobRegisteredData, JobSettleCause, JobSettledData, JobSpec, JobStatus, JobToolCall, JobView, @@ -117,6 +118,13 @@ interface TrackedJob { spillPaths: (string | undefined)[] } +/** The cancellation a wait reports when its caller's signal aborts; the name lets the tool registry classify it. */ +function waitAborted(): Error { + const error = new Error('wait aborted') + error.name = 'AbortError' + return error +} + /** True for the three terminal {@link JobStatus} values. */ function isTerminal(status: JobStatus): boolean { return status === 'completed' || status === 'killed' || status === 'failed' @@ -207,7 +215,10 @@ export class LocalJobRegistry extends JobRegistry { start(spec: JobSpec): JobId { const owner = this.resolveOwner(spec.owner) if (!this.servesOwner(owner)) { - throw new Error('background jobs unavailable: no job controller serves this agent (load @deepseek-ai/dsh-tool-jobs in its composition)') + throw new JobError( + 'background jobs unavailable: no job controller serves this agent (load @deepseek-ai/dsh-tool-jobs in its composition)', + 'JOB_CONTROLLER_UNAVAILABLE', + ) } if (spec.kind.length === 0) throw new Error('invalid job kind: expected a non-empty string') if (spec.label.length === 0) throw new Error('invalid job label: expected a non-empty string') @@ -219,8 +230,9 @@ export class LocalJobRegistry extends JobRegistry { const active = this.activeJobCount(owner) if (active >= this.maxConcurrentJobsPerOwner) { - throw new Error( + throw new JobError( `background job limit reached for this owner (limit: ${this.maxConcurrentJobsPerOwner}); use job_kill to stop an unneeded job, wait for it to finish, then retry`, + 'JOB_LIMIT_REACHED', ) } @@ -362,11 +374,11 @@ export class LocalJobRegistry extends JobRegistry { if (session === undefined) return undefined const agents = this.selfCtx.get('agents') if (agents === undefined) { - throw new Error('background job ownership requires the agent registry (load @deepseek-ai/dsh-agent)') + throw new ToolContextUnavailableError('background job ownership requires the agent registry (load @deepseek-ai/dsh-agent)') } const owner = agents.get(session) if (owner === undefined) { - throw new Error(`session "${session}" has no live agent (background job owner must be live)`) + throw new JobError(`session "${session}" has no live agent (background job owner must be live)`, 'JOB_OWNER_NOT_LIVE') } return owner } @@ -397,7 +409,7 @@ export class LocalJobRegistry extends JobRegistry { /** Look up a job and enforce caller access. */ private expect(id: JobId, caller?: SessionId): TrackedJob { const job = this.store.get(id) - if (job === undefined) throw new Error(`unknown job ${id}`) + if (job === undefined) throw new JobError(`unknown job ${id}`, 'JOB_NOT_FOUND') this.assertAccess(job, caller) return job } @@ -409,7 +421,7 @@ export class LocalJobRegistry extends JobRegistry { */ private assertAccess(job: TrackedJob, caller: SessionId | undefined): void { if (job.owner !== undefined && job.owner.id !== caller) { - throw new Error(`job ${job.id} belongs to another session`) + throw new JobError(`job ${job.id} belongs to another session`, 'JOB_FOREIGN_SESSION') } } @@ -498,7 +510,7 @@ export class LocalJobRegistry extends JobRegistry { throw new Error(`invalid wait timeout: expected a positive number of milliseconds, got ${JSON.stringify(timeoutMs)}`) } if (!isTerminal(job.status)) { - if (signal?.aborted) throw new Error('wait aborted') + if (signal?.aborted) throw waitAborted() // The scoped deadline distinguishes a successful wait timeout from // caller cancellation and clears its timer on every exit. using d = deadline(signal, timeoutMs, TASK_WAIT_TIMEOUT) @@ -517,7 +529,7 @@ export class LocalJobRegistry extends JobRegistry { if (timeoutOf(d.signal, TASK_WAIT_TIMEOUT) !== undefined) { resolve() } else { - reject(new Error('wait aborted')) + reject(waitAborted()) } } job.waitResolvers.add(onSettled) diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index 0027549fb1..521c7647d6 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -11,7 +11,7 @@ import { bindScopeParent, createScope, scopeOf } from '@deepseek-ai/dsh-scope' import type { ScopeKey } from '@deepseek-ai/dsh-scope' import { JobId } from '@deepseek-ai/dsh-jobs' import type { - JobEvent, JobEventFilter, JobHandle, JobHooks, JobKind, JobOutcome, JobOutputSource, JobSpec, JobView, + JobErrorCode, JobEvent, JobEventFilter, JobHandle, JobHooks, JobKind, JobOutcome, JobOutputSource, JobSpec, JobView, } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry, { type Config as JobsConfig } from '@deepseek-ai/dsh-jobs-local' import { unsupportedModel, unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -172,6 +172,9 @@ function scriptedSource(reads: { text: string; lossy?: boolean }[], channel?: 's } } +/** The structured identity a registry refusal carries. */ +const jobError = (code: JobErrorCode): { name: 'JobError'; code: JobErrorCode } => ({ name: 'JobError', code }) + describe('LocalJobRegistry.start', () => { it('preserves the SessionId brand on public owner projections', () => { expectTypeOf().toEqualTypeOf() @@ -182,6 +185,7 @@ describe('LocalJobRegistry.start', () => { await ctx.plugin(LocalJobRegistry) expect(() => ctx.jobs.start(producer().spec)) .toThrow('background jobs unavailable: no job controller serves this agent (load @deepseek-ai/dsh-tool-jobs in its composition)') + expect(() => ctx.jobs.start(producer().spec)).toThrow(expect.objectContaining(jobError('JOB_CONTROLLER_UNAVAILABLE'))) }) it('refuses an owner whose own composition attaches no controller', async () => { @@ -255,6 +259,7 @@ describe('LocalJobRegistry.start', () => { const run = vi.fn((job: JobHandle) => blocked.spec.run(job)) expect(() => ctx.jobs.start({ ...blocked.spec, run })) .toThrow('background job limit reached for this owner (limit: 10)') + expect(() => ctx.jobs.start({ ...blocked.spec, run })).toThrow(expect.objectContaining(jobError('JOB_LIMIT_REACHED'))) expect(run).not.toHaveBeenCalled() for (const job of live) job.settle({ status: 'completed' }) }) @@ -414,6 +419,7 @@ describe('LocalJobRegistry reads and settlement', () => { const ctx = await harness() expect(() => ctx.jobs.read(JobId('bash-99'))).toThrow('unknown job bash-99') expect(() => ctx.jobs.get(JobId('bash-99'))).toThrow('unknown job bash-99') + expect(() => ctx.jobs.get(JobId('bash-99'))).toThrow(expect.objectContaining(jobError('JOB_NOT_FOUND'))) }) it('announces settlement once with containment across listeners', async () => { @@ -601,11 +607,13 @@ describe('LocalJobRegistry.wait', () => { const wait = ctx.jobs.wait(id, 5_000, undefined, controller.signal) controller.abort() await expect(wait).rejects.toThrow('wait aborted') + await expect(wait).rejects.toMatchObject({ name: 'AbortError' }) expect(ctx.jobs.list()[0]).toMatchObject({ status: 'running' }) const preAborted = new AbortController() preAborted.abort() await expect(ctx.jobs.wait(id, 5_000, undefined, preAborted.signal)).rejects.toThrow('wait aborted') + await expect(ctx.jobs.wait(id, 5_000, undefined, preAborted.signal)).rejects.toMatchObject({ name: 'AbortError' }) }) it('an abort racing settlement in the same tick rejects the wait and leaves the settlement intact', async () => { @@ -736,6 +744,7 @@ describe('LocalJobRegistry owner isolation', () => { expect(() => foreign.kill(owned, other.id)).toThrow('belongs to another session') await expect(foreign.wait(owned, 10, other.id)).rejects.toThrow('belongs to another session') expect(() => ctx.jobs.read(owned)).toThrow('belongs to another session') + expect(() => ctx.jobs.read(owned)).toThrow(expect.objectContaining(jobError('JOB_FOREIGN_SESSION'))) }) it('list() shows only caller-owned plus unowned jobs', async () => { @@ -758,6 +767,8 @@ describe('LocalJobRegistry owner isolation', () => { ctx.jobs.attachController('test-controller') expect(() => ctx.jobs.start({ ...producer().spec, owner: SessionId('a') })) .toThrow('background job ownership requires the agent registry') + expect(() => ctx.jobs.start({ ...producer().spec, owner: SessionId('a') })) + .toThrow(expect.objectContaining({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })) // The failed registration mutated nothing: no stored job. expect(ctx.jobs.list()).toEqual([]) expect(ctx.jobs.start(producer().spec)).toMatch(/^bash-[0-9a-f]{16}$/) @@ -770,6 +781,7 @@ describe('LocalJobRegistry owner isolation', () => { // Owner resolution precedes registry mutation and cleanup attachment. expect(() => ctx.jobs.start(producer({ owner: ghost }).spec)) .toThrow('has no live agent') + expect(() => ctx.jobs.start(producer({ owner: ghost }).spec)).toThrow(expect.objectContaining(jobError('JOB_OWNER_NOT_LIVE'))) expect(ctx.jobs.list(ghost.id)).toEqual([]) // A later valid registration must still attach cleanup for the live instance. diff --git a/packages/jobs/jobs-local/tsconfig.json b/packages/jobs/jobs-local/tsconfig.json index f94627dd8f..892c4da43e 100644 --- a/packages/jobs/jobs-local/tsconfig.json +++ b/packages/jobs/jobs-local/tsconfig.json @@ -28,6 +28,9 @@ }, { "path": "../jobs" + }, + { + "path": "../../core/tools" } ] } diff --git a/packages/jobs/tool-jobs/src/index.ts b/packages/jobs/tool-jobs/src/index.ts index dff4681cf1..8da4efea17 100644 --- a/packages/jobs/tool-jobs/src/index.ts +++ b/packages/jobs/tool-jobs/src/index.ts @@ -15,7 +15,7 @@ import z from '@deepseek-ai/schemastery' import { boundContextSummary, createUserMessage, type ContentBlock } from '@deepseek-ai/dsh-llm' import type { ContextFormed, MessageId } from '@deepseek-ai/dsh-llm' import { TextRetainer } from '@deepseek-ai/dsh-output-retention' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools' import { JobId } from '@deepseek-ai/dsh-jobs' import type { JobEvent, JobView, JobRead } from '@deepseek-ai/dsh-jobs' @@ -208,7 +208,7 @@ function visibleOutputLimit(ctx: Context, exec: ToolExecution): number | undefin /** Validate the non-empty constraint that ParameterSchemaSpec cannot express. */ function validateJobId(value: string): JobId { if (value.length === 0) { - throw new Error(`invalid job_id: expected a non-empty string, got ${JSON.stringify(value)}`) + throw new ToolArgsError([`invalid job_id: expected a non-empty string, got ${JSON.stringify(value)}`]) } return JobId(value) } @@ -457,6 +457,9 @@ export function apply(ctx: Context, config: Config): void { }, async execute(args, exec) { const id = validateJobId(args.job_id) + if (args.timeout_ms !== undefined && (!Number.isFinite(args.timeout_ms) || args.timeout_ms <= 0)) { + throw new ToolArgsError([`invalid timeout_ms: expected a positive number of milliseconds, got ${JSON.stringify(args.timeout_ms)}`]) + } const jobs = ctx.jobs const agent = exec.agent // A wait this execution ends on next-step input claims the read that @@ -509,7 +512,11 @@ export function apply(ctx: Context, config: Config): void { // An input released this wait, so the read below carries the // current state; a cancellation leaves no consumer for that read, // and the claim's release delivers the settlement it withheld. - if (exec.signal.aborted) throw new Error('wait aborted') + if (exec.signal.aborted) { + const aborted = new Error('wait aborted') + aborted.name = 'AbortError' + throw aborted + } } finally { unsubscribe() } diff --git a/packages/jobs/tool-jobs/tests/tool-jobs.spec.ts b/packages/jobs/tool-jobs/tests/tool-jobs.spec.ts index 4d2592a880..e782de33e2 100644 --- a/packages/jobs/tool-jobs/tests/tool-jobs.spec.ts +++ b/packages/jobs/tool-jobs/tests/tool-jobs.spec.ts @@ -569,10 +569,17 @@ describe('job_output', () => { it('rejects an empty or unknown job id as an errored result', async () => { const { ctx } = await setup() - expect((await call(ctx, 'job_output', { job_id: '' })).isError).toBe(true) + expect(await call(ctx, 'job_output', { job_id: '' })).toMatchObject({ + isError: true, + error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + }) const unknown = await call(ctx, 'job_output', { job_id: 'bash-99' }) - expect(unknown.isError).toBe(true) + expect(unknown).toMatchObject({ isError: true, error: { info: { name: 'JobError', code: 'JOB_NOT_FOUND' } } }) expect(text(unknown)).toContain('unknown job bash-99') + expect(await call(ctx, 'job_output', { job_id: 'bash-99', wait: true, timeout_ms: 0 })).toMatchObject({ + isError: true, + error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } }, + }) }) }) @@ -1153,7 +1160,7 @@ describe('completion notices', () => { await tick() aborter.abort() const result = await pending - expect(result.isError).toBe(true) + expect(result).toMatchObject({ isError: true, error: { info: { name: 'AbortError', code: 'ABORTED' } } }) expect(text(result)).toContain('wait aborted') p.settle({ status: 'completed' }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1884575900..90d655e2af 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13140,6 +13140,9 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:* version: link:../../util/timeout + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools packages/jobs/tool-jobs: dependencies: From dbcab765f95ada1fb0eb09ba304bfefcd86d4513 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:29:33 +0800 Subject: [PATCH 046/438] fix(shell): keep coded failures on the bash and pwsh job path A foreground bash or pwsh call that waits on a job rethrew a failed preparation as new Error(view.detail), dropping the original class and code, so even SandboxUnavailableError reached tool/result without error.name or error.code. processJob now keeps the original error for a failed job and the tool rethrows it; launch and spawn rejections on every path keep a HarnessError's identity, and a platform spawn error becomes SubprocessError (SUBPROCESS_SPAWN_NOT_FOUND or _SPAWN_FAILED). Argument violations are ToolArgsError, a missing sandboxing executor for sandbox_permissions is SandboxEscalationError SANDBOX_ESCALATION_UNAVAILABLE, a disabled background call is JobError JOB_BACKGROUND_DISABLED, and a missing job runtime is ToolContextUnavailableError. Refs #7869 --- packages/shell/tool-bash/README.i18n.yaml | 4 +- packages/shell/tool-bash/README.md | 2 +- packages/shell/tool-bash/README.zh.md | 2 +- packages/shell/tool-bash/package.json | 6 +- packages/shell/tool-bash/src/background.ts | 21 ++++++- packages/shell/tool-bash/src/index.ts | 59 ++++++++++++++----- .../shell/tool-bash/tests/background.spec.ts | 44 +++++++++++++- packages/shell/tool-bash/tests/tools.spec.ts | 44 ++++++++++++-- packages/shell/tool-bash/tsconfig.json | 3 + packages/shell/tool-pwsh/README.i18n.yaml | 4 +- packages/shell/tool-pwsh/README.md | 2 +- packages/shell/tool-pwsh/README.zh.md | 2 +- packages/shell/tool-pwsh/package.json | 6 +- packages/shell/tool-pwsh/src/background.ts | 21 ++++++- packages/shell/tool-pwsh/src/index.ts | 59 ++++++++++++++----- .../shell/tool-pwsh/tests/background.spec.ts | 51 +++++++++++++++- packages/shell/tool-pwsh/tests/tools.spec.ts | 44 +++++++++++++- packages/shell/tool-pwsh/tsconfig.json | 3 + pnpm-lock.yaml | 6 ++ 19 files changed, 322 insertions(+), 61 deletions(-) diff --git a/packages/shell/tool-bash/README.i18n.yaml b/packages/shell/tool-bash/README.i18n.yaml index c1244306b1..625910149b 100644 --- a/packages/shell/tool-bash/README.i18n.yaml +++ b/packages/shell/tool-bash/README.i18n.yaml @@ -111,8 +111,8 @@ en: 2d4f2c8605eccab3 zh: 67f1f0218f73c6bf /deepseek-ai-dsh-tool-bash/model-experience/tool-errors/what-the-model-sees: - en: d6d7068e23fc1b93 - zh: 515e8aa586415179 + en: f4cebcfd09cd3b13 + zh: 4e3954f417b4a9ed /deepseek-ai-dsh-tool-bash/model-experience/tool-errors/token-effect: en: a3a78ef476ec5e56 zh: dd2c8ad0f69e8ff1 diff --git a/packages/shell/tool-bash/README.md b/packages/shell/tool-bash/README.md index 045344c881..411d5da79f 100644 --- a/packages/shell/tool-bash/README.md +++ b/packages/shell/tool-bash/README.md @@ -196,7 +196,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the approval availability/rejection/cancellation variants, and `tool call aborted`. +Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the approval availability/rejection/cancellation variants, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`). #### Token effect diff --git a/packages/shell/tool-bash/README.zh.md b/packages/shell/tool-bash/README.zh.md index 53d2b1984e..7f222c91aa 100644 --- a/packages/shell/tool-bash/README.zh.md +++ b/packages/shell/tool-bash/README.zh.md @@ -196,7 +196,7 @@ renderer 输出依数据而定的 stdout 尾部,再输出可选的 `[stderr]` #### 模型看到什么 -验证与策略失败统一为 `Error: `。本包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、升权配对失败、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、审批不可用/拒绝/取消变体,以及 `tool call aborted`。 +验证与策略失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、审批不可用/拒绝/取消变体,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`)。 #### Token 影响 diff --git a/packages/shell/tool-bash/package.json b/packages/shell/tool-bash/package.json index 3d7102e3a9..b2314e05f9 100644 --- a/packages/shell/tool-bash/package.json +++ b/packages/shell/tool-bash/package.json @@ -43,7 +43,8 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -73,6 +74,7 @@ "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-session-projection": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*" } } diff --git a/packages/shell/tool-bash/src/background.ts b/packages/shell/tool-bash/src/background.ts index 49da48b00b..8835c6603c 100644 --- a/packages/shell/tool-bash/src/background.ts +++ b/packages/shell/tool-bash/src/background.ts @@ -11,6 +11,16 @@ import { escalationHintMarker, sandboxDenialMarker } from '@deepseek-ai/dsh-sand import type { ShellProcess, ShellSandboxInfo } from '@deepseek-ai/dsh-shell' import type { JobChunk, JobHooks, JobOutcome, JobOutputSource } from '@deepseek-ai/dsh-jobs' +/** Job hooks plus the original error of a job that failed before its process produced an outcome. */ +export interface ProcessJobHooks extends JobHooks { + /** + * The error that ended a `failed` job, kept with its own class and code; + * undefined while the job runs and for a completed or killed job. + * @returns the original failure, boxed so any thrown value is preserved. + */ + failure(): { error: unknown } | undefined +} + /** * Sandbox facts worth the terminal detail: a runner that never ran the * command, or a denial (with the escalation hint this composition offers). @@ -94,14 +104,16 @@ export function ringDelta(chunks: readonly JobChunk[]): string { * Adapt asynchronous shell preparation after job admission without exposing a partial process. * @param start - starts the process with job-owned cancellation. * @param outcome - projects the settled process into the job outcome. - * @returns synchronous job hooks whose completion includes preparation and process settlement. + * @returns synchronous job hooks whose completion includes preparation and process settlement, + * and the original error of a failed preparation for a caller that reports it. */ export function processJob( start: (signal: AbortSignal) => Promise, outcome: (process: ShellProcess) => JobOutcome, -): JobHooks { +): ProcessJobHooks { const controller = new AbortController() let process: ShellProcess | undefined + let failure: { error: unknown } | undefined const done: Promise = (async () => { try { process = await start(controller.signal) @@ -112,8 +124,10 @@ export function processJob( } return outcome(process) } catch (error: unknown) { + const killed = controller.signal.aborted && process === undefined + if (!killed) failure = { error } return { - status: controller.signal.aborted && process === undefined ? 'killed' : 'failed', + status: killed ? 'killed' : 'failed', detail: error instanceof Error ? error.message : String(error), } } @@ -125,5 +139,6 @@ export function processJob( process?.kill() }, done, + failure: () => failure, } } diff --git a/packages/shell/tool-bash/src/index.ts b/packages/shell/tool-bash/src/index.ts index 39a2a20369..46554fc192 100644 --- a/packages/shell/tool-bash/src/index.ts +++ b/packages/shell/tool-bash/src/index.ts @@ -16,14 +16,16 @@ import { FiberState } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { isAbsolute, sep } from 'node:path' -import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, TerminalCallView, ToolDefinition, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' import { HarnessError } from '@deepseek-ai/dsh-llm' +import { JobError } from '@deepseek-ai/dsh-jobs' import type { JobId, JobRegistry, JobView } from '@deepseek-ai/dsh-jobs' import type {} from '@deepseek-ai/dsh-user-approval' import type {} from '@deepseek-ai/dsh-shell-env' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' -import { ESCALATION_TARGETS, approveEscalation, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' +import { ESCALATION_TARGETS, SandboxEscalationError, approveEscalation, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' +import { subprocessSpawnFailure } from '@deepseek-ai/dsh-subprocess' import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-shell' import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellRunResult } from '@deepseek-ai/dsh-shell' @@ -72,13 +74,13 @@ interface BashToolArgs { function validateBashArgs(args: BashToolArgs, effectiveMode: SandboxMode | undefined): void { if (args.command.trim().length === 0) { - throw new Error('invalid command: expected a non-empty string') + throw new ToolArgsError(['invalid command: expected a non-empty string']) } if (args.description.trim().length === 0) { - throw new Error('invalid description: expected a non-empty string') + throw new ToolArgsError(['invalid description: expected a non-empty string']) } if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { - throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`) + throw new ToolArgsError([`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`]) } if (args.sandbox_permissions !== undefined && args.sandbox_permissions === effectiveMode) return const justification = args.sandbox_permissions === undefined && args.justification?.trim() === '' @@ -185,11 +187,23 @@ function toolAborted(): HarnessError { return error } +/** + * Report a launch or preparation rejection as this tool's failure. A coded + * error keeps its class and code; this call's cancellation stays as thrown so + * the registry records it as aborted; any other value is classified as a + * subprocess spawn failure with the original as `cause`. + */ +function launchFailure(error: unknown, signal: AbortSignal): unknown { + return signal.aborted ? error : subprocessSpawnFailure(error, 'bash') +} + /** A registered command: its id, the process once the starter spawned it, and the reason an outside kill gave. */ interface StartedJob { readonly id: JobId readonly process: () => ShellExecution | undefined readonly stopped: () => string | undefined + /** The original error of a registration whose preparation failed before the process published. */ + readonly failure: () => { error: unknown } | undefined } /** Canonical background-handle properties shared by the bash output union. */ @@ -232,7 +246,10 @@ export function apply(ctx: Context, config: Config = {}): void { standingPolicy: SandboxExecutionPolicy | undefined, ): Promise => { if (escalationModes.length === 0) { - throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)') + throw new SandboxEscalationError( + 'sandbox_permissions is not available in this composition (no sandboxing executor to escalate)', + 'SANDBOX_ESCALATION_UNAVAILABLE', + ) } const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode return approveEscalation( @@ -266,6 +283,8 @@ export function apply(ctx: Context, config: Config = {}): void { const startJob = (registry: JobRegistry, args: BashToolArgs, exec: ToolExecution, spec: ShellExecSpec): StartedJob => { let proc: ShellExecution | undefined let stopped: string | undefined + // The registry runs the starter inside start(), so this is assigned before start() returns. + let failure!: () => { error: unknown } | undefined const id = registry.start({ kind: 'bash', label: args.command, @@ -280,6 +299,7 @@ export function apply(ctx: Context, config: Config = {}): void { }, started => processOutcome(started, escalationModes), ) + failure = () => hooks.failure() return { done: hooks.done, // A kill from outside this call (the human's, a parallel job_kill) @@ -291,7 +311,7 @@ export function apply(ctx: Context, config: Config = {}): void { } }, }) - return { id, process: () => proc, stopped: () => stopped } + return { id, process: () => proc, stopped: () => stopped, failure: () => failure() } } /** Wait on a registered foreground command until it settles or the timeout passes. */ const waitOnJob = async (registry: JobRegistry, attached: StartedJob, exec: ToolExecution, spec: ShellExecSpec) => { @@ -357,11 +377,14 @@ export function apply(ctx: Context, config: Config = {}): void { // the split streams and classification the foreground result needs. registry.remove(attached.id, owner) const process = attached.process() - // No process was published: the starter failed before the spawn, and the - // job's terminal detail is the failure the foreground projection would - // have rejected with. - if (process === undefined) throw new Error(view.detail) - const result = await process.result() + // No process was published: the starter failed before the spawn. The + // original error keeps its class and code, exactly as the foreground + // projection would have rejected; a kill before the spawn has only its detail. + if (process === undefined) { + const failure = attached.failure() + throw failure === undefined ? new Error(view.detail) : launchFailure(failure.error, exec.signal) + } + const result = await process.result().catch((error: unknown) => { throw launchFailure(error, exec.signal) }) const stopped = attached.stopped() return { kind: 'foreground' as const, ...canonicalBashResult(result, spec.workdir), ...stopped !== undefined ? { stopped } : {} } } @@ -498,10 +521,10 @@ export function apply(ctx: Context, config: Config = {}): void { if (args.run_in_background === true) { // Undeclared keys are allowed, so schema omission also needs enforcement. if (!backgroundEnabled) { - throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)') + throw new JobError('run_in_background is disabled for this deployment (enableRunInBackground: false)', 'JOB_BACKGROUND_DISABLED') } 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') } // The caller owns cancellation until ctx.jobs commits detached ownership. if (exec.signal.aborted) throw toolAborted() @@ -524,8 +547,12 @@ export function apply(ctx: Context, config: Config = {}): void { if (attached !== undefined) return waitOnJob(jobs, attached, exec, spec) } const spec = ctx.shell.resolve({ ...request, signal: exec.signal }) - const foreground = await ctx.shell.execute(spec) - const result = await foreground.result() + let result: ShellRunResult + try { + result = await (await ctx.shell.execute(spec)).result() + } catch (error) { + throw launchFailure(error, exec.signal) + } if (result.aborted) throw toolAborted() return { kind: 'foreground' as const, ...canonicalBashResult(result, spec.workdir) } }, diff --git a/packages/shell/tool-bash/tests/background.spec.ts b/packages/shell/tool-bash/tests/background.spec.ts index add9714ac4..58129b3a0b 100644 --- a/packages/shell/tool-bash/tests/background.spec.ts +++ b/packages/shell/tool-bash/tests/background.spec.ts @@ -19,6 +19,7 @@ import type { JobId } from '@deepseek-ai/dsh-jobs' import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs' import type { ShellExecution, ShellProcess } from '@deepseek-ai/dsh-shell' import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local' +import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' import * as ToolBash from '@deepseek-ai/dsh-tool-bash' import { processSources, ringDelta } from '../src/background.ts' @@ -279,10 +280,49 @@ describe('foreground commands as jobs', () => { it('a command whose start fails reports the failure as an error result and leaves no job behind', async () => { const ctx = await setup() - vi.spyOn(ctx.shell, 'execute').mockRejectedValue(new Error('spawn bash ENOENT')) + vi.spyOn(ctx.shell, 'execute').mockRejectedValue(Object.assign(new Error('spawn bash ENOENT'), { code: 'ENOENT' })) const result = await call(ctx, { command: 'true', description: 'test command' }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } }, + }) + expect(text(result)).toBe('Error: cannot start "bash": the program or the working directory does not exist (spawn bash ENOENT)') + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a spawn that fails after the process published reports a coded failure and leaves no job behind', async () => { + const ctx = await setup() + const result = await call(ctx, { command: 'true', description: 'test command', workdir: join(spillDir, 'missing-workdir') }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } }, + }) + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a job stopped from outside before its process published reports the stop', async () => { + const ctx = await setup() + vi.spyOn(ctx.shell, 'execute').mockImplementation(spec => new Promise((_resolve, reject) => { + spec.signal?.addEventListener('abort', () => { reject(new Error('preparation stopped')) }, { once: true }) + })) + const pending = call(ctx, { command: 'ls', description: 'test command' }) + await vi.waitFor(() => { expect(ctx.jobs.list()).toHaveLength(1) }) + ctx.jobs.kill(ctx.jobs.list()[0]!.id, undefined, 'cancelled by the user') + const result = await pending expect(result.isError).toBe(true) - expect(text(result)).toBe('Error: spawn bash ENOENT') + expect((result.content[0] as { text: string }).text).toBe('Error: preparation stopped; cancelled by the user') + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a coded preparation failure keeps its name and code through the job path', async () => { + const ctx = await setup() + vi.spyOn(ctx.shell, 'execute').mockRejectedValue(new SandboxUnavailableError('workspace-write', 'bwrap: setting up uid map: Permission denied')) + const result = await call(ctx, { command: 'true', description: 'test command' }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SandboxUnavailableError', code: 'SANDBOX_UNAVAILABLE' } }, + }) + expect(text(result)).toContain('Runner failure: bwrap: setting up uid map: Permission denied') expect(ctx.jobs.list()).toEqual([]) }) diff --git a/packages/shell/tool-bash/tests/tools.spec.ts b/packages/shell/tool-bash/tests/tools.spec.ts index d3f20572f8..554b7f4e35 100644 --- a/packages/shell/tool-bash/tests/tools.spec.ts +++ b/packages/shell/tool-bash/tests/tools.spec.ts @@ -394,7 +394,7 @@ describe('bash tool', () => { ])('rejects value-invalid args %j', async (args, pattern) => { const ctx = await setup() const result = await call(ctx, 'bash', args) - expect(result.isError).toBe(true) + expect(result).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) expect(text(result)).toMatch(pattern) }) @@ -640,7 +640,10 @@ describe('background execution through the job runtime', () => { it('fails loud when the job runtime is not loaded', async () => { const ctx = await setup() // no LocalJobRegistry / ToolJobs const result = await call(ctx, 'bash', { command: 'sleep 60', description: 'test command', run_in_background: true }) - expect(result.isError).toBe(true) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } }, + }) expect(text(result)).toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') }) @@ -717,7 +720,7 @@ describe('background execution through the job runtime', () => { // Schema omission is advertising; execution must also enforce the opt-out. const forced = await call(ctx, 'bash', { command: 'echo hi', description: 'test command', run_in_background: true }) - expect(forced.isError).toBe(true) + expect(forced).toMatchObject({ isError: true, error: { info: { name: 'JobError', code: 'JOB_BACKGROUND_DISABLED' } } }) expect(text(forced)).toContain('run_in_background is disabled for this deployment') const foreground = await call(ctx, 'bash', { command: 'echo hi', description: 'test command' }) expect(foreground.isError).toBe(false) @@ -755,7 +758,10 @@ describe('sandbox escalation through the generic task producer', () => { { command: 'true', description: 'd', justification: 'why' }, { command: 'true', description: 'd', sandbox_permissions: 'workspace-write', justification: ' ' }, ]) { - expect((await call(ctx, 'bash', args)).isError).toBe(true) + expect(await call(ctx, 'bash', args)).toMatchObject({ + isError: true, + error: { info: { name: 'SandboxEscalationError', code: 'SANDBOX_ESCALATION_INVALID_ARGUMENT' } }, + }) } }) @@ -793,7 +799,9 @@ describe('sandbox escalation through the generic task producer', () => { it('rejects injected escalation without a sandbox and narrower escalation without prompting', async () => { const plain = await setup() - expect(text(await call(plain, 'bash', escalate))).toContain('not available in this composition') + const unavailable = await call(plain, 'bash', escalate) + expect(text(unavailable)).toContain('not available in this composition') + expect(unavailable).toMatchObject({ error: { info: { name: 'SandboxEscalationError', code: 'SANDBOX_ESCALATION_UNAVAILABLE' } } }) const { ctx } = await setupSandboxed(true) const prompted = vi.fn() @@ -1543,3 +1551,29 @@ describe('resolved launch directory metadata', () => { } }) }) + +describe('launch failures without a job registry', () => { + it('classifies a platform spawn error and keeps this call\'s cancellation', async () => { + const ctx = await setup() + const missing = vi.spyOn(ctx.shell, 'execute').mockRejectedValueOnce(Object.assign(new Error('spawn bash ENOENT'), { code: 'ENOENT' })) + expect(await call(ctx, 'bash', { command: 'true', description: 'd' })).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } }, + }) + missing.mockRestore() + + const controller = new AbortController() + const reason = new Error('caller stopped') + vi.spyOn(ctx.shell, 'execute').mockImplementationOnce(() => { + controller.abort(reason) + return Promise.reject(reason) + }) + const aborted = await executeToolFixture(ctx, { + signal: controller.signal, + callId: ToolCallId('launch-aborted'), + name: 'bash', + arguments: { command: 'true', description: 'd' }, + }) + expect(aborted).toMatchObject({ isError: true, error: { info: { name: 'AbortError', code: TOOL_ABORTED } } }) + }) +}) diff --git a/packages/shell/tool-bash/tsconfig.json b/packages/shell/tool-bash/tsconfig.json index 5efa5088e1..42510cdbdd 100644 --- a/packages/shell/tool-bash/tsconfig.json +++ b/packages/shell/tool-bash/tsconfig.json @@ -49,6 +49,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../subprocess/subprocess" } ] } diff --git a/packages/shell/tool-pwsh/README.i18n.yaml b/packages/shell/tool-pwsh/README.i18n.yaml index ed32de4eef..8032f1b349 100644 --- a/packages/shell/tool-pwsh/README.i18n.yaml +++ b/packages/shell/tool-pwsh/README.i18n.yaml @@ -108,8 +108,8 @@ en: 2d4f2c8605eccab3 zh: 67f1f0218f73c6bf /deepseek-ai-dsh-tool-pwsh/model-experience/tool-errors/what-the-model-sees: - en: f0802a10dbe0f7d2 - zh: 80f8b312dcfc0065 + en: d45b05d98cf6e7e3 + zh: b3c59fb3603f511e /deepseek-ai-dsh-tool-pwsh/model-experience/tool-errors/token-effect: en: 243bad012dd99c7f zh: 5ee74905020bd49a diff --git a/packages/shell/tool-pwsh/README.md b/packages/shell/tool-pwsh/README.md index 051f3cd4a2..34bc941529 100644 --- a/packages/shell/tool-pwsh/README.md +++ b/packages/shell/tool-pwsh/README.md @@ -188,7 +188,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the shared escalation failures (not strictly wider / no approval service / no agent to route / no approval channel / user rejected / was cancelled), `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, and `tool call aborted`. +Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the shared escalation failures (not strictly wider / no approval service / no agent to route / no approval channel / user rejected / was cancelled), `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`). #### Token effect diff --git a/packages/shell/tool-pwsh/README.zh.md b/packages/shell/tool-pwsh/README.zh.md index 90e2b726c1..f81c92a602 100644 --- a/packages/shell/tool-pwsh/README.zh.md +++ b/packages/shell/tool-pwsh/README.zh.md @@ -188,7 +188,7 @@ Non-zero exits are reported as `[exit code: N]` markers; investigate failures be #### 模型看到什么 -验证与基础设施失败统一为 `Error: `。本包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、升权配对失败、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、共享升权失败(未严格加宽/无审批服务/无 agent 可路由/无审批通道/用户拒绝/已取消)、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`,以及 `tool call aborted`。 +验证与基础设施失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、共享升权失败(未严格加宽/无审批服务/无 agent 可路由/无审批通道/用户拒绝/已取消)、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`)。 #### Token 影响 diff --git a/packages/shell/tool-pwsh/package.json b/packages/shell/tool-pwsh/package.json index 360190080e..284751c48c 100644 --- a/packages/shell/tool-pwsh/package.json +++ b/packages/shell/tool-pwsh/package.json @@ -43,7 +43,8 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-user-approval": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -72,6 +73,7 @@ "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-fs-local": "workspace:*" + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*" } } diff --git a/packages/shell/tool-pwsh/src/background.ts b/packages/shell/tool-pwsh/src/background.ts index 67d937df79..120e595b04 100644 --- a/packages/shell/tool-pwsh/src/background.ts +++ b/packages/shell/tool-pwsh/src/background.ts @@ -11,6 +11,16 @@ import { escalationHintMarker, sandboxDenialMarker } from '@deepseek-ai/dsh-sand import type { ShellProcess, ShellSandboxInfo } from '@deepseek-ai/dsh-shell' import type { JobChunk, JobHooks, JobOutcome, JobOutputSource } from '@deepseek-ai/dsh-jobs' +/** Job hooks plus the original error of a job that failed before its process produced an outcome. */ +export interface ProcessJobHooks extends JobHooks { + /** + * The error that ended a `failed` job, kept with its own class and code; + * undefined while the job runs and for a completed or killed job. + * @returns the original failure, boxed so any thrown value is preserved. + */ + failure(): { error: unknown } | undefined +} + /* jscpd:ignore-start -- deliberate twin of dsh-tool-bash/background.ts (Agent Note). */ /** @@ -96,14 +106,16 @@ export function ringDelta(chunks: readonly JobChunk[]): string { * Adapt asynchronous shell preparation after job admission without exposing a partial process. * @param start - starts the process with job-owned cancellation. * @param outcome - projects the settled process into the job outcome. - * @returns synchronous job hooks whose completion includes preparation and process settlement. + * @returns synchronous job hooks whose completion includes preparation and process settlement, + * and the original error of a failed preparation for a caller that reports it. */ export function processJob( start: (signal: AbortSignal) => Promise, outcome: (process: ShellProcess) => JobOutcome, -): JobHooks { +): ProcessJobHooks { const controller = new AbortController() let process: ShellProcess | undefined + let failure: { error: unknown } | undefined const done: Promise = (async () => { try { process = await start(controller.signal) @@ -114,8 +126,10 @@ export function processJob( } return outcome(process) } catch (error: unknown) { + const killed = controller.signal.aborted && process === undefined + if (!killed) failure = { error } return { - status: controller.signal.aborted && process === undefined ? 'killed' : 'failed', + status: killed ? 'killed' : 'failed', detail: error instanceof Error ? error.message : String(error), } } @@ -127,6 +141,7 @@ export function processJob( process?.kill() }, done, + failure: () => failure, } } /* jscpd:ignore-end */ diff --git a/packages/shell/tool-pwsh/src/index.ts b/packages/shell/tool-pwsh/src/index.ts index a3472b4357..0ef0fa260b 100644 --- a/packages/shell/tool-pwsh/src/index.ts +++ b/packages/shell/tool-pwsh/src/index.ts @@ -25,14 +25,16 @@ import type {} from '@deepseek-ai/dsh-working-directory' import { FiberState } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { defineTool, TOOL_ABORTED } from '@deepseek-ai/dsh-tools' +import { defineTool, TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, TerminalCallView, ToolDefinition, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools' import { HarnessError } from '@deepseek-ai/dsh-llm' +import { JobError } from '@deepseek-ai/dsh-jobs' import type { JobId, JobRegistry, JobView } from '@deepseek-ai/dsh-jobs' import type {} from '@deepseek-ai/dsh-shell-env' import type {} from '@deepseek-ai/dsh-user-approval' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' -import { ESCALATION_TARGETS, approveEscalation, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' +import { ESCALATION_TARGETS, SandboxEscalationError, approveEscalation, sandboxPermissionsDescription, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' +import { subprocessSpawnFailure } from '@deepseek-ai/dsh-subprocess' import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellRunResult } from '@deepseek-ai/dsh-shell' import { parseExitStatus } from '@deepseek-ai/dsh-shell' @@ -106,13 +108,13 @@ interface PwshForegroundResult { /* jscpd:ignore-start -- minimal mirror of dsh-tool-bash's validation and execute plumbing (Agent Note). */ function validatePwshArgs(args: PwshToolArgs): void { if (args.command.trim().length === 0) { - throw new Error('invalid command: expected a non-empty string') + throw new ToolArgsError(['invalid command: expected a non-empty string']) } if (args.description.trim().length === 0) { - throw new Error('invalid description: expected a non-empty string') + throw new ToolArgsError(['invalid description: expected a non-empty string']) } if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { - throw new Error(`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`) + throw new ToolArgsError([`invalid timeoutMs: expected a positive number, got ${JSON.stringify(args.timeoutMs)}`]) } validateEscalationArgs(args.sandbox_permissions, args.justification) } @@ -193,11 +195,23 @@ function toolAborted(): HarnessError { return error } +/** + * Report a launch or preparation rejection as this tool's failure. A coded + * error keeps its class and code; this call's cancellation stays as thrown so + * the registry records it as aborted; any other value is classified as a + * subprocess spawn failure with the original as `cause`. + */ +function launchFailure(error: unknown, signal: AbortSignal): unknown { + return signal.aborted ? error : subprocessSpawnFailure(error, 'pwsh') +} + /** A registered command: its id, the process once the starter spawned it, and the reason an outside kill gave. */ interface StartedJob { readonly id: JobId readonly process: () => ShellExecution | undefined readonly stopped: () => string | undefined + /** The original error of a registration whose preparation failed before the process published. */ + readonly failure: () => { error: unknown } | undefined } /** Canonical background-handle properties shared by the pwsh output union. */ @@ -245,7 +259,10 @@ export function apply(ctx: Context, config: Config = {}): void { standingPolicy: SandboxExecutionPolicy | undefined, ): Promise => { if (escalationModes.length === 0) { - throw new Error('sandbox_permissions is not available in this composition (no sandboxing executor to escalate)') + throw new SandboxEscalationError( + 'sandbox_permissions is not available in this composition (no sandboxing executor to escalate)', + 'SANDBOX_ESCALATION_UNAVAILABLE', + ) } const effectiveMode = (standingPolicy as SandboxExecutionPolicy).mode return approveEscalation( @@ -281,6 +298,8 @@ export function apply(ctx: Context, config: Config = {}): void { const startJob = (registry: JobRegistry, args: PwshToolArgs, exec: ToolExecution, spec: ShellExecSpec): StartedJob => { let proc: ShellExecution | undefined let stopped: string | undefined + // The registry runs the starter inside start(), so this is assigned before start() returns. + let failure!: () => { error: unknown } | undefined const id = registry.start({ kind: 'pwsh', label: args.command, @@ -295,6 +314,7 @@ export function apply(ctx: Context, config: Config = {}): void { }, started => processOutcome(started, escalationModes), ) + failure = () => hooks.failure() return { done: hooks.done, // A kill from outside this call (the human's, a parallel job_kill) @@ -306,7 +326,7 @@ export function apply(ctx: Context, config: Config = {}): void { } }, }) - return { id, process: () => proc, stopped: () => stopped } + return { id, process: () => proc, stopped: () => stopped, failure: () => failure() } } /** Wait on a registered foreground command until it settles or the timeout passes. */ const waitOnJob = async (registry: JobRegistry, attached: StartedJob, exec: ToolExecution, spec: ShellExecSpec) => { @@ -372,11 +392,14 @@ export function apply(ctx: Context, config: Config = {}): void { // the split streams and classification the foreground result needs. registry.remove(attached.id, owner) const process = attached.process() - // No process was published: the starter failed before the spawn, and the - // job's terminal detail is the failure the foreground projection would - // have rejected with. - if (process === undefined) throw new Error(view.detail) - const result = await process.result() + // No process was published: the starter failed before the spawn. The + // original error keeps its class and code, exactly as the foreground + // projection would have rejected; a kill before the spawn has only its detail. + if (process === undefined) { + const failure = attached.failure() + throw failure === undefined ? new Error(view.detail) : launchFailure(failure.error, exec.signal) + } + const result = await process.result().catch((error: unknown) => { throw launchFailure(error, exec.signal) }) const stopped = attached.stopped() return { ...canonicalPwshResult(result, spec.workdir), ...stopped !== undefined ? { stopped } : {} } } @@ -521,10 +544,10 @@ export function apply(ctx: Context, config: Config = {}): void { if (args.run_in_background === true) { // Undeclared keys are allowed, so schema omission also needs enforcement. if (!backgroundEnabled) { - throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)') + throw new JobError('run_in_background is disabled for this deployment (enableRunInBackground: false)', 'JOB_BACKGROUND_DISABLED') } 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') } // The caller owns cancellation until ctx.jobs commits detached ownership. if (exec.signal.aborted) throw toolAborted() @@ -547,8 +570,12 @@ export function apply(ctx: Context, config: Config = {}): void { if (attached !== undefined) return waitOnJob(jobs, attached, exec, spec) } const spec = ctx.shell.resolve({ ...request, signal: exec.signal }) - const foreground = await ctx.shell.execute(spec) - const result = await foreground.result() + let result: ShellRunResult + try { + result = await (await ctx.shell.execute(spec)).result() + } catch (error) { + throw launchFailure(error, exec.signal) + } if (result.aborted) throw toolAborted() return canonicalPwshResult(result, spec.workdir) }, diff --git a/packages/shell/tool-pwsh/tests/background.spec.ts b/packages/shell/tool-pwsh/tests/background.spec.ts index 2794df944a..48b01dde16 100644 --- a/packages/shell/tool-pwsh/tests/background.spec.ts +++ b/packages/shell/tool-pwsh/tests/background.spec.ts @@ -13,6 +13,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { unsupportedModel, provideWorkingDirectoryFixture, unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs' +import { SandboxPreparationError } from '@deepseek-ai/dsh-sandbox' import { ShellExecutor } from '@deepseek-ai/dsh-shell' import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellProcess } from '@deepseek-ai/dsh-shell' import { renderPwshPromoted } from '../src/render.ts' @@ -346,8 +347,56 @@ describe('foreground commands as jobs (pwsh)', () => { const { ctx, pwsh } = await setup() pwsh.backgroundHandler = () => { throw new Error('spawn pwsh ENOENT') } const result = await call(ctx, { command: 'Get-Missing', description: 'test command' }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_FAILED' } }, + }) + expect((result.content[0] as { text: string }).text).toBe('Error: cannot start "pwsh": spawn pwsh ENOENT') + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a spawn that fails after the process published reports a coded failure', async () => { + const { ctx, pwsh } = await setup() + pwsh.backgroundHandler = () => { + const started = observableProcess() + started.finish() + return Object.assign(started.proc, { + result: () => Promise.reject(Object.assign(new Error('spawn pwsh ENOENT'), { code: 'ENOENT' })), + }) + } + const result = await call(ctx, { command: 'Get-ChildItem', description: 'test command' }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } }, + }) + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a job stopped from outside before its process published reports the stop', async () => { + const { ctx, pwsh } = await setup() + vi.spyOn(pwsh, 'execute').mockImplementation(spec => new Promise((_resolve, reject) => { + spec.signal?.addEventListener('abort', () => { reject(new Error('preparation stopped')) }, { once: true }) + })) + const pending = call(ctx, { command: 'Get-ChildItem', description: 'test command' }) + await vi.waitFor(() => { expect(ctx.jobs.list()).toHaveLength(1) }) + ctx.jobs.kill(ctx.jobs.list()[0]!.id, undefined, 'cancelled by the user') + const result = await pending expect(result.isError).toBe(true) - expect((result.content[0] as { text: string }).text).toBe('Error: spawn pwsh ENOENT') + expect((result.content[0] as { text: string }).text).toBe('Error: preparation stopped; cancelled by the user') + expect(ctx.jobs.list()).toEqual([]) + }) + + it('a Windows ACL preparation failure keeps its name and code through the job path', async () => { + const { ctx, pwsh } = await setup() + const cause = new Error('SetNamedSecurityInfoW failed (Win32 5): C:\\ws') + pwsh.backgroundHandler = () => { + throw new SandboxPreparationError('sandbox-local: windows-acl workspace grant failed', 'SANDBOX_PREPARATION_FAILED', { cause }) + } + const result = await call(ctx, { command: 'Get-ChildItem', description: 'test command' }) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED' } }, + }) expect(ctx.jobs.list()).toEqual([]) }) diff --git a/packages/shell/tool-pwsh/tests/tools.spec.ts b/packages/shell/tool-pwsh/tests/tools.spec.ts index 731da47a4c..00fb01724f 100644 --- a/packages/shell/tool-pwsh/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh/tests/tools.spec.ts @@ -434,6 +434,13 @@ describe('argument validation', () => { expect(text(await call(ctx, 'pwsh', { command: 'Write-Output hi', description: ' ' }))).toContain('expected a non-empty string') expect(text(await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'd', timeoutMs: -1 }))) .toContain('invalid timeoutMs: expected a positive number') + for (const args of [ + { command: ' ', description: 'd' }, + { command: 'Write-Output hi', description: ' ' }, + { command: 'Write-Output hi', description: 'd', timeoutMs: -1 }, + ]) { + expect(await call(ctx, 'pwsh', args)).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) + } }) }) @@ -676,7 +683,9 @@ describe('sandbox escalation through ctx.approval', () => { it('rejects injected escalation without a sandbox and narrower escalation without prompting', async () => { const plain = await setup() - expect(text(await call(plain.ctx, 'pwsh', escalate))).toContain('not available in this composition') + const unavailable = await call(plain.ctx, 'pwsh', escalate) + expect(text(unavailable)).toContain('not available in this composition') + expect(unavailable).toMatchObject({ error: { info: { name: 'SandboxEscalationError', code: 'SANDBOX_ESCALATION_UNAVAILABLE' } } }) const { ctx } = await setupSandboxed(true) const prompted = vi.fn() @@ -861,7 +870,10 @@ describe('background execution through the job runtime', () => { it('fails loud when the job runtime is not loaded', async () => { const { ctx } = await setup() // no LocalJobRegistry / ToolJobs const result = await call(ctx, 'pwsh', { command: 'Start-Sleep -Seconds 60', description: 'test command', run_in_background: true }) - expect(result.isError).toBe(true) + expect(result).toMatchObject({ + isError: true, + error: { info: { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } }, + }) expect(text(result)).toContain('background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs') }) @@ -912,7 +924,7 @@ describe('background execution through the job runtime', () => { // Schema omission is advertising; execution must also enforce the opt-out. const forced = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'test command', run_in_background: true }) - expect(forced.isError).toBe(true) + expect(forced).toMatchObject({ isError: true, error: { info: { name: 'JobError', code: 'JOB_BACKGROUND_DISABLED' } } }) expect(text(forced)).toContain('run_in_background is disabled for this deployment') const foreground = await call(ctx, 'pwsh', { command: 'Write-Output hi', description: 'test command' }) expect(foreground.isError).toBe(false) @@ -1280,3 +1292,29 @@ describe('resolved launch directory metadata', () => { } }) }) + +describe('launch failures without a job registry', () => { + it('classifies a platform spawn error and keeps this call\'s cancellation', async () => { + const { ctx } = await setup() + const missing = vi.spyOn(ctx.shell, 'execute').mockRejectedValueOnce(Object.assign(new Error('spawn pwsh ENOENT'), { code: 'ENOENT' })) + expect(await call(ctx, 'pwsh', { command: 'Write-Output ok', description: 'd' })).toMatchObject({ + isError: true, + error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } }, + }) + missing.mockRestore() + + const controller = new AbortController() + const reason = new Error('caller stopped') + vi.spyOn(ctx.shell, 'execute').mockImplementationOnce(() => { + controller.abort(reason) + return Promise.reject(reason) + }) + const aborted = await executeToolFixture(ctx, { + signal: controller.signal, + callId: ToolCallId('launch-aborted'), + name: 'pwsh', + arguments: { command: 'Write-Output ok', description: 'd' }, + }) + expect(aborted).toMatchObject({ isError: true, error: { info: { name: 'AbortError', code: TOOL_ABORTED } } }) + }) +}) diff --git a/packages/shell/tool-pwsh/tsconfig.json b/packages/shell/tool-pwsh/tsconfig.json index 80a56fcda6..4015c265db 100644 --- a/packages/shell/tool-pwsh/tsconfig.json +++ b/packages/shell/tool-pwsh/tsconfig.json @@ -52,6 +52,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../subprocess/subprocess" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 90d655e2af..4b81d0ed5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15586,6 +15586,9 @@ importers: '@deepseek-ai/dsh-shell-env': specifier: workspace:* version: link:../shell-env + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess '@deepseek-ai/dsh-subprocess-local': specifier: workspace:* version: link:../../subprocess/subprocess-local @@ -15735,6 +15738,9 @@ importers: '@deepseek-ai/dsh-shell-env': specifier: workspace:* version: link:../shell-env + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess '@deepseek-ai/dsh-subprocess-local': specifier: workspace:* version: link:../../subprocess/subprocess-local From 3538757cbea0decda47b20d34f7c28bdf17fa6ca Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:35:58 +0800 Subject: [PATCH 047/438] feat(terminal): code PTY session and persistent shell failures TerminalError gains SESSION_CLOSING, SESSION_EXITED, STARTUP_EXITED, STARTUP_TIMEOUT, NO_SANDBOX, and INIT_REJECTED, following its existing unprefixed code style. The terminal service and terminal-bash use them for a send to a closing or exited session, a shell that exits or misses readiness during startup, and a confined mode without a sandbox provider; an empty confined argv is SubprocessError SUBPROCESS_INVALID_ARGV, and a send on an aborted signal throws an error named AbortError. The persistent bash and pwsh tools report a missing owner as ToolContextUnavailableError, a blank command as ToolArgsError, and a shell that rejects its setup as TerminalError INIT_REJECTED. Refs #7869 --- .../tool-bash-persistent/README.i18n.yaml | 4 ++-- packages/shell/tool-bash-persistent/README.md | 2 +- .../shell/tool-bash-persistent/README.zh.md | 2 +- .../shell/tool-bash-persistent/src/index.ts | 9 +++++---- .../tool-bash-persistent/tests/tools.spec.ts | 14 +++++++++++--- .../tool-pwsh-persistent/README.i18n.yaml | 4 ++-- packages/shell/tool-pwsh-persistent/README.md | 2 +- .../shell/tool-pwsh-persistent/README.zh.md | 2 +- .../shell/tool-pwsh-persistent/src/index.ts | 6 +++--- .../tool-pwsh-persistent/tests/tools.spec.ts | 9 +++++++-- packages/terminal/terminal-bash/src/index.ts | 18 ++++++++++++------ packages/terminal/terminal-bash/src/session.ts | 17 +++++++++++------ .../terminal/terminal-bash/tests/index.spec.ts | 4 ++++ .../terminal-bash/tests/session.spec.ts | 11 ++++++++--- packages/terminal/terminal/README.i18n.yaml | 4 ++-- packages/terminal/terminal/README.md | 2 +- packages/terminal/terminal/README.zh.md | 2 +- packages/terminal/terminal/src/index.ts | 17 +++++++++++++++-- .../terminal/terminal/tests/service.spec.ts | 2 ++ 19 files changed, 90 insertions(+), 41 deletions(-) diff --git a/packages/shell/tool-bash-persistent/README.i18n.yaml b/packages/shell/tool-bash-persistent/README.i18n.yaml index cc6225da8c..a7d7a29c7c 100644 --- a/packages/shell/tool-bash-persistent/README.i18n.yaml +++ b/packages/shell/tool-bash-persistent/README.i18n.yaml @@ -27,8 +27,8 @@ en: b398f124ea7b77b0 zh: 50855e601e6c1b88 /deepseek-ai-dsh-tool-bash-persistent/use-this-package/what-can-go-wrong: - en: 2713550ebdb02f69 - zh: 52ed398dc541d1fc + en: 52e0e1489c6f8071 + zh: 27251d61351ee72d /deepseek-ai-dsh-tool-bash-persistent/understand-the-implementation: en: 8d94a7381bca3fa9 zh: f4bd2866fff6fa8d diff --git a/packages/shell/tool-bash-persistent/README.md b/packages/shell/tool-bash-persistent/README.md index 4bbea6bf1a..9feed7a656 100644 --- a/packages/shell/tool-bash-persistent/README.md +++ b/packages/shell/tool-bash-persistent/README.md @@ -58,7 +58,7 @@ Commands share one shell per agent, so state persists until an `exit`, a timeout ### What can go wrong -A call without an owning agent session fails with `bash requires an owning agent session`, and a composition without a PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. An interactive foreground child (for example a REPL) returns early with partial output only where the backend proves its stdin wait; elsewhere the call runs to `timeoutMs`, which closes the uncertain shell and reports the reset. Cancellation also resets and discards the result, even when a complete status marker is already observable. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. +A call without an owning agent session fails with `bash requires an owning agent session` (`ToolContextUnavailableError`, `TOOL_CONTEXT_UNAVAILABLE`), a blank command fails with `ToolArgsError` (`INVALID_ARGS`), and a composition without a PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. An interactive foreground child (for example a REPL) returns early with partial output only where the backend proves its stdin wait; elsewhere the call runs to `timeoutMs`, which closes the uncertain shell and reports the reset. Cancellation also resets and discards the result, even when a complete status marker is already observable. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. ----- diff --git a/packages/shell/tool-bash-persistent/README.zh.md b/packages/shell/tool-bash-persistent/README.zh.md index 6b4877e177..c348502a09 100644 --- a/packages/shell/tool-bash-persistent/README.zh.md +++ b/packages/shell/tool-bash-persistent/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 可能出什么问题 -没有拥有者 agent 会话的调用会以 `bash requires an owning agent session` 失败,没有 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。交互式前台子进程(例如 REPL)只有在后端证明其 stdin 等待时才提前返回部分输出;否则调用一直运行到 `timeoutMs`,随后关闭不确定的 shell 并报告重置。取消也会重置并丢弃结果,即使完整状态标记已经可观察。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 +没有拥有者 agent 会话的调用会以 `bash requires an owning agent session`(`ToolContextUnavailableError`,`TOOL_CONTEXT_UNAVAILABLE`)失败,空白命令以 `ToolArgsError`(`INVALID_ARGS`)失败,没有 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。交互式前台子进程(例如 REPL)只有在后端证明其 stdin 等待时才提前返回部分输出;否则调用一直运行到 `timeoutMs`,随后关闭不确定的 shell 并报告重置。取消也会重置并丢弃结果,即使完整状态标记已经可观察。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 ----- diff --git a/packages/shell/tool-bash-persistent/src/index.ts b/packages/shell/tool-bash-persistent/src/index.ts index 94de7ccf09..ac8d11ef77 100644 --- a/packages/shell/tool-bash-persistent/src/index.ts +++ b/packages/shell/tool-bash-persistent/src/index.ts @@ -9,9 +9,10 @@ import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' import { truncateWithoutSplittingSurrogatePair } from '@deepseek-ai/dsh-output-retention' +import { TerminalError } from '@deepseek-ai/dsh-terminal' import type { TerminalReadResult, TerminalSessionId } from '@deepseek-ai/dsh-terminal' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' // TODO: Replace the file-search advice; arbitrary command output need not come from a searchable file. const TRUNCATED_MESSAGE = 'To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.' @@ -278,7 +279,7 @@ function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShell }) const result = await setup.done if (result.sessionStatus.kind === 'exited' || result.waitReason === 'timeout') { - throw new Error('persistent bash shell did not accept initialization') + throw new TerminalError('persistent bash shell did not accept initialization', 'INIT_REJECTED') } return spawned.sessionId } catch (error: unknown) { @@ -428,9 +429,9 @@ function registerPersistentBash(ctx: Context, config: ResolvedConfig): void { render: (_args, value) => [{ type: 'text', text: value }], }, async execute(args, exec) { - if (args.command.trim().length === 0) throw new Error('command must be a non-empty string') + if (args.command.trim().length === 0) throw new ToolArgsError(['command must be a non-empty string']) const owner = exec.agent - if (owner === undefined) throw new Error('bash requires an owning agent session') + if (owner === undefined) throw new ToolContextUnavailableError('bash requires an owning agent session') return serialized(owner, async () => { if (exec.signal.aborted) return '' // ToolRuntime publishes ABORTED after settlement. return executeCommand(ctx, shells, owner, args.command, config, exec.signal) diff --git a/packages/shell/tool-bash-persistent/tests/tools.spec.ts b/packages/shell/tool-bash-persistent/tests/tools.spec.ts index 7a926e670e..6793099643 100644 --- a/packages/shell/tool-bash-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-bash-persistent/tests/tools.spec.ts @@ -694,7 +694,10 @@ describe('tool-bash-persistent', () => { 'fails initialization and closes the unusable shell for %s', async (mode) => { const { ctx, owner, stub } = await setup({ backendType: 'stub' }, mode) - expect((await call(ctx, owner, 'pwd')).isError).toBe(true) + expect(await call(ctx, owner, 'pwd')).toMatchObject({ + isError: true, + error: { info: { name: 'TerminalError', code: 'INIT_REJECTED' } }, + }) expect(stub.sessions[0]?.closed).toContain('persistent bash initialization failed') }, ) @@ -752,8 +755,13 @@ describe('tool-bash-persistent', () => { it('rejects invalid config and invalid calls', async () => { const { ctx, owner, stub } = await setup() - expect((await call(ctx, undefined, 'pwd')).isError).toBe(true) - expect(text(await call(ctx, owner, ' '))).toContain('command must be a non-empty string') + expect(await call(ctx, undefined, 'pwd')).toMatchObject({ + isError: true, + error: { info: { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } }, + }) + const blank = await call(ctx, owner, ' ') + expect(text(blank)).toContain('command must be a non-empty string') + expect(blank).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) const controller = new AbortController() controller.abort(new Error('caller stopped')) diff --git a/packages/shell/tool-pwsh-persistent/README.i18n.yaml b/packages/shell/tool-pwsh-persistent/README.i18n.yaml index 60b8ae7682..ab2bb8cd7f 100644 --- a/packages/shell/tool-pwsh-persistent/README.i18n.yaml +++ b/packages/shell/tool-pwsh-persistent/README.i18n.yaml @@ -27,8 +27,8 @@ en: 9f4c22b06f940caf zh: 61f755cec7ff5b76 /deepseek-ai-dsh-tool-pwsh-persistent/use-this-package/what-can-go-wrong: - en: 70bf2e1e8d8ccbf6 - zh: 6c78d8c85113adf7 + en: 3abc9cc73411c042 + zh: 31c9e3ddf7160414 /deepseek-ai-dsh-tool-pwsh-persistent/understand-the-implementation: en: 8d94a7381bca3fa9 zh: f4bd2866fff6fa8d diff --git a/packages/shell/tool-pwsh-persistent/README.md b/packages/shell/tool-pwsh-persistent/README.md index 0bd03285be..5437ef8a9a 100644 --- a/packages/shell/tool-pwsh-persistent/README.md +++ b/packages/shell/tool-pwsh-persistent/README.md @@ -60,7 +60,7 @@ Commands share one shell per agent, so cwd, `$env:` variables, functions, and ba ### What can go wrong -A call without an owning agent session fails with `pwsh requires an owning agent session`, and a composition without a pwsh-dialect PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. A model redefinition of the `prompt` function removes the readiness marker, and the shell then settles on the silence tier instead of the marker fast path. Raw ESC characters inside a command are consumed by PSReadLine before execution and are unsupported. A timeout closes the uncertain shell and reports bounded partial output and the reset. Cancellation resets the shell and discards command output. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. +A call without an owning agent session fails with `pwsh requires an owning agent session` (`ToolContextUnavailableError`, `TOOL_CONTEXT_UNAVAILABLE`), a blank command fails with `ToolArgsError` (`INVALID_ARGS`), and a composition without a pwsh-dialect PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. A model redefinition of the `prompt` function removes the readiness marker, and the shell then settles on the silence tier instead of the marker fast path. Raw ESC characters inside a command are consumed by PSReadLine before execution and are unsupported. A timeout closes the uncertain shell and reports bounded partial output and the reset. Cancellation resets the shell and discards command output. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. ----- diff --git a/packages/shell/tool-pwsh-persistent/README.zh.md b/packages/shell/tool-pwsh-persistent/README.zh.md index 7f05af221f..f249622ce2 100644 --- a/packages/shell/tool-pwsh-persistent/README.zh.md +++ b/packages/shell/tool-pwsh-persistent/README.zh.md @@ -60,7 +60,7 @@ kind: "package-reference" ### 可能出什么问题 -没有拥有者 agent 会话的调用会以 `pwsh requires an owning agent session` 失败,没有 pwsh 方言 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。模型重定义 `prompt` 函数会移除就绪标记,shell 随后在静默层级而非标记快路径上结算。命令内的原始 ESC 字符会在执行前被 PSReadLine 消费,不受支持。超时关闭不确定的 shell,并报告受限的部分输出与重置。取消会重置 shell 并丢弃命令输出。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 +没有拥有者 agent 会话的调用会以 `pwsh requires an owning agent session`(`ToolContextUnavailableError`,`TOOL_CONTEXT_UNAVAILABLE`)失败,空白命令以 `ToolArgsError`(`INVALID_ARGS`)失败,没有 pwsh 方言 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。模型重定义 `prompt` 函数会移除就绪标记,shell 随后在静默层级而非标记快路径上结算。命令内的原始 ESC 字符会在执行前被 PSReadLine 消费,不受支持。超时关闭不确定的 shell,并报告受限的部分输出与重置。取消会重置 shell 并丢弃命令输出。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 ----- diff --git a/packages/shell/tool-pwsh-persistent/src/index.ts b/packages/shell/tool-pwsh-persistent/src/index.ts index 132ca51d2c..69c2ef9990 100644 --- a/packages/shell/tool-pwsh-persistent/src/index.ts +++ b/packages/shell/tool-pwsh-persistent/src/index.ts @@ -13,7 +13,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { truncateWithoutSplittingSurrogatePair } from '@deepseek-ai/dsh-output-retention' import type { TerminalReadResult, TerminalSessionId } from '@deepseek-ai/dsh-terminal' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' -import { defineTool } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' // TODO: Replace the file-search advice; arbitrary command output need not come from a searchable file. const TRUNCATED_MESSAGE = 'To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with Select-String in order to find the line numbers of what you are looking for.' @@ -439,9 +439,9 @@ function registerPersistentPwsh(ctx: Context, config: ResolvedConfig): void { render: (_args, value) => [{ type: 'text', text: value }], }, async execute(args, exec) { - if (args.command.trim().length === 0) throw new Error('command must be a non-empty string') + if (args.command.trim().length === 0) throw new ToolArgsError(['command must be a non-empty string']) const owner = exec.agent - if (owner === undefined) throw new Error('pwsh requires an owning agent session') + if (owner === undefined) throw new ToolContextUnavailableError('pwsh requires an owning agent session') return serialized(owner, async () => { if (exec.signal.aborted) return '' // ToolRuntime publishes ABORTED after settlement. return executeCommand(ctx, shells, owner, args.command, config, exec.signal) diff --git a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts index f842613039..c22cad7974 100644 --- a/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh-persistent/tests/tools.spec.ts @@ -829,8 +829,13 @@ describe('tool-pwsh-persistent', () => { it('rejects invalid config and invalid calls', async () => { const { ctx, owner, stub } = await setup() - expect((await call(ctx, undefined, 'pwd')).isError).toBe(true) - expect(text(await call(ctx, owner, ' '))).toContain('command must be a non-empty string') + expect(await call(ctx, undefined, 'pwd')).toMatchObject({ + isError: true, + error: { info: { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } }, + }) + const blank = await call(ctx, owner, ' ') + expect(text(blank)).toContain('command must be a non-empty string') + expect(blank).toMatchObject({ isError: true, error: { info: { name: 'ToolArgsError', code: 'INVALID_ARGS' } } }) const controller = new AbortController() controller.abort(new Error('caller stopped')) diff --git a/packages/terminal/terminal-bash/src/index.ts b/packages/terminal/terminal-bash/src/index.ts index 5359948eb6..bdb60aa177 100644 --- a/packages/terminal/terminal-bash/src/index.ts +++ b/packages/terminal/terminal-bash/src/index.ts @@ -8,8 +8,9 @@ import type {} from '@deepseek-ai/dsh-working-directory' import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' -import { TerminalBackendCleanupError } from '@deepseek-ai/dsh-terminal' +import { TerminalBackendCleanupError, TerminalError } from '@deepseek-ai/dsh-terminal' import type { TerminalBackend, TerminalBackendSpawnSpec, TerminalSendOperation } from '@deepseek-ai/dsh-terminal' +import { SubprocessError } from '@deepseek-ai/dsh-subprocess' import type { SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type {} from '@deepseek-ai/dsh-sandbox-policy' @@ -94,12 +95,17 @@ function childEnvironment(spec: TerminalBackendSpawnSpec, dialect: ShellDialect) export const PWSH_PROMPT_SETUP = "function prompt { [Console]::Write([char]27 + ']133;D;' + [int]$LASTEXITCODE + [char]7); '" + CONTROLLED_PROMPT + "' }" +/** The startup deadline failure shared by both dialects. */ +function startupTimeout(): TerminalError { + return new TerminalError('PTY shell did not reach readiness before startup timeout', 'STARTUP_TIMEOUT') +} + async function spawnArgv(ctx: Context, config: ResolvedConfig, policy: SandboxExecutionPolicy, signal?: AbortSignal): Promise { const argv = [config.shellPath, ...config.shellArgs] if (policy.mode === 'danger-full-access') return argv const sandbox = ctx.get('sandbox') if (sandbox === undefined) { - throw new Error(`terminal-bash: sandbox mode "${policy.mode}" requires a ctx.sandbox provider in the execution world`) + throw new TerminalError(`terminal-bash: sandbox mode "${policy.mode}" requires a ctx.sandbox provider in the execution world`, 'NO_SANDBOX') } // Re-state the discriminant because object spread does not preserve its narrowed type. return (await sandbox.confine(argv, { ...policy, mode: policy.mode }, signal)).argv @@ -134,8 +140,8 @@ async function startupSession( ...signal !== undefined ? { signal } : {}, }) const result = await startupOperation.done - if (result.waitReason === 'session_exit') throw new Error('PTY shell exited during startup') - if (result.waitReason === 'timeout') throw new Error('PTY shell did not reach readiness before startup timeout') + if (result.waitReason === 'session_exit') throw new TerminalError('PTY shell exited during startup', 'STARTUP_EXITED') + if (result.waitReason === 'timeout') throw startupTimeout() viewport = result.viewport if (result.waitReason === 'stdin_read') break } @@ -154,7 +160,7 @@ async function startupSession( const deadline = Promise.withResolvers() deadlineTimer = setTimeout(() => { startupOperation?.cancel() - deadline.reject(new Error('PTY shell did not reach readiness before startup timeout')) + deadline.reject(startupTimeout()) }, timeoutMs) races.push(deadline.promise) } @@ -201,7 +207,7 @@ export class BashTerminalBackend implements TerminalBackend { const policy = this.ctx.sandboxPolicy.resolve({ session: spec.owner.session }) const argv = await spawnArgv(this.ctx, this.config, policy, spec.signal) spec.signal?.throwIfAborted() - if (argv[0] === undefined) throw new Error('terminal-bash: sandbox returned empty argv') + if (argv[0] === undefined) throw new SubprocessError('terminal-bash: sandbox returned empty argv', 'SUBPROCESS_INVALID_ARGV') const terminal = await this.spawnTerminal({ argv, cwd: spec.cwd ?? await this.ctx.workingDirectory.ensure(spec.owner, spec.signal), diff --git a/packages/terminal/terminal-bash/src/session.ts b/packages/terminal/terminal-bash/src/session.ts index 993b15c4ee..a78c6e4f7c 100644 --- a/packages/terminal/terminal-bash/src/session.ts +++ b/packages/terminal/terminal-bash/src/session.ts @@ -314,8 +314,8 @@ export class LocalPtySession implements TerminalBackendSession { try { const operation = this.startSend({ text: '', submit: false, ...signal !== undefined ? { signal } : {} }) const result = await operation.done - if (result.waitReason === 'session_exit') throw new Error('PTY shell exited during startup') - if (result.waitReason === 'timeout') throw new Error('PTY shell did not reach readiness before startup timeout') + if (result.waitReason === 'session_exit') throw new TerminalError('PTY shell exited during startup', 'STARTUP_EXITED') + if (result.waitReason === 'timeout') throw new TerminalError('PTY shell did not reach readiness before startup timeout', 'STARTUP_TIMEOUT') this.motd = result.viewport } catch (error: unknown) { signal?.throwIfAborted() @@ -326,8 +326,8 @@ export class LocalPtySession implements TerminalBackendSession { } startSend(request: TerminalSendRequest): TerminalSendOperation { - if (this.closing) throw new Error('PTY session is closing') - if (this.statusValue.kind === 'exited') throw new Error('PTY session has exited') + if (this.closing) throw new TerminalError('PTY session is closing', 'SESSION_CLOSING') + if (this.statusValue.kind === 'exited') throw new TerminalError('PTY session has exited', 'SESSION_EXITED') if (this.active !== undefined) { const draining = this.activeWrite !== undefined ? ' or draining provider write' @@ -336,7 +336,12 @@ export class LocalPtySession implements TerminalBackendSession { : '' throw new TerminalError(`PTY session already has an active send${draining}`, 'SEND_ACTIVE') } - if (request.signal?.aborted === true) throw new Error('PTY send aborted before write') + if (request.signal?.aborted === true) { + // Named as a cancellation so the tool registry classifies it as the caller's abort. + const aborted = new Error('PTY send aborted before write') + aborted.name = 'AbortError' + throw aborted + } const operation = new LocalSendOperation( this.config.maxReadBytes, @@ -452,7 +457,7 @@ export class LocalPtySession implements TerminalBackendSession { } async signal(signal: TerminalSignal): Promise { - if (this.closing) throw new Error('PTY session is closing') + if (this.closing) throw new TerminalError('PTY session is closing', 'SESSION_CLOSING') const targetPgid = await this.terminal.signalForeground(signal) return { delivered: true, targetPgid } } diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index 71793a5f6e..d992f8ee7f 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -133,6 +133,7 @@ describe('BashTerminalBackend startup rollback', () => { controller.abort(abortReason) await expect(backend.spawn(spec(agent(ctx), controller.signal))).rejects.toBe(abortReason) await expect(backend.spawn(spec(agent(ctx)))).rejects.toThrow('empty argv') + await expect(backend.spawn(spec(agent(ctx)))).rejects.toMatchObject({ name: 'SubprocessError', code: 'SUBPROCESS_INVALID_ARGV' }) }) it('closes failed startup and aggregates cleanup failure', async () => { @@ -347,6 +348,7 @@ describe('BashTerminalBackend startup rollback', () => { await expect(confined.spawn(spec(agent(confinedCtx)))).rejects.toThrow( 'sandbox mode "workspace-write" requires a ctx.sandbox provider in the execution world', ) + await expect(confined.spawn(spec(agent(confinedCtx)))).rejects.toEqual(expect.objectContaining({ name: 'TerminalError', code: 'NO_SANDBOX' })) }) it('forwards terminal allocation cancellation directly', async () => { @@ -523,8 +525,10 @@ describe('BashTerminalBackend startup rollback', () => { }) as unknown as LocalPtySession const exited = new BashTerminalBackend(ctx, { ...config(), shellDialect: 'pwsh' }, async () => terminalHandle(), () => sessionFor('session_exit')) await expect(exited.spawn(spec(agent(ctx)))).rejects.toThrow('PTY shell exited during startup') + await expect(exited.spawn(spec(agent(ctx)))).rejects.toEqual(expect.objectContaining({ name: 'TerminalError', code: 'STARTUP_EXITED' })) const timedOut = new BashTerminalBackend(ctx, { ...config(), shellDialect: 'pwsh' }, async () => terminalHandle(), () => sessionFor('timeout')) await expect(timedOut.spawn(spec(agent(ctx)))).rejects.toThrow('did not reach readiness before startup timeout') + await expect(timedOut.spawn(spec(agent(ctx)))).rejects.toEqual(expect.objectContaining({ name: 'TerminalError', code: 'STARTUP_TIMEOUT' })) }) it('bounds all pwsh startup retries with one deadline', async () => { diff --git a/packages/terminal/terminal-bash/tests/session.spec.ts b/packages/terminal/terminal-bash/tests/session.spec.ts index bff1317c26..4dab23a32e 100644 --- a/packages/terminal/terminal-bash/tests/session.spec.ts +++ b/packages/terminal/terminal-bash/tests/session.spec.ts @@ -752,6 +752,7 @@ describe('LocalPtySession readiness and output', () => { terminal.emitExit(7, 9) expect(await exiting.done).toMatchObject({ waitReason: 'session_exit', sessionStatus: { kind: 'exited', exitCode: null, signal: 'SIGKILL' } }) expect(() => session.startSend({ text: '', submit: false })).toThrow('has exited') + expect(() => session.startSend({ text: '', submit: false })).toThrow(expect.objectContaining({ name: 'TerminalError', code: 'SESSION_EXITED' })) }) it('cancels with foreground-group SIGINT, observes AbortSignal, and contains write failures', async () => { @@ -776,6 +777,7 @@ describe('LocalPtySession readiness and output', () => { const aborted = new AbortController() aborted.abort() expect(() => session.startSend({ text: '', submit: false, signal: aborted.signal })).toThrow('aborted before write') + expect(() => session.startSend({ text: '', submit: false, signal: aborted.signal })).toThrow(expect.objectContaining({ name: 'AbortError' })) terminal.throwWrite = true const failed = session.startSend({ text: 'x', submit: false }) @@ -1166,6 +1168,7 @@ describe('LocalPtySession readiness and output', () => { const initializing = startup.initialize(new AbortController().signal) startupTerminal.emitExit(1) await expect(initializing).rejects.toThrow('exited during startup') + await expect(initializing).rejects.toEqual(expect.objectContaining({ name: 'TerminalError', code: 'STARTUP_EXITED' })) expect(startup.status()).toEqual({ kind: 'exited', exitCode: 1, signal: null }) const terminal = new FakeTerminal() @@ -1238,7 +1241,9 @@ describe('LocalPtySession readiness and output', () => { const timeoutTerminal = new FakeTerminal() const timeout = new LocalPtySession(timeoutTerminal, config()) - const timedOut = expect(timeout.initialize()).rejects.toThrow('startup timeout') + const timedOut = expect(timeout.initialize()).rejects.toEqual(expect.objectContaining({ + name: 'TerminalError', code: 'STARTUP_TIMEOUT', message: expect.stringContaining('startup timeout') as string, + })) await vi.advanceTimersByTimeAsync(100) await timedOut }) @@ -1640,8 +1645,8 @@ describe('LocalPtySession bounds, signals, and teardown', () => { const closing = session.close('test') expect(session.close('other')).toBe(closing) await expect(closing).rejects.toThrow('PTY cleanup failed (test)') - expect(() => session.startSend({ text: '', submit: false })).toThrow('closing') - await expect(session.signal('SIGTERM')).rejects.toThrow('closing') + expect(() => session.startSend({ text: '', submit: false })).toThrow(expect.objectContaining({ name: 'TerminalError', code: 'SESSION_CLOSING' })) + await expect(session.signal('SIGTERM')).rejects.toEqual(expect.objectContaining({ name: 'TerminalError', code: 'SESSION_CLOSING' })) }) it('reports cleanup failure without waiting for top-level exit and permits retry', async () => { diff --git a/packages/terminal/terminal/README.i18n.yaml b/packages/terminal/terminal/README.i18n.yaml index 50ce7993cf..6b91667f72 100644 --- a/packages/terminal/terminal/README.i18n.yaml +++ b/packages/terminal/terminal/README.i18n.yaml @@ -48,8 +48,8 @@ en: 7af36e58919e41d5 zh: 4fe7b4db1099bcbf /deepseek-ai-dsh-terminal/understand-the-implementation/send-reservation: - en: 5815723cd0c6089c - zh: 0c612ffa4b8c466c + en: 0b8dc3a382aa7bf2 + zh: e6cc6906e01827d2 /deepseek-ai-dsh-terminal/further-exploration: en: 8459a3b70a9f8bad zh: 21372aa8939d2182 diff --git a/packages/terminal/terminal/README.md b/packages/terminal/terminal/README.md index 26e8506bd8..40cb6866f8 100644 --- a/packages/terminal/terminal/README.md +++ b/packages/terminal/terminal/README.md @@ -88,7 +88,7 @@ Each published session is a record of its id, owner, optional name, backend type ### Send reservation -The service reserves a session synchronously for one active send before returning the operation, including before a background job id becomes visible; a second send fails with `SEND_ACTIVE`, so output and cancellation never cross operation ownership. +The service reserves a session synchronously for one active send before returning the operation, including before a background job id becomes visible; a second send fails with `SEND_ACTIVE`, so output and cancellation never cross operation ownership. Failures are `TerminalError` instances (a `HarnessError`); besides the registry codes, a send to a closing session fails with `SESSION_CLOSING`, and backends report `SESSION_EXITED`, `STARTUP_EXITED`, `STARTUP_TIMEOUT`, `NO_SANDBOX`, and `INIT_REJECTED` with the same class.
diff --git a/packages/terminal/terminal/README.zh.md b/packages/terminal/terminal/README.zh.md index a185554a9e..bb21c9e502 100644 --- a/packages/terminal/terminal/README.zh.md +++ b/packages/terminal/terminal/README.zh.md @@ -88,7 +88,7 @@ kind: "package-reference" ### 发送预留 -服务在返回操作之前同步为一个活跃发送预留会话,包括在后台任务的 job id 可见之前;第二次发送会以 `SEND_ACTIVE` 失败,因此输出与取消永远不会跨操作所有权。 +服务在返回操作之前同步为一个活跃发送预留会话,包括在后台任务的 job id 可见之前;第二次发送会以 `SEND_ACTIVE` 失败,因此输出与取消永远不会跨操作所有权。失败均为 `TerminalError`(一种 `HarnessError`);除注册表 code 外,向正在关闭的会话发送会以 `SESSION_CLOSING` 失败,后端以同一类报告 `SESSION_EXITED`、`STARTUP_EXITED`、`STARTUP_TIMEOUT`、`NO_SANDBOX` 与 `INIT_REJECTED`。
diff --git a/packages/terminal/terminal/src/index.ts b/packages/terminal/terminal/src/index.ts index f97ab51cae..df09ff94aa 100644 --- a/packages/terminal/terminal/src/index.ts +++ b/packages/terminal/terminal/src/index.ts @@ -52,16 +52,29 @@ declare module '@deepseek-ai/cordis' { } } -/** Machine-routable PTY service failures. */ +/** + * Machine-routable PTY service and backend failures. Backends use + * `INIT_REJECTED` when the shell rejects its setup input, `NO_SANDBOX` when a + * confined mode has no sandbox provider, `SESSION_CLOSING` and + * `SESSION_EXITED` for an operation on a closing or exited session, and + * `STARTUP_EXITED` or `STARTUP_TIMEOUT` when the shell exits or misses + * readiness during startup. + */ export type TerminalErrorCode = | 'DUPLICATE_BACKEND' | 'DUPLICATE_NAME' | 'FOREIGN_SESSION' + | 'INIT_REJECTED' | 'NO_BACKEND' + | 'NO_SANDBOX' | 'NO_SESSION' | 'OWNER_NOT_LIVE' | 'SEND_ACTIVE' | 'SERVICE_DISPOSING' + | 'SESSION_CLOSING' + | 'SESSION_EXITED' + | 'STARTUP_EXITED' + | 'STARTUP_TIMEOUT' /** Harness error carrying a stable {@link TerminalErrorCode}. */ export class TerminalError extends HarnessError { @@ -246,7 +259,7 @@ export class TerminalSessionService extends Service { */ startSend(owner: Agent, id: TerminalSessionId, request: TerminalSendRequest): TerminalSendOperation { const record = this.expectOwned(owner, id) - if (record.closing !== undefined) throw new Error(`PTY session ${id} is closing`) + if (record.closing !== undefined) throw new TerminalError(`PTY session ${id} is closing`, 'SESSION_CLOSING') if (record.active !== undefined) throw new TerminalError(`PTY session ${id} already has an active send`, 'SEND_ACTIVE') const operation = record.session.startSend(request) record.active = operation diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 3d8304275b..0237f2970a 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -525,6 +525,8 @@ describe('TerminalSessionService ownership and lifecycle', () => { b.sessions[0]!.closeGate = Promise.withResolvers() const first = ctx.terminals.kill(owner, created.sessionId) expect(() => ctx.terminals.startSend(owner, created.sessionId, { text: '', submit: false })).toThrow('closing') + expect(() => ctx.terminals.startSend(owner, created.sessionId, { text: '', submit: false })) + .toThrow(expect.objectContaining({ name: 'TerminalError', code: 'SESSION_CLOSING' })) const second = ctx.terminals.kill(owner, created.sessionId) b.sessions[0]!.closeGate?.resolve(undefined) expect(await first).toBe(true) From 818b603ed4ea8128e2c2b3cd346502758780da5d Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:38:23 +0800 Subject: [PATCH 048/438] feat(shell-env): add ShellEnvError for invalid contributions A contributor that returns an undeclared key or a non-string value now fails the shell call with ShellEnvError SHELL_ENV_CONTRIBUTION_INVALID instead of a plain Error, with the same message. Refs #7869 --- packages/shell/shell-env/README.i18n.yaml | 4 +-- packages/shell/shell-env/README.md | 2 +- packages/shell/shell-env/README.zh.md | 2 +- packages/shell/shell-env/package.json | 3 +- packages/shell/shell-env/src/index.ts | 33 +++++++++++++++++-- .../shell/shell-env/tests/shell-env.spec.ts | 2 ++ packages/shell/shell-env/tsconfig.json | 3 ++ 7 files changed, 42 insertions(+), 7 deletions(-) diff --git a/packages/shell/shell-env/README.i18n.yaml b/packages/shell/shell-env/README.i18n.yaml index 63f09470f2..eac66fcb65 100644 --- a/packages/shell/shell-env/README.i18n.yaml +++ b/packages/shell/shell-env/README.i18n.yaml @@ -21,8 +21,8 @@ en: bab0b75fb967d41a zh: 8f636d9965d01ad1 /deepseek-ai-dsh-shell-env/use-this-package/adding-your-own-environment-facts: - en: 21ef223626e35905 - zh: 5c468055099b0135 + en: 14da34f853d089be + zh: 5ad3942aa5321893 /deepseek-ai-dsh-shell-env/use-this-package/choosing-the-harness-home: en: 0041438f2b7f7e4f zh: 93fa165b07adcdf4 diff --git a/packages/shell/shell-env/README.md b/packages/shell/shell-env/README.md index c2507b3c7c..86037caffe 100644 --- a/packages/shell/shell-env/README.md +++ b/packages/shell/shell-env/README.md @@ -50,7 +50,7 @@ export function apply(ctx: Context): void { } ``` -Contributors must declare every key they return; returning an undeclared or non-string value fails the call. Registration is disposed with the registering plugin, so hot-reloading a plugin removes its facts. +Contributors must declare every key they return; returning an undeclared or non-string value fails the call with `ShellEnvError` (`SHELL_ENV_CONTRIBUTION_INVALID`). Registration is disposed with the registering plugin, so hot-reloading a plugin removes its facts. ### Choosing the Harness home diff --git a/packages/shell/shell-env/README.zh.md b/packages/shell/shell-env/README.zh.md index 8860c11b54..a3d4a98516 100644 --- a/packages/shell/shell-env/README.zh.md +++ b/packages/shell/shell-env/README.zh.md @@ -50,7 +50,7 @@ export function apply(ctx: Context): void { } ``` -contributor 必须声明它返回的每个键;返回未声明或非字符串的值会让该次调用失败。注册随注册插件的释放而释放,因此热重载插件会移除它的事实。 +contributor 必须声明它返回的每个键;返回未声明或非字符串的值会让该次调用以 `ShellEnvError`(`SHELL_ENV_CONTRIBUTION_INVALID`)失败。注册随注册插件的释放而释放,因此热重载插件会移除它的事实。 ### 选择 Harness 主目录 diff --git a/packages/shell/shell-env/package.json b/packages/shell/shell-env/package.json index 4fb761f034..4fb7d7de4f 100644 --- a/packages/shell/shell-env/package.json +++ b/packages/shell/shell-env/package.json @@ -36,7 +36,8 @@ "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", "@deepseek-ai/dsh-shell": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" diff --git a/packages/shell/shell-env/src/index.ts b/packages/shell/shell-env/src/index.ts index d53a393a8d..aa3012e2b4 100644 --- a/packages/shell/shell-env/src/index.ts +++ b/packages/shell/shell-env/src/index.ts @@ -14,6 +14,7 @@ import z from '@deepseek-ai/schemastery' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-shell' import type { DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-shell' import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-home-paths' +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { ToolExecution } from '@deepseek-ai/dsh-tools' // Declares `Context.profileContext`, the launcher-provided profile the built-ins read. import type {} from '@deepseek-ai/dsh-app-boot' @@ -24,6 +25,31 @@ declare module '@deepseek-ai/cordis' { } } +/** + * Every {@link ShellEnvError} code: + * - `SHELL_ENV_CONTRIBUTION_INVALID` — a registered contributor returned an undeclared key or a non-string value; the + * shell command does not run, and the contributing plugin must be fixed. + */ +export const SHELL_ENV_ERROR_CODES = ['SHELL_ENV_CONTRIBUTION_INVALID'] as const + +/** One code from {@link SHELL_ENV_ERROR_CODES}. */ +export type ShellEnvErrorCode = typeof SHELL_ENV_ERROR_CODES[number] + +/** Shell environment failure carrying a stable {@link ShellEnvErrorCode}. */ +export class ShellEnvError extends HarnessError { + override readonly code: ShellEnvErrorCode + + /** + * @param message - names the contributor and the offending key. + * @param code - the failure class consumers route on. + */ + constructor(message: string, code: ShellEnvErrorCode) { + super(message, code) + this.name = 'ShellEnvError' + this.code = code + } +} + export const name = 'shell-env' export const inject: string[] = [] @@ -182,10 +208,13 @@ export class ShellEnvRegistry extends Service { for (const [rawKey, value] of Object.entries(resolved)) { const key = rawKey as DshEnvironmentKey if (!Object.hasOwn(contributor.variables, key)) { - throw new Error(`bash env contributor "${contributor.name}" returned undeclared key "${key}"`) + throw new ShellEnvError(`bash env contributor "${contributor.name}" returned undeclared key "${key}"`, 'SHELL_ENV_CONTRIBUTION_INVALID') } if (typeof value !== 'string') { - throw new Error(`bash env contributor "${contributor.name}" returned a non-string value for "${key}"`) + throw new ShellEnvError( + `bash env contributor "${contributor.name}" returned a non-string value for "${key}"`, + 'SHELL_ENV_CONTRIBUTION_INVALID', + ) } values[key] = value } diff --git a/packages/shell/shell-env/tests/shell-env.spec.ts b/packages/shell/shell-env/tests/shell-env.spec.ts index e14d41b06c..74590aa42e 100644 --- a/packages/shell/shell-env/tests/shell-env.spec.ts +++ b/packages/shell/shell-env/tests/shell-env.spec.ts @@ -192,6 +192,7 @@ describe('ShellEnvRegistry', () => { }) expect(() => registry.collect(execution())).toThrow(/drifted-provider.*DSH_UNDECLARED/) + expect(() => registry.collect(execution())).toThrow(expect.objectContaining({ name: 'ShellEnvError', code: 'SHELL_ENV_CONTRIBUTION_INVALID' })) }) it('rejects non-string values returned by a contributor', () => { @@ -203,6 +204,7 @@ describe('ShellEnvRegistry', () => { }) expect(() => registry.collect(execution())).toThrow(/wrong-value-type.*non-string.*DSH_STRING/) + expect(() => registry.collect(execution())).toThrow(expect.objectContaining({ name: 'ShellEnvError', code: 'SHELL_ENV_CONTRIBUTION_INVALID' })) }) it('removes an effect-scoped contributor when its plugin is disposed', async () => { diff --git a/packages/shell/shell-env/tsconfig.json b/packages/shell/shell-env/tsconfig.json index fc6a34b571..ae66c37da9 100644 --- a/packages/shell/shell-env/tsconfig.json +++ b/packages/shell/shell-env/tsconfig.json @@ -28,6 +28,9 @@ }, { "path": "../../boot/app-boot" + }, + { + "path": "../../llm/llm" } ] } From 529077d109a444b14158f9f98d1917e1fa70bd92 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:48:50 +0800 Subject: [PATCH 049/438] test(snapshots): record structured errors for shell, job, and escalation failures Refreshed replays now persist error.name and error.code on three tool results that previously carried only text: the rejected escalation (SandboxEscalationError SANDBOX_ESCALATION_REJECTED), the background job limit (JobError JOB_LIMIT_REACHED), and the unknown job id after a missing sandbox runner (JobError JOB_NOT_FOUND). Model-visible content is unchanged. Refs #7869 --- snapshots/acp/escalation-rejected/session.v4.jsonl | 2 +- snapshots/session/background-job-admission/session.v4.jsonl | 2 +- snapshots/session/missing-sandbox-runner/session.v4.jsonl | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/snapshots/acp/escalation-rejected/session.v4.jsonl b/snapshots/acp/escalation-rejected/session.v4.jsonl index e0eabb8fe3..434c7bcf86 100644 --- a/snapshots/acp/escalation-rejected/session.v4.jsonl +++ b/snapshots/acp/escalation-rejected/session.v4.jsonl @@ -16,7 +16,7 @@ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","name":"bash","arguments":"{\"command\": \"printf 'escalated\\\\n' > /tmp/dsh-escalated.txt && cat /tmp/dsh-escalated.txt && rm /tmp/dsh-escalated.txt\", \"description\": \"Write to /tmp and verify, then clean up\", \"sandbox_permissions\": \"danger-full-access\", \"justification\": \"the user asked to write a file outside the workspace\"}"}} {"type":"approval/asked","data":{"id":"{{approval:1}}","toolName":"bash","callId":"call_00_WB1vnPomi8yr6MlcFKTj7912","reason":"escalate sandbox to danger-full-access: the user asked to write a file outside the workspace"}} {"type":"approval/decided","data":{"id":"{{approval:1}}","outcome":"rejected"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_WB1vnPomi8yr6MlcFKTj7912"},"toolCallId":"call_00_WB1vnPomi8yr6MlcFKTj7912","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\"; it stays denied, so stop and explain instead of working around it"}],"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_00_WB1vnPomi8yr6MlcFKTj7912"},"toolCallId":"call_00_WB1vnPomi8yr6MlcFKTj7912","content":[{"type":"text","text":"Error: the user rejected escalating this command to \"danger-full-access\"; it stays denied, so stop and explain instead of working around it"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"SandboxEscalationError","code":"SANDBOX_ESCALATION_REJECTED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."},{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30},"stream":[{"type":"chunk","time":1788699392206,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699392206,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," rejected"," the"," escalation","."," As"," instructed",","," I"," will"," not"," ret","ry"," and"," will"," not"," work"," around"," it"," —"," just"," explain"," in"," one"," short"," sentence"," and"," stop","."]},{"type":"chunk","time":1788699392207,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699392207,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," rejected"," the"," permission"," escalation",","," so"," this"," command"," cannot"," be"," run","."]},{"type":"chunk","time":1788699392207,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user rejected the escalation. As instructed, I will not retry and will not work around it — just explain in one short sentence and stop."}}},{"type":"chunk","time":1788699392207,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"The user rejected the permission escalation, so this command cannot be run."}}},{"type":"chunk","time":1788699392207,"chunk":{"type":"usage","usage":{"inputTokens":69,"outputTokens":45,"cacheReadTokens":1664,"reasoningTokens":30}}},{"type":"chunk","time":1788699392207,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/background-job-admission/session.v4.jsonl b/snapshots/session/background-job-admission/session.v4.jsonl index 161b12144f..4c37185c96 100644 --- a/snapshots/session/background-job-admission/session.v4.jsonl +++ b/snapshots/session/background-job-admission/session.v4.jsonl @@ -20,7 +20,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bounded-task-second","name":"bash","arguments":"{\"command\":\"printf SHOULD_NOT_RUN > second-task-ran.txt; while :; do sleep 60; done\",\"description\":\"Attempt a second background job\",\"run_in_background\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427794157,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427794157,"index":0,"dt":[],"id":"bounded-task-second","name":"bash","args":["{\"command\":\"printf SHOULD_NOT_RUN > second-task-ran.txt; while :; do sleep 60; done\",\"description\":\"Attempt a second background job\",\"run_in_background\":true}"]},{"type":"chunk","time":1791427794157,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bounded-task-second","name":"bash","arguments":"{\"command\":\"printf SHOULD_NOT_RUN > second-task-ran.txt; while :; do sleep 60; done\",\"description\":\"Attempt a second background job\",\"run_in_background\":true}"}}},{"type":"chunk","time":1791427794157,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427794157,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"bounded-task-second","name":"bash","arguments":"{\"command\":\"printf SHOULD_NOT_RUN > second-task-ran.txt; while :; do sleep 60; done\",\"description\":\"Attempt a second background job\",\"run_in_background\":true}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"bounded-task-second"},"toolCallId":"bounded-task-second","content":[{"type":"text","text":"Error: background job limit reached for this owner (limit: 1); use job_kill to stop an unneeded job, wait for it to finish, then retry"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[20],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"bounded-task-second"},"toolCallId":"bounded-task-second","content":[{"type":"text","text":"Error: background job limit reached for this owner (limit: 1); use job_kill to stop an unneeded job, wait for it to finish, then retry"}],"isError":true,"id":"{{message:7}}"},"error":{"name":"JobError","code":"JOB_LIMIT_REACHED"}},"sourceEventSeqs":[20],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"bounded-task-kill","name":"job_kill","arguments":"{\"job_id\":\"{{id:1}}\",\"reason\":\"free the bounded task slot\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1791427794174,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427794174,"index":0,"dt":[],"id":"bounded-task-kill","name":"job_kill","args":["{\"job_id\":\"{{id:1}}\",\"reason\":\"free the bounded task slot\"}"]},{"type":"chunk","time":1791427794174,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"bounded-task-kill","name":"job_kill","arguments":"{\"job_id\":\"{{id:1}}\",\"reason\":\"free the bounded task slot\"}"}}},{"type":"chunk","time":1791427794174,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1791427794174,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/missing-sandbox-runner/session.v4.jsonl b/snapshots/session/missing-sandbox-runner/session.v4.jsonl index a6bc8b460e..7922555084 100644 --- a/snapshots/session/missing-sandbox-runner/session.v4.jsonl +++ b/snapshots/session/missing-sandbox-runner/session.v4.jsonl @@ -21,7 +21,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"missing-runner-output","name":"job_output","arguments":"{\"job_id\":\"bash-1\",\"wait\":true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":1,"outputTokens":1},"stream":[{"type":"chunk","time":1791427848744,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791427848744,"index":0,"dt":[],"id":"missing-runner-output","name":"job_output","args":["{\"job_id\":\"bash-1\",\"wait\":true}"]},{"type":"chunk","time":1791427848744,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"missing-runner-output","name":"job_output","arguments":"{\"job_id\":\"bash-1\",\"wait\":true}"}}},{"type":"chunk","time":1791427848744,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}},{"type":"chunk","time":1791427848744,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"missing-runner-output","name":"job_output","arguments":"{\"job_id\":\"bash-1\",\"wait\":true}"}} -{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"missing-runner-output"},"toolCallId":"missing-runner-output","content":[{"type":"text","text":"Error: unknown job bash-1"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[21],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"missing-runner-output"},"toolCallId":"missing-runner-output","content":[{"type":"text","text":"Error: unknown job bash-1"}],"isError":true,"id":"{{message:7}}"},"error":{"name":"JobError","code":"JOB_NOT_FOUND"}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"RUNNER_FAILURES_SURFACED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":1,"outputTokens":1},"stream":[{"type":"chunk","time":1791427848761,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1791427848761,"index":0,"dt":[],"texts":["RUNNER_FAILURES_SURFACED"]},{"type":"chunk","time":1791427848762,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"RUNNER_FAILURES_SURFACED"}}},{"type":"chunk","time":1791427848762,"chunk":{"type":"usage","usage":{"inputTokens":1,"outputTokens":1}}},{"type":"chunk","time":1791427848762,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} From c92eded7e4eca82ce31f4b41c0a2d35bce9599da Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:59:04 +0800 Subject: [PATCH 050/438] docs: regenerate catalogs for the shell, sandbox, and working-directory errors Regenerated Cordis, config, and persistence catalogs pick up the new WorkingDirectoryError and SandboxPreparationError exports and the shifted source lines; persisted type digests are unchanged. Refs #7869 --- docs/config-catalog.md | 14 +++++++------- docs/config-catalog.zh.md | 14 +++++++------- docs/persistence-catalog.i18n.yaml | 16 ++++++++-------- docs/persistence-catalog.md | 8 ++++---- docs/persistence-catalog.zh.md | 8 ++++---- docs/persistence-schema.json | 6 +++--- docs/subsystems/sandbox.md | 2 ++ docs/subsystems/sandbox.zh.md | 2 ++ docs/subsystems/working-directory.md | 7 +++++-- docs/subsystems/working-directory.zh.md | 7 +++++-- .../extensions/tool-cordis/src/api-catalog.ts | 5 +++-- 11 files changed, 50 insertions(+), 39 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..90892cc3dd 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1891,7 +1891,7 @@ export interface TlsConfig { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:47`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -2938,7 +2938,7 @@ export interface Config { ## `@deepseek-ai/dsh-sandbox-local` -- `source`: [`packages/sandbox/sandbox-local/src/index.ts:45`](../packages/sandbox/sandbox-local/src/index.ts) +- `source`: [`packages/sandbox/sandbox-local/src/index.ts:63`](../packages/sandbox/sandbox-local/src/index.ts) ```ts config-catalog /** Plugin config. All optional — `static Config` supplies the defaults. */ @@ -3362,7 +3362,7 @@ export interface Config extends SessionTitleLlmConfig { ## `@deepseek-ai/dsh-shell-env` -- `source`: [`packages/shell/shell-env/src/index.ts:31`](../packages/shell/shell-env/src/index.ts) +- `source`: [`packages/shell/shell-env/src/index.ts:57`](../packages/shell/shell-env/src/index.ts) ```ts config-catalog /** Plugin config (all optional — the built-in facts resolve without defaults). */ @@ -4083,7 +4083,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-bash/src/index.ts:37`](../packages/shell/tool-bash/src/index.ts) +- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts) ```ts config-catalog /** Configuration for the bash tool. */ @@ -4113,7 +4113,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash-persistent` - `inject`: `tools` · `terminals` · `workingDirectory` -- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:447`](../packages/shell/tool-bash-persistent/src/index.ts) +- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:448`](../packages/shell/tool-bash-persistent/src/index.ts) ```ts config-catalog /** Configuration for the persistent Bash tool. */ @@ -4348,7 +4348,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-pwsh` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-pwsh/src/index.ts:54`](../packages/shell/tool-pwsh/src/index.ts) +- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts) ```ts config-catalog /** Configuration for the pwsh tool. */ @@ -4942,7 +4942,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:70`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..663fb50b89 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1893,7 +1893,7 @@ export interface TlsConfig { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:47`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -2940,7 +2940,7 @@ export interface Config { ## `@deepseek-ai/dsh-sandbox-local` -- `source`: [`packages/sandbox/sandbox-local/src/index.ts:45`](../packages/sandbox/sandbox-local/src/index.ts) +- `source`: [`packages/sandbox/sandbox-local/src/index.ts:63`](../packages/sandbox/sandbox-local/src/index.ts) ```ts config-catalog /** Plugin config. All optional — `static Config` supplies the defaults. */ @@ -3364,7 +3364,7 @@ export interface Config extends SessionTitleLlmConfig { ## `@deepseek-ai/dsh-shell-env` -- `source`: [`packages/shell/shell-env/src/index.ts:31`](../packages/shell/shell-env/src/index.ts) +- `source`: [`packages/shell/shell-env/src/index.ts:57`](../packages/shell/shell-env/src/index.ts) ```ts config-catalog /** Plugin config (all optional — the built-in facts resolve without defaults). */ @@ -4085,7 +4085,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-bash/src/index.ts:37`](../packages/shell/tool-bash/src/index.ts) +- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts) ```ts config-catalog /** Configuration for the bash tool. */ @@ -4115,7 +4115,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash-persistent` - `inject`: `tools` · `terminals` · `workingDirectory` -- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:447`](../packages/shell/tool-bash-persistent/src/index.ts) +- `source`: [`packages/shell/tool-bash-persistent/src/index.ts:448`](../packages/shell/tool-bash-persistent/src/index.ts) ```ts config-catalog /** Configuration for the persistent Bash tool. */ @@ -4350,7 +4350,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-pwsh` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-pwsh/src/index.ts:54`](../packages/shell/tool-pwsh/src/index.ts) +- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts) ```ts config-catalog /** Configuration for the pwsh tool. */ @@ -4944,7 +4944,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:67`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:70`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index a5fb682b48..4214f43702 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -300,8 +300,8 @@ en: e8dd0cebbb930eb7 zh: e8dd0cebbb930eb7 /session-persistence-event-catalog/events/working-directory/working-directory-change-log-only: - en: fc893ed0d93765df - zh: 2df365d9d0ac6f6e + en: 27f0761cbdd6fe2f + zh: 33528f333498132d /session-persistence-event-catalog/events/workspace: en: 63ee1a85e4b59ae3 zh: 63ee1a85e4b59ae3 @@ -1203,8 +1203,8 @@ en: 1f691c223f54ab2c zh: f88fef3ee9745c91 /session-persistence-event-catalog/resolved-persistence-types/sandboxmode: - en: c9fa5343ea99733b - zh: d6de41351c57a73f + en: 5adc2bf6745ccc67 + zh: 566cb9aaa4a177c9 /session-persistence-event-catalog/resolved-persistence-types/schedulechange: en: b20a355fde48f699 zh: 5d0fd858e2dbff06 @@ -1494,8 +1494,8 @@ en: bef51e0442ebb903 zh: 240ebeb160533d8c /session-persistence-event-catalog/resolved-persistence-types/cwd: - en: 35feea0430c0f14b - zh: d5aaf1d2ca80114a + en: 2809c921c6996791 + zh: 80b15177561766d7 /session-persistence-event-catalog/resolved-persistence-types/decision-durationms-exitcode-handlerid: en: a99ac57bbec0370f zh: 9073329e324a66e0 @@ -1929,8 +1929,8 @@ en: 0b74295f7c5c8f11 zh: 5f1213cec87f6be0 /session-persistence-event-catalog/resolved-persistence-types/kind-working-directory: - en: 626ea3180b86e5b6 - zh: 4b6e0dc1312b3c5a + en: b28ca6b37f5a338d + zh: 4c4f2f05721b8b62 /session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking: en: 3216b23c131d0070 zh: 73ca171c6014f16e diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6b80fbbc99..cd09a9358c 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -1329,7 +1329,7 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../packages/web/ } ``` -Source: [`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts) +Source: [`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) ### `workspace/*` @@ -4619,7 +4619,7 @@ One of: SHA-256: `fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd` -Sources: [`packages/sandbox/sandbox/src/index.ts:30`](../packages/sandbox/sandbox/src/index.ts) +Sources: [`packages/sandbox/sandbox/src/index.ts:38`](../packages/sandbox/sandbox/src/index.ts) One of: @@ -6209,7 +6209,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:24`](../packages/compacti SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` -Sources: [`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts) +Sources: [`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -7949,7 +7949,7 @@ Sources: [`packages/experimental/webhook/src/types.ts:74`](../packages/experimen SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` -Sources: [`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts) +Sources: [`packages/session/working-directory/src/index.ts:48`](../packages/session/working-directory/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c73b594c28..84c826fe67 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -1331,7 +1331,7 @@ export type SessionEvent = { } ``` -来源:[`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) ### `workspace/*` @@ -4621,7 +4621,7 @@ SHA-256: `530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6` SHA-256: `fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd` -来源:[`packages/sandbox/sandbox/src/index.ts:30`](../packages/sandbox/sandbox/src/index.ts) +来源:[`packages/sandbox/sandbox/src/index.ts:38`](../packages/sandbox/sandbox/src/index.ts) 以下类型之一: @@ -6211,7 +6211,7 @@ SHA-256: `3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f` SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` -来源:[`packages/session/working-directory/src/index.ts:52`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7951,7 +7951,7 @@ SHA-256: `9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94` SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` -来源:[`packages/session/working-directory/src/index.ts:45`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:48`](../packages/session/working-directory/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 3a1b058f36..a2832eb98c 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -159,7 +159,7 @@ {"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":[]}, - {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:45"]}, + {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:48"]}, {"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]}, {"digest":"234142ee4f996f38cc9fa3b8b3e3de29b03c9aefe5ebf6c224eddd564505aa85","names":[],"sources":[]}, {"digest":"237c004c73b6b288246816e0d7fde16e09c63a47aa3b1227383d7afe58666163","names":[],"sources":[]}, @@ -607,7 +607,7 @@ {"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]}, {"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:29"]}, {"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]}, - {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:52"]}, + {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:55"]}, {"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]}, {"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]}, {"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]}, @@ -692,7 +692,7 @@ {"digest":"f97f47b0eb87905ed77cc27c5e4ed75ef805cb372c98905253709de1aab9b63c","names":[],"sources":[]}, {"digest":"f9cfc89e8fe085b4fcc9cd32b74b6f103608c54d7d8cd97b47c01de34f252ba3","names":[],"sources":[]}, {"digest":"fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be","names":["packages/llm/llm/src/message.ts#AssistantMessage"],"sources":["packages/llm/llm/src/message.ts:167"]}, - {"digest":"fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd","names":["packages/sandbox/sandbox/src/index.ts#SandboxMode"],"sources":["packages/sandbox/sandbox/src/index.ts:30"]}, + {"digest":"fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd","names":["packages/sandbox/sandbox/src/index.ts#SandboxMode"],"sources":["packages/sandbox/sandbox/src/index.ts:38"]}, {"digest":"fab35c4520883c0d69e42d079c9f543fc5ac7a2d15b537b5572fcd99059c7018","names":[],"sources":[]}, {"digest":"fb5e0517050d2c6d40e5b8145db1f7c5ca7044d5d50fada6ff80e0b22c6ca973","names":[],"sources":[]}, {"digest":"fb8b6a2e53cb9cf44c551176de0fb77d1ddc60037b99a891ff8a860b6d5c29a0","names":[],"sources":[]}, diff --git a/docs/subsystems/sandbox.md b/docs/subsystems/sandbox.md index e5c3021503..71f4eedea6 100644 --- a/docs/subsystems/sandbox.md +++ b/docs/subsystems/sandbox.md @@ -213,6 +213,8 @@ The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mo * snapshotted together; existing operations and processes keep their policy. * @param request - optional session and approved mode override. * @returns the fully resolved per-call mode and absolute workspace root. + * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's recorded cwd is + * relative or contains a NUL byte. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy diff --git a/docs/subsystems/sandbox.zh.md b/docs/subsystems/sandbox.zh.md index 10093b09e2..2b79f4c17c 100644 --- a/docs/subsystems/sandbox.zh.md +++ b/docs/subsystems/sandbox.zh.md @@ -213,6 +213,8 @@ The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mo * snapshotted together; existing operations and processes keep their policy. * @param request - optional session and approved mode override. * @returns the fully resolved per-call mode and absolute workspace root. + * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's recorded cwd is + * relative or contains a NUL byte. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy diff --git a/docs/subsystems/working-directory.md b/docs/subsystems/working-directory.md index c6f4545328..cac8b9afa4 100644 --- a/docs/subsystems/working-directory.md +++ b/docs/subsystems/working-directory.md @@ -42,7 +42,8 @@ get(session: Session): string * @param signal - cancellation for filesystem inspection. * @returns the existing directory; recovery is committed before fulfillment. * A notice failure is warned without reverting the committed state. - * @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_UNAVAILABLE` when the original project is also + * unavailable or the service is disposed, or the rejection of a `working-directory/access` listener. */ ensure(agent: Agent, signal?: AbortSignal): Promise @@ -53,7 +54,9 @@ ensure(agent: Agent, signal?: AbortSignal): Promise * @param signal - cancellation before the durable change. * @returns the canonical absolute directory, committed before fulfillment. * A notice failure is warned; the next request still receives the committed directory. - * @throws when the requested path is not an existing directory. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_INVALID` for an empty path and + * `WORKING_DIRECTORY_NOT_FOUND` when the path is not an existing directory, or the rejection of a + * `working-directory/access` listener. */ set(agent: Agent, path: string, signal?: AbortSignal): Promise ``` diff --git a/docs/subsystems/working-directory.zh.md b/docs/subsystems/working-directory.zh.md index 98020a3dfc..aa6270328a 100644 --- a/docs/subsystems/working-directory.zh.md +++ b/docs/subsystems/working-directory.zh.md @@ -42,7 +42,8 @@ get(session: Session): string * @param signal - cancellation for filesystem inspection. * @returns the existing directory; recovery is committed before fulfillment. * A notice failure is warned without reverting the committed state. - * @throws when the original project is also unavailable, or when a `working-directory/access` listener rejects. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_UNAVAILABLE` when the original project is also + * unavailable or the service is disposed, or the rejection of a `working-directory/access` listener. */ ensure(agent: Agent, signal?: AbortSignal): Promise @@ -53,7 +54,9 @@ ensure(agent: Agent, signal?: AbortSignal): Promise * @param signal - cancellation before the durable change. * @returns the canonical absolute directory, committed before fulfillment. * A notice failure is warned; the next request still receives the committed directory. - * @throws when the requested path is not an existing directory. + * @throws {@link WorkingDirectoryError} `WORKING_DIRECTORY_INVALID` for an empty path and + * `WORKING_DIRECTORY_NOT_FOUND` when the path is not an existing directory, or the rejection of a + * `working-directory/access` listener. */ set(agent: Agent, path: string, signal?: AbortSignal): Promise ``` diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..7f3a279bf7 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2620,6 +2620,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session cwd is its workspace-write boundary; the configured root is the fallback for agentless calls and sessions without a cwd. Configured extra roots and this Session\'s active registrations are snapshotted together; existing operations and processes keep their policy.', parameters: [{ name: 'request', description: 'optional session and approved mode override.' }], returns: 'the fully resolved per-call mode and absolute workspace root.', + throws: ['`SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session\'s recorded cwd is relative or contains a NUL byte.'], }, { signature: 'registerWritableRoot(session: Session, directory: string): () => void', @@ -4550,14 +4551,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Validate the current directory and restore the original project when it disappeared.', parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session.' }, { name: 'signal', description: 'cancellation for filesystem inspection.' }], returns: 'the existing directory; recovery is committed before fulfillment. A notice failure is warned without reverting the committed state.', - throws: ['when the original project is also unavailable, or when a `working-directory/access` listener rejects.'], + throws: ['{@link WorkingDirectoryError} `WORKING_DIRECTORY_UNAVAILABLE` when the original project is also unavailable or the service is disposed, or the rejection of a `working-directory/access` listener.'], }, { signature: 'set(agent: Agent, path: string, signal?: AbortSignal): Promise', description: 'Change one Session\'s directory without changing existing processes or permissions.', parameters: [{ name: 'agent', description: 'live or unpublished Agent owning the Session.' }, { name: 'path', description: 'absolute path or a path relative to its current directory.' }, { name: 'signal', description: 'cancellation before the durable change.' }], returns: 'the canonical absolute directory, committed before fulfillment. A notice failure is warned; the next request still receives the committed directory.', - throws: ['when the requested path is not an existing directory.'], + throws: ['{@link WorkingDirectoryError} `WORKING_DIRECTORY_INVALID` for an empty path and `WORKING_DIRECTORY_NOT_FOUND` when the path is not an existing directory, or the rejection of a `working-directory/access` listener.'], }, ], }, From fe2effea1f77b37e89f1d7a99286fdedbab75e38 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 20:51:38 +0800 Subject: [PATCH 051/438] feat(terminal): give TerminalBackendCleanupError the CLEANUP_FAILED code TerminalBackendCleanupError extended AggregateError, so a backend that failed startup and then failed to clean its partial resources reached tool/result with a name but no error.name/error.code. It now extends TerminalError with code CLEANUP_FAILED, keeps spawnError, cleanupError, and the errors list, and sets the setup failure as cause. TerminalError and the cleanup error move to src/error.ts so src/types.ts stays type-only; TerminalError's constructor accepts ErrorOptions. Refs #7869 --- docs/subsystems/terminal.md | 2 +- docs/subsystems/terminal.zh.md | 2 +- .../terminal-bash/tests/index.spec.ts | 3 + packages/terminal/terminal/README.i18n.yaml | 8 +-- packages/terminal/terminal/README.md | 5 +- packages/terminal/terminal/README.zh.md | 5 +- packages/terminal/terminal/src/error.ts | 70 +++++++++++++++++++ packages/terminal/terminal/src/index.ts | 40 +---------- packages/terminal/terminal/src/types.ts | 17 +---- .../terminal/terminal/tests/service.spec.ts | 16 +++++ 10 files changed, 104 insertions(+), 64 deletions(-) create mode 100644 packages/terminal/terminal/src/error.ts diff --git a/docs/subsystems/terminal.md b/docs/subsystems/terminal.md index c1c78963e4..0d917219d5 100644 --- a/docs/subsystems/terminal.md +++ b/docs/subsystems/terminal.md @@ -31,7 +31,7 @@ A backend owns how one registered type starts and detects readiness. `TerminalSe interface TerminalBackend { /** Stable type selected by {@link TerminalSpawnRequest.type}. */ readonly type: string - /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses {@link TerminalBackendCleanupError}. */ + /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses `TerminalBackendCleanupError`. */ spawn(spec: TerminalBackendSpawnSpec): Promise } ``` diff --git a/docs/subsystems/terminal.zh.md b/docs/subsystems/terminal.zh.md index e97e5771f5..a9d2b36d27 100644 --- a/docs/subsystems/terminal.zh.md +++ b/docs/subsystems/terminal.zh.md @@ -31,7 +31,7 @@ type TerminalSessionStatus = interface TerminalBackend { /** Stable type selected by {@link TerminalSpawnRequest.type}. */ readonly type: string - /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses {@link TerminalBackendCleanupError}. */ + /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses `TerminalBackendCleanupError`. */ spawn(spec: TerminalBackendSpawnSpec): Promise } ``` diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index d992f8ee7f..2859644622 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -158,8 +158,11 @@ describe('BashTerminalBackend startup rollback', () => { const aggregate = new BashTerminalBackend(ctx, config(), spawnTerminal, () => doublyFailed) await expect(aggregate.spawn(spec(agent(ctx)))).rejects.toEqual(expect.objectContaining({ name: 'TerminalBackendCleanupError', + code: 'CLEANUP_FAILED', spawnError: startupFailure, cleanupError: cleanupFailure, + errors: [startupFailure, cleanupFailure], + cause: startupFailure, } satisfies Partial)) }) diff --git a/packages/terminal/terminal/README.i18n.yaml b/packages/terminal/terminal/README.i18n.yaml index 6b91667f72..e734b14bf2 100644 --- a/packages/terminal/terminal/README.i18n.yaml +++ b/packages/terminal/terminal/README.i18n.yaml @@ -39,14 +39,14 @@ en: 6bae42fb7275816f zh: 5f75e1b26074108c /deepseek-ai-dsh-terminal/understand-the-implementation/source-map: - en: 48dab6fe2f770ced - zh: 9bbfd23bcc5ac2b3 + en: 3ab5d082aa13d500 + zh: e97b962d02e474b7 /deepseek-ai-dsh-terminal/understand-the-implementation/data-model-and-lifecycle: en: a2adfa2708882e19 zh: 002f257fd8c4addb /deepseek-ai-dsh-terminal/understand-the-implementation/ownership-and-cleanup-rules: - en: 7af36e58919e41d5 - zh: 4fe7b4db1099bcbf + en: b669a68c739b062a + zh: cc641f850905095f /deepseek-ai-dsh-terminal/understand-the-implementation/send-reservation: en: 0b8dc3a382aa7bf2 zh: e6cc6906e01827d2 diff --git a/packages/terminal/terminal/README.md b/packages/terminal/terminal/README.md index 40cb6866f8..ff34d9a3cc 100644 --- a/packages/terminal/terminal/README.md +++ b/packages/terminal/terminal/README.md @@ -74,7 +74,8 @@ The service owns everything except terminal mechanics: session identity, publica | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | `TerminalSessionService`: backend registry, spawn/send/read/signal/kill/list, owner cleanups, disposal | -| [`src/types.ts`](src/types.ts) | Shared contracts: backend interface, session types, wait reasons, signal set, error codes | +| [`src/types.ts`](src/types.ts) | Shared contracts: backend interface, session types, wait reasons, signal set | +| [`src/error.ts`](src/error.ts) | `TerminalError`, its codes, and `TerminalBackendCleanupError` | ### Data model and lifecycle @@ -83,7 +84,7 @@ Each published session is a record of its id, owner, optional name, backend type ### Ownership and cleanup rules - Fencing uses the exact `Agent` object: `hasOwnerActivity(owner)` spans unpublished setup through final close with no publication gap, so lifecycle policy can fence the owner precisely. -- A backend that cannot clean partial startup resources rejects with `TerminalBackendCleanupError`; the service retains that failure as tracked owner activity until owner or service disposal consumes and reports it. +- A backend that cannot clean partial startup resources rejects with `TerminalBackendCleanupError`, a `TerminalError` with code `CLEANUP_FAILED` that lists both failures in `errors`; the service retains that failure as tracked owner activity until owner or service disposal consumes and reports it. - Caller cancellation keeps its exact `AbortSignal.reason`; `kill()` and disposal resolve only after the backend's captured process tree is quiescent. ### Send reservation diff --git a/packages/terminal/terminal/README.zh.md b/packages/terminal/terminal/README.zh.md index bb21c9e502..cef5a62110 100644 --- a/packages/terminal/terminal/README.zh.md +++ b/packages/terminal/terminal/README.zh.md @@ -74,7 +74,8 @@ kind: "package-reference" | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | `TerminalSessionService`:后端注册表、spawn/send/read/signal/kill/list、所有者清理与 dispose | -| [`src/types.ts`](src/types.ts) | 共享约定:后端接口、会话类型、等待原因、信号集合、错误码 | +| [`src/types.ts`](src/types.ts) | 共享约定:后端接口、会话类型、等待原因、信号集合 | +| [`src/error.ts`](src/error.ts) | `TerminalError`、其 code 与 `TerminalBackendCleanupError` | ### 数据模型与生命周期 @@ -83,7 +84,7 @@ kind: "package-reference" ### 所有权与清理规则 - 限制基于确切的 `Agent` 对象:`hasOwnerActivity(owner)` 覆盖从尚未发布的设置到最终关闭的全过程,没有发布竞态,因此生命周期策略可以精确限制所有者。 -- 无法清理部分启动资源的后端会以 `TerminalBackendCleanupError` 拒绝;服务会将该失败保留为受跟踪的所有者活动,直到所有者或服务 dispose 消费并报告它。 +- 无法清理部分启动资源的后端会以 `TerminalBackendCleanupError` 拒绝,它是 code 为 `CLEANUP_FAILED` 的 `TerminalError`,并在 `errors` 中列出两个失败;服务会将该失败保留为受跟踪的所有者活动,直到所有者或服务 dispose 消费并报告它。 - 调用方取消保留其确切的 `AbortSignal.reason`;`kill()` 与 dispose 只在后端捕获的进程树完全停稳后完成。 ### 发送预留 diff --git a/packages/terminal/terminal/src/error.ts b/packages/terminal/terminal/src/error.ts new file mode 100644 index 0000000000..b487ac9bc4 --- /dev/null +++ b/packages/terminal/terminal/src/error.ts @@ -0,0 +1,70 @@ +/** Machine-routable PTY service and backend failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Machine-routable PTY service and backend failures. Backends use + * `INIT_REJECTED` when the shell rejects its setup input, `NO_SANDBOX` when a + * confined mode has no sandbox provider, `SESSION_CLOSING` and + * `SESSION_EXITED` for an operation on a closing or exited session, + * `STARTUP_EXITED` or `STARTUP_TIMEOUT` when the shell exits or misses + * readiness during startup, and `CLEANUP_FAILED` (always as + * {@link TerminalBackendCleanupError}) when startup failed and the partial + * resources it left could not be cleaned. + */ +export type TerminalErrorCode = + | 'CLEANUP_FAILED' + | 'DUPLICATE_BACKEND' + | 'DUPLICATE_NAME' + | 'FOREIGN_SESSION' + | 'INIT_REJECTED' + | 'NO_BACKEND' + | 'NO_SANDBOX' + | 'NO_SESSION' + | 'OWNER_NOT_LIVE' + | 'SEND_ACTIVE' + | 'SERVICE_DISPOSING' + | 'SESSION_CLOSING' + | 'SESSION_EXITED' + | 'STARTUP_EXITED' + | 'STARTUP_TIMEOUT' + +/** Harness error carrying a stable {@link TerminalErrorCode}. */ +export class TerminalError extends HarnessError { + override readonly code: TerminalErrorCode + + /** + * @param message - names the PTY operation and the safe next step. + * @param code - the failure class consumers route on. + * @param options - standard `cause` chaining. + */ + constructor(message: string, code: TerminalErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'TerminalError' + this.code = code + } +} + +/** + * Backend-reported failure to clean partial resources after unpublished setup + * failed; code `CLEANUP_FAILED`. Backend-owned resources may still be alive. + * `errors` lists both failures in the order `AggregateError` would, and + * `cause` is the setup failure. + */ +export class TerminalBackendCleanupError extends TerminalError { + /** The setup failure followed by the cleanup failure. */ + readonly errors: readonly unknown[] + + /** + * @param spawnError - original setup or cancellation failure. + * @param cleanupError - failure that may leave backend-owned resources alive. + */ + constructor( + readonly spawnError: unknown, + readonly cleanupError: unknown, + ) { + super('PTY backend startup and cleanup both failed', 'CLEANUP_FAILED', { cause: spawnError }) + this.name = 'TerminalBackendCleanupError' + this.errors = [spawnError, cleanupError] + } +} diff --git a/packages/terminal/terminal/src/index.ts b/packages/terminal/terminal/src/index.ts index df09ff94aa..2e6e78b6ea 100644 --- a/packages/terminal/terminal/src/index.ts +++ b/packages/terminal/terminal/src/index.ts @@ -6,8 +6,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError } from '@deepseek-ai/dsh-error' -import { TerminalBackendCleanupError } from './types.ts' +import { TerminalBackendCleanupError, TerminalError } from './error.ts' import type { TerminalBackend, TerminalBackendSession, @@ -41,7 +40,7 @@ export type { TerminalSpawnResult, TerminalWaitReason, } from './types.ts' -export { TerminalBackendCleanupError } from './types.ts' +export { TerminalBackendCleanupError, TerminalError, type TerminalErrorCode } from './error.ts' /** Opaque identity minted by {@link TerminalSessionService} for one live PTY session. */ export type TerminalSessionId = TerminalSessionIdValue @@ -52,41 +51,6 @@ declare module '@deepseek-ai/cordis' { } } -/** - * Machine-routable PTY service and backend failures. Backends use - * `INIT_REJECTED` when the shell rejects its setup input, `NO_SANDBOX` when a - * confined mode has no sandbox provider, `SESSION_CLOSING` and - * `SESSION_EXITED` for an operation on a closing or exited session, and - * `STARTUP_EXITED` or `STARTUP_TIMEOUT` when the shell exits or misses - * readiness during startup. - */ -export type TerminalErrorCode = - | 'DUPLICATE_BACKEND' - | 'DUPLICATE_NAME' - | 'FOREIGN_SESSION' - | 'INIT_REJECTED' - | 'NO_BACKEND' - | 'NO_SANDBOX' - | 'NO_SESSION' - | 'OWNER_NOT_LIVE' - | 'SEND_ACTIVE' - | 'SERVICE_DISPOSING' - | 'SESSION_CLOSING' - | 'SESSION_EXITED' - | 'STARTUP_EXITED' - | 'STARTUP_TIMEOUT' - -/** Harness error carrying a stable {@link TerminalErrorCode}. */ -export class TerminalError extends HarnessError { - override readonly code: TerminalErrorCode - - constructor(message: string, code: TerminalErrorCode) { - super(message, code) - this.name = 'TerminalError' - this.code = code - } -} - /** * Brand one registry-minted string as a {@link TerminalSessionId}. * @param value - raw registry-issued id. diff --git a/packages/terminal/terminal/src/types.ts b/packages/terminal/terminal/src/types.ts index cbdd08d8a8..c3a191ba51 100644 --- a/packages/terminal/terminal/src/types.ts +++ b/packages/terminal/terminal/src/types.ts @@ -10,21 +10,6 @@ import type { Agent } from '@deepseek-ai/dsh-agent' /** Internal exported basis for the public `TerminalSessionId` type/value pair. */ export type TerminalSessionIdValue = Branded<'TerminalSessionId'> -/** - * Backend-reported failure to clean partial resources after unpublished setup failed. - * @param spawnError - original setup or cancellation failure. - * @param cleanupError - failure that may leave backend-owned resources alive. - */ -export class TerminalBackendCleanupError extends AggregateError { - constructor( - readonly spawnError: unknown, - readonly cleanupError: unknown, - ) { - super([spawnError, cleanupError], 'PTY backend startup and cleanup both failed') - this.name = 'TerminalBackendCleanupError' - } -} - /** Why one interactive send returned control to its caller. */ export type TerminalWaitReason = 'stdin_read' | 'inferred_idle' | 'timeout' | 'session_exit' @@ -166,7 +151,7 @@ export interface TerminalBackendSession { export interface TerminalBackend { /** Stable type selected by {@link TerminalSpawnRequest.type}. */ readonly type: string - /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses {@link TerminalBackendCleanupError}. */ + /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses `TerminalBackendCleanupError`. */ spawn(spec: TerminalBackendSpawnSpec): Promise } diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 0237f2970a..3199deb1a0 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -203,6 +203,9 @@ describe('TerminalSessionService ownership and lifecycle', () => { expect(concurrent).toBeInstanceOf(TerminalError) expect(concurrent).toBeInstanceOf(HarnessError) expect(concurrent).toMatchObject({ name: 'TerminalError', code: 'SEND_ACTIVE' }) + const cleanup = new TerminalBackendCleanupError(new Error('setup failed'), new Error('cleanup failed')) + expect(cleanup).toBeInstanceOf(TerminalError) + expect(cleanup).toMatchObject({ name: 'TerminalBackendCleanupError', code: 'CLEANUP_FAILED' }) expect(operation.readOutput()).toEqual({ delta: 'delta', truncated: false }) expect(operation.cancel()).toBe(true) await operation.done @@ -297,6 +300,19 @@ describe('TerminalSessionService ownership and lifecycle', () => { await expect(pending).rejects.toBe(reason) }) + it('rejects an uncancelled spawn with the backend cleanup failure and its code', async () => { + const ctx = await harness() + const failure = new TerminalBackendCleanupError(new Error('startup failed'), new Error('backend cleanup failed')) + ctx.terminals.registerBackend({ type: 'cleanup-failing', spawn: () => Promise.reject(failure) }) + const owner = stubAgent(ctx, 'owner') + await ctx.agents.register(owner) + + await expect(ctx.terminals.spawn(owner, { type: 'cleanup-failing' })).rejects.toBe(failure) + expect(failure).toMatchObject({ name: 'TerminalBackendCleanupError', code: 'CLEANUP_FAILED' }) + const internal = ctx.terminals as unknown as { disposeOwned(owner: Agent): Promise } + await expect(internal.disposeOwned(owner)).rejects.toThrow('failed to clean up PTY lifecycle') + }) + it.each(['owner', 'service'] as const)('retains caller-triggered backend cleanup failure until %s disposal', async (scope) => { const ctx = await harness() const started = Promise.withResolvers() From 690634f5e9ac7e28d643f69fcc94f0a81d20574e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 22:05:35 +0800 Subject: [PATCH 052/438] refactor(errors): base the new shell, sandbox, and subprocess errors on dsh-error The error classes this branch adds import HarnessError from the dependency-free @deepseek-ai/dsh-error package: Win32Error, SubprocessError, and ShellEnvError packages depend on dsh-error instead of the LLM runtime, and dsh-sandbox and dsh-working-directory declare it beside their existing dsh-llm dependency. The SHELL_ENV and WORKING_DIRECTORY code lists stay in internal modules so the plugin entries export only the error classes and code types. Generated module, config, and event graphs follow. Refs #7869 --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 32 ++++++++++++------- docs/module-graph.zh.md | 32 ++++++++++++------- packages/sandbox/sandbox/package.json | 6 ++-- packages/sandbox/sandbox/src/escalation.ts | 2 +- .../sandbox/sandbox/tests/vocabulary.spec.ts | 2 +- packages/sandbox/sandbox/tsconfig.json | 3 ++ .../session/working-directory/package.json | 6 ++-- .../session/working-directory/src/error.ts | 2 +- .../session/working-directory/src/index.ts | 2 +- .../session/working-directory/tsconfig.json | 3 ++ packages/shell/shell-env/README.i18n.yaml | 4 +-- packages/shell/shell-env/README.md | 1 + packages/shell/shell-env/README.zh.md | 1 + packages/shell/shell-env/package.json | 4 +-- packages/shell/shell-env/src/error.ts | 28 ++++++++++++++++ packages/shell/shell-env/src/index.ts | 29 ++--------------- packages/shell/shell-env/tsconfig.json | 2 +- packages/subprocess/subprocess/package.json | 4 +-- packages/subprocess/subprocess/src/error.ts | 2 +- .../subprocess/subprocess/tests/error.spec.ts | 2 +- packages/subprocess/subprocess/tsconfig.json | 2 +- .../subprocess/win32-process/package.json | 4 +-- .../subprocess/win32-process/src/errors.ts | 2 +- .../win32-process/tests/ffi.spec.ts | 2 +- .../subprocess/win32-process/tsconfig.json | 2 +- pnpm-lock.yaml | 22 ++++++++----- 30 files changed, 124 insertions(+), 85 deletions(-) create mode 100644 packages/shell/shell-env/src/error.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 90892cc3dd..f0e447ae59 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -3362,7 +3362,7 @@ export interface Config extends SessionTitleLlmConfig { ## `@deepseek-ai/dsh-shell-env` -- `source`: [`packages/shell/shell-env/src/index.ts:57`](../packages/shell/shell-env/src/index.ts) +- `source`: [`packages/shell/shell-env/src/index.ts:34`](../packages/shell/shell-env/src/index.ts) ```ts config-catalog /** Plugin config (all optional — the built-in facts resolve without defaults). */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 663fb50b89..dad8488a45 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -3364,7 +3364,7 @@ export interface Config extends SessionTitleLlmConfig { ## `@deepseek-ai/dsh-shell-env` -- `source`: [`packages/shell/shell-env/src/index.ts:57`](../packages/shell/shell-env/src/index.ts) +- `source`: [`packages/shell/shell-env/src/index.ts:34`](../packages/shell/shell-env/src/index.ts) ```ts config-catalog /** Plugin config (all optional — the built-in facts resolve without defaults). */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..c0a83f9f7f 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -98,7 +98,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:32`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..20e1101166 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -100,7 +100,7 @@ | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:29`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:32`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:129`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:156`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:147`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..dbd423430a 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -505,7 +505,9 @@ flowchart TD pkg_storage_domain --> pkg_storage pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage + pkg_subprocess --> pkg_error pkg_subprocess --> pkg_http_proxy + pkg_win32_process --> pkg_error pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry pkg_system_prompt --> pkg_llm @@ -539,6 +541,7 @@ flowchart TD pkg_host_frontend_static --> pkg_host_webserver pkg_lsp --> pkg_brand pkg_lsp --> pkg_llm + pkg_sandbox --> pkg_error pkg_sandbox --> pkg_llm pkg_sandbox --> pkg_session pkg_session_format_catalog --> pkg_session @@ -735,6 +738,7 @@ flowchart TD pkg_session_title --> pkg_session pkg_session_title --> pkg_session_projection pkg_working_directory --> pkg_agent + pkg_working_directory --> pkg_error pkg_working_directory --> pkg_fs pkg_working_directory --> pkg_llm pkg_working_directory --> pkg_session @@ -804,10 +808,6 @@ flowchart TD pkg_permission_presets --> pkg_shell pkg_permission_presets --> pkg_typert_protocol pkg_permission_presets --> pkg_user_approval - pkg_jobs_local --> pkg_agent - pkg_jobs_local --> pkg_jobs - pkg_jobs_local --> pkg_scope - pkg_jobs_local --> pkg_timeout pkg_ptc_runtime_node --> pkg_fs pkg_ptc_runtime_node --> pkg_ptc_runtime pkg_ptc_runtime_node --> pkg_sandbox @@ -1023,6 +1023,11 @@ flowchart TD pkg_tool_ask_user --> pkg_agent pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_questions + pkg_jobs_local --> pkg_agent + pkg_jobs_local --> pkg_jobs + pkg_jobs_local --> pkg_scope + pkg_jobs_local --> pkg_timeout + pkg_jobs_local --> pkg_tools pkg_tool_jobs --> pkg_agent pkg_tool_jobs --> pkg_jobs pkg_tool_jobs --> pkg_llm @@ -1059,6 +1064,7 @@ flowchart TD pkg_tool_working_directory --> pkg_tools pkg_tool_working_directory --> pkg_working_directory pkg_shell_env --> pkg_app_boot + pkg_shell_env --> pkg_error pkg_shell_env --> pkg_home_paths pkg_shell_env --> pkg_shell pkg_shell_env --> pkg_tools @@ -1176,6 +1182,7 @@ flowchart TD pkg_tool_bash --> pkg_sandbox_policy pkg_tool_bash --> pkg_shell pkg_tool_bash --> pkg_shell_env + pkg_tool_bash --> pkg_subprocess pkg_tool_bash --> pkg_system_prompt pkg_tool_bash --> pkg_tools pkg_tool_bash --> pkg_user_approval @@ -1187,6 +1194,7 @@ flowchart TD pkg_tool_pwsh --> pkg_sandbox_policy pkg_tool_pwsh --> pkg_shell pkg_tool_pwsh --> pkg_shell_env + pkg_tool_pwsh --> pkg_subprocess pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval @@ -1683,7 +1691,6 @@ flowchart TD | [`session-format-v3-to-v4`](../packages/session/session-format-v3-to-v4) | `session` | — | | [`ssh-helper-runtime`](../packages/ssh/ssh-helper-runtime) | `ssh` | — | | [`storage`](../packages/storage/storage) | `storage` | — | -| [`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` | — | @@ -1702,7 +1709,8 @@ flowchart TD | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`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) | +| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`error`](../packages/util/error), [`http-proxy`](../packages/util/http-proxy) | +| [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | [`error`](../packages/util/error) | | [`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) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | @@ -1719,7 +1727,7 @@ flowchart TD | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | -| [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`session-format-catalog`](../packages/session/session-format-catalog) | `session` | [`session`](../packages/core/session) | | [`session-log-deepseek`](../packages/session/session-log-deepseek) | `session` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | @@ -1780,7 +1788,7 @@ flowchart TD | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | +| [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -1795,7 +1803,6 @@ flowchart TD | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | @@ -1838,6 +1845,7 @@ flowchart TD | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | | [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/interaction/tool-ask-user) | `interaction` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-jobs`](../packages/jobs/tool-jobs) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-lsp`](../packages/lsp/tool-lsp) | `lsp` | [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`mcp-resources`](../packages/mcp/mcp-resources) | `mcp` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1845,7 +1853,7 @@ flowchart TD | [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`tool-working-directory`](../packages/session/tool-working-directory) | `session` | [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | +| [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`error`](../packages/util/error), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local), [`util-values`](../packages/util/values) | @@ -1865,8 +1873,8 @@ flowchart TD | [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) | | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | -| [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`fs-ssh`](../packages/ssh/fs-ssh) | `ssh` | [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`ssh`](../packages/ssh/ssh) | | [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | `ssh` | [`sandbox`](../packages/sandbox/sandbox), [`ssh`](../packages/ssh/ssh) | | [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | `ssh` | [`ssh`](../packages/ssh/ssh), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..caf5f595f8 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -507,7 +507,9 @@ flowchart TD pkg_storage_domain --> pkg_storage pkg_storage_json --> pkg_storage pkg_storage_sqlite --> pkg_storage + pkg_subprocess --> pkg_error pkg_subprocess --> pkg_http_proxy + pkg_win32_process --> pkg_error pkg_remote_mock --> pkg_typert_protocol pkg_typert_loader --> pkg_typert_registry pkg_system_prompt --> pkg_llm @@ -541,6 +543,7 @@ flowchart TD pkg_host_frontend_static --> pkg_host_webserver pkg_lsp --> pkg_brand pkg_lsp --> pkg_llm + pkg_sandbox --> pkg_error pkg_sandbox --> pkg_llm pkg_sandbox --> pkg_session pkg_session_format_catalog --> pkg_session @@ -737,6 +740,7 @@ flowchart TD pkg_session_title --> pkg_session pkg_session_title --> pkg_session_projection pkg_working_directory --> pkg_agent + pkg_working_directory --> pkg_error pkg_working_directory --> pkg_fs pkg_working_directory --> pkg_llm pkg_working_directory --> pkg_session @@ -806,10 +810,6 @@ flowchart TD pkg_permission_presets --> pkg_shell pkg_permission_presets --> pkg_typert_protocol pkg_permission_presets --> pkg_user_approval - pkg_jobs_local --> pkg_agent - pkg_jobs_local --> pkg_jobs - pkg_jobs_local --> pkg_scope - pkg_jobs_local --> pkg_timeout pkg_ptc_runtime_node --> pkg_fs pkg_ptc_runtime_node --> pkg_ptc_runtime pkg_ptc_runtime_node --> pkg_sandbox @@ -1025,6 +1025,11 @@ flowchart TD pkg_tool_ask_user --> pkg_agent pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_questions + pkg_jobs_local --> pkg_agent + pkg_jobs_local --> pkg_jobs + pkg_jobs_local --> pkg_scope + pkg_jobs_local --> pkg_timeout + pkg_jobs_local --> pkg_tools pkg_tool_jobs --> pkg_agent pkg_tool_jobs --> pkg_jobs pkg_tool_jobs --> pkg_llm @@ -1061,6 +1066,7 @@ flowchart TD pkg_tool_working_directory --> pkg_tools pkg_tool_working_directory --> pkg_working_directory pkg_shell_env --> pkg_app_boot + pkg_shell_env --> pkg_error pkg_shell_env --> pkg_home_paths pkg_shell_env --> pkg_shell pkg_shell_env --> pkg_tools @@ -1178,6 +1184,7 @@ flowchart TD pkg_tool_bash --> pkg_sandbox_policy pkg_tool_bash --> pkg_shell pkg_tool_bash --> pkg_shell_env + pkg_tool_bash --> pkg_subprocess pkg_tool_bash --> pkg_system_prompt pkg_tool_bash --> pkg_tools pkg_tool_bash --> pkg_user_approval @@ -1189,6 +1196,7 @@ flowchart TD pkg_tool_pwsh --> pkg_sandbox_policy pkg_tool_pwsh --> pkg_shell pkg_tool_pwsh --> pkg_shell_env + pkg_tool_pwsh --> pkg_subprocess pkg_tool_pwsh --> pkg_system_prompt pkg_tool_pwsh --> pkg_tools pkg_tool_pwsh --> pkg_user_approval @@ -1685,7 +1693,6 @@ flowchart TD | [`session-format-v3-to-v4`](../packages/session/session-format-v3-to-v4) | `session` | — | | [`ssh-helper-runtime`](../packages/ssh/ssh-helper-runtime) | `ssh` | — | | [`storage`](../packages/storage/storage) | `storage` | — | -| [`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` | — | @@ -1704,7 +1711,8 @@ flowchart TD | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`storage`](../packages/storage/storage) | | [`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) | +| [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`error`](../packages/util/error), [`http-proxy`](../packages/util/http-proxy) | +| [`win32-process`](../packages/subprocess/win32-process) | `subprocess` | [`error`](../packages/util/error) | | [`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) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | @@ -1721,7 +1729,7 @@ flowchart TD | [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) | | [`host-frontend-static`](../packages/host/frontend-static) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | -| [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | +| [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`session-format-catalog`](../packages/session/session-format-catalog) | `session` | [`session`](../packages/core/session) | | [`session-log-deepseek`](../packages/session/session-log-deepseek) | `session` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`session`](../packages/core/session) | | [`session-persistence`](../packages/session/session-persistence) | `session` | [`brand`](../packages/util/brand), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | @@ -1782,7 +1790,7 @@ flowchart TD | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`agent`](../packages/core/agent), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`session-telemetry`](../packages/session/session-telemetry) | `session` | [`agent`](../packages/core/agent), [`session`](../packages/core/session) | | [`session-title`](../packages/session/session-title) | `session` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | -| [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | +| [`working-directory`](../packages/session/working-directory) | `session` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`terminal`](../packages/terminal/terminal) | `terminal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`error`](../packages/util/error) | | [`loader-smoke`](../packages/test-support/loader-smoke) | `test-support` | [`agent`](../packages/core/agent), [`http-proxy`](../packages/util/http-proxy), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -1797,7 +1805,6 @@ flowchart TD | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | @@ -1840,6 +1847,7 @@ flowchart TD | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | | [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/interaction/tool-ask-user) | `interaction` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-jobs`](../packages/jobs/tool-jobs) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-lsp`](../packages/lsp/tool-lsp) | `lsp` | [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`mcp-resources`](../packages/mcp/mcp-resources) | `mcp` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1847,7 +1855,7 @@ flowchart TD | [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy) | `session` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`tools`](../packages/core/tools) | | [`session-title-first-prompt-llm`](../packages/session/session-title-first-prompt-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) | | [`tool-working-directory`](../packages/session/tool-working-directory) | `session` | [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | +| [`shell-env`](../packages/shell/shell-env) | `shell` | [`app-boot`](../packages/boot/app-boot), [`error`](../packages/util/error), [`home-paths`](../packages/util/home-paths), [`shell`](../packages/shell/shell), [`tools`](../packages/core/tools) | | [`tool-bash-persistent`](../packages/shell/tool-bash-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-pwsh-persistent`](../packages/shell/tool-pwsh-persistent) | `shell` | [`agent`](../packages/core/agent), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`ssh`](../packages/ssh/ssh) | `ssh` | [`brand`](../packages/util/brand), [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`fs-sandbox`](../packages/fs/fs-sandbox), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-local`](../packages/sandbox/sandbox-local), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session-projection`](../packages/session/session-projection), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local), [`util-values`](../packages/util/values) | @@ -1867,8 +1875,8 @@ flowchart TD | [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) | | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) | -| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | -| [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | +| [`tool-pwsh`](../packages/shell/tool-pwsh) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) | | [`fs-ssh`](../packages/ssh/fs-ssh) | `ssh` | [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`ssh`](../packages/ssh/ssh) | | [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | `ssh` | [`sandbox`](../packages/sandbox/sandbox), [`ssh`](../packages/ssh/ssh) | | [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | `ssh` | [`ssh`](../packages/ssh/ssh), [`subprocess`](../packages/subprocess/subprocess), [`subprocess-local`](../packages/subprocess/subprocess-local) | diff --git a/packages/sandbox/sandbox/package.json b/packages/sandbox/sandbox/package.json index 6b6f314b78..4445da55fa 100644 --- a/packages/sandbox/sandbox/package.json +++ b/packages/sandbox/sandbox/package.json @@ -32,12 +32,14 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*" + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-util-values": "workspace:*" diff --git a/packages/sandbox/sandbox/src/escalation.ts b/packages/sandbox/sandbox/src/escalation.ts index 84d5f49561..7e0193b6c8 100644 --- a/packages/sandbox/sandbox/src/escalation.ts +++ b/packages/sandbox/sandbox/src/escalation.ts @@ -16,7 +16,7 @@ * @module dsh-sandbox/escalation */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { assertNever } from '@deepseek-ai/dsh-util-values' import { escalationDisplayReason } from './locales.ts' import type { SandboxMode } from './index.ts' diff --git a/packages/sandbox/sandbox/tests/vocabulary.spec.ts b/packages/sandbox/sandbox/tests/vocabulary.spec.ts index 26db8fe796..8c3002a4ea 100644 --- a/packages/sandbox/sandbox/tests/vocabulary.spec.ts +++ b/packages/sandbox/sandbox/tests/vocabulary.spec.ts @@ -7,7 +7,7 @@ */ import { describe, expect, it } from 'vitest' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { SANDBOX_PREPARATION_ERROR_CODES, SANDBOX_UNAVAILABLE, SandboxPreparationError, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox' describe('SandboxUnavailableError', () => { diff --git a/packages/sandbox/sandbox/tsconfig.json b/packages/sandbox/sandbox/tsconfig.json index 95245937ec..48fc673d7e 100644 --- a/packages/sandbox/sandbox/tsconfig.json +++ b/packages/sandbox/sandbox/tsconfig.json @@ -19,6 +19,9 @@ }, { "path": "../../core/session" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/session/working-directory/package.json b/packages/session/working-directory/package.json index e7433cb7ca..9682f5da41 100644 --- a/packages/session/working-directory/package.json +++ b/packages/session/working-directory/package.json @@ -38,7 +38,8 @@ "@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-system-prompt": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-sandbox-policy": "workspace:*", @@ -54,7 +55,8 @@ "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tool-working-directory": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", diff --git a/packages/session/working-directory/src/error.ts b/packages/session/working-directory/src/error.ts index ec2a2ef7a2..acae1f0307 100644 --- a/packages/session/working-directory/src/error.ts +++ b/packages/session/working-directory/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable Session working-directory failures. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link WorkingDirectoryError} code: diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 7a0f66ede6..6ef5ce0279 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -15,7 +15,7 @@ import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-system-prompt' import { WorkingDirectoryError } from './error.ts' -export { WORKING_DIRECTORY_ERROR_CODES, WorkingDirectoryError, type WorkingDirectoryErrorCode } from './error.ts' +export { WorkingDirectoryError, type WorkingDirectoryErrorCode } from './error.ts' declare module '@deepseek-ai/cordis' { interface Events { diff --git a/packages/session/working-directory/tsconfig.json b/packages/session/working-directory/tsconfig.json index 6d24c1126a..7d67ef3a9f 100644 --- a/packages/session/working-directory/tsconfig.json +++ b/packages/session/working-directory/tsconfig.json @@ -31,6 +31,9 @@ }, { "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/error" } ] } diff --git a/packages/shell/shell-env/README.i18n.yaml b/packages/shell/shell-env/README.i18n.yaml index eac66fcb65..871ab18c3a 100644 --- a/packages/shell/shell-env/README.i18n.yaml +++ b/packages/shell/shell-env/README.i18n.yaml @@ -36,8 +36,8 @@ en: 5438a951817526d9 zh: 66459cdea830a8c8 /deepseek-ai-dsh-shell-env/understand-the-implementation/source-map: - en: 72eba3bfadcfa581 - zh: dcd83e02a1910f27 + en: da18240c8c1dc687 + zh: a854ddaca8953832 /deepseek-ai-dsh-shell-env/understand-the-implementation/collection: en: 0c2d7d5b2131630f zh: b44d4f0ddf89421b diff --git a/packages/shell/shell-env/README.md b/packages/shell/shell-env/README.md index 86037caffe..f6b005367e 100644 --- a/packages/shell/shell-env/README.md +++ b/packages/shell/shell-env/README.md @@ -87,6 +87,7 @@ This section explains the design decisions behind the registry and points at the | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry, `ShellEnvRegistry` service, and the built-in facts | +| [`src/error.ts`](src/error.ts) | `ShellEnvError` and its codes | ### Collection diff --git a/packages/shell/shell-env/README.zh.md b/packages/shell/shell-env/README.zh.md index a3d4a98516..99abd27556 100644 --- a/packages/shell/shell-env/README.zh.md +++ b/packages/shell/shell-env/README.zh.md @@ -87,6 +87,7 @@ contributor 必须声明它返回的每个键;返回未声明或非字符串 | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | 插件入口、`ShellEnvRegistry` 服务与内置事实 | +| [`src/error.ts`](src/error.ts) | `ShellEnvError` 及其 code | ### 收集 diff --git a/packages/shell/shell-env/package.json b/packages/shell/shell-env/package.json index 4fb7d7de4f..3393956475 100644 --- a/packages/shell/shell-env/package.json +++ b/packages/shell/shell-env/package.json @@ -37,7 +37,7 @@ "@deepseek-ai/dsh-home-paths": "workspace:*", "@deepseek-ai/dsh-shell": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -47,7 +47,7 @@ "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-shell": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*" } diff --git a/packages/shell/shell-env/src/error.ts b/packages/shell/shell-env/src/error.ts new file mode 100644 index 0000000000..cd320b4971 --- /dev/null +++ b/packages/shell/shell-env/src/error.ts @@ -0,0 +1,28 @@ +/** Machine-routable shell environment failures. @module */ + +import { HarnessError } from '@deepseek-ai/dsh-error' + +/** + * Every {@link ShellEnvError} code: + * - `SHELL_ENV_CONTRIBUTION_INVALID` — a registered contributor returned an undeclared key or a non-string value; the + * shell command does not run, and the contributing plugin must be fixed. + */ +export const SHELL_ENV_ERROR_CODES = ['SHELL_ENV_CONTRIBUTION_INVALID'] as const + +/** One code from {@link SHELL_ENV_ERROR_CODES}. */ +export type ShellEnvErrorCode = typeof SHELL_ENV_ERROR_CODES[number] + +/** Shell environment failure carrying a stable {@link ShellEnvErrorCode}. */ +export class ShellEnvError extends HarnessError { + override readonly code: ShellEnvErrorCode + + /** + * @param message - names the contributor and the offending key. + * @param code - the failure class consumers route on. + */ + constructor(message: string, code: ShellEnvErrorCode) { + super(message, code) + this.name = 'ShellEnvError' + this.code = code + } +} diff --git a/packages/shell/shell-env/src/index.ts b/packages/shell/shell-env/src/index.ts index aa3012e2b4..ee84bf764b 100644 --- a/packages/shell/shell-env/src/index.ts +++ b/packages/shell/shell-env/src/index.ts @@ -14,42 +14,19 @@ import z from '@deepseek-ai/schemastery' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-shell' import type { DshEnvironment, DshEnvironmentKey } from '@deepseek-ai/dsh-shell' import { DSH_HOME_ENV, resolveDshHome } from '@deepseek-ai/dsh-home-paths' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { ShellEnvError } from './error.ts' import type { ToolExecution } from '@deepseek-ai/dsh-tools' // Declares `Context.profileContext`, the launcher-provided profile the built-ins read. import type {} from '@deepseek-ai/dsh-app-boot' +export { ShellEnvError, type ShellEnvErrorCode } from './error.ts' + declare module '@deepseek-ai/cordis' { interface Context { shellEnv: ShellEnvRegistry } } -/** - * Every {@link ShellEnvError} code: - * - `SHELL_ENV_CONTRIBUTION_INVALID` — a registered contributor returned an undeclared key or a non-string value; the - * shell command does not run, and the contributing plugin must be fixed. - */ -export const SHELL_ENV_ERROR_CODES = ['SHELL_ENV_CONTRIBUTION_INVALID'] as const - -/** One code from {@link SHELL_ENV_ERROR_CODES}. */ -export type ShellEnvErrorCode = typeof SHELL_ENV_ERROR_CODES[number] - -/** Shell environment failure carrying a stable {@link ShellEnvErrorCode}. */ -export class ShellEnvError extends HarnessError { - override readonly code: ShellEnvErrorCode - - /** - * @param message - names the contributor and the offending key. - * @param code - the failure class consumers route on. - */ - constructor(message: string, code: ShellEnvErrorCode) { - super(message, code) - this.name = 'ShellEnvError' - this.code = code - } -} - export const name = 'shell-env' export const inject: string[] = [] diff --git a/packages/shell/shell-env/tsconfig.json b/packages/shell/shell-env/tsconfig.json index ae66c37da9..050a016f80 100644 --- a/packages/shell/shell-env/tsconfig.json +++ b/packages/shell/shell-env/tsconfig.json @@ -30,7 +30,7 @@ "path": "../../boot/app-boot" }, { - "path": "../../llm/llm" + "path": "../../util/error" } ] } diff --git a/packages/subprocess/subprocess/package.json b/packages/subprocess/subprocess/package.json index 4d4968fbfb..1ff80d99f7 100644 --- a/packages/subprocess/subprocess/package.json +++ b/packages/subprocess/subprocess/package.json @@ -37,12 +37,12 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-http-proxy": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-http-proxy": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/subprocess/subprocess/src/error.ts b/packages/subprocess/subprocess/src/error.ts index 064dc494ae..febc495b63 100644 --- a/packages/subprocess/subprocess/src/error.ts +++ b/packages/subprocess/subprocess/src/error.ts @@ -1,6 +1,6 @@ /** Machine-routable subprocess failures shared by every `ctx.subprocess` provider and its consumers. @module */ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** * Every {@link SubprocessError} code: diff --git a/packages/subprocess/subprocess/tests/error.spec.ts b/packages/subprocess/subprocess/tests/error.spec.ts index ecdcb89a98..dbb0554043 100644 --- a/packages/subprocess/subprocess/tests/error.spec.ts +++ b/packages/subprocess/subprocess/tests/error.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { SUBPROCESS_ERROR_CODES, SubprocessError, diff --git a/packages/subprocess/subprocess/tsconfig.json b/packages/subprocess/subprocess/tsconfig.json index a39b295358..c961cc9e54 100644 --- a/packages/subprocess/subprocess/tsconfig.json +++ b/packages/subprocess/subprocess/tsconfig.json @@ -21,7 +21,7 @@ "path": "../../util/launch-environment" }, { - "path": "../../llm/llm" + "path": "../../util/error" } ] } diff --git a/packages/subprocess/win32-process/package.json b/packages/subprocess/win32-process/package.json index 7eae3438fc..205b2113f4 100644 --- a/packages/subprocess/win32-process/package.json +++ b/packages/subprocess/win32-process/package.json @@ -31,7 +31,7 @@ "license": "MIT", "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" }, "dependencies": { "@deepseek-ai/dsh-lazy-require": "workspace:*", @@ -39,6 +39,6 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-llm": "workspace:*" + "@deepseek-ai/dsh-error": "workspace:*" } } diff --git a/packages/subprocess/win32-process/src/errors.ts b/packages/subprocess/win32-process/src/errors.ts index d8cd4caa86..be3e531bc5 100644 --- a/packages/subprocess/win32-process/src/errors.ts +++ b/packages/subprocess/win32-process/src/errors.ts @@ -1,4 +1,4 @@ -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' /** Code of every {@link Win32Error}; the failing API and its numeric code stay in `api`, `win32Code`, and `message`. */ export const WIN32_ERROR = 'WIN32_ERROR' diff --git a/packages/subprocess/win32-process/tests/ffi.spec.ts b/packages/subprocess/win32-process/tests/ffi.spec.ts index a202503369..c3f4a9bfb8 100644 --- a/packages/subprocess/win32-process/tests/ffi.spec.ts +++ b/packages/subprocess/win32-process/tests/ffi.spec.ts @@ -1,6 +1,6 @@ import koffi from 'koffi' import { describe, expect, it, vi } from 'vitest' -import { HarnessError } from '@deepseek-ai/dsh-llm' +import { HarnessError } from '@deepseek-ai/dsh-error' import { WIN32_ERROR, Win32Error, diff --git a/packages/subprocess/win32-process/tsconfig.json b/packages/subprocess/win32-process/tsconfig.json index ac86e810e8..7430b866fa 100644 --- a/packages/subprocess/win32-process/tsconfig.json +++ b/packages/subprocess/win32-process/tsconfig.json @@ -13,7 +13,7 @@ "path": "../../util/lazy-require" }, { - "path": "../../llm/llm" + "path": "../../util/error" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b81d0ed5a..341f928b4c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14162,6 +14162,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm @@ -15314,6 +15317,9 @@ importers: '@deepseek-ai/dsh-agent-loop-testkit': specifier: workspace:* version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs @@ -15519,12 +15525,12 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:* version: link:../../boot/app-boot + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../util/home-paths - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm '@deepseek-ai/dsh-shell': specifier: workspace:* version: link:../shell @@ -16987,15 +16993,15 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-http-proxy': specifier: workspace:* version: link:../../util/http-proxy '@deepseek-ai/dsh-launch-environment': specifier: workspace:* version: link:../../util/launch-environment - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm packages/subprocess/subprocess-local: dependencies: @@ -17037,9 +17043,9 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-llm': + '@deepseek-ai/dsh-error': specifier: workspace:* - version: link:../../llm/llm + version: link:../../util/error packages/team/agent-team: dependencies: From aa90f0be5679c97e03d3f86817b53eaf0a037c34 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 18:10:50 +0800 Subject: [PATCH 053/438] 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 054/438] 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 055/438] 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 056/438] 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 057/438] 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 058/438] 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 059/438] 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 060/438] 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 061/438] 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 11a5bf8a55bb11a9ce7ae7e54775776c0dfca395 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:06:13 +0800 Subject: [PATCH 062/438] refactor(tool-fs): keep attachment store codes in read_image failures The attachment store already classifies its rejections, so read_image no longer translates them into ImageInputError codes. An AttachmentError keeps its name and code; for codes with a known remedy the tool rethrows it with a message naming the file and the next step, and the store error as cause. Other store failures pass through unchanged. ImageInputError keeps only the refusals the tool makes before storing the image: IMAGE_UNSUPPORTED_MODEL and IMAGE_UNSUPPORTED_FORMAT. The removed codes (IMAGE_TYPE_MISMATCH, IMAGE_INVALID, IMAGE_TOO_LARGE, IMAGE_CONVERSION_FAILED, IMAGE_STORE_FAILED) were never released. --- .../attachment-error-codes/guide.i18n.yaml | 4 +- .../attachment-error-codes/guide.md | 2 +- .../attachment-error-codes/guide.zh.md | 2 +- packages/fs/tool-fs/README.i18n.yaml | 8 ++-- packages/fs/tool-fs/README.md | 4 +- packages/fs/tool-fs/README.zh.md | 4 +- packages/fs/tool-fs/src/image-error.ts | 22 ++------- packages/fs/tool-fs/src/read-image.ts | 46 ++++++++++-------- packages/fs/tool-fs/tests/read-image.spec.ts | 48 ++++++++++--------- 9 files changed, 67 insertions(+), 73 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml index 091cae83fa..66e712178e 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 4f2b2f0db0646d3b zh: 9467f41336a65c48 /attachment-failures-keep-their-codes/change: - en: daa5a93cf418a352 - zh: 3b391fbb4a87f2b1 + en: 0f8c05c401f15a7d + zh: adf5976a05802bf1 /attachment-failures-keep-their-codes/migration: en: 8599ead7a17bc7eb zh: 1120fd02065567f5 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md index 263ddf5df8..70acc07793 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md @@ -12,7 +12,7 @@ English | [中文](guide.zh.md) `AttachmentError` from `@deepseek-ai/dsh-attachment` now extends `HarnessError` from `@deepseek-ai/dsh-error`. Its `name` (`AttachmentError`) and every `ATTACHMENT_*` and image admission code are unchanged. Two persisted results change: - When a model request fails because an adapter could not read an image attachment, the failed turn's `turn/end` error previously recorded `code: 'UNKNOWN'`. It now records the `AttachmentError` code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, `ATTACHMENT_READ_FAILED`, or an image admission code such as `INVALID_IMAGE` or `IMAGE_TOO_LARGE`. -- A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` converts attachment failures to `ImageInputError` codes instead. +- A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` also records the `AttachmentError` code and names the file and the next step in the message. `instanceof HarnessError` now matches `AttachmentError`. `isAttachmentError` is unchanged. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md index 674f00805b..7c00e63528 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md @@ -12,7 +12,7 @@ description: "AttachmentError 现在继承 HarnessError,工具失败与模型 `@deepseek-ai/dsh-attachment` 的 `AttachmentError` 现在继承 `@deepseek-ai/dsh-error` 中的 `HarnessError`。其 `name`(`AttachmentError`)以及所有 `ATTACHMENT_*` 与图像准入错误码均保持不变。两类持久化结果会变化: - 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录 `AttachmentError` 的错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT`、`ATTACHMENT_READ_FAILED`,或 `INVALID_IMAGE`、`IMAGE_TOO_LARGE` 等图像准入错误码。 -- 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 则把附件失败转换为 `ImageInputError` 错误码。 +- 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 同样记录 `AttachmentError` 的错误码,并在消息中写明文件与下一步。 `instanceof HarnessError` 现在会匹配 `AttachmentError`。`isAttachmentError` 不变。 diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index e8c96ec826..f9d9c8ac82 100644 --- a/packages/fs/tool-fs/README.i18n.yaml +++ b/packages/fs/tool-fs/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9bddebaf4aff0a8d zh: fea0196162e3fcd1 /deepseek-ai-dsh-tool-fs/use-this-package/failures-and-recovery: - en: 06fe9bd1d49c1d53 - zh: a8a6963daae11267 + en: 4e33f0736e64c72b + zh: b7a0f2386760e08e /deepseek-ai-dsh-tool-fs/understand-the-implementation: en: e30f7038c28e93f8 zh: a3868dbd90367b13 @@ -39,8 +39,8 @@ en: 1f4d7213aa3d0d60 zh: aa6573f96c8b5220 /deepseek-ai-dsh-tool-fs/understand-the-implementation/source-map: - en: 791043de5ce46710 - zh: c5315d0195908f83 + en: 8be089bfe40bb7ab + zh: 7753de2feca62205 /deepseek-ai-dsh-tool-fs/understand-the-implementation/per-tool-flow: en: 35fbee1ef9811806 zh: 17c725e2b742c073 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index cf3ef031df..93985eeb21 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -83,7 +83,7 @@ With the policy plugin mounted, `write` and `edit` obtain their guard from the ` For `apply_patch`, syntax and preflight refusals throw with `isError: true` before any disk change. `FsError` preserves filesystem codes; `PatchToolError extends HarnessError` carries `PATCH_SYNTAX` and `PATCH_SYMLINK_SOURCE`. Once commit starts, the tool returns a value with `isError: false` even on failure or uncertainty, so known partial effects retain their diff metadata; a call cancelled during commit receives the tool registry's abort result like every other tool, and its completed changes remain visible through Review. `phase`, `cancelled`, ordered `operations` and `affectedPaths` describe the commit; each operation retains its index, kind, display paths, patch line, status, diagnostic and known changes. Full `before`/`after` text serves rendering and PTC; the Session stores the rendered result plus `meta.diffs` and `meta.stopped`. Creations store no diff, as for `write`; deletions and move sources store a removal diff only when the provider returned a bounded basis, using `newText: ''` because `FileDiff.newText` cannot be null. -`read_image` refusals throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model), `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file), `IMAGE_TYPE_MISMATCH` (rename or convert the file), `IMAGE_INVALID` (truncated or corrupt bytes), `IMAGE_TOO_LARGE` (downscale the image), `IMAGE_CONVERSION_FAILED` (a 16-bit PNG could not be normalized; convert it to 8-bit), and `IMAGE_STORE_FAILED` (any other attachment-store failure, kept as `cause`). An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any store failure other than an `AttachmentError`, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged. +`read_image` refusals it makes before storing the image throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model) or `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file). Refusals from the attachment store keep their `AttachmentError` `name` and `code`, such as `INVALID_IMAGE`, `IMAGE_TYPE_MISMATCH`, or `IMAGE_DIMENSION_TOO_LARGE`; for codes with a known remedy, the message names the file and the next step, and the store error is the `cause`. An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any other store failure, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged. Failures are normalized as `Error: ` with a structured code preserved for callers. Stable messages include the `ToolArgsError` (`INVALID_ARGS`) messages `invalid arguments: file_path must be a non-empty string` and `invalid arguments: limit must be less than or equal to `, `cannot read "": not found`, `cannot read "": not a regular file`, and the image-route refusal `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. @@ -108,7 +108,7 @@ The tools are the executor; policy is an event gate. The tools inject no policy | [`src/index.ts`](src/index.ts) | Plugin entry: `Config`, tool composition, `read_image` attachments gate | | [`src/read.ts`](src/read.ts) | `read` executor: one stat, streaming decision, window build, observation | | [`src/read-image.ts`](src/read-image.ts) | `read_image` executor: route and media-type gates, bounded bytes, attachment save | -| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` and its closed `read_image` failure codes | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` and the closed codes for refusals `read_image` makes itself | | [`src/write.ts`](src/write.ts) | `write` executor: intent waterfall, atomic write, observation | | [`src/apply-patch.ts`](src/apply-patch.ts), [`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` registration, strict commit values and compact diagnostics | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | Pure call previews and known result diffs | diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 09af000f07..ec28bf145c 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference" `apply_patch` 的语法与预检拒绝在磁盘变更前抛错,结果为 `isError: true`。`FsError` 保留文件系统错误码;`PatchToolError extends HarnessError` 携带 `PATCH_SYNTAX` 和 `PATCH_SYMLINK_SOURCE`。进入提交后,即使失败或结果不确定也返回 `isError: false` 的值,确保已知部分效果的 diff 元数据得以保留;提交期间被取消的调用与其他工具一样收到工具注册表的中止结果,已完成的变更仍可通过 Review 查看。`phase`、`cancelled`、有序 `operations` 与 `affectedPaths` 描述提交;每条操作保留索引、种类、展示路径、补丁行号、状态、诊断与已知变更。完整 `before`/`after` 文本供渲染和 PTC 使用;Session 保存渲染文本以及 `meta.diffs` 与 `meta.stopped`。新建与 `write` 一样不保存 diff;删除与移动源仅在提供方返回有界基线时保存删除 diff,并使用 `newText: ''`,因为 `FileDiff.newText` 不可为 null。 -`read_image` 的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)、`IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)、`IMAGE_TYPE_MISMATCH`(重命名或转换文件)、`IMAGE_INVALID`(字节被截断或损坏)、`IMAGE_TOO_LARGE`(缩小图像)、`IMAGE_CONVERSION_FAILED`(16 位 PNG 无法规范化;转换为 8 位)以及 `IMAGE_STORE_FAILED`(其他附件存储失败,原错误保留为 `cause`)。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的 `AttachmentError` 以外的失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。 +`read_image` 在存储图像前自行作出的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)或 `IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)。附件存储作出的拒绝保留其 `AttachmentError` 的 `name` 与 `code`,例如 `INVALID_IMAGE`、`IMAGE_TYPE_MISMATCH` 或 `IMAGE_DIMENSION_TOO_LARGE`;对有明确补救办法的错误码,消息会写明文件与下一步,存储错误作为 `cause`。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的其他失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。 失败被规范化为 `Error: `,并为调用方保留结构化错误码。稳定消息包括 `ToolArgsError`(`INVALID_ARGS`)消息 `invalid arguments: file_path must be a non-empty string` 与 `invalid arguments: limit must be less than or equal to `、`cannot read "": not found`、`cannot read "": not a regular file`,以及图像路由拒绝 `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。 @@ -108,7 +108,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 插件入口:`Config`、工具组合、`read_image` 附件门禁 | | [`src/read.ts`](src/read.ts) | `read` 执行器:一次 stat、流式决策、窗口构建、观察 | | [`src/read-image.ts`](src/read-image.ts) | `read_image` 执行器:路由与媒体类型门禁、有界字节、附件保存 | -| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` 及其封闭的 `read_image` 失败码 | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` 及 `read_image` 自行拒绝时使用的封闭错误码 | | [`src/write.ts`](src/write.ts) | `write` 执行器:意图 waterfall、原子写入、观察 | | [`src/apply-patch.ts`](src/apply-patch.ts)、[`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` 注册、严格提交值与精简诊断 | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | 纯调用预览与已知结果 diff | diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts index a19a0b0f8d..ccacb48744 100644 --- a/packages/fs/tool-fs/src/image-error.ts +++ b/packages/fs/tool-fs/src/image-error.ts @@ -3,37 +3,23 @@ import { HarnessError } from '@deepseek-ai/dsh-error' /** - * Every machine-routable `read_image` failure code: + * Every `read_image` failure the tool classifies itself, before the attachment store sees the bytes: * * - `IMAGE_UNSUPPORTED_MODEL`: the calling route does not declare image input; switch to an image-capable model. * - `IMAGE_UNSUPPORTED_FORMAT`: the extension, the file signature, or the deployment's accepted media types * exclude the format; convert the file to an accepted format or read another file. - * - `IMAGE_TYPE_MISMATCH`: the extension or file signature declares one format but the bytes decode as another; rename or convert the file. - * - `IMAGE_INVALID`: bytes in a supported format do not decode; the file is truncated or corrupt. - * - `IMAGE_TOO_LARGE`: a side, the decoded pixel count, or the stored byte budget exceeds the deployment limit; - * downscale the image and read the smaller copy. - * - `IMAGE_CONVERSION_FAILED`: a 16-bit PNG could not be normalized to 8-bit sRGB; convert it to an 8-bit format. - * - `IMAGE_STORE_FAILED`: the attachment store could not commit the image for another reason; report the cause - * instead of retrying unchanged. + * + * Failures the attachment store classifies keep their `AttachmentError` codes. */ export const IMAGE_INPUT_ERROR_CODES = [ 'IMAGE_UNSUPPORTED_MODEL', 'IMAGE_UNSUPPORTED_FORMAT', - 'IMAGE_TYPE_MISMATCH', - 'IMAGE_INVALID', - 'IMAGE_TOO_LARGE', - 'IMAGE_CONVERSION_FAILED', - 'IMAGE_STORE_FAILED', ] as const /** One `read_image` failure code. */ export type ImageInputErrorCode = typeof IMAGE_INPUT_ERROR_CODES[number] -/** - * Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. `IMAGE_TOO_LARGE` and - * `IMAGE_TYPE_MISMATCH` share their spelling with `AttachmentError` codes, so consumers route on `name` - * and `code` together, and code-only predicates such as `isAttachmentError` do not identify this class. - */ +/** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */ export class ImageInputError extends HarnessError { override readonly code: ImageInputErrorCode diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 9f7d714ed6..be422b38aa 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -215,45 +215,49 @@ interface SaveFailureFacts { } /** - * Classify one `saveImage` rejection as the error `read_image` throws. - * Attachment admission codes become {@link ImageInputError} codes and other - * `AttachmentError` codes become `IMAGE_STORE_FAILED`, keeping the original as - * `cause`. The attachment store reports its own failures as `AttachmentError`, - * so any other value, including cancellation, passes through unchanged. + * Add the read path and the next step to one `saveImage` rejection. The attachment store + * classifies its own failures, so an `AttachmentError` keeps its `name` and `code` and only + * gains a message naming the file and remedy, with the original as `cause`; a code without + * a remedy, and any value that is not an `AttachmentError`, passes through unchanged. * @param error - the value `saveImage` rejected with. - * @param attachments - the store whose limits the refusal names. - * @param facts - the path and media-type facts the refusal names. + * @param attachments - the store whose limits the message names. + * @param facts - the path and media-type facts the message names. * @returns the error to throw from the tool body. */ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFailureFacts): unknown { - const { displayPath, extension, mediaType, sniffed } = facts - const refusal = (detail: string, code: ImageInputError['code']) => - new ImageInputError(`cannot read "${displayPath}": ${detail}`, code, { cause: error }) - const storeFailed = (detail: string) => refusal(`the attachment store could not save the image: ${detail}`, 'IMAGE_STORE_FAILED') if (!(error instanceof AttachmentError)) return error + const detail = saveFailureDetail(error, attachments, facts) + return detail === undefined + ? error + : new AttachmentError(`cannot read "${facts.displayPath}": ${detail}`, error.code, { cause: error }) +} + +/** The model-facing remedy for one attachment rejection, or undefined when the store message stands. */ +function saveFailureDetail(error: AttachmentError, attachments: AttachmentStore, facts: SaveFailureFacts): string | undefined { + const { extension, mediaType, sniffed } = facts // Size refusals stay recoverable tool errors: an oversized image must never // enter durable history, where it would ride every later model request past // provider-side dimension rejections. switch (error.code) { case 'IMAGE_DIMENSION_TOO_LARGE': - return refusal(`at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + return `at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy` case 'IMAGE_TOO_MANY_PIXELS': - return refusal(`the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + return `the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy` case 'IMAGE_TOO_LARGE': case 'IMAGES_TOO_LARGE': - return refusal('the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy', 'IMAGE_TOO_LARGE') + return 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy' case 'UNSUPPORTED_IMAGE_TYPE': - return refusal(`${mediaType} images are not accepted by this deployment`, 'IMAGE_UNSUPPORTED_FORMAT') + return `${mediaType} images are not accepted by this deployment` case 'INVALID_IMAGE': - return refusal('the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt', 'IMAGE_INVALID') + return 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt' case 'IMAGE_TYPE_MISMATCH': return sniffed - ? refusal(`the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, 'IMAGE_TYPE_MISMATCH') - : refusal(`the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, 'IMAGE_TYPE_MISMATCH') + ? `the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt` + : `the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats` case 'ATTACHMENT_WRITE_FAILED': return /16-bit PNG/iu.test(error.message) - ? refusal('the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry', 'IMAGE_CONVERSION_FAILED') - : storeFailed(error.message) + ? 'the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry' + : undefined case 'TOO_MANY_IMAGES': case 'INVALID_IMAGE_BASE64': case 'INVALID_FILE_BASE64': @@ -263,7 +267,7 @@ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFa case 'ATTACHMENT_READ_FAILED': case 'ATTACHMENT_PROJECTION_UNSUPPORTED': case 'ATTACHMENT_FILES_UNSUPPORTED': - return storeFailed(error.message) + return undefined /* v8 ignore next -- Closed AttachmentErrorCode union; assertNever checks exhaustiveness at compile time. */ default: return assertNever(error.code) diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index bced7b466e..a55bb1c717 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -397,7 +397,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'broken' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('do not decode as a supported PNG/JPEG/WebP/GIF image') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_INVALID' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'INVALID_IMAGE' }) }) it('applies the deployment media-type policy to the sniffed format', async () => { @@ -463,7 +463,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'sniffed' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('the file signature claims image/png, but the bytes decode as a different image format') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TYPE_MISMATCH' }) }) }) @@ -593,7 +593,7 @@ describe('image admission failures', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('the .jpg extension declares image/jpeg') expect(text(result)).toContain('rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TYPE_MISMATCH' }) }) it('caps an extension-less read at maxImageBytes before format detection', async () => { @@ -620,7 +620,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'big.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('exceeds the 4-pixel decoded-size limit') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TOO_MANY_PIXELS' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) @@ -630,7 +630,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'wide.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('at least one image side exceeds the 2px limit') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_DIMENSION_TOO_LARGE' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) @@ -674,31 +674,35 @@ describe('image admission failures', () => { } it.each([ - ['IMAGE_TOO_LARGE', 'Image cannot be encoded within the configured normalized-image byte cap.', 'IMAGE_TOO_LARGE', + ['IMAGE_TOO_LARGE', 'Image cannot be encoded within the configured normalized-image byte cap.', 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], - ['IMAGES_TOO_LARGE', 'Image batch exceeds the configured aggregate image-byte limit.', 'IMAGE_TOO_LARGE', + ['IMAGES_TOO_LARGE', 'Image batch exceeds the configured aggregate image-byte limit.', 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], - ['UNSUPPORTED_IMAGE_TYPE', 'Image type image/png is not accepted by this deployment.', 'IMAGE_UNSUPPORTED_FORMAT', + ['UNSUPPORTED_IMAGE_TYPE', 'Image type image/png is not accepted by this deployment.', 'image/png images are not accepted by this deployment'], - ['INVALID_IMAGE', 'Unsupported or malformed image data.', 'IMAGE_INVALID', + ['INVALID_IMAGE', 'Unsupported or malformed image data.', 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt'], - ['ATTACHMENT_WRITE_FAILED', 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', 'IMAGE_CONVERSION_FAILED', + ['ATTACHMENT_WRITE_FAILED', 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', 'the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry'], - ['ATTACHMENT_WRITE_FAILED', 'Unable to persist attachment.', 'IMAGE_STORE_FAILED', - 'the attachment store could not save the image: Unable to persist attachment.'], - ...([ - 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', 'ATTACHMENT_CORRUPT', - 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', 'ATTACHMENT_FILES_UNSUPPORTED', - ] as const).map(code => [code, 'Stored attachment failed.', 'IMAGE_STORE_FAILED', - 'the attachment store could not save the image: Stored attachment failed.'] as const), - ] as const)('classifies AttachmentError %s (%s) as %s', async (attachmentCode, message, code, detail) => { - const cause = new AttachmentError(message, attachmentCode) + ] as const)('keeps AttachmentError %s and adds the read path and remedy', async (code, message, detail) => { + const cause = new AttachmentError(message, code) const result = await failingSave(() => cause) expect(result.isError).toBe(true) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code }) expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": ${detail}`) }) + it.each([ + 'ATTACHMENT_WRITE_FAILED', 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', + 'ATTACHMENT_CORRUPT', 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', + 'ATTACHMENT_FILES_UNSUPPORTED', + ] as const)('passes AttachmentError %s without a read remedy through unchanged', async (code) => { + const result = await failingSave(() => new AttachmentError('Stored attachment failed.', code)) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code }) + expect(text(result)).toBe('Error: Stored attachment failed.') + }) + it('passes a store defect, a classified HarnessError, and an AbortError through unchanged', async () => { const defect = await failingSave(() => new Error('unrelated infrastructure failure')) expect(defect.isError).toBe(true) @@ -726,13 +730,13 @@ describe('image admission failures', () => { expect(text(result)).not.toContain('cannot read') }) - it('classifies a save failure that is not cancellation even after the caller aborts', async () => { + it('keeps a save failure that is not cancellation even after the caller aborts', async () => { const controller = new AbortController() const result = await failingSave(() => { controller.abort() return new AttachmentError('Unable to persist attachment.', 'ATTACHMENT_WRITE_FAILED') }, 'red.png', controller.signal) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'ATTACHMENT_WRITE_FAILED' }) }) it('reports a missing image file and a directory target through the fs vocabulary', async () => { From 05270c6fcbe119da39dca2e351684b603445b23b Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:22:51 +0800 Subject: [PATCH 063/438] test(sandbox,terminal): drop the new assertions to unknown The ACL preparation tests match the error cause with a partial object instead of a matcher cast to unknown, and the uncancelled cleanup failure test checks the retained owner activity through the public service rather than casting the service to reach its disposal method. Refs #7869 --- packages/sandbox/sandbox-local/tests/acl-grants.spec.ts | 6 +++--- packages/terminal/terminal/tests/service.spec.ts | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts index c98fbf0eb9..4f4c99c0e4 100644 --- a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts +++ b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts @@ -267,7 +267,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', message: expect.stringMatching(/workspace grant failed and its cleanup also failed/u) as string, - cause: expect.objectContaining({ errors: [mockState.addFailure, mockState.disposeFailure] }) as unknown, + cause: { errors: [mockState.addFailure, mockState.disposeFailure] }, }) expect(mockState.grants).toHaveLength(2) } finally { @@ -290,7 +290,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', message: expect.stringContaining('workspace and temp directory resolution failed') as string, - cause: expect.objectContaining({ code: 'ENOENT' }) as unknown, + cause: { code: 'ENOENT' }, }) expect(mockState.grants).toHaveLength(0) } finally { @@ -313,7 +313,7 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { name: 'SandboxPreparationError', code: 'SANDBOX_PREPARATION_FAILED', message: expect.stringContaining('private temp directory creation failed') as string, - cause: expect.objectContaining({ code: 'EACCES' }) as unknown, + cause: { code: 'EACCES' }, }) } finally { if (previous === undefined) delete process.env.TMPDIR diff --git a/packages/terminal/terminal/tests/service.spec.ts b/packages/terminal/terminal/tests/service.spec.ts index 3199deb1a0..a43448b761 100644 --- a/packages/terminal/terminal/tests/service.spec.ts +++ b/packages/terminal/terminal/tests/service.spec.ts @@ -309,8 +309,7 @@ describe('TerminalSessionService ownership and lifecycle', () => { await expect(ctx.terminals.spawn(owner, { type: 'cleanup-failing' })).rejects.toBe(failure) expect(failure).toMatchObject({ name: 'TerminalBackendCleanupError', code: 'CLEANUP_FAILED' }) - const internal = ctx.terminals as unknown as { disposeOwned(owner: Agent): Promise } - await expect(internal.disposeOwned(owner)).rejects.toThrow('failed to clean up PTY lifecycle') + expect(ctx.terminals.hasOwnerActivity(owner)).toBe(true) }) it.each(['owner', 'service'] as const)('retains caller-triggered backend cleanup failure until %s disposal', async (scope) => { From 85c7b7be35444afca594a42c2178be373ede41c6 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:28:16 +0800 Subject: [PATCH 064/438] test(fs-local): cover readFile errno classification on every platform The Windows coverage lane left the errno branch of readFileAbortable uncovered: its only test denies reads with chmod, which is POSIX-only, and the v8 ignore did not reach the throw. readForEdit reads without a preceding stat, so a missing file and a directory exercise the branch on every platform; the ignore is removed. --- packages/fs/fs-local/src/fsio.ts | 1 - packages/fs/fs-local/tests/fsio.spec.ts | 9 +++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/fs/fs-local/src/fsio.ts b/packages/fs/fs-local/src/fsio.ts index 63da0a95f0..c6959128a4 100644 --- a/packages/fs/fs-local/src/fsio.ts +++ b/packages/fs/fs-local/src/fsio.ts @@ -66,7 +66,6 @@ async function readFileAbortable(absolutePath: string, displayPath: string, verb try { return await readFile(absolutePath, signal ? { signal } : {}) } catch (error: unknown) { - /* v8 ignore next 2 -- a non-abort rejection needs a permission fault after a successful stat; POSIX covers it. */ if (isAbortError(error)) throw new FsError(`${verb} aborted`, 'FS_ABORTED') throw fsErrorFromErrno(verb, displayPath, error) } diff --git a/packages/fs/fs-local/tests/fsio.spec.ts b/packages/fs/fs-local/tests/fsio.spec.ts index 4d4f9a3748..6c7379051d 100644 --- a/packages/fs/fs-local/tests/fsio.spec.ts +++ b/packages/fs/fs-local/tests/fsio.spec.ts @@ -981,6 +981,15 @@ describe('readForEdit + restoreLineEndings', () => { await expect(readForEdit(join(dir, 'bad'), join(dir, 'bad'))).rejects.toMatchObject({ code: 'FS_NOT_TEXT' }) }) + it('classifies a missing file and a directory read for editing', async () => { + await expect(readForEdit(join(dir, 'missing'), '~/missing')).rejects.toMatchObject({ + name: 'FsError', code: 'FS_NOT_FOUND', message: 'cannot edit "~/missing": not found', + }) + await expect(readForEdit(dir, '~/dir')).rejects.toMatchObject({ + name: 'FsError', code: 'FS_NOT_REGULAR_FILE', message: 'cannot edit "~/dir": not a regular file', + }) + }) + it('passes a live (non-aborted) signal through the read', async () => { const file = join(dir, 'a.txt') await writeFile(file, 'one\ntwo') From 3ce9462e7f8ee65e4b61578ccfc4c72b1c8e59a5 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:31:56 +0800 Subject: [PATCH 065/438] fix(terminal): keep both startup failures on TerminalBackendCleanupError's cause Renderers such as errorChain and the activation report expand AggregateError members but otherwise follow only cause, so a cause of just the setup failure hid the cleanup failure that may leave resources alive. The cause is now an AggregateError of both failures. An upgrade guide records that the class extends TerminalError instead of AggregateError. INIT_REJECTED is documented as the code a consumer that drives a shell uses when the shell rejects its setup input, and the persistent bash tool README records it. Refs #7869 --- .../guide.i18n.yaml | 16 ++++++++++++++ .../terminal-backend-cleanup-error/guide.md | 20 +++++++++++++++++ .../guide.zh.md | 20 +++++++++++++++++ .../tool-bash-persistent/README.i18n.yaml | 4 ++-- packages/shell/tool-bash-persistent/README.md | 2 +- .../shell/tool-bash-persistent/README.zh.md | 2 +- .../terminal-bash/tests/index.spec.ts | 2 +- packages/terminal/terminal/README.i18n.yaml | 8 +++---- packages/terminal/terminal/README.md | 4 ++-- packages/terminal/terminal/README.zh.md | 4 ++-- packages/terminal/terminal/src/error.ts | 22 +++++++++++-------- 11 files changed, 82 insertions(+), 22 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md diff --git a/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.i18n.yaml new file mode 100644 index 0000000000..fc72ae7b2e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md +/: + en: 91597636f5a71894 + zh: 02d2517952d86cfd +/terminalbackendcleanuperror-extends-terminalerror: + en: cb11df977825904b + zh: 080f157e78942a9d +/terminalbackendcleanuperror-extends-terminalerror/change: + en: bf3bd46faf910ff0 + zh: fd47d6e58f467a1e +/terminalbackendcleanuperror-extends-terminalerror/migration: + en: 85fe7dd354cf8657 + zh: e39dc4ce137aeb13 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md new file mode 100644 index 0000000000..7ab32fec51 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "TerminalBackendCleanupError extends TerminalError instead of AggregateError and carries the CLEANUP_FAILED code." +--- + +# `TerminalBackendCleanupError` extends `TerminalError` + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-terminal` exports `TerminalBackendCleanupError`, which a PTY backend throws when startup failed and cleaning its partial resources also failed. It previously extended `AggregateError`. It now extends `TerminalError`, so it is a `HarnessError` with code `CLEANUP_FAILED`, and a tool result that carries it records `error.name` `TerminalBackendCleanupError` and `error.code` `CLEANUP_FAILED`. The constructor, the `name`, `spawnError`, `cleanupError`, and the `errors` list in that order are unchanged; `errors` is typed `readonly unknown[]` instead of `any[]`. `cause` is a new `AggregateError` of the same two failures. `error instanceof AggregateError` is now `false`. + +Backends and consumers that only construct the error, read `spawnError` or `cleanupError`, or test `instanceof TerminalBackendCleanupError` are unaffected. + +## Migration + +1. Replace `error instanceof AggregateError` checks meant for this error with `error instanceof TerminalBackendCleanupError`, or with `error.code === 'CLEANUP_FAILED'` on a `TerminalError`. +2. Where TypeScript code reads members of `error.errors` without narrowing, narrow each `unknown` element before use, or read `spawnError` and `cleanupError`. +3. Confirm with `pnpm exec tsc --noEmit` in the consuming project, and check that a startup cleanup failure still reaches the handling path. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md new file mode 100644 index 0000000000..7f69c4558d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/terminal-backend-cleanup-error/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "TerminalBackendCleanupError 改为继承 TerminalError 而非 AggregateError,并带 CLEANUP_FAILED 错误码。" +--- + +# `TerminalBackendCleanupError` 改为继承 `TerminalError` + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-terminal` 导出的 `TerminalBackendCleanupError` 由 PTY 后端在启动失败且清理部分资源也失败时抛出。它原先继承 `AggregateError`,现在继承 `TerminalError`,因此是带 code `CLEANUP_FAILED` 的 `HarnessError`,携带它的工具结果会记录 `error.name` `TerminalBackendCleanupError` 和 `error.code` `CLEANUP_FAILED`。构造函数、`name`、`spawnError`、`cleanupError` 以及按原顺序排列的 `errors` 列表不变;`errors` 的类型由 `any[]` 改为 `readonly unknown[]`。`cause` 新增为同样两个失败组成的 `AggregateError`。`error instanceof AggregateError` 现在为 `false`。 + +只构造该错误、读取 `spawnError` 或 `cleanupError`、或检查 `instanceof TerminalBackendCleanupError` 的后端与消费方不受影响。 + +## 迁移 + +1. 把针对该错误的 `error instanceof AggregateError` 检查改为 `error instanceof TerminalBackendCleanupError`,或对 `TerminalError` 检查 `error.code === 'CLEANUP_FAILED'`。 +2. TypeScript 代码未经收窄就读取 `error.errors` 元素成员时,先收窄每个 `unknown` 元素,或改为读取 `spawnError` 与 `cleanupError`。 +3. 在消费项目中运行 `pnpm exec tsc --noEmit` 确认通过,并检查启动清理失败仍会进入原有的处理路径。 diff --git a/packages/shell/tool-bash-persistent/README.i18n.yaml b/packages/shell/tool-bash-persistent/README.i18n.yaml index a7d7a29c7c..3bf961d1ca 100644 --- a/packages/shell/tool-bash-persistent/README.i18n.yaml +++ b/packages/shell/tool-bash-persistent/README.i18n.yaml @@ -27,8 +27,8 @@ en: b398f124ea7b77b0 zh: 50855e601e6c1b88 /deepseek-ai-dsh-tool-bash-persistent/use-this-package/what-can-go-wrong: - en: 52e0e1489c6f8071 - zh: 27251d61351ee72d + en: 080e71c8720eab46 + zh: 2b0266e78c868d9c /deepseek-ai-dsh-tool-bash-persistent/understand-the-implementation: en: 8d94a7381bca3fa9 zh: f4bd2866fff6fa8d diff --git a/packages/shell/tool-bash-persistent/README.md b/packages/shell/tool-bash-persistent/README.md index 9feed7a656..3a6de11ff4 100644 --- a/packages/shell/tool-bash-persistent/README.md +++ b/packages/shell/tool-bash-persistent/README.md @@ -58,7 +58,7 @@ Commands share one shell per agent, so state persists until an `exit`, a timeout ### What can go wrong -A call without an owning agent session fails with `bash requires an owning agent session` (`ToolContextUnavailableError`, `TOOL_CONTEXT_UNAVAILABLE`), a blank command fails with `ToolArgsError` (`INVALID_ARGS`), and a composition without a PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. An interactive foreground child (for example a REPL) returns early with partial output only where the backend proves its stdin wait; elsewhere the call runs to `timeoutMs`, which closes the uncertain shell and reports the reset. Cancellation also resets and discards the result, even when a complete status marker is already observable. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. +A call without an owning agent session fails with `bash requires an owning agent session` (`ToolContextUnavailableError`, `TOOL_CONTEXT_UNAVAILABLE`), a blank command fails with `ToolArgsError` (`INVALID_ARGS`), a shell that does not accept the echo and history setup fails with `persistent bash shell did not accept initialization` (`TerminalError`, `INIT_REJECTED`), and a composition without a PTY backend activates the tool but fails its first call with `no PTY backend registered for "shell"`. An interactive foreground child (for example a REPL) returns early with partial output only where the backend proves its stdin wait; elsewhere the call runs to `timeoutMs`, which closes the uncertain shell and reports the reset. Cancellation also resets and discards the result, even when a complete status marker is already observable. After cleanup settles, ToolRuntime publishes `Error: tool call aborted` with code `ABORTED`; cancellation reasons are not rendered as command output. A queued cancelled call sends no command. ----- diff --git a/packages/shell/tool-bash-persistent/README.zh.md b/packages/shell/tool-bash-persistent/README.zh.md index c348502a09..f74537f54e 100644 --- a/packages/shell/tool-bash-persistent/README.zh.md +++ b/packages/shell/tool-bash-persistent/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 可能出什么问题 -没有拥有者 agent 会话的调用会以 `bash requires an owning agent session`(`ToolContextUnavailableError`,`TOOL_CONTEXT_UNAVAILABLE`)失败,空白命令以 `ToolArgsError`(`INVALID_ARGS`)失败,没有 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。交互式前台子进程(例如 REPL)只有在后端证明其 stdin 等待时才提前返回部分输出;否则调用一直运行到 `timeoutMs`,随后关闭不确定的 shell 并报告重置。取消也会重置并丢弃结果,即使完整状态标记已经可观察。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 +没有拥有者 agent 会话的调用会以 `bash requires an owning agent session`(`ToolContextUnavailableError`,`TOOL_CONTEXT_UNAVAILABLE`)失败,空白命令以 `ToolArgsError`(`INVALID_ARGS`)失败,不接受回显与历史设置的 shell 以 `persistent bash shell did not accept initialization`(`TerminalError`,`INIT_REJECTED`)失败,没有 PTY 后端的组合会激活该工具,但首次调用以 `no PTY backend registered for "shell"` 失败。交互式前台子进程(例如 REPL)只有在后端证明其 stdin 等待时才提前返回部分输出;否则调用一直运行到 `timeoutMs`,随后关闭不确定的 shell 并报告重置。取消也会重置并丢弃结果,即使完整状态标记已经可观察。清理完成后,ToolRuntime 发布 `Error: tool call aborted`,错误码为 `ABORTED`;取消原因不作为命令输出渲染。排队期间被取消的调用不发送命令。 ----- diff --git a/packages/terminal/terminal-bash/tests/index.spec.ts b/packages/terminal/terminal-bash/tests/index.spec.ts index 2859644622..47cca862e9 100644 --- a/packages/terminal/terminal-bash/tests/index.spec.ts +++ b/packages/terminal/terminal-bash/tests/index.spec.ts @@ -162,7 +162,7 @@ describe('BashTerminalBackend startup rollback', () => { spawnError: startupFailure, cleanupError: cleanupFailure, errors: [startupFailure, cleanupFailure], - cause: startupFailure, + cause: expect.objectContaining({ errors: [startupFailure, cleanupFailure] }) as AggregateError, } satisfies Partial)) }) diff --git a/packages/terminal/terminal/README.i18n.yaml b/packages/terminal/terminal/README.i18n.yaml index e734b14bf2..9f24300c84 100644 --- a/packages/terminal/terminal/README.i18n.yaml +++ b/packages/terminal/terminal/README.i18n.yaml @@ -45,11 +45,11 @@ en: a2adfa2708882e19 zh: 002f257fd8c4addb /deepseek-ai-dsh-terminal/understand-the-implementation/ownership-and-cleanup-rules: - en: b669a68c739b062a - zh: cc641f850905095f + en: 3c977ec7192623b1 + zh: 78d14a23e087808a /deepseek-ai-dsh-terminal/understand-the-implementation/send-reservation: - en: 0b8dc3a382aa7bf2 - zh: e6cc6906e01827d2 + en: b80a540215116c43 + zh: 1dc651d09ceb4b15 /deepseek-ai-dsh-terminal/further-exploration: en: 8459a3b70a9f8bad zh: 21372aa8939d2182 diff --git a/packages/terminal/terminal/README.md b/packages/terminal/terminal/README.md index ff34d9a3cc..ac88814518 100644 --- a/packages/terminal/terminal/README.md +++ b/packages/terminal/terminal/README.md @@ -84,12 +84,12 @@ Each published session is a record of its id, owner, optional name, backend type ### Ownership and cleanup rules - Fencing uses the exact `Agent` object: `hasOwnerActivity(owner)` spans unpublished setup through final close with no publication gap, so lifecycle policy can fence the owner precisely. -- A backend that cannot clean partial startup resources rejects with `TerminalBackendCleanupError`, a `TerminalError` with code `CLEANUP_FAILED` that lists both failures in `errors`; the service retains that failure as tracked owner activity until owner or service disposal consumes and reports it. +- A backend that cannot clean partial startup resources rejects with `TerminalBackendCleanupError`, a `TerminalError` with code `CLEANUP_FAILED` that lists both failures in `errors` and in an `AggregateError` `cause`; the service retains that failure as tracked owner activity until owner or service disposal consumes and reports it. - Caller cancellation keeps its exact `AbortSignal.reason`; `kill()` and disposal resolve only after the backend's captured process tree is quiescent. ### Send reservation -The service reserves a session synchronously for one active send before returning the operation, including before a background job id becomes visible; a second send fails with `SEND_ACTIVE`, so output and cancellation never cross operation ownership. Failures are `TerminalError` instances (a `HarnessError`); besides the registry codes, a send to a closing session fails with `SESSION_CLOSING`, and backends report `SESSION_EXITED`, `STARTUP_EXITED`, `STARTUP_TIMEOUT`, `NO_SANDBOX`, and `INIT_REJECTED` with the same class. +The service reserves a session synchronously for one active send before returning the operation, including before a background job id becomes visible; a second send fails with `SEND_ACTIVE`, so output and cancellation never cross operation ownership. Failures are `TerminalError` instances (a `HarnessError`); besides the registry codes, a send to a closing session fails with `SESSION_CLOSING`, and backends report `SESSION_EXITED`, `STARTUP_EXITED`, `STARTUP_TIMEOUT`, and `NO_SANDBOX` with the same class. A consumer that drives a shell uses `INIT_REJECTED` when that shell rejects the consumer's setup input.
diff --git a/packages/terminal/terminal/README.zh.md b/packages/terminal/terminal/README.zh.md index cef5a62110..07022207e5 100644 --- a/packages/terminal/terminal/README.zh.md +++ b/packages/terminal/terminal/README.zh.md @@ -84,12 +84,12 @@ kind: "package-reference" ### 所有权与清理规则 - 限制基于确切的 `Agent` 对象:`hasOwnerActivity(owner)` 覆盖从尚未发布的设置到最终关闭的全过程,没有发布竞态,因此生命周期策略可以精确限制所有者。 -- 无法清理部分启动资源的后端会以 `TerminalBackendCleanupError` 拒绝,它是 code 为 `CLEANUP_FAILED` 的 `TerminalError`,并在 `errors` 中列出两个失败;服务会将该失败保留为受跟踪的所有者活动,直到所有者或服务 dispose 消费并报告它。 +- 无法清理部分启动资源的后端会以 `TerminalBackendCleanupError` 拒绝,它是 code 为 `CLEANUP_FAILED` 的 `TerminalError`,在 `errors` 和 `AggregateError` 类型的 `cause` 中列出两个失败;服务会将该失败保留为受跟踪的所有者活动,直到所有者或服务 dispose 消费并报告它。 - 调用方取消保留其确切的 `AbortSignal.reason`;`kill()` 与 dispose 只在后端捕获的进程树完全停稳后完成。 ### 发送预留 -服务在返回操作之前同步为一个活跃发送预留会话,包括在后台任务的 job id 可见之前;第二次发送会以 `SEND_ACTIVE` 失败,因此输出与取消永远不会跨操作所有权。失败均为 `TerminalError`(一种 `HarnessError`);除注册表 code 外,向正在关闭的会话发送会以 `SESSION_CLOSING` 失败,后端以同一类报告 `SESSION_EXITED`、`STARTUP_EXITED`、`STARTUP_TIMEOUT`、`NO_SANDBOX` 与 `INIT_REJECTED`。 +服务在返回操作之前同步为一个活跃发送预留会话,包括在后台任务的 job id 可见之前;第二次发送会以 `SEND_ACTIVE` 失败,因此输出与取消永远不会跨操作所有权。失败均为 `TerminalError`(一种 `HarnessError`);除注册表 code 外,向正在关闭的会话发送会以 `SESSION_CLOSING` 失败,后端以同一类报告 `SESSION_EXITED`、`STARTUP_EXITED`、`STARTUP_TIMEOUT` 与 `NO_SANDBOX`。通过服务驱动 shell 的消费方在该 shell 拒绝自身的初始化输入时使用 `INIT_REJECTED`。
diff --git a/packages/terminal/terminal/src/error.ts b/packages/terminal/terminal/src/error.ts index b487ac9bc4..71db13687c 100644 --- a/packages/terminal/terminal/src/error.ts +++ b/packages/terminal/terminal/src/error.ts @@ -4,13 +4,14 @@ import { HarnessError } from '@deepseek-ai/dsh-error' /** * Machine-routable PTY service and backend failures. Backends use - * `INIT_REJECTED` when the shell rejects its setup input, `NO_SANDBOX` when a - * confined mode has no sandbox provider, `SESSION_CLOSING` and - * `SESSION_EXITED` for an operation on a closing or exited session, - * `STARTUP_EXITED` or `STARTUP_TIMEOUT` when the shell exits or misses - * readiness during startup, and `CLEANUP_FAILED` (always as + * `NO_SANDBOX` when a confined mode has no sandbox provider, + * `SESSION_CLOSING` and `SESSION_EXITED` for an operation on a closing or + * exited session, `STARTUP_EXITED` or `STARTUP_TIMEOUT` when the shell exits + * or misses readiness during startup, and `CLEANUP_FAILED` (always as * {@link TerminalBackendCleanupError}) when startup failed and the partial - * resources it left could not be cleaned. + * resources it left could not be cleaned. A consumer that drives a shell + * through the service uses `INIT_REJECTED` when that shell rejects the + * consumer's own setup input. */ export type TerminalErrorCode = | 'CLEANUP_FAILED' @@ -48,8 +49,9 @@ export class TerminalError extends HarnessError { /** * Backend-reported failure to clean partial resources after unpublished setup * failed; code `CLEANUP_FAILED`. Backend-owned resources may still be alive. - * `errors` lists both failures in the order `AggregateError` would, and - * `cause` is the setup failure. + * `errors` lists the setup failure, then the cleanup failure; `cause` is an + * `AggregateError` of the same two failures, so renderers that follow `cause` + * report both. */ export class TerminalBackendCleanupError extends TerminalError { /** The setup failure followed by the cleanup failure. */ @@ -63,7 +65,9 @@ export class TerminalBackendCleanupError extends TerminalError { readonly spawnError: unknown, readonly cleanupError: unknown, ) { - super('PTY backend startup and cleanup both failed', 'CLEANUP_FAILED', { cause: spawnError }) + super('PTY backend startup and cleanup both failed', 'CLEANUP_FAILED', { + cause: new AggregateError([spawnError, cleanupError], 'PTY backend startup and cleanup both failed'), + }) this.name = 'TerminalBackendCleanupError' this.errors = [spawnError, cleanupError] } From 088d1f3b0405fe85650eaf298321ab4fa7767eb9 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:38:50 +0800 Subject: [PATCH 066/438] fix(shell): classify only errno spawn failures and real cancellations subprocessSpawnFailure() now converts only errors that carry a string errno code and returns every other value unchanged, so an internal failure such as a dropped collect stream is no longer reported as cannot start / SUBPROCESS_SPAWN_FAILED. The bash and pwsh tools pass a rejection through unchanged only when it is the call's own cancellation reason; a spawn error that settles after the call was cancelled is still classified. The job starter reads the failure through an optional hooks binding instead of a definite-assignment assertion. Refs #7869 --- packages/shell/tool-bash/README.i18n.yaml | 4 +-- packages/shell/tool-bash/README.md | 2 +- packages/shell/tool-bash/README.zh.md | 2 +- packages/shell/tool-bash/src/index.ts | 25 ++++++++++--------- packages/shell/tool-bash/tests/tools.spec.ts | 16 ++++++++++++ packages/shell/tool-pwsh/README.i18n.yaml | 4 +-- packages/shell/tool-pwsh/README.md | 2 +- packages/shell/tool-pwsh/README.zh.md | 2 +- packages/shell/tool-pwsh/src/index.ts | 25 ++++++++++--------- .../shell/tool-pwsh/tests/background.spec.ts | 4 +-- packages/shell/tool-pwsh/tests/tools.spec.ts | 16 ++++++++++++ .../subprocess/subprocess/README.i18n.yaml | 4 +-- packages/subprocess/subprocess/README.md | 2 +- packages/subprocess/subprocess/README.zh.md | 2 +- packages/subprocess/subprocess/src/error.ts | 22 +++++++--------- .../subprocess/subprocess/tests/error.spec.ts | 11 +++++--- 16 files changed, 89 insertions(+), 54 deletions(-) diff --git a/packages/shell/tool-bash/README.i18n.yaml b/packages/shell/tool-bash/README.i18n.yaml index 625910149b..95fd6ed161 100644 --- a/packages/shell/tool-bash/README.i18n.yaml +++ b/packages/shell/tool-bash/README.i18n.yaml @@ -111,8 +111,8 @@ en: 2d4f2c8605eccab3 zh: 67f1f0218f73c6bf /deepseek-ai-dsh-tool-bash/model-experience/tool-errors/what-the-model-sees: - en: f4cebcfd09cd3b13 - zh: 4e3954f417b4a9ed + en: 1772eedea1c1ee6a + zh: a0d77bdd515cb517 /deepseek-ai-dsh-tool-bash/model-experience/tool-errors/token-effect: en: a3a78ef476ec5e56 zh: dd2c8ad0f69e8ff1 diff --git a/packages/shell/tool-bash/README.md b/packages/shell/tool-bash/README.md index 411d5da79f..7c1a498b13 100644 --- a/packages/shell/tool-bash/README.md +++ b/packages/shell/tool-bash/README.md @@ -196,7 +196,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the approval availability/rejection/cancellation variants, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`). +Validation and policy failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the approval availability/rejection/cancellation variants, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error, recognized by its errno `code`, becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`), even when it settles after the call was cancelled. #### Token effect diff --git a/packages/shell/tool-bash/README.zh.md b/packages/shell/tool-bash/README.zh.md index 7f222c91aa..1e0f96c57f 100644 --- a/packages/shell/tool-bash/README.zh.md +++ b/packages/shell/tool-bash/README.zh.md @@ -196,7 +196,7 @@ renderer 输出依数据而定的 stdout 尾部,再输出可选的 `[stderr]` #### 模型看到什么 -验证与策略失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、审批不可用/拒绝/取消变体,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`)。 +验证与策略失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、审批不可用/拒绝/取消变体,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;按 errno `code` 识别的平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`),在调用取消后才出现时也是如此。 #### Token 影响 diff --git a/packages/shell/tool-bash/src/index.ts b/packages/shell/tool-bash/src/index.ts index 46554fc192..f3e8b14eb2 100644 --- a/packages/shell/tool-bash/src/index.ts +++ b/packages/shell/tool-bash/src/index.ts @@ -30,6 +30,7 @@ import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import { DSH_ENV_PREFIX } from '@deepseek-ai/dsh-shell' import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellRunResult } from '@deepseek-ai/dsh-shell' import { processJob, processOutcome, processSources, ringDelta } from './background.ts' +import type { ProcessJobHooks } from './background.ts' import { parseExitStatus, renderJobRead, renderPromoted, renderResult } from './render.ts' export const name = 'tool-bash' @@ -188,13 +189,14 @@ function toolAborted(): HarnessError { } /** - * Report a launch or preparation rejection as this tool's failure. A coded - * error keeps its class and code; this call's cancellation stays as thrown so - * the registry records it as aborted; any other value is classified as a - * subprocess spawn failure with the original as `cause`. + * Report a launch or preparation rejection as this tool's failure. This + * call's cancellation reason stays as thrown so the registry records it as + * aborted; a platform spawn error is classified as a subprocess spawn failure + * with the original as `cause`; any other value, including a coded error, + * keeps its own identity. */ function launchFailure(error: unknown, signal: AbortSignal): unknown { - return signal.aborted ? error : subprocessSpawnFailure(error, 'bash') + return signal.aborted && error === signal.reason ? error : subprocessSpawnFailure(error, 'bash') } /** A registered command: its id, the process once the starter spawned it, and the reason an outside kill gave. */ @@ -283,8 +285,7 @@ export function apply(ctx: Context, config: Config = {}): void { const startJob = (registry: JobRegistry, args: BashToolArgs, exec: ToolExecution, spec: ShellExecSpec): StartedJob => { let proc: ShellExecution | undefined let stopped: string | undefined - // The registry runs the starter inside start(), so this is assigned before start() returns. - let failure!: () => { error: unknown } | undefined + let hooks: ProcessJobHooks | undefined const id = registry.start({ kind: 'bash', label: args.command, @@ -292,26 +293,26 @@ export function apply(ctx: Context, config: Config = {}): void { ...exec.agent ? { owner: exec.agent.id } : {}, output: processSources(() => proc), run: () => { - const hooks = processJob( + const job = processJob( async (signal) => { proc = await ctx.shell.execute({ ...spec, signal }) return proc }, started => processOutcome(started, escalationModes), ) - failure = () => hooks.failure() + hooks = job return { - done: hooks.done, + done: job.done, // A kill from outside this call (the human's, a parallel job_kill) // reaches the process here; its reason is what the model reads. cancel: (reason) => { stopped = reason - hooks.cancel(reason) + job.cancel(reason) }, } }, }) - return { id, process: () => proc, stopped: () => stopped, failure: () => failure() } + return { id, process: () => proc, stopped: () => stopped, failure: () => hooks?.failure() } } /** Wait on a registered foreground command until it settles or the timeout passes. */ const waitOnJob = async (registry: JobRegistry, attached: StartedJob, exec: ToolExecution, spec: ShellExecSpec) => { diff --git a/packages/shell/tool-bash/tests/tools.spec.ts b/packages/shell/tool-bash/tests/tools.spec.ts index 554b7f4e35..45e92e05d5 100644 --- a/packages/shell/tool-bash/tests/tools.spec.ts +++ b/packages/shell/tool-bash/tests/tools.spec.ts @@ -1576,4 +1576,20 @@ describe('launch failures without a job registry', () => { }) expect(aborted).toMatchObject({ isError: true, error: { info: { name: 'AbortError', code: TOOL_ABORTED } } }) }) + + it('classifies a spawn error that settles after this call was cancelled', async () => { + const ctx = await setup() + const controller = new AbortController() + vi.spyOn(ctx.shell, 'execute').mockImplementationOnce(() => { + controller.abort(new Error('caller stopped')) + return Promise.reject(Object.assign(new Error('spawn bash ENOENT'), { code: 'ENOENT' })) + }) + const result = await executeToolFixture(ctx, { + signal: controller.signal, + callId: ToolCallId('launch-aborted-spawn-error'), + name: 'bash', + arguments: { command: 'true', description: 'd' }, + }) + expect(result).toMatchObject({ isError: true, error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } } }) + }) }) diff --git a/packages/shell/tool-pwsh/README.i18n.yaml b/packages/shell/tool-pwsh/README.i18n.yaml index 8032f1b349..e4c8f16b4b 100644 --- a/packages/shell/tool-pwsh/README.i18n.yaml +++ b/packages/shell/tool-pwsh/README.i18n.yaml @@ -108,8 +108,8 @@ en: 2d4f2c8605eccab3 zh: 67f1f0218f73c6bf /deepseek-ai-dsh-tool-pwsh/model-experience/tool-errors/what-the-model-sees: - en: d45b05d98cf6e7e3 - zh: b3c59fb3603f511e + en: c71e7f547de19d3d + zh: a9d9c3a84e1618b9 /deepseek-ai-dsh-tool-pwsh/model-experience/tool-errors/token-effect: en: 243bad012dd99c7f zh: 5ee74905020bd49a diff --git a/packages/shell/tool-pwsh/README.md b/packages/shell/tool-pwsh/README.md index 34bc941529..ff35a8068d 100644 --- a/packages/shell/tool-pwsh/README.md +++ b/packages/shell/tool-pwsh/README.md @@ -188,7 +188,7 @@ Append-only; newly visible content follows the reusable request prefix and does #### What the model sees -Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the shared escalation failures (not strictly wider / no approval service / no agent to route / no approval channel / user rejected / was cancelled), `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`). +Validation and infrastructure failures are normalized as `Error: `. This package's stable messages are `invalid arguments: invalid command: expected a non-empty string`, `invalid arguments: invalid description: expected a non-empty string`, `invalid arguments: invalid timeoutMs: expected a positive number, got `, the escalation pairing failures, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, the shared escalation failures (not strictly wider / no approval service / no agent to route / no approval channel / user rejected / was cancelled), `run_in_background is disabled for this deployment (enableRunInBackground: false)`, `background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`, and `tool call aborted`. Each failure also records `error.name` and `error.code` on `tool/result`: argument violations are `ToolArgsError` (`INVALID_ARGS`, message prefix `invalid arguments: `), escalation failures are `SandboxEscalationError` (`SANDBOX_ESCALATION_INVALID_ARGUMENT`, `_UNAVAILABLE`, `_REJECTED`, `_CANCELLED`), a disabled background call is `JobError` (`JOB_BACKGROUND_DISABLED`), a missing job runtime is `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`), and cancellation is `AbortError` (`ABORTED`). A launch or preparation failure keeps the class and code it was thrown with, such as `SandboxUnavailableError` or `SandboxPreparationError`, whether the call waited on a job or not; a platform spawn error, recognized by its errno `code`, becomes `SubprocessError` (`SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT`, otherwise `SUBPROCESS_SPAWN_FAILED`), even when it settles after the call was cancelled. #### Token effect diff --git a/packages/shell/tool-pwsh/README.zh.md b/packages/shell/tool-pwsh/README.zh.md index f81c92a602..6225e8ad33 100644 --- a/packages/shell/tool-pwsh/README.zh.md +++ b/packages/shell/tool-pwsh/README.zh.md @@ -188,7 +188,7 @@ Non-zero exits are reported as `[exit code: N]` markers; investigate failures be #### 模型看到什么 -验证与基础设施失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、共享升权失败(未严格加宽/无审批服务/无 agent 可路由/无审批通道/用户拒绝/已取消)、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`)。 +验证与基础设施失败统一为 `Error: `。本包的稳定消息包括 `invalid arguments: invalid command: expected a non-empty string`、`invalid arguments: invalid description: expected a non-empty string`、`invalid arguments: invalid timeoutMs: expected a positive number, got `、升权配对失败、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、共享升权失败(未严格加宽/无审批服务/无 agent 可路由/无审批通道/用户拒绝/已取消)、`run_in_background is disabled for this deployment (enableRunInBackground: false)`、`background jobs unavailable: load @deepseek-ai/dsh-jobs and @deepseek-ai/dsh-tool-jobs`,以及 `tool call aborted`。每个失败还会在 `tool/result` 上记录 `error.name` 与 `error.code`:参数违规为 `ToolArgsError`(`INVALID_ARGS`,消息前缀为 `invalid arguments: `),升权失败为 `SandboxEscalationError`(`SANDBOX_ESCALATION_INVALID_ARGUMENT`、`_UNAVAILABLE`、`_REJECTED`、`_CANCELLED`),被禁用的后台调用为 `JobError`(`JOB_BACKGROUND_DISABLED`),缺少任务运行时为 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`),取消为 `AbortError`(`ABORTED`)。启动或准备阶段的失败保留其抛出时的类与 code(例如 `SandboxUnavailableError` 或 `SandboxPreparationError`),无论调用是否在 job 上等待;按 errno `code` 识别的平台 spawn 错误转为 `SubprocessError`(`ENOENT` 为 `SUBPROCESS_SPAWN_NOT_FOUND`,其余为 `SUBPROCESS_SPAWN_FAILED`),在调用取消后才出现时也是如此。 #### Token 影响 diff --git a/packages/shell/tool-pwsh/src/index.ts b/packages/shell/tool-pwsh/src/index.ts index 0ef0fa260b..1a5eac1e7d 100644 --- a/packages/shell/tool-pwsh/src/index.ts +++ b/packages/shell/tool-pwsh/src/index.ts @@ -39,6 +39,7 @@ import type { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy' import type { ShellExecRequest, ShellExecSpec, ShellExecution, ShellRunResult } from '@deepseek-ai/dsh-shell' import { parseExitStatus } from '@deepseek-ai/dsh-shell' import { processJob, processOutcome, processSources, ringDelta } from './background.ts' +import type { ProcessJobHooks } from './background.ts' import { renderPwshJobRead, renderPwshPromoted, renderPwshResult } from './render.ts' import type { RenderablePwshResult } from './render.ts' @@ -196,13 +197,14 @@ function toolAborted(): HarnessError { } /** - * Report a launch or preparation rejection as this tool's failure. A coded - * error keeps its class and code; this call's cancellation stays as thrown so - * the registry records it as aborted; any other value is classified as a - * subprocess spawn failure with the original as `cause`. + * Report a launch or preparation rejection as this tool's failure. This + * call's cancellation reason stays as thrown so the registry records it as + * aborted; a platform spawn error is classified as a subprocess spawn failure + * with the original as `cause`; any other value, including a coded error, + * keeps its own identity. */ function launchFailure(error: unknown, signal: AbortSignal): unknown { - return signal.aborted ? error : subprocessSpawnFailure(error, 'pwsh') + return signal.aborted && error === signal.reason ? error : subprocessSpawnFailure(error, 'pwsh') } /** A registered command: its id, the process once the starter spawned it, and the reason an outside kill gave. */ @@ -298,8 +300,7 @@ export function apply(ctx: Context, config: Config = {}): void { const startJob = (registry: JobRegistry, args: PwshToolArgs, exec: ToolExecution, spec: ShellExecSpec): StartedJob => { let proc: ShellExecution | undefined let stopped: string | undefined - // The registry runs the starter inside start(), so this is assigned before start() returns. - let failure!: () => { error: unknown } | undefined + let hooks: ProcessJobHooks | undefined const id = registry.start({ kind: 'pwsh', label: args.command, @@ -307,26 +308,26 @@ export function apply(ctx: Context, config: Config = {}): void { ...exec.agent ? { owner: exec.agent.id } : {}, output: processSources(() => proc), run: () => { - const hooks = processJob( + const job = processJob( async (signal) => { proc = await ctx.shell.execute({ ...spec, signal }) return proc }, started => processOutcome(started, escalationModes), ) - failure = () => hooks.failure() + hooks = job return { - done: hooks.done, + done: job.done, // A kill from outside this call (the human's, a parallel job_kill) // reaches the process here; its reason is what the model reads. cancel: (reason) => { stopped = reason - hooks.cancel(reason) + job.cancel(reason) }, } }, }) - return { id, process: () => proc, stopped: () => stopped, failure: () => failure() } + return { id, process: () => proc, stopped: () => stopped, failure: () => hooks?.failure() } } /** Wait on a registered foreground command until it settles or the timeout passes. */ const waitOnJob = async (registry: JobRegistry, attached: StartedJob, exec: ToolExecution, spec: ShellExecSpec) => { diff --git a/packages/shell/tool-pwsh/tests/background.spec.ts b/packages/shell/tool-pwsh/tests/background.spec.ts index 48b01dde16..870325ab91 100644 --- a/packages/shell/tool-pwsh/tests/background.spec.ts +++ b/packages/shell/tool-pwsh/tests/background.spec.ts @@ -345,13 +345,13 @@ describe('foreground commands as jobs (pwsh)', () => { it('a command whose start fails reports the failure as an error result and leaves no job behind', async () => { const { ctx, pwsh } = await setup() - pwsh.backgroundHandler = () => { throw new Error('spawn pwsh ENOENT') } + pwsh.backgroundHandler = () => { throw Object.assign(new Error('spawn pwsh EACCES'), { code: 'EACCES' }) } const result = await call(ctx, { command: 'Get-Missing', description: 'test command' }) expect(result).toMatchObject({ isError: true, error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_FAILED' } }, }) - expect((result.content[0] as { text: string }).text).toBe('Error: cannot start "pwsh": spawn pwsh ENOENT') + expect((result.content[0] as { text: string }).text).toBe('Error: cannot start "pwsh": spawn pwsh EACCES') expect(ctx.jobs.list()).toEqual([]) }) diff --git a/packages/shell/tool-pwsh/tests/tools.spec.ts b/packages/shell/tool-pwsh/tests/tools.spec.ts index 00fb01724f..7db5c6fc5d 100644 --- a/packages/shell/tool-pwsh/tests/tools.spec.ts +++ b/packages/shell/tool-pwsh/tests/tools.spec.ts @@ -1317,4 +1317,20 @@ describe('launch failures without a job registry', () => { }) expect(aborted).toMatchObject({ isError: true, error: { info: { name: 'AbortError', code: TOOL_ABORTED } } }) }) + + it('classifies a spawn error that settles after this call was cancelled', async () => { + const { ctx } = await setup() + const controller = new AbortController() + vi.spyOn(ctx.shell, 'execute').mockImplementationOnce(() => { + controller.abort(new Error('caller stopped')) + return Promise.reject(Object.assign(new Error('spawn pwsh ENOENT'), { code: 'ENOENT' })) + }) + const result = await executeToolFixture(ctx, { + signal: controller.signal, + callId: ToolCallId('launch-aborted-spawn-error'), + name: 'pwsh', + arguments: { command: 'Write-Output ok', description: 'd' }, + }) + expect(result).toMatchObject({ isError: true, error: { info: { name: 'SubprocessError', code: 'SUBPROCESS_SPAWN_NOT_FOUND' } } }) + }) }) diff --git a/packages/subprocess/subprocess/README.i18n.yaml b/packages/subprocess/subprocess/README.i18n.yaml index 762893c5a0..8f829ef784 100644 --- a/packages/subprocess/subprocess/README.i18n.yaml +++ b/packages/subprocess/subprocess/README.i18n.yaml @@ -39,8 +39,8 @@ en: 4d4cbb311575d071 zh: 7be2d265adb661bc /deepseek-ai-dsh-subprocess/use-this-package/what-can-go-wrong: - en: 718494d6530da700 - zh: a41b7d48a9d12178 + en: 819a0d9b6ac823ab + zh: 57be33bc8204dd3e /deepseek-ai-dsh-subprocess/understand-the-implementation: en: 25cd344c959cfd9e zh: 045880776ab82d1e diff --git a/packages/subprocess/subprocess/README.md b/packages/subprocess/subprocess/README.md index 337afd9fba..f94817fa4d 100644 --- a/packages/subprocess/subprocess/README.md +++ b/packages/subprocess/subprocess/README.md @@ -81,7 +81,7 @@ Children never inherit the harness's ambient secrets: credential-shaped names an ### What can go wrong -Coded failures are `SubprocessError` instances whose `code` is one of `SUBPROCESS_ERROR_CODES`: an empty argv is `SUBPROCESS_INVALID_ARGV`, an executable lookup miss is `SubprocessExecutableNotFoundError` (`SUBPROCESS_EXECUTABLE_NOT_FOUND`), a provider's private runner that fails or breaks its channel is `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`, and an unloadable terminal implementation is `SUBPROCESS_PTY_UNAVAILABLE`. A spawn requested on an already aborted signal throws an error named `AbortError`. A spawn that never starts rejects `done` with the platform's original error, so consumers can inspect its errno fields; a consumer that reports the rejection as its own failure converts it with `subprocessSpawnFailure()`, which yields `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` otherwise. There is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced. +Coded failures are `SubprocessError` instances whose `code` is one of `SUBPROCESS_ERROR_CODES`: an empty argv is `SUBPROCESS_INVALID_ARGV`, an executable lookup miss is `SubprocessExecutableNotFoundError` (`SUBPROCESS_EXECUTABLE_NOT_FOUND`), a provider's private runner that fails or breaks its channel is `SUBPROCESS_RUNNER_FAILED` or `SUBPROCESS_RUNNER_IPC_FAILED`, and an unloadable terminal implementation is `SUBPROCESS_PTY_UNAVAILABLE`. A spawn requested on an already aborted signal throws an error named `AbortError`. A spawn that never starts rejects `done` with the platform's original error, so consumers can inspect its errno fields; a consumer that reports the rejection as its own failure converts it with `subprocessSpawnFailure()`, which turns an error with a string errno `code` into `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` for any other errno, and returns every other value unchanged. There is no buffered output for a process that never ran. `waitForExit()` also rejects when the provider cannot prove its selected range is empty, and a provider fallback may not own descendants that escape its process group or observed session. When a transport owns its own spawn (the SDK client, MCP), route around the service and import `scrubbedParentEnv` directly so environment policy stays single-sourced. ----- diff --git a/packages/subprocess/subprocess/README.zh.md b/packages/subprocess/subprocess/README.zh.md index da111f517a..90cabb9c87 100644 --- a/packages/subprocess/subprocess/README.zh.md +++ b/packages/subprocess/subprocess/README.zh.md @@ -81,7 +81,7 @@ const output = handle.collected.stdout?.readFrom(0) ### 可能出错的地方 -带 code 的失败都是 `SubprocessError`,其 `code` 属于 `SUBPROCESS_ERROR_CODES`:argv 为空是 `SUBPROCESS_INVALID_ARGV`,可执行文件查找未命中是 `SubprocessExecutableNotFoundError`(`SUBPROCESS_EXECUTABLE_NOT_FOUND`),提供方私有 runner 失败或通道损坏是 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED`,终端实现无法加载是 `SUBPROCESS_PTY_UNAVAILABLE`。在已 abort 的 signal 上请求 spawn 会抛出名为 `AbortError` 的错误。从未启动成功的 spawn 会让 `done` 以平台原始错误 reject,便于消费者检查 errno 字段;把该 reject 报告为自身失败的消费者用 `subprocessSpawnFailure()` 转换,`ENOENT` 得到 `SUBPROCESS_SPAWN_NOT_FOUND`,其余得到 `SUBPROCESS_SPAWN_FAILED`。从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。 +带 code 的失败都是 `SubprocessError`,其 `code` 属于 `SUBPROCESS_ERROR_CODES`:argv 为空是 `SUBPROCESS_INVALID_ARGV`,可执行文件查找未命中是 `SubprocessExecutableNotFoundError`(`SUBPROCESS_EXECUTABLE_NOT_FOUND`),提供方私有 runner 失败或通道损坏是 `SUBPROCESS_RUNNER_FAILED` 或 `SUBPROCESS_RUNNER_IPC_FAILED`,终端实现无法加载是 `SUBPROCESS_PTY_UNAVAILABLE`。在已 abort 的 signal 上请求 spawn 会抛出名为 `AbortError` 的错误。从未启动成功的 spawn 会让 `done` 以平台原始错误 reject,便于消费者检查 errno 字段;把该 reject 报告为自身失败的消费者用 `subprocessSpawnFailure()` 转换:带字符串 errno `code` 的错误中,`ENOENT` 得到 `SUBPROCESS_SPAWN_NOT_FOUND`,其余 errno 得到 `SUBPROCESS_SPAWN_FAILED`;其他值原样返回。从未运行过的进程没有任何缓冲输出。提供方无法证明所选范围为空时,`waitForExit()` 也会 reject;提供方 fallback 可能无法拥有逃离其进程组或已观察会话的后代。当传输拥有自己的 spawn(SDK 客户端、MCP)时,请绕开本服务并直接导入 `scrubbedParentEnv`,让环境策略保持单一来源。 ----- diff --git a/packages/subprocess/subprocess/src/error.ts b/packages/subprocess/subprocess/src/error.ts index febc495b63..df6acbec18 100644 --- a/packages/subprocess/subprocess/src/error.ts +++ b/packages/subprocess/subprocess/src/error.ts @@ -61,21 +61,17 @@ export class SubprocessExecutableNotFoundError extends SubprocessError { * `cause`. * @param error - the provider's rejection value. * @param program - the program the consumer asked to spawn, named in the message. - * @returns `error` unchanged when it is a `HarnessError` or a cancellation - * (`name === 'AbortError'`); otherwise a {@link SubprocessError} with - * `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and `SUBPROCESS_SPAWN_FAILED` for - * any other value. + * @returns a {@link SubprocessError} for a platform spawn error, recognized by + * its string errno `code`: `SUBPROCESS_SPAWN_NOT_FOUND` for `ENOENT` and + * `SUBPROCESS_SPAWN_FAILED` for any other errno. Every other value, including + * a `HarnessError`, is returned unchanged, because it is not a spawn failure + * this helper can classify. */ export function subprocessSpawnFailure(error: unknown, program: string): unknown { - if (error instanceof HarnessError) return error - if (error instanceof Error && error.name === 'AbortError') return error - const errno = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined - let detail = 'unprintable failure' - try { - detail = error instanceof Error ? error.message : String(error) - } catch { - // A provider-owned rejection whose conversion throws still yields a coded failure. - } + if (!(error instanceof Error) || error instanceof HarnessError) return error + const errno = (error as { code?: unknown }).code + if (typeof errno !== 'string') return error + const detail = error.message if (errno === 'ENOENT') { return new SubprocessError( `cannot start ${JSON.stringify(program)}: the program or the working directory does not exist (${detail})`, diff --git a/packages/subprocess/subprocess/tests/error.spec.ts b/packages/subprocess/subprocess/tests/error.spec.ts index dbb0554043..4916e05c06 100644 --- a/packages/subprocess/subprocess/tests/error.spec.ts +++ b/packages/subprocess/subprocess/tests/error.spec.ts @@ -34,9 +34,14 @@ describe('subprocessSpawnFailure', () => { }) const denied = Object.assign(new Error('spawn bash EACCES'), { code: 'EACCES' }) expect(subprocessSpawnFailure(denied, 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', cause: denied }) - expect(subprocessSpawnFailure('raw', 'bash')).toMatchObject({ code: 'SUBPROCESS_SPAWN_FAILED', message: 'cannot start "bash": raw' }) - const unprintable = { [Symbol.toPrimitive]() { throw new Error('no') } } - expect(subprocessSpawnFailure(unprintable, 'bash')).toMatchObject({ message: 'cannot start "bash": unprintable failure' }) + }) + + it('returns values without an errno code unchanged', () => { + const internal = new Error('subprocess implementation dropped a requested collect stream') + expect(subprocessSpawnFailure(internal, 'bash')).toBe(internal) + const numeric = Object.assign(new Error('exit'), { code: 1 }) + expect(subprocessSpawnFailure(numeric, 'bash')).toBe(numeric) + expect(subprocessSpawnFailure('raw', 'bash')).toBe('raw') }) it('returns coded errors and cancellations unchanged', () => { From 50577597e925fd37767dd9147b1ad9bb5d12a95c Mon Sep 17 00:00:00 2001 From: Huo Yaoyuan Date: Fri, 6 Nov 2026 17:40:53 +0800 Subject: [PATCH 067/438] 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 449addf2c9cafd7c76656fb03ff9ec698c4d7468 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:42:23 +0800 Subject: [PATCH 068/438] fix(jobs): report a missing owner registry with a JobError code A job registration that names an owner in a composition without an Agent registry now throws JobError JOB_OWNER_REGISTRY_UNAVAILABLE instead of the tool-layer ToolContextUnavailableError: the registry is a service whose start() also has non-tool callers. jobs-local no longer depends on dsh-tools. Refs #7869 --- docs/config-catalog.md | 6 +++--- docs/config-catalog.zh.md | 6 +++--- docs/module-graph.md | 11 +++++------ docs/module-graph.zh.md | 11 +++++------ packages/jobs/jobs-local/README.i18n.yaml | 4 ++-- packages/jobs/jobs-local/README.md | 2 +- packages/jobs/jobs-local/README.zh.md | 2 +- packages/jobs/jobs-local/package.json | 6 ++---- packages/jobs/jobs-local/src/index.ts | 3 +-- packages/jobs/jobs-local/tests/jobs.spec.ts | 2 +- packages/jobs/jobs-local/tsconfig.json | 3 --- packages/jobs/jobs/src/error.ts | 2 ++ pnpm-lock.yaml | 3 --- 13 files changed, 26 insertions(+), 35 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f0e447ae59..7f4507050d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1891,7 +1891,7 @@ export interface TlsConfig { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:47`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -4083,7 +4083,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts) +- `source`: [`packages/shell/tool-bash/src/index.ts:40`](../packages/shell/tool-bash/src/index.ts) ```ts config-catalog /** Configuration for the bash tool. */ @@ -4348,7 +4348,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-pwsh` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts) +- `source`: [`packages/shell/tool-pwsh/src/index.ts:57`](../packages/shell/tool-pwsh/src/index.ts) ```ts config-catalog /** Configuration for the pwsh tool. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index dad8488a45..167e434a7b 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1893,7 +1893,7 @@ export interface TlsConfig { ## `@deepseek-ai/dsh-jobs-local` -- `source`: [`packages/jobs/jobs-local/src/index.ts:47`](../packages/jobs/jobs-local/src/index.ts) +- `source`: [`packages/jobs/jobs-local/src/index.ts:46`](../packages/jobs/jobs-local/src/index.ts) ```ts config-catalog /** Configuration for the process-local job registry. */ @@ -4085,7 +4085,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-bash` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-bash/src/index.ts:39`](../packages/shell/tool-bash/src/index.ts) +- `source`: [`packages/shell/tool-bash/src/index.ts:40`](../packages/shell/tool-bash/src/index.ts) ```ts config-catalog /** Configuration for the bash tool. */ @@ -4350,7 +4350,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-pwsh` - `inject`: `tools` · `shell` · `systemPrompt` · `shellEnv` · `workingDirectory` -- `source`: [`packages/shell/tool-pwsh/src/index.ts:56`](../packages/shell/tool-pwsh/src/index.ts) +- `source`: [`packages/shell/tool-pwsh/src/index.ts:57`](../packages/shell/tool-pwsh/src/index.ts) ```ts config-catalog /** Configuration for the pwsh tool. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index dbd423430a..065d448df7 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -808,6 +808,10 @@ flowchart TD pkg_permission_presets --> pkg_shell pkg_permission_presets --> pkg_typert_protocol pkg_permission_presets --> pkg_user_approval + pkg_jobs_local --> pkg_agent + pkg_jobs_local --> pkg_jobs + pkg_jobs_local --> pkg_scope + pkg_jobs_local --> pkg_timeout pkg_ptc_runtime_node --> pkg_fs pkg_ptc_runtime_node --> pkg_ptc_runtime pkg_ptc_runtime_node --> pkg_sandbox @@ -1023,11 +1027,6 @@ flowchart TD pkg_tool_ask_user --> pkg_agent pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_questions - pkg_jobs_local --> pkg_agent - pkg_jobs_local --> pkg_jobs - pkg_jobs_local --> pkg_scope - pkg_jobs_local --> pkg_timeout - pkg_jobs_local --> pkg_tools pkg_tool_jobs --> pkg_agent pkg_tool_jobs --> pkg_jobs pkg_tool_jobs --> pkg_llm @@ -1803,6 +1802,7 @@ flowchart TD | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | @@ -1845,7 +1845,6 @@ flowchart TD | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | | [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/interaction/tool-ask-user) | `interaction` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-jobs`](../packages/jobs/tool-jobs) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-lsp`](../packages/lsp/tool-lsp) | `lsp` | [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`mcp-resources`](../packages/mcp/mcp-resources) | `mcp` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index caf5f595f8..f60f9a4e3d 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -810,6 +810,10 @@ flowchart TD pkg_permission_presets --> pkg_shell pkg_permission_presets --> pkg_typert_protocol pkg_permission_presets --> pkg_user_approval + pkg_jobs_local --> pkg_agent + pkg_jobs_local --> pkg_jobs + pkg_jobs_local --> pkg_scope + pkg_jobs_local --> pkg_timeout pkg_ptc_runtime_node --> pkg_fs pkg_ptc_runtime_node --> pkg_ptc_runtime pkg_ptc_runtime_node --> pkg_sandbox @@ -1025,11 +1029,6 @@ flowchart TD pkg_tool_ask_user --> pkg_agent pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_questions - pkg_jobs_local --> pkg_agent - pkg_jobs_local --> pkg_jobs - pkg_jobs_local --> pkg_scope - pkg_jobs_local --> pkg_timeout - pkg_jobs_local --> pkg_tools pkg_tool_jobs --> pkg_agent pkg_tool_jobs --> pkg_jobs pkg_tool_jobs --> pkg_llm @@ -1805,6 +1804,7 @@ flowchart TD | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | +| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | | [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node) | `ptc-runtime` | [`fs`](../packages/fs/fs), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`session-title-llm`](../packages/session/session-title-llm) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`timeout`](../packages/util/timeout) | | [`bash-sandbox`](../packages/shell/bash-sandbox) | `shell` | [`bash-local`](../packages/shell/bash-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell) | @@ -1847,7 +1847,6 @@ flowchart TD | [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) | | [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/interaction/tool-ask-user) | `interaction` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | -| [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`tool-jobs`](../packages/jobs/tool-jobs) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-lsp`](../packages/lsp/tool-lsp) | `lsp` | [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`mcp-resources`](../packages/mcp/mcp-resources) | `mcp` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/packages/jobs/jobs-local/README.i18n.yaml b/packages/jobs/jobs-local/README.i18n.yaml index 93045928da..746d8cbf72 100644 --- a/packages/jobs/jobs-local/README.i18n.yaml +++ b/packages/jobs/jobs-local/README.i18n.yaml @@ -33,8 +33,8 @@ en: ae926795d8aaa88f zh: 0e6ec0265eefccf7 /deepseek-ai-dsh-jobs-local/use-this-package/what-can-go-wrong: - en: 3737bc2cfa7f7012 - zh: 07bc090cbfa44584 + en: 5600eb21a76970ee + zh: 66bf8fab3f380115 /deepseek-ai-dsh-jobs-local/understand-the-implementation: en: f782557ca8da3138 zh: e8f0082b9692cacc diff --git a/packages/jobs/jobs-local/README.md b/packages/jobs/jobs-local/README.md index 1f753e7f93..7f7b5b1401 100644 --- a/packages/jobs/jobs-local/README.md +++ b/packages/jobs/jobs-local/README.md @@ -64,7 +64,7 @@ Lifecycle facts are appended synchronously at the registration or settlement com ### What can go wrong -Starting work fails without a controller that serves the owner — loading `dsh-tool-jobs` attaches one, and `start()` otherwise refuses with a message naming it. Refusals are `JobError` instances: `JOB_CONTROLLER_UNAVAILABLE`, `JOB_LIMIT_REACHED`, `JOB_OWNER_NOT_LIVE`, `JOB_NOT_FOUND`, and `JOB_FOREIGN_SESSION`; an owned registration without the agent registry throws `ToolContextUnavailableError`. A wait whose signal aborts rejects with an error named `AbortError`. A producer cancel that returns without settling `done` stays indistinguishable from a slow stop and can stall teardown while holding one capacity slot. Live registry records disappear when the harness process exits; persisted lifecycle events remain. +Starting work fails without a controller that serves the owner — loading `dsh-tool-jobs` attaches one, and `start()` otherwise refuses with a message naming it. Refusals are `JobError` instances: `JOB_CONTROLLER_UNAVAILABLE`, `JOB_LIMIT_REACHED`, `JOB_OWNER_NOT_LIVE`, `JOB_NOT_FOUND`, and `JOB_FOREIGN_SESSION`; an owned registration without the agent registry throws `JOB_OWNER_REGISTRY_UNAVAILABLE`. A wait whose signal aborts rejects with an error named `AbortError`. A producer cancel that returns without settling `done` stays indistinguishable from a slow stop and can stall teardown while holding one capacity slot. Live registry records disappear when the harness process exits; persisted lifecycle events remain. ----- diff --git a/packages/jobs/jobs-local/README.zh.md b/packages/jobs/jobs-local/README.zh.md index 30dc26d3b0..ee2ff3c879 100644 --- a/packages/jobs/jobs-local/README.zh.md +++ b/packages/jobs/jobs-local/README.zh.md @@ -64,7 +64,7 @@ kind: "package-reference" ### 可能出什么问题 -没有服务于所有者的控制器时无法启动工作——加载 `dsh-tool-jobs` 即附加一个,否则 `start()` 会以指出它的消息拒绝。拒绝均为 `JobError`:`JOB_CONTROLLER_UNAVAILABLE`、`JOB_LIMIT_REACHED`、`JOB_OWNER_NOT_LIVE`、`JOB_NOT_FOUND` 与 `JOB_FOREIGN_SESSION`;没有 agent 注册表时登记带所有者的 job 会抛出 `ToolContextUnavailableError`。signal 中止的等待以名为 `AbortError` 的错误拒绝。返回但始终未结算 `done` 的生产方取消与缓慢停止无法区分,可能使销毁停滞并持续占用一个容量名额。运行期注册表记录会在 harness 进程退出时消失;已持久化的生命周期事件会保留。 +没有服务于所有者的控制器时无法启动工作——加载 `dsh-tool-jobs` 即附加一个,否则 `start()` 会以指出它的消息拒绝。拒绝均为 `JobError`:`JOB_CONTROLLER_UNAVAILABLE`、`JOB_LIMIT_REACHED`、`JOB_OWNER_NOT_LIVE`、`JOB_NOT_FOUND` 与 `JOB_FOREIGN_SESSION`;没有 agent 注册表时登记带所有者的 job 会以 `JOB_OWNER_REGISTRY_UNAVAILABLE` 失败。signal 中止的等待以名为 `AbortError` 的错误拒绝。返回但始终未结算 `done` 的生产方取消与缓慢停止无法区分,可能使销毁停滞并持续占用一个容量名额。运行期注册表记录会在 harness 进程退出时消失;已持久化的生命周期事件会保留。 ----- diff --git a/packages/jobs/jobs-local/package.json b/packages/jobs/jobs-local/package.json index b7e73d4753..b635f6289d 100644 --- a/packages/jobs/jobs-local/package.json +++ b/packages/jobs/jobs-local/package.json @@ -36,8 +36,7 @@ "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/cordis": "workspace:~" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" @@ -52,7 +51,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-jobs": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-tools": "workspace:*" + "@deepseek-ai/cordis": "workspace:~" } } diff --git a/packages/jobs/jobs-local/src/index.ts b/packages/jobs/jobs-local/src/index.ts index 4e1a0959f6..378aaf0c08 100644 --- a/packages/jobs/jobs-local/src/index.ts +++ b/packages/jobs/jobs-local/src/index.ts @@ -18,7 +18,6 @@ import { ScopedLayers, scopeOf } from '@deepseek-ai/dsh-scope' import type { SessionId } from '@deepseek-ai/dsh-session' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' import { JobError, JobRegistry, JobId } from '@deepseek-ai/dsh-jobs' -import { ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { JobAppendOptions, JobEvent, JobEvents, JobHandle, JobKind, JobOutcome, JobOutputRead, JobOutputSource, JobRead, JobRegisteredData, JobSettleCause, JobSettledData, JobSpec, JobStatus, JobToolCall, JobView, @@ -374,7 +373,7 @@ export class LocalJobRegistry extends JobRegistry { if (session === undefined) return undefined const agents = this.selfCtx.get('agents') if (agents === undefined) { - throw new ToolContextUnavailableError('background job ownership requires the agent registry (load @deepseek-ai/dsh-agent)') + throw new JobError('background job ownership requires the agent registry (load @deepseek-ai/dsh-agent)', 'JOB_OWNER_REGISTRY_UNAVAILABLE') } const owner = agents.get(session) if (owner === undefined) { diff --git a/packages/jobs/jobs-local/tests/jobs.spec.ts b/packages/jobs/jobs-local/tests/jobs.spec.ts index 521c7647d6..f3d47532f2 100644 --- a/packages/jobs/jobs-local/tests/jobs.spec.ts +++ b/packages/jobs/jobs-local/tests/jobs.spec.ts @@ -768,7 +768,7 @@ describe('LocalJobRegistry owner isolation', () => { expect(() => ctx.jobs.start({ ...producer().spec, owner: SessionId('a') })) .toThrow('background job ownership requires the agent registry') expect(() => ctx.jobs.start({ ...producer().spec, owner: SessionId('a') })) - .toThrow(expect.objectContaining({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })) + .toThrow(expect.objectContaining(jobError('JOB_OWNER_REGISTRY_UNAVAILABLE'))) // The failed registration mutated nothing: no stored job. expect(ctx.jobs.list()).toEqual([]) expect(ctx.jobs.start(producer().spec)).toMatch(/^bash-[0-9a-f]{16}$/) diff --git a/packages/jobs/jobs-local/tsconfig.json b/packages/jobs/jobs-local/tsconfig.json index 892c4da43e..f94627dd8f 100644 --- a/packages/jobs/jobs-local/tsconfig.json +++ b/packages/jobs/jobs-local/tsconfig.json @@ -28,9 +28,6 @@ }, { "path": "../jobs" - }, - { - "path": "../../core/tools" } ] } diff --git a/packages/jobs/jobs/src/error.ts b/packages/jobs/jobs/src/error.ts index e0f0af64d9..28c2984382 100644 --- a/packages/jobs/jobs/src/error.ts +++ b/packages/jobs/jobs/src/error.ts @@ -10,6 +10,7 @@ import { HarnessError } from '@deepseek-ai/dsh-error' * - `JOB_NOT_FOUND` — the job id names no listed job. * - `JOB_FOREIGN_SESSION` — the job belongs to another Session. * - `JOB_OWNER_NOT_LIVE` — the owning Agent is no longer live. + * - `JOB_OWNER_REGISTRY_UNAVAILABLE` — a job names an owner, but the composition has no Agent registry to resolve it. * - `JOB_LIMIT_REACHED` — the registry's configured job limit is reached. */ export const JOB_ERROR_CODES = [ @@ -18,6 +19,7 @@ export const JOB_ERROR_CODES = [ 'JOB_NOT_FOUND', 'JOB_FOREIGN_SESSION', 'JOB_OWNER_NOT_LIVE', + 'JOB_OWNER_REGISTRY_UNAVAILABLE', 'JOB_LIMIT_REACHED', ] as const diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 341f928b4c..59409205d1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13140,9 +13140,6 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:* version: link:../../util/timeout - '@deepseek-ai/dsh-tools': - specifier: workspace:* - version: link:../../core/tools packages/jobs/tool-jobs: dependencies: From 02c62579875ebc878cec487467074b78126e7949 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:43:12 +0800 Subject: [PATCH 069/438] fix(shell-env): keep the dsh-llm devDependency its tests import Moving ShellEnvError onto dsh-error replaced the existing dsh-llm devDependency, but the shell-env tests still import ToolCallId from dsh-llm. Both are now declared. Refs #7869 --- packages/shell/shell-env/package.json | 1 + pnpm-lock.yaml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/packages/shell/shell-env/package.json b/packages/shell/shell-env/package.json index 3393956475..cb1beb7098 100644 --- a/packages/shell/shell-env/package.json +++ b/packages/shell/shell-env/package.json @@ -48,6 +48,7 @@ "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", "@deepseek-ai/dsh-error": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-shell": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59409205d1..26fc83966c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15528,6 +15528,9 @@ importers: '@deepseek-ai/dsh-home-paths': specifier: workspace:* version: link:../../util/home-paths + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm '@deepseek-ai/dsh-shell': specifier: workspace:* version: link:../shell From 25b2fd24c0d32578a36e3149c7b389d1d2e6a375 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:43:13 +0800 Subject: [PATCH 070/438] docs(sandbox-policy): state that a relative session cwd also fails The workspaceRoot row named only a NUL byte, while the session cwd check rejects relative paths too, as the resolve() JSDoc states. Refs #7869 --- packages/sandbox/sandbox-policy/README.i18n.yaml | 4 ++-- packages/sandbox/sandbox-policy/README.md | 2 +- packages/sandbox/sandbox-policy/README.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/sandbox/sandbox-policy/README.i18n.yaml b/packages/sandbox/sandbox-policy/README.i18n.yaml index 9bef469d7d..1d00a1307f 100644 --- a/packages/sandbox/sandbox-policy/README.i18n.yaml +++ b/packages/sandbox/sandbox-policy/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6704447e52ec295b zh: 9ed812d9e29d5533 /deepseek-ai-dsh-sandbox-policy/use-this-package/minimal-configuration: - en: 0b62eae224181946 - zh: 2e77e7f49bd074d4 + en: 4425f5a22850d740 + zh: 7dfd299ade0fc561 /deepseek-ai-dsh-sandbox-policy/use-this-package/registering-a-session-s-writable-directory: en: 841ea47ef1ed7ee6 zh: cd573e67a67742e2 diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index 0d26190122..96db8d41e9 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -45,7 +45,7 @@ Load the package with a default mode; the fail-safe default is `read-only`, and | Field | Default | Meaning | |---|---|---| | `mode` | `read-only` | The deployment default mode a session starts from, validated at load | -| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a cwd; relative values fail at load. Normal agent calls use the session's immutable cwd; a cwd containing a NUL byte fails the call with `SANDBOX_INVALID_ROOT` | +| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a cwd; relative values fail at load. Normal agent calls use the session's immutable cwd; a relative cwd or one containing a NUL byte fails the call with `SANDBOX_INVALID_ROOT` | | `additionalWritableRoots` | `[]` | Physical absolute directories also writable under `workspace-write`; Windows file tools honor them, Windows subprocesses ignore them, and `read-only` grants no access | For a linked Git worktree, the caller can grant its shared Git directory with `additionalWritableRoots`. The caller selects that directory explicitly; the policy does not inspect Git files or grant a parent checkout. These grants are deployment configuration shared by the composition's sessions, rather than saved Session permissions. Granting the entire Git directory also permits changes to hooks and configuration that a later host Git invocation can execute outside the sandbox; use that grant only for trusted tasks. Use physical absolute directory paths. The enforcing host rejects missing paths, non-directories, and symlinked directories on each call, including a directory replaced by a symlink between calls. Remote grants are validated on the remote host. diff --git a/packages/sandbox/sandbox-policy/README.zh.md b/packages/sandbox/sandbox-policy/README.zh.md index a436f298d5..372ed91b4f 100644 --- a/packages/sandbox/sandbox-policy/README.zh.md +++ b/packages/sandbox/sandbox-policy/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" | 字段 | 默认值 | 含义 | |---|---|---| | `mode` | `read-only` | 会话起始的部署默认模式,加载时验证 | -| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有 cwd 的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的不可变 cwd;cwd 含 NUL 字节时调用以 `SANDBOX_INVALID_ROOT` 失败 | +| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有 cwd 的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的不可变 cwd;cwd 为相对路径或含 NUL 字节时调用以 `SANDBOX_INVALID_ROOT` 失败 | | `additionalWritableRoots` | `[]` | 在 `workspace-write` 下额外允许写入的物理绝对目录;Windows 文件工具执行这些授权,Windows 子进程忽略它们,`read-only` 不授予访问权限 | 对于关联的 Git worktree,调用方可通过 `additionalWritableRoots` 授予共享 Git 目录的写权限。调用方必须显式选择该目录;策略不会读取 Git 文件或授权父检出目录。这些授权是组合中所有会话共享的部署配置,而非保存的 Session 权限。授权整个 Git 目录也允许修改钩子和配置,后续主机 Git 调用可能在沙箱之外执行它们;仅对可信任务使用此授权。使用物理绝对目录路径。执行限制的主机在每次调用时拒绝不存在的路径、非目录和符号链接目录,包括两次调用之间被替换为符号链接的目录。远端授权在远端主机上验证。 From d67e146e73e98a564f5f26e880cad1d140fa4eb3 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 17:43:31 +0800 Subject: [PATCH 071/438] fix(goal): report saved objectives when attachment admission closes --- docs/event-producer-consumer.md | 22 ++--- docs/event-producer-consumer.zh.md | 22 ++--- docs/subsystems/core.md | 7 ++ docs/subsystems/core.zh.md | 7 ++ packages/core/agent-loop/src/agent.ts | 2 +- packages/core/agent/src/runtime-types.ts | 7 ++ packages/goal/command-goal/README.i18n.yaml | 4 +- packages/goal/command-goal/README.md | 2 +- packages/goal/command-goal/README.zh.md | 2 +- packages/goal/command-goal/package.json | 1 + packages/goal/command-goal/src/index.ts | 39 +++++---- .../command-goal/tests/command-goal.spec.ts | 87 +++++++++++++++++-- 12 files changed, 152 insertions(+), 50 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 5247fc4477..e60d35766c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:302`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:340`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:348`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:362`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f8c8c77e5a..83ff9eb7d4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,17 +14,17 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:302`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:340`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:348`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:362`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 7e86e6e0d1..0e718fe573 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -74,6 +74,13 @@ interface Agent { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index c82be05f03..c624316f57 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -78,6 +78,13 @@ interface Agent { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 95c27e6c92..56cb982c75 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -265,7 +265,7 @@ export class ReactLoopAgent implements Agent { } while (activity !== this.activityDone) } - private assertOpen(): void { + assertOpen(): void { if (this.lifetimeSignal.aborted) { throw new AgentClosedError(this.id, { cause: this.lifetimeSignal.reason }) } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 39b15064dc..98f0d3ebe7 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -202,6 +202,13 @@ declare module './types.ts' { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/packages/goal/command-goal/README.i18n.yaml b/packages/goal/command-goal/README.i18n.yaml index 9efbb3b229..a057275fbe 100644 --- a/packages/goal/command-goal/README.i18n.yaml +++ b/packages/goal/command-goal/README.i18n.yaml @@ -24,8 +24,8 @@ en: 38a273cb14017e13 zh: d4b7b501bcd9589b /deepseek-ai-dsh-command-goal/use-this-package/attachments: - en: e61cd7437ed4aa73 - zh: 552c36c3b8d16007 + en: 60281bad395286ac + zh: c1a6e51161717616 /deepseek-ai-dsh-command-goal/use-this-package/compose-it: en: ba5792bd8714f1c3 zh: c9e5500c0a3b7651 diff --git a/packages/goal/command-goal/README.md b/packages/goal/command-goal/README.md index a627a15e82..96aa3c7b9a 100644 --- a/packages/goal/command-goal/README.md +++ b/packages/goal/command-goal/README.md @@ -46,7 +46,7 @@ Control words (`clear`, `pause`, `resume`, `edit`) are recognized only when they ### Attachments -`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. +`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. If the Agent starts closing before the command writes the objective, the command rejects with `AGENT_CLOSED`. If attachment submission is rejected after the objective is saved, the command reports the saved objective and leaves the attachments in the composer. ### Compose it diff --git a/packages/goal/command-goal/README.zh.md b/packages/goal/command-goal/README.zh.md index 9e4bac63d9..e8d0b08b85 100644 --- a/packages/goal/command-goal/README.zh.md +++ b/packages/goal/command-goal/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" ### 附件 -`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 +`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 如果 Agent 在命令写入目标前开始关闭,命令会以 `AGENT_CLOSED` 拒绝请求。如果目标已保存,但随后提交附件时遭到拒绝,命令会提示目标已保存,并将附件保留在输入区。 ### 组合方式 diff --git a/packages/goal/command-goal/package.json b/packages/goal/command-goal/package.json index f51a794228..881b44177e 100644 --- a/packages/goal/command-goal/package.json +++ b/packages/goal/command-goal/package.json @@ -32,6 +32,7 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", "@deepseek-ai/dsh-goal": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/goal/command-goal/src/index.ts b/packages/goal/command-goal/src/index.ts index 9238d76632..cd84cbddf5 100644 --- a/packages/goal/command-goal/src/index.ts +++ b/packages/goal/command-goal/src/index.ts @@ -4,6 +4,7 @@ */ import type { Context } from '@deepseek-ai/cordis' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import { CommandDefinitionId } from '@deepseek-ai/dsh-commands/brand' import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands' import { GoalError } from '@deepseek-ai/dsh-goal' @@ -109,17 +110,25 @@ function missingGoal(action: string): CommandResult { } /** - * Submit the invocation's admitted composer attachments as one model-visible user - * message ahead of the goal's next round. The attachments precede a fixed text - * block naming their role, so a later goal round reads them from ordinary - * session history without the goal domain storing attachment state. + * Report the committed objective and submit its attachments ahead of the next goal round. + * A closed Agent leaves the objective saved and the attachments in the composer. */ -function submitObjectiveAttachments(invocation: CommandInvocation): void { - if (invocation.attachments.length === 0) return - invocation.agent.followup(createUserMessage({ - content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], - source: { kind: 'user' }, - })) +function finishObjective(invocation: CommandInvocation, title: string, goal: GoalView): CommandResult { + if (invocation.attachments.length > 0) { + try { + invocation.agent.followup(createUserMessage({ + content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], + source: { kind: 'user' }, + })) + } catch (error: unknown) { + if (!(error instanceof AgentClosedError)) throw error + return { + kind: 'error', + text: 'Goal saved. The agent is closing, so the attachments were not submitted.', + } + } + } + return renderGoal(title, goal) } /** Execute one parsed human command through the domain that owns persistence. */ @@ -131,6 +140,7 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman text: 'Attachments only accompany a goal objective: /goal or /goal edit .', } } + if (command.kind === 'create' || command.kind === 'edit') invocation.agent.assertOpen?.() try { const current = ctx.goals.get(invocation.agent) switch (command.kind) { @@ -148,19 +158,16 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman } } const created = ctx.goals.create(invocation.agent, { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal created', created) + return finishObjective(invocation, 'Goal created', created) } case 'edit': { if (current === undefined) return missingGoal('edit') if (current.phase === 'complete') { const replaced = ctx.goals.create(invocation.agent, { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal created', replaced) + return finishObjective(invocation, 'Goal created', replaced) } const edited = ctx.goals.edit(invocation.agent, goalRef(current), { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal updated', edited) + return finishObjective(invocation, 'Goal updated', edited) } case 'pause': if (current === undefined) return missingGoal('pause') diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 6cb4cf83c9..e69b3fe89d 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { AgentClosedError } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' @@ -15,14 +15,19 @@ interface Harness { readonly ctx: Context readonly agent: Agent readonly session: Session + readonly closing: AbortController readonly plugin: Awaited> } /** Build a live idle agent accepted by the exact-identity goal service. */ -function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { +function stubAgent(ctx: Context, id: string): Pick { // Store-created: the command executor durably logs lifecycle events on it. const session = ctx.sessions.create(SessionId(id)) const inbox = createInboxStub() + const closing = new AbortController() + const assertOpen = (): void => { + if (closing.signal.aborted) throw new AgentClosedError(session.id) + } let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, @@ -33,14 +38,18 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } ctx: new Context(), get status() { return status }, send: () => {}, - followup: () => {}, + assertOpen, + followup(input) { + assertOpen() + inbox.append('next-turn', input) + }, steer: () => {}, inject(input) { this.inbox.append('next-step', input) }, cancel() { status = 'idle' }, runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - return { agent, session } + return { agent, session, closing } } /** Mount the real command registry, goal domain, and producer. */ @@ -52,9 +61,9 @@ async function harness(): Promise { await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) const plugin = await ctx.plugin(commandGoal) - const { agent, session } = stubAgent(ctx, `command-goal-${Math.random()}`) + const { agent, session, closing } = stubAgent(ctx, `command-goal-${Math.random()}`) await ctx.agents.register(agent) - return { ctx, agent, session, plugin } + return { ctx, agent, session, closing, plugin } } /** The log with executor-owned command lifecycle bookkeeping stripped (goal assertions target domain events). */ @@ -243,7 +252,7 @@ describe('/goal attachments', () => { const PNG = 'AAAA' /** Wire the fake store the executor admits through (once per harness). */ - function provideStore(test: Harness): void { + function provideStore(test: Harness, beforeSave?: () => Promise): void { let saved = 0 const saveImage = (input: { mediaType: string; name?: string }) => { saved += 1 @@ -260,6 +269,7 @@ describe('/goal attachments', () => { validateImage: () => Promise.resolve(), saveImage, async saveImages(inputs: readonly { mediaType: string; name?: string }[]) { + if (beforeSave !== undefined) await beforeSave() const refs = [] for (const input of inputs) refs.push(await saveImage(input)) return refs @@ -317,6 +327,69 @@ describe('/goal attachments', () => { expect(followup).toHaveBeenCalledTimes(1) }) + it.each(['create', 'edit'] as const)('rejects %s when closure begins during attachment storage', async (operation) => { + const test = await harness() + const saving = Promise.withResolvers() + const release = Promise.withResolvers() + provideStore(test, () => { + saving.resolve(undefined) + return release.promise + }) + const original = operation === 'edit' + ? test.ctx.goals.create(test.agent, { objective: 'original objective' }) + : undefined + const suffix = operation === 'edit' ? ' edit use the reference image' : ' use the reference image' + const result = runWithAttachments(test, suffix) + try { + await saving.promise + test.closing.abort() + release.resolve(undefined) + await expect(result).rejects.toMatchObject({ code: 'AGENT_CLOSED' }) + expect(test.ctx.goals.get(test.agent)).toEqual(original) + expect(test.agent.inbox.nextTurn).toEqual([]) + } finally { + release.resolve(undefined) + await result.catch(() => undefined) + await test.ctx.fiber.dispose() + } + }) + + it('reports the saved objective when closure interrupts attachment delivery after commit', async () => { + const test = await harness() + provideStore(test) + const stop = test.ctx.on('goal/changed', ({ change }) => { + if (change.operation === 'create') test.closing.abort() + }) + try { + const result = await runWithAttachments(test, ' use the reference image') + expect(result).toEqual({ + kind: 'error', + text: 'Goal saved. The agent is closing, so the attachments were not submitted.', + }) + expect(test.ctx.goals.get(test.agent)?.objective).toBe('use the reference image') + expect(test.session.snapshotEvents().at(-1)).toMatchObject({ + type: 'command/done', + data: result, + }) + expect(test.agent.inbox.nextTurn).toEqual([]) + } finally { + stop() + await test.ctx.fiber.dispose() + } + }) + + it('propagates unrelated attachment delivery failures', async () => { + const test = await harness() + provideStore(test) + const failure = new Error('inbox write failed') + vi.spyOn(test.agent, 'followup').mockImplementation(() => { throw failure }) + try { + await expect(runWithAttachments(test, ' use the reference image')).rejects.toBe(failure) + } finally { + await test.ctx.fiber.dispose() + } + }) + it('rejects attachments on sub-commands that cannot use them, leaving the domain untouched', async () => { const test = await harness() provideStore(test) From eed89dea5b8e0e1d2dcec7e8684865d0fe50a71c Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 17:49:06 +0800 Subject: [PATCH 072/438] docs(goal): record the command agent dependency --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..41eca08cbd 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -761,6 +761,7 @@ flowchart TD pkg_tools --> pkg_session pkg_tools --> pkg_system_prompt pkg_tools --> pkg_user_approval + pkg_command_goal --> pkg_agent pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm @@ -1786,7 +1787,7 @@ flowchart TD | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..edfeb63f2d 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -763,6 +763,7 @@ flowchart TD pkg_tools --> pkg_session pkg_tools --> pkg_system_prompt pkg_tools --> pkg_user_approval + pkg_command_goal --> pkg_agent pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm @@ -1788,7 +1789,7 @@ flowchart TD | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | From 38b59a84bc3d5c3b38c2d8ebeba039b836755161 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:50:54 +0800 Subject: [PATCH 073/438] feat(forge): read pull request commits and commit ranges ForgeProvider gains optional commits and compare methods, which a provider implements together. The forge service returns undefined from commits and an unavailable failure from compare when either is missing. The GitHub provider lists commits through GraphQL pages pinned to one head, bounded by the new maxCommits setting, and reads ranges through the compare API in diff form. --- .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 4 +- .../experimental/forge-github/README.zh.md | 4 +- .../experimental/forge-github/src/commits.ts | 100 ++++++++++++++++++ .../experimental/forge-github/src/index.ts | 9 +- .../experimental/forge-github/src/provider.ts | 45 +++++++- .../forge-github/tests/plugin.spec.ts | 2 + .../forge-github/tests/provider.spec.ts | 76 ++++++++++++- .../forge-github/tests/review.spec.ts | 4 +- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 + packages/experimental/forge/README.zh.md | 2 + packages/experimental/forge/src/index.ts | 32 +++++- packages/experimental/forge/src/types.ts | 34 ++++++ .../forge/tests/lifecycle.spec.ts | 6 +- .../experimental/forge/tests/registry.spec.ts | 21 ++++ 16 files changed, 327 insertions(+), 22 deletions(-) create mode 100644 packages/experimental/forge-github/src/commits.ts diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index b096b71898..fec538644d 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: f2bd06d91b744305 - zh: ad956b539a43b880 + en: 282129be7093ee26 + zh: ff1eeeb907a46245 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 90f3c10096be642a zh: 4e1b663c52019ac2 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 2d9e2ce57a..f392b899a0 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -34,7 +34,7 @@ Mount the provider after the forge registry and list every GitHub Enterprise hos hosts: [github.com, ghe.example.com] ``` -The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` must be a positive safe integer; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, and `maxOutputBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). +The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` and `maxCommits` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, and `maxCommits` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `git@github.com:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://///pull/` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname `: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none. @@ -44,7 +44,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos///compare/...` with the diff media type, accepting only full commits, and fails like `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 1ac57ffa7d..da6995e916 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -34,7 +34,7 @@ kind: "package-reference" hosts: [github.com, ghe.example.com] ``` -即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs` 与 `maxOutputBytes` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 +即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 与 `maxCommits` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes` 与 `maxCommits` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 @@ -44,7 +44,7 @@ kind: "package-reference" pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型读取 `repos///compare/...`,只接受完整提交,失败时与 `diff` 相同。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 diff --git a/packages/experimental/forge-github/src/commits.ts b/packages/experimental/forge-github/src/commits.ts new file mode 100644 index 0000000000..24a0d830b0 --- /dev/null +++ b/packages/experimental/forge-github/src/commits.ts @@ -0,0 +1,100 @@ +/** GitHub pull request commit listing through GraphQL, pinned to one head commit across pages. */ + +import type { ChangeRequestRef, ForgeCommit, ForgeCommitList, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import { checkedRepository } from './urls.ts' + +/** Commits GitHub returns per GraphQL page, its connection maximum. */ +const PAGE = 100 + +/** One page of a pull request's commits with its head; `cursor` continues after the previous page. */ +export const COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + headRefOid + commits(first: $first, after: $cursor) { + totalCount + pageInfo { hasNextPage endCursor } + nodes { commit { oid messageHeadline authoredDate author { name user { login } } parents(first: 1) { nodes { oid } } } } + } + } + } +}` + +const pageSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ + headRefOid: z.string(), + commits: z.object({ + totalCount: z.number().int().nonnegative(), + pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), + nodes: z.array(z.object({ + commit: z.object({ + oid: z.string(), + messageHeadline: z.string(), + authoredDate: z.string(), + author: z.object({ name: z.string().nullable(), user: z.object({ login: z.string() }).nullable() }).nullable(), + parents: z.object({ nodes: z.array(z.object({ oid: z.string() })) }), + }), + })), + }), + }).nullable(), + }).nullable(), + }), +}) + +/** Runs one `gh` GraphQL request; resolves to its parsed JSON body, or why GitHub did not answer it. */ +export type GraphqlReader = (args: readonly string[], signal: AbortSignal) => Promise< + { readonly ok: true; readonly body: unknown } | { readonly ok: false; readonly failure: ForgeFailure }> + +/** + * List a pull request's commits oldest first, at most `limit`, reading pages until the limit or the last commit. + * Every page must report the head of the first page, so the list never mixes two pushes. + * @param read - runs one GraphQL request. + * @param ref - validated pull request address. + * @param limit - most commits listed. + * @param signal - cancellation of every page. + * @returns the commits at one head, or why GitHub did not list them. + */ +export async function listCommits( + read: GraphqlReader, + ref: ChangeRequestRef, + limit: number, + signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const commits: ForgeCommit[] = [] + let head: string | undefined + let cursor: string | null = null + for (;;) { + const body = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE, limit - commits.length)}`, + ...cursor === null ? [] : ['-f', `cursor=${cursor}`], + ], signal) + if (!body.ok) return body.failure + const parsed = pageSchema.safeParse(body.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the commit listing' } + const pull = parsed.data.data.repository?.pullRequest + if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` } + if (head !== undefined && pull.headRefOid !== head) { + return { code: 'unavailable', message: 'The pull request head changed while its commits were read' } + } + head = pull.headRefOid + for (const { commit } of pull.commits.nodes) { + commits.push({ + sha: commit.oid, + parent: commit.parents.nodes[0]?.oid ?? null, + title: commit.messageHeadline, + author: commit.author?.user?.login ?? commit.author?.name ?? null, + authoredAt: commit.authoredDate, + }) + } + const { hasNextPage, endCursor } = pull.commits.pageInfo + if (!hasNextPage || endCursor === null || commits.length >= limit) { + return { headSha: head, commits, truncated: pull.commits.totalCount > commits.length } + } + cursor = endCursor + } +} diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index a0bc66126a..16481d8c81 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -20,6 +20,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } export const Config: z = z.object({ @@ -27,6 +29,7 @@ export const Config: z = z.object({ hosts: z.array(z.string()).default(['github.com']), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), + maxCommits: z.number().default(250), }) const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i @@ -41,8 +44,8 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } - if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) { - throw new Error('forge-github: maxOutputBytes must be a positive safe integer') + for (const key of ['maxOutputBytes', 'maxCommits'] as const) { + if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } - ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes)) + ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes, resolved.maxCommits)) } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index ca56473956..c73a174f72 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -2,9 +2,11 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, - ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, + ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' +import { listCommits } from './commits.ts' +import type { GraphqlReader } from './commits.ts' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts' import type { GhOutput, GhRunner } from './gh.ts' import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery } from './graphql.ts' @@ -40,8 +42,14 @@ export class GitHubProvider implements ForgeProvider { * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. * @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read. + * @param maxCommits - most commits one commit listing returns. */ - constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly maxOutputBytes: number) { + constructor( + private readonly gh: GhRunner, + hosts: readonly string[], + private readonly maxOutputBytes: number, + private readonly maxCommits: number, + ) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) } @@ -160,6 +168,26 @@ export class GitHubProvider implements ForgeProvider { ], signal) } + /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */ + async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return failure + return await listCommits(this.graphql, ref, this.maxCommits, signal) + } + + /** Read the changes between two commits through the compare API in its diff form. */ + async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + const { host, owner, name } = checkedRepository(ref) + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + for (const commit of [base, head]) { + if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + } + return await this.read([ + 'api', '--hostname', host, '-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`, + ], signal) + } + fileUrl(ref: ChangeRequestRef, commit: string, path: string): string { const { host, owner, name } = ref.repository return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}` @@ -199,6 +227,17 @@ export class GitHubProvider implements ForgeProvider { return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message } } + /** Run one GraphQL request; a refusal, a body that is not GraphQL, and GraphQL errors become failures. */ + private readonly graphql: GraphqlReader = async (args, signal) => { + const output = await this.read(args, signal) + if (typeof output !== 'string') return { ok: false, failure: output } + const body = parseJson(output) + if (!hasGraphqlFields(body)) return { ok: false, failure: { code: 'unavailable', message: 'unexpected GitHub response' } } + const errors = typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors) ? body.errors : [] + if (errors.length > 0) return { ok: false, failure: responseFailure({ exitCode: 0, stdout: output, stderr: '' }, errors[0]) } + return { ok: true, body } + } + /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */ private async act(args: readonly string[], signal: AbortSignal): Promise { const output = await this.attempt(args, signal) diff --git a/packages/experimental/forge-github/tests/plugin.spec.ts b/packages/experimental/forge-github/tests/plugin.spec.ts index a214182694..2701a2720e 100644 --- a/packages/experimental/forge-github/tests/plugin.spec.ts +++ b/packages/experimental/forge-github/tests/plugin.spec.ts @@ -56,6 +56,8 @@ describe('forge-github plugin', () => { [{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'], + [{ maxCommits: 0 }, 'forge-github: maxCommits must be a positive safe integer'], + [{ maxCommits: 2.5 }, 'forge-github: maxCommits must be a positive safe integer'], ])('rejects %j at load', async (config, message) => { const context = await forge() diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index ce513e0ab8..2433e580f7 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -24,7 +24,7 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { } function provider(run: GhRunner): GitHubProvider { - return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608) + return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608, 250) } describe('GitHub provider addressing', () => { @@ -46,7 +46,7 @@ describe('GitHub provider addressing', () => { it('uses a configured HTTP port for URL mapping and GitHub queries', async () => { const gh = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1) } } })) - const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608) + const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608, 250) const repository = subject.repositoryFromRemote('https://ghe.example.com:8443/team/repo.git')! const ref = { repository, number: 1 } expect(subject.changeRequestFromUrl(subject.changeRequestUrl(ref))).toEqual(ref) @@ -92,7 +92,7 @@ describe('GitHub provider fetch', () => { const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(last.stdout) for (const limit of [total, total - 1, Buffer.byteLength(first.stdout) - 1]) { const gh = fakeGh(args => args.includes('id=fixed-rollup') ? last : first) - const result = await new GitHubProvider(gh.run, ['github.com'], limit).fetchChecks(pull(1), signal) + const result = await new GitHubProvider(gh.run, ['github.com'], limit, 250).fetchChecks(pull(1), signal) if (limit === total) expect(result).toMatchObject({ checksTruncated: false }) else expect(result).toMatchObject({ code: 'too-large' }) expect(gh.calls).toHaveLength(limit < Buffer.byteLength(first.stdout) ? 1 : 2) @@ -192,7 +192,7 @@ describe('GitHub provider fetch', () => { it('rejects references retained after their host was removed from configuration', async () => { const gh = fakeGh(() => output('')) const retained = provider(gh.run).changeRequestFromUrl('https://ghe.corp.example/team/svc/pull/2')! - const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608) + const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608, 250) const results = await replacement.fetch([retained], signal) await expect(replacement.findByHead(retained.repository, 'topic', signal)).rejects.toThrow('is not configured') expect(results.get(changeRequestKey(retained))).toMatchObject({ code: 'unavailable' }) @@ -419,6 +419,72 @@ describe('GitHub provider reads', () => { }) }) +describe('GitHub provider commits', () => { + const sha = (n: number): string => String(n).repeat(40).slice(0, 40) + const node = (n: number, author: unknown = { name: 'Octo Cat', user: { login: 'octo' } }) => ({ commit: { + oid: sha(n), messageHeadline: `commit ${n}`, authoredDate: `2026-10-0${n}T00:00:00Z`, author, + parents: { nodes: n === 1 ? [] : [{ oid: sha(n - 1) }] }, + } }) + const page = (nodes: unknown[], next: string | null, head = sha(3), total = 3) => output({ data: { repository: { pullRequest: { + headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage: next !== null, endCursor: next }, nodes }, + } } } }) + + it('lists the commits oldest first across pages pinned to one head, bounded by maxCommits', async () => { + const gh = fakeGh(args => args.includes('cursor=page-1') ? page([node(3, { name: 'Ann', user: null })], null) : page([node(1), node(2, null)], 'page-1')) + + await expect(provider(gh.run).commits(pull(7), signal)).resolves.toEqual({ + headSha: sha(3), + truncated: false, + commits: [ + { sha: sha(1), parent: null, title: 'commit 1', author: 'octo', authoredAt: '2026-10-01T00:00:00Z' }, + { sha: sha(2), parent: sha(1), title: 'commit 2', author: null, authoredAt: '2026-10-02T00:00:00Z' }, + { sha: sha(3), parent: sha(2), title: 'commit 3', author: 'Ann', authoredAt: '2026-10-03T00:00:00Z' }, + ], + }) + expect(gh.calls[0]).toEqual(expect.arrayContaining(['--hostname', 'github.com', 'owner=octo', 'name=demo', 'number=7', 'first=100'])) + expect(gh.calls[0]?.some(arg => arg.startsWith('cursor='))).toBe(false) + expect(gh.calls[1]).toEqual(expect.arrayContaining(['cursor=page-1'])) + + const bounded = fakeGh(() => page([node(1), node(2)], 'page-1')) + await expect(new GitHubProvider(bounded.run, ['github.com'], 8_388_608, 2).commits(pull(7), signal)) + .resolves.toMatchObject({ truncated: true, commits: [{ sha: sha(1) }, { sha: sha(2) }] }) + expect(bounded.calls).toHaveLength(1) + expect(bounded.calls[0]).toEqual(expect.arrayContaining(['first=2'])) + }) + + it('refuses a listing whose head moves between pages, a missing pull request, and an unexpected response', async () => { + const moved = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(4)) : page([node(1)], 'page-1')) + await expect(provider(moved.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: null } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: null } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: { headRefOid: 1 } } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response to the commit listing' }) + }) + + it('reports GraphQL errors, a body that is not GraphQL, and a refused request as failures', async () => { + await expect(provider(fakeGh(() => output({ errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible' }] })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'Resource not accessible' }) + await expect(provider(fakeGh(() => output('not json')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response' }) + await expect(provider(fakeGh(() => output('', 1, 'To get started with GitHub CLI, please run: gh auth login')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }) + }) + + it('reads the changes between two commits through the compare API in its diff form', async () => { + const gh = fakeGh(() => output('diff --git a/x b/x\n')) + + await expect(provider(gh.run).compare(pull(7, enterprise), sha(1), sha(3), signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls).toEqual([[ + 'api', '--hostname', 'ghe.corp.example', '-H', 'Accept: application/vnd.github.diff', `repos/team/svc/compare/${sha(1)}...${sha(3)}`, + ]]) + await expect(provider(gh.run).compare(pull(7), 'main', sha(3), signal)).rejects.toThrow('forge-github: invalid commit "main"') + await expect(provider(gh.run).compare(pull(7), sha(1), 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"') + }) +}) + it('rejects readiness, actions, and content reads for an unconfigured host without starting gh', async () => { const gh = fakeGh(() => output('unexpected')) const subject = provider(gh.run) @@ -429,5 +495,7 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.merge(target, { method: 'squash', headSha: 'a'.repeat(40) }, signal)).resolves.toEqual({ code: 'failed', message }) await expect(subject.diff(target, signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.commits(target, signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.compare(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) expect(gh.calls).toEqual([]) }) diff --git a/packages/experimental/forge-github/tests/review.spec.ts b/packages/experimental/forge-github/tests/review.spec.ts index e128508994..7b45b6d9d8 100644 --- a/packages/experimental/forge-github/tests/review.spec.ts +++ b/packages/experimental/forge-github/tests/review.spec.ts @@ -11,7 +11,7 @@ const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment } const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' } function fixture() { const gh = vi.fn().mockResolvedValueOnce({ exitCode: 0, stdout: JSON.stringify({ head: { sha: head }, state: 'open' }), stderr: '' }).mockResolvedValue(success) - return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608), signal: new AbortController().signal } + return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608, 250), signal: new AbortController().signal } } describe('review submission', () => { @@ -91,7 +91,7 @@ describe('review submission', () => { }) it('rejects a host outside the provider configuration without invoking gh', async () => { const { gh, signal } = fixture() - expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) + expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608, 250).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) expect(gh).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index a51d57819e..164392fafd 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 9ca86ee541048ff2 - zh: 7aef4feb76542dd6 + en: e99829d47d5d3863 + zh: 64413f0ab530b37f /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 5d2bb55ec6..f2df88eb54 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -38,6 +38,8 @@ Mount the registry with at least one provider package, such as the GitHub provid `diff(ref, signal)` reads the change request's unified patch as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. +Providers may implement `commits` and `compare` together. `commits(ref, signal)` lists a change request's commits oldest first, each with its full object name, first parent, title, author, and author time, at one head commit and with a `truncated` flag; `compare(ref, base, head, signal)` reads the unified patch from commit `base` to commit `head`. The registry returns undefined from `commits` and an `unavailable` failure from `compare` when the provider lacks either method, so a consumer can offer commit views only where both exist. + `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. `ctx.forge.watch(ref, listener)` is also an effect. The first watcher of a change request polls it at once; `latest(ref)` returns the most recent result. Each forge has at most one polling fetch in flight, and that fetch includes every due change request of the forge. An open change request is polled every `activeIntervalMs` while checks are pending or mergeability is unknown, and every `idleIntervalMs` otherwise. Closed change requests use `idleIntervalMs` to detect reopening; merged requests stop automatic polling. `refresh(ref)` polls a watched change request at once, including after a terminal state; if a fetch is already in flight for its forge, another fetch starts immediately after it settles. A failed read repeats after `activeIntervalMs` doubled for each consecutive failure, up to `maxBackoffMs`, which must be at least `activeIntervalMs`. Unregistering a provider settles its watched change requests as `unavailable`. Polling stops when the last watcher leaves. The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge) lists the defaults. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 8961c8d31d..8515de0652 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -38,6 +38,8 @@ kind: "package-reference" `diff(ref, signal)` 读取托管平台计算出的变更请求统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 +提供方可以同时实现 `commits` 与 `compare`。`commits(ref, signal)` 在一个 head 提交上按从旧到新列出变更请求的提交,每个提交带完整对象名、第一个父提交、标题、作者与作者时间,并带 `truncated` 标志;`compare(ref, base, head, signal)` 读取从提交 `base` 到提交 `head` 的统一补丁。提供方缺少其中任一方法时,注册表的 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此使用方只在两者都存在时提供按提交查看。 + `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 `ctx.forge.watch(ref, listener)` 同样是 effect。变更请求的第一个监听方会立即触发轮询;`latest(ref)` 返回最近一次结果。每个 forge 同时最多只有一次轮询读取在进行,这次读取包含该 forge 所有到期的变更请求。打开状态的变更请求在检查未完成或可合并性未知时每 `activeIntervalMs` 轮询一次,否则每 `idleIntervalMs` 轮询一次。已关闭的变更请求按 `idleIntervalMs` 轮询以检测重新打开;已合并的停止自动轮询。`refresh(ref)` 立即轮询一个被监听的变更请求,已结束的也包括在内;该 forge 已有读取在进行时,等待其结束后立即再读一次。读取失败后,重试间隔为 `activeIntervalMs` 按连续失败次数翻倍,最长 `maxBackoffMs`;该值必须大于或等于 `activeIntervalMs`。注销提供方会让其被监听的变更请求以 `unavailable` 结束。最后一个监听方离开后轮询停止。默认值见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge)。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index d5204d988a..2ed58446a1 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -6,7 +6,7 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { changeRequestKey } from './keys.ts' import { nextPollDelay } from './schedule.ts' import type { - ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, + ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from './types.ts' @@ -247,6 +247,36 @@ export class ForgeService extends Service { (provider, operation) => provider.diff(ref, operation)) } + /** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve(undefined) : provider.commits(ref, operation)) + } + + /** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve({ code: 'unavailable', message: 'This provider does not read commits' } as const) + : provider.compare(ref, base, head, operation)) + } + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 35a977dcfe..1aa84c15aa 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -176,6 +176,30 @@ export interface ForgeActionFailure { readonly message: string } +/** One commit of a change request. */ +export interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} + +/** The commits of a change request at one head commit. */ +export interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} + /** Whether a provider can reach one host with the current credentials. */ export interface ForgeReadiness { /** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */ @@ -220,6 +244,16 @@ export interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } /** diff --git a/packages/experimental/forge/tests/lifecycle.spec.ts b/packages/experimental/forge/tests/lifecycle.spec.ts index 26e779eb87..42f649cefa 100644 --- a/packages/experimental/forge/tests/lifecycle.spec.ts +++ b/packages/experimental/forge/tests/lifecycle.spec.ts @@ -120,7 +120,7 @@ it('does not announce provider withdrawal after its registry has stopped', async expect(observer).toHaveBeenCalledTimes(1) }) -it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks'] as const)( +it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks', 'commits', 'compare'] as const)( 'cancels and drains %s when its provider stops', async (method) => { ctx = await forgeContext() const provider: ForgeProvider = new FakeProvider() @@ -141,6 +141,8 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', vi.spyOn(provider, 'fileText').mockImplementation(async (_ref, _commit, _path, signal) => { await hold(signal); return 'file' }) provider.submitReview = async (_ref, _request, signal) => { await hold(signal); return { ok: true, url: 'https://fake.test/review' } } provider.fetchChecks = async (target, signal) => { await hold(signal); return snapshot(target) } + provider.commits = async (_ref, signal) => { await hold(signal); return { headSha: 'a'.repeat(40), commits: [], truncated: false } } + provider.compare = async (_ref, _base, _head, signal) => { await hold(signal); return 'diff' } const fiber = await provide(ctx, provider) const service = ctx.forge const signal = new AbortController().signal @@ -152,6 +154,8 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', merge: () => service.merge(ref(1), { method: 'squash', headSha: 'a'.repeat(40) }, signal), diff: () => service.diff(ref(1), signal), fileText: () => service.fileText(ref(1), 'a'.repeat(40), 'file.txt', signal), + commits: () => service.commits(ref(1), signal), + compare: () => service.compare(ref(1), 'a'.repeat(40), 'b'.repeat(40), signal), } const rejected = expect(calls[method]()).rejects.toThrow('was unregistered') let disposed = false diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index c70a07057b..68bdf8811b 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -104,6 +104,27 @@ describe('forge registry', () => { expect(provider.actions).toEqual(['diff 3', `text 3 ${'b'.repeat(40)} src/a.ts`]) }) + it('reads commits and commit ranges only from a provider that implements both', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const list = { headSha: 'b'.repeat(40), truncated: false, commits: [] } + + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'This provider does not read commits' }) + const commits = vi.fn(async () => list) + Object.assign(provider, { commits }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + const compare = vi.fn(async () => 'diff --git a/x b/x') + Object.assign(provider, { compare }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBe(list) + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toBe('diff --git a/x b/x') + expect(commits).toHaveBeenCalledWith(ref(3), expect.any(AbortSignal)) + expect(compare).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), 'b'.repeat(40), expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() From 929e283c5e414a43585aa729471bce2799f09ff3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:51:06 +0800 Subject: [PATCH 074/438] feat(forge-panel): classify changed files into review layers and read chosen commits Each diff file now carries a review layer and a change digest. The layer follows the new testPaths and interfacePaths globs and the linguist-generated lines of the root .gitattributes, which the panel reads at the compared side and caches beside change request patches. localCommits and changeRequestCommits list commits, and a branch scope or change request diff can name consecutive commits to show instead of the whole comparison. --- .../experimental/client-ui-forge/package.json | 6 +- .../experimental/client-ui-forge/src/diff.ts | 85 ++++++--- .../experimental/client-ui-forge/src/index.ts | 165 +++++++++++++++--- .../client-ui-forge/src/layers.ts | 87 +++++++++ .../client-ui-forge/src/local-diff.ts | 108 ++++++++++-- .../client-ui-forge/src/patch-cache.ts | 30 ++-- .../experimental/client-ui-forge/src/types.ts | 53 +++++- .../tests/controller.host.spec.ts | 122 +++++++++++-- .../client-ui-forge/tests/diff.host.spec.ts | 34 +++- .../client-ui-forge/tests/harness.ts | 15 +- .../client-ui-forge/tests/layers.host.spec.ts | 65 +++++++ .../tests/local-diff-safety.host.spec.ts | 29 +-- .../tests/local-diff.host.spec.ts | 151 ++++++++++++++-- .../tests/patch-cache.host.spec.ts | 41 +++-- .../client-ui-forge/tsconfig.host.json | 1 + pnpm-lock.yaml | 14 +- 16 files changed, 863 insertions(+), 143 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/layers.ts create mode 100644 packages/experimental/client-ui-forge/tests/layers.host.spec.ts diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 7ab090b292..8dd840d825 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -71,7 +71,8 @@ "diff": "^9.0.0", "zod": "4.6.6", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "picomatch": "^4.0.7" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -115,7 +116,8 @@ "@deepseek-ai/dsh-timeout": "workspace:*", "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-session-query": "workspace:*", - "@deepseek-ai/dsh-api-remote-access": "workspace:*" + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@types/picomatch": "^4.0.3" }, "files": [ "locale/*.json", diff --git a/packages/experimental/client-ui-forge/src/diff.ts b/packages/experimental/client-ui-forge/src/diff.ts index aa6cc8515a..4ec3d62b71 100644 --- a/packages/experimental/client-ui-forge/src/diff.ts +++ b/packages/experimental/client-ui-forge/src/diff.ts @@ -1,7 +1,11 @@ /** Unified patch parsing into the panel's browser-safe diff model, and the diff and size of an untracked file. */ +import { createHash } from 'node:crypto' import { parsePatch } from 'diff' -import type { ForgeChangedFile, ForgeDiffFile, ForgeDiffStatus } from './types.ts' +import type { ForgeChangedFile, ForgeDiffFile, ForgeDiffHunk, ForgeDiffStatus } from './types.ts' + +/** A changed file before its path is classified into a review layer. */ +export type ParsedDiffFile = Omit /** Git's name for the missing side of an added or deleted file. */ const NULL_PATH = '/dev/null' @@ -9,6 +13,9 @@ const NULL_PATH = '/dev/null' /** Bytes Git inspects for a NUL byte before it calls content binary. */ const BINARY_PROBE_BYTES = 8000 +/** Blob names of both sides on a Git `index` header line, which identify a binary change that carries no hunks. */ +const INDEX_LINE = /^index ([0-9a-f]+\.\.[0-9a-f]+)/m + /** * Parse a Git-style unified patch, as `git diff` or a code host prints it, * with `a/` and `b/` path prefixes. Hunk ranges follow jsdiff: a range that @@ -16,8 +23,11 @@ const BINARY_PROBE_BYTES = 8000 * @param patch - the patch text. * @returns one file per patch section in patch order. */ -export function parseDiff(patch: string): ForgeDiffFile[] { - return parsePatch(patch).flatMap((section) => { +export function parseDiff(patch: string): ParsedDiffFile[] { + const parsed = parsePatch(patch) + // Hunk lines start with a space, `+`, `-`, or `\`, so only a Git section header starts a line with `diff --git `. + const headers = patch.split(/^(?=diff --git )/m).filter(section => section.startsWith('diff --git ')) + return parsed.flatMap((section, index) => { const before = pathOf(section.oldFileName, 'a/') const after = pathOf(section.newFileName, 'b/') const path = after ?? before @@ -33,46 +43,67 @@ export function parseDiff(patch: string): ForgeDiffFile[] { else if (line.startsWith('-')) deletions++ } } + const binary = section.isBinary === true + const previousPath = status === 'renamed' ? before : null + const hunks = section.hunks.map(({ oldStart, oldLines, newStart, newLines, lines }) => ( + { oldStart, oldLines, newStart, newLines, lines })) + // Each header matches its parsed section only when every section starts with a Git header. + const header = binary && headers.length === parsed.length ? String(headers[index]) : '' + const blobs = INDEX_LINE.exec(header)?.[1] ?? '' return [{ - path, - previousPath: status === 'renamed' ? before : null, - status, - binary: section.isBinary === true, - oversized: false, - untracked: false, - additions, - deletions, - hunks: section.hunks.map(({ oldStart, oldLines, newStart, newLines, lines }) => ({ oldStart, oldLines, newStart, newLines, lines })), + path, previousPath, status, binary, oversized: false, untracked: false, additions, deletions, hunks, + digest: changeDigest(path, previousPath, status, hunks, blobs), }] }) } +/** Digest of one change: its paths, status, hunks, and the identity of content that hunks do not show. */ +function changeDigest( + path: string, previousPath: string | null, status: ForgeDiffStatus, hunks: readonly ForgeDiffHunk[], content: string, +): string { + return createHash('sha256').update(JSON.stringify([path, previousPath, status, hunks, content])).digest('hex').slice(0, 32) +} + /** * Describe an untracked file as added in full. * @param path - path relative to the repository root. * @param content - the file's bytes. * @returns the file with one hunk of added lines, none when it is empty, or none and `binary` when its content is not text. */ -export function untrackedFile(path: string, content: Uint8Array): ForgeDiffFile { - const file: ForgeDiffFile = { - path, previousPath: null, status: 'added', binary: false, oversized: false, untracked: true, additions: 0, deletions: 0, hunks: [], - } +export function untrackedFile(path: string, content: Uint8Array): ParsedDiffFile { const text = decodeText(content) - if (text === undefined) return { ...file, binary: true } - if (text.length === 0) return file + if (text === undefined) return addedFile(path, [], { binary: true, oversized: false, content: createHash('sha256').update(content).digest('hex') }) + if (text.length === 0) return addedFile(path, [], { binary: false, oversized: false, content: '' }) const lines = text.split('\n') const ended = lines.at(-1) === '' if (ended) lines.pop() + return addedFile(path, [{ + oldStart: 1, + oldLines: 0, + newStart: 1, + newLines: lines.length, + lines: [...lines.map(line => `+${line}`), ...ended ? [] : ['\\ No newline at end of file']], + }], { binary: false, oversized: false, content: '' }) +} + +/** + * Describe an untracked file over `maxDiffBytes`, which carries no hunks and whose content is not read. + * @param path - path relative to the repository root. + * @returns the oversized added file. + */ +export function oversizedUntrackedFile(path: string): ParsedDiffFile { + return addedFile(path, [], { binary: false, oversized: true, content: 'oversized' }) +} + +/** An untracked file as added, whose digest also covers `content`, the identity of content its hunks do not show. */ +function addedFile(path: string, hunks: readonly ForgeDiffHunk[], { binary, oversized, content }: { + readonly binary: boolean + readonly oversized: boolean + readonly content: string +}): ParsedDiffFile { return { - ...file, - additions: lines.length, - hunks: [{ - oldStart: 1, - oldLines: 0, - newStart: 1, - newLines: lines.length, - lines: [...lines.map(line => `+${line}`), ...ended ? [] : ['\\ No newline at end of file']], - }], + path, previousPath: null, status: 'added', binary, oversized, untracked: true, + additions: hunks[0]?.newLines ?? 0, deletions: 0, hunks, digest: changeDigest(path, null, 'added', hunks, content), } } diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 6800a70b34..c1679818d2 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -5,7 +5,10 @@ import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' -import type { ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, MergeMethod } from '@deepseek-ai/dsh-experimental-forge' +import type { + ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, + MergeMethod, +} from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import { appendPluginRecord } from '@deepseek-ai/dsh-session' @@ -19,15 +22,17 @@ import { gitIn, inspectCheckout, listBranches } from './git.ts' import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, FilterConfigError, forkPoint, localDiff, localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, FilterConfigError, forkPoint, localCommits, localDiff, + localText, NoForkPoint, } from './local-diff.ts' +import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' import { PatchCache } from './patch-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, - ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits, + ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -41,8 +46,28 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch listing limit and the worktree branch prefix. */ -type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly worktreePrefix: string } +/** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */ +type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string } + +/** + * Tests, test data, snapshots, locale dictionaries, and lockfiles, after the review plugin's collapsed and + * non-interface paths; `locales.ts` is the typed dictionary module of a DSH Client plugin. + */ +const TEST_PATHS = [ + '**/test/**', '**/tests/**', '**/__tests__/**', '**/__mocks__/**', '**/__fixtures__/**', '**/e2e/**', + '**/*.spec.*', '**/*.test.*', '**/*.e2e.*', + '**/__snapshots__/**', 'snapshots/**', '**/*.snap', + '**/locale/*.json', '**/locales/**', '**/locales.ts', + '**/pnpm-lock.yaml', '**/package-lock.json', '**/npm-shrinkwrap.json', '**/yarn.lock', +] as const + +/** Package manifests, type declarations, and configuration by extension, name, or directory, after the review plugin's scanner. */ +const INTERFACE_PATHS = [ + '**/package.json', '**/*.d.ts', '**/*.d.mts', '**/*.d.cts', '**/types.ts', + '**/*.{json,jsonc,yaml,yml,toml,ini,conf,cfg,properties,xml,plist}', + '**/.env', '**/.env.*', '**/.*rc', '**/.*rc.*', '**/*{config,settings,preferences,options}*', + '**/{config,configs,settings,profiles}/**', +] as const /** * Serves the forge panel. Following a Session inspects the checkout of its @@ -75,6 +100,9 @@ export class ForgePanelController extends TypertRemoteService { maxDiffBytes: z.number().default(8_388_608), maxUntrackedFiles: z.number().default(100), maxCachedDiffBytes: z.number().default(16_777_216), + maxCommits: z.number().default(250), + testPaths: z.array(z.string()).default([...TEST_PATHS]), + interfacePaths: z.array(z.string()).default([...INTERFACE_PATHS]), }) private readonly home: Context @@ -83,6 +111,7 @@ export class ForgePanelController extends TypertRemoteService { private worktreeStates!: ProjectionHandle private creations!: WorktreeCreations private readonly patches: PatchCache + private readonly layers: FileLayers private states: ChangeRequestStates | undefined private readonly stopPanels: () => Promise private readonly stopStates: () => Promise @@ -97,10 +126,14 @@ export class ForgePanelController extends TypertRemoteService { throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } } - for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes'] as const) { + for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits'] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') + for (const key of ['testPaths', 'interfacePaths'] as const) { + if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`) + } + this.layers = new FileLayers(resolved.testPaths, resolved.interfacePaths) this.home = ctx this.config = resolved this.patches = new PatchCache(resolved.maxCachedDiffBytes) @@ -271,7 +304,8 @@ export class ForgePanelController extends TypertRemoteService { * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote @@ -283,19 +317,42 @@ export class ForgePanelController extends TypertRemoteService { const created = this.worktreeState(session).created const fork = scope.kind !== 'branch' ? null : await diffing(scope.base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, scope.base)) - return await diffing(localDiff(this.home, this.config, session, root, fork, scope, signal)) + return await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal)) + } + + /** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ + @Remote + async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise { + signal.throwIfAborted() + const inspection = await this.checkoutOf(session, signal) + const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal) + const created = this.worktreeState(session).created + const fork = await diffing(base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, base)) + if (fork === null) throw new RemoteError('forgePanel/no-fork-point', 'The checkout has no fork point to compare its branch with', {}) + return await localCommits(git, fork, this.config.maxCommits) } /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise { @@ -325,36 +382,63 @@ export class ForgePanelController extends TypertRemoteService { } /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ @Remote - async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise { + async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const list = await this.home.forge.commits(this.bound(session, url).ref, signal) + if (list !== undefined && 'code' in list) throw readError(list) + return list ?? null + } + + /** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ + @Remote + async changeRequestDiff( + session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, + ): Promise { signal.throwIfAborted() const { ref, update } = this.bound(session, url) if (update === null || !('snapshot' in update)) { throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {}) } + if (commits !== null) return await this.commitsDiff(ref, commits, signal) const { headSha, headBranch, baseBranch } = update.snapshot const key = changeRequestKey(ref) const version = JSON.stringify([headSha, baseBranch]) - let patch = this.patches.get(key, version) - if (patch === undefined) { - const read = await this.home.forge.diff(ref, signal) - if (typeof read !== 'string') throw readError(read) + let read = this.patches.get(key, version) + if (read === undefined) { + const patch = await this.home.forge.diff(ref, signal) + if (typeof patch !== 'string') throw readError(patch) + read = { patch, attributes: await this.attributesAt(ref, headSha, signal) } this.patches.set(key, version, read) - patch = read } - const files = parseDiff(patch) + const files = this.layers.classify(parseDiff(read.patch), read.attributes) let localAhead: number | null = null try { localAhead = await aheadOf( @@ -604,6 +688,33 @@ export class ForgePanelController extends TypertRemoteService { return this.home.workingDirectory.get(session) === directory ? missing : null } + /** The changes of consecutive commits of a change request, from the first one's first parent to the last. */ + private async commitsDiff(ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal): Promise { + const list = await this.home.forge.commits(ref, signal) + if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {}) + if ('code' in list) throw readError(list) + const first = list.commits.findIndex(commit => commit.sha === commits.from) + const last = list.commits.findIndex(commit => commit.sha === commits.to) + if (first === -1 || last < first) { + throw new RemoteError('forgePanel/commits-missing', 'The chosen commits are no longer in the change request', {}) + } + const parent = list.commits[first]?.parent ?? null + if (parent === null) throw new RemoteError('forgePanel/diff-failed', 'The first chosen commit has no parent to compare with', {}) + const patch = await this.home.forge.compare(ref, parent, commits.to, signal) + if (typeof patch !== 'string') throw readError(patch) + const files = this.layers.classify(parseDiff(patch), await this.attributesAt(ref, commits.to, signal)) + const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) + return { headSha: commits.to, files, localAhead: null, fileUrls } + } + + /** The root `.gitattributes` of a change request's repository at a commit, empty when the commit has none. */ + private async attributesAt(ref: ChangeRequestRef, commit: string, signal: AbortSignal): Promise { + const attributes = await this.home.forge.fileText(ref, commit, ATTRIBUTES_PATH, signal) + if (typeof attributes === 'string') return attributes + if (attributes.code === 'not-found') return '' + throw readError(attributes) + } + /** Inspect the checkout of the Session's current directory, which local diffs read. */ private async checkoutOf(session: Session, signal: AbortSignal): Promise { const inspection = await inspectCheckout(this.home, this.config, session, this.home.workingDirectory.get(session), signal) @@ -726,7 +837,8 @@ function readError(failure: ForgeFailure): RemoteError { } /** - * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, and a missing base branch as Remote errors. + * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, a missing base branch, and chosen + * commits that are not on the branch as Remote errors. * @param reading - the read. * @returns what the read returned. */ @@ -738,6 +850,7 @@ async function diffing(reading: Promise): Promise { if (error instanceof DiffTooLarge) throw new RemoteError('forgePanel/diff-too-large', error.message, {}, { cause: error }) if (error instanceof NoForkPoint) throw new RemoteError('forgePanel/no-fork-point', error.message, {}, { cause: error }) if (error instanceof BaseMissing) throw new RemoteError('forgePanel/base-missing', error.message, {}, { cause: error }) + if (error instanceof CommitsMissing) throw new RemoteError('forgePanel/commits-missing', error.message, {}, { cause: error }) throw error } } diff --git a/packages/experimental/client-ui-forge/src/layers.ts b/packages/experimental/client-ui-forge/src/layers.ts new file mode 100644 index 0000000000..827bbf4269 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/layers.ts @@ -0,0 +1,87 @@ +/** + * Review layers of changed files: the `testPaths` and `interfacePaths` globs of the panel's configuration, and the + * `linguist-generated` attribute of a repository's root `.gitattributes`, which also places a file in the `test` layer. + */ + +import picomatch from 'picomatch' +import type { ParsedDiffFile } from './diff.ts' +import type { ForgeDiffFile, ForgeFileLayer } from './types.ts' + +/** Path of the attributes file read beside each diff, relative to the repository root. */ +export const ATTRIBUTES_PATH = '.gitattributes' + +/** The attribute GitHub Linguist reads to treat a file as generated. */ +const GENERATED = 'linguist-generated' + +type Matcher = (path: string) => boolean + +/** + * Compile globs into one matcher; `*` matches dot files and never crosses `/`. + * @param globs - picomatch globs. + * @returns whether a repository-relative path matches any glob. + */ +function matcherOf(globs: readonly string[]): Matcher { + return globs.length === 0 ? () => false : picomatch([...globs], { dot: true }) +} + +/** + * Read which paths a `.gitattributes` text marks `linguist-generated`. Lines apply in order, so a later line overrides + * an earlier one; `linguist-generated` and `=true` set the attribute, `-linguist-generated` and `=false` unset it, and + * `!linguist-generated` returns it to unspecified. A pattern without `/` matches a file name at any depth, and one with + * `/` matches from the repository root. Macro definitions, quoted patterns, and patterns ending in `/`, which name + * directories and so never match a file, are skipped. + * @param attributes - the text of the root `.gitattributes`, empty without one. + * @returns whether a repository-relative path is generated. + */ +export function generatedMatcher(attributes: string): Matcher { + const rules: { readonly match: Matcher; readonly generated: boolean | undefined }[] = [] + for (const raw of attributes.split(/\r?\n/)) { + const [pattern, ...fields] = raw.trim().split(/\s+/) + if (pattern === undefined || pattern === '' || pattern.startsWith('#') || pattern.startsWith('[attr]') + || pattern.startsWith('"') || pattern.endsWith('/')) continue + let generated: boolean | null | undefined = null + for (const field of fields) { + if (field === GENERATED || field === `${GENERATED}=true`) generated = true + else if (field === `-${GENERATED}` || field === `${GENERATED}=false`) generated = false + else if (field === `!${GENERATED}`) generated = undefined + } + if (generated === null) continue + const anchored = pattern.replace(/^\//, '') + rules.push({ match: picomatch(anchored, { dot: true, basename: !pattern.includes('/') }), generated }) + } + return (path) => { + let generated: boolean | undefined + for (const rule of rules) if (rule.match(path)) generated = rule.generated + return generated === true + } +} + +/** Classifies changed files into review layers by the panel's path globs and a repository's attributes. */ +export class FileLayers { + private readonly test: Matcher + private readonly interface: Matcher + + /** + * @param testPaths - globs of the `test` layer. + * @param interfacePaths - globs of the `interface` layer. + */ + constructor(testPaths: readonly string[], interfacePaths: readonly string[]) { + this.test = matcherOf(testPaths) + this.interface = matcherOf(interfacePaths) + } + + /** + * Place each file in its layer: `test` first, then `interface`, else `implementation`. + * @param files - parsed files. + * @param attributes - the text of the repository's root `.gitattributes`, empty without one. + * @returns the files in the same order with their layers. + */ + classify(files: readonly ParsedDiffFile[], attributes: string): ForgeDiffFile[] { + const generated = generatedMatcher(attributes) + return files.map((file) => { + const layer: ForgeFileLayer = this.test(file.path) || generated(file.path) ? 'test' + : this.interface(file.path) ? 'interface' : 'implementation' + return { ...file, layer } + }) + } +} diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 34c6ac6114..c17c443d13 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -10,13 +10,17 @@ import type { Context } from '@deepseek-ai/cordis' import { FsError } from '@deepseek-ai/dsh-fs' import type { Session } from '@deepseek-ai/dsh-session' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { decodeText, parseDiff, parseNumstat, untrackedFile } from './diff.ts' +import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from './diff.ts' +import type { ParsedDiffFile } from './diff.ts' import { gitIn, GitOutputTooLarge } from './git.ts' import type { Git, GitConfig, GitOutput, Inspection } from './git.ts' +import { ATTRIBUTES_PATH } from './layers.ts' +import type { FileLayers } from './layers.ts' import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts' import type { - ForgeBaseBranches, ForgeDiffFile, ForgeLocalChanges, ForgeLocalDiff, ForgeLocalScope, ForgeSessionWorktree, + ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree, } from './types.ts' +import type { ForgeCommit } from '@deepseek-ai/dsh-experimental-forge/types' /** Git limits plus the size limits of local diffs. */ export interface DiffConfig extends GitConfig { @@ -56,6 +60,17 @@ export class BaseMissing extends Error { override name = 'BaseMissing' } +/** Thrown when chosen commits are not among the commits of the `branch` scope, or are out of order. */ +export class CommitsMissing extends Error { + override name = 'CommitsMissing' +} + +/** A full SHA-1 or SHA-256 object name, the only form of a chosen commit Git receives. */ +const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ + +/** One commit per record: object name, first parent, author, author date, and subject, separated by NUL. */ +const LOG_FORMAT = '--format=%H%x00%P%x00%an%x00%aI%x00%s%x1e' + /** No executable diff helpers or submodule working-tree inspection; preserve recorded submodule commit changes. */ const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv', '--submodule=short', '--ignore-submodules=dirty', '--no-color', '-M', '--src-prefix=a/', '--dst-prefix=b/'] as const @@ -155,16 +170,20 @@ export async function baseBranches( /** * Read changes at `root` with command-local clean/process filter overrides and without * submodule working-tree inspection. Git's built-in newline, ident, and encoding conversions still apply. + * Each file's layer follows `layers` and the root `.gitattributes` of the new side: the index for `staged`, + * else the working tree. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. * @param config - Git and size limits. * @param session - Session whose sandbox policy and execution world apply. * @param root - top-level directory of the checkout. * @param fork - fork point of the `branch` scope, or null without one. * @param scope - which changes to read. + * @param layers - classifier of each file's review layer. * @param signal - cancellation of every command and read. * @returns tracked files in Git's order, then untracked files unless the scope is `staged`. * @throws NoForkPoint for the `branch` scope without `fork`; FilterConfigError when filter configuration - * cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output; an Error when Git fails. + * cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output or `.gitattributes`; + * an Error when Git or the `.gitattributes` read fails. */ export async function localDiff( ctx: Context, @@ -173,6 +192,7 @@ export async function localDiff( root: string, fork: ForkPoint | null, scope: ForgeLocalScope, + layers: FileLayers, signal: AbortSignal, ): Promise { const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) @@ -180,6 +200,7 @@ export async function localDiff( switch (scope.kind) { case 'branch': if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with') + if (scope.commits !== null) return await commitsDiff(git, fork, scope.commits, layers) range = [fork.commit] break case 'uncommitted': range = [await headOrEmptyTree(git)]; break @@ -190,14 +211,28 @@ export async function localDiff( } const overrides = await diffFilterOverrides(git) const tracked = parseDiff((await bounded(git('diff', [...DIFF, ...range, '--'], undefined, overrides))).stdout) - if (scope.kind === 'staged') return { base: null, files: tracked, omitted: 0 } + if (scope.kind === 'staged') { + const shown = await bounded(git('attributes', ['show', `:${ATTRIBUTES_PATH}`], [0, 128])) + return { base: null, files: layers.classify(tracked, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 } + } const untracked = await untrackedFiles(ctx, config, git, root, signal) - return { base: fork === null || scope.kind !== 'branch' ? null : fork.label, files: [...tracked, ...untracked.files], omitted: untracked.omitted } + let attributes = '' + try { + attributes = decodeText(await readFile(ctx, config, root, ATTRIBUTES_PATH, signal)) ?? '' + } catch (error) { + if (!(error instanceof FsError && error.code === 'FS_NOT_FOUND')) throw error + } + return { + base: fork === null || scope.kind !== 'branch' ? null : fork.label, + files: layers.classify([...tracked, ...untracked.files], attributes), + omitted: untracked.omitted, + } } /** * Read the new side of one file in a scope, which supplies the unchanged - * lines between hunks: the index for `staged`, else the working tree. + * lines between hunks: the index for `staged`, the last chosen commit for + * chosen commits of the `branch` scope, else the working tree. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. * @param config - Git and size limits. * @param session - Session whose sandbox policy and execution world apply. @@ -219,9 +254,11 @@ export async function localText( ): Promise { if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`) let text: string | undefined - if (scope.kind === 'staged') { + const commit = scope.kind === 'staged' ? '' : scope.kind === 'branch' && scope.commits !== null ? scope.commits.to : undefined + if (commit !== undefined) { + if (commit !== '' && !COMMIT.test(commit)) throw new CommitsMissing('The chosen commit is not a full object name') const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) - const shown = (await bounded(git('show', ['show', `:${path}`]))).stdout + const shown = (await bounded(git('show', ['show', `${commit}:${path}`]))).stdout text = shown.slice(0, BINARY_PROBE).includes('\0') ? undefined : shown } else { text = decodeText(await readFile(ctx, config, root, path, signal)) @@ -283,10 +320,57 @@ export async function aheadOf(git: Git, branch: string, commit: string): Promise return Number((await git('rev-list', ['rev-list', '--count', `${commit}..HEAD`])).stdout.trim()) } +/** + * List the commits of the `branch` scope: those reachable from HEAD but not from the fork point, parents before children. + * @param git - runner bound to the checkout, whose output limit bounds the listing. + * @param fork - fork point of the `branch` scope. + * @param limit - most commits listed. + * @returns the oldest `limit` commits and HEAD's commit. + * @throws an Error when Git fails or prints more than the runner's output limit. + */ +export async function localCommits(git: Git, fork: ForkPoint, limit: number): Promise { + const head = (await git('head', ['rev-parse', '--verify', 'HEAD'])).stdout.trim() + const all = await branchCommits(git, fork) + return { headSha: head, commits: all.slice(0, limit), truncated: all.length > limit } +} + +/** Every commit between the fork point and HEAD, parents before children. */ +async function branchCommits(git: Git, fork: ForkPoint): Promise { + const output = await git('log', ['log', '--topo-order', '--reverse', LOG_FORMAT, `${fork.commit}..HEAD`, '--']) + return output.stdout.split('\x1e').flatMap((record): ForgeCommit[] => { + const fields = record.replace(/^\n/, '').split('\0') + // The text after the last record holds no fields. + if (fields.length !== 5) return [] + const [sha, parents, author, authoredAt, title] = fields as [string, string, string, string, string] + return [{ sha, parent: /^\S+/.exec(parents)?.[0] ?? null, title, author, authoredAt }] + }) +} + +/** The committed changes of consecutive commits of the `branch` scope, from the first commit's first parent to the last. */ +async function commitsDiff(git: Git, fork: ForkPoint, chosen: ForgeCommitRange, layers: FileLayers): Promise { + if (!COMMIT.test(chosen.from) || !COMMIT.test(chosen.to)) throw new CommitsMissing('The chosen commits are not full object names') + const commits = await branchCommits(git, fork) + const first = commits.findIndex(commit => commit.sha === chosen.from) + const start = commits[first] + if (start === undefined || commits.findIndex(commit => commit.sha === chosen.to) < first) { + throw new CommitsMissing('The chosen commits are no longer on the branch') + } + // A first commit without a parent starts an unrelated history that HEAD merged; it adds every file. + const parent = start.parent ?? await emptyTree(git) + const overrides = await diffFilterOverrides(git) + const files = parseDiff((await bounded(git('diff', [...DIFF, parent, chosen.to, '--'], undefined, overrides))).stdout) + const shown = await bounded(git('attributes', ['show', `${chosen.to}:${ATTRIBUTES_PATH}`], [0, 128])) + return { base: fork.label, files: layers.classify(files, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 } +} + /** HEAD, or the empty tree while the checked-out branch has no commit. */ async function headOrEmptyTree(git: Git): Promise { const head = await git('head', ['rev-parse', '--verify', '--quiet', 'HEAD'], [0, 1]) - if (head.exitCode === 0) return 'HEAD' + return head.exitCode === 0 ? 'HEAD' : await emptyTree(git) +} + +/** The object name of the empty tree. */ +async function emptyTree(git: Git): Promise { return (await git('empty-tree', ['hash-object', '-t', 'tree', '--stdin'])).stdout.trim() } @@ -297,17 +381,17 @@ async function untrackedFiles( git: Git, root: string, signal: AbortSignal, -): Promise<{ readonly files: ForgeDiffFile[]; readonly omitted: number }> { +): Promise<{ readonly files: ParsedDiffFile[]; readonly omitted: number }> { const listed = await bounded(git('untracked', ['ls-files', '--others', '--exclude-standard', '-z'])) const paths = listed.stdout.split('\0').filter(path => path.length > 0 && !path.endsWith('/')) - const files: ForgeDiffFile[] = [] + const files: ParsedDiffFile[] = [] for (const path of paths.slice(0, config.maxUntrackedFiles)) { let content: Uint8Array try { content = await readFile(ctx, config, root, path, signal) } catch (error) { if (error instanceof DiffTooLarge) { - files.push({ ...untrackedFile(path, new Uint8Array()), oversized: true }) + files.push(oversizedUntrackedFile(path)) continue } if (error instanceof FsError) continue diff --git a/packages/experimental/client-ui-forge/src/patch-cache.ts b/packages/experimental/client-ui-forge/src/patch-cache.ts index 9ccc8d37e9..f331c08c19 100644 --- a/packages/experimental/client-ui-forge/src/patch-cache.ts +++ b/packages/experimental/client-ui-forge/src/patch-cache.ts @@ -1,22 +1,28 @@ /** - * Change request patches kept in memory, so the changes view reads no diff - * from the code host again while a change request keeps its head commit and base branch. + * Change request patches kept in memory with the repository attributes read beside them, so the changes view reads + * neither from the code host again while a change request keeps its head commit and base branch. */ import { Buffer } from 'node:buffer' import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge' +/** One change request's patch and the root `.gitattributes` text at its head commit, empty without one. */ +export interface CachedPatch { + readonly patch: string + readonly attributes: string +} + interface Entry { /** Head commit and base branch the patch was read at. */ readonly version: string - readonly patch: string - /** UTF-8 size of `patch`. */ + readonly value: CachedPatch + /** UTF-8 size of the patch and the attributes. */ readonly bytes: number } /** * One patch per change request, bounded by the total UTF-8 size of the kept - * patches; the least recently read patch leaves first. + * patches and their attributes; the least recently read patch leaves first. */ export class PatchCache { private readonly entries = new Map() @@ -29,14 +35,14 @@ export class PatchCache { * Read the patch kept for a change request at a version, marking it the most recently read. * @param key - the change request. * @param version - head commit and base branch the reader needs. - * @returns the patch, or undefined when none is kept at that version. + * @returns the patch and its attributes, or undefined when none is kept at that version. */ - get(key: ChangeRequestKey, version: string): string | undefined { + get(key: ChangeRequestKey, version: string): CachedPatch | undefined { const entry = this.entries.get(key) if (entry?.version !== version) return undefined this.entries.delete(key) this.entries.set(key, entry) - return entry.patch + return entry.value } /** @@ -44,13 +50,13 @@ export class PatchCache { * least recently read patches until the rest fit within `maxBytes`. * @param key - the change request. * @param version - head commit and base branch the patch was read at. - * @param patch - the patch. + * @param value - the patch and its attributes. */ - set(key: ChangeRequestKey, version: string, patch: string): void { + set(key: ChangeRequestKey, version: string, value: CachedPatch): void { this.remove(key) - const bytes = Buffer.byteLength(patch) + const bytes = Buffer.byteLength(value.patch) + Buffer.byteLength(value.attributes) if (bytes > this.maxBytes) return - this.entries.set(key, { version, patch, bytes }) + this.entries.set(key, { version, value, bytes }) this.bytes += bytes for (const oldest of this.entries.keys()) { if (this.bytes <= this.maxBytes) break diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 2a11e67ac6..64cebb0aa4 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -1,7 +1,7 @@ /** Browser-safe panel state, the worktree request record, Remote error codes, and Host configuration of the forge panel. */ import type {} from '@deepseek-ai/dsh-typert-protocol' -import type { ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ChangeRequestSnapshot, ForgeCommitList, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types' /** Git facts for the checkout that contains the Session's current directory. */ @@ -242,14 +242,26 @@ export interface ForgeBaseBranches { readonly local: readonly ForgeBaseBranch[] } +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +export interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} + /** Which local changes a diff covers; each reads the Session's checkout through Git. */ export type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -274,6 +286,12 @@ export interface ForgeDiffHunk { /** How one file changed. */ export type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +export type ForgeFileLayer = 'interface' | 'implementation' | 'test' + /** One changed file of a diff. */ export interface ForgeDiffFile { /** Path relative to the repository root after the change, or before it for a deleted file. */ @@ -294,6 +312,13 @@ export interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } /** Local changes of the Session's checkout in one scope. */ @@ -306,21 +331,24 @@ export interface ForgeLocalDiff { readonly omitted: number } -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ export interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +export type ForgeLocalCommits = ForgeCommitList + /** One file the `branch` scope changes, without its hunks. */ export interface ForgeChangedFile { /** Path relative to the repository root after the change. */ @@ -366,6 +394,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } declare module '@deepseek-ai/dsh-typert-protocol' { @@ -412,6 +449,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/checks-failed': Record /** The code host did not provide the change request's diff or file, or its status has not been read yet; the message says why. */ 'forgePanel/diff-failed': Record + /** A chosen commit is no longer among the listed commits of the branch or change request, or the commits are out of order. */ + 'forgePanel/commits-missing': Record } } diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 89f380292c..feb7660187 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -501,7 +501,7 @@ describe('forgePanel local changes', () => { await writeFile(join(repo, 'notes.md'), 'hello\n') const opened = await open(repo) - const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) + const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal) expect(diff.base).toBe('origin/main') expect(diff.files.map(file => [file.path, file.status, file.untracked])).toEqual([['tracked.txt', 'modified', false], ['notes.md', 'added', true]]) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'staged' }, signal)).resolves.toEqual({ base: null, files: [], omitted: 0 }) @@ -519,22 +519,57 @@ describe('forgePanel local changes', () => { const opened = await open(repo) const paths = (diff: ForgeLocalDiff): string[] => diff.files.map(file => file.path) - const automatic = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) + const automatic = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal) expect([automatic.base, paths(automatic)]).toEqual(['origin/main', ['feature.txt', 'notes.md']]) - const chosen = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/topic' }, signal) + const chosen = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/topic', commits: null }, signal) expect([chosen.base, paths(chosen)]).toEqual(['topic', ['notes.md']]) await expect(opened.ctx.forgePanel.diffBases(opened.session, '', signal)).resolves.toEqual({ automatic: { name: 'origin/main', worktree: false }, remote: [{ ref: 'refs/remotes/origin/main', name: 'origin/main' }], local: [{ ref: 'refs/heads/topic', name: 'topic' }], }) - await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/gone' }, signal)) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/gone', commits: null }, signal)) .rejects.toMatchObject({ code: 'forgePanel/base-missing' }) const outside = await open(await plain()) await expect(outside.ctx.forgePanel.diffBases(outside.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) }) + it('lists the commits of the branch scope and reads chosen ones', async () => { + const { repo } = await project() + await withDefaultBranch(repo) + for (const name of ['one', 'two', 'three']) { + await writeFile(join(repo, `${name}.txt`), `${name}\n`) + await git(repo, 'add', `${name}.txt`) + await git(repo, 'commit', '--quiet', '-m', name) + } + await git(repo, 'branch', 'topic', 'HEAD~1') + await writeFile(join(repo, 'notes.md'), 'hello\n') + const opened = await open(repo, { maxCommits: 2 }) + + const listed = await opened.ctx.forgePanel.localCommits(opened.session, null, signal) + expect(listed).toMatchObject({ truncated: true, headSha: await git(repo, 'rev-parse', 'HEAD') }) + expect(listed.commits.map(commit => commit.title)).toEqual(['one', 'two']) + await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/topic', signal)) + .resolves.toMatchObject({ truncated: false, commits: [{ title: 'three' }] }) + const [one, two] = listed.commits.map(commit => commit.sha) + const chosen = await opened.ctx.forgePanel.localDiff(opened.session, + { kind: 'branch', base: null, commits: { from: one ?? '', to: two ?? '' } }, signal) + expect(chosen.files.map(file => file.path)).toEqual(['one.txt', 'two.txt']) + await expect(opened.ctx.forgePanel.localText(opened.session, + { kind: 'branch', base: null, commits: { from: one ?? '', to: one ?? '' } }, 'one.txt', signal)).resolves.toBe('one\n') + await expect(opened.ctx.forgePanel.localDiff(opened.session, + { kind: 'branch', base: 'refs/heads/topic', commits: { from: one ?? '', to: two ?? '' } }, signal)) + .rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/gone', signal)).rejects.toMatchObject({ code: 'forgePanel/base-missing' }) + + const unrelated = await project() + const lonely = await open(unrelated.repo) + await expect(lonely.ctx.forgePanel.localCommits(lonely.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) + const outside = await open(await plain()) + await expect(outside.ctx.forgePanel.localCommits(outside.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) + }) + it('lists more refs than other Git output may print, up to maxDiffBytes', async () => { const { repo } = await project() await withDefaultBranch(repo) @@ -561,7 +596,7 @@ describe('forgePanel local changes', () => { const { repo } = await project() await writeFile(join(repo, 'tracked.txt'), 'x\n'.repeat(2000)) const opened = await open(repo, { maxDiffBytes: 1024 }) - await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'unstaged' }, signal)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) @@ -607,7 +642,7 @@ describe('forgePanel change request diffs', () => { shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) await reader(opened).until(state => polled(state, pullUrl(7))) - const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal) + const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) expect(diff).toMatchObject({ headSha: head, localAhead: 1, fileUrls: { 'src/a.ts': `${pullUrl(7)}/files/${head}/src/a.ts` } }) expect(diff.files.map(file => [file.path, file.additions, file.deletions])).toEqual([['src/a.ts', 1, 1]]) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), head, 'src/a.ts', signal)).resolves.toBe('new\n') @@ -621,7 +656,8 @@ describe('forgePanel change request diffs', () => { await reader(opened).until(state => polled(state, pullUrl(7))) opened.sandbox.failure = new Error('sandbox unavailable') - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)).resolves.toMatchObject({ localAhead: null }) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) + .resolves.toMatchObject({ localAhead: null }) }) it('downloads a diff once per head commit and base branch for every Session, keeping no failed read', async () => { @@ -631,7 +667,7 @@ describe('forgePanel change request diffs', () => { const follower = reader(opened) await follower.until(state => polled(state, pullUrl(7))) const paths = async (session: Session = opened.session): Promise => - (await opened.ctx.forgePanel.changeRequestDiff(session, pullUrl(7), signal)).files.map(file => file.path) + (await opened.ctx.forgePanel.changeRequestDiff(session, pullUrl(7), null, signal)).files.map(file => file.path) const moved = async (snapshot: { headSha: string; baseBranch: string }): Promise => { opened.provider.overrides.set(7, snapshot) await opened.ctx.forgePanel.refresh(opened.session, signal) @@ -657,6 +693,63 @@ describe('forgePanel change request diffs', () => { expect(opened.provider.diffs).toEqual([7, 7, 7, 7]) }) + it('classifies files by the root .gitattributes at the head and refuses attributes the host does not provide', async () => { + const { repo } = await project() + const opened = await open(repo) + const head = 'a'.repeat(40) + opened.provider.patches.set(7, `${PATCH}${PATCH.replaceAll('src/a.ts', 'gen/b.ts')}${PATCH.replaceAll('src/a.ts', 'src/a.spec.ts')}`) + opened.provider.texts.set(`${head}:.gitattributes`, 'gen/** linguist-generated\n') + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => polled(state, pullUrl(7))) + + const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + expect(diff.files.map(file => [file.path, file.layer])).toEqual([['src/a.ts', 'implementation'], ['gen/b.ts', 'test'], ['src/a.spec.ts', 'test']]) + + const other = await open(repo) + other.provider.patches.set(7, PATCH) + other.provider.texts.set(`${head}:.gitattributes`, { code: 'unavailable', message: 'down' }) + shellTurn(other.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(other).until(state => polled(state, pullUrl(7))) + await expect(other.ctx.forgePanel.changeRequestDiff(other.session, pullUrl(7), null, signal)) + .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'down' }) + }) + + it('lists the commits of a change request and reads consecutive ones from the first one\'s parent', async () => { + const { repo } = await project() + const opened = await open(repo) + const sha = (n: number): string => String(n).repeat(40) + const commit = (n: number, parent: string | null) => ({ sha: sha(n), parent, title: `c${n}`, author: 'octo', authoredAt: '2026-10-09T00:00:00Z' }) + const list = { headSha: sha(3), truncated: false, commits: [commit(1, null), commit(2, sha(1)), commit(3, sha(2))] } + opened.provider.commitLists.set(7, list) + opened.provider.comparisons.set(`${sha(1)}..${sha(3)}`, PATCH) + opened.provider.texts.set(`${sha(3)}:.gitattributes`, 'src/** linguist-generated\n') + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => polled(state, pullUrl(7))) + const read = (from: number, to: number) => + opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), { from: sha(from), to: sha(to) }, signal) + + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).resolves.toEqual(list) + await expect(read(2, 3)).resolves.toEqual({ + headSha: sha(3), localAhead: null, fileUrls: { 'src/a.ts': `${pullUrl(7)}/files/${sha(3)}/src/a.ts` }, + files: [expect.objectContaining({ path: 'src/a.ts', layer: 'test' })], + }) + expect(opened.provider.diffs).toEqual([]) + await expect(read(1, 1)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The first chosen commit has no parent to compare with' }) + await expect(read(3, 2)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(read(4, 3)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: `no comparison ${sha(2)}..${sha(3)}` }) + opened.provider.comparisons.set(`${sha(2)}..${sha(3)}`, { code: 'too-large', message: 'too many files' }) + await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) + + opened.provider.commitLists.set(7, { code: 'unavailable', message: 'down' }) + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).rejects.toMatchObject({ code: 'forgePanel/diff-failed' }) + await expect(read(2, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'down' }) + delete opened.provider.commits + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).resolves.toBeNull() + await expect(read(2, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The code host provider does not read commits' }) + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(9), signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + }) + it('reports a diff or file over a size limit as too large', async () => { const { repo } = await project() const opened = await open(repo) @@ -666,7 +759,7 @@ describe('forgePanel change request diffs', () => { shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) await reader(opened).until(state => polled(state, pullUrl(7))) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large', message: 'the diff exceeded the maximum number of files (300)' }) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), head, 'big.bin', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large', message: 'big.bin is too large to fetch' }) @@ -682,10 +775,10 @@ describe('forgePanel change request diffs', () => { ]) await reader(opened).until(state => polled(state, pullUrl(7)) && failing(state, pullUrl(8))) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(9), signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(8), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(9), null, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(8), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The change request status has not been read yet' }) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'no diff of #7' }) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), 'a'.repeat(40), 'gone.ts', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: `no gone.ts at ${'a'.repeat(40)}` }) @@ -1713,7 +1806,7 @@ describe('forgePanel actions', () => { await expect(opened.ctx.forgePanel.refresh(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'unstaged' }, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(1), null, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(1), 'a'.repeat(40), 'x', controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.markReady(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.merge(opened.session, pullUrl(1), 'merge', 'a'.repeat(40), controller.signal)).rejects.toThrow('closed') @@ -1765,6 +1858,9 @@ describe('forgePanel configuration', () => { [{ maxBranches: 0 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxBranches: 2.5 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxCachedDiffBytes: 0 }, 'forge-panel: maxCachedDiffBytes must be a positive integer'], + [{ maxCommits: 0 }, 'forge-panel: maxCommits must be a positive integer'], + [{ testPaths: ['**/*.spec.*', ' '] }, 'forge-panel: testPaths entries must not be empty'], + [{ interfacePaths: [''] }, 'forge-panel: interfacePaths entries must not be empty'], [{ worktreePrefix: '-dsh/' }, prefix], [{ worktreePrefix: 'dsh /' }, prefix], [{ worktreePrefix: 'dsh:' }, prefix], diff --git a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts index 0d8aab0297..598109e93e 100644 --- a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts @@ -1,6 +1,6 @@ /** Patch parsing into the panel's diff model, untracked files as added in full, and numstat records. */ import { describe, expect, it } from 'vitest' -import { decodeText, parseDiff, parseNumstat, untrackedFile } from '../src/diff.ts' +import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from '../src/diff.ts' /** * A `git diff` patch with a binary change, a pure rename, a quoted path, a path @@ -82,6 +82,26 @@ describe('parseDiff', () => { expect(files[7]?.hunks).toEqual([{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 0, lines: ['-q', '-z'] }]) }) + it('digests each change by its paths, status, and hunks, and a binary change by its blob names', () => { + const files = parseDiff(PATCH) + const digests = files.map(file => file.digest) + expect(new Set(digests).size).toBe(files.length) + expect(digests.every(digest => /^[0-9a-f]{32}$/.test(digest))).toBe(true) + expect(parseDiff(PATCH).map(file => file.digest)).toEqual(digests) + const edited = parseDiff(PATCH.replace('+B', '+C')).map(file => file.digest) + expect(edited.filter((digest, index) => digest !== digests[index])).toHaveLength(1) + expect(edited[3]).not.toBe(digests[3]) + expect(parseDiff(PATCH.replace('index bdc955b..8352675', 'index bdc955b..0000001'))[0]?.digest).not.toBe(digests[0]) + }) + + it('digests a binary change without its blob names when a section does not start with a Git header', () => { + const binary = 'diff --git a/x.png b/x.png\nindex 1111111..2222222 100644\nBinary files a/x.png and b/x.png differ\n' + const withLeader = `--- a/y\n+++ b/y\n@@ -1 +1 @@\n-a\n+b\n${binary}` + const other = withLeader.replace('2222222', '3333333') + expect(parseDiff(withLeader)[1]?.digest).toBe(parseDiff(other)[1]?.digest) + expect(parseDiff(binary)[0]?.digest).not.toBe(parseDiff(binary.replace('2222222', '3333333'))[0]?.digest) + }) + it('takes paths without a prefix as they are and skips a section without a path', () => { expect(parseDiff('--- old\n+++ new\n@@ -1 +1 @@\n-a\n+b\n').map(file => [file.path, file.status])).toEqual([['new', 'modified']]) expect(parseDiff('')).toEqual([]) @@ -94,10 +114,20 @@ describe('untrackedFile', () => { ['no final newline', 'one\ntwo', ['+one', '+two', '\\ No newline at end of file']], ['carriage returns', 'one\r\ntwo\r\n', ['+one\r', '+two\r']], ])('adds every line of a text file with %s', (_label, text, lines) => { - expect(untrackedFile('notes/new.md', new TextEncoder().encode(text))).toEqual({ + const { digest, ...added } = untrackedFile('notes/new.md', new TextEncoder().encode(text)) + expect(added).toEqual({ path: 'notes/new.md', previousPath: null, status: 'added', binary: false, oversized: false, untracked: true, additions: 2, deletions: 0, hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 2, lines }], }) + expect(digest).toMatch(/^[0-9a-f]{32}$/) + }) + + it('digests binary content by its bytes and an oversized file by its path alone', () => { + const digest = (bytes: number[]): string => untrackedFile('blob', Uint8Array.from(bytes)).digest + expect(digest([0, 1])).toBe(digest([0, 1])) + expect(digest([0, 1])).not.toBe(digest([0, 2])) + expect(oversizedUntrackedFile('big.log')).toMatchObject({ oversized: true, binary: false, hunks: [], untracked: true }) + expect(oversizedUntrackedFile('big.log').digest).not.toBe(untrackedFile('big.log', new Uint8Array()).digest) }) it('describes an empty file without a hunk', () => { diff --git a/packages/experimental/client-ui-forge/tests/harness.ts b/packages/experimental/client-ui-forge/tests/harness.ts index 652de1a153..6dd6e7dc18 100644 --- a/packages/experimental/client-ui-forge/tests/harness.ts +++ b/packages/experimental/client-ui-forge/tests/harness.ts @@ -12,8 +12,8 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { createInboxStub, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit' import ForgeService, { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, - ForgeRepository, MergeRequest, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, + ForgeReadiness, ForgeRepository, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import ForgeSessionService from '@deepseek-ai/dsh-experimental-forge-session' import WorktreeService from '@deepseek-ai/dsh-experimental-worktree' @@ -291,6 +291,17 @@ export class FakeProvider implements ForgeProvider { readonly heads = new Map() /** Head lookups in call order, as `/ `. */ readonly lookups: string[] = [] + /** Commit lists or failures by change request number; others return a not-found failure. */ + readonly commitLists = new Map() + /** Patches or failures between two commits by `..`; others return a not-found failure. */ + readonly comparisons = new Map() + /** Commit listing; a test deletes it to stand for a provider that does not read commits. */ + commits?: (ref: ChangeRequestRef, signal: AbortSignal) => Promise = (ref: ChangeRequestRef) => + Promise.resolve(this.commitLists.get(ref.number) ?? { code: 'not-found', message: `no commits of #${ref.number}` }) + /** Comparison of two commits. */ + compare?: (ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal) => Promise = + (_ref: ChangeRequestRef, base: string, head: string) => + Promise.resolve(this.comparisons.get(`${base}..${head}`) ?? { code: 'not-found', message: `no comparison ${base}..${head}` }) repositoryFromRemote(url: string): ForgeRepository | undefined { const [, host = '', owner = '', name = ''] = /^https:\/\/([a-z.]+\.test)\/([^/]+)\/([^/]+?)\.git$/.exec(url) ?? [] diff --git a/packages/experimental/client-ui-forge/tests/layers.host.spec.ts b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts new file mode 100644 index 0000000000..172ebc57d6 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts @@ -0,0 +1,65 @@ +/** Review layers of changed files: path globs and the `linguist-generated` attribute of a root `.gitattributes`. */ +import { describe, expect, it } from 'vitest' +import { untrackedFile } from '../src/diff.ts' +import { FileLayers, generatedMatcher } from '../src/layers.ts' + +describe('generatedMatcher', () => { + it('applies lines in order, with unset and unspecified values overriding an earlier set', () => { + const generated = generatedMatcher([ + '# comment', + '', + '[attr]binary -diff -merge -text', + '"quoted name.json" linguist-generated', + 'build/ linguist-generated', + '*.schema.json linguist-generated=true', + 'docs/kept.schema.json -linguist-generated', + 'docs/reset.schema.json !linguist-generated', + 'docs/off.schema.json linguist-generated=false', + '/root.gen.ts linguist-generated', + 'gen/*.ts text linguist-generated', + 'other.txt text', + ].join('\r\n')) + + expect(generated('a.schema.json')).toBe(true) + expect(generated('docs/deep/a.schema.json')).toBe(true) + expect(generated('docs/kept.schema.json')).toBe(false) + expect(generated('docs/reset.schema.json')).toBe(false) + expect(generated('docs/off.schema.json')).toBe(false) + expect(generated('root.gen.ts')).toBe(true) + expect(generated('nested/root.gen.ts')).toBe(false) + expect(generated('gen/a.ts')).toBe(true) + expect(generated('src/gen/a.ts')).toBe(false) + expect(generated('build/out.js')).toBe(false) + expect(generated('quoted name.json')).toBe(false) + expect(generated('other.txt')).toBe(false) + }) + + it('marks nothing without attributes', () => { + expect(generatedMatcher('')('a.ts')).toBe(false) + }) +}) + +describe('FileLayers', () => { + const file = (path: string) => untrackedFile(path, new Uint8Array()) + + it('places a file in the test layer first, then the interface layer, else the implementation layer', () => { + const layers = new FileLayers(['**/*.spec.*', '**/locale/*.json'], ['**/package.json', '**/*.json']) + const classified = layers.classify( + ['src/a.ts', 'src/a.spec.ts', 'package.json', 'locale/en.json', 'docs/schema.json', '.github/x.json'].map(file), + 'docs/schema.json linguist-generated\n', + ) + + expect(classified.map(item => [item.path, item.layer])).toEqual([ + ['src/a.ts', 'implementation'], + ['src/a.spec.ts', 'test'], + ['package.json', 'interface'], + ['locale/en.json', 'test'], + ['docs/schema.json', 'test'], + ['.github/x.json', 'interface'], + ]) + }) + + it('places every file in the implementation layer without globs or attributes', () => { + expect(new FileLayers([], []).classify([file('a.spec.ts')], '')).toMatchObject([{ layer: 'implementation' }]) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts index 0a2d95cdfc..1019374d67 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts @@ -8,8 +8,11 @@ import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' import { inspectCheckout } from '../src/git.ts' import { FilterConfigError, localChanges, localDiff } from '../src/local-diff.ts' import type { DiffConfig } from '../src/local-diff.ts' +import { FileLayers } from '../src/layers.ts' import { git, gitContext, plainSession, repository, sandboxRecord, scratch } from './harness.ts' +const LAYERS = new FileLayers([], []) + const CONFIG: DiffConfig = { gitCommand: 'git', gitTimeoutMs: 10_000, graceMs: 500, maxOutputBytes: 1_048_576, maxDiffBytes: 1_048_576, maxUntrackedFiles: 100, } @@ -54,7 +57,7 @@ describe('diff helper restrictions', () => { const spawn = vi.spyOn(b.ctx.subprocess, 'spawn') try { - await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) const diffs = spawn.mock.calls.map(([spec]) => spec).filter(spec => spec.argv.includes('diff')) expect(diffs).toHaveLength(2) @@ -90,7 +93,7 @@ describe('diff helper restrictions', () => { expect(await readFile(marker, 'utf8')).toBe('ran') await rm(marker) - await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(marker)).rejects.toThrow() }) @@ -103,7 +106,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', 'filter.demo.clean', `${b.command} clean`) await writeFile(join(b.repo, 'tracked.txt'), 'initial\r\n') - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) const changes = await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) expect(diff.files).toEqual([]) expect(changes?.files.some(file => file.path === 'tracked.txt')).toBe(false) @@ -124,7 +127,7 @@ describe('diff helper restrictions', () => { const index = await readFile(join(b.repo, '.git', 'index')) const indexStat = await stat(join(b.repo, '.git', 'index')) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) const changes = await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) expect(diff.files.find(file => file.path === 'tracked.txt')?.hunks.flatMap(hunk => hunk.lines)).toEqual(['-initial', '+changed']) @@ -145,7 +148,7 @@ describe('diff helper restrictions', () => { expect(await readFile(b.marker, 'utf8')).toBe('ran') await rm(b.marker) - await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(b.marker)).rejects.toThrow() }) @@ -156,7 +159,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', key, b.command) await writeFile(join(b.repo, 'tracked.txt'), 'changed\n') - await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(b.marker)).rejects.toThrow() }) @@ -170,7 +173,7 @@ describe('diff helper restrictions', () => { await writeFile(join(nested, 'tracked.txt'), 'dirty\n') await git(nested, 'config', 'core.fsmonitor', b.command) await git(b.repo, 'config', 'diff.submodule', 'diff') - const clean = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const clean = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(clean.files).toEqual([]) await expect(access(b.marker)).rejects.toThrow() @@ -179,7 +182,7 @@ describe('diff helper restrictions', () => { await git(nested, 'config', 'user.email', 'forge@example.invalid') await git(nested, '-c', 'commit.gpgSign=false', 'commit', '-am', 'nested change') await git(nested, 'config', 'core.fsmonitor', b.command) - const changed = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const changed = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(changed.files.map(file => file.path)).toEqual(['nested']) expect(changed.files[0]?.hunks.flatMap(hunk => hunk.lines).join('\n')).toContain('Subproject commit') await expect(access(b.marker)).rejects.toThrow() @@ -190,7 +193,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', `filter.${'long'.repeat(200)}.clean`, b.command) await writeFile(join(b.repo, '.gitattributes'), `tracked.txt filter=${'long'.repeat(200)}\n`) await writeFile(join(b.repo, 'tracked.txt'), 'changed\n') - await expect(localDiff(b.ctx, { ...CONFIG, maxDiffBytes: 128 }, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)) + await expect(localDiff(b.ctx, { ...CONFIG, maxDiffBytes: 128 }, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)) .rejects.toBeInstanceOf(FilterConfigError) await expect(localChanges(b.ctx, { ...CONFIG, maxOutputBytes: 128 }, b.session, b.inspection, null, b.signal)) .rejects.toBeInstanceOf(FilterConfigError) @@ -203,7 +206,7 @@ describe('diff helper restrictions', () => { const resolve = vi.spyOn(b.ctx.subprocess, 'resolveExecutable').mockRejectedValue(failure) const spawn = vi.spyOn(b.ctx.subprocess, 'spawn') try { - await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)) + await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)) .rejects.toMatchObject({ name: 'FilterConfigError', cause: failure }) expect(spawn).not.toHaveBeenCalled() } finally { resolve.mockRestore(); spawn.mockRestore() } @@ -218,9 +221,9 @@ describe('diff helper restrictions', () => { await git(b.repo, 'commit', '-m', 'pointer') await git(b.repo, 'config', 'filter.lfs.process', b.command) await git(b.repo, 'config', 'filter.lfs.required', 'true') - await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)).resolves.toMatchObject({ files: [] }) + await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)).resolves.toMatchObject({ files: [] }) await writeFile(join(b.repo, 'asset.bin'), Uint8Array.from([0, 1, 2, 3])) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(diff.files).toMatchObject([{ path: 'asset.bin', binary: true, hunks: [] }]) await expect(access(b.marker)).rejects.toThrow() }) @@ -241,7 +244,7 @@ describe('diff helper restrictions', () => { expect(await readFile(b.marker, 'utf8')).toBe('ran') await rm(b.marker) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(diff.files).toMatchObject([{ path: 'asset.txt', additions: 1, deletions: 3 }]) await expect(access(b.marker)).rejects.toThrow() }) diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index 53e1a4a925..7c7f74b9c6 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -7,9 +7,11 @@ import { FsError } from '@deepseek-ai/dsh-fs' import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, forkPoint, localChanges, localDiff, localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, forkPoint, localChanges, localCommits, localDiff, + localText, NoForkPoint, } from '../src/local-diff.ts' -import type { DiffConfig } from '../src/local-diff.ts' +import type { DiffConfig, ForkPoint } from '../src/local-diff.ts' +import { FileLayers } from '../src/layers.ts' import type { ForgeLocalScope, ForgeSessionWorktree } from '../src/types.ts' import { git, gitContext, plainSession, repository, sandboxRecord, scratch } from './harness.ts' @@ -17,6 +19,9 @@ const CONFIG: DiffConfig = { gitCommand: 'git', gitTimeoutMs: 10_000, graceMs: 500, maxOutputBytes: 1_048_576, maxDiffBytes: 1_048_576, maxUntrackedFiles: 100, } +/** Text files form the `test` layer and JSON files the `interface` layer. */ +const LAYERS = new FileLayers(['**/untracked.txt'], ['**/*.json']) + const cleanups: (() => Promise)[] = [] afterEach(async () => { @@ -203,14 +208,14 @@ describe('baseBranches', () => { describe('localDiff', () => { it.each([ - [{ kind: 'branch', base: null }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], + [{ kind: 'branch', base: null, commits: null }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'uncommitted' }, null, ['staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'unstaged' }, null, ['tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'staged' }, null, ['staged.txt added']], ] as const)('reads the %o scope with untracked files last, leaving out ignored files and nested repositories', async (scope, base, files) => { const { repo, fork } = await forked(await directory()) const ctx = await context(repo) - const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, scope, signal) + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, scope, LAYERS, signal) expect(diff.base).toBe(base) expect(diff.omitted).toBe(0) @@ -219,7 +224,7 @@ describe('localDiff', () => { it('carries the hunks of tracked and untracked files', async () => { const { repo, fork } = await forked(await directory()) - const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, { kind: 'unstaged' }, signal) + const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, { kind: 'unstaged' }, LAYERS, signal) expect(diff.files.map(file => [file.additions, file.deletions, file.hunks.flatMap(hunk => hunk.lines)])).toEqual([ [1, 0, [' initial', '+changed']], @@ -230,7 +235,7 @@ describe('localDiff', () => { it('refuses the branch scope without a fork point', async () => { const { repo } = await forked(await directory()) - await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch', base: null }, signal)).rejects.toBeInstanceOf(NoForkPoint) + await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch', base: null, commits: null }, LAYERS, signal)).rejects.toBeInstanceOf(NoForkPoint) }) it('compares a branch without commits with the empty tree', async () => { @@ -242,7 +247,7 @@ describe('localDiff', () => { const ctx = await context(repo) for (const kind of ['staged', 'uncommitted'] as const) { - const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, null, { kind }, signal) + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, null, { kind }, LAYERS, signal) expect(diff.files.map(file => [file.path, file.status])).toEqual([['first.txt', 'added']]) } }) @@ -251,7 +256,7 @@ describe('localDiff', () => { const { repo, fork } = await forked(await directory()) await writeFile(join(repo, 'tracked.txt'), 'line\n'.repeat(400)) - await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) + await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal)) .rejects.toBeInstanceOf(DiffTooLarge) }) @@ -269,7 +274,7 @@ describe('localDiff', () => { return await read(target, readSignal, maxBytes) }) const config = { ...CONFIG, maxDiffBytes: 2048, maxUntrackedFiles: 4 } - const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal) + const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal) expect(diff.files.filter(file => file.untracked).map(file => [file.path, file.binary, file.oversized, file.additions])).toEqual([ ['more/big.txt', false, true, 0], @@ -284,13 +289,137 @@ describe('localDiff', () => { const ctx = await context(repo) vi.spyOn(ctx.fs, 'readBytes').mockRejectedValue(new Error('disk on fire')) - await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal)) .rejects.toThrow('disk on fire') }) }) +describe('review layers', () => { + it('classifies files by the globs and the root .gitattributes of the working tree, or of the index for the staged scope', async () => { + const { repo, fork } = await forked(await directory()) + const point = { commit: fork, label: 'origin/main', worktree: false } + await writeFile(join(repo, 'config.json'), '{}\n') + await writeFile(join(repo, '.gitattributes'), 'tracked.txt linguist-generated\n') + const ctx = await context(repo) + const layers = async (scope: ForgeLocalScope): Promise => + (await localDiff(ctx, CONFIG, plainSession(repo), repo, point, scope, LAYERS, signal)).files.map(file => `${file.path} ${file.layer}`) + + expect(await layers({ kind: 'unstaged' })).toEqual([ + 'tracked.txt test', '.gitattributes implementation', 'config.json interface', 'untracked.txt test', + ]) + await writeFile(join(repo, '.gitattributes'), 'staged.txt linguist-generated\n') + await git(repo, 'add', '.gitattributes') + await writeFile(join(repo, '.gitattributes'), '') + expect(await layers({ kind: 'staged' })).toEqual(['.gitattributes implementation', 'staged.txt test']) + expect(await layers({ kind: 'uncommitted' })).toEqual([ + '.gitattributes implementation', 'staged.txt implementation', 'tracked.txt implementation', 'config.json interface', 'untracked.txt test', + ]) + }) + + it('reads no attributes for a staged scope without .gitattributes and stops at an unreadable working tree file', async () => { + const { repo, fork } = await forked(await directory()) + const ctx = await context(repo) + const point = { commit: fork, label: 'origin/main', worktree: false } + + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'staged' }, LAYERS, signal)) + .resolves.toMatchObject({ files: [{ path: 'staged.txt', layer: 'implementation' }] }) + await writeFile(join(repo, '.gitattributes'), Uint8Array.from([0x74, 0, 0x74])) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'unstaged' }, LAYERS, signal)) + .resolves.toMatchObject({ files: [{ path: 'tracked.txt', layer: 'implementation' }, { path: '.gitattributes' }, { path: 'untracked.txt' }] }) + const read = ctx.fs.readBytes.bind(ctx.fs) + vi.spyOn(ctx.fs, 'readBytes').mockImplementation(async (target, readSignal, maxBytes) => { + if (ctx.fs.processPath(target).endsWith('.gitattributes')) throw new FsError('denied', 'FS_PERMISSION_DENIED') + return await read(target, readSignal, maxBytes) + }) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'unstaged' }, LAYERS, signal)).rejects.toThrow('denied') + }) +}) + +describe('commits of the branch scope', () => { + /** {@link forked} with two more commits on `feat`, `second.txt` and then `.gitattributes` with a generated `third.json`. */ + async function committed(): Promise<{ readonly repo: string; readonly point: ForkPoint; readonly shas: readonly string[] }> { + const { repo, fork } = await forked(await directory()) + await git(repo, 'commit', '--quiet', '-m', 'staged') + await writeFile(join(repo, 'second.txt'), 'two\n') + await git(repo, 'add', 'second.txt') + await git(repo, 'commit', '--quiet', '-m', 'second') + await writeFile(join(repo, '.gitattributes'), 'third.json linguist-generated\n') + await writeFile(join(repo, 'third.json'), '{}\n') + await git(repo, 'add', '.gitattributes', 'third.json') + await git(repo, 'commit', '--quiet', '-m', 'third') + const shas = (await git(repo, 'rev-list', '--reverse', `${fork}..HEAD`)).split('\n') + return { repo, point: { commit: fork, label: 'origin/main', worktree: false }, shas } + } + + it('lists the commits between the fork point and HEAD oldest first, bounded by the limit', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const runner = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) + + const listed = await localCommits(runner, point, 10) + expect(listed).toMatchObject({ headSha: shas.at(-1), truncated: false }) + expect(listed.commits.map(commit => [commit.title, commit.author])).toEqual([ + ['committed', 'Forge fixture'], ['staged', 'Forge fixture'], ['second', 'Forge fixture'], ['third', 'Forge fixture'], + ]) + expect(listed.commits.map(commit => commit.sha)).toEqual(shas) + expect(listed.commits.map(commit => commit.parent)).toEqual([point.commit, ...shas.slice(0, -1)]) + expect(Date.parse(listed.commits[0]?.authoredAt ?? '')).not.toBeNaN() + await expect(localCommits(runner, point, 2)).resolves.toMatchObject({ truncated: true, commits: [{ title: 'committed' }, { title: 'staged' }] }) + }) + + it('reads the committed changes of consecutive commits with the attributes of the last one, without working tree changes', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const range = async (from: number, to: number): Promise => { + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, point, + { kind: 'branch', base: null, commits: { from: shas[from] ?? '', to: shas[to] ?? '' } }, LAYERS, signal) + expect(diff).toMatchObject({ base: 'origin/main', omitted: 0 }) + return diff.files.map(file => `${file.path} ${file.layer}`) + } + + expect(await range(2, 2)).toEqual(['second.txt implementation']) + expect(await range(1, 3)).toEqual(['.gitattributes implementation', 'second.txt implementation', 'staged.txt implementation', 'third.json test']) + await expect(localText(ctx, CONFIG, plainSession(repo), repo, + { kind: 'branch', base: null, commits: { from: shas[2] ?? '', to: shas[2] ?? '' } }, 'second.txt', signal)).resolves.toBe('two\n') + }) + + it('compares a first commit without a parent with the empty tree', async () => { + const { repo, point } = await committed() + await git(repo, 'checkout', '--quiet', '--orphan', 'other') + await git(repo, 'rm', '--quiet', '-r', '-f', '--cached', '.') + await writeFile(join(repo, 'orphan.txt'), 'root\n') + await git(repo, 'add', 'orphan.txt') + await git(repo, 'commit', '--quiet', '-m', 'orphan') + const orphan = await git(repo, 'rev-parse', 'HEAD') + await git(repo, 'checkout', '--quiet', '--force', 'feat') + await git(repo, 'merge', '--quiet', '--allow-unrelated-histories', '--no-edit', 'other') + const ctx = await context(repo) + + const listed = await localCommits(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), point, 10) + expect(listed.commits.find(commit => commit.sha === orphan)?.parent).toBeNull() + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, point, + { kind: 'branch', base: null, commits: { from: orphan, to: orphan } }, LAYERS, signal) + expect(diff.files.map(file => [file.path, file.status])).toEqual([['orphan.txt', 'added']]) + }) + + it('refuses commits that are not full object names, not on the branch, or out of order', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const read = (from: string, to: string): Promise => + localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'branch', base: null, commits: { from, to } }, LAYERS, signal) + const [first = '', second = ''] = shas + + await expect(read('HEAD', second)).rejects.toBeInstanceOf(CommitsMissing) + await expect(read(first, '--output=x')).rejects.toBeInstanceOf(CommitsMissing) + await expect(read(point.commit, second)).rejects.toThrow('The chosen commits are no longer on the branch') + await expect(read(second, first)).rejects.toThrow('The chosen commits are no longer on the branch') + await expect(localText(ctx, CONFIG, plainSession(repo), repo, + { kind: 'branch', base: null, commits: { from: first, to: 'HEAD' } }, 'second.txt', signal)).rejects.toBeInstanceOf(CommitsMissing) + }) +}) + describe('localText', () => { - const branch: ForgeLocalScope = { kind: 'branch', base: null } + const branch: ForgeLocalScope = { kind: 'branch', base: null, commits: null } it('reads the working tree, or the index for the staged scope', async () => { const { repo } = await forked(await directory()) diff --git a/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts b/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts index ab0d6ff28c..b66cc97290 100644 --- a/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts @@ -5,6 +5,11 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import { PatchCache } from '../src/patch-cache.ts' +/** A patch without attributes. */ +function entry(patch: string): { readonly patch: string; readonly attributes: string } { + return { patch, attributes: '' } +} + function key(number: number): ChangeRequestKey { return changeRequestKey({ repository: { forge: 'fake', host: 'fake.test', owner: 'octo', name: 'demo' }, number }) } @@ -14,35 +19,43 @@ describe('PatchCache', () => { const cache = new PatchCache(100) expect(cache.get(key(1), 'v1')).toBeUndefined() - cache.set(key(1), 'v1', 'one') - expect(cache.get(key(1), 'v1')).toBe('one') + cache.set(key(1), 'v1', entry('one')) + expect(cache.get(key(1), 'v1')).toEqual(entry('one')) expect(cache.get(key(1), 'v2')).toBeUndefined() - cache.set(key(1), 'v2', 'two') + cache.set(key(1), 'v2', entry('two')) expect(cache.get(key(1), 'v1')).toBeUndefined() - expect(cache.get(key(1), 'v2')).toBe('two') + expect(cache.get(key(1), 'v2')).toEqual(entry('two')) }) it('drops the least recently read patches once the kept patches exceed the bound in UTF-8 bytes', () => { const cache = new PatchCache(10) - cache.set(key(1), 'v', 'aaaa') - cache.set(key(2), 'v', 'bbb') - expect(cache.get(key(1), 'v')).toBe('aaaa') + cache.set(key(1), 'v', entry('aaaa')) + cache.set(key(2), 'v', entry('bbb')) + expect(cache.get(key(1), 'v')).toEqual(entry('aaaa')) // Two three-byte characters bring the total to 13 bytes, so #2, read least recently, leaves. - cache.set(key(3), 'v', '变更') + cache.set(key(3), 'v', entry('变更')) expect(cache.get(key(2), 'v')).toBeUndefined() - expect(cache.get(key(1), 'v')).toBe('aaaa') - expect(cache.get(key(3), 'v')).toBe('变更') + expect(cache.get(key(1), 'v')).toEqual(entry('aaaa')) + expect(cache.get(key(3), 'v')).toEqual(entry('变更')) + }) + + it('counts the attributes kept beside a patch toward the bound', () => { + const cache = new PatchCache(6) + cache.set(key(1), 'v', { patch: 'aaa', attributes: 'bbbb' }) + expect(cache.get(key(1), 'v')).toBeUndefined() + cache.set(key(1), 'v', { patch: 'aaa', attributes: 'bbb' }) + expect(cache.get(key(1), 'v')).toEqual({ patch: 'aaa', attributes: 'bbb' }) }) it('keeps no patch over the bound, dropping the earlier version all the same', () => { const cache = new PatchCache(4) - cache.set(key(1), 'v1', 'one') - cache.set(key(1), 'v2', 'large') + cache.set(key(1), 'v1', entry('one')) + cache.set(key(1), 'v2', entry('large')) expect(cache.get(key(1), 'v1')).toBeUndefined() expect(cache.get(key(1), 'v2')).toBeUndefined() - cache.set(key(1), 'v3', 'four') - expect(cache.get(key(1), 'v3')).toBe('four') + cache.set(key(1), 'v3', entry('four')) + expect(cache.get(key(1), 'v3')).toEqual(entry('four')) }) }) diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index 13474f6353..65f55fefac 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -10,6 +10,7 @@ "src/diff.ts", "src/git.ts", "src/local-diff.ts", + "src/layers.ts", "src/panel.ts", "src/parse.ts", "src/patch-cache.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..8633c2464e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9246,6 +9246,9 @@ importers: diff: specifier: ^9.0.0 version: 9.0.0 + picomatch: + specifier: ^4.0.7 + version: 4.0.7 zod: specifier: 4.6.6 version: 4.6.6 @@ -9367,6 +9370,9 @@ importers: '@testing-library/react': specifier: ^16.3.3 version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@types/picomatch': + specifier: ^4.0.3 + version: 4.0.3 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -31306,6 +31312,10 @@ snapshots: optionalDependencies: picomatch: 4.0.4 + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + fetch-blob@3.2.0: dependencies: node-domexception: 1.0.0 @@ -34001,8 +34011,8 @@ snapshots: tinyglobby@0.2.17: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyrainbow@3.1.0: {} From c313392bf822d0e1c75e461970be58b0fd8c583f Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:51:22 +0800 Subject: [PATCH 075/438] feat(forge-panel): review changes by layer, mark files viewed, and view chosen commits The changes view gains a lens of All, Interface, Implementation, and Tests that spans the file tree above it, a switch that hides test files from the tree and the diff, and a viewed checkbox on each file header that collapses the file. The toolbar counts viewed files and V toggles the file being read. Marks are kept per Session, source, path, and change digest in browser storage, so a file that changes again reads as changed since viewed. All commits beside Submit review, and beside the base branch of the Branch scope, shows one commit or a Shift run of commits. --- .../forge-panel/changes-view.expected.md | 6 + .../forge-panel/file-tree-toggle.expected.md | 10 + .../filter-config-failed.expected.md | 1 + .../forge-panel/review-layers.expected.md | 42 +++ apps/web/tests/forge-panel.e2e.ts | 201 +++++++++- docs/config-catalog.md | 15 +- docs/config-catalog.zh.md | 15 +- docs/subsystems/forge.i18n.yaml | 8 +- docs/subsystems/forge.md | 164 ++++++++- docs/subsystems/forge.zh.md | 164 ++++++++- .../client-ui-forge/README.i18n.yaml | 16 +- .../experimental/client-ui-forge/README.md | 21 +- .../experimental/client-ui-forge/README.zh.md | 21 +- .../src/client/ChangesTab.module.css | 142 ++++++- .../client-ui-forge/src/client/ChangesTab.tsx | 346 +++++++++++++----- .../src/client/CommitMenu.module.css | 130 +++++++ .../client-ui-forge/src/client/CommitMenu.tsx | 162 ++++++++ .../client-ui-forge/src/client/DiffFile.tsx | 18 +- .../src/client/FileTreePane.tsx | 7 +- .../src/client/ReviewControls.module.css | 147 ++++++++ .../src/client/ReviewControls.tsx | 148 ++++++++ .../src/client/changes-store.ts | 67 +++- .../client-ui-forge/src/client/locales.ts | 216 +++++++++++ .../client-ui-forge/src/client/mount.ts | 12 +- .../src/client/review-queue.ts | 18 +- .../client-ui-forge/src/client/review.ts | 24 +- .../src/client/viewed-files.ts | 145 ++++++++ .../tests/changes-address.client.spec.ts | 31 +- .../tests/changes-tab.client.spec.tsx | 242 +++++++++++- .../tests/diff-review.client.spec.tsx | 6 +- .../tests/diff-rows.client.spec.ts | 2 +- .../tests/file-tree.client.spec.tsx | 6 +- .../tests/mount.client.spec.ts | 34 +- .../tests/review-controls.client.spec.tsx | 229 ++++++++++++ .../tests/review.client.spec.tsx | 54 ++- .../tests/viewed-files.client.spec.ts | 92 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 68 +++- scripts/gen-cordis-catalog.ts | 5 + scripts/type-equiv.manifest.json | 25 ++ 39 files changed, 2801 insertions(+), 259 deletions(-) create mode 100644 apps/web/tests/expected/forge-panel/review-layers.expected.md create mode 100644 packages/experimental/client-ui-forge/src/client/CommitMenu.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/CommitMenu.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewControls.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewControls.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/viewed-files.ts create mode 100644 packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx create mode 100644 packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md index b4f0445c07..1e3111ba0c 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -1,8 +1,12 @@ - img "变更请求状态:需要处理" - text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 - button "提交评审" - button "在浏览器中打开" - button "全部 2 个文件" +- button "分层透镜:全部": 全部 +- switch "隐藏测试文件" +- progressbar "已审阅的文件": 已审阅 0 / 2 - text: +4 −2 - button "刷新变更" - button "全部折叠" @@ -11,6 +15,7 @@ - region "全部 2 个文件": - button "收起 panel.md" [expanded] - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" - button "panel.md 的更多操作" - button "选择第 R1 行": "1" - text: "+ # Panel" @@ -18,6 +23,7 @@ - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" - button "panel.ts 的更多操作" - button "选择第 L1 行": "1" - text: export const n1 = 1 diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md index 72d7382c18..e7f09431a2 100644 --- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -1,8 +1,16 @@ - img "变更请求状态:需要处理" - text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 - button "提交评审" - button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 2" [checked] + - radio "接口 0" + - radio "实现 2" + - radio "测试 0" - button "全部 2 个文件" +- switch "隐藏测试文件" +- progressbar "已审阅的文件": 已审阅 0 / 2 - text: +4 −2 - button "刷新变更" - button "全部折叠" @@ -12,6 +20,7 @@ - region "全部 2 个文件": - button "收起 panel.md" [expanded] - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" - button "panel.md 的更多操作" - button "选择第 R1 行": "1" - text: "+ # Panel" @@ -19,6 +28,7 @@ - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" - button "panel.ts 的更多操作" - button "选择第 L1 行": "1" - text: export const n1 = 1 diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md index 114cf607bf..d5e6cce057 100644 --- a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md +++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md @@ -1,6 +1,7 @@ - text: main - button "基准分支:origin/main": origin/main - text: 包含未提交的修改 +- button "查看的提交:全部提交": 全部提交 - button "创建变更请求" - button "分支" - button "全部 0 个文件" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-layers.expected.md b/apps/web/tests/expected/forge-panel/review-layers.expected.md new file mode 100644 index 0000000000..e160dbbd40 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-layers.expected.md @@ -0,0 +1,42 @@ +- img "变更请求状态:需要处理" +- text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 +- button "提交评审" +- button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 3" [checked] + - radio "接口 1" + - radio "实现 2" + - radio "测试" [disabled] +- button "全部 3 个文件" +- switch "隐藏测试文件" [checked] +- progressbar "已审阅的文件": 已审阅 2 / 3 +- text: +5 −2 +- button "刷新变更" +- button "全部折叠" +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- button "将文件树移到右侧" [expanded] +- region "全部 3 个文件": + - button "展开 panel.md" + - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" [checked] + - button "panel.md 的更多操作" + - button "展开 panel.ts" + - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" [checked] + - button "panel.ts 的更多操作" + - button "收起 package.json" [expanded] + - text: package.json 新文件 +1 −0 + - checkbox "将 package.json 标记为已审阅" + - button "package.json 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ { \"name\": \"demo\" }" +- separator "调整文件树宽度" +- navigation "全部 3 个文件": + - textbox "筛选文件…" + - button "docs" [expanded] + - button "docs/panel.md": panel.md +2 −0 + - button "src" [expanded] + - button "src/panel.ts": panel.ts +2 −2 + - button "package.json": package.json +1 −0 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 44f24a6a58..9335003dc1 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -45,8 +45,9 @@ const run = promisify(execFile) * `gh pr ready 9` and the REST merge of pull request 9 change what later * queries report, through `state.json`. `gh pr diff N` prints `pr-N.diff`, or * fails with `pr-N.refused` on standard error when that file exists, and the raw - * contents API serves `contents.json`, keyed by `path@commit`. Every invocation - * is appended to `calls.jsonl`. + * contents API serves `contents.json`, keyed by `path@commit`. The commit listing of + * pull request 7 serves `commits.json`, oldest first, and the compare API serves + * `compare.json`, keyed by `base...head`. Every invocation is appended to `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -96,6 +97,16 @@ if (args[0] === 'pr' && args[1] === 'diff') { await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve)) process.exit(0) } +if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.diff') { + const range = args[5].slice('repos/octo/demo/compare/'.length) + const patch = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined + if (patch === undefined) { + process.stderr.write('gh: Not Found (HTTP 404)\\n') + process.exit(1) + } + process.stdout.write(patch) + process.exit(0) +} if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.raw+json') { const [resource, query] = args[5].split('?') const path = decodeURIComponent(resource.slice('repos/octo/demo/contents/'.length)) @@ -139,6 +150,17 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } }] }, }, } + if (query.includes('commits(first: $first')) { + const commits = existsSync(join(here, 'commits.json')) ? JSON.parse(readFileSync(join(here, 'commits.json'), 'utf8')) : [] + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40), commits: { + totalCount: commits.length, pageInfo: { hasNextPage: false, endCursor: null }, + nodes: commits.map(commit => ({ commit: { + oid: commit.sha, messageHeadline: commit.title, authoredDate: '2026-10-08T00:00:00Z', + author: { name: 'Octo', user: { login: 'octo' } }, parents: { nodes: [{ oid: commit.parent }] }, + } })), + } } } } })) + process.exit(0) + } if (query.includes('node(id: $id)')) { process.stdout.write(JSON.stringify({ data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, @@ -204,6 +226,50 @@ const PR7_DIFF = [ '', ].join('\n') +/** A patch section that adds `lines` as the new file `path`. */ +function addedSection(path: string, lines: readonly string[]): string[] { + return [`diff --git a/${path} b/${path}`, 'new file mode 100644', 'index 0000000..4444444', '--- /dev/null', `+++ b/${path}`, + `@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)] +} + +/** Commits of pull request 7 in the review fixture, oldest first; the last is its head. */ +const REVIEW_COMMITS = [ + { sha: '1'.repeat(40), parent: 'f'.repeat(40), title: 'Add the pull request panel' }, + { sha: '2'.repeat(40), parent: '1'.repeat(40), title: 'Test the panel and translate it' }, + { sha: HEAD7, parent: '2'.repeat(40), title: 'Publish the panel schema' }, +] as const + +/** New files of each review fixture commit after the first, which changes `src/panel.ts` and adds `docs/panel.md`. */ +const REVIEW_SECTIONS = { + test: [ + ...addedSection('src/panel.spec.ts', ['it(\'shows the panel\', () => {})']), + ...addedSection('locale/zh.json', ['{ "title": "面板" }']), + ], + schema: [ + ...addedSection('package.json', ['{ "name": "demo" }']), + ...addedSection('docs/schema.json', ['{ "type": "object" }']), + ], +} + +/** + * Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is + * interface, and the spec, the locale dictionary, and `docs/schema.json`, which `.gitattributes` marks generated, are tests. + */ +const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n') + +/** Write the review fixture of pull request 7: its patch, commits, commit ranges, and root `.gitattributes`. */ +async function writeReviewFixture(root: string): Promise { + await writeFile(join(root, 'pr-7.diff'), REVIEW_DIFF) + await writeFile(join(root, 'commits.json'), JSON.stringify(REVIEW_COMMITS)) + await writeFile(join(root, 'compare.json'), JSON.stringify({ + [`${'1'.repeat(40)}...${'2'.repeat(40)}`]: [...REVIEW_SECTIONS.test, ''].join('\n'), + [`${'1'.repeat(40)}...${HEAD7}`]: [...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n'), + })) + const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record + for (const commit of ['2'.repeat(40), HEAD7]) contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\n' + await writeFile(join(root, 'contents.json'), JSON.stringify(contents)) +} + async function git(cwd: string, ...args: string[]): Promise { const { stdout } = await run('git', args, { cwd, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } }) return stdout.trim() @@ -1604,3 +1670,134 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor() expect(tripwire.pageErrors).toEqual([]) }) + +/** Open the change request view of pull request 7 in full screen, its tree on the left. */ +async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly view: ReturnType; readonly sessionId: SessionId }> { + const { settled } = await sendPrompt(page, scaffold) + const sessionId = await settled + const session = scaffold.ctx.sessions.get(sessionId) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() + await page.getByRole('button', { name: '全屏', exact: true }).click() + const view = page.locator('[data-forge-changes="change"]') + await view.locator('[data-forge-diff-file="src/panel.ts"]').waitFor({ timeout: 20_000 }) + return { view, sessionId } +} + +/** Paths of the diff sections a changes view shows, in order. */ +async function shownPaths(view: ReturnType): Promise<(string | null)[]> { + return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))) +} + +it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers') + await writeReviewFixture(root) + const { view } = await openReview(page, scaffold) + const lens = view.getByRole('radiogroup', { name: '分层透镜', exact: true }) + const tree = view.getByRole('navigation') + await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部6', '接口1', '实现2', '测试3']) + // The lens spans the file tree with the filter field's insets, and its divider continues the tree's border. + const [lensBox, fieldBox, cellBox, treeBox] = await Promise.all([ + lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=..').boundingBox(), tree.locator('xpath=..').boundingBox(), + ]) + if (lensBox === null || fieldBox === null || cellBox === null || treeBox === null) throw new Error('Lens and tree must be visible') + expect([lensBox.x, lensBox.x + lensBox.width]).toEqual([fieldBox.x, fieldBox.x + fieldBox.width]) + expect(cellBox.x + cellBox.width).toBe(treeBox.x + treeBox.width) + + await lens.getByRole('radio', { name: /^接口/ }).click() + await expect.poll(() => shownPaths(view)).toEqual(['package.json']) + await lens.getByRole('radio', { name: /^测试/ }).click() + await expect.poll(() => shownPaths(view)).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts']) + await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click() + await expect.poll(() => shownPaths(view)).toEqual(['docs/panel.md', 'src/panel.ts', 'package.json']) + expect(await tree.getByRole('button', { name: 'src/panel.spec.ts', exact: true }).count()).toBe(0) + expect(await lens.getByRole('radio', { name: /^测试/ }).isDisabled()).toBe(true) + + const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true }) + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 0 / 3') + const docs = view.locator('[data-forge-diff-file="docs/panel.md"]') + await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).check() + await expect.poll(() => docs.getAttribute('data-expanded')).toBe(null) + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 3') + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + await panel.getByText('export const n2 = \'two\'', { exact: true }).first().click() + await page.keyboard.press('v') + await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3') + await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'), + await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + + await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click() + const commits = view.getByRole('button', { name: '查看的提交:全部提交', exact: true }) + await commits.click() + const menu = page.locator('[data-forge-commit-menu]') + await expect.poll(() => menu.getByRole('menuitem').evaluateAll(rows => rows.map(row => row.querySelector('[data-forge-commit]')?.getAttribute('data-forge-commit') ?? 'all'))) + .toEqual(['all', '1'.repeat(40), '2'.repeat(40), HEAD7]) + await menu.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts']) + expect(await view.getByRole('button', { name: '提交评审', exact: true }).isDisabled()).toBe(true) + await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click() + await page.locator(`[data-forge-commit="${HEAD7}"]`).click({ modifiers: ['Shift'] }) + await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).waitFor() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json']) + await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3']) + const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) + expect(calls.filter(args => args[0] === 'api' && args[4] === 'Accept: application/vnd.github.diff').map(args => args[5])).toEqual([ + `repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`, + ]) + await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click() + await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6) + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed') + expect(tripwire.pageErrors).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a mark when the file changes again, and views branch commits', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-review-local', 'normal', { branch: 'feat' }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'main') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await mkdir(join(project, 'src')) + for (const [path, text, message] of [ + ['src/app.ts', 'export const app = 1\n', 'Add the app'], + ['src/app.spec.ts', 'it(\'runs\', () => {})\n', 'Test the app'], + ] as const) { + await writeFile(join(project, path), text) + await git(project, 'add', path) + await git(project, 'commit', '--quiet', '-m', message) + } + await writeFile(join(project, 'notes.md'), 'note\n') + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click() + await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + const card = page.locator('[data-forge-local]') + await card.getByRole('button', { name: /^查看本会话的变更:3 个文件/ }).click({ timeout: 20_000 }) + const local = page.locator('[data-forge-changes="local"]') + const app = local.locator('[data-forge-diff-file="src/app.ts"]') + await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).check({ timeout: 20_000 }) + await expect.poll(() => app.getAttribute('data-expanded')).toBe(null) + + await page.reload() + await page.locator('[data-forge-changes="local"] [data-forge-diff-file="src/app.ts"]').waitFor({ timeout: 20_000 }) + await expect.poll(() => app.getAttribute('data-viewed')).toBe('viewed') + expect(await app.getAttribute('data-expanded')).toBe(null) + await writeFile(join(project, 'src', 'app.ts'), 'export const app = 2\n') + await local.getByRole('button', { name: '刷新变更', exact: true }).click() + await expect.poll(() => app.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed') + await app.getByText('有新改动', { exact: true }).waitFor() + await expect.poll(() => app.getAttribute('data-expanded')).toBe('') + expect(await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).isChecked()).toBe(false) + + await local.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click() + const menu = page.locator('[data-forge-commit-menu]') + await menu.getByRole('menuitem', { name: /Test the app/ }).click() + await expect.poll(() => shownPaths(local), { timeout: 20_000 }).toEqual(['src/app.spec.ts']) + // Without the file tree beside the diff, the toolbar offers the lens as a menu. + await local.getByRole('button', { name: '分层透镜:全部', exact: true }).click() + await expect.poll(() => page.getByRole('menu').getByRole('menuitem').allTextContents()).toEqual(['全部1', '接口0', '实现0', '测试1']) + await page.keyboard.press('Escape') + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..eb88c30e25 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1049,7 +1049,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1077,6 +1077,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } ``` @@ -1142,7 +1151,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:266`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1178,6 +1187,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..3188fdb42d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1051,7 +1051,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1079,6 +1079,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } ``` @@ -1144,7 +1153,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:266`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1180,6 +1189,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } ``` diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 3f4994aa39..5c531ea679 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -6,8 +6,8 @@ en: 3990a17e12c66a23 zh: 4170c33e49248f8f /forges/providers-and-change-requests: - en: 4ec7d1892b4067db - zh: 6bb70d21ae3d7a89 + en: e5d807b29f553751 + zh: e0b25d9e964f988e /forges/status-polling: en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 @@ -18,5 +18,5 @@ en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: dbc28e731f357edf - zh: a1977fafc0651427 + en: 5fcac3740f59ffc0 + zh: a95a881cd06a59d8 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f36141ea1b..4f4febadfe 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -74,9 +74,49 @@ interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } ``` +```ts type-equiv +/** One commit of a change request. */ +interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} +``` + +```ts type-equiv +/** The commits of a change request at one head commit. */ +interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} +``` + +`ctx.forge.commits` and `ctx.forge.compare` delegate to a provider that implements both; otherwise `commits` resolves to undefined and `compare` to an `unavailable` failure, so the forge panel offers its commit picker only where the provider reads commits. + ```ts type-equiv /** Whether a provider can reach one host with the current credentials. */ interface ForgeReadiness { @@ -568,7 +608,20 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. +The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. + +```ts type-equiv +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} +``` ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -576,9 +629,10 @@ type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -640,6 +694,14 @@ interface ForgeDiffHunk { type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ``` +```ts type-equiv +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +type ForgeFileLayer = 'interface' | 'implementation' | 'test' +``` + ```ts type-equiv /** One changed file of a diff. */ interface ForgeDiffFile { @@ -661,6 +723,13 @@ interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } ``` @@ -677,22 +746,27 @@ interface ForgeLocalDiff { ``` ```ts type-equiv -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } ``` +```ts type-equiv +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +type ForgeLocalCommits = ForgeCommitList +``` + ```ts type-equiv /** One file the `branch` scope changes, without its hunks. */ interface ForgeChangedFile { @@ -822,6 +896,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. @@ -975,21 +1070,36 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise +/** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ +@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise + /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise @@ -1006,19 +1116,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ -@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ +@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise /** * Read one file of a change request's repository at a commit, which diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 61c53fbd6c..e731e65c23 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -74,9 +74,49 @@ interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } ``` +```ts type-equiv +/** One commit of a change request. */ +interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} +``` + +```ts type-equiv +/** The commits of a change request at one head commit. */ +interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} +``` + +`ctx.forge.commits` 与 `ctx.forge.compare` 委托给同时实现两者的提供方;否则 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此 forge 面板只在提供方能读取提交时提供提交选择器。 + ```ts type-equiv /** Whether a provider can reach one host with the current credentials. */ interface ForgeReadiness { @@ -568,7 +608,20 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 +变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更,或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 + +```ts type-equiv +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} +``` ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -576,9 +629,10 @@ type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -640,6 +694,14 @@ interface ForgeDiffHunk { type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ``` +```ts type-equiv +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +type ForgeFileLayer = 'interface' | 'implementation' | 'test' +``` + ```ts type-equiv /** One changed file of a diff. */ interface ForgeDiffFile { @@ -661,6 +723,13 @@ interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } ``` @@ -677,22 +746,27 @@ interface ForgeLocalDiff { ``` ```ts type-equiv -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } ``` +```ts type-equiv +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +type ForgeLocalCommits = ForgeCommitList +``` + ```ts type-equiv /** One file the `branch` scope changes, without its hunks. */ interface ForgeChangedFile { @@ -822,6 +896,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. @@ -975,21 +1070,36 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise +/** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ +@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise + /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise @@ -1006,19 +1116,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ -@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ +@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise /** * Read one file of a change request's repository at a commit, which diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 203cd3e907..445e3f73db 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 1101418b5621ba9d - zh: 4d66052d4708d02c + en: dcde9f0c7c82ab08 + zh: 77a570133b45dbd9 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0c2dd86b5f6b489d - zh: 2f0fce0affa48f59 + en: 1c8c6cfa6ad4b906 + zh: 15a0beb677f6e0fd /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: d62a9841cc34dfdd - zh: 5aa4ffb331c5bb93 + en: 10101427d1e0589b + zh: c981cec12f64eb75 /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 0f795ca1c607af01 - zh: a05ac28fb2313d6e + en: 51f6e22d3f2b7d03 + zh: 252f1ba8b2941b60 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 29afc7d4e6..a24de40f12 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -40,11 +40,13 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. - **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. A file is in Tests when its path matches `testPaths` or the repository's root `.gitattributes` marks it `linguist-generated`, else in Interface when its path matches `interfacePaths`, such as package manifests, configuration, and type declarations, else in Implementation. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first; a click shows one commit and a Shift click the commits from the last one clicked; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and a chosen commit that is gone offers Show all commits. + The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, and `maxCachedDiffBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. @@ -67,11 +69,11 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, and hunks, plus the blob names of a binary change or the content of an untracked binary file, and a layer from picomatch matches of `testPaths` and `interfacePaths`, with dot files included, and from the `linguist-generated` lines of the root `.gitattributes`: the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point with `log --topo-order --reverse`, at most `maxCommits`. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. | Source | Responsibility | |---|---| @@ -82,13 +84,17 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/git.ts`](src/git.ts) | Git queries under Session permissions | | [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order | | [`src/diff.ts`](src/diff.ts) | Patch parsing, untracked files as additions, and numstat records | -| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, new-side text, and the `branch` scope summary | +| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, branch commits, new-side text, and the `branch` scope summary | +| [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | Commit picker | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | Viewed marks kept in the browser | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | @@ -111,7 +117,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t ## Model Experience -Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, and local Branch quotes the base the view compared with. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. #### KV Cache effect @@ -130,9 +136,12 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. - **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. -- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. +- **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. +- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. +- **Review layers** — the Interface layer follows path globs only and keeps whole files; finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. +- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, 250 for GitHub, and a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index f45d0c2568..cdeaac4ac9 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -40,11 +40,13 @@ kind: "package-reference" - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。路径匹配 `testPaths` 或被仓库根目录 `.gitattributes` 标为 `linguist-generated` 的文件属于“测试”;否则路径匹配 `interfacePaths`(例如包清单、配置与类型声明)的文件属于“接口”;其余属于“实现”。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在时提供“查看全部提交”。 + 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles` 与 `maxCachedDiffBytes` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 “全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 @@ -67,11 +69,11 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态与 hunk 组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并用 picomatch(包含点文件)匹配 `testPaths` 与 `interfacePaths`、读取根目录 `.gitattributes` 中的 `linguist-generated` 行来确定分层:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --topo-order --reverse` 列出分叉点之后的提交,最多 `maxCommits` 个。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 | 源码 | 职责 | |---|---| @@ -82,13 +84,17 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 | | [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 | | [`src/diff.ts`](src/diff.ts) | 补丁解析、把未跟踪文件表示为新增,以及 numstat 记录 | -| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、新版本文本与 `branch` 范围摘要 | +| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、分支提交、新版本文本与 `branch` 范围摘要 | +| [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | 提交选择器 | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | 保存在浏览器中的已审阅标记 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -111,7 +117,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 #### KV Cache 影响 @@ -130,9 +136,12 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 - **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 -- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 +- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 +- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 +- **分层**——“接口”层只按路径 glob 划分并保留整个文件;找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 +- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为 250 个),每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 47193f0887..f664c4b2fa 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -91,21 +91,96 @@ } .headerEnd { - flex: none; + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + min-width: 0; margin-left: auto; } + .toolbar { display: flex; flex: none; - align-items: center; - gap: 4px; + align-items: stretch; box-sizing: border-box; - min-height: 38px; - padding: 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); } +/* Spans the file tree's width with the tree's search inset, and its divider continues the tree's border. */ +.lensCell { + display: none; + flex: none; + align-items: center; + box-sizing: border-box; + width: var(--forge-tree-width); + padding: 0 8px; + border-inline-end: 0.5px solid var(--dsw-alias-border-l3); +} + +.toolbar[data-tree='right'] .lensCell { + order: 1; + border-inline-start: 0.5px solid var(--dsw-alias-border-l3); + border-inline-end: 0; +} + +.toolbarMain { + display: flex; + flex: 1; + flex-wrap: wrap; + align-items: center; + gap: 0 4px; + box-sizing: border-box; + min-width: 0; + min-height: 38px; + padding: 5px 8px; +} + +.lensMenu { + display: inline-flex; +} + +@container forge-changes (min-width: 760px) { + .toolbar:not([data-tree='hidden']) .lensCell { + display: flex; + } + + .toolbar:not([data-tree='hidden']) .lensMenu { + display: none; + } +} + +.spacer { + flex: 1; +} + +.progressSlot { + display: inline-flex; +} + +/* Breaks the toolbar's review controls onto a second row where one row is too narrow for them. */ +.rowBreak { + display: none; +} + +@container forge-changes (max-width: 640px) { + .reviewRow { + order: 2; + } + + .rowBreak { + display: block; + flex-basis: 100%; + order: 1; + height: 4px; + } + + .progressSlot { + margin-left: auto; + } +} + .select { display: inline-flex; flex: 0 1 auto; @@ -173,7 +248,6 @@ flex: none; align-items: center; gap: 2px; - margin-left: auto; } .tool { @@ -371,6 +445,62 @@ transform: rotate(-90deg); } +.changedTag { + flex: none; +} + +/* The viewed mark: a native checkbox with its label as one bordered chip, peer to the file menu button. */ +.viewed { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + box-sizing: border-box; + height: 24px; + padding: 0 8px 0 6px; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: var(--dsw-radius-sm); + color: var(--dsw-alias-label-secondary); + white-space: nowrap; + cursor: pointer; + user-select: none; +} + +.viewed input { + margin: 0; + accent-color: var(--dsw-alias-state-business-primary); + cursor: pointer; +} + +.viewed:has(input:checked) { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .viewed:hover { + color: var(--dsw-alias-label-primary); + } +} + +.viewed:has(input:focus-visible) { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.viewed input:focus-visible { + outline: none; +} + +@container forge-changes (max-width: 520px) { + .viewed { + padding: 0 6px; + } + + .viewedLabel { + display: none; + } +} + .badge { flex: none; max-width: 50%; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 983c6b58a3..833585a83a 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -7,7 +7,10 @@ * scope summary changes; a read keeps the previous changes on screen until it settles. */ -import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' +import { + useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent, + type ReactNode, +} from 'react' import clsx from 'clsx' import { Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, @@ -21,10 +24,10 @@ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-rig import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, - ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, + ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' -import type { ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import type { ReviewActions } from './ReviewComposer.tsx' @@ -32,7 +35,10 @@ import { SubmitReview } from './SubmitReview.tsx' import type { ReviewSelection, ReviewSource } from './review.ts' import { BaseMenu } from './BaseMenu.tsx' import { parseChangesAddress, type ChangesSource } from './changes-address.ts' -import type { createChangesStore } from './changes-store.ts' +import type { ChangesLens, createChangesStore } from './changes-store.ts' +import { CommitMenu } from './CommitMenu.tsx' +import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' +import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts' import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' @@ -68,8 +74,16 @@ export interface ChangesTabInjected { readonly diffBases: (query: string, signal: AbortSignal) => Promise> /** Read the new side of one file in a local scope. */ readonly localText: (scope: ForgeLocalScope, path: string) => Promise> - /** Read the changes of a change request by its binding URL; `signal` aborts the read. */ - readonly changeRequestDiff: (url: string, signal: AbortSignal) => Promise> + /** List the commits of the `branch` scope compared with `base`, or with the automatic fork point for null; `signal` aborts the read. */ + readonly localCommits: (base: string | null, signal: AbortSignal) => Promise> + /** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */ + readonly changeRequestDiff: ( + url: string, commits: ForgeCommitRange | null, signal: AbortSignal, + ) => Promise> + /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */ + readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise> + /** The Session's viewed marks, kept in the browser. */ + readonly viewedFiles: ViewedFiles /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Open a URL outside the app. */ @@ -106,8 +120,10 @@ type ChangesData = readonly files: readonly ForgeDiffFile[] /** Binding URL of the change request. */ readonly url: string - /** Head commit the files describe, which supplies unchanged lines. */ + /** Commit the files end at, the head or the last chosen commit, which supplies unchanged lines. */ readonly headSha: string + /** Commits the files cover, or null for the whole change request. */ + readonly commits: ForgeCommitRange | null /** Commits the checkout's branch has beyond the head, or null. */ readonly localAhead: number | null /** Web page of each file at the head. */ @@ -148,6 +164,7 @@ const FAILURE: Partial> = { 'forgePanel/no-fork-point': 'diff.noForkPoint', 'forgePanel/diff-too-large': 'diff.tooLarge', 'forgePanel/filter-config-failed': 'diff.filterConfigFailed', + 'forgePanel/commits-missing': 'commits.missing', } /** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */ @@ -171,6 +188,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T async function readChanges( source: ChangesSource, scope: ForgeLocalScope, + commits: ForgeCommitRange | null, reads: Pick, signal: AbortSignal, ): Promise> { @@ -180,10 +198,10 @@ async function readChanges( const { files, base, omitted } = result.value return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } - const result = await reads.changeRequestDiff(source.url, signal) + const result = await reads.changeRequestDiff(source.url, commits, signal) if (!result.ok) return result const { files, headSha, localAhead, fileUrls } = result.value - return { ok: true, value: { kind: 'change', files, url: source.url, headSha, localAhead, fileUrls } } + return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } } } /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ @@ -191,25 +209,51 @@ function baseRefOf(scope: ForgeLocalScope): string | null { return scope.kind === 'branch' ? scope.base : null } +/** The commits a local scope shows, or null for all of them and for scopes other than `branch`. */ +function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null { + return scope.kind === 'branch' ? scope.commits : null +} + /** The source review comments on loaded changes record: the change request head, or the local scope with its base. */ function reviewSourceOf(data: ChangesData): ReviewSource { return data.kind === 'local' - ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope) } - : { kind: 'change', url: data.url, headSha: data.headSha } + ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope) } + : { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits } } -/** The files that start expanded: every file until those above it change more than {@link OPEN_LINES} lines. */ -function initiallyOpen(files: readonly ForgeDiffFile[]): ReadonlySet { +/** + * Identity of a diff source for viewed marks: the change request or local scope with its base ref and chosen commits. + * A change request's marks stay across head commits, so a file whose change a new push altered reads as changed. + */ +function viewedSourceOf(source: ReviewSource): string { + return JSON.stringify(source.kind === 'local' + ? ['local', source.scope, source.baseRef, source.commits] + : ['change', source.url, source.commits]) +} + +/** + * The files that start expanded: every file not marked viewed until those above it change more than {@link OPEN_LINES} lines. + * @param files - every file in display order. + * @param marks - the viewed marks when the files loaded. + * @returns the paths of the expanded files. + */ +function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): ReadonlySet { const open = new Set() let above = 0 for (const file of files) { if (above > OPEN_LINES) break + if (viewedStateOf(marks, file.path, file.digest) === 'viewed') continue open.add(file.path) above += drawnLines(file) } return open } +/** Whether a file shows under a lens while test files hide or not. */ +function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean { + return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens) +} + /** What a rename badge names: the old file name, or the old path when only the directory changed. */ function renamedFrom(previous: string, path: string): string { const name = pathPartsOf(previous).name @@ -231,9 +275,11 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { return parts.join(' · ') } -function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onReview, t }: { +function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: { readonly url: string readonly entry: ForgePanelChangeRequest | undefined + /** Commit picker left of the review button. */ + readonly commitMenu: ReactNode readonly reviewCount: number readonly reviewDisabled: boolean readonly onReview: () => void @@ -249,9 +295,12 @@ function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onRev {snapshot === null ? url : snapshot.title} {number !== null && {t('change.number', { number })}} - + + {commitMenu} + + - )} + {(scope === 'branch' || creatable) && + {scope === 'branch' && commitMenu} + {creatable && } + } ) } @@ -369,8 +421,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { * @returns the view body. */ export function ChangesTab({ - useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, changeRequestDiff, - changeRequestText, + useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, + changeRequestText, changeRequestCommits, viewedFiles, openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -423,6 +475,7 @@ export function ChangesTab({ const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) const [treePosition, setTreePosition] = useState('left') + const [treeWidth, setTreeWidth] = useState(0) const treeId = useId() const [chosen, setChosen] = useState>>({}) // Each navigation applies once; its file, if it names one, opens and scrolls into view. @@ -447,7 +500,18 @@ export function ChangesTab({ const state = snapshot?.state ?? null const scope = choices?.scope ?? 'branch' const base = choices?.base ?? null - const localScope = useMemo((): ForgeLocalScope => scope === 'branch' ? { kind: 'branch', base: base?.ref ?? null } : { kind: scope }, [scope, base]) + const chosenCommits = choices?.commits ?? null + const lens = choices?.lens ?? 'all' + const hideTests = choices?.hideTests ?? false + const localScope = useMemo((): ForgeLocalScope => scope === 'branch' + ? { kind: 'branch', base: base?.ref ?? null, commits: chosenCommits } : { kind: scope }, [scope, base, chosenCommits]) + const changeCommits = source.kind === 'change' ? chosenCommits : null + const changeUrlOf = source.kind === 'change' ? source.url : '' + const listChangeCommits = useCallback( + (signal: AbortSignal) => changeRequestCommits(changeUrlOf, signal), [changeRequestCommits, changeUrlOf], + ) + const baseRef = base?.ref ?? null + const listLocalCommits = useCallback((signal: AbortSignal) => localCommits(baseRef, signal), [localCommits, baseRef]) const split = choices?.split ?? true const wrap = choices?.wrap ?? true const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined @@ -456,7 +520,9 @@ export function ChangesTab({ const pending = entry !== undefined && entry.ref !== null && entry.update === null const head = entry?.snapshot?.headSha ?? (pending ? null : '') const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head - const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : 'change' + // The commits change with the head of a change request, and with the local branch or its base. + const commitsVersion = source.kind === 'local' ? `${baseRef ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? '' + const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}` const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null) const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null) // Names the read the inputs ask for; it is in flight until `finished` matches it. @@ -465,7 +531,7 @@ export function ChangesTab({ useEffect(() => { if (!tab.visible || read === null || read === finished) return const controller = new AbortController() - void readChanges(source, localScope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { + void readChanges(source, localScope, changeCommits, { localDiff, changeRequestDiff }, controller.signal).then((result) => { if (controller.signal.aborted) return setFinished(read) if (result.ok) { @@ -476,9 +542,15 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, source, localScope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null - const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests]) + const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item, + allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record, [allFiles, hideTests]) + const shownSource = data === null ? null : reviewSourceOf(data) + const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource) + const marks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -487,17 +559,29 @@ export function ChangesTab({ const latest = useRef(data) useEffect(() => { latest.current = data }, [data]) const [revealed, setRevealed] = useState>(new Set()) - const initial = useMemo(() => initiallyOpen(files), [files]) + // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays + // collapsed while it is marked viewed unless the reader expands it; a file whose change differs from its mark expands + // like an unmarked one. + const initial = useMemo(() => initiallyOpen(allFiles, marks), [allFiles]) + const expandedByDefault = (file: ForgeDiffFile): boolean => initial.has(file.path) && viewedStateOf(marks, file.path, file.digest) !== 'viewed' + const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file) const sections = useRef(new Map()) const scrollport = useRef(null) // A short final file cannot align with the viewport top; retain its jump until the reader scrolls away. const jumpPosition = useRef<{ readonly data: ChangesData; readonly top: number } | null>(null) useLayoutEffect(() => { if (!tab.visible || wanted === null || data === null) return + // A file the lens or the test switch hides is shown before the view scrolls to it. + const hidden = allFiles.find(file => file.path === wanted && !shownBy(file, lens, hideTests)) + if (hidden !== undefined) { + if (lens !== 'all') actions.lensed(tab.id, 'all') + if (hideTests && hidden.layer === 'test') actions.toggledTests(tab.id) + return + } sections.current.get(wanted)?.scrollIntoView({ block: 'start' }) if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop } setWanted(null) - }, [tab.visible, wanted, data]) + }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id]) const refresh = (): void => { setAttempt(value => value + 1) } const root = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.root : null // A chosen base branch that is gone or shares no history with HEAD offers the automatic fork point instead. @@ -507,8 +591,10 @@ export function ChangesTab({ const failureText = baseFailure ?? t(message ?? 'diff.error') const changeUrl = source.kind === 'change' ? entry?.snapshot?.url ?? source.url : null const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed') - const automaticBase = baseFailure !== undefined && ( + const automaticBase = baseFailure !== undefined ? ( + ) : failed === 'forgePanel/commits-missing' && ( + ) /** Apply a change to the unchanged lines of `owner`, unless newer changes replaced it. */ @@ -553,7 +639,8 @@ export function ChangesTab({ return list } - const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { @@ -563,9 +650,9 @@ export function ChangesTab({ }} t={t} /> const recordActions: ReviewActions = { - source: data !== null ? reviewSourceOf(data) : source.kind === 'local' - ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope) } - : { kind: 'change', url: source.url, headSha: '' }, + source: shownSource ?? (source.kind === 'local' + ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } + : { kind: 'change', url: source.url, headSha: '', commits: changeCommits }), records: queue, addToInput: addReviewToInput, openLink, } const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] @@ -578,26 +665,35 @@ export function ChangesTab({ setChosen(value => ({ ...value, [path]: true })) setWanted(path) } + /** + * The file being read: the file last jumped to while the scroll stays there, else the last file whose section starts + * above the viewport top. + */ + const currentIndex = (viewport: HTMLElement): number => { + const remembered = jumpPosition.current + const index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop + ? files.findIndex(file => file.path === treeState.selected) : -1 + if (index >= 0) return index + const top = viewport.getBoundingClientRect().top + return Math.max(0, files.findLastIndex((file) => { + const section = sections.current.get(file.path) + return section !== undefined && section.getBoundingClientRect().top <= top + 1 + })) + } + /** Whether a key press belongs to a field, a comment, a menu, or a text selection rather than to the file list. */ + const typing = (container: HTMLElement, origin: EventTarget): boolean => { + const selection = window.getSelection() + return !(origin instanceof HTMLElement) || !container.contains(origin) + || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment], [role="menu"]') !== null + || (selection !== null && !selection.isCollapsed) + } const navigateFiles = (event: KeyboardEvent): void => { if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) return const viewport = event.currentTarget - const origin = event.target - const selection = window.getSelection() - if (!(origin instanceof HTMLElement) || !viewport.contains(origin) - || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment]') !== null - || (selection !== null && !selection.isCollapsed)) return - const remembered = jumpPosition.current - let index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop - ? files.findIndex(file => file.path === treeState.selected) : -1 - if (index < 0) { - const top = viewport.getBoundingClientRect().top - index = Math.max(0, files.findLastIndex((file) => { - const section = sections.current.get(file.path) - return section !== undefined && section.getBoundingClientRect().top <= top + 1 - })) - } + if (typing(viewport, event.target)) return + const index = currentIndex(viewport) event.preventDefault() event.stopPropagation() const next = files[index + (event.key === 'ArrowRight' ? 1 : -1)] @@ -605,6 +701,37 @@ export function ChangesTab({ viewport.focus({ preventScroll: true }) jump(next.path) } + /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */ + const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => { + if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { + report('viewed.saveFailed') + return + } + const section = sections.current.get(file.path) + const viewport = scrollport.current + if (viewed && section !== undefined && viewport !== null + && section.getBoundingClientRect().top < viewport.getBoundingClientRect().top) setWanted(file.path) + // A new mark collapses the file through its default; clearing a mark expands it. + setChosen(({ [file.path]: _choice, ...value }) => viewed ? value : { ...value, [file.path]: true }) + } + /** The shown file whose section holds an element or a text node, if any. */ + const fileAt = (target: EventTarget | null | undefined): ForgeDiffFile | undefined => { + const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null + const path = element?.closest('[data-forge-diff-file]')?.getAttribute('data-forge-diff-file') + return files.find(file => file.path === path) + } + // `V` marks or clears the file being read, from anywhere in the tab except fields, comments, and menus: the file + // holding the focus, else the one holding the text cursor, as after clicking its code, else the file at the top. + const toggleViewed = (event: KeyboardEvent): void => { + const viewport = scrollport.current + if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey + || event.key.toLowerCase() !== 'v' || viewport === null || data === null || typing(event.currentTarget, event.target)) return + const file = fileAt(event.target) ?? fileAt(window.getSelection()?.anchorNode) ?? files[currentIndex(viewport)] + /* v8 ignore next -- the files region renders only while files show, so its position always names one */ + if (file === undefined) return + event.preventDefault() + markViewed(data, file, viewedStateOf(marks, file.path, file.digest) !== 'viewed') + } let body: ReactNode if (data === null) { @@ -635,10 +762,12 @@ export function ChangesTab({ } } else if (data.files.length === 0) { body =
{orphanRecords}
{t('diff.empty')}
+ } else if (files.length === 0) { + body =
{orphanRecords}
{t('lens.empty')}
} else { body = (
{ if (jumpPosition.current?.top !== event.currentTarget.scrollTop) jumpPosition.current = null }}> @@ -654,7 +783,7 @@ export function ChangesTab({ records: queue, openLink, reviewStarted: reviewState.comments.length > 0, onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, publishingBlocked: reviewState.uncertain !== null, - ...data.kind === 'local' ? {} : { + ...data.kind === 'local' || data.commits !== null ? {} : { queue: selection => queue.add(selection), publish: selection => selection.source.kind === 'change' ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, @@ -662,8 +791,8 @@ export function ChangesTab({ : Promise.resolve(t('review.stale')), }, }} - expanded={chosen[path] ?? initial.has(path)} - onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? initial.has(path)) })) }} + expanded={isExpanded(file)} + onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? expandedByDefault(file)) })) }} large={drawnLines(file) > LARGE_FILE_LINES} revealed={revealed.has(path)} onReveal={() => { setRevealed(value => new Set([...value, path])) }} @@ -675,6 +804,8 @@ export function ChangesTab({ badge={badgeOf(file, data, t)} tooltip={pathTooltipOf(file, t)} actions={fileActions(data, file)} + viewed={viewedStateOf(marks, path, file.digest)} + onViewed={(viewed) => { markViewed(data, file, viewed) }} sectionRef={(element) => { if (element === null) sections.current.delete(path) else sections.current.set(path, element) @@ -694,7 +825,7 @@ export function ChangesTab({ jump, } // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise. - const anyExpanded = files.some(file => chosen[file.path] ?? initial.has(file.path)) + const anyExpanded = files.some(isExpanded) const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll') const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft') let additions = 0 @@ -703,13 +834,21 @@ export function ChangesTab({ additions += file.additions deletions += file.deletions } + const viewedCount = files.filter(file => viewedStateOf(marks, file.path, file.digest) === 'viewed').length + const treeShown = allFiles.length > 0 && treePosition !== 'hidden' + const lensProps = { lens, counts: lensCounts, hideTests, choose: (next: ChangesLens) => { actions.lensed(tab.id, next) }, t } + const commitMenu = source.kind === 'local' && scope !== 'branch' ? null : { actions.committed(tab.id, next) }} t={t} /> + const toolbarStyle: CSSProperties & { '--forge-tree-width': string } = { '--forge-tree-width': `${treeWidth}px` } return ( -
+
{source.kind === 'local' ? { actions.based(tab.id, next) }} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} + diffBases={diffBases} choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu} + createChangeRequest={createChangeRequest} t={t} /> + : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
{t('review.unknown')} @@ -718,45 +857,58 @@ export function ChangesTab({
} {!reviewOpen && reviewError !== null && reviewState.uncertain === null && {reviewError}} -
- {tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } - {files.length > 0 && } - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + - + {allFiles.length > 0 && } +
{data !== null && failed !== null && ( {body} - {files.length > 0 && } + {allFiles.length > 0 && }
) diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css new file mode 100644 index 0000000000..34159de448 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css @@ -0,0 +1,130 @@ +/* Commit picker trigger in the changes header and its menu of commits, oldest first. */ +.anchor { + flex: 0 1 auto; + min-width: 0; +} + +.trigger { + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + box-sizing: border-box; + min-width: 0; + max-width: 100%; + height: 28px; + padding: 0 6px 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.chosen .triggerName { + font-family: var(--ds-font-family-code); +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .trigger:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; +} + +.trigger svg { + flex: none; +} + +.triggerName { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.menu { + width: min(400px, calc(100vw - 24px)); +} + +.rows { + max-height: 360px; + overflow: auto; + padding: 4px; + color: var(--dsw-alias-label-primary); + font-size: 12px; +} + +.option { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-width: 0; +} + +.allTitle { + flex: 1; + min-width: 0; +} + +.sha { + flex: none; + color: var(--dsw-alias-label-secondary); + font-family: var(--ds-font-family-code); +} + +.title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.meta { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; +} + +.check { + display: inline-flex; + flex: none; + color: var(--dsw-alias-state-business-primary); +} + +.unchecked { + visibility: hidden; +} + +.label { + padding: 6px 8px 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 8px; + color: var(--dsw-alias-label-secondary); +} + +.note { + padding: 8px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; +} diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx new file mode 100644 index 0000000000..58e7702b75 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx @@ -0,0 +1,162 @@ +/** + * Commit picker of the changes header: every commit, or one commit, or with Shift a run of consecutive commits of a + * change request or of the local `branch` scope, listed oldest first like the code host's commit list. + */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, Menu, MenuItemButton, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeCommitRange } from '../types.ts' +import { formatAgo } from './format.ts' +import type { NS } from './locales.ts' +import css from './CommitMenu.module.css' + +/** Characters of a commit object name the picker shows. */ +const SHORT = 7 + +/** Props of the commit picker. */ +export interface CommitMenuProps extends PropsLocale { + /** Commits shown, or null for all of them. */ + readonly chosen: ForgeCommitRange | null + /** Whether the owning tab is visible; a hidden tab keeps the menu closed. */ + readonly visible: boolean + /** Read the commits; null means the source cannot show single commits. `signal` aborts the read. */ + readonly list: (signal: AbortSignal) => Promise> + /** Changes when the commits may have changed, such as a new head commit; the next opening reads them again. */ + readonly version: string + /** Show consecutive commits, or every commit for null. */ + readonly choose: (commits: ForgeCommitRange | null) => void +} + +/** + * Name the shown commits on the trigger. + * @param chosen - the shown commits, or null for all of them. + * @param t - forge panel copy. + * @returns the label. + */ +export function commitsLabel(chosen: ForgeCommitRange | null, t: PropsLocale['t']): string { + if (chosen === null) return t('commits.all') + if (chosen.from === chosen.to) return chosen.from.slice(0, SHORT) + return t('commits.range', { from: chosen.from.slice(0, SHORT), to: chosen.to.slice(0, SHORT) }) +} + +/** + * Render the trigger and, while open, the commit list. A click shows one commit; a Shift click shows the commits + * from the last commit clicked without Shift to the clicked one. + * @param props - the shown commits, the listing read, the choose action, and copy. + * @returns the trigger with its portalled menu, or nothing when the source cannot show single commits. + */ +export function CommitMenu({ chosen, visible, list, version, choose, t }: CommitMenuProps): ReactNode { + const [open, setOpen] = useState(false) + const [attempt, setAttempt] = useState(0) + const [listing, setListing] = useState<{ readonly version: string; readonly result: RemoteResult } | null>(null) + const shift = useRef(false) + const anchor = useRef(chosen?.from ?? null) + const loaded = useRef(null) + const shown = visible && open + const current = listing?.version === version ? listing.result : null + // The list is read once per version, which tells whether the source has commits to pick, and again on each opening. + useEffect(() => { + if (!visible || (!shown && loaded.current === version)) return + const controller = new AbortController() + void list(controller.signal).then((result) => { + if (controller.signal.aborted) return + loaded.current = version + setListing({ version, result }) + }) + return () => { controller.abort() } + }, [visible, shown, version, attempt, list]) + if (current?.ok === true && current.value === null) return null + const commits = current?.ok === true && current.value !== null ? current.value : null + const pick = (sha: string | null): void => { + setOpen(false) + if (sha === null || commits === null) { + anchor.current = null + if (chosen !== null) choose(null) + return + } + const order = commits.commits.map(commit => commit.sha) + const start = shift.current && anchor.current !== null && order.includes(anchor.current) ? anchor.current : sha + if (!shift.current || start === sha) anchor.current = sha + const [from, to] = order.indexOf(start) <= order.indexOf(sha) ? [start, sha] : [sha, start] + if (from !== chosen?.from || to !== chosen.to) choose({ from, to }) + } + const inChosen = (index: number): boolean => { + if (chosen === null || commits === null) return false + const order = commits.commits.map(commit => commit.sha) + return index >= order.indexOf(chosen.from) && index <= order.indexOf(chosen.to) && order.includes(chosen.from) + } + + let body: ReactNode + if (current === null) { + body =
{t('commits.loading')}
+ } else if (!current.ok || commits === null) { + body = ( +
+ {t('commits.failed')} + +
+ ) + } else { + const now = Date.now() + body = <> + { pick(null) }}> + + {t('commits.all')} + {t('commits.count', { count: commits.commits.length })} + {chosen === null && } + + + {commits.commits.length > 0 &&
{t('commits.shiftHint')}
} + {commits.commits.map((commit, index) => { + const selected = inChosen(index) + return ( + { pick(commit.sha) }}> + + {commit.sha.slice(0, SHORT)} + {commit.title} + {formatAgo(commit.authoredAt, now, t) ?? ''} + + + + ) + })} + {commits.truncated &&
{t('commits.truncated', { count: commits.commits.length })}
} + + } + + const label = commitsLabel(chosen, t) + return ( + { setOpen(false) }} + anchor={( + + + + )} + > + {/* Rows report activation without the event, so the modifier is read while the click or key travels to them. */} +
{ shift.current = event.shiftKey }} + onKeyDownCapture={(event) => { shift.current = event.shiftKey }}> + {body} +
+
+ ) +} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index eb7e21e6b0..ad46c66132 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -9,7 +9,7 @@ import clsx from 'clsx' import { flushSync } from 'react-dom' import { FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, - Tooltip, + Tag, Tooltip, languageForPath, Menu, MenuItemButton, useCodeHighlighter, type CodeHighlighter, type HighlightSpan, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' @@ -23,6 +23,7 @@ import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx' import reviewCss from './ReviewComposer.module.css' import { FileLabel } from './FileLabel.tsx' import type { ForgePanelKey, NS } from './locales.ts' +import type { ViewedState } from './viewed-files.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -72,6 +73,10 @@ export interface DiffFileProps { readonly tooltip: string /** Rows of the file's menu. */ readonly actions: readonly DiffFileAction[] + /** Whether the reader marked this change viewed, or marked an earlier change of the file. */ + readonly viewed: ViewedState + /** Mark the file viewed, which also collapses it, or clear the mark. */ + readonly onViewed: (viewed: boolean) => void /** Receives the section element, which scrolling to the file targets. */ readonly sectionRef: (element: HTMLElement | null) => void /** Forge panel copy. */ @@ -438,10 +443,11 @@ function FileMenu({ name, actions, t }: { * @returns the file section. */ export function DiffFile(props: DiffFileProps): ReactNode { - const { file, expanded, onToggle, badge, tooltip, actions, sectionRef, t } = props + const { file, expanded, onToggle, badge, tooltip, actions, viewed, onViewed, sectionRef, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) return ( -
+
{expanded && } diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx index b055655814..a4995615f1 100644 --- a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx @@ -15,12 +15,14 @@ export type FileTreePosition = 'right' | 'left' | 'hidden' /** * Render a keyboard- and pointer-resizable tree beside the diff. - * @param props - tree rows, pane position, and the toggle's controlled element id. + * @param props - tree rows, pane position, the toggle's controlled element id, and the receiver of the shown width. * @returns the bounded pane and its resize separator. */ -export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { +export function FileTreePane({ position, id, onWidth, ...props }: ChangedFilesProps & { readonly position: FileTreePosition readonly id: string + /** Receives the pane's width in pixels whenever it changes, so the toolbar can align a cell with it. */ + readonly onWidth: (width: number) => void }): ReactNode { const pane = useRef(null) const drag = useRef<{ pointer: number; x: number; width: number } | null>(null) @@ -41,6 +43,7 @@ export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { return () => { observer.disconnect() } }, []) const shown = Math.min(width, maximum) + useLayoutEffect(() => { onWidth(shown) }, [shown, onWidth]) const direction = position === 'left' ? 1 : -1 const resize = (next: number): void => { setWidth(Math.round(Math.max(MIN_WIDTH, Math.min(maximum, next)))) } return