feat(cua): allow session-approved system-pointer drags on macOS

This commit is contained in:
creatixchu committed 2026-11-12 13:50:00 +08:00
1 parent 8d9c78459c
commit 71cf14878d
27 files changed
+267 -111

No files matched your search

@@ -15,11 +15,11 @@
en: 1777e7bf6785f986
zh: e3daac1074ebb74d
/deepseek-ai-dsh-cua-macos/use-this-package:
en: f8caa12d40d3034d
zh: 599f8be5147e0404
en: 8b3a2a83bb8354f2
zh: a6799c335c010c58
/deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment:
en: 7058be5d1b778643
zh: 821de6b0ad7aba27
en: 01790bf966abe339
zh: cd91247a910dfa4c
/deepseek-ai-dsh-cua-macos/understand-the-implementation:
en: 4e82b85a5aa72eee
zh: 4e004b7a205d8688
+5 -3
View File
@@ -62,7 +62,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates
| `screenshotTarget` | unset | Fixed `{ longEdge, maxBytes }` request-image target for screenshots. Unset resolves the target from the Agent's model route and refuses capture when that route declares no image input. |
| `allowedApps` | `[]` | Legacy path/signature grants, imported once for removal; they do not authorize new bundle-ID identities. |
| `helperPath` | package-owned executable | Absolute executable inside the signed helper `.app`; a bare binary fails with `NATIVE_APPLICATION_REQUIRED`. |
| `requireSystemPointerApproval` | `true` | Ask on the first explicit request to move the system pointer. With `false`, only explicitly requested moves use it. |
| `requireSystemPointerApproval` | `true` | Ask once per session before an explicitly requested system-pointer move or drag. |
| `sourceSigning` | `ad-hoc` | Source signing: `ad-hoc`, or `{ identity, keychain }` for an existing certificate and keychain path. Ignored for installed packages and `helperPath`. |
| `buildTimeoutMs` | `300000` | Maximum native preparation time. |
| `timeoutMs` | `30000` | Per-operation deadline; cancellation can leave partial input. |
@@ -123,6 +123,8 @@ Use the `cua` API to discover and select the application (`listApps`, `getState`
Ordinary `mouseMove(target)` defaults to AX hover. Without both `AXShowAlternateUI` and `AXShowDefaultUI` on an enabled target or ancestor, it returns `HOVER_UNAVAILABLE` without prompting. Only when the task requires physical movement should the main task call `win.mouseMove(target, { useSystemPointer: true })`. On approval the Host rechecks the window and point and dispatches this move. Pass `useSystemPointer: true` on every physical move. Later explicit moves reuse the decision until the session closes or DSH restarts. Omitting the option or passing `false` uses AX. Refusal sends no input.
By default, drag posts mouse events to the target window. For controls that need system button state, use `win.drag(from, to, { useSystemPointer: true })`. This shares the session permission for system-pointer moves. The start and path must hit the foreground window. Cancellation or loss of the target releases the button at the last posted point.
`paste(text, { format: "text" | "html" })` temporarily publishes the requested clipboard format and invokes the application’s enabled standard Paste menu command. It keeps the temporary format until a pasteboard reader requests its data, then restores every captured original format while it still owns the clipboard, preserving a later copy. Paste operations share a cross-process lock and cancellation joins helper cleanup. A forced process exit can prevent restoration. Unsupported Paste commands fail without typing fallback; `typeText` remains separate key-event input.
`selectText` selects a unique literal occurrence or places the cursor before/after it through writable `AXSelectedTextRange`. Adjacent prefix/suffix disambiguate repeats. Selection preserves the remaining text and formatting, and verifies the resulting UTF-16 range; unsupported, missing, ambiguous or changed text fails without keyboard fallback. AX text includes `selectionWritable`, selection ranges and selected text when available.
@@ -221,7 +223,7 @@ Use an explicit window for screenshots and pointer input. Before coordinate inpu
- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
@@ -234,7 +236,7 @@ Available at app or window level depending on the platform.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
Use win.mouseMove(target, { useSystemPointer: true }) or win.drag(from, to, { useSystemPointer: true }) only when the task requires the system pointer. System drag presses, moves, and releases the selected mouse button in the unobscured foreground window. Omit the option for ordinary window-directed drag. Inspect the application after dispatch before deciding whether to try another route. The first explicit request asks for session permission unless approval is disabled. Approval or refusal applies to moves and drags until the session closes or DSH restarts. Pass true on each physical gesture. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
```
#### Token effect
+5 -3
View File
@@ -62,7 +62,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis.
| `screenshotTarget` | 未设置 | 截图使用的固定 `{ longEdge, maxBytes }` 请求图片目标。未设置时按 Agent 的模型路由解析,该路由未声明图片输入时拒绝截图。 |
| `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 |
| `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 |
| `requireSystemPointerApproval` | `true` | 主任务首次显式请求移动系统指针时询问用户。设为 `false` 时仅本次显式移动免询问。 |
| `requireSystemPointerApproval` | `true` | 主任务首次显式请求使用系统鼠标移动或拖动时询问用户。 |
| `sourceSigning` | `ad-hoc` | 源码签名:`ad-hoc` 临时签名,或 `{ identity, keychain }` 指定已有证书及钥匙串路径。安装版和 `helperPath` 忽略此项。 |
| `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 |
| `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 |
@@ -123,6 +123,8 @@ inspect(await window.getScreenshot())
普通 `mouseMove(target)` 默认通过辅助功能悬停。如果目标或其祖先没有同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`,则返回 `HOVER_UNAVAILABLE`,不会弹窗。只有任务确实需要移动用户的鼠标时,主任务才调用 `win.mouseMove(target, { useSystemPointer: true })`。用户允许后,Host 重新检查窗口和目标位置,再执行本次移动。每次移动系统指针都要显式传 `useSystemPointer: true`。省略参数或传 `false` 时使用辅助功能悬停。拒绝时不派发输入。会话记住此次选择,直到关闭会话或重启 DSH。
默认拖动向目标窗口发送鼠标事件。需要系统鼠标按键状态的控件可使用 `win.drag(from, to, { useSystemPointer: true })`。该操作与系统指针移动共用会话授权,起点和拖动路径必须位于可接收输入的前台窗口内。取消或失去目标窗口时,helper 在最后投递的位置释放鼠标键。
`paste(text, { format: "text" | "html" })` 临时提供指定格式的剪贴板内容,并调用应用已启用的标准 Paste 菜单命令。临时格式保留到剪贴板读取方请求其数据,然后只在仍持有剪贴板时恢复保存的全部原格式,保留期间产生的新复制内容。粘贴操作共用跨进程锁,取消会等待辅助进程清理。强制终止进程可能阻止恢复。应用不支持 Paste 命令时明确失败,不自动改成逐字输入;`typeText` 仍单独提供按键事件输入。
`selectText` 通过可写的 `AXSelectedTextRange` 选中唯一的字面文本,或把光标放在它的前后。紧邻的前后文用于区分重复文本。选区操作保留其余文字和格式,并核对实际 UTF-16 范围;控件不支持、文本不存在、匹配不唯一或文字变化时明确失败,不自动改用键盘输入。AX 文本包含可用的 `selectionWritable`、选区范围和选中文字。
@@ -221,7 +223,7 @@ Use an explicit window for screenshots and pointer input. Before coordinate inpu
- mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without that route, HOVER_UNAVAILABLE is returned before sending input. Physical movement requires an unobscured foreground target. Explain any necessary activation and observe the target again.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean, useSystemPointer?: boolean }) -> ActionResult — drag between two points of one window.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
@@ -234,7 +236,7 @@ Available at app or window level depending on the platform.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
Use win.mouseMove(target, { useSystemPointer: true }) or win.drag(from, to, { useSystemPointer: true }) only when the task requires the system pointer. System drag presses, moves, and releases the selected mouse button in the unobscured foreground window. Omit the option for ordinary window-directed drag. Inspect the application after dispatch before deciding whether to try another route. The first explicit request asks for session permission unless approval is disabled. Approval or refusal applies to moves and drags until the session closes or DSH restarts. Pass true on each physical gesture. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.
```
#### Token 影响
@@ -21,8 +21,8 @@
en: 21d92283c084d8bb
zh: 7a29731b9f58c709
/dsh-cua-native-helper/observation-and-input:
en: a1de529f35c130d4
zh: ec19b62804df2264
en: d00e18983253b900
zh: 4a8a6ca1ed9df290
/dsh-cua-native-helper/verification:
en: 908b13b2732c1bec
zh: ac3bbd77ed9a69b8
@@ -99,7 +99,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro
Hiding a window does not itself expire its AX snapshot. An inventory refresh can retain the previous screenshot mapping only while the same window ID remains present at the same observed size. An observed size change requires a new screenshot for pixel input; a closed window cannot be targeted. Omission from discovery does not block input to a known ID: ownership, geometry and input checks still apply, and dispatch does not confirm receipt.
Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. 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. 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.
Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and default drag validate window ownership and bounds, then post to the target PID and window. 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. 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. An explicit `useSystemPointer: true` drag posts through the HID event tap, checks the foreground window at the start and each movement, and supplies one gesture event number and per-segment deltas. Cancellation releases at the last posted point.
`click.holdMs` is an optional nonnegative integer in milliseconds per press; zero adds no hold delay. Each connection supplies `maxClickHoldMs` to bound explicit holds. The diagnostic helper option `--max-click-hold-ms` defaults to 5000. Omission retains ordinary click timing. The complete gesture holds the request scheduler slot; cancellation, timeout and disconnect interrupt the hold and post the pending mouse-up before releasing that slot. Received events remain effective, and forced process termination cannot guarantee cleanup.
@@ -99,7 +99,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后
窗口隐藏本身不会使 AX 快照失效。刷新清单时,只有同一窗口 ID 仍存在且观察到的尺寸未变,才能继续使用此前截图的像素坐标。观察到尺寸变化后需要重新截图;窗口销毁后不能继续操作。清单中省略窗口不会阻止按已知 ID 发起输入。窗口归属、尺寸和输入检查仍然生效,成功分派不代表应用已接收。
点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。
点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和默认拖动核实窗口归属和边界后,向目标进程和窗口投递事件。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。显式传入 `useSystemPointer: true` 的拖动通过 HID 投递,起点及每段移动都要命中目标前台窗口。手势共用事件号,每段携带位移。取消时在最后投递的位置松开鼠标键。
`click.holdMs` 是可选的每次按住时长,单位为毫秒,接受非负整数;0 表示不额外等待。每个连接通过 `maxClickHoldMs` 限制显式按住时长。诊断 helper 的 `--max-click-hold-ms` 选项默认 5000。省略时保留普通点击时长。整个手势占用请求调度槽位;取消、超时和断开连接会中断等待,在释放槽位前发送对应的松开事件。已接收的事件仍然生效,进程被强制终止时无法保证清理。
@@ -446,9 +446,10 @@ actor AXWorker {
let dy = params.contains("deltaLinesY") ? try params.integer("deltaLinesY", in: -10...10) : 0
try inputs().1.scroll(in: route, at: params.point(), deltaLinesX: Int32(dx), deltaLinesY: Int32(dy))
} else {
try inputs().1.drag(in: route, from: params.point("fromX", "fromY"), to: params.point("toX", "toY"),
try await inputs().1.drag(in: route, from: params.point("fromX", "fromY"), to: params.point("toX", "toY"),
durationMs: params.integer("durationMs", in: 1...5000), steps: params.integer("steps", in: 1...240),
button: params.optionalString("mouseButton") ?? "left", modifiers: params.modifiers())
button: params.optionalString("mouseButton") ?? "left", modifiers: params.modifiers(),
useSystemPointer: params.optionalBoolean("useSystemPointer") ?? false)
}
default: throw NativeFailure(code: "UNSUPPORTED", message: method)
}
@@ -6,7 +6,7 @@ enum NativeProtocol {
"activate": ["appHandle"],
"applicationIcons": ["paths"],
"click": ["appHandle", "clickCount", "elementId", "holdMs", "modifiers", "mouseButton", "snapshotId", "windowId", "x", "y"],
"drag": ["appHandle", "durationMs", "fromX", "fromY", "modifiers", "mouseButton", "snapshotId", "steps", "toX", "toY", "windowId"],
"drag": ["appHandle", "durationMs", "fromX", "fromY", "modifiers", "mouseButton", "snapshotId", "steps", "toX", "toY", "useSystemPointer", "windowId"],
"findApps": ["maxAppMatches", "query"],
"getApp": ["selector"],
"getCapabilities": [],
@@ -32,28 +32,36 @@ final class WindowPointerInput {
@MainActor static func mouseMove(in route: WindowRoute, at point: WindowPoint, checkCancellation: @Sendable () throws -> Void) throws {
try checkCancellation()
try Self.validate(point, in: route)
try NativePlatform.verify(route.owner)
try NativePlatform.requireUnlocked(NativePlatform.sessionLocked())
let current = try NativePlatform.ownedWindow(route.owner.pid, route.windowID)
guard current.bounds == route.bounds else {
throw NativeFailure(code: "WINDOW_CHANGED", message: "Window moved or resized before hover; read fresh state")
}
try validateSystemWindow(route)
let screen = screenPoint(point, in: route)
try checkSystemHit(route, at: screen)
guard let event = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved,
mouseCursorPosition: Self.screenPoint(point, in: route), mouseButton: .left) else {
mouseCursorPosition: screen, mouseButton: .left) else {
throw NativeFailure(code: "NATIVE_ERROR", message: "Could not create system pointer movement")
}
event.flags = []
try Self.requireSystemPointerTarget(route, frontPID: NativePlatform.frontPID(),
hitWindowID: NativePlatform.mouseWindow(at: Self.screenPoint(point, in: route)))
try checkCancellation()
event.post(tap: .cghidEventTap)
try checkCancellation()
}
private static func validateSystemWindow(_ route: WindowRoute) throws {
try NativePlatform.verify(route.owner)
try NativePlatform.requireUnlocked(NativePlatform.sessionLocked())
let current = try NativePlatform.ownedWindow(route.owner.pid, route.windowID)
guard current.bounds == route.bounds else {
throw NativeFailure(code: "WINDOW_CHANGED", message: "Window moved or resized before system-pointer input; read fresh state")
}
}
@MainActor private static func checkSystemHit(_ route: WindowRoute, at screen: CGPoint) throws {
try requireSystemPointerTarget(route, frontPID: NativePlatform.frontPID(), hitWindowID: NativePlatform.mouseWindow(at: screen))
}
/// Input-transparent windows do not obscure a target; AppKit owns mouse hit testing.
static func requireSystemPointerTarget(_ route: WindowRoute, frontPID: Int32?, hitWindowID: Int) throws {
guard frontPID == route.owner.pid, hitWindowID == Int(route.windowID) else {
throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "System-pointer hover requires foreground PID \(route.owner.pid) and mouse-hit window \(route.windowID); observed foreground PID \(frontPID.map(String.init) ?? "unknown") and mouse-hit window \(hitWindowID). Call app.activate() or use performAction with an advertised AXRaise, then observe again")
throw NativeFailure(code: "FOREGROUND_REQUIRED", message: "System-pointer input requires foreground PID \(route.owner.pid) and mouse-hit window \(route.windowID); observed foreground PID \(frontPID.map(String.init) ?? "unknown") and mouse-hit window \(hitWindowID). Call app.activate() or use performAction with an advertised AXRaise, then observe again")
}
}
@@ -142,8 +150,9 @@ final class WindowPointerInput {
/// Drag the selected button along an interpolated path, releasing at the last posted point on cancellation.
func drag(
in route: WindowRoute, from start: WindowPoint, to end: WindowPoint, durationMs: Int, steps: Int,
button: String = "left", modifiers: [String] = []
) throws {
button: String = "left", modifiers: [String] = [], useSystemPointer: Bool = false,
isolation: isolated (any Actor)? = #isolation
) async throws {
try checkCancellation()
try Self.validate(start, in: route)
try Self.validate(end, in: route)
@@ -151,61 +160,73 @@ final class WindowPointerInput {
throw NativeFailure(code: "INVALID_ARGUMENT", message: "Drag durationMs must be 1...5000 and steps 1...240")
}
let source = try Self.source()
let selectedButton = try Self.button(button)
let selected = try Self.button(button)
let flags = try KeyboardInput.modifierFlags(modifiers)
let group = Self.clickGroup()
let down = try mouseEvent(
source: source, route: route, screen: Self.screenPoint(start, in: route), local: start,
type: Self.down(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags
)
let initialRelease = try mouseEvent(
source: source, route: route, screen: Self.screenPoint(start, in: route), local: start,
type: Self.up(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags
)
func event(_ type: CGEventType, at point: WindowPoint) throws -> CGEvent {
let screen = Self.screenPoint(point, in: route)
if !useSystemPointer {
return try mouseEvent(source: source, route: route, screen: screen, local: point, type: type,
button: selected, clickState: 1, subtype: 0, group: group, flags: flags)
}
guard let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: screen, mouseButton: selected) else {
throw NativeFailure(code: "NATIVE_ERROR", message: "Could not create system drag event")
}
event.flags = flags
event.setIntegerValueField(.mouseEventNumber, value: group)
event.setIntegerValueField(.mouseEventClickState, value: type == .mouseMoved ? 0 : 1)
return event
}
func post(_ event: CGEvent) {
if useSystemPointer {
event.timestamp = DispatchTime.now().uptimeNanoseconds
event.post(tap: .cghidEventTap)
} else {
poster.post(event, to: route.owner.pid)
}
}
let down = try event(Self.down(selected), at: start)
var release = try event(Self.up(selected), at: start)
var previous = start
var path: [DragStep] = []
for index in 1...steps {
let fraction = Double(index) / Double(steps)
let local = WindowPoint(
x: start.x + (end.x - start.x) * fraction,
y: start.y + (end.y - start.y) * fraction
)
let screen = Self.screenPoint(local, in: route)
path.append(DragStep(
movement: try mouseEvent(
source: source, route: route, screen: screen, local: local,
type: Self.dragged(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags
),
release: try mouseEvent(
source: source, route: route, screen: screen, local: local,
type: Self.up(selectedButton), button: selectedButton, clickState: 1, subtype: 0, group: group, flags: flags
)
))
let local = WindowPoint(x: start.x + (end.x - start.x) * fraction, y: start.y + (end.y - start.y) * fraction)
let movement = try event(Self.dragged(selected), at: local)
if useSystemPointer {
movement.setIntegerValueField(.mouseEventDeltaX, value: Int64(local.x.rounded() - previous.x.rounded()))
movement.setIntegerValueField(.mouseEventDeltaY, value: Int64(local.y.rounded() - previous.y.rounded()))
}
path.append(DragStep(movement: movement, release: try event(Self.up(selected), at: local)))
previous = local
}
var heldRelease: CGEvent?
if useSystemPointer {
try Self.validateSystemWindow(route)
try await Self.checkSystemHit(route, at: down.location)
guard ![CGMouseButton.left, .right, .center].contains(where: { CGEventSource.buttonState(.combinedSessionState, button: $0) }) else {
throw NativeFailure(code: "INPUT_BUSY", message: "A mouse button is already held")
}
try checkCancellation()
post(try event(.mouseMoved, at: start))
try await Self.checkSystemHit(route, at: down.location)
}
let interval = Self.dragStepInterval(durationMs: durationMs, steps: steps)
try checkCancellation()
post(down)
do {
defer {
if let heldRelease {
poster.post(heldRelease, to: route.owner.pid)
Thread.sleep(forTimeInterval: 0.100)
}
}
try checkCancellation()
poster.post(down, to: route.owner.pid)
heldRelease = initialRelease
Thread.sleep(forTimeInterval: 0.016)
let stepInterval = Self.dragStepInterval(durationMs: durationMs, steps: steps)
defer { post(release) }
try await Task.sleep(for: .milliseconds(16))
for step in path {
if useSystemPointer { try await Self.checkSystemHit(route, at: step.movement.location) }
try checkCancellation()
poster.post(step.movement, to: route.owner.pid)
heldRelease = step.release
if stepInterval > 0 { Thread.sleep(forTimeInterval: stepInterval) }
post(step.movement)
release = step.release
try await Task.sleep(for: .seconds(interval))
}
Thread.sleep(forTimeInterval: 0.050)
try await Task.sleep(for: .milliseconds(50))
try checkCancellation()
if let release = heldRelease { poster.post(release, to: route.owner.pid) }
heldRelease = nil
Thread.sleep(forTimeInterval: 0.100)
}
try await Task.sleep(for: .milliseconds(100))
try checkCancellation()
}
@@ -15,11 +15,13 @@ export function renderNativeProtocol(): { json: string; swift: string } {
maxElements: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxElements),
maxDepth: z.number().int().min(1).max(AX_TRAVERSAL_MAX.maxDepth),
}
const systemPointer = { useSystemPointer: z.boolean().optional() }
const { fields, enums, json } = nativeProtocol({
getState: NativeResourceParameters.getState.extend(traversal),
paste: NativeResourceParameters.paste.extend(traversal),
sendKeyEvent: z.object({ runId: z.string().min(1) }),
mouseMove: z.object({ useSystemPointer: z.boolean().optional() }),
mouseMove: z.object(systemPointer),
drag: NativeResourceParameters.drag.extend(systemPointer),
requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters,
}, [z.object({
method: z.literal('releaseHeldKeys'), params: z.object({ runId: z.string().min(1) }).strict(),
@@ -1198,6 +1198,9 @@
"type": "integer",
"minimum": 1,
"maximum": 240
},
"useSystemPointer": {
"type": "boolean"
}
},
"required": [
@@ -89,7 +89,12 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega
value["keyCode"] = event.keyCode
value["characters"] = event.characters ?? ""
value["repeat"] = event.isARepeat
} else { value["button"] = event.buttonNumber }
} else {
value["button"] = event.buttonNumber
value["pressedButtons"] = NSEvent.pressedMouseButtons
value["deltaX"] = event.deltaX
value["point"] = [event.locationInWindow.x, event.locationInWindow.y]
}
self.events.append(value)
self.persist()
}
@@ -46,6 +46,39 @@ def stop_application(pid):
raise AssertionError("fixture did not exit after SIGTERM")
def check_system_drag(helper, owner, window, point, state_file):
call = helper.call
call("activate", owner)
wait_for_state(state_file, lambda v: v["active"] and v["keyWindow"])
call("getState", {**window, "maxElements": 300, "maxDepth": 20})
count = len(json.loads(state_file.read_text())["events"])
params = {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80,
"toY": point["y"] + 20, "durationMs": 400, "steps": 20, "useSystemPointer": True}
call("drag", params)
state = wait_for_state(state_file, lambda v: any(e["type"] == 2 for e in v["events"][count:]))
events = state["events"][count:]
assert events[0]["type"] == 1 and events[-1]["type"] == 2, events
assert any(e["type"] == 6 and e["pressedButtons"] & 1 and e["deltaX"] > 0 for e in events), events
assert events[-1]["point"][0] - events[0]["point"][0] == 80, events
key = hashlib.sha256(Path(helper.process.args[0]).read_bytes()).hexdigest()
connection = Connection(Path(f"/tmp/dsh-cua-{os.getuid()}/{key}.sock"), key)
try:
app = connection.call("getApp", {"selector": str(state["pid"])})
target = {**params, "appHandle": app["appHandle"], "durationMs": 5000, "steps": 2}
connection.call("getState", {"appHandle": app["appHandle"], "windowId": window["windowId"], "maxElements": 300, "maxDepth": 20})
count = len(state["events"])
connection.send({"id": "cancel-drag", "method": "drag", "params": target})
wait_for_state(state_file, lambda v: any(e["type"] == 6 for e in v["events"][count:]))
connection.send({"type": "cancel", "id": "cancel-drag"})
assert connection.read()["error"]["code"] == "NATIVE_CANCELLED"
state = wait_for_state(state_file, lambda v: any(e["type"] == 2 for e in v["events"][count:]))
events = state["events"][count:]
assert [e["type"] for e in events] == [1, 6, 2], events
assert events[-1]["point"] == events[-2]["point"] and not events[-1]["pressedButtons"] & 1, events
finally:
connection.close()
def check_clicks(helper, window, point, state_file):
observed = helper.call("getState", {**window, "maxElements": 2000, "maxDepth": 25})
pad = next(item for item in observed["elements"] if item["role"] == "AXButton" and item["title"] == "Input receiver")
@@ -172,6 +205,7 @@ def main():
only = parser.add_mutually_exclusive_group()
only.add_argument("--click-only", action="store_true")
only.add_argument("--keyboard-only", action="store_true")
only.add_argument("--drag-only", action="store_true")
args = parser.parse_args()
transcript = []
helper = None
@@ -203,6 +237,13 @@ def main():
app = call("launchApp", owner)
assert app["running"] is True, app
pid = wait_for_state(state_file, lambda value: bool(value["windowId"]))["pid"]
if args.drag_only:
state = json.loads(state_file.read_text())
pad = state["pad"]
check_system_drag(helper, owner, {**owner, "windowId": state["windowId"]},
{"x": pad[0] + 80, "y": pad[1] + 70}, state_file)
print("PASS: system drag delivers held-button movement and releases at the last point on cancellation")
return
if args.keyboard_only:
check_keyboard(call, owner, state_file, json.loads(state_file.read_text()))
print("PASS: Shift+D shortcut, two-second W+D hold, independent D up, explicit W repeat and one final up")
@@ -1210,6 +1210,32 @@ it('requires an explicit system-pointer request on every move and asks only once
expect(f.ask).toHaveBeenCalledTimes(1)
})
it.each([true, false])('asks before a system drag and shares the session decision with hover (allow=%s)', async (allow) => {
const f = await hoverFixture()
const target = { appHandle: 'app-one', windowId: '7', relative: true, fromX: 100, fromY: 200, toX: 300, toY: 400 }
native.request.mockResolvedValueOnce({ appHandle: target.appHandle, windowId: null, snapshotId: 's', tree: '', truncated: false,
windows: [{ windowId: '7', appName: 'Fixture', title: '', bounds: imageMetadata.bounds, isOnScreen: true, onCurrentSpace: true }] })
await f.execute('getState', { appHandle: target.appHandle })
if (!allow) f.ask.mockResolvedValue({ answers: [{ id: 'cua-mouse-control', selected: ['Deny'] }] })
native.request.mockClear()
const drag = await f.execute('drag', { ...target, useSystemPointer: true })
const hover = await f.execute('mouseMove', physicalHover)
expect(f.ask).toHaveBeenCalledTimes(1)
if (allow) {
expect(drag.isError).toBe(false)
expect(hover.isError).toBe(false)
expect(native.request.mock.calls.map(([method, params]) => [method, params.useSystemPointer])).toEqual([['drag', true], ['mouseMove', true]])
} else {
for (const result of [drag, hover]) expect(JSON.stringify(result.content)).toContain('MOUSE_CONTROL_DENIED')
expect(native.request).not.toHaveBeenCalled()
}
for (const params of [target, { ...target, useSystemPointer: false }]) {
expect((await f.execute('drag', params)).isError).toBe(false)
expect(native.request.mock.lastCall?.[1]).not.toHaveProperty('useSystemPointer')
}
expect(f.ask).toHaveBeenCalledTimes(1)
})
it('keeps refusals and grants separate and forgets a closed session on reopen', async () => {
const f = await hoverFixture()
expect((await f.execute('mouseMove', physicalHover)).isError).toBe(false)
+2 -2
View File
@@ -15,8 +15,8 @@
en: 5db4d4fea25493b9
zh: 65ab64fc24eb0d09
/deepseek-ai-dsh-cua/use-this-package:
en: c59986e14b6cf9ad
zh: 10c7f6acef208342
en: 3f741ae248d47d45
zh: 2f40e4b24365fa51
/deepseek-ai-dsh-cua/use-this-package/permission-controls:
en: 754ca69ec462325a
zh: 440d76acf2666689
+2
View File
@@ -51,6 +51,8 @@ Application consent precedes launch, observation, capture, and input. Session ac
Actions return a `dispatched` boolean; `mouseMove` also reports `hoverRoute` and `systemPointerMoved`, and `show()` adds `windowId` and `foregroundChanged`. Read fresh state to verify the result. Screenshots and pointer actions are available only on explicit window objects. Coordinate actions default to pixels in the latest returned screenshot; `relative: true` accepts integers from 0 to 999 after a successful AX observation covering the window or a screenshot. Selecting a window alone does not establish this observation. Values are divided by 1000 and scaled to the window dimensions, then clamped inside the window. The Host resolves attachment normalization and the selected model route’s image projection before returning the screenshot, then converts input to the provider’s native window coordinates. Resizing invalidates the screenshot mapping; `SCREENSHOT_REQUIRED` requires a new screenshot for absolute coordinates. Resizing rejects old coordinates with `WINDOW_CHANGED`; movement alone preserves window-local coordinates.
On providers with system-pointer support, `win.drag(from, to, { useSystemPointer: true })` shares the session’s mouse permission with `win.mouseMove`. Request the system pointer explicitly for each gesture.
`click(target, { holdMs: 800 })` holds the mouse button for 800 milliseconds before release. `holdMs` applies only to `click`; it accepts nonnegative integers and applies to each press of a double-click; zero releases without an additional hold. The provider config `maxClickHoldMs` limits explicit holds and defaults to 5000 ms. Explicit holds use pointer input; omission preserves ordinary click behavior. The operation deadline includes the hold, and cancellation or timeout releases the button. Received input cannot be undone; forced helper termination cannot guarantee release.
### Permission controls
+2
View File
@@ -51,6 +51,8 @@ kind: "package-reference"
动作返回 `dispatched` 布尔值;`mouseMove` 还会返回 `hoverRoute` 和 `systemPointerMoved`,`show()` 还会返回 `windowId` 和 `foregroundChanged`。请读取新状态以验证结果。截图和指针操作只能通过显式窗口对象使用。坐标操作默认使用最近返回截图中的像素;成功读取覆盖该窗口的 AX 或取得截图后,传入 `relative: true` 可使用 0~999 的整数坐标。仅选择窗口不会建立该观察。数值除以 1000 后按窗口尺寸缩放,并限制在窗口内。Host 在返回截图前解析附件归一化和当前模型的图片缩放规则,再将输入换算为提供方的原生窗口坐标。窗口尺寸变化会使截图映射失效,绝对坐标遇到 `SCREENSHOT_REQUIRED` 时需要重新截图。窗口缩放后以 `WINDOW_CHANGED` 拒绝旧坐标;单纯移动窗口不改变窗口内坐标。
提供方声明支持系统指针时,`win.drag(from, to, { useSystemPointer: true })` 和 `win.mouseMove` 共用本次会话的鼠标授权。每次需要移动系统指针时都要显式传入该选项。
`click(target, { holdMs: 800 })` 按住鼠标按钮 800 毫秒后松开。`holdMs` 仅适用于 `click`;它接受非负整数,双击时应用于每次按下;0 表示按下后立即松开,不额外等待。提供方配置 `maxClickHoldMs` 限制显式按住时长,默认 5000 毫秒。指定时长后使用鼠标事件;省略时保留普通点击行为。按住时间计入操作超时,取消或超时会松开按钮。已接收的输入无法撤销;辅助进程被强制终止时无法保证松开。
### 权限控件
+3 -2
View File
@@ -1,7 +1,7 @@
/** Object facade over logged native operations; its caller owns evaluator persistence. */
import type { z } from 'zod'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, MouseMoveTargets, Request, ShowResult, StateResult, WindowsResult } from './protocol.ts'
import { ActionNamesResult, ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, MouseMoveTargets, Request, ShowResult, StateResult, SystemPointerRequest, WindowsResult } from './protocol.ts'
import type { CuaApi, CuaApp, CuaAppHandle, CuaCapabilities, CuaDispatch, CuaOperation, CuaProgramImage, CuaSurface, CuaWindow } from './types.ts'
export type * from './types.ts'
@@ -24,7 +24,7 @@ function requestIssueMessage(issues: readonly z.core.$ZodIssue[], parent: readon
function validatedCall(dispatch: CuaDispatch) {
return (method: CuaOperation['method'], params: Record<string, JsonValue>, options?: object) => {
const request = Request.safeParse({ method, params })
const request = SystemPointerRequest.safeParse({ method, params })
if (!request.success) throw new Error(`${method} ${requestIssueMessage(request.error.issues)}`)
if (options) {
// The facade owns the target and coordinates. The Host validates additional options against its provider schema.
@@ -217,6 +217,7 @@ function createCuaObjects(call: ReturnType<typeof validatedCall>): {
async drag(from, to, options) {
return base.action('drag', { ...coordinateParams(appHandle, windowId),
fromX: from[0], fromY: from[1], toX: to[0], toY: to[1],
...options?.useSystemPointer === undefined ? {} : { useSystemPointer: options.useSystemPointer },
...options?.relative === undefined ? {} : { relative: options.relative },
...options?.mouseButton === undefined ? {} : { mouseButton: options.mouseButton },
...options?.modifiers === undefined ? {} : { modifiers: [...options.modifiers] },
+6 -3
View File
@@ -1,6 +1,8 @@
/** Shared model instructions for native application and window operations. */
const hoverSignature = 'mouseMove(target: string | [number, number], options?: { relative?: boolean })'
const dragSignature = "drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean })"
/** System-prompt section that carries the CUA operation guidance for one Agent. */
export const CUA_PROMPT_SECTION_NAME = 'computer-use:dsh-cua'
@@ -42,7 +44,7 @@ Use an explicit window for screenshots and pointer input. Before coordinate inpu
- ${hoverSignature} -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press.
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
- ${dragSignature} -> ActionResult — drag between two points of one window.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
@@ -61,7 +63,8 @@ Raw tools use { method, params }: include appHandle for app calls and windowId f
*/
export function withSystemPointerGuidance(guidance: string): string {
const signature = 'mouseMove(target: string | [number, number], options?: { relative?: boolean, useSystemPointer?: boolean })'
return `${guidance.replace(hoverSignature, signature)}
const systemDrag = dragSignature.replace('relative?: boolean', 'relative?: boolean, useSystemPointer?: boolean')
return `${guidance.replace(hoverSignature, signature).replace(dragSignature, systemDrag)}
Only if the task cannot be completed without moving the user’s pointer, call await win.mouseMove(target, { useSystemPointer: true }). Prefer an advertised accessibility action, a click on a visible control, or browser tools when possible. The question interrupts the user. When approval is disabled an explicit move can act immediately. Pass true on every physical move, even after approval. Omitting the option or passing false uses the default hover route without prompting. Approval or refusal lasts until this session closes or DSH restarts. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.`
Use win.mouseMove(target, { useSystemPointer: true }) or win.drag(from, to, { useSystemPointer: true }) only when the task requires the system pointer. System drag presses, moves, and releases the selected mouse button in the unobscured foreground window. Omit the option for ordinary window-directed drag. Inspect the application after dispatch before deciding whether to try another route. The first explicit request asks for session permission unless approval is disabled. Approval or refusal applies to moves and drags until the session closes or DSH restarts. Pass true on each physical gesture. A refusal sends no input. If the user dismisses the request, ask again only if they request it. Wait for an outstanding request to finish. Subagents cannot request physical movement.`
}
+4 -3
View File
@@ -37,7 +37,7 @@ export type { CuaPrograms } from './tool-registration.ts'
/** Native executable and per-operation resource bounds. */
export interface CuaConfig {
/** Ask once per live Session before an explicitly requested system-pointer move. */
/** Ask once per live Session before explicitly requested system-pointer moves or drags. */
requireSystemPointerApproval: boolean
/** Preset receiving raw cua; other composed presets receive cua_run_code. False registers raw cua globally. */
agentPreset: string | false
@@ -246,7 +246,8 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
const signal = execution.signal
signal.throwIfAborted()
const client = execution.nativeClient
if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer
if (method === 'drag' && !useSystemPointer) delete params.useSystemPointer
else if (useSystemPointer !== undefined) params.useSystemPointer = useSystemPointer
if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution)
const nativeParams = method === 'findApps'
? { ...params, maxAppMatches: config.maxAppMatches }
@@ -369,7 +370,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend)
owner.coordinates = new CuaCoordinates()
}
const nativeClient = client
const route = request.method === 'mouseMove'
const route = request.method === 'mouseMove' || request.method === 'drag'
? mouseControl?.resolve(agent, 'useSystemPointer' in request.params && request.params.useSystemPointer === true)
: undefined
if (route?.prepare) owner.coordinates.parameters(request)
@@ -11,13 +11,13 @@ export const mouseControlPrompt = {
pt: 'Permitir que o agente mova o ponteiro do mouse?',
},
detail: {
en: 'Allowing moves your pointer to this target now. Later hovers move it only when the agent explicitly requests pointer movement. Your choice is remembered until you close the session or restart DSH.',
zh: '允许后,指针会立即移到目标位置。之后只有智能体明确请求移动鼠标时才会移动指针。会话会记住你的选择,直到关闭会话或重启 DSH。',
ja: '許可するとポインタが今すぐ移動します。以後は、エージェントが明示的に移動を要求した場合だけポインタが動きます。この選択はセッションを閉じるか DSH を再起動するまで有効です。',
es: 'Si aceptas, el puntero se moverá ahora al destino. Después solo se moverá cuando el agente lo solicite expresamente. Tu decisión se recuerda hasta que cierres la sesión o reinicies DSH.',
fr: 'Si vous acceptez, le pointeur se déplace immédiatement sur la cible. Il ne se déplacera ensuite que si l’agent le demande explicitement. Votre choix est mémorisé jusqu’à la fermeture de la session ou au redémarrage de DSH.',
de: 'Bei Zustimmung bewegt sich der Zeiger jetzt zum Ziel. Danach wird er nur bewegt, wenn der Agent dies ausdrücklich anfordert. Ihre Entscheidung gilt, bis Sie die Sitzung schließen oder DSH neu starten.',
ru: 'При разрешении указатель сразу переместится на цель. При следующих наведениях он будет перемещаться только по явному запросу агента. Выбор сохраняется до закрытия сеанса или перезапуска DSH.',
pt: 'Se permitir, o ponteiro irá para o alvo agora. Depois, só se moverá quando o agente solicitar isso explicitamente. Sua escolha vale até encerrar a sessão ou reiniciar o DSH.',
en: 'The agent can move your pointer and drag with a mouse button held when it explicitly requests control. Your choice lasts until you close this session or restart DSH.',
zh: '智能体明确请求使用鼠标时,可以移动指针,也可以按住鼠标键拖动。此选择在关闭本次会话或重启 DSH 前有效。',
ja: 'エージェントが明示的に要求したとき、ポインタの移動やマウスボタンを押したままのドラッグを許可します。この選択はセッションを閉じるか DSH を再起動するまで有効です。',
es: 'Cuando lo solicite expresamente, el agente podrá mover el puntero y arrastrar con un botón pulsado. Tu decisión se recuerda hasta que cierres la sesión o reinicies DSH.',
fr: 'Sur demande explicite, l’agent pourra déplacer le pointeur et faire glisser la souris en maintenant un bouton enfoncé. Votre choix reste valable jusqu’à la fermeture de la session ou au redémarrage de DSH.',
de: 'Auf ausdrückliche Anforderung darf der Agent den Mauszeiger bewegen und mit gedrückter Maustaste ziehen. Ihre Entscheidung gilt, bis Sie die Sitzung schließen oder DSH neu starten.',
ru: 'По явному запросу агент сможет перемещать указатель и перетаскивать объекты с нажатой кнопкой мыши. Выбор сохраняется до закрытия сеанса или перезапуска DSH.',
pt: 'Quando solicitar explicitamente, o agente poderá mover o ponteiro e arrastar com um botão do mouse pressionado. Sua escolha vale até encerrar a sessão ou reiniciar o DSH.',
},
}
@@ -21,7 +21,7 @@ export class MouseControl {
resolve(agent: Agent, requested: boolean): { useSystemPointer: boolean; prepare?: (signal: AbortSignal) => Promise<void> } {
if (!requested) return { useSystemPointer: false }
if (agent.session.header.origin === 'subagent') {
throw new NativeError('MOUSE_CONTROL_UNAVAILABLE', "Delegated tasks cannot move the user's pointer. Use AX hover, click, or performAction. If the task requires a physical hover, report that step in your final result for the main task.")
throw new NativeError('MOUSE_CONTROL_UNAVAILABLE', "Delegated tasks cannot move the user's pointer. Use a window-directed action or report the required system-pointer gesture to the main task.")
}
if (!this.requireApproval || this.decisions.get(agent) === true) return { useSystemPointer: true }
return { useSystemPointer: true, prepare: signal => this.approve(agent, signal) }
+18 -11
View File
@@ -44,7 +44,18 @@ export const MouseMoveTargets = [
z.object(snapshot).strict(), z.object(absoluteCoordinate).strict(), z.object(relativeCoordinate).strict(),
] as const
function requestSchema<T extends z.ZodType>(hover: T) {
const dragTargets = [
z.object({ ...window, ...pointer, snapshotId: z.string().min(1).optional(), relative: z.literal(false).optional(),
fromX: point, fromY: point, toX: point, toY: point }).strict(),
z.object({ ...window, ...pointer, snapshotId: z.string().min(1).optional(), relative: relativeCoordinate.relative,
fromX: relativePoint, fromY: relativePoint, toX: relativePoint, toY: relativePoint }).strict(),
] as const
const systemPointerOption = {
useSystemPointer: z.boolean().optional().describe('Request use of the system pointer. The Host checks permission before dispatch.'),
}
function requestSchema<H extends z.ZodType, D extends z.ZodType>(hover: H, drag: D) {
return z.discriminatedUnion('method', [
operation('getCapabilities', {}), operation('listApps', {}),
operation('findApps', { query: z.string().min(1, 'Expected a non-empty search string').regex(/\S/, 'Expected a non-empty search string') }),
@@ -80,23 +91,19 @@ function requestSchema<T extends z.ZodType>(hover: T) {
z.object({ ...relativeCoordinate,
deltaLinesX: z.number().int().min(-10).max(10), deltaLinesY: z.number().int().min(-10).max(10) }).strict(),
]) }).strict(),
z.object({ method: z.literal('drag'), params: z.union([
z.object({ ...window, ...pointer, snapshotId: z.string().min(1).optional(), relative: z.literal(false).optional(),
fromX: point, fromY: point, toX: point, toY: point }).strict(),
z.object({ ...window, ...pointer, snapshotId: z.string().min(1).optional(), relative: relativeCoordinate.relative,
fromX: relativePoint, fromY: relativePoint, toX: relativePoint, toY: relativePoint }).strict(),
]) }).strict(),
z.object({ method: z.literal('drag'), params: drag }).strict(),
operation('screenshot', window),
])
}
/** Portable model operations, including standard hover without a system-pointer option. */
export const Request = requestSchema(z.union(MouseMoveTargets))
export const Request = requestSchema(z.union(MouseMoveTargets), z.union(dragTargets))
/** Model operations for providers that can move the user's system pointer. */
export const SystemPointerRequest = requestSchema(z.union(MouseMoveTargets.map(target => target.extend({
useSystemPointer: z.boolean().optional().describe('Request use of the system pointer. The Host checks permission before dispatch.'),
}))))
export const SystemPointerRequest = requestSchema(
z.union(MouseMoveTargets.map(target => target.extend(systemPointerOption))),
z.union(dragTargets.map(target => target.extend(systemPointerOption))),
)
/** Native resource fields supplied or completed by the Host before dispatch. */
export const NativeResourceParameters = {
+2 -2
View File
@@ -71,7 +71,7 @@ export type CuaMouseButton = NonNullable<CuaParameters<'click'>['mouseButton']>
*/
export type CuaClickOptions = Pick<CuaParameters<'click'>, 'mouseButton' | 'clickCount' | 'modifiers' | 'holdMs'> & CuaCoordinateOptions
/** One same-window drag; omitted button is left and omitted modifiers are empty. */
export type CuaDragOptions = Pick<CuaParameters<'drag'>, 'mouseButton' | 'modifiers'> & CuaCoordinateOptions
export type CuaDragOptions = Pick<CuaParameters<'drag'>, 'mouseButton' | 'modifiers' | 'useSystemPointer'> & CuaCoordinateOptions
/** Clipboard representation delivered through the application's Paste command. */
export type CuaPasteOptions = Pick<CuaParameters<'paste'>, 'format'>
/** Adjacent literal context disambiguates repeated text; cursor modes collapse the matched range. */
@@ -208,7 +208,7 @@ export interface CuaWindow extends CuaSurface {
* Drag between points in one window while holding the selected button and modifiers.
* @param from - starting screenshot-local point or integer ratio.
* @param to - destination in the same coordinate mode.
* @param options - button, modifiers and coordinate mode for the complete gesture.
* @param options - button, modifiers, coordinate mode, and optional system-pointer control on supported providers.
* @returns dispatch evidence.
*/
drag(from: readonly [number, number], to: readonly [number, number], options?: CuaDragOptions): Promise<CuaActionResult>
+2 -2
View File
@@ -229,10 +229,10 @@ describe('pointer buttons and modifiers', () => {
appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', x: 10, y: 20,
mouseButton: 'left', clickCount: 1, modifiers: ['command'],
} })
await window.drag([10, 20], [30, 40], { mouseButton: 'middle', modifiers: ['shift', 'option'] })
await window.drag([10, 20], [30, 40], { mouseButton: 'middle', modifiers: ['shift', 'option'], useSystemPointer: true })
expect(f.dispatch).toHaveBeenLastCalledWith({ method: 'drag', params: {
appHandle: 'app-17', windowId: '23', snapshotId: 'snapshot-2', fromX: 10, fromY: 20, toX: 30, toY: 40,
mouseButton: 'middle', modifiers: ['shift', 'option'],
useSystemPointer: true, mouseButton: 'middle', modifiers: ['shift', 'option'],
} })
const count = f.dispatch.mock.calls.length
await expect(window.click(element('0'), { mouseButton: 'middle', clickCount: 2 })).rejects.toThrow('Only left double-click')
@@ -251,9 +251,13 @@ it('requires keyboard scopes', () => {
expect(CapabilitiesResult.safeParse(capabilities).success).toBe(false)
})
it('admits the pointer option only in the system-pointer model schema and only as a boolean', () => {
const target = { appHandle: 'app', windowId: '1', x: 0, y: 0 }
const request = { method: 'mouseMove', params: { ...target, useSystemPointer: true } }
it.each<[string, Record<string, number | boolean>]>([
['mouseMove', { x: 0, y: 0 }],
['drag', { fromX: 1, fromY: 2, toX: 3, toY: 4 }],
['drag', { relative: true, fromX: 1, fromY: 2, toX: 3, toY: 4 }],
])('admits %s system-pointer control only for supporting providers', (method, points) => {
const target = { appHandle: 'app', windowId: '1', ...points }
const request = { method, params: { ...target, useSystemPointer: true } }
expect(Request.safeParse(request).success).toBe(false)
expect(SystemPointerRequest.safeParse(request).success).toBe(true)
expect(SystemPointerRequest.safeParse({ ...request, params: { ...target, useSystemPointer: 'true' } }).success).toBe(false)
@@ -2111,6 +2111,39 @@
}
]
},
{
"kind": "chunks",
"chunks": [
{
"type": "block-start",
"index": 0,
"blockType": "tool-call"
},
{
"type": "block-end",
"index": 0,
"block": {
"type": "tool-call",
"id": "cua-system-drag",
"name": "cua",
"arguments": "{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":\"7\",\"fromX\":150,\"fromY\":200,\"toX\":600,\"toY\":650,\"relative\":true,\"useSystemPointer\":true}}"
}
},
{
"type": "usage",
"usage": {
"inputTokens": 3,
"outputTokens": 3
}
},
{
"type": "finish",
"reason": {
"kind": "tool-calls"
}
}
]
},
{
"kind": "chunks",
"chunks": [