diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 5ed55c261a..0d8c9f4b67 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 7b30b973a849247d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: e2e1797ad6b73f25 - zh: 35b7a06e471e433c + en: 0cc818af177bab43 + zh: 2e90b8bef2b377c0 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: e7909c9b43e44fbc zh: 98949877d4ea3a86 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 74887ae936..f550425863 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -42,6 +42,7 @@ The dump command checks profile composition without a model request. For a real | `helperPath` | package-owned executable | Optional absolute native executable override. | | `buildTimeoutMs` | `300000` | Maximum native preparation time. | | `timeoutMs` | `30000` | Per-operation deadline; cancellation can leave partial input. | +| `recentActivityWindowMs` | `60000` | Lookback for advisory activity reports, in milliseconds; never reserves or blocks an application. | | `connectTimeoutMs` | `5000` | Deadline for connecting to or starting the shared helper. | | `screenshotTimeoutMs` | `5000` | Screenshot deadline including queue time, capped by `timeoutMs`. | | `axTimeoutMs` | `3000` | Deadline per Accessibility system call, configured independently of the complete operation. | @@ -53,6 +54,8 @@ The dump command checks profile composition without a model request. For a real | `dragDurationMs` / `dragSteps` | `400` / `20` | Duration and movement segments for a drag. | | `textEventIntervalMs` | `0.25` | Delay after each Unicode down/up event, from 0 to 1000 ms. Chord timing is independent. | +App observations, screenshots and successful input replies include `recentActivity`: the latest matching attempt by another connected Agent and the latest detected external input within the configured lookback. Application-level records also apply to individual windows. External input can come from a person or automation; neither source proves a completed change or continued use. The shared helper starts passive monitoring after an authorized application is accessed, records only input categories and timing, and excludes its own input events. Keyboard events remain application-scoped; mouse events name a window only when its ownership is verified. Unavailable input monitoring and secure input are reported explicitly. These advisories do not block operations; no recorded activity does not guarantee inactivity. The object API emits advisories even with `emit:false`. + The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. For example, `getApp` returns the `appHandle` needed by `listWindows`, `getState` and input operations. Keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. Key chords use `+` between modifiers and the key. Use `+` for the plus key, `cmd++` for Command-plus, or the key name `plus`; an unfinished chord such as `cmd+` is rejected. @@ -184,6 +187,8 @@ App and Window methods: Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a window is hidden or minimized, try app.show() or window.show() and read fresh state. show requests unhide and unminimize without activation, raising or switching Spaces; it chooses the explicit, focused, main or sole AX window. A null windowId means no window was selected for restoration. foregroundChanged compares the front app and top window before and after the request; null means unavailable, and delayed focus changes remain possible. If restoration is unsupported or the window remains unusable, including another Space or Stage Manager, explain the needed foreground step, use app.activate() or an advertised raise action, and read fresh state. Completing the task takes priority when foreground access is necessary. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. +Recent activity is advisory history, not a lock, reservation, or instruction to stop. You may continue operating an application even when recentActivity reports another actor. Use the task and current UI to decide whether to re-observe or coordinate with the user. other-agent means another connected Agent attempted an operation; external-input means detected input outside this helper and may come from a person, another Agent, or other automation. Neither confirms a successful change or continued use. A null windowId means application-level activity whose window is unknown. The host configures the lookback (default one minute). Monitoring begins when an authorized application is accessed; missing activity does not prove nobody acted. unavailable or secure-input means external input observation is incomplete; do not infer inactivity. Activity advisories are emitted even with emit:false. + Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. Absolute coordinate input requires a fresh screenshot of that window. Relative input can use a successful AX observation or screenshot. SCREENSHOT_REQUIRED means capture a fresh screenshot before using pixel coordinates. For click and hover, coordinate targets must be [x, y], for example hover([650, 400], {relative:true}). A bare number such as hover(650) is always an AX element index. The relative option applies only to coordinate targets, not AX indices. Window resizing since the latest observation rejects coordinate input; movement alone preserves window-local coordinates. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. Hover first uses advertised AX alternate UI without moving the system cursor, preserving revealed descendants until the pointer target leaves their region. When unavailable, it moves the visible system cursor without pressing a button; that route requires the target point to be unobscured in the foreground app. FOREGROUND_REQUIRED requires explicit activation or raising and a fresh observation before retrying. Returning, AX reads and screenshots do not restore the previous point. Wait for the application's hover delay, observe, then hover into the revealed controls before clicking. Use successive hover calls for intermediate points. The result reports hoverRoute and systemPointerMoved. Other input or application changes can interrupt the interaction; app objects do not reserve applications between calls. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 43c37296bb..bd4bddec2d 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -42,6 +42,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. | `helperPath` | 包内可执行文件 | 可选的原生可执行文件绝对路径覆盖。 | | `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 | | `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 | +| `recentActivityWindowMs` | `60000` | 近期活动提示的回看时长,单位为毫秒;不预留或阻止操作应用。 | | `connectTimeoutMs` | `5000` | 连接或启动共享 helper 的截止时间。 | | `screenshotTimeoutMs` | `5000` | 截图总期限,包含排队时间,且不超过 `timeoutMs`。 | | `axTimeoutMs` | `3000` | 每次 Accessibility 系统调用的截止时间,与完整操作截止独立配置。 | @@ -53,6 +54,8 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. | `dragDurationMs` / `dragSteps` | `400` / `20` | 拖动时长和移动分段数。 | | `textEventIntervalMs` | `0.25` | 每个 Unicode 按下或抬起事件后的间隔,范围为 0 至 1000 毫秒。组合键的节奏独立。 | +应用观察、截图和成功的输入回复包含 `recentActivity`:配置时长内另一个已连接 Agent 最近发起的相关操作,以及最近检测到的外部输入。应用级记录也适用于其各个窗口。外部输入可能来自人或自动化程序;两类来源都不能证明界面已改变或仍在使用。共享 helper 在已授权应用被访问后开始被动监听,只记录输入类别和时间,并排除自身输入事件。键盘事件只归属到应用;鼠标事件只有在确认窗口归属后才标明窗口。输入监听不可用和安全输入状态会明确反馈。这些提示不阻止操作;没有活动记录不代表无人操作。对象 API 即使设置 `emit:false` 也会输出活动提示。 + [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。例如,`getApp` 返回 `listWindows`、`getState` 和输入操作所需的 `appHandle`。 数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。组合键用 `+` 分隔修饰键与按键。加号键写作 `+`,Command 加号写作 `cmd++`,也可以使用键名 `plus`;`cmd+` 这类缺少按键的输入会被拒绝。 @@ -184,6 +187,8 @@ App and Window methods: Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a window is hidden or minimized, try app.show() or window.show() and read fresh state. show requests unhide and unminimize without activation, raising or switching Spaces; it chooses the explicit, focused, main or sole AX window. A null windowId means no window was selected for restoration. foregroundChanged compares the front app and top window before and after the request; null means unavailable, and delayed focus changes remain possible. If restoration is unsupported or the window remains unusable, including another Space or Stage Manager, explain the needed foreground step, use app.activate() or an advertised raise action, and read fresh state. Completing the task takes priority when foreground access is necessary. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. +Recent activity is advisory history, not a lock, reservation, or instruction to stop. You may continue operating an application even when recentActivity reports another actor. Use the task and current UI to decide whether to re-observe or coordinate with the user. other-agent means another connected Agent attempted an operation; external-input means detected input outside this helper and may come from a person, another Agent, or other automation. Neither confirms a successful change or continued use. A null windowId means application-level activity whose window is unknown. The host configures the lookback (default one minute). Monitoring begins when an authorized application is accessed; missing activity does not prove nobody acted. unavailable or secure-input means external input observation is incomplete; do not infer inactivity. Activity advisories are emitted even with emit:false. + Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. Absolute coordinate input requires a fresh screenshot of that window. Relative input can use a successful AX observation or screenshot. SCREENSHOT_REQUIRED means capture a fresh screenshot before using pixel coordinates. For click and hover, coordinate targets must be [x, y], for example hover([650, 400], {relative:true}). A bare number such as hover(650) is always an AX element index. The relative option applies only to coordinate targets, not AX indices. Window resizing since the latest observation rejects coordinate input; movement alone preserves window-local coordinates. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. Hover first uses advertised AX alternate UI without moving the system cursor, preserving revealed descendants until the pointer target leaves their region. When unavailable, it moves the visible system cursor without pressing a button; that route requires the target point to be unobscured in the foreground app. FOREGROUND_REQUIRED requires explicit activation or raising and a fresh observation before retrying. Returning, AX reads and screenshots do not restore the previous point. Wait for the application's hover delay, observe, then hover into the revealed controls before clicking. Use successive hover calls for intermediate points. The result reports hoverRoute and systemPointerMoved. Other input or application changes can interrupt the interaction; app objects do not reserve applications between calls. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 80c8df17af..8a5bda7a37 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -127,6 +127,14 @@ actor AXWorker { catch { forget(handle); throw error } return identity } + func activityTarget(_ params: RequestParameters) throws -> ActivityTarget { + let handle = try params.string("appHandle") + let identity = try validateIdentity(handle) + let window = try params.optionalWindowID() + let snapshotID = try params.optionalString("snapshotId") + let scope = try snapshotID.map { try snapshot(handle, $0).scope.windowID } + return ActivityTarget(process: identity, windowID: window ?? scope ?? nil) + } private func acquire(_ identity: ProcessIdentity) throws -> String { if let old = targets.first(where: { if case .running(let value) = $0.value { return value.pid == identity.pid }; return false }) { if case .running(let value) = old.value, value == identity { return old.key } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/ExternalInputMonitor.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/ExternalInputMonitor.swift new file mode 100644 index 0000000000..f45963b8f7 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/ExternalInputMonitor.swift @@ -0,0 +1,74 @@ +// Passive input metadata only. Unmarked events may come from people or other automation. +import AppKit +import Carbon +import CoreGraphics +import Foundation + +@MainActor final class ExternalInputMonitor { + private let activity: RecentActivity + private var tap: CFMachPort? + private var source: CFRunLoopSource? + + init(activity: RecentActivity) { self.activity = activity } + + var status: String { + if IsSecureEventInputEnabled() { return "secure-input" } + guard let tap, CGEvent.tapIsEnabled(tap: tap) else { return "unavailable" } + return "listening" + } + + func start() { + guard tap == nil else { return } + let types: [CGEventType] = [.leftMouseDown, .rightMouseDown, .otherMouseDown, .scrollWheel, .keyDown] + let mask = types.reduce(CGEventMask(0)) { $0 | (CGEventMask(1) << $1.rawValue) } + guard let created = CGEvent.tapCreate(tap: .cgAnnotatedSessionEventTap, place: .tailAppendEventTap, + options: .listenOnly, eventsOfInterest: mask, callback: { _, type, event, info in + guard let info else { return Unmanaged.passUnretained(event) } + MainActor.assumeIsolated { + let monitor = Unmanaged.fromOpaque(info).takeUnretainedValue() + monitor.receive(type, event: event) + } + return Unmanaged.passUnretained(event) + }, userInfo: Unmanaged.passUnretained(self).toOpaque()), + let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, created, 0) else { return } + tap = created + source = runLoopSource + CFRunLoopAddSource(CFRunLoopGetMain(), runLoopSource, .commonModes) + CGEvent.tapEnable(tap: created, enable: true) + } + + func stop() { + if let source { CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes) } + if let tap { CGEvent.tapEnable(tap: tap, enable: false); CFMachPortInvalidate(tap) } + source = nil + tap = nil + } + + func receive(_ type: CGEventType, event: CGEvent) { + if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { + // The next request retries registration; an unavailable monitor remains visible in replies. + stop() + return + } + guard event.getIntegerValueField(.eventSourceUnixProcessID) != Int64(getpid()) else { return } + let rawPID = event.getIntegerValueField(.eventTargetUnixProcessID) + guard let pid = Int32(exactly: rawPID), pid > 0, let process = activity.trackedProcess(pid), + (try? NativePlatform.identity(pid)) == process else { return } + let operation: String + let windowID: UInt32? + switch type { + case .keyDown: + operation = "keyboard" + // Key events do not identify a reliable window; sampling later focus could misattribute them. + windowID = nil + case .leftMouseDown, .rightMouseDown, .otherMouseDown, .scrollWheel: + operation = type == .scrollWheel ? "scroll" : "click" + let rawWindow = event.getIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent) + if let id = UInt32(exactly: rawWindow), id > 0, + (try? NativePlatform.ownedWindow(pid, id)) != nil { windowID = id } + else { windowID = nil } + default: return + } + activity.record(ActivityTarget(process: process, windowID: windowID), owner: nil, operation: operation) + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift index 762ecaea49..866718e0c2 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Protocol.swift @@ -102,7 +102,7 @@ struct NativeRequest: Sendable { } } -struct ProcessIdentity: Equatable, Sendable { +struct ProcessIdentity: Hashable, Sendable { let pid: Int32 let startedSeconds: UInt64 let startedMicroseconds: UInt64 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift new file mode 100644 index 0000000000..41816da4e2 --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RecentActivity.swift @@ -0,0 +1,67 @@ +// Shared recent input history; records describe attempts, never exclusive ownership or verified effects. +import Foundation +import Dispatch + +struct ActivityTarget: Hashable, Sendable { + let process: ProcessIdentity + let windowID: UInt32? +} + +@MainActor final class RecentActivity { + private struct Record { + let target: ActivityTarget + let owner: UUID? + let operation: String + let time: Double + } + private struct Client { + let lookback: Double + var processes: Set = [] + } + private var clients: [UUID: Client] = [:] + private var records: [Record] = [] + private let now: () -> Double + + init(now: @escaping () -> Double = { Double(DispatchTime.now().uptimeNanoseconds) / 1_000_000_000 }) { + self.now = now + } + func connect(_ owner: UUID, lookback: Double) { clients[owner] = Client(lookback: lookback) } + func disconnect(_ owner: UUID) { clients.removeValue(forKey: owner); prune() } + func watch(_ target: ActivityTarget, owner: UUID) { clients[owner]?.processes.insert(target.process) } + func trackedProcess(_ pid: Int32) -> ProcessIdentity? { + clients.values.lazy.flatMap(\.processes).first { $0.pid == pid } + } + func record(_ target: ActivityTarget, owner: UUID?, operation: String) { + prune() + guard clients.values.contains(where: { $0.processes.contains(target.process) }) else { return } + records.removeAll { $0.target == target && $0.owner == owner } + records.append(Record(target: target, owner: owner, operation: operation, time: now())) + } + func report(_ target: ActivityTarget, owner: UUID, monitoring: String) -> JSONValue { + prune() + guard let client = clients[owner] else { return .null } + let timestamp = now() + let matching = records.filter { + $0.owner != owner && $0.target.process == target.process && + (target.windowID == nil || $0.target.windowID == nil || $0.target.windowID == target.windowID) && + timestamp - $0.time <= client.lookback + } + // One latest record per source bounds model output independently of input frequency. + let recent = [matching.last { $0.owner != nil }, matching.last { $0.owner == nil }].compactMap { $0 } + return .object([ + "lookbackMs": .number(client.lookback * 1000), + "externalInputMonitoring": .string(monitoring), + "events": .array(recent.map { record in .object([ + "source": .string(record.owner == nil ? "external-input" : "other-agent"), + "windowId": record.target.windowID.map { .number(Double($0)) } ?? .null, + "ageMs": .number(max(0, (timestamp - record.time) * 1000).rounded(.down)), + "operation": .string(record.operation), + ]) }), + ]) + } + private func prune() { + let cutoff = now() - (clients.values.map(\.lookback).max() ?? 0) + let processes = Set(clients.values.flatMap(\.processes)) + records.removeAll { $0.time < cutoff || !processes.contains($0.target.process) } + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index ae9969cb1d..9a5927990a 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -14,6 +14,9 @@ import Darwin private let writer: JSONLWriter private let channel: SharedSocket private let scheduler: RequestScheduler + private let activity: RecentActivity + private let inputMonitor: ExternalInputMonitor + private let owner: UUID private let onClose: @MainActor @Sendable () -> Void private let onFatal: @Sendable (NativeFailure, Double) -> Void private var deadline: NativeDeadline? @@ -28,6 +31,7 @@ import Darwin init(configuration: HelperConfiguration, capture: WindowCapture, channel: SharedSocket, cancellation: CancellationLatch, scheduler: RequestScheduler, writer: JSONLWriter, + activity: RecentActivity, inputMonitor: ExternalInputMonitor, owner: UUID, onClose: @escaping @MainActor @Sendable () -> Void, onFatal: @escaping @Sendable (NativeFailure, Double) -> Void) { self.configuration = configuration @@ -35,6 +39,10 @@ import Darwin self.cancellation = cancellation self.channel = channel self.scheduler = scheduler + self.activity = activity + self.inputMonitor = inputMonitor + self.owner = owner + activity.connect(owner, lookback: configuration.recentActivityWindowSeconds) self.onClose = onClose self.onFatal = onFatal worker = AXWorker(cancellation: cancellation, axTimeout: configuration.axTimeoutSeconds, @@ -160,6 +168,14 @@ import Darwin private func execute(_ request: NativeRequest, trace: ScreenshotTrace?) async throws -> JSONValue { let params = try RequestParameters(request) if request.method == "screenshot" { try capture.requireAvailable() } + let target: ActivityTarget? + if params.contains("appHandle"), request.method != "launchApp" { + target = try await worker.activityTarget(params) + if let target { activity.watch(target, owner: owner); inputMonitor.start() } + } else { target = nil } + let observes = ["getState", "screenshot", "listWindows"].contains(request.method) + // Attempts may have partial effects even when the operation later fails or is cancelled. + if let target, !observes { activity.record(target, owner: owner, operation: request.method) } let requiresCatalog = ["getApp", "listApps", "findApps", "typeText", "pressKey"].contains(request.method) let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil) let result: JSONValue @@ -199,6 +215,10 @@ import Darwin result = try await worker.finishLaunch(plan, pid: pid) } } + if let target, var fields = result.object { + fields["recentActivity"] = activity.report(target, owner: owner, monitoring: inputMonitor.status) + return .object(fields) + } return result } private func performForeground(_ plan: ForegroundPlan, requestID: String) async throws -> JSONValue { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift index e38ece600d..e5575854e7 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift @@ -22,6 +22,7 @@ struct HelperConfiguration: Sendable { var textEventIntervalSeconds: Double = 0.00025 var timeoutSeconds: Double = 30 var screenshotTimeoutSeconds: Double = 5 + var recentActivityWindowSeconds: Double = 60 init(arguments: [String]) throws { var index = 0 while index < arguments.count { @@ -43,6 +44,11 @@ struct HelperConfiguration: Sendable { case "--shutdown-grace-ms": guard let value = Double(text), value.isFinite, value > 0 else { throw RequestParameters.invalid("Shutdown grace must be positive") } shutdownGraceSeconds = value / 1000 + case "--recent-activity-window-ms": + guard let value = Double(text), value.isFinite, value.rounded() == value, (1...2147483647).contains(value) else { + throw RequestParameters.invalid("Recent activity window must be an integer from 1 to 2147483647 milliseconds") + } + recentActivityWindowSeconds = value / 1000 case "--timeout-ms", "--screenshot-timeout-ms": guard let value = Double(text), value.isFinite, value > 0 else { throw RequestParameters.invalid("Operation timeout must be positive") } if key == "--timeout-ms" { timeoutSeconds = value / 1000 } @@ -58,7 +64,7 @@ struct HelperConfiguration: Sendable { guard let fields = decoded.object, Set(fields.keys) == ["type", "protocol", "runtimeKey", "config"], fields["type"] == .string("hello"), fields["protocol"] == .number(1), fields["runtimeKey"] == .string(runtimeKey), let config = fields["config"]?.object, - Set(config.keys) == ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "screenshotTimeoutMs", "timeoutMs", "graceMs"] else { + Set(config.keys) == ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "screenshotTimeoutMs", "timeoutMs", "graceMs", "recentActivityWindowMs"] else { throw NativeFailure(code: "NATIVE_PROTOCOL", message: "Expected shared helper protocol 1 hello for this runtime") } func number(_ name: String) throws -> String { @@ -73,7 +79,7 @@ struct HelperConfiguration: Sendable { "--max-request-bytes", number("maxRequestBytes"), "--max-response-bytes", number("maxResponseBytes"), "--ax-timeout-ms", number("axTimeoutMs"), "--text-event-interval-ms", number("textEventIntervalMs"), "--screenshot-timeout-ms", number("screenshotTimeoutMs"), "--timeout-ms", number("timeoutMs"), - "--shutdown-grace-ms", number("graceMs"), + "--shutdown-grace-ms", number("graceMs"), "--recent-activity-window-ms", number("recentActivityWindowMs"), ]) } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperProxy.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperProxy.swift index cffb83da0e..f5421b2164 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperProxy.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperProxy.swift @@ -17,6 +17,7 @@ enum SharedHelperProxy { "axTimeoutMs": .number(Double(configuration.axTimeoutSeconds) * 1000), "textEventIntervalMs": .number(configuration.textEventIntervalSeconds * 1000), "screenshotTimeoutMs": .number(configuration.screenshotTimeoutSeconds * 1000), "timeoutMs": .number(configuration.timeoutSeconds * 1000), "graceMs": .number(configuration.shutdownGraceSeconds * 1000), + "recentActivityWindowMs": .number(configuration.recentActivityWindowSeconds * 1000), ])]) try channel.write(JSONEncoder().encode(hello) + Data([10]), timeout: configuration.timeoutSeconds) let frames = Frames(channel: channel, limit: configuration.maxResponseBytes) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperServer.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperServer.swift index 2de82bce2c..daa45f48be 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperServer.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/SharedHelperServer.swift @@ -75,6 +75,8 @@ final class NativeSignals { private let lifetime: SharedHelperLifetime private let scheduler = RequestScheduler() private let capture = WindowCapture() + private let activity = RecentActivity() + private lazy var inputMonitor = ExternalInputMonitor(activity: activity) private let instanceID = UUID().uuidString private var connections: [UUID: RequestCoordinator] = [:] private var startupDeadline: NativeDeadline? @@ -157,7 +159,7 @@ final class NativeSignals { catch { channel.shutdown(); disconnected(id); return } let lifetime = self.lifetime let coordinator = RequestCoordinator(configuration: configuration, capture: capture, channel: channel, cancellation: cancellation, - scheduler: scheduler, writer: writer, onClose: { [weak self] in + scheduler: scheduler, writer: writer, activity: activity, inputMonitor: inputMonitor, owner: id, onClose: { [weak self] in channel.shutdown() self?.disconnected(id) }, onFatal: { [weak self] _, grace in @@ -171,6 +173,7 @@ final class NativeSignals { private func disconnected(_ id: UUID) { connections.removeValue(forKey: id) + activity.disconnect(id) lifetime.remove(id) exitIfEmpty() } @@ -179,6 +182,7 @@ final class NativeSignals { private func exitIfEmpty() { guard let status = lifetime.exitStatusIfEmpty() else { return } + inputMonitor.stop() listener.shutdown() unlink(options.socketPath) unlink(options.readyPath) diff --git a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py index 85a74e7e64..65e3ff2ca2 100644 --- a/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py +++ b/packages/experimental/cua-macos/native/tests/shared_helper_e2e.py @@ -22,7 +22,7 @@ from native_test_support import BINARY, ROOT, line, stop CONFIG = {"maxRequestBytes": 1024 * 1024, "maxResponseBytes": 32 * 1024 * 1024, - "axTimeoutMs": 3000, "textEventIntervalMs": 0.25, "screenshotTimeoutMs": 5000, + "axTimeoutMs": 3000, "textEventIntervalMs": 0.25, "recentActivityWindowMs": 60000, "screenshotTimeoutMs": 5000, "timeoutMs": 30000, "graceMs": 3000} diff --git a/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift b/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift new file mode 100644 index 0000000000..a3bec88f48 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/RecentActivityTests.swift @@ -0,0 +1,98 @@ +// Activity history uses an injected monotonic clock and connection-scoped application identities. +import CoreGraphics +import Foundation +import Testing +@testable import CuaNative + +@Test @MainActor func reportsOtherActorsWithinEachConnectionsLookback() { + var time = 100.0 + let history = RecentActivity(now: { time }) + let a = UUID(), b = UUID() + let app = ProcessIdentity(pid: 42, startedSeconds: 1, startedMicroseconds: 0) + let first = ActivityTarget(process: app, windowID: 10) + let second = ActivityTarget(process: app, windowID: 11) + history.connect(a, lookback: 60) + history.connect(b, lookback: 5) + history.watch(first, owner: a) + history.watch(first, owner: b) + history.record(first, owner: b, operation: "click") + history.record(second, owner: b, operation: "scroll") + #expect(history.report(first, owner: b, monitoring: "listening")["events"] == .array([])) + #expect(history.report(first, owner: a, monitoring: "listening")["events"] == .array([ + .object(["source": .string("other-agent"), "windowId": .number(10), "ageMs": .number(0), "operation": .string("click")]), + ])) + time += 6 + history.record(first, owner: a, operation: "setValue") + #expect(history.report(first, owner: a, monitoring: "listening")["events"] != .array([])) + time += 6 + #expect(history.report(first, owner: b, monitoring: "listening")["events"] == .array([])) + time = 160 + #expect(history.report(first, owner: a, monitoring: "listening")["events"] != .array([])) + time += 0.001 + #expect(history.report(first, owner: a, monitoring: "listening")["events"] == .array([])) +} + +@Test @MainActor func appScopedInputAppliesToEveryWindowAndHistoryIsBoundedPerSource() { + let history = RecentActivity(now: { 1 }) + let a = UUID(), b = UUID() + let app = ProcessIdentity(pid: 42, startedSeconds: 1, startedMicroseconds: 0) + let target = ActivityTarget(process: app, windowID: 10) + history.connect(a, lookback: 60) + history.connect(b, lookback: 60) + history.watch(target, owner: a) + for _ in 0..<100 { + history.record(target, owner: b, operation: "click") + history.record(ActivityTarget(process: app, windowID: nil), owner: nil, operation: "keyboard") + } + let report = history.report(target, owner: a, monitoring: "unavailable") + #expect(report["externalInputMonitoring"] == .string("unavailable")) + #expect(report["events"] == .array([ + .object(["source": .string("other-agent"), "windowId": .number(10), "ageMs": .number(0), "operation": .string("click")]), + .object(["source": .string("external-input"), "windowId": .null, "ageMs": .number(0), "operation": .string("keyboard")]), + ])) + history.disconnect(b) + #expect(history.report(target, owner: a, monitoring: "listening")["events"] == report["events"]) + history.disconnect(a) + #expect(history.trackedProcess(42) == nil) + history.connect(a, lookback: 60) + history.watch(target, owner: a) + #expect(history.report(target, owner: a, monitoring: "listening")["events"] == .array([])) +} + +@Test @MainActor func doesNotShareHistoryAcrossProcessLifetimesOrUnobservedApps() { + let history = RecentActivity(now: { 1 }) + let owner = UUID() + let old = ActivityTarget(process: ProcessIdentity(pid: 42, startedSeconds: 1, startedMicroseconds: 0), windowID: 1) + let new = ActivityTarget(process: ProcessIdentity(pid: 42, startedSeconds: 2, startedMicroseconds: 0), windowID: 1) + history.connect(owner, lookback: 60) + history.record(old, owner: nil, operation: "click") + history.watch(old, owner: owner) + #expect(history.report(old, owner: owner, monitoring: "listening")["events"] == .array([])) + history.record(old, owner: nil, operation: "click") + #expect(history.report(new, owner: owner, monitoring: "listening")["events"] == .array([])) + #expect(history.report(old, owner: UUID(), monitoring: "listening") == .null) +} + +@Test @MainActor func externalInputExcludesHelperEventsAndKeepsUnknownWindowsAtAppScope() throws { + let history = RecentActivity(now: { 1 }) + let owner = UUID() + let target = ActivityTarget(process: try NativePlatform.identity(getpid()), windowID: nil) + history.connect(owner, lookback: 60) + history.watch(target, owner: owner) + let monitor = ExternalInputMonitor(activity: history) + defer { monitor.stop() } + let event = try #require(CGEvent(source: nil)) + event.setIntegerValueField(.eventTargetUnixProcessID, value: Int64(getpid())) + event.setIntegerValueField(.eventSourceUnixProcessID, value: Int64(getpid())) + monitor.receive(.keyDown, event: event) + #expect(history.report(target, owner: owner, monitoring: "listening")["events"] == .array([])) + event.setIntegerValueField(.eventSourceUnixProcessID, value: 0) + monitor.receive(.mouseMoved, event: event) + #expect(history.report(target, owner: owner, monitoring: "listening")["events"] == .array([])) + monitor.receive(.keyDown, event: event) + #expect(history.report(target, owner: owner, monitoring: "listening")["events"] == .array([ + .object(["source": .string("external-input"), "windowId": .null, "ageMs": .number(0), "operation": .string("keyboard")]), + ])) + monitor.receive(.tapDisabledByTimeout, event: event) + #expect(monitor.status != "listening") +} diff --git a/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift b/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift index 4dc70ccb93..ef59e3f8fd 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift @@ -10,7 +10,7 @@ private func hello(overrides: [String: JSONValue] = [:]) throws -> Data { var config: [String: JSONValue] = [ "maxRequestBytes": .number(4096), "maxResponseBytes": .number(8192), "axTimeoutMs": .number(250), "textEventIntervalMs": .number(0.5), "screenshotTimeoutMs": .number(2000), - "timeoutMs": .number(8000), "graceMs": .number(500), + "recentActivityWindowMs": .number(45000), "timeoutMs": .number(8000), "graceMs": .number(500), ] config.merge(overrides) { _, value in value } return try JSONEncoder().encode(JSONValue.object([ @@ -26,6 +26,7 @@ private func hello(overrides: [String: JSONValue] = [:]) throws -> Data { #expect(configuration.textEventIntervalSeconds == 0.0005) #expect(configuration.screenshotTimeoutSeconds == 2) #expect(configuration.timeoutSeconds == 8) + #expect(configuration.recentActivityWindowSeconds == 45) #expect(configuration.shutdownGraceSeconds == 0.5) #expect(throws: NativeFailure.self) { try HelperConfiguration(hello: hello(), runtimeKey: String(repeating: "b", count: 64)) @@ -36,7 +37,8 @@ private func hello(overrides: [String: JSONValue] = [:]) throws -> Data { ("maxRequestBytes", JSONValue.number(1023)), ("maxResponseBytes", .number(1.5)), ("axTimeoutMs", .number(0)), ("textEventIntervalMs", .number(-1)), ("screenshotTimeoutMs", .number(0)), ("timeoutMs", .string("8000")), ("graceMs", .number(-1)), - ("unexpected", .bool(true)), + ("recentActivityWindowMs", .number(0)), ("recentActivityWindowMs", .number(1.5)), + ("recentActivityWindowMs", .number(2147483648)), ("unexpected", .bool(true)), ]) func refusesInvalidSharedConfiguration(_ name: String, _ value: JSONValue) throws { #expect(throws: NativeFailure.self) { try HelperConfiguration(hello: hello(overrides: [name: value]), runtimeKey: runtimeKey) } diff --git a/packages/experimental/cua-macos/native/upstream.json b/packages/experimental/cua-macos/native/upstream.json index df84ce4dbb..b77a8e6450 100644 --- a/packages/experimental/cua-macos/native/upstream.json +++ b/packages/experimental/cua-macos/native/upstream.json @@ -42,9 +42,11 @@ "Sources/CuaNative/ApplicationAuthorization.swift", "Sources/CuaNative/ApplicationDiscovery.swift", "Sources/CuaNative/ClipboardPaste.swift", + "Sources/CuaNative/ExternalInputMonitor.swift", "Sources/CuaNative/Main.swift", "Sources/CuaNative/NativeProtocol.generated.swift", "Sources/CuaNative/Protocol.swift", + "Sources/CuaNative/RecentActivity.swift", "Sources/CuaNative/RequestAdmission.swift", "Sources/CuaNative/RequestCoordinator.swift", "Sources/CuaNative/RequestScheduler.swift", diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 829706b8ab..17819c6c20 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -37,6 +37,8 @@ App and Window methods: Raw operation tools use { method, params }, including params: {} for parameterless methods. getApp selects without activating the app. Keep applications in the background for observation and routine input. Do not activate or raise an app during initialization, before each action, or merely because another app is foreground. Prefer advertised AX actions. If a window is hidden or minimized, try app.show() or window.show() and read fresh state. show requests unhide and unminimize without activation, raising or switching Spaces; it chooses the explicit, focused, main or sole AX window. A null windowId means no window was selected for restoration. foregroundChanged compares the front app and top window before and after the request; null means unavailable, and delayed focus changes remain possible. If restoration is unsupported or the window remains unusable, including another Space or Stage Manager, explain the needed foreground step, use app.activate() or an advertised raise action, and read fresh state. Completing the task takes priority when foreground access is necessary. Avoid repeated activation when the user switches away; continue background-capable steps and report what requires foreground access. Applications may still change focus in response to input. +Recent activity is advisory history, not a lock, reservation, or instruction to stop. You may continue operating an application even when recentActivity reports another actor. Use the task and current UI to decide whether to re-observe or coordinate with the user. other-agent means another connected Agent attempted an operation; external-input means detected input outside this helper and may come from a person, another Agent, or other automation. Neither confirms a successful change or continued use. A null windowId means application-level activity whose window is unknown. The host configures the lookback (default one minute). Monitoring begins when an authorized application is accessed; missing activity does not prove nobody acted. unavailable or secure-input means external input observation is incomplete; do not infer inactivity. Activity advisories are emitted even with emit:false. + Await operations sequentially. After input, read fresh state to verify the effect. A successful action means dispatched, not verified completion. Cancellation may leave partial effects; never retry uncertain input without observing. STALE_APP requires getApp again; STALE_SNAPSHOT requires getState again. Absolute coordinate input requires a fresh screenshot of that window. Relative input can use a successful AX observation or screenshot. SCREENSHOT_REQUIRED means capture a fresh screenshot before using pixel coordinates. For click and hover, coordinate targets must be [x, y], for example hover([650, 400], {relative:true}). A bare number such as hover(650) is always an AX element index. The relative option applies only to coordinate targets, not AX indices. Window resizing since the latest observation rejects coordinate input; movement alone preserves window-local coordinates. WINDOW_CHANGED requires fresh state before any retry; use an advertised AX action or explicitly restore the window before screenshot or coordinate input, then observe again. PERMISSION_DENIED requires the user to grant macOS Accessibility or Screen Recording access in System Settings. After granting access, observe fresh state before continuing; do not automatically replay prior input. Hover first uses advertised AX alternate UI without moving the system cursor, preserving revealed descendants until the pointer target leaves their region. When unavailable, it moves the visible system cursor without pressing a button; that route requires the target point to be unobscured in the foreground app. FOREGROUND_REQUIRED requires explicit activation or raising and a fresh observation before retrying. Returning, AX reads and screenshots do not restore the previous point. Wait for the application's hover delay, observe, then hover into the revealed controls before clicking. Use successive hover calls for intermediate points. The result reports hoverRoute and systemPointerMoved. Other input or application changes can interrupt the interaction; app objects do not reserve applications between calls. diff --git a/packages/experimental/cua-macos/src/shared-native.ts b/packages/experimental/cua-macos/src/shared-native.ts index 3f59c02b93..57532c1567 100644 --- a/packages/experimental/cua-macos/src/shared-native.ts +++ b/packages/experimental/cua-macos/src/shared-native.ts @@ -205,9 +205,10 @@ class SharedNativeChannel implements NativeChannel { else ended.resolve() }) socket.once('connect', () => { - const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs } = this.config + const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, + screenshotTimeoutMs, timeoutMs, graceMs, recentActivityWindowMs } = this.config socket.write(JSON.stringify({ type: 'hello', protocol: 1, runtimeKey, - config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs } }) + '\n') + config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, screenshotTimeoutMs, timeoutMs, graceMs, recentActivityWindowMs } }) + '\n') }) const receive = (chunk: Buffer): void => { const newline = chunk.indexOf(10) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index b91166bad4..bd3a67594b 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -56,7 +56,7 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ const config = { helperPath: resolve('fixture-helper'), buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20, - graceMs: 10, textEventIntervalMs: 8, maxElements: 64, maxDepth: 8, dragDurationMs: 200, dragSteps: 10, + graceMs: 10, recentActivityWindowMs: 60_000, textEventIntervalMs: 8, maxElements: 64, maxDepth: 8, dragDurationMs: 200, dragSteps: 10, } satisfies Omit const { helperPath: _helperPath, ...automaticConfig } = config diff --git a/packages/experimental/cua-macos/tests/shared-native.spec.ts b/packages/experimental/cua-macos/tests/shared-native.spec.ts index af6587ac65..4f74b8da16 100644 --- a/packages/experimental/cua-macos/tests/shared-native.spec.ts +++ b/packages/experimental/cua-macos/tests/shared-native.spec.ts @@ -131,7 +131,7 @@ async function fixture(options: { const config: NativeClientConfig = { helperPath, cwd: root, connectTimeoutMs: options.connectTimeoutMs ?? 5000, screenshotTimeoutMs: 5000, timeoutMs: 30_000, graceMs: options.graceMs ?? 1000, axTimeoutMs: 3000, - maxRequestBytes: 65536, maxResponseBytes: 1048576, textEventIntervalMs: 0.5, + maxRequestBytes: 65536, maxResponseBytes: 1048576, recentActivityWindowMs: 60_000, textEventIntervalMs: 0.5, } function open(): NativeChannel { const channel = createSharedNativeChannel({ subprocess: { spawn } }, config) @@ -188,7 +188,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', ( for (const handle of f.handles) expect(handle.terminate).not.toHaveBeenCalled() expect(f.hellos).toEqual([expect.objectContaining({ type: 'hello', protocol: 1, config: { axTimeoutMs: 3000, timeoutMs: 30000, screenshotTimeoutMs: 5000, graceMs: 1000, - maxRequestBytes: 65536, maxResponseBytes: 1048576, textEventIntervalMs: 0.5, + maxRequestBytes: 65536, maxResponseBytes: 1048576, recentActivityWindowMs: 60_000, textEventIntervalMs: 0.5, } }), expect.anything()]) }) diff --git a/packages/experimental/cua/src/api.ts b/packages/experimental/cua/src/api.ts index 4f4126f167..84013f44a7 100644 --- a/packages/experimental/cua/src/api.ts +++ b/packages/experimental/cua/src/api.ts @@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer' 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 { ActionResult, AppResult, AppsResult, CapabilitiesResult, FoundAppsResult, HoverResult, RecentActivityResult, Request, ScreenshotResult, ShowResult, StateResult, WindowsResult } from './protocol.ts' import type { CuaApi, CuaApp, CuaAppHandle, CuaDispatch, CuaObservationOptions, CuaObservationSink, CuaOperation, CuaScreenshot, CuaSurface, CuaWindow } from './types.ts' export type * from './types.ts' @@ -47,14 +47,21 @@ function keyChord(chord: string): { key: string; modifiers: string[] } { /** * Create app/window objects using the caller's authorized dispatcher. * @param dispatch - Current tool authority; rejects propagate without retries. - * @param sink - Optional text/image output; emit false suppresses this sink only. + * @param sink - Optional text/image output; emit false suppresses observations, but activity advisories still emit. * @returns Objects independent of variable storage and evaluator lifecycle. */ export function createCuaApi(dispatch: CuaDispatch, sink?: CuaObservationSink): CuaApi { - const call = (method: CuaOperation['method'], params: Record) => { + const call = async (method: CuaOperation['method'], params: Record) => { const request = Request.safeParse({ method, params }) if (!request.success) throw new Error(`${method} ${requestIssueMessage(request.error.issues)}`) - return dispatch(request.data) + const value = await dispatch(request.data) + if (value !== null && typeof value === 'object' && !Array.isArray(value) && value.recentActivity !== undefined) { + const activity = RecentActivityResult.parse(value.recentActivity) + if (activity.events.length > 0 || activity.externalInputMonitoring !== 'listening') { + await sink?.text(`Recent activity (advisory only): ${JSON.stringify(activity)}`) + } + } + return value } const action = async (method: CuaOperation['method'], params: Record) => ActionResult.parse(await call(method, params)) async function emit(value: object, options?: CuaObservationOptions): Promise { diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 131e15c3ec..3782fe57ee 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -40,6 +40,8 @@ export interface CuaConfig { buildTimeoutMs: number /** Deadline for one native operation, including capture and AX traversal. */ timeoutMs: number + /** Lookback in milliseconds for macOS activity advisories; does not reserve applications. */ + recentActivityWindowMs: number /** Maximum time to connect to or start the shared native helper. */ connectTimeoutMs: number /** Screenshot deadline including time queued behind other native operations. */ @@ -79,6 +81,7 @@ export const CuaConfig = Schema.object({ helperPath: Schema.string(), buildTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(300_000), timeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(30_000), + recentActivityWindowMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(60_000), connectTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(5000), screenshotTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(5000), axTimeoutMs: Schema.number().step(1).min(1).max(2 ** 31 - 1).default(3000), @@ -153,7 +156,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) helperPath, cwd: process.cwd(), timeoutMs: config.timeoutMs, axTimeoutMs: config.axTimeoutMs, connectTimeoutMs: config.connectTimeoutMs, screenshotTimeoutMs: config.screenshotTimeoutMs, maxRequestBytes: config.maxRequestBytes, maxResponseBytes: config.maxResponseBytes, graceMs: config.graceMs, - textEventIntervalMs: config.textEventIntervalMs, + textEventIntervalMs: config.textEventIntervalMs, recentActivityWindowMs: config.recentActivityWindowMs, } const entryId = ctx.fiber.entry?.options.id ctx.inject(['settings'], scope => scope.effect(() => scope.settings.configure({ auto: false }, ctx.fiber))) diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index a61ff18bf1..cbc67f470a 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -43,6 +43,7 @@ export interface NativeClientConfig { maxResponseBytes: number graceMs: number textEventIntervalMs: number + recentActivityWindowMs: number } /** One Agent's ordered connection to native operations and cleanup acknowledgement. */ diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 46eddd2e1c..4998bef781 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -81,6 +81,17 @@ export const NativeResourceParameters = { /** Executor-only continuation after application consent; absent from the model Request union. */ export const NativeOnlyOperations = [operation('launchApp', app)] as const +/** Recent input attempts are advisory; external sources and actual application effects are unverified. */ +export const RecentActivityResult = z.object({ + lookbackMs: z.number().int().positive(), + externalInputMonitoring: z.enum(['listening', 'unavailable', 'secure-input']), + events: z.array(z.object({ + source: z.enum(['other-agent', 'external-input']), windowId: id.nullable(), + ageMs: z.number().int().nonnegative(), operation: z.string().min(1), + })).max(2), +}) +const recentActivity = { recentActivity: RecentActivityResult.optional() } + /** Process identity returned only after a successful app selection. */ export const AppResult = z.object({ appHandle: z.string().min(1).transform(value => value as CuaAppHandle), pid, name: z.string(), bundleId: z.string().optional(), @@ -101,12 +112,12 @@ export const StateResult = z.object({ pid, windowId: id.nullable(), focusedWindowId: id.nullable().optional(), snapshotId: z.string().min(1).transform(value => value as CuaSnapshotId), - tree: z.string(), windows: WindowsResult, truncated: z.boolean(), + tree: z.string(), windows: WindowsResult, truncated: z.boolean(), ...recentActivity, }) /** Original native PNG and window-point geometry before Host image preparation. */ export const NativeScreenshotResult = z.object({ mimeType: z.literal('image/png'), data: imageBase64, pixelWidth: id, pixelHeight: id, windowId: id, - bounds: bounds.extend({ width: z.number().positive(), height: z.number().positive() }), coordinateSpace: z.literal('window-points'), + bounds: bounds.extend({ width: z.number().positive(), height: z.number().positive() }), coordinateSpace: z.literal('window-points'), ...recentActivity, }) /** Encoded model-request image; default input coordinates use these pixel dimensions. */ export const ScreenshotResult = NativeScreenshotResult.extend({ @@ -119,7 +130,7 @@ export const CapabilitiesResult = z.object({ methods: z.array(z.string()), coordinateSpace: z.literal('screenshot-pixels'), browser: z.literal(false), }) /** An action has reached native dispatch; application state was not verified. */ -export const ActionResult = z.object({ dispatched: z.literal(true), verified: z.literal(false) }) +export const ActionResult = z.object({ dispatched: z.literal(true), verified: z.literal(false), ...recentActivity }) /** Hover reports whether the selected route moved the user's system pointer. */ export const HoverResult = ActionResult.extend({ hoverRoute: z.enum(['accessibility', 'system-pointer']), systemPointerMoved: z.boolean() }) /** Background restoration dispatch and sampled foreground changes; null means the observation was unavailable. */ diff --git a/packages/experimental/cua/tests/application-access.spec.ts b/packages/experimental/cua/tests/application-access.spec.ts index fc77988a11..ad2852f070 100644 --- a/packages/experimental/cua/tests/application-access.spec.ts +++ b/packages/experimental/cua/tests/application-access.spec.ts @@ -31,7 +31,7 @@ vi.mock('../src/native-client.ts', async original => ({ const unusedConnector = () => { throw new Error('Mocked native client does not connect') } const nativeConfig = { helperPath: '/fixture', cwd: '/', timeoutMs: 1000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 100, - maxRequestBytes: 4096, maxResponseBytes: 4096, graceMs: 100, textEventIntervalMs: 1 } + maxRequestBytes: 4096, maxResponseBytes: 4096, graceMs: 100, recentActivityWindowMs: 60_000, textEventIntervalMs: 1 } const identity = ApplicationAuthorizationResult.parse({ id: 'a'.repeat(64), name: 'Test application', executablePath: '/Applications/Fixture.app/Contents/MacOS/Fixture', persistable: true }) const handle = 'fixture-app' as CuaAppHandle const signal = new AbortController().signal diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index 83c35d481a..53468436fa 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -42,7 +42,8 @@ function fixture(options: { helperPath: '/fixture/helper', cwd: '/fixture', axTimeoutMs: 321, timeoutMs: options.timeoutMs ?? 60_000, connectTimeoutMs: 5000, screenshotTimeoutMs: options.screenshotTimeoutMs ?? 5000, maxRequestBytes: options.maxRequestBytes ?? 1024, - maxResponseBytes: options.maxResponseBytes ?? 1024, graceMs: options.graceMs ?? 10, textEventIntervalMs: 0.5, + maxResponseBytes: options.maxResponseBytes ?? 1024, graceMs: options.graceMs ?? 10, + recentActivityWindowMs: 60_000, textEventIntervalMs: 0.5, } const client = new NativeClient(owner, config, shared.create, options.reportDiagnostic) function finish() { done.resolve(); gone.resolve() }