diff --git a/docs/spec/05-computer-control.md b/docs/spec/05-computer-control.md new file mode 100644 index 0000000..5d9c098 --- /dev/null +++ b/docs/spec/05-computer-control.md @@ -0,0 +1,949 @@ +# 05 — Computer control, desktop actions, application automation and the Linux bridge + +Source of truth: CapriCore 1.0.4 tree at `~/Capri` (read-only). All `file:line` references are 1-based and relative to that root. "Windows helper" = `integrations/desktop-actions/native/DesktopActions.cs`; "Linux bridge" = `integrations/desktop-actions/native/linux/capri_linux/*.py` (unofficial `FWS-LINUX-BRIDGE` adaptation). Examples in this document are synthetic. + +Priorities: **P0** = computer control is unsafe or unusable without it; **P1** = expected by a Capri user; **P2** = optional/niche (often a hard-coded scenario). + +--- + +## 1. Purpose and scope + +This subsystem lets the companion operate the owner's desktop on explicit owner request, safely: + +* permission model: Full computer access (whole-computer grant with a 3 s host-enforced confirmation), the global *Application access* pause switch, per-app catalog grants, 90 s approval cards; +* a host-owned **computer-control session** (visible indicator on every monitor, Escape emergency stop, 80-input / 10-minute budget, turn binding, held-input release); +* the **observe → plan → act → verify** agent loop driven by a local LLM (Ollama `/api/chat` with JSON-schema constrained output), with completion review, loop guards and recovery replanning; +* deterministic fast paths: exact app launch, Discord GUI tasks, Google Meet / Teams call tasks, a Steam Cyberpunk launch, an Edgerunners teaser scenario, DaVinci Resolve timeline assembly; +* the **desktop catalog** (installed-app discovery, launch, inspect, text entry, browser address-bar draft, open URL, Recycle-Bin trash + recovery copies) with a durable idempotent **operation journal**; +* fixed Notepad/Calculator actions (`application_control`) and the precise **calculator engine** (scientific / programmer / unit conversion / date); +* **task workflows** (owner-recorded click/key/text sequences, replay under the session rules); +* **Discord Rich Presence**; +* the **native helper protocol** (`Capri.DesktopActions` JSON over stdio) and its Linux implementation: KWin scripting + RemoteDesktop portal + kglobalaccel on KDE Plasma Wayland, i3 IPC + XTest/XRes on X11, AT-SPI for controls, plus the Linux capture, cursor, awareness and input-daemon helpers. + +### 1.1 File map + +| Capri file | What it holds | Features | +|---|---|---| +| `apps/desktop/computer-control.mjs` | `ComputerControl` session + input primitives | CC-03..CC-08 | +| `apps/desktop/computer-agent.mjs` | `ComputerAgent` loop, browser step helper, guards, messages | CC-11, CC-14..CC-16 | +| `apps/desktop/computer-planner.mjs` | planner/review/intent-classifier requests, schemas, prompts, Discord planner filter | CC-12, CC-17, CC-35 | +| `apps/desktop/planner-json.mjs` | host JSON-schema validator, JSON-mode fallback | CC-12 | +| `apps/desktop/computer-task-plan.mjs` | checkpoint plan state | CC-13 | +| `apps/desktop/computer-vision.mjs` | screenshot → bounded click targets | CC-10 | +| `apps/desktop/computer-mode-request.mjs` | lexical routing (enable/disable/run, app launch, music exclusion, Discord anchor) | CC-17 | +| `apps/desktop/computer-requests.mjs` | `ComputerRequests` (grant then run) | CC-18 | +| `apps/desktop/computer-preferences.mjs` | indicator appearance settings | CC-05 | +| `apps/desktop/full-computer-access.mjs` | Full computer access grant | CC-01 | +| `apps/desktop/application-access.mjs` | global Application-access pause | CC-02 | +| `apps/desktop/action-broker.mjs` | loopback tool endpoint + `ActionApprovals` | CC-28, CC-50 | +| `apps/desktop/desktop-catalog.mjs` | `DesktopCatalog`, journal, trash/recovery | CC-19..CC-27 | +| `apps/desktop/application-target.mjs`, `application-window-choice.mjs`, `browser-identity.mjs` | name matching, window choice, browser identity | CC-20..CC-22 | +| `apps/desktop/browser-search-state.mjs` | navigation/search verification | CC-16 | +| `apps/desktop/native-escape-stop.mjs` | Escape watcher process driver | CC-04 | +| `apps/desktop/native-helper.mjs` | lazy C# helper compiler (Windows only) | CC-42 | +| `apps/desktop/native-screenshot.mjs` | active-display capture | CC-09 | +| `apps/desktop/task-workflows.mjs`, `apps/desktop/native/task-recorder.cs` | workflows record/replay | CC-42 | +| `apps/desktop/task-route.mjs` | tool-domain narrowing, standalone calculation | CC-17, CC-31 | +| `apps/desktop/discord-application.mjs`, `discord-computer-task.mjs`, `discord-task-intent.mjs` | Discord GUI automation | CC-32..CC-35 | +| `apps/desktop/discord-presence.mjs`, `config/discord-presence.json` | Rich Presence | CC-36 | +| `apps/desktop/call-computer-task.mjs` | Meet/Teams join + chat draft | CC-37 | +| `apps/desktop/steam-game-launch.mjs`, `steam-task-state.mjs` | Steam fast path + milestones | CC-38, CC-39 | +| `apps/desktop/clip-command.mjs` | "clip that" predicate | CC-43 | +| `integrations/desktop-actions/service.mjs` | helper spawn protocol, `ApplicationService`, helper env | CC-29, CC-44 | +| `integrations/desktop-actions/calculator.mjs`, `math-expression.mjs`, `math-worker.mjs` | calculator engine + grammar | CC-30, CC-31 | +| `integrations/desktop-actions/index.mjs`, `openclaw.plugin.json`, `package.json`, `settings.mjs`, `provision.mjs` | OpenClaw `application_control` tool, defaults, helper provisioning | CC-29, CC-44 | +| `integrations/desktop-actions/native/DesktopActions.cs` | Windows helper (semantics reference) | CC-44, §8 | +| `integrations/desktop-actions/native/linux/capri-*` + `capri_linux/*.py` | Linux helper, input daemon, escape, capture, cursor, awareness | CC-44..CC-49, §8 | +| `tools/verify/native/*.cs` | disposable WinForms fixtures for E2E verification | §11 | +| `docs/computer-control.md`, `docs/application-actions.md`, `docs/timers-and-actions.md`, `docs/discord-control.md` | user docs | — | + +Closely coupled code owned by other specs but described here where it defines this subsystem's contract: `integrations/companion-tools/index.mjs` (tool schemas/descriptions of `desktop_control`, `workflow_control`, `settings_control`), `apps/desktop/companion-actions.mjs` (tool dispatch), `apps/desktop/chat-service.mjs` (routing into computer tasks), `apps/desktop/main.mjs:3755-4000` (wiring), `apps/desktop/main/control-overlay.mjs`, `main/control-window-layer.mjs`, `main/confirmations.mjs`, `main/linux-cursor.mjs`, `renderer/control-overlay.*`, `apps/desktop/edgerunners-teaser.mjs`, `integrations/resolve/{service.mjs,bridge.lua}`, `apps/desktop/action-replies.mjs`. + +Out of scope: chat turn engine internals, conversation store, screen-observation and clip capture pipelines (only the `isClipCommand` predicate is here), `FilePermissions` (consumed), Spotify, timers, avatar. + +--- + +## 2. Feature catalog + +### CC-01 Full computer access grant — P0 +Source: `apps/desktop/full-computer-access.mjs:5-85`, wiring `main.mjs:839-847`, IPC `main.mjs:5151-5158`. +* Persisted setting `{enabled: bool, drives: string[]}` (default `{enabled:false, drives:[]}`), validated: ≤26 unique drives; Windows each `^[A-Z]:\\$`; **Linux each must be exactly `/`**. +* `configure(false)`: bump `epoch`, persist `enabled:false` (drives kept), emit change. Revocation **immediately stops any active session** (`onChange` → `computerControl.stop()`), and removes transient discovered apps from use (CC-20). +* `configure(true)`: if already enabled or `enabling` → return snapshot. Else `epoch++`, `enabling=true`, emit; show host confirmation (CC-28 "Confirmations"): title `Give access to the whole computer?`, detail (quote §6.9), confirm label `Give full computer access`, `danger:true`, **`delayMs:3000`** (confirm button cannot be accepted before 3 s; enforced by host, not only UI), cancelled by turn signal; auto-cancel after 180 s. If declined, or epoch changed (superseded/revoked meanwhile) → unchanged snapshot. Then `discover()` drives via helper `catalog_drives` (Linux: `["/"]`); if aborted or epoch changed → no grant; if empty → error `No local drives were detected.`; else persist `{enabled:true, drives}`. `enabling=false` in all cases. +* `scopes()` (consumed by file access): for each drive `{id: 'fa11acc0-0000-4000-8000-' + sha256(root).hex[0..12], root, write:true, kind:'computer', confirmationRequired:false}`; empty when disabled. +* Effective permission everywhere: `fullAccess = fullComputerAccess.enabled && applicationAccess.enabled` (`main.mjs:3756,3771`). +* Chat paths: phrases "Enable/Disable full computer access" etc. (CC-17) and tool `settings_control {action:'request', setting:'fullComputerAccess', value}` (CC-51). A model can request, never grant. + +### CC-02 Application access pause — P0 +Source: `apps/desktop/application-access.mjs:1-62`, wiring `main.mjs:807-816`. +* Persisted `{enabled: bool}` (default `true`). Exposes an `AbortSignal` that is aborted while paused (re-created on resume). +* `assertAllowed(tool, args)`: when paused, throws `Application access is paused. Turn it on from Capri’s toolbar.` (code `APPLICATION_ACCESS_PAUSED`) for tools `desktop_control`, `application_control`, `spotify_control`, `workflow_control`, except actions `status`, `apps`, `control_status`. +* `mask(value)`: when paused, Notepad/Calculator grants read as false (grants are not overwritten). +* `set(v)` is serialized (promise chain). On pause: persist first, abort signal, then `stop()` = cancel workflows, cancel pending approvals, close Spotify, emergency-stop any computer task/session; always emit change even if stop fails. + +### CC-03 Computer-control session — P0 +Source: `apps/desktop/computer-control.mjs:36-304`; wiring `main.mjs:3770-3874`, supervision `main.mjs:6993-7018`. +Constants: `timeoutMs=600000` (10 min), `maxSteps=80` (inputs), `indicatorTimeoutMs=5000`, `cleanupTimeoutMs=2000`, default `pointerDuration` from settings (CC-05, default 260 ms; class default 220). +* Session object: `{id: uuid, turn, goal, maxSteps, steps, deadline, controller: AbortController, target: lastObservation|null, ready: bool, inputs: Set, nativeOnlyApplications?, pending?}`. +* `turn` = current owner turn id: `workflowTurn ?? chat.active.id`. `canStart()` = (workflow turn exists OR active chat turn not aborted) AND not shutting down. `allowed()` = full access && application access. +* `begin(goal, {maxSteps, signal})` state machine: + 1. Validate `maxSteps` integer 1..400 (`Invalid computer-control step budget.`); require `allowed()` (`Enable Full computer access in Settings → Computer control first.`), `canStart()` (`Computer control requires an active owner conversation turn.`), turn not in `blockedTurn` (`Computer control was stopped for this turn. Wait for a new owner request.`); if a stop is in progress, await it and retry; goal 1..8000 chars (`Describe the owner task.`). + 2. If a session exists: not ready → `Wait for the current operation to finish.`; ready → return snapshot (idempotent). + 3. Create session (not ready); owner `signal` abort → `stop()`. + 4. `registerEscape(cb)` must resolve true, else error `Escape emergency stop is unavailable. Computer control did not start.` (fail closed). + 5. Show indicator (CC-05) under `AbortSignal.any(session.controller, timeout(5000))`; re-check session/allowed/canStart/turn before and after; on timeout `Computer control indicator did not become visible.`; on abort `Computer control cancelled.` + 6. `ready=true`; arm 10-minute timer → `stop()`; publish `{type:'computer.control', active, steps, deadline}`; return `{ok:true, active:true, steps:0, deadline, instruction}` (§6.6). + 7. Any failure → `stop()` and rethrow. +* `requireSession()`: throws `Computer control is not ready. Wait for its indicator.` if not ready; stops and throws `Computer control is stopped. Start a new owner-requested session.` if no session / not allowed / cannot start / turn changed / deadline passed / `steps >= maxSteps`. +* `stop({blockTurn=true})` (idempotent, returns shared promise): detach session, `blockedTurn = session.turn` unless `blockTurn:false` (normal task completion uses false; Escape/revocation use default true so the same turn cannot restart control), clear timer, **hide indicator first** (even for an orphan indicator, bounded 2 s), abort session controller, publish, release started held inputs immediately, then after hide: unregister Escape, wait (≤2 s) for any pending native call, release again (a terminating helper may have sent a final key-down), hide again, resolve `{ok:true, active:false,...}`. +* Held-input release (`releaseInput`): every key/click/drag/type command registers a release record before dispatch: `computer_release` with keys = `command.keys` (press_keys) or drag `modifiers` or for typing `['CTRL','SHIFT','L','HOME','END']`, plus `button` (`left` default) for click/drag/type. Keys are sent in chunks of ≤4 (helper limit), each bounded by 2 s. Released after every completed action (in `finally`) and on stop. +* `supervise({indicatorVisible, escapeAvailable})` runs every **400 ms** from the main loop; stops the session if: indicator visible without session; not allowed; cannot start; turn changed; or session ready but Escape is no longer registered (`globalShortcut.isRegistered('Escape') || nativeEscape.active`). +* Stop triggers (main): Escape (native watcher, in-app `before-input-event` Escape when a session/indicator exists, Electron global shortcut), "Stop computer control" button (`capri:computer-stop`), revocation of full/application access, chat turn completed/cancelled/failed for the session's turn, `capri:cancel`, any chat task end (`finally` of submitMessage), companion hidden, screen lock, system suspend, shutdown, indicator lost (renderer crash/closed window/cursor tracking failure), the 10-minute timer, step budget exhaustion. `emergencyComputerStop()` = cancel workflows + stop session + cancel chat turn + cancel visual reply + cancel approvals (`main.mjs:3906-3913`). + +### CC-04 Escape emergency stop — P0 +Source: `apps/desktop/native-escape-stop.mjs:1-129`, `main.mjs:3814-3843`, helper `WatchEscape` (`DesktopActions.cs:1243-1263`), Linux `capri_linux/main.py:822-842`, `capri_linux/escape.py`. +* `registerEscape` = try Electron `globalShortcut.register('Escape')` (best effort) AND start the native watcher; native watcher must confirm `armed` within `min(3000, armTimeoutMs)` ms, else registration fails → control does not start. On failure both are unregistered. +* Watcher process: separate helper process (same executable as the action helper), stdin one line `{"action":"computer_watch_escape","parentPid":,"durationMs":600000}`; env = helper env (§5.2). It never injects input or reads UI. +* Watcher stdout: JSON lines `{"ok":true,"event":"armed"|"escape"|"parent_exit"|"expired"}`. Host rules: any stderr byte → failure; >4096 stdout bytes → failure; invalid JSON → failure; `ok!==true` → failure; `armed` (first) → resolve true, start life timer `durationMs+1000` → on expiry failure; `escape` while armed → `onEscape`; anything else → failure. Callbacks fire once; old generations cannot fire into a new session. **Failure of an armed watcher triggers emergency stop** (fail closed). +* Helper validation: `parentPid > 0`, ≠ own pid, `1000 <= durationMs <= 600000`; watches parent by pid + start time (exits `parent_exit` on restart/exit). +* Windows: polls `GetAsyncKeyState(VK_ESCAPE)` every 20 ms (does not consume the key). Linux X11: polls `XQueryKeymap` for the Escape keycode every 20 ms. Linux KDE Wayland: registers a **kglobalaccel global shortcut** (component `capri-emergency-stop`, action `stop`, friendly names `Capri`/`Capri emergency stop`, key `Qt::Key_Escape = 0x01000000`), listens for `org.kde.kglobalaccel.Component.globalShortcutPressed` on `/component/capri_emergency_stop`; always removes the registration on exit and before registering (stale crash leftovers). Note: on KDE this **grabs Escape globally** for the session duration (apps don't receive Escape). +* In-app Escape: any Capri web-contents keyDown `Escape` while a session or indicator exists → emergency stop (`main.mjs:3935-3946`). + +### CC-05 Visible control indicator and appearance — P0 (indicator), P1 (effects/preview) +Source: `main/control-overlay.mjs`, `main/control-window-layer.mjs`, `renderer/control-overlay.{html,css,mjs}`, `computer-preferences.mjs`, `main.mjs:3844-3874, 5159-5182`. +* One transparent, frameless, non-focusable, skip-taskbar, always-on-top (`screen-saver` level), fullscreen, **click-through** window per connected display, created sequentially; each must load, initialize `globalThis.capriControl`, set caption, configure, `showInactive`, wait two animation frames, then its actual bounds must equal the display bounds (Linux: each coordinate within ±2 px because XWayland may report 1919×1199 on 1920×1200), otherwise `Computer control indicator could not cover the complete display.` → begin fails. +* Caption (localized): `Computer control active — press Escape to stop` (static HTML fallback `CAPRI // COMPUTER CONTROL · ESC TO STOP`). +* Concurrent `show()` calls share one initialization; `hide()` aborts pending initialization, hides and destroys every window even if one destruction throws; renderer gone / window closed / script failure → `lost(reason)` once → emergency stop. +* Cursor tracker every 33 ms sends pointer position per monitor for trail effects; agent phase (`observing|planning|acting|verifying|...`) and input pulses (`computer.input` event) drive effects. +* While active, Capri's own windows are demoted from always-on-top and moved to the bottom of the stacking order without changing focus (`ControlWindowLayer.begin/end`), and avatar detach state is reset. +* Appearance settings (CC-05 table in §4): `enabled` (decorative effects), `intensity` 0..100, `theme` `capri|blackwall`, `cursor` (trail), `pointerDuration` 0..1000 ms (pointer animation; 0 = instant). Effects are edge-only (outer ~82 px strips), border 3 px; reduced-motion → 250 ms frame interval and static time; else 33 ms. Turning effects off keeps the border/label. +* Preview (`capri:computer-preview`): refused while a session exists; shows the indicator for 3 s with caption `Computer control // Preview · 3 s`; never grants control. + +### CC-06 Observation (`observe`) — P0 +Source: `computer-control.mjs:311-515`; helper `computer_state` (`DesktopActions.cs:400-462`; Linux `main.py:383-453`). +* Clears `session.target`. Calls `computer_state` (with `ignoreProcessId = Capri's pid`), optional capture+vision (unless `vision:false` or the foreground `applicationKind` is in `session.nativeOnlyApplications`, i.e. Discord when the goal mentions Discord), then `computer_state` again; if windowId or process start time changed → error code `COMPUTER_OBSERVATION_CHANGED` (`The foreground window changed during observation. Observe it again.`). Vision failure is swallowed (`visionStatus:'unavailable'`) unless aborted. +* Application adapter (Resolve, CC-41) may add `application` data; if so a third `computer_state` must still match. +* Foreground selection (helper): if the foreground window belongs to an allowed process (not Capri: not `ignoreProcessId`, verifiable executable, not a Capri executable, Linux: owned by same uid) use it; otherwise pick the **first suitable window in top-most-first order** (visible, not minimized, non-empty title, non-zero size; Windows also excludes tool/no-activate windows, cloaked windows, shell classes) and activate it; none → `COMPUTER_APPLICATION_UNAVAILABLE` (`Open the application you want Capri to control. No input was sent.`); activation failure → `COMPUTER_FOREGROUND_CHANGED`. +* Controls: breadth-first walk of the window's accessibility tree (≤800 nodes, ≤2 s; Windows also ≤4 owned popup menus × 80 nodes / 300 ms), skipping password/offscreen/disabled/zero-size; non-editables only of types Button, Hyperlink, TabItem, MenuItem, CheckBox, RadioButton, ComboBox, ListItem, TreeItem, Slider, Text, Image (Linux also DataItem); unnamed non-editables skipped (Linux: unnamed Text uses its text ≤100). Up to 200 collected, then sorted by rank (focused 0, Discord composer 0.5, browser address 1, taskbar 2, `Images`-tab label or image candidate 2.5, Text 4, other 3) and cut to **≤140 controls and ≤50,000 UTF-8 JSON bytes**; `controlsTruncated` reports a cut. +* Per control (helper shape): `id` (opaque runtime id; Linux `""`), `untrustedName` (≤100), `untrustedValue` (value text ≤500, ≤2048 for an address bar; never read when the name matches `password|token|secret|api.?key|парол|секрет` (+`mot de passe` on Linux); Windows: Image with empty value → URL of containing hyperlink), `type` (`ControlType.`), `automationId` (≤100), `x`,`y` (center, desktop pixels), `imageCandidate` (Image ≥96×80), `editable`, `focused`, `browserAddress`, `browserSearch` (editable, in page document, not address, search-field heuristic), `pageContent` (inside a web Document), `hovered`, `selected` (bool|null); Discord extras (CC-34); Windows taskbar extras `surface:'taskbar'`, `notificationArea`, `surfaceWindowId/ProcessId/StartedAtTicks`. +* Window fields: `windowId` (decimal string `^[1-9]\d{0,19}$`), `processId`, `startedAtTicks` (Windows .NET ticks; Linux `/proc//stat` field 22 start time), `untrustedTitle` (≤180), `applicationKind` (`discord` or null), `executable`, `resolveExecutable`, `modal`, `fullscreen` (window rect = monitor rect ±2 px), `x,y,width,height`, `desktopSurfaces` (Windows taskbars on the active monitor; Linux always `[]`), `controlsTruncated`, Discord `discordUserPanel`, `discordComposerScan`; Linux adds `accessibility: bool` (tree found). +* Host result (returned to agent): `{ok, observationId (8 hex chars), window:{windowId, untrustedTitle, [applicationKind, discordComposerScan, controlsTruncated, discordUserPanel], fullscreen?, modal?}, scene (vision summary|null), application?, visionStatus ('ready'|'unavailable'|'not_requested'), screenAvailable, targets:[...], desktop:{scope:'active_display', taskbarAvailable}, note}`. +* Target ids: `-ui-` for controls, `-image-` for vision points. Target fields: `targetId, untrustedLabel, position:{x,y}` (percent of window, rounded), `source:'vision'?`, `untrustedValue?`, `role?`, `automationId?`, Discord flags, `editable, focused, hovered, selected?, browserAddress?, browserSearch?, imageCandidate?, pageContent?, surface?, notificationArea?`. Vision points map image px → desktop px: `x = bounds.x + round(px*bounds.width/image.width)`; a vision point inside a taskbar rect becomes a taskbar target with `pageContent:false`. +* `session.target = {...after, observationId, at: now, targets: Map, application}`; inputs require it and require `now - at <= 30000` ms (except `resolve_assemble`). + +### CC-07 Input actions — P0 +Source: `computer-control.mjs:516-713`; helper `computer_*` (`DesktopActions.cs:465-575`, Linux `main.py:554-734`). + +| Action (agent) | Args (validated host-side) | Native command | Notes | +|---|---|---|---| +| `press_keys` | `keys` 1–4 unique names matching key set (§5.2.4), `holdMs` 0..2000, `observationId` = latest | `computer_keys {keys, holdMs, focusedControlId?}` | `focusedControlId` = id of the observed focused control; native rejects if focus moved (`COMPUTER_FOREGROUND_CHANGED`, nothing sent). Keys pressed in order, held, released in reverse in `finally`. | +| `move_pointer` | `targetId` from latest observation | `computer_pointer {x,y,controlId?,durationMs}` | hover only | +| `click` | `targetId`, `button` left/right/middle, `clickCount` 1/2 | `computer_click {x,y,button,clickCount,durationMs,controlId?}` (+ taskbar origin fields) | double-click interval `min(60, max(1, doubleClickTime/3))` ms (Linux fixed 60 ms) | +| `drag` | `targetId`, `toTargetId` (both in app, not taskbar), `modifiers` ⊆ {CTRL,SHIFT,ALT} unique | `computer_drag {x,y,toX,toY,controlId?,toControlId?,modifiers,durationMs:max(300,pointerDuration)}` | path checked against covering windows at every step | +| `enter_text` | `targetId` editable with native id, `text` 1..4000 chars without C0 controls except TAB/LF/CR, `mode` replace(default)/append | `computer_type {controlId,text,mode,durationMs}` | real keystrokes after verified focus; verified by reading back | +| `scroll` | `amount` integer ±1..±10, `observationId` = latest | `computer_scroll {amount}` | positive = up | +| `resolve_assemble` | see CC-41 | adapter | | + +* Every native command carries `windowId, processId, startedAtTicks` of the observed target. Each successful dispatch increments `session.steps` *before* dispatch, publishes, emits `computer.input`, sets `session.target=null` (a new observation is mandatory) and returns `{...receipt, instruction:'Observe to verify this action before the next step.'}`. +* Pointer motion: smoothstep easing `t*t*(3-2t)` from current pointer to target over `durationMs` (0..2000; default 220 for click/pointer/type, 350 to drag start, `max(200, durationMs||500)` for the drag), ~12 ms steps; **target identity (foreground window, pid, start time) is re-checked at every step**. +* Click target resolution when `controlId` present: re-find the element by id in the live tree (must be visible/enabled with geometry); candidate points: clickable point (Windows) then box fractions (0.5,0.5), (0.25,0.5), (0.75,0.5), (0.5,0.25), (0.5,0.75); first point whose top-level window under the point is the target (or its owned popup menu) and whose hit-test element is the control or an ancestor/descendant button-like element → else `COMPUTER_TARGET_COVERED` (`The visible control does not match the observed target. No click was sent.`). After moving, re-hit-test; mismatch → `COMPUTER_TARGET_COVERED` (`The page moved during pointer movement...`). +* Point must be inside the virtual desktop (`Pointer coordinates are outside the desktop.`). +* Text entry (`TypeObservedField`): verify Discord draft precondition if any; refuse if mouse buttons or modifiers are physically held (`COMPUTER_INPUT_BUSY`; Linux KDE cannot detect, X11 via pointer mask); **browser address field** → focus via Ctrl+L and wait ≤600 ms for the focused element to be the address edit (fullscreen → `COMPUTER_FULLSCREEN_TOOLBAR`, else `COMPUTER_FIELD_FOCUS_CHANGED`); **other field** → must not be covered (`COMPUTER_TARGET_COVERED`), move pointer to its center, left click, wait 100 ms, foreground must be unchanged and focus must be inside the field (`COMPUTER_FIELD_FOCUS_CHANGED`; Windows Qt edit fallback: set value through ValuePattern; Linux fallback: AT-SPI `grab_focus` and require FOCUSED state). Then select: replace = Ctrl+Home, Shift+Ctrl+End; append = Ctrl+End; verify focus still inside field; type Unicode text (Windows `KEYEVENTF_UNICODE`, Linux portal keysyms or `xdotool type`). Then poll the field value until `normalize(value) == expected` (CRLF→LF; expected = old+text for append, text for replace, ≤8000) for `min(5000, 1200 + 4*len)` ms → `{ok, typed:true, submitted:false, windowId, confirmation:'Clicked the field and entered the text without submitting it.'}`; else `Text entry could not be verified. Check the field before retrying.` (uncertain). +* Scroll: Windows wheel `amount*120`; Linux KDE portal discrete axis steps `-amount`; X11 button 4 (up) / 5 (down) × |amount|. +* Discord-guarded mutation (only `enter_text` or single `ENTER` press, only when the trusted 3rd argument `discordMutation` is supplied by the Discord runner): requires foreground `applicationKind==='discord'`, `expectedValueSha256` 64-hex (sha256 of the current draft) and optional `expectedDiscordPaneId` equal to the field's pane id, field editable with native id, and for ENTER the observed focused control must be that field → native re-verifies pane, composer inventory and draft hash immediately before typing and before each key (CC-34). Mismatch → `The verified Discord composer changed. Observe the chat again.` / `COMPUTER_OBSERVATION_CHANGED`. + +### CC-08 Native preflight identity checks and error taxonomy — P0 +Source: `DesktopActions.cs:55-58,165-184`, Linux `main.py:84-115`, `service.mjs:195-205`, agent `computer-agent.mjs:1446-1474,1640-1679`. +* `InputTarget(q, beforeInput)`: `windowId` must parse and (non-taskbar) be the current foreground window → else `COMPUTER_FOREGROUND_CHANGED` when before any input (`inputPerformed:false`) or plain failure mid-action; window pid must equal `processId` (`The target process changed.`); process must be allowed (`COMPUTER_APPLICATION_UNAVAILABLE`); process start time must equal `startedAtTicks` (`The target process restarted.`). +* **Linux divergence:** if the observed window is not active, the Linux bridge first re-activates it (KWin/i3) and waits ≤1.5 s ("Talking to Capri focuses Capri"); identity is then checked on the newly active window. The Rust port must keep this (the owner typically focuses Capri to speak) but only for the exact observed window id. +* Error codes (only these are propagated as `error.code`; regex `^COMPUTER_[A-Z_]+$`): `COMPUTER_OBSERVATION_CHANGED`, `COMPUTER_APPLICATION_UNAVAILABLE`, `COMPUTER_FOREGROUND_CHANGED`, `COMPUTER_FIELD_STALE`, `COMPUTER_FIELD_FOCUS_CHANGED`, `COMPUTER_FULLSCREEN_TOOLBAR`, `COMPUTER_TARGET_COVERED`, `COMPUTER_INPUT_BUSY`, `COMPUTER_INPUT_UNAVAILABLE` (Linux KDE: portal consent missing), `COMPUTER_BROWSER_WINDOW_UNVERIFIED` (agent-side). A refusal before any input sets `inputPerformed:false` (Windows `InputPreflightException`, Linux `Preflight`). +* Agent replans (counts as a failure, max 3) **only** for `inputPerformed===false` with codes FIELD_STALE, FIELD_FOCUS_CHANGED, FULLSCREEN_TOOLBAR, TARGET_COVERED, FOREGROUND_CHANGED; TARGET_COVERED also requests vision. Any other native failure after dispatch is **uncertain** → task ends `incomplete`, never replayed. + +### CC-09 Active-display capture for the executor — P1 +Source: `native-screenshot.mjs:7-90`, `main.mjs:3796-3806`, Linux `capri_linux/capture.py`. +* Captures the monitor containing the active window (fallback: first output) as PNG with its desktop bounds `{x,y,width,height}`; image size must equal bounds (`Capture geometry differs from its image`). Limits: 0 < w,h ≤ 16384 and w·h ≤ 40,000,000; stdout ≤ 96 MiB; timeout 15 s; Linux runner `python3 -I capri-capture --with-geometry` → JSON `{x,y,width,height,png:}` (or bare base64 without the flag; `--probe` prints bounds only). +* KDE: `spectacle --background --nonotify --fullscreen --output ` (tmp in `$XDG_RUNTIME_DIR`, prefix `capri-capture-`), then crop the output rect from the full-desktop image using scale `image.size / desktop_bounds.size`, resize (Lanczos) to exactly w×h, re-encode RGB PNG. i3/X11: `maim --hidecursor --geometry WxH+X+Y `. Timeout 12 s. Temp file always deleted. +* The executor then downsizes to fit 1280×720 (`factor = min(1, 1280/w, 720/h)`, rounded, ≥1 px) before vision; returns `{png, width, height, bounds}`. **Images are never saved, logged or put in conversation history.** + +### CC-10 Vision targets — P1 +Source: `computer-vision.mjs:1-89`. +* Only allowed when the inference URL is `http://127.0.0.1...` (local boundary), else construction throws. +* POST `/api/chat` (§5.1.4) with the image and goal as data; response text ≤32768 chars; packet must be `done:true`, no `tool_calls`, `done_reason!='length'`; content JSON `{summary: string ≤1200, targets: ≤15 × {label ≤120, x,y integers inside image}}` else `Invalid screen targets.` +* Output feeds CC-06 (`scene` = summary; points become `source:'vision'` targets). Vision is used only when requested by the loop (after an `observe` step, a covered target, a missing target, or Steam milestones), never for Discord. + +### CC-11 Computer task agent loop — P0 +Source: `computer-agent.mjs:282-1755` (`run` 586-1708). +Constants: `maxDecisions=100`, plan failures ≤2 consecutive planner errors, most guard counters abort at 3 consecutive failures (`failures` resets to 0 after any successful input or verified Discord step), observation read retries ≤2 (200 ms apart), navigation wait 700 ms (≤20 s per pending navigation), `wait` action 700 ms, repeated identical action key > 2 → stalled. +Entry: `run(goal, {signal, previousTask, ownerRequestedCall})`: +1. Reject if already running (`A computer task is already running.`); goal 1..8000 chars, no NUL. +2. If the goal is a meeting call task (CC-37) and not `ownerRequestedCall`, or the call parse is `clarify` → return `callTaskNeedsOwner` (`status:'needs_user'`), no session. +3. `control.begin(goal)`; if the goal mentions Discord, `session.nativeOnlyApplications=['discord']` (no screenshots of Discord). Combined signal = session ∪ caller. +4. **Route order** (first match wins): (a) exact single Discord operation (CC-32/33: parsed request, not `clarify`, `discordRequestProblem` null, `discordSingleOperationGoal`) → Discord runner; (b) meeting call task → CC-37; (c) Edgerunners teaser → CC-40; (d) Cyberpunk Steam launch when a launcher is wired (Windows only) → CC-38; (e) general loop. +5. General loop setup: `opening = ownerAppLaunch(goal)`; `discordProofRequired = goal mentions Discord && !(opening.single && opening.name mentions Discord)`; `steamGoal = steamGameGoal(goal)`; if `opening` and exactly one catalog match by exact name (`findApplications(name, {exact:true})`, may run discovery under full access) → first decision is a host-made `launch` step (no model call). +6. Per decision: observe (vision only if `useVision`), then: record previous outcome into the task plan (`changed = signature(before) != signature(view)`), stop as `stalled` if recovery attempts exhausted, check a pending navigation (CC-16), plan (or host-made step), validate (task-plan update, unavailable-observation rule, browser-input rewrite, Discord literal substitution, argument checks, Discord gates, duplicate/loop guards, page-search guards, Steam guards, finish/review, ask_user, draft-only), then dispatch (CC-07 through the journal, CC-27) and record history. +7. Observation unavailable at start (`COMPUTER_APPLICATION_UNAVAILABLE` before any step/history) → placeholder view `{observationUnavailable:true, window:{}, targets:[], scene:null, screenAvailable:false}`; then only `launch`, `open_url` or `ask_user` are accepted (others → correction; second failure → `needs_user` with message `window`); an unsuccessful action in that state → `needs_user`. +8. Browser-input rewrite (unless the goal is draft-only): text starting `http(s)://` and goal says go to/navigate/visit/watch (RU `перейди`, `открой сайт`) → `open_url {url:text}`; non-URL text and goal says "google " / "search the web" (not "google chrome") / RU `погугли`, and not a site search → `browser_search`. +9. Exactly-opening success: if the host-made launch succeeded with a verified focused window and the goal was a single launch → completed with summary `Opened .` / RU `Открыла .` +10. Launch with `focused:false` and a window id: observe (no vision); if that window is already foreground → treat as focused; else if exactly one non-tray taskbar button label matches the app name (normalizing `Application `/`приложение ` prefix, ` - N running windows` suffix, ` pinned`/`закреплено` suffix) → click it via the journal, observe again, success if now foreground. (Windows only; Linux has no taskbar targets.) +11. Unsuccessful step (`!ok || needsWindow || needsApproval || windowVerified===false || focused===false`): `missing_app_id`/`unknown_app_id` on the host-made launch → `needs_user` (`launch`); `needsWindow` → if input may have been performed, or action is `browser_input`, or owner gave the title, or 3rd failure → `needs_user` (`window`), else mark plan blocked and correct (§6.4); otherwise correction = focus message or `JSON.stringify(result).slice(0,3000)`; 3rd failure → `incomplete` (`launch` or `unverified`). +12. History entry per dispatched step (task-local, never persisted): `{action, query?, text?, keys?, target (label), targetSurface?, ok, confirmation, submitted, searchSubmitted, windowId, navigationRequested?, requireImages?, previousTitle?, at?, navigationUrl?, effect? ('Draft only. NO keys were pressed; NO search or navigation was performed.' for browser_input), resolve fields}`. +13. Loop end without finish → `{ok:false, status:'limit'}` with `stalled` message. +14. Exceptions: if cancelled (caller signal, session aborted, or session gone) → rethrow (caller reports cancellation). Otherwise `lastFailure = {phase, reason, action, code?, steps, at}` with reason `target_covered` (message mentions covering), `window_changed` (foreground/focus/target changed), `planning_failed` (plan/JSON), else `action_failed`; return `{ok:false, status:'incomplete', steps, summary}` with message key `covered` / `window` (APPLICATION_UNAVAILABLE) / `navigation` (BROWSER_WINDOW_UNVERIFIED) / `foreground` / `unverified`. +15. `finally`: record `lastOutcome {status, reason, phase, steps, at}` if not yet; stop the session with `blockTurn:false` if still ours; `running=false`; emit progress `completed|stopped`; call `audit(diagnostics())` (metadata only); keep `lastTaskPlan` diagnostics. +* Result shape: `{ok, status: 'completed'|'incomplete'|'needs_user'|'stalled'|'limit'|'submitted'|'cancelled', steps, verified?, summary, ...extra}`. Progress events `{type:'computer.task', active, phase, steps}` with phases `idle, observing, planning, acting, verifying, call-focus, completed, stopped`. +* `diagnostics()` = `{active, phase, steps, lastFailure, lastOutcome, actions: trace[{action, outcome, code?}], plan?: {revision, completed, remaining, recoveryAttempts}}` — never goal, titles, typed text or model output. + +### CC-12 Planner request (decision model) — P0 +Source: `computer-planner.mjs:684-984`, schemas `133-360, 387-595`, `planner-json.mjs`. +* Endpoint must be `http://127.0.0.1:` without credentials → `POST /api/chat` (Ollama native API; remote providers are adapted to the same local shape by the inference subsystem). Timeout 35 s per request (plus caller signal). Response ≤65536 chars. +* Context sent (user message = JSON + goal text): `{originalOwnerGoal, discordTaskAllowed, previousOwnerTaskForReferencesOnly?, language, currentObservation (compacted view), completedSteps (history except last 16, ok only, fields action/query/target≤100/text≤160/keys), actualSteps (last 16 steps, string fields ≤300, text ≤800), taskPlan, correction (Steam remaining + navigation correction + host correction), expectedControl?, knownApplications:[{name}], completionClaim? (review)}`. +* View compaction: Discord views are filtered first (CC-35). Targets filtered to `editable || label || value`, sorted by rank (exact `expectedControl` label −1; focused or browserSearch 0; vision 1; Images tab or image candidate 1.5; address bar 2; Hyperlink/TabItem 2.5; surface 4; Text 5; others 3), first 72, label ≤80 (fallback role or `Visible target`), **targetId presented as `"