@namzu/computer-use 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +3 -3
  3. package/dist/SubprocessComputerUseHost.d.ts +58 -10
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +214 -47
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +171 -10
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  9. package/dist/adapters/cua-driver/adapter.js +1479 -161
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  11. package/dist/adapters/cua-driver/client.d.ts +16 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  13. package/dist/adapters/cua-driver/client.js +54 -5
  14. package/dist/adapters/cua-driver/client.js.map +1 -1
  15. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  16. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/escalation.js +82 -0
  18. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  19. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  20. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  21. package/dist/adapters/cua-driver/keys.js +23 -0
  22. package/dist/adapters/cua-driver/keys.js.map +1 -1
  23. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  24. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/observe.js +227 -0
  26. package/dist/adapters/cua-driver/observe.js.map +1 -0
  27. package/dist/adapters/cua-driver/provision.d.ts +13 -13
  28. package/dist/adapters/cua-driver/provision.js +13 -13
  29. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  30. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  32. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  33. package/dist/adapters/types.d.ts +4 -4
  34. package/dist/adapters/types.d.ts.map +1 -1
  35. package/dist/adapters/types.js.map +1 -1
  36. package/dist/adapters/win32.d.ts +10 -0
  37. package/dist/adapters/win32.d.ts.map +1 -1
  38. package/dist/adapters/win32.js +12 -2
  39. package/dist/adapters/win32.js.map +1 -1
  40. package/dist/errors.d.ts +19 -0
  41. package/dist/errors.d.ts.map +1 -1
  42. package/dist/errors.js +26 -0
  43. package/dist/errors.js.map +1 -1
  44. package/dist/foreground/guard.d.ts +31 -0
  45. package/dist/foreground/guard.d.ts.map +1 -0
  46. package/dist/foreground/guard.js +156 -0
  47. package/dist/foreground/guard.js.map +1 -0
  48. package/dist/foreground/index.d.ts +11 -0
  49. package/dist/foreground/index.d.ts.map +1 -0
  50. package/dist/foreground/index.js +7 -0
  51. package/dist/foreground/index.js.map +1 -0
  52. package/dist/foreground/ladder.d.ts +143 -0
  53. package/dist/foreground/ladder.d.ts.map +1 -0
  54. package/dist/foreground/ladder.js +505 -0
  55. package/dist/foreground/ladder.js.map +1 -0
  56. package/dist/foreground/lease.d.ts +69 -0
  57. package/dist/foreground/lease.d.ts.map +1 -0
  58. package/dist/foreground/lease.js +182 -0
  59. package/dist/foreground/lease.js.map +1 -0
  60. package/dist/foreground/types.d.ts +287 -0
  61. package/dist/foreground/types.d.ts.map +1 -0
  62. package/dist/foreground/types.js +32 -0
  63. package/dist/foreground/types.js.map +1 -0
  64. package/dist/foreground/windows-helper-script.d.ts +19 -0
  65. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  66. package/dist/foreground/windows-helper-script.js +472 -0
  67. package/dist/foreground/windows-helper-script.js.map +1 -0
  68. package/dist/foreground/windows-monitor.d.ts +75 -0
  69. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  70. package/dist/foreground/windows-monitor.js +216 -0
  71. package/dist/foreground/windows-monitor.js.map +1 -0
  72. package/dist/foreground/windows.d.ts +21 -0
  73. package/dist/foreground/windows.d.ts.map +1 -0
  74. package/dist/foreground/windows.js +54 -0
  75. package/dist/foreground/windows.js.map +1 -0
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +3 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/presence/helper-script.d.ts +39 -0
  81. package/dist/presence/helper-script.d.ts.map +1 -0
  82. package/dist/presence/helper-script.js +320 -0
  83. package/dist/presence/helper-script.js.map +1 -0
  84. package/dist/presence/index.d.ts +6 -0
  85. package/dist/presence/index.d.ts.map +1 -0
  86. package/dist/presence/index.js +4 -0
  87. package/dist/presence/index.js.map +1 -0
  88. package/dist/presence/presence.d.ts +70 -0
  89. package/dist/presence/presence.d.ts.map +1 -0
  90. package/dist/presence/presence.js +147 -0
  91. package/dist/presence/presence.js.map +1 -0
  92. package/dist/presence/windows.d.ts +19 -0
  93. package/dist/presence/windows.d.ts.map +1 -0
  94. package/dist/presence/windows.js +39 -0
  95. package/dist/presence/windows.js.map +1 -0
  96. package/dist/util/call-scope.d.ts +34 -0
  97. package/dist/util/call-scope.d.ts.map +1 -0
  98. package/dist/util/call-scope.js +58 -0
  99. package/dist/util/call-scope.js.map +1 -0
  100. package/package.json +2 -2
  101. package/src/SubprocessComputerUseHost.ts +288 -46
  102. package/src/adapters/cua-driver/adapter.ts +1754 -175
  103. package/src/adapters/cua-driver/client.ts +59 -2
  104. package/src/adapters/cua-driver/escalation.ts +137 -0
  105. package/src/adapters/cua-driver/keys.ts +20 -0
  106. package/src/adapters/cua-driver/observe.ts +310 -0
  107. package/src/adapters/cua-driver/provision.ts +13 -13
  108. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  109. package/src/adapters/types.ts +8 -3
  110. package/src/adapters/win32.ts +26 -3
  111. package/src/errors.ts +32 -0
  112. package/src/foreground/guard.ts +182 -0
  113. package/src/foreground/index.ts +45 -0
  114. package/src/foreground/ladder.ts +616 -0
  115. package/src/foreground/lease.ts +232 -0
  116. package/src/foreground/types.ts +318 -0
  117. package/src/foreground/windows-helper-script.ts +471 -0
  118. package/src/foreground/windows-monitor.ts +288 -0
  119. package/src/foreground/windows.ts +73 -0
  120. package/src/index.ts +15 -1
  121. package/src/presence/helper-script.ts +323 -0
  122. package/src/presence/index.ts +17 -0
  123. package/src/presence/presence.ts +195 -0
  124. package/src/presence/windows.ts +54 -0
  125. package/src/util/call-scope.ts +73 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,68 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 7db536c: The Windows desktop driver Namzu downloads is now cua-driver 0.38.0 (it was 0.28.2): a 36 MB archive for x64 or 33 MB for arm64, checked against the hashes pinned in the package as before. The first `initialize()` on a machine that has the old copy fetches the new one into `<NAMZU_HOME>/computer-use/cua-driver/0.38.0/`; the old folder is left where it is and can be deleted. The window UI tree is now read with the driver's `full_output` flag, because 0.35 stopped returning the structured element list unless asked. Nothing to change in your code.
8
+
9
+ ## 4.0.0
10
+
11
+ ### Major Changes
12
+
13
+ - 880586f: On Windows, computer use no longer takes the screen from a person who is using it. Input that cannot be delivered in the background (a web page's keys, a covered window, a window that needs real focus, anything sent with `delivery_mode: "foreground"`, display-scope input and `focus_window`) now waits until the user has had no real keyboard or mouse input for 2 s, holds a cross-session lease on the screen, is watched for the user's input while it runs, and afterwards puts back the previous window and pointer, but only if nobody touched input meanwhile.
14
+
15
+ What changes for the model: a blocked action comes back as "Not delivered" and safe to retry, naming what blocks it (the user is busy, another session holds the screen, the user said no, a lock screen or administrator prompt is in front, the target runs with higher rights). A background action that had to use the screen says so and for how long. If the user presses Escape during one, every later `computer_use` call of that turn returns the same stop message until the next turn. When the user stays busy for 15 s they are asked once whether the application may use the screen for a moment; where nobody can be asked (exec, scheduled runs) the action parks and retries for up to 120 s and then says what blocks it.
16
+
17
+ What changes for a host: `ComputerUseHost` gains optional `beginTurn(turnId)` and `endTurn()`; `FocusWindowResult` gains optional `delivery`, `retrySafety` and `detail`. All are additive. `SubprocessComputerUseHost` takes `foreground: { approve?, session?, timing? }` and exports `ComputerUseStoppedError`. Breaking default in `@namzu/computer-use` (hence the major): an action that used to reach the screen at once (a display click, `focus_window`, `delivery_mode: "foreground"`) now waits for a still moment and can come back as not delivered; the value that changed is the idle wait before display input and `focus_window`, from none to 2 s; to keep the old behaviour for a script that owns the machine, pass `foreground: { timing: { idleMs: 0, approvedIdleMs: 0 } }`. The CLI asks the one question through its question card.
18
+
19
+ - 880586f: `computer_use` now says what it knows about each action instead of reporting a call that returned as "done", and works from a window's controls first.
20
+
21
+ What changes for the model: an action reports `done, verified` only when the host read the state back, `sent, not confirmed` when the input went out and nothing could check it (look before repeating, because repeating can act twice), and a failure marked "Not delivered" when nothing reached the target (safe to try again). `data.steps[]` carries `delivery` (`delivered_verified`, `delivered_unverified`, `not_delivered`) and `retrySafety` (`safe`, `unsafe`). A new `wait_for` action (element, text or window condition, bounded) replaces fixed waits and returns the window's controls with fresh refs. The tool text leads with `list_windows`, `ui_snapshot`, `ui_act`; the first coordinate click in a captured window gets a reminder, not a refusal.
22
+
23
+ What changes for a host: `UiActResult` gains optional `delivery`, `retrySafety` and `readBack`; `executeWindow` may return a `WindowInputResult`; a display `{ type: 'ok' }` may carry `delivery`, `retrySafety` and `detail`. All are additive and optional, so an existing host keeps working and keeps the plain `done`. `ComputerUseHost.executeWindow` is now declared as returning `Promise<void | WindowInputResult>`; a wrapper that annotates it as `Promise<void>` and discards the result still compiles, but one that forwards it should use the wider type.
24
+
25
+ What changes in the Windows backend (`@namzu/computer-use`): `set_value`, `toggle` and `select` read the control back and are verified or not delivered by what the window then shows; `set_value` on a field with no settable value is "not delivered" and no longer types into it as a fallback; a click that leaves another window in front, and window input the driver could not confirm, are "sent, not confirmed" instead of done; a refused background input is "not delivered" with what to do next. Refs of a window stay valid after a read-back. If your own tooling parsed the old "typed into the empty field" detail or relied on those cases counting as success, read `delivery` instead.
26
+
27
+ This is `major` for `@namzu/computer-use` because an outcome a caller could rely on changes: the `set_value` fallback to typing is gone, former successes become failures or unconfirmed results, and a driver error the backend cannot classify is now reported as "sent, not confirmed" and unsafe to repeat rather than "not delivered". To keep the old behaviour, read `ok` only and ignore `delivery`; nothing restores the typing fallback.
28
+
29
+ ### Minor Changes
30
+
31
+ - 880586f: Computer use on Windows now says "done, verified" for inputs that worked but the driver could not confirm, types into classic text boxes in the background, and puts your window back after it used the screen.
32
+
33
+ A press, a key or typed text in a window is read back by what the window shows afterwards: typed text that now appears, or a change that followed the input, held still, and was not happening before it, is `done, verified (reads "…")`; nothing observable stays `sent, not confirmed`, and an unrelated change is never taken as the effect. `set_value` on a classic Win32 edit control and `type_text` into a window whose focused control is one are sent as window messages and read back with the control's own text, with no focus change; a program running with higher rights refuses them and the result is `not_delivered` with the reason. A list the driver's value call does not change (a web page's select element) is chosen with the keyboard through the idle-gated foreground ladder and read back, else the result names the browser tool. After a foreground burst the previous window is restored whenever the target took the front, including when Windows refused the helper's own raise, and the result says why when it could not be.
34
+
35
+ For a host: `WindowInputResult` gains an optional `readBack`, additive. `ForegroundMonitor` gains an optional `editText`; `encodeHelperCommand` now encodes only the bootstrap, and `helperScriptLine` gives the script line written first to the helper. Nothing to change unless you call those directly.
36
+
37
+ - 880586f: Computer use on Windows now stops when you interrupt it, says plainly when an administrator window swallowed its typing, and refuses to act on a locked computer.
38
+
39
+ Interrupting a turn (Esc) ends a pending desktop action at once instead of waiting for the driver: an action that may already have been sent is reported as sent, not confirmed and unsafe to repeat, one that was not sent yet as not delivered and safe, and the window and pointer it borrowed are put back only after the driver has stopped acting. When a window running with higher rights is in front, input sent from here is dropped by Windows without any error; Namzu now detects that (the window's integrity level beforehand, and whether the system registered the input afterwards) and reports "An administrator window is in front; Namzu cannot type into it" as not delivered and safe to repeat. A locked computer (lock screen, sign-in screen or a secure prompt) is refused before anything is read or sent, and a screenshot taken while it locked is discarded. The desktop driver's own cursor is switched off so only Namzu's is shown.
40
+
41
+ For a host: every desktop-reaching `ComputerUseHost` method (`execute`, `listWindows`, `focusWindow`, `captureWindow`, `executeWindow`, `captureRegion`, `uiSnapshot`, `uiAct`) gains a trailing optional `signal?: AbortSignal`, additive; a host that ignores it keeps working. `MonitorState` gains optional integrity fields, `MonitorBurstEnd` gains optional `inputMoved` and `frontElevated`, and `@namzu/computer-use` exports `ComputerUseLockedError`. Nothing to change unless you implement a host or a foreground monitor.
42
+
43
+ - 880586f: On Windows, while a window is being operated you now see an agent cursor (a pixel-art arrow, separate from your real pointer) and a dithered border around that window. Both are click-through, never take focus, stay out of the taskbar and out of screenshots, and fade a few seconds after the last action or when the turn ends. They are on by default. To turn them off, pass `presence: false` to `SubprocessComputerUseHost` or set `NAMZU_COMPUTER_USE_PRESENCE=off`. If the overlay cannot start, or Windows cannot keep it out of screen captures, nothing is shown and actions are unaffected.
44
+ - 880586f: A `ui_snapshot` ref now names a control and survives later snapshots, a large window is shown as an outline you open one region at a time, and an action on a ref that no longer fits fails with a typed reason instead of acting on whatever is there.
45
+
46
+ What changes for the model: refs (`e12`) no longer die at the next `ui_snapshot`. `ui_act` finds the control again by its id, its place in the tree, then its role and name, and only then sends anything; if the control has gone the step fails with `STALE_REF`, and if several controls fit it fails with `AMBIGUOUS_TARGET`. Both mean nothing was sent, so it is safe to take a new snapshot and choose again. A window with more than about 220 controls comes back as an outline in which a region is marked `(+N more inside)` and has a ref; `ui_snapshot { root: <ref> }` reads that region alone (`offset` for the next page of a long one) and leaves every other ref usable, and `ui_snapshot { query: <text> }` lists only matching controls. The advice to "read a smaller window" is replaced by "drill into a region".
47
+
48
+ What changes for a host (additive and optional): `ComputerUseHost.uiSnapshot(windowId?, options?)` takes `UiSnapshotOptions` (`root`, `offset`, `query`); `UiElement` gains `hiddenChildren`; `UiSnapshot` gains `outline`, `total`, `region` and `next`; `UiActResult` gains `code` (`UiActFailureCode`: `STALE_REF`, `AMBIGUOUS_TARGET`). A host that ignores the new options keeps working: its refs are simply treated as stable for as long as it keeps them valid. The tool no longer discards the refs of earlier snapshots, so a host that reuses a ref string for a different control must not.
49
+
50
+ What changes in the Windows backend (`@namzu/computer-use`): refs carry identity evidence (automation id, role and name, tree path, window) and are re-resolved against a new read when older than 3 s, when a newer read of the window replaced the driver's handle, or after a driver restart; the same id under a different name is not accepted as the same control. The window is walked with the driver's own 5 000 node cap, a browser window is read once more when its first walk shows only the frame, and a control that holds nothing is no longer made the parent of rows the driver reported below a skipped level. Code that relied on an old ref being refused after the next snapshot, or on the exact wording "not a control of the latest ui_snapshot", should read `code` and `delivery` instead. This is `minor` for `@namzu/computer-use`: the refusal of an old ref has become a successful re-resolution, which no documented contract promised to preserve.
51
+
52
+ The CLI's permission review reads the new `ui_snapshot` fields (`root`, `offset`, `query`) as the read-only requests they are, instead of asking about an unknown field.
53
+
54
+ - 880586f: Selecting a file row in a folder window now selects it and no longer opens it. `ui_act select` on a list or tree row that can also be invoked goes through the row's selection pattern and is verified by reading the row back as selected; where that cannot be reached nothing is sent and the result says a click would open the row. Text typed in the background into a window that was never activated is delivered again (the window's single edit control is used when its thread has no focus window). A caller that relied on `select` opening a file should use `invoke`.
55
+
56
+ A background input that the window provably did not react to is now sent once more on the screen (through the idle gate, lease and restore) and its result is `sent, no effect seen` and safe to repeat if that also does nothing; a result that said `sent, not confirmed` for such an input before now says so only when the window changed in a way that cannot be tied to the input. A shortcut with a modifier that matches an item of the window's classic menu is carried out as that menu command without pressing a key. `ForegroundMonitor` gains an optional `menuCommand`; a custom monitor is unaffected. A key or mouse button held down now counts as the person using the computer.
57
+
58
+ An input is no longer sent a second time on the screen when the window read cannot show that it did nothing: a read with a cut text or a cut walk, Enter, Backspace, Delete, Space and Ctrl+Z/Y/X/V, and a shortcut carried out as a menu command are reported `sent, not confirmed` instead.
59
+
60
+ ### Patch Changes
61
+
62
+ - 880586f: The agent cursor and presence border now also appear on a window that was opened after the overlay helper started (before, such a window got neither), they are placed correctly on displays scaled above 100%, and a helper that ends mid-session is started again by the next action instead of leaving the overlay off for the rest of the session. Nothing to change on your side.
63
+ - 880586f: A `ui_act` ref to one of several identical controls (same role and name, no id) no longer acts on a neighbour after the window changes: it answers `AMBIGUOUS_TARGET` and sends nothing, so take a new `ui_snapshot` and use the ref it gives. A window handle that another program reuses no longer adopts the old program's refs, a `query` snapshot no longer overwrites where existing refs were found, and one read creates at most 1,000 new refs. A paged outline no longer repeats nameless containers on the next page.
64
+ - 880586f: Computer use on Windows no longer reports typed text as delivered because an unrelated label changed, no longer types into a dialog that happens to share the program, no longer stops a run when the front window cannot be read, and no longer tells the model that input was dropped (and is safe to repeat) unless an administrator window was actually in front. A cancelled action stops waiting for a helper that does not answer.
65
+
3
66
  ## 3.1.0
4
67
 
5
68
  ### Minor Changes
@@ -239,7 +302,7 @@ progress in <a local notes directory>/...` — a runtime error
239
302
  returns 404, to explain the doctor's protocol/runtime split. The split is now
240
303
  explained in the sentence itself.
241
304
  - `@namzu/sdk` source comments cited design documents by path. They cite the
242
- session by name instead, which is what the reference was ever worth.
305
+ session by name instead, which is all such a citation was ever worth.
243
306
 
244
307
  No API, type, or behaviour change. The `@namzu/sandbox` message text is the
245
308
  only runtime string affected, and nothing asserts on it.
package/README.md CHANGED
@@ -107,10 +107,10 @@ one `cua-driver.exe mcp` process for the host's lifetime, spoken to over its
107
107
  standard streams:
108
108
 
109
109
  - **Pinned and checked.** The first `initialize()` downloads cua-driver
110
- 0.28.2 for this architecture (x64 or arm64, a 27–29 MB archive from the
110
+ 0.38.0 for this architecture (x64 or arm64, a 34–36 MB archive from the
111
111
  project's GitHub releases), checks the SHA-256 of the archive and of the
112
112
  executable in it against values in this package, and keeps
113
- `cua-driver.exe` in `<NAMZU_HOME>/computer-use/cua-driver/0.28.2/`
113
+ `cua-driver.exe` in `<NAMZU_HOME>/computer-use/cua-driver/0.38.0/`
114
114
  (`~/.namzu` by default). Nothing else in the archive is written. Later
115
115
  sessions start the cached copy after checking its hash again.
116
116
  - **Quiet.** It runs with its telemetry and its release check switched off
@@ -160,7 +160,7 @@ standard streams:
160
160
  - **Fallback.** When cua-driver cannot be downloaded, verified or started,
161
161
  or does not reach the desktop, the host uses PowerShell instead — one
162
162
  `powershell.exe` per action, DPI aware, Unicode text, no window list.
163
- `host.backend` says which is in use (`cua-driver 0.28.2`, `powershell`),
163
+ `host.backend` says which is in use (`cua-driver 0.38.0`, `powershell`),
164
164
  `host.fallbackReason` why cua-driver is not.
165
165
 
166
166
  `NAMZU_CUA_DRIVER=off` keeps cua-driver out (no download); a path in it runs
@@ -1,6 +1,8 @@
1
- import type { ComputerUseAction, ComputerUseCapabilities, ComputerUseHost, ComputerUseResult, DisplayGeometry, FocusWindowResult, Rect, ScreenshotResult, UiActResult, UiElementAction, UiSnapshot, WindowInfo, WindowInputAction, WindowScreenshotResult } from '@namzu/sdk';
1
+ import type { ComputerUseAction, ComputerUseCapabilities, ComputerUseHost, ComputerUseResult, DisplayGeometry, FocusWindowResult, Rect, ScreenshotResult, UiActResult, UiElementAction, UiSnapshot, UiSnapshotOptions, WindowInfo, WindowInputAction, WindowInputResult, WindowScreenshotResult } from '@namzu/sdk';
2
2
  import { type Adapter } from './adapters/types.js';
3
3
  import type { Win32AdapterOptions } from './adapters/win32.js';
4
+ import { type ForegroundApprover, type ForegroundLadder, type LadderTiming } from './foreground/index.js';
5
+ import { type Presence } from './presence/index.js';
4
6
  export interface SubprocessComputerUseHostOptions {
5
7
  readonly env?: NodeJS.ProcessEnv;
6
8
  readonly platform?: NodeJS.Platform;
@@ -15,6 +17,32 @@ export interface SubprocessComputerUseHostOptions {
15
17
  * first use, with the PowerShell path as its fallback. See the README.
16
18
  */
17
19
  readonly windows?: SubprocessComputerUseHostWindowsOptions;
20
+ /**
21
+ * The foreground ladder: how an action that can only be delivered in the
22
+ * foreground uses the user's screen. On Windows it is on by default.
23
+ */
24
+ readonly foreground?: SubprocessComputerUseHostForegroundOptions;
25
+ /**
26
+ * The agent cursor and the border around the window being operated. On by
27
+ * default on Windows; `false` turns them off, as does the environment
28
+ * variable `NAMZU_COMPUTER_USE_PRESENCE=off`. A ready overlay replaces the
29
+ * one built for this machine (for tests).
30
+ */
31
+ readonly presence?: boolean | Presence;
32
+ }
33
+ export interface SubprocessComputerUseHostForegroundOptions {
34
+ /**
35
+ * Asks the person, once, whether an application may use the screen for a
36
+ * moment while they are busy. Absent (or answering `unavailable`), a run
37
+ * with nobody to ask waits and retries within a bound instead.
38
+ */
39
+ readonly approve?: ForegroundApprover;
40
+ /** Names this session in the screen lease. */
41
+ readonly session?: string;
42
+ /** Overrides for the thresholds and bounds; see `DEFAULT_TIMING`. */
43
+ readonly timing?: Partial<LadderTiming>;
44
+ /** A ready ladder, instead of the one built for this machine. For tests. */
45
+ readonly ladder?: ForegroundLadder;
18
46
  }
19
47
  export type SubprocessComputerUseHostWindowsOptions = Pick<Win32AdapterOptions, 'backend' | 'cuaDriverPath' | 'cacheDir' | 'download'>;
20
48
  /**
@@ -35,10 +63,12 @@ export declare class SubprocessComputerUseHost implements ComputerUseHost {
35
63
  readonly id = "subprocess-computer-use-host";
36
64
  private _capabilities;
37
65
  private adapter;
66
+ private ladder;
67
+ private presence;
38
68
  constructor(options?: SubprocessComputerUseHostOptions);
39
69
  get capabilities(): ComputerUseCapabilities;
40
70
  /**
41
- * What drives the desktop once initialised — `cua-driver 0.28.2`,
71
+ * What drives the desktop once initialised — `cua-driver 0.38.0`,
42
72
  * `powershell`, … — for logs and diagnosis. Undefined before
43
73
  * `initialize()` and for adapters that do not say.
44
74
  */
@@ -47,23 +77,23 @@ export declare class SubprocessComputerUseHost implements ComputerUseHost {
47
77
  get fallbackReason(): string | undefined;
48
78
  initialize(): Promise<void>;
49
79
  getDisplayGeometry(): Promise<DisplayGeometry>;
50
- execute(action: ComputerUseAction): Promise<ComputerUseResult>;
80
+ execute(action: ComputerUseAction, signal?: AbortSignal): Promise<ComputerUseResult>;
51
81
  /** Offered to the model only when `capabilities.windows` is true. */
52
- listWindows(): Promise<readonly WindowInfo[]>;
82
+ listWindows(signal?: AbortSignal): Promise<readonly WindowInfo[]>;
53
83
  /** Offered to the model only when `capabilities.windows` is true. */
54
- focusWindow(id: string): Promise<FocusWindowResult>;
84
+ focusWindow(id: string, signal?: AbortSignal): Promise<FocusWindowResult>;
55
85
  /** Window-local PNG and input, only when the selected adapter supports both. */
56
- captureWindow(id: string): Promise<WindowScreenshotResult>;
57
- executeWindow(captureId: string, action: WindowInputAction): Promise<void>;
86
+ captureWindow(id: string, signal?: AbortSignal): Promise<WindowScreenshotResult>;
87
+ executeWindow(captureId: string, action: WindowInputAction, signal?: AbortSignal): Promise<WindowInputResult | undefined>;
58
88
  /** Offered to the model only when `capabilities.regionCapture` is true. */
59
- captureRegion(rect: Rect): Promise<ScreenshotResult>;
89
+ captureRegion(rect: Rect, signal?: AbortSignal): Promise<ScreenshotResult>;
60
90
  /**
61
91
  * A window's controls. Offered to the model only when
62
92
  * `capabilities.uiTree` is true.
63
93
  *
64
94
  * @experimental Follows the SDK's UI-tree surface.
65
95
  */
66
- uiSnapshot(windowId?: string): Promise<UiSnapshot>;
96
+ uiSnapshot(windowId?: string, options?: UiSnapshotOptions, signal?: AbortSignal): Promise<UiSnapshot>;
67
97
  /**
68
98
  * Act on a control of the latest {@link uiSnapshot}. A request lost after
69
99
  * it was sent (the driver died or stopped answering) may have acted, so
@@ -71,9 +101,27 @@ export declare class SubprocessComputerUseHost implements ComputerUseHost {
71
101
  *
72
102
  * @experimental Follows the SDK's UI-tree surface.
73
103
  */
74
- uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult>;
104
+ uiAct(ref: string, action: UiElementAction, value?: string, signal?: AbortSignal): Promise<UiActResult>;
75
105
  /** Stops whatever the adapter keeps running (the Windows cua-driver process). */
76
106
  dispose(): Promise<void>;
107
+ /**
108
+ * The model's turn is making a tool call. A new turn lifts an Escape stop.
109
+ */
110
+ beginTurn(turnId: string): void;
111
+ /** The turn ended or was interrupted: the input monitor and any lease are released. */
112
+ endTurn(): Promise<void>;
113
+ /**
114
+ * One tool call: its cancellation reaches every driver call and foreground
115
+ * burst made for it. When cancelled, a call that changes the desktop answers
116
+ * at once with what is known (`onAbort`, told whether anything may have been
117
+ * sent); a read has no answer to give and throws.
118
+ */
119
+ private scoped;
120
+ /** True when the computer is known to be locked; false when it is not or cannot be told. */
121
+ private locked;
122
+ private refuseWhenLocked;
123
+ /** A capture taken while the screen was locked shows no current state: it is dropped. */
124
+ private notCapturedLocked;
77
125
  private requireAdapter;
78
126
  }
79
127
  //# sourceMappingURL=SubprocessComputerUseHost.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"SubprocessComputerUseHost.d.ts","sourceRoot":"","sources":["../src/SubprocessComputerUseHost.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,iBAAiB,EACjB,uBAAuB,EACvB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,IAAI,EACJ,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,UAAU,EACV,UAAU,EACV,iBAAiB,EACjB,sBAAsB,EACtB,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,KAAK,OAAO,EAA2B,MAAM,qBAAqB,CAAA;AAC3E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA;AAsB9D,MAAM,WAAW,gCAAgC;IAChD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAA;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IACnC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAC1B;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,uCAAuC,CAAA;CAC1D;AAED,MAAM,MAAM,uCAAuC,GAAG,IAAI,CACzD,mBAAmB,EACnB,SAAS,GAAG,eAAe,GAAG,UAAU,GAAG,UAAU,CACrD,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,qBAAa,yBAA0B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AAC;IAWhF,aAAa,CAClB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,iBAAiB,EACzB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAAC;IA2BzC,2EAA2E;IACrE,aAAa,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAWhF;;;;;OAKG;IACG,UAAU,CACf,QAAQ,CAAC,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,iBAAiB,EAC3B,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,UAAU,CAAC;IAStB;;;;;;OAMG;IACG,KAAK,CACV,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAAe,EACvB,KAAK,CAAC,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,WAAW,CAAC;IA8BvB,iFAAiF;IAC3E,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ9B;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B,uFAAuF;IACjF,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAK9B;;;;;OAKG;YACW,MAAM;IAgBpB,4FAA4F;YAC9E,MAAM;YASN,gBAAgB;IAI9B,yFAAyF;YAC3E,iBAAiB;IAI/B,OAAO,CAAC,cAAc;CAStB"}
@@ -1,6 +1,9 @@
1
1
  import { AdapterUnavailableError } from './adapters/types.js';
2
2
  import { detectDisplayServer } from './detect/index.js';
3
- import { ComputerUseOutcomeUnknownError } from './errors.js';
3
+ import { ComputerUseLockedError, ComputerUseOutcomeUnknownError, ComputerUseStoppedError, LOCKED_TEXT, } from './errors.js';
4
+ import { createWindowsForegroundLadder, } from './foreground/index.js';
5
+ import { createWindowsPresence } from './presence/index.js';
6
+ import { CallAbortedError, inCallScope } from './util/call-scope.js';
4
7
  import { SpawnError } from './util/spawn.js';
5
8
  const UNINITIALISED_CAPABILITIES = {
6
9
  displayServer: 'unknown',
@@ -35,6 +38,8 @@ export class SubprocessComputerUseHost {
35
38
  id = 'subprocess-computer-use-host';
36
39
  _capabilities;
37
40
  adapter = null;
41
+ ladder;
42
+ presence;
38
43
  constructor(options = {}) {
39
44
  this.options = options;
40
45
  const displayServer = detectDisplayServer(options.env, options.platform);
@@ -42,6 +47,7 @@ export class SubprocessComputerUseHost {
42
47
  ...UNINITIALISED_CAPABILITIES,
43
48
  displayServer,
44
49
  });
50
+ this.ladder = options.foreground?.ladder;
45
51
  if (options.adapter) {
46
52
  this.adapter = options.adapter;
47
53
  this._capabilities = options.adapter.capabilities;
@@ -51,7 +57,7 @@ export class SubprocessComputerUseHost {
51
57
  return this._capabilities;
52
58
  }
53
59
  /**
54
- * What drives the desktop once initialised — `cua-driver 0.28.2`,
60
+ * What drives the desktop once initialised — `cua-driver 0.38.0`,
55
61
  * `powershell`, … — for logs and diagnosis. Undefined before
56
62
  * `initialize()` and for adapters that do not say.
57
63
  */
@@ -66,7 +72,27 @@ export class SubprocessComputerUseHost {
66
72
  if (this.adapter)
67
73
  return;
68
74
  const displayServer = this._capabilities.displayServer;
69
- const adapter = await loadAdapter(displayServer, this.options);
75
+ if (!this.ladder && displayServer === 'win32') {
76
+ this.ladder = createWindowsForegroundLadder({
77
+ ...(this.options.env !== undefined ? { env: this.options.env } : {}),
78
+ ...(this.options.platform !== undefined ? { platform: this.options.platform } : {}),
79
+ ...(this.options.foreground?.approve ? { approve: this.options.foreground.approve } : {}),
80
+ ...(this.options.foreground?.session ? { session: this.options.foreground.session } : {}),
81
+ ...(this.options.foreground?.timing ? { timing: this.options.foreground.timing } : {}),
82
+ });
83
+ }
84
+ if (!this.presence && displayServer === 'win32') {
85
+ const option = this.options.presence;
86
+ this.presence =
87
+ typeof option === 'object'
88
+ ? option
89
+ : createWindowsPresence({
90
+ ...(this.options.env !== undefined ? { env: this.options.env } : {}),
91
+ ...(this.options.platform !== undefined ? { platform: this.options.platform } : {}),
92
+ ...(option === false ? { enabled: false } : {}),
93
+ });
94
+ }
95
+ const adapter = await loadAdapter(displayServer, this.options, this.ladder, this.presence);
70
96
  // Loading an adapter proves its tools exist on PATH, not that a desktop
71
97
  // answers. A WSL process finds PowerShell and still may have no
72
98
  // interactive Windows session to capture; an ssh session finds xdotool
@@ -92,64 +118,120 @@ export class SubprocessComputerUseHost {
92
118
  const adapter = this.requireAdapter();
93
119
  return adapter.getDisplayGeometry();
94
120
  }
95
- async execute(action) {
121
+ async execute(action, signal) {
96
122
  const adapter = this.requireAdapter();
97
- try {
98
- return await adapter.execute(action);
99
- }
100
- catch (error) {
101
- // SpawnError is produced only after the subprocess started and then
102
- // timed out or closed non-zero. An unsafe action may have taken effect
103
- // before that terminal status (a multi-command drag is the clearest
104
- // example), so replaying it could duplicate or compound the change.
105
- // A raw spawn error means the process never established that boundary;
106
- // safe reads and idempotent mouse_move keep their ordinary diagnosis.
107
- if (error instanceof SpawnError && UNSAFE_TO_REPLAY_AFTER_START.has(action.type)) {
108
- throw new ComputerUseOutcomeUnknownError(action.type, error);
123
+ const read = action.type === 'screenshot' || action.type === 'cursor_position';
124
+ return this.scoped(signal, async () => {
125
+ if (await this.locked()) {
126
+ if (read)
127
+ throw new ComputerUseLockedError();
128
+ return {
129
+ type: 'ok',
130
+ delivery: 'not_delivered',
131
+ retrySafety: 'safe',
132
+ detail: LOCKED_TEXT,
133
+ };
109
134
  }
110
- throw error;
111
- }
135
+ try {
136
+ const result = await adapter.execute(action);
137
+ if (action.type === 'screenshot')
138
+ await this.notCapturedLocked();
139
+ return result;
140
+ }
141
+ catch (error) {
142
+ // SpawnError is produced only after the subprocess started and then
143
+ // timed out or closed non-zero. An unsafe action may have taken effect
144
+ // before that terminal status (a multi-command drag is the clearest
145
+ // example), so replaying it could duplicate or compound the change.
146
+ // A raw spawn error means the process never established that boundary;
147
+ // safe reads and idempotent mouse_move keep their ordinary diagnosis.
148
+ if (error instanceof SpawnError && UNSAFE_TO_REPLAY_AFTER_START.has(action.type)) {
149
+ throw new ComputerUseOutcomeUnknownError(action.type, error);
150
+ }
151
+ throw error;
152
+ }
153
+ }, read
154
+ ? undefined
155
+ : (sent) => ({
156
+ type: 'ok',
157
+ ...abortedDelivery(sent),
158
+ }));
112
159
  }
113
160
  /** Offered to the model only when `capabilities.windows` is true. */
114
- async listWindows() {
161
+ async listWindows(signal) {
115
162
  const adapter = this.requireAdapter();
116
163
  if (!adapter.listWindows)
117
164
  throw unsupported('listWindows', this._capabilities.displayServer);
118
- return adapter.listWindows();
165
+ return this.scoped(signal, async () => {
166
+ await this.refuseWhenLocked();
167
+ return adapter.listWindows();
168
+ });
119
169
  }
120
170
  /** Offered to the model only when `capabilities.windows` is true. */
121
- async focusWindow(id) {
171
+ async focusWindow(id, signal) {
122
172
  const adapter = this.requireAdapter();
123
173
  if (!adapter.focusWindow)
124
174
  throw unsupported('focusWindow', this._capabilities.displayServer);
125
- return adapter.focusWindow(id);
175
+ return this.scoped(signal, async () => {
176
+ if (await this.locked())
177
+ return {
178
+ ok: false,
179
+ focusedId: null,
180
+ delivery: 'not_delivered',
181
+ retrySafety: 'safe',
182
+ detail: LOCKED_TEXT,
183
+ };
184
+ return adapter.focusWindow(id);
185
+ }, (sent) => ({
186
+ ok: false,
187
+ focusedId: null,
188
+ ...abortedDelivery(sent),
189
+ }));
126
190
  }
127
191
  /** Window-local PNG and input, only when the selected adapter supports both. */
128
- async captureWindow(id) {
192
+ async captureWindow(id, signal) {
129
193
  const adapter = this.requireAdapter();
130
194
  if (!adapter.captureWindow)
131
195
  throw unsupported('captureWindow', this._capabilities.displayServer);
132
- return adapter.captureWindow(id);
196
+ return this.scoped(signal, async () => {
197
+ await this.refuseWhenLocked();
198
+ const shot = await adapter.captureWindow(id);
199
+ await this.notCapturedLocked();
200
+ return shot;
201
+ });
133
202
  }
134
- async executeWindow(captureId, action) {
203
+ async executeWindow(captureId, action, signal) {
135
204
  const adapter = this.requireAdapter();
136
205
  if (!adapter.executeWindow)
137
206
  throw unsupported('executeWindow', this._capabilities.displayServer);
138
- try {
139
- await adapter.executeWindow(captureId, action);
140
- }
141
- catch (error) {
142
- if (error instanceof SpawnError && UNSAFE_TO_REPLAY_AFTER_START.has(action.type))
143
- throw new ComputerUseOutcomeUnknownError(action.type, error);
144
- throw error;
145
- }
207
+ return this.scoped(signal, async () => {
208
+ if (await this.locked())
209
+ return {
210
+ delivery: 'not_delivered',
211
+ retrySafety: 'safe',
212
+ detail: LOCKED_TEXT,
213
+ };
214
+ try {
215
+ return await adapter.executeWindow(captureId, action);
216
+ }
217
+ catch (error) {
218
+ if (error instanceof SpawnError && UNSAFE_TO_REPLAY_AFTER_START.has(action.type))
219
+ throw new ComputerUseOutcomeUnknownError(action.type, error);
220
+ throw error;
221
+ }
222
+ }, (sent) => abortedDelivery(sent));
146
223
  }
147
224
  /** Offered to the model only when `capabilities.regionCapture` is true. */
148
- async captureRegion(rect) {
225
+ async captureRegion(rect, signal) {
149
226
  const adapter = this.requireAdapter();
150
227
  if (!adapter.captureRegion)
151
228
  throw unsupported('captureRegion', this._capabilities.displayServer);
152
- return adapter.captureRegion(rect);
229
+ return this.scoped(signal, async () => {
230
+ await this.refuseWhenLocked();
231
+ const shot = await adapter.captureRegion(rect);
232
+ await this.notCapturedLocked();
233
+ return shot;
234
+ });
153
235
  }
154
236
  /**
155
237
  * A window's controls. Offered to the model only when
@@ -157,11 +239,14 @@ export class SubprocessComputerUseHost {
157
239
  *
158
240
  * @experimental Follows the SDK's UI-tree surface.
159
241
  */
160
- async uiSnapshot(windowId) {
242
+ async uiSnapshot(windowId, options, signal) {
161
243
  const adapter = this.requireAdapter();
162
244
  if (!adapter.uiSnapshot)
163
245
  throw unsupported('uiSnapshot', this._capabilities.displayServer);
164
- return adapter.uiSnapshot(windowId);
246
+ return this.scoped(signal, async () => {
247
+ await this.refuseWhenLocked();
248
+ return adapter.uiSnapshot(windowId, options);
249
+ });
165
250
  }
166
251
  /**
167
252
  * Act on a control of the latest {@link uiSnapshot}. A request lost after
@@ -170,39 +255,119 @@ export class SubprocessComputerUseHost {
170
255
  *
171
256
  * @experimental Follows the SDK's UI-tree surface.
172
257
  */
173
- async uiAct(ref, action, value) {
258
+ async uiAct(ref, action, value, signal) {
174
259
  const adapter = this.requireAdapter();
175
260
  if (!adapter.uiAct)
176
261
  throw unsupported('uiAct', this._capabilities.displayServer);
177
- try {
178
- return await adapter.uiAct(ref, action, value);
179
- }
180
- catch (error) {
181
- if (error instanceof SpawnError)
262
+ return this.scoped(signal, async () => {
263
+ if (await this.locked())
182
264
  return {
183
265
  ok: false,
184
- detail: `the desktop driver stopped before it answered, so ${action} may or may not have happened; look at the screen (ui_snapshot or screenshot) before trying again. ${error.message}`,
266
+ delivery: 'not_delivered',
267
+ retrySafety: 'safe',
268
+ detail: LOCKED_TEXT,
185
269
  };
186
- throw error;
187
- }
270
+ try {
271
+ return await adapter.uiAct(ref, action, value);
272
+ }
273
+ catch (error) {
274
+ if (error instanceof SpawnError)
275
+ return {
276
+ ok: false,
277
+ delivery: 'delivered_unverified',
278
+ retrySafety: 'unsafe',
279
+ detail: `the desktop driver stopped before it answered, so ${action} may or may not have happened; look at the screen (ui_snapshot or screenshot) before trying again. ${error.message}`,
280
+ };
281
+ throw error;
282
+ }
283
+ }, (sent) => ({ ok: false, ...abortedDelivery(sent) }));
188
284
  }
189
285
  /** Stops whatever the adapter keeps running (the Windows cua-driver process). */
190
286
  async dispose() {
191
287
  const adapter = this.adapter;
192
288
  this.adapter = null;
193
289
  await adapter?.dispose?.();
290
+ await this.ladder?.dispose();
291
+ await this.presence?.dispose();
292
+ }
293
+ /**
294
+ * The model's turn is making a tool call. A new turn lifts an Escape stop.
295
+ */
296
+ beginTurn(turnId) {
297
+ this.ladder?.beginTurn(turnId);
298
+ }
299
+ /** The turn ended or was interrupted: the input monitor and any lease are released. */
300
+ async endTurn() {
301
+ await this.ladder?.endTurn();
302
+ this.presence?.hide();
303
+ }
304
+ /**
305
+ * One tool call: its cancellation reaches every driver call and foreground
306
+ * burst made for it. When cancelled, a call that changes the desktop answers
307
+ * at once with what is known (`onAbort`, told whether anything may have been
308
+ * sent); a read has no answer to give and throws.
309
+ */
310
+ async scoped(signal, run, onAbort) {
311
+ return inCallScope(signal, async (scope) => {
312
+ try {
313
+ return await run();
314
+ }
315
+ catch (error) {
316
+ if (!(error instanceof CallAbortedError))
317
+ throw error;
318
+ if (!onAbort)
319
+ throw error;
320
+ return onAbort(scope.sent || error.sent);
321
+ }
322
+ });
323
+ }
324
+ /** True when the computer is known to be locked; false when it is not or cannot be told. */
325
+ async locked() {
326
+ if (!this.ladder)
327
+ return false;
328
+ const state = await this.ladder.lockState().catch((error) => {
329
+ if (error instanceof CallAbortedError)
330
+ throw error;
331
+ return null;
332
+ });
333
+ return state === 'locked';
334
+ }
335
+ async refuseWhenLocked() {
336
+ if (await this.locked())
337
+ throw new ComputerUseLockedError();
338
+ }
339
+ /** A capture taken while the screen was locked shows no current state: it is dropped. */
340
+ async notCapturedLocked() {
341
+ if (await this.locked())
342
+ throw new ComputerUseLockedError();
194
343
  }
195
344
  requireAdapter() {
345
+ if (this.ladder?.stopped)
346
+ throw new ComputerUseStoppedError();
196
347
  if (!this.adapter) {
197
348
  throw new Error('SubprocessComputerUseHost: adapter not initialised — call `await host.initialize()` first');
198
349
  }
199
350
  return this.adapter;
200
351
  }
201
352
  }
353
+ /** What a cancelled call that changes the desktop tells the model. */
354
+ function abortedDelivery(sent) {
355
+ return sent
356
+ ? {
357
+ delivery: 'delivered_unverified',
358
+ retrySafety: 'unsafe',
359
+ detail: 'The turn was cancelled while this was being sent, so it may have gone through. Look at the window before repeating it.',
360
+ }
361
+ : {
362
+ delivery: 'not_delivered',
363
+ retrySafety: 'safe',
364
+ detail: 'The turn was cancelled before this was sent, so nothing happened.',
365
+ };
366
+ }
202
367
  function unsupported(method, displayServer) {
203
368
  return new Error(`SubprocessComputerUseHost: ${method} is not supported by the ${displayServer} adapter in use.`);
204
369
  }
205
- async function loadAdapter(displayServer, options) {
370
+ async function loadAdapter(displayServer, options, ladder, presence) {
206
371
  switch (displayServer) {
207
372
  case 'darwin': {
208
373
  const { DarwinAdapter } = await import('./adapters/darwin.js');
@@ -222,6 +387,8 @@ async function loadAdapter(displayServer, options) {
222
387
  ...options.windows,
223
388
  ...(options.env !== undefined ? { env: options.env } : {}),
224
389
  ...(options.platform !== undefined ? { platform: options.platform } : {}),
390
+ ...(ladder ? { foreground: ladder } : {}),
391
+ ...(presence ? { presence } : {}),
225
392
  });
226
393
  }
227
394
  case 'unknown':