@roam-agent/roam-computer-use 0.0.0-stage → 0.5.2

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 (112) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -2
  3. package/assets/reference/img.jpg +0 -0
  4. package/docs/README.md +45 -0
  5. package/docs/content/docs/explanation/action-pipeline.mdx +36 -0
  6. package/docs/content/docs/explanation/architecture.mdx +161 -0
  7. package/docs/content/docs/explanation/index.mdx +19 -0
  8. package/docs/content/docs/explanation/meta.json +5 -0
  9. package/docs/content/docs/explanation/observation-pipeline.mdx +37 -0
  10. package/docs/content/docs/explanation/platform-boundary.mdx +37 -0
  11. package/docs/content/docs/explanation/state-and-scheduling.mdx +35 -0
  12. package/docs/content/docs/how-to-guides/develop-and-validate.mdx +112 -0
  13. package/docs/content/docs/how-to-guides/index.mdx +12 -0
  14. package/docs/content/docs/how-to-guides/linux.mdx +68 -0
  15. package/docs/content/docs/how-to-guides/meta.json +1 -0
  16. package/docs/content/docs/how-to-guides/troubleshooting.mdx +126 -0
  17. package/docs/content/docs/index.mdx +67 -0
  18. package/docs/content/docs/meta.json +5 -0
  19. package/docs/content/docs/reference/agent/contract.mdx +162 -0
  20. package/docs/content/docs/reference/agent/index.mdx +8 -0
  21. package/docs/content/docs/reference/agent/meta.json +8 -0
  22. package/docs/content/docs/reference/agent/tools.mdx +221 -0
  23. package/docs/content/docs/reference/codebase.mdx +139 -0
  24. package/docs/content/docs/reference/configuration.mdx +113 -0
  25. package/docs/content/docs/reference/index.mdx +28 -0
  26. package/docs/content/docs/reference/meta.json +10 -0
  27. package/docs/content/docs/reference/platforms/index.mdx +18 -0
  28. package/docs/content/docs/reference/platforms/macos/accessibility.mdx +61 -0
  29. package/docs/content/docs/reference/platforms/macos/actions.mdx +63 -0
  30. package/docs/content/docs/reference/platforms/macos/capture.mdx +58 -0
  31. package/docs/content/docs/reference/platforms/macos/implementation.mdx +98 -0
  32. package/docs/content/docs/reference/platforms/macos/index.mdx +16 -0
  33. package/docs/content/docs/reference/platforms/macos/meta.json +10 -0
  34. package/docs/content/docs/reference/platforms/macos/root-targeting.mdx +47 -0
  35. package/docs/content/docs/reference/platforms/meta.json +8 -0
  36. package/docs/content/docs/reference/platforms/windows.mdx +75 -0
  37. package/docs/content/docs/tutorials/getting-started.mdx +46 -0
  38. package/docs/content/docs/tutorials/index.mdx +10 -0
  39. package/docs/content/docs/tutorials/meta.json +1 -0
  40. package/extensions/computer-use.ts +235 -0
  41. package/native/linux/bridge-rs/Cargo.lock +1204 -0
  42. package/native/linux/bridge-rs/Cargo.toml +21 -0
  43. package/native/linux/bridge-rs/src/atspi.rs +670 -0
  44. package/native/linux/bridge-rs/src/error.rs +65 -0
  45. package/native/linux/bridge-rs/src/lib.rs +11 -0
  46. package/native/linux/bridge-rs/src/main.rs +1110 -0
  47. package/native/linux/bridge-rs/src/protocol.rs +49 -0
  48. package/native/linux/bridge-rs/src/state.rs +293 -0
  49. package/native/linux/bridge-rs/src/wayland.rs +89 -0
  50. package/native/linux/bridge-rs/src/x11.rs +909 -0
  51. package/native/linux/bridge-rs/tests/protocol_tests.rs +73 -0
  52. package/native/macos/activity_glow.swift +169 -0
  53. package/native/macos/bridge.swift +3968 -0
  54. package/native/windows/bridge-rs/Cargo.lock +396 -0
  55. package/native/windows/bridge-rs/Cargo.toml +30 -0
  56. package/native/windows/bridge-rs/src/capture.rs +561 -0
  57. package/native/windows/bridge-rs/src/error.rs +81 -0
  58. package/native/windows/bridge-rs/src/input.rs +501 -0
  59. package/native/windows/bridge-rs/src/lib.rs +85 -0
  60. package/native/windows/bridge-rs/src/main.rs +1683 -0
  61. package/native/windows/bridge-rs/src/protocol.rs +53 -0
  62. package/native/windows/bridge-rs/src/refs.rs +237 -0
  63. package/native/windows/bridge-rs/src/state.rs +55 -0
  64. package/native/windows/bridge-rs/src/uia.rs +1252 -0
  65. package/native/windows/bridge-rs/src/window.rs +718 -0
  66. package/native/windows/bridge-rs/tests/protocol_tests.rs +252 -0
  67. package/native/windows/bridge-rs/tests/refs_tests.rs +86 -0
  68. package/native/windows/bridge-rs/tests/state_tests.rs +33 -0
  69. package/package.json +105 -5
  70. package/prebuilt/macos/arm64/bridge +0 -0
  71. package/prebuilt/macos/x64/bridge +0 -0
  72. package/roam/README.md +52 -0
  73. package/roam/bridge/macos/arm64/bridge +0 -0
  74. package/roam/bridge/macos/x64/bridge +0 -0
  75. package/roam/bridge/manifest.json +20 -0
  76. package/roam/helper-path.d.mts +9 -0
  77. package/roam/helper-path.mjs +36 -0
  78. package/roam/identity.d.mts +16 -0
  79. package/roam/identity.mjs +64 -0
  80. package/roam/index.ts +51 -0
  81. package/roam/redirect.ts +51 -0
  82. package/roam/repair.ts +120 -0
  83. package/scripts/build-native.mjs +286 -0
  84. package/scripts/lib/roam-bridge.mjs +98 -0
  85. package/scripts/setup-helper.mjs +635 -0
  86. package/src/actions.ts +130 -0
  87. package/src/bridge.ts +2594 -0
  88. package/src/cdp.ts +658 -0
  89. package/src/config.ts +226 -0
  90. package/src/contract.ts +107 -0
  91. package/src/extension/index.ts +9 -0
  92. package/src/find-params.ts +21 -0
  93. package/src/note.ts +195 -0
  94. package/src/outline.ts +702 -0
  95. package/src/output.ts +134 -0
  96. package/src/permissions.ts +111 -0
  97. package/src/platform/architecture.ts +23 -0
  98. package/src/platform/coerce.ts +16 -0
  99. package/src/platform/index.ts +61 -0
  100. package/src/platform/linux/backend.ts +186 -0
  101. package/src/platform/linux/helper.ts +238 -0
  102. package/src/platform/macos/backend.ts +147 -0
  103. package/src/platform/macos/browser.ts +110 -0
  104. package/src/platform/macos/helper.ts +369 -0
  105. package/src/platform/macos/permissions.ts +146 -0
  106. package/src/platform/types.ts +229 -0
  107. package/src/platform/windows/backend.ts +142 -0
  108. package/src/platform/windows/helper.ts +140 -0
  109. package/src/root-selection.ts +25 -0
  110. package/src/runtime.ts +129 -0
  111. package/src/state.ts +146 -0
  112. package/src/view.ts +147 -0
@@ -0,0 +1,229 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { LookResponse } from "../outline.ts";
3
+ import type { PermissionStatus } from "../permissions.ts";
4
+
5
+ export type PlatformName = "macos" | "windows" | "linux";
6
+ export type NativeInputDelivery = "hid" | "pid";
7
+ export type ActOutcome = "worked" | "didnt" | "unknown";
8
+ /**
9
+ * Best-effort presentation hint for a root. The seam guarantees only the
10
+ * `window` vs transient distinction; specific transient kinds are display hints
11
+ * and must never drive behavior in shared code. Platforms that need precise
12
+ * distinctions internally should use native signals.
13
+ */
14
+ export type PlatformRootKind = "window" | "menu" | "sheet" | "popover" | "dialog";
15
+
16
+ export interface PlatformDiagnostics {
17
+ protocolVersion: number;
18
+ architectureVersion?: number;
19
+ invariants?: string[];
20
+ pid: number;
21
+ parentPid?: number;
22
+ parentAppName?: string;
23
+ parentBundleId?: string;
24
+ parentPath?: string;
25
+ executablePath?: string;
26
+ os?: string;
27
+ arch?: string;
28
+ accessibility?: boolean;
29
+ screenRecording?: boolean;
30
+ }
31
+
32
+ export interface PlatformReadyState {
33
+ permissionStatus?: PermissionStatus;
34
+ lastPermissionCheckAt: number;
35
+ helperDiagnostics?: PlatformDiagnostics;
36
+ }
37
+
38
+ export interface PlatformRootQuery {
39
+ pid?: number;
40
+ title?: string;
41
+ }
42
+
43
+ export interface PlatformApp {
44
+ appName: string;
45
+ bundleId?: string;
46
+ pid: number;
47
+ isFrontmost?: boolean;
48
+ }
49
+
50
+ export interface FramePoints {
51
+ x: number;
52
+ y: number;
53
+ w: number;
54
+ h: number;
55
+ }
56
+
57
+ export interface PlatformRoot {
58
+ kind: PlatformRootKind;
59
+ rootRef?: string;
60
+ windowRef?: string;
61
+ windowId?: number;
62
+ pid?: number;
63
+ appName?: string;
64
+ bundleId?: string;
65
+ title: string;
66
+ role?: string;
67
+ subrole?: string;
68
+ zOrder: number;
69
+ framePoints: FramePoints;
70
+ scaleFactor: number;
71
+ isOnscreen: boolean;
72
+ isFocused: boolean;
73
+ isMinimized: boolean;
74
+ /** Best-effort; platforms without a main-window concept may mirror `isFocused`. */
75
+ isMain: boolean;
76
+ /** Platform-reported modality fact, including platform-specific modal/dialog/sheet signals. */
77
+ isModal: boolean;
78
+ metadata?: Record<string, unknown>;
79
+ }
80
+
81
+ export interface PlatformFrontmostResult {
82
+ appName: string;
83
+ bundleId?: string;
84
+ pid: number;
85
+ windowTitle?: string;
86
+ windowId?: number;
87
+ rootRef?: string;
88
+ }
89
+
90
+ export interface PlatformFocusWindowResult {
91
+ focused: boolean;
92
+ alreadyFocused?: boolean;
93
+ reason?: string;
94
+ }
95
+
96
+ export interface HelperActPerformed {
97
+ grounding?: "description" | "coordinates" | "keyboard-events";
98
+ /** `ax` means the platform accessibility API (AX on macOS, UIA on Windows). */
99
+ delivery?: "ax" | NativeInputDelivery;
100
+ refound?: boolean;
101
+ /** Free-form diagnostic naming the platform's delta mechanism. */
102
+ deltaSource?: string;
103
+ selectionGrounding?: "ax" | "keyboard";
104
+ transaction?: boolean;
105
+ actionCount?: number;
106
+ activated?: boolean;
107
+ raised?: boolean;
108
+ focused?: boolean;
109
+ }
110
+
111
+ export interface PlatformRootDelta {
112
+ change: "appeared" | "closed" | "focused";
113
+ kind: string;
114
+ ref?: string;
115
+ title?: string;
116
+ pid: number;
117
+ isModal?: boolean;
118
+ metadata?: Record<string, unknown>;
119
+ }
120
+
121
+ export interface HelperActResult {
122
+ outcome: ActOutcome;
123
+ performed?: HelperActPerformed;
124
+ evidence?: Record<string, unknown>;
125
+ error?: { code?: string; message?: string; whatIsThere?: unknown };
126
+ rootDelta?: PlatformRootDelta[];
127
+ steps?: HelperActResult[];
128
+ stoppedAt?: number;
129
+ }
130
+
131
+ /**
132
+ * Native root identity. `windowId` is a CoreGraphics-style id and is omitted (never `0`) when the
133
+ * root has no capturable window. `rootRef` and `windowRef` are two spellings of the same native
134
+ * root reference; backends normalize them with `normalizeTarget`.
135
+ */
136
+ export interface PlatformTarget {
137
+ pid?: number;
138
+ windowId?: number;
139
+ rootRef?: string;
140
+ windowRef?: string;
141
+ }
142
+
143
+ export interface PlatformObserveRequest {
144
+ target: PlatformTarget;
145
+ /** Existing immutable look whose untouched refs/coordinate geometry survive a scoped refresh. */
146
+ baseLookId?: string;
147
+ readText: "auto" | "always" | "never";
148
+ scopeRef?: string;
149
+ maxDimension?: number;
150
+ includeImage?: boolean;
151
+ }
152
+
153
+ export type PlatformActTarget = { ref: string } | { x: number; y: number } | { focus: PlatformPoint };
154
+ type PlatformDeliveryPolicy = "ax_only" | "background" | "default" | "foreground";
155
+ type PlatformMouseButton = "left" | "right" | "middle";
156
+ type PlatformActDeliveryParam = { delivery?: NativeInputDelivery };
157
+ export type PlatformPoint = { x: number; y: number };
158
+
159
+ export interface PlatformActRequestBase {
160
+ lookId: string;
161
+ pid?: number;
162
+ target: PlatformActTarget;
163
+ policy: PlatformDeliveryPolicy;
164
+ }
165
+
166
+ export type PlatformActRequest = PlatformActRequestBase & (
167
+ | { action: "press" | "click"; params: { button?: PlatformMouseButton; clickCount?: number } & PlatformActDeliveryParam }
168
+ | { action: "setText"; params: { text: string } & PlatformActDeliveryParam }
169
+ | { action: "typeText"; params: { text: string } & PlatformActDeliveryParam }
170
+ | { action: "keypress"; params: { keys: string[] } & PlatformActDeliveryParam }
171
+ | { action: "scroll"; params: { scrollX: number; scrollY: number } & PlatformActDeliveryParam }
172
+ | { action: "drag"; params: { path: PlatformPoint[] } & PlatformActDeliveryParam }
173
+ | { action: "moveMouse"; params: PlatformActDeliveryParam }
174
+ );
175
+
176
+ export interface PlatformReadTextRequest {
177
+ /** Observation that owns the element ref. Native backends must not resolve across observations. */
178
+ lookId: string;
179
+ elementRef: string;
180
+ offset: number;
181
+ limit: number;
182
+ }
183
+
184
+ export interface PlatformReadTextResponse {
185
+ text: string;
186
+ offset: number;
187
+ limit: number;
188
+ totalChars: number;
189
+ hasMore: boolean;
190
+ }
191
+
192
+ export interface PlatformWaitForRequest extends PlatformTarget {
193
+ lookId?: string;
194
+ text?: string;
195
+ role?: string;
196
+ value?: string;
197
+ scopeRef?: string;
198
+ scopeExact?: boolean;
199
+ gone: boolean;
200
+ timeoutMs: number;
201
+ }
202
+
203
+ export interface PlatformWaitForResponse {
204
+ found: boolean;
205
+ gone?: boolean;
206
+ timedOut?: boolean;
207
+ nodeCount?: number;
208
+ }
209
+
210
+ export interface ComputerUsePlatformBackend {
211
+ name: PlatformName;
212
+ /** Release process-local resources when the Pi session is torn down. */
213
+ shutdown?(): void | Promise<void>;
214
+ setActivity?(active: boolean): void | Promise<void>;
215
+ ensureReady(ctx: ExtensionContext, state: PlatformReadyState, signal?: AbortSignal): Promise<PlatformReadyState>;
216
+ listApps(signal?: AbortSignal): Promise<PlatformApp[]>;
217
+ listRoots(query: PlatformRootQuery, signal?: AbortSignal): Promise<PlatformRoot[]>;
218
+ getFrontmost(signal?: AbortSignal): Promise<PlatformFrontmostResult>;
219
+ focusWindow(target: PlatformTarget, signal?: AbortSignal): Promise<PlatformFocusWindowResult>;
220
+ observe(request: PlatformObserveRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<LookResponse>;
221
+ act(request: PlatformActRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<HelperActResult>;
222
+ /** Execute one-resource actions with one root baseline and one final settle. */
223
+ actBatch?(requests: PlatformActRequest[], options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<HelperActResult>;
224
+ readText(args: PlatformReadTextRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<PlatformReadTextResponse>;
225
+ waitFor(args: PlatformWaitForRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<PlatformWaitForResponse>;
226
+ isBrowserApp(appName: string, bundleId?: string): boolean;
227
+ isChromeFamilyApp(appName: string, bundleId?: string): boolean;
228
+ openBrowserLocation(target: { appName: string; bundleId?: string }, url: string, signal?: AbortSignal): Promise<boolean>;
229
+ }
@@ -0,0 +1,142 @@
1
+ import { parseLookResponse, type LookResponse } from "../../outline.ts";
2
+ import { toBoolean, toFiniteNumber, toOptionalString } from "../coerce.ts";
3
+ import type { ComputerUsePlatformBackend, FramePoints, HelperActResult, PlatformActRequest, PlatformApp, PlatformFocusWindowResult, PlatformFrontmostResult, PlatformObserveRequest, PlatformReadTextRequest, PlatformReadTextResponse, PlatformReadyState, PlatformRoot, PlatformRootKind, PlatformRootQuery, PlatformTarget, PlatformWaitForRequest, PlatformWaitForResponse } from "../types.ts";
4
+ import { WINDOWS_HELPER_PROTOCOL_VERSION, windowsHelper } from "./helper.ts";
5
+ import { assertPlatformArchitecture } from "../architecture.ts";
6
+
7
+ function normalizedProcessName(appName: string): string {
8
+ return appName.toLowerCase().replace(/\.exe$/i, "");
9
+ }
10
+
11
+ function classifyBrowser(appName: string): false | "chrome" | "edge" | "brave" | "firefox" | "vivaldi" | "opera" {
12
+ switch (normalizedProcessName(appName)) {
13
+ case "chrome":
14
+ case "chromium":
15
+ return "chrome";
16
+ case "msedge":
17
+ case "edge":
18
+ return "edge";
19
+ case "brave":
20
+ case "brave-browser":
21
+ return "brave";
22
+ case "firefox":
23
+ return "firefox";
24
+ case "vivaldi":
25
+ return "vivaldi";
26
+ case "opera":
27
+ case "opera_gx":
28
+ return "opera";
29
+ default:
30
+ return false;
31
+ }
32
+ }
33
+
34
+ function parseFramePoints(raw: unknown): FramePoints {
35
+ const frame = (raw as any)?.framePoints ?? (raw as any)?.bounds ?? {};
36
+ return {
37
+ x: toFiniteNumber(frame.x, 0),
38
+ y: toFiniteNumber(frame.y, 0),
39
+ w: Math.max(1, toFiniteNumber(frame.w ?? frame.width, 1)),
40
+ h: Math.max(1, toFiniteNumber(frame.h ?? frame.height, 1)),
41
+ };
42
+ }
43
+
44
+ function parseRootKind(raw: unknown): PlatformRootKind {
45
+ return raw === "menu" || raw === "dialog" || raw === "popover" || raw === "window" ? raw : "window";
46
+ }
47
+
48
+ function parseRoots(result: unknown): PlatformRoot[] {
49
+ const array = Array.isArray(result) ? result : (result as any)?.roots;
50
+ if (!Array.isArray(array)) return [];
51
+ return array.map((raw: any, index): PlatformRoot => {
52
+ return {
53
+ kind: parseRootKind(raw?.kind),
54
+ rootRef: toOptionalString(raw?.rootRef ?? raw?.windowRef ?? raw?.ref),
55
+ windowRef: toOptionalString(raw?.windowRef ?? raw?.rootRef ?? raw?.ref),
56
+ windowId: Number.isFinite(raw?.windowId) ? Math.trunc(raw.windowId) : undefined,
57
+ pid: Number.isFinite(raw?.pid) ? Math.trunc(raw.pid) : undefined,
58
+ appName: toOptionalString(raw?.appName ?? raw?.processName),
59
+ bundleId: toOptionalString(raw?.bundleId),
60
+ title: toOptionalString(raw?.title) ?? "",
61
+ role: toOptionalString(raw?.role),
62
+ subrole: toOptionalString(raw?.subrole),
63
+ zOrder: Math.trunc(toFiniteNumber(raw?.zOrder, index)),
64
+ framePoints: parseFramePoints(raw),
65
+ scaleFactor: Math.max(1, toFiniteNumber(raw?.scaleFactor, 1)),
66
+ isOnscreen: raw?.isOnscreen === undefined ? true : toBoolean(raw?.isOnscreen),
67
+ isFocused: toBoolean(raw?.isFocused),
68
+ isMinimized: toBoolean(raw?.isMinimized),
69
+ isMain: toBoolean(raw?.isMain ?? raw?.isFocused),
70
+ isModal: toBoolean(raw?.isModal),
71
+ metadata: raw?.metadata,
72
+ };
73
+ });
74
+ }
75
+
76
+ function appsFromRoots(roots: PlatformRoot[]): PlatformApp[] {
77
+ const seen = new Set<number>();
78
+ return roots.flatMap((root) => {
79
+ if (!root.pid || seen.has(root.pid)) return [];
80
+ seen.add(root.pid);
81
+ return [{ appName: root.appName ?? "Unknown", bundleId: root.bundleId, pid: root.pid, isFrontmost: root.isFocused }];
82
+ });
83
+ }
84
+
85
+ function helperAction(request: PlatformActRequest): Record<string, unknown> {
86
+ if (!("focus" in request.target)) return { ...request };
87
+ return { ...request, target: request.target.focus, params: { ...request.params, preserveFocus: true } };
88
+ }
89
+
90
+ async function ensureReady(_ctx: unknown, state: PlatformReadyState, signal?: AbortSignal): Promise<PlatformReadyState> {
91
+ await windowsHelper.ensureInstalled(signal);
92
+ const diagnostics = await windowsHelper.command<any>("diagnostics", {}, { signal, timeoutMs: 5_000 });
93
+ if (diagnostics?.protocolVersion !== WINDOWS_HELPER_PROTOCOL_VERSION) {
94
+ throw new Error(`Windows helper protocol mismatch: expected ${WINDOWS_HELPER_PROTOCOL_VERSION}, got ${diagnostics?.protocolVersion ?? "unknown"}. Restart Pi to use the installed helper.`);
95
+ }
96
+ assertPlatformArchitecture("Windows", diagnostics);
97
+ return { ...state, lastPermissionCheckAt: Date.now(), helperDiagnostics: diagnostics };
98
+ }
99
+
100
+ export const windowsBackend: ComputerUsePlatformBackend = {
101
+ name: "windows",
102
+ shutdown(): void { windowsHelper.dispose(); },
103
+ ensureReady,
104
+ async listApps(signal?: AbortSignal): Promise<PlatformApp[]> {
105
+ return appsFromRoots(parseRoots(await windowsHelper.command("listRoots", {}, { signal })));
106
+ },
107
+ async listRoots(query: PlatformRootQuery, signal?: AbortSignal): Promise<PlatformRoot[]> {
108
+ const roots = parseRoots(await windowsHelper.command("listRoots", Number.isFinite(query.pid) ? { pid: Math.trunc(query.pid!) } : {}, { signal }));
109
+ const title = query.title?.trim().toLowerCase();
110
+ return title ? roots.filter((root) => root.title.trim().toLowerCase().includes(title)) : roots;
111
+ },
112
+ async getFrontmost(signal?: AbortSignal): Promise<PlatformFrontmostResult> {
113
+ const roots = parseRoots(await windowsHelper.command("listRoots", {}, { signal }));
114
+ const focused = roots.find((root) => root.isFocused) ?? roots[0];
115
+ if (!focused?.pid) throw new Error("No frontmost window was available.");
116
+ return { appName: focused.appName ?? "Unknown", bundleId: focused.bundleId, pid: focused.pid, windowTitle: focused.title, windowId: focused.windowId, rootRef: focused.rootRef };
117
+ },
118
+ async focusWindow(target: PlatformTarget, signal?: AbortSignal): Promise<PlatformFocusWindowResult> {
119
+ return await windowsHelper.command<PlatformFocusWindowResult>("focusWindow", { ...target }, { signal });
120
+ },
121
+ async observe(request: PlatformObserveRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<LookResponse> {
122
+ return parseLookResponse(await windowsHelper.command("look", { ...request.target, baseLookId: request.baseLookId, maxDimension: request.maxDimension, readText: request.readText, scopeRef: request.scopeRef, includeImage: request.includeImage }, options));
123
+ },
124
+ async act(request: PlatformActRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<HelperActResult> {
125
+ return await windowsHelper.command<HelperActResult>("act", helperAction(request), options);
126
+ },
127
+ async actBatch(requests: PlatformActRequest[], options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<HelperActResult> {
128
+ return await windowsHelper.command<HelperActResult>("actBatch", { actions: requests.map(helperAction) }, options);
129
+ },
130
+ async readText(args: PlatformReadTextRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<PlatformReadTextResponse> {
131
+ return await windowsHelper.command("uiaReadText", { ...args }, options);
132
+ },
133
+ async waitFor(args: PlatformWaitForRequest, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<PlatformWaitForResponse> {
134
+ return await windowsHelper.command("uiaWaitFor", { ...args }, options);
135
+ },
136
+ isBrowserApp(appName: string): boolean { return classifyBrowser(appName) !== false; },
137
+ isChromeFamilyApp(appName: string): boolean { return classifyBrowser(appName) === "chrome" || classifyBrowser(appName) === "edge" || classifyBrowser(appName) === "brave"; },
138
+ async openBrowserLocation(target: { appName: string; bundleId?: string }, url: string, signal?: AbortSignal): Promise<boolean> {
139
+ await windowsHelper.command("openBrowserLocation", { ...target, url }, { signal, timeoutMs: 10_000 });
140
+ return true;
141
+ },
142
+ };
@@ -0,0 +1,140 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { constants as fsConstants } from "node:fs";
4
+ import { access } from "node:fs/promises";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
10
+ const SETUP_HELPER_SCRIPT = path.join(PACKAGE_ROOT, "scripts", "setup-helper.mjs");
11
+ const HELPER_SETUP_TIMEOUT_MS = 60_000;
12
+ const COMMAND_TIMEOUT_MS = 15_000;
13
+
14
+ export const WINDOWS_HELPER_PROTOCOL_VERSION = 4;
15
+ export const WINDOWS_HELPER_PATH = process.env.PI_COMPUTER_USE_WINDOWS_HELPER_PATH || path.join(os.homedir(), ".pi", "agent", "helpers", "pi-computer-use", "windows-bridge.exe");
16
+
17
+ interface Pending<T> {
18
+ resolve(value: T): void;
19
+ reject(error: Error): void;
20
+ timer: NodeJS.Timeout;
21
+ }
22
+
23
+ async function isExecutable(filePath: string): Promise<boolean> {
24
+ try { await access(filePath, fsConstants.X_OK); return true; } catch { return false; }
25
+ }
26
+
27
+ async function runProcess(command: string, args: string[], timeoutMs: number, signal?: AbortSignal, env?: NodeJS.ProcessEnv): Promise<void> {
28
+ if (signal?.aborted) throw new Error("Operation aborted.");
29
+ await new Promise<void>((resolve, reject) => {
30
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], env });
31
+ let stdout = "";
32
+ let stderr = "";
33
+ const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", onAbort); };
34
+ const timer = setTimeout(() => { child.kill("SIGTERM"); cleanup(); reject(new Error(`Command timed out after ${timeoutMs}ms: ${command} ${args.join(" ")}`)); }, timeoutMs);
35
+ const onAbort = () => { child.kill("SIGTERM"); cleanup(); reject(new Error("Operation aborted.")); };
36
+ child.stdout.on("data", (chunk) => { stdout += String(chunk); });
37
+ child.stderr.on("data", (chunk) => { stderr += String(chunk); });
38
+ child.on("error", (error) => { cleanup(); reject(error); });
39
+ child.on("close", (code) => {
40
+ cleanup();
41
+ if (code === 0) return resolve();
42
+ const output = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n");
43
+ reject(new Error(`Command failed (${code}): ${command} ${args.join(" ")}\n${output}`.trim()));
44
+ });
45
+ signal?.addEventListener("abort", onAbort, { once: true });
46
+ });
47
+ }
48
+
49
+ export class WindowsHelperClient {
50
+ private installChecked = false;
51
+ private child?: ChildProcessWithoutNullStreams;
52
+ private buffer = "";
53
+ private pending = new Map<string, Pending<unknown>>();
54
+
55
+ dispose(): void {
56
+ const error = new Error("Windows helper closed because the Pi session ended.");
57
+ for (const pending of this.pending.values()) {
58
+ clearTimeout(pending.timer);
59
+ pending.reject(error);
60
+ }
61
+ this.pending.clear();
62
+ this.buffer = "";
63
+
64
+ const child = this.child;
65
+ this.child = undefined;
66
+ if (!child) return;
67
+ child.stdin.destroy();
68
+ child.stdout.destroy();
69
+ child.stderr.destroy();
70
+ child.kill("SIGTERM");
71
+ child.unref();
72
+ }
73
+
74
+ async ensureInstalled(signal?: AbortSignal): Promise<void> {
75
+ if ((await isExecutable(WINDOWS_HELPER_PATH)) && this.installChecked) return;
76
+ // Re-enter Electron and Bun standalone hosts as their JavaScript runtimes.
77
+ await runProcess(process.execPath, [SETUP_HELPER_SCRIPT, "--platform", "windows", "--runtime"], HELPER_SETUP_TIMEOUT_MS, signal, { ...process.env, ELECTRON_RUN_AS_NODE: "1", BUN_BE_BUN: "1" });
78
+ this.installChecked = true;
79
+ if (!(await isExecutable(WINDOWS_HELPER_PATH))) throw new Error(`Failed to install Windows helper at ${WINDOWS_HELPER_PATH}.`);
80
+ }
81
+
82
+ private async process(signal?: AbortSignal): Promise<ChildProcessWithoutNullStreams> {
83
+ await this.ensureInstalled(signal);
84
+ if (this.child && this.child.exitCode === null && !this.child.killed) return this.child;
85
+ const child = spawn(WINDOWS_HELPER_PATH, [], { stdio: ["pipe", "pipe", "pipe"] });
86
+ child.stdout.setEncoding("utf8");
87
+ child.stderr.setEncoding("utf8");
88
+ child.stdin.setDefaultEncoding("utf8");
89
+ child.stdout.on("data", (chunk: string) => this.onStdout(chunk));
90
+ child.on("exit", () => { if (this.child === child) this.child = undefined; });
91
+ child.on("error", () => { if (this.child === child) this.child = undefined; });
92
+ this.child = child;
93
+ this.buffer = "";
94
+ return child;
95
+ }
96
+
97
+ private onStdout(chunk: string): void {
98
+ this.buffer += chunk;
99
+ for (;;) {
100
+ const newline = this.buffer.indexOf("\n");
101
+ if (newline < 0) return;
102
+ const line = this.buffer.slice(0, newline).trim();
103
+ this.buffer = this.buffer.slice(newline + 1);
104
+ if (!line) continue;
105
+ let parsed: any;
106
+ try { parsed = JSON.parse(line); } catch { continue; }
107
+ const pending = this.pending.get(parsed.id);
108
+ if (!pending) continue;
109
+ this.pending.delete(parsed.id);
110
+ clearTimeout(pending.timer);
111
+ if (parsed.protocolVersion !== WINDOWS_HELPER_PROTOCOL_VERSION) {
112
+ pending.reject(new Error(`Windows helper protocol mismatch: expected ${WINDOWS_HELPER_PROTOCOL_VERSION}, got ${parsed.protocolVersion ?? "unknown"}. Restart Pi to use the installed helper.`));
113
+ } else if (parsed.ok === true) {
114
+ pending.resolve(parsed.result);
115
+ } else {
116
+ const error = new Error(parsed.error?.message ?? "Windows helper command failed.") as Error & { code?: string };
117
+ error.code = parsed.error?.code;
118
+ pending.reject(error);
119
+ }
120
+ }
121
+ }
122
+
123
+ async command<T>(cmd: string, args: Record<string, unknown> = {}, options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<T> {
124
+ const child = await this.process(options?.signal);
125
+ const id = randomUUID();
126
+ const timeoutMs = options?.timeoutMs ?? COMMAND_TIMEOUT_MS;
127
+ return await new Promise<T>((resolve, reject) => {
128
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Helper command '${cmd}' timed out after ${timeoutMs}ms.`)); }, timeoutMs);
129
+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });
130
+ child.stdin.write(`${JSON.stringify({ protocolVersion: WINDOWS_HELPER_PROTOCOL_VERSION, id, cmd, args })}\n`, (error) => {
131
+ if (!error) return;
132
+ this.pending.delete(id);
133
+ clearTimeout(timer);
134
+ reject(error);
135
+ });
136
+ });
137
+ }
138
+ }
139
+
140
+ export const windowsHelper = new WindowsHelperClient();
@@ -0,0 +1,25 @@
1
+ import type { PlatformRoot } from "./platform/types.ts";
2
+
3
+ type RankedRoot = Pick<PlatformRoot,
4
+ "windowId" | "windowRef" | "isModal" | "isFocused" | "isMain" | "isMinimized" | "isOnscreen" | "zOrder" | "title"
5
+ >;
6
+
7
+ export function scoreWindow(window: RankedRoot): number {
8
+ let score = 0;
9
+ if (window.isModal) score += 180;
10
+ if (window.isFocused) score += 100;
11
+ if (window.isMain) score += 80;
12
+ if (!window.isMinimized) score += 40;
13
+ if (window.isOnscreen) score += 20;
14
+ if (window.windowId && window.windowId > 0) score += 10;
15
+ if (window.title.trim().length > 0) score += 2;
16
+ return score;
17
+ }
18
+
19
+ export function shouldPreferForegroundModalWindow(current: RankedRoot, candidate: RankedRoot): boolean {
20
+ if (candidate.windowId === current.windowId && candidate.windowRef === current.windowRef) return false;
21
+ if (!candidate.isOnscreen || candidate.isMinimized || !candidate.isModal) return false;
22
+ // AXDialog can describe a background main window, so modality alone is insufficient.
23
+ const candidateIsInFront = candidate.isFocused || candidate.zOrder < current.zOrder;
24
+ return candidateIsInFront && scoreWindow(candidate) >= scoreWindow(current);
25
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export interface StoredState<T> {
4
+ stateId: string;
5
+ resourceKey: string;
6
+ epoch: number;
7
+ value: T;
8
+ }
9
+
10
+ export class StaleResourceStateError extends Error {
11
+ constructor(readonly resourceKey: string, readonly expectedEpoch: number, readonly actualEpoch: number) {
12
+ super(`State is stale for ${resourceKey}: expected epoch ${expectedEpoch}, current epoch ${actualEpoch}.`);
13
+ this.name = "StaleResourceStateError";
14
+ }
15
+ }
16
+
17
+ /** Bounded insertion-ordered store for immutable agent-facing observations. */
18
+ export class StateStore<T> {
19
+ private readonly records = new Map<string, StoredState<T>>();
20
+
21
+ constructor(private readonly limit = 128) {}
22
+
23
+ create(resourceKey: string, epoch: number, value: T): StoredState<T> {
24
+ const record = { stateId: randomUUID(), resourceKey, epoch, value };
25
+ this.set(record);
26
+ return record;
27
+ }
28
+
29
+ set(record: StoredState<T>): void {
30
+ this.records.delete(record.stateId);
31
+ this.records.set(record.stateId, record);
32
+ while (this.records.size > this.limit) {
33
+ const oldest = this.records.keys().next().value as string | undefined;
34
+ if (!oldest) break;
35
+ this.records.delete(oldest);
36
+ }
37
+ }
38
+
39
+ get(stateId: string): StoredState<T> | undefined {
40
+ return this.records.get(stateId);
41
+ }
42
+
43
+ clear(): void {
44
+ this.records.clear();
45
+ }
46
+
47
+ get size(): number {
48
+ return this.records.size;
49
+ }
50
+ }
51
+
52
+ interface ResourceRecord {
53
+ epoch: number;
54
+ tail: Promise<void>;
55
+ }
56
+
57
+ /**
58
+ * Orders live operations per physical resource while allowing unrelated
59
+ * resources to overlap. Cached state queries bypass this scheduler entirely.
60
+ */
61
+ export class ResourceScheduler {
62
+ private readonly resources = new Map<string, ResourceRecord>();
63
+ private closed = false;
64
+
65
+ epoch(resourceKey: string): number {
66
+ return this.resource(resourceKey).epoch;
67
+ }
68
+
69
+ restoreEpoch(resourceKey: string, epoch: number): void {
70
+ const record = this.resource(resourceKey);
71
+ record.epoch = Math.max(record.epoch, Math.max(0, Math.trunc(epoch)));
72
+ }
73
+
74
+ async read<T>(resourceKey: string, work: (epoch: number) => Promise<T>): Promise<{ value: T; epoch: number }> {
75
+ return await this.enqueue(resourceKey, async (record) => ({ value: await work(record.epoch), epoch: record.epoch }));
76
+ }
77
+
78
+ async readAt<T>(resourceKey: string, expectedEpoch: number, work: (epoch: number) => Promise<T>): Promise<{ value: T; epoch: number }> {
79
+ return await this.enqueue(resourceKey, async (record) => {
80
+ if (record.epoch !== expectedEpoch) throw new StaleResourceStateError(resourceKey, expectedEpoch, record.epoch);
81
+ return { value: await work(record.epoch), epoch: record.epoch };
82
+ });
83
+ }
84
+
85
+ async write<T>(resourceKey: string, baseEpoch: number, work: (nextEpoch: number) => Promise<T>): Promise<{ value: T; epoch: number }> {
86
+ return await this.enqueue(resourceKey, async (record) => {
87
+ if (record.epoch !== baseEpoch) throw new StaleResourceStateError(resourceKey, baseEpoch, record.epoch);
88
+ const nextEpoch = record.epoch + 1;
89
+ // Invalidate the base state before dispatch. If native execution becomes
90
+ // uncertain or throws after a partial effect, later writes still fail safe.
91
+ record.epoch = nextEpoch;
92
+ return { value: await work(nextEpoch), epoch: nextEpoch };
93
+ });
94
+ }
95
+
96
+ async drain(): Promise<void> {
97
+ await Promise.all([...this.resources.values()].map((record) => record.tail.catch(() => undefined)));
98
+ }
99
+
100
+ async close(): Promise<void> {
101
+ this.closed = true;
102
+ await this.drain();
103
+ this.resources.clear();
104
+ }
105
+
106
+ private resource(resourceKey: string): ResourceRecord {
107
+ let record = this.resources.get(resourceKey);
108
+ if (!record) {
109
+ record = { epoch: 0, tail: Promise.resolve() };
110
+ this.resources.set(resourceKey, record);
111
+ }
112
+ return record;
113
+ }
114
+
115
+ private async enqueue<T>(resourceKey: string, work: (record: ResourceRecord) => Promise<T>): Promise<T> {
116
+ if (this.closed) throw new Error("Computer-use session is shutting down.");
117
+ const record = this.resource(resourceKey);
118
+ const previous = record.tail;
119
+ let release!: () => void;
120
+ const next = new Promise<void>((resolve) => { release = resolve; });
121
+ record.tail = previous.catch(() => undefined).then(() => next);
122
+ await previous.catch(() => undefined);
123
+ try {
124
+ return await work(record);
125
+ } finally {
126
+ release();
127
+ }
128
+ }
129
+ }