@roam-agent/roam-computer-use 0.0.0-stage → 0.5.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 (111) 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 +104 -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/setup-helper.mjs +635 -0
  85. package/src/actions.ts +130 -0
  86. package/src/bridge.ts +2594 -0
  87. package/src/cdp.ts +658 -0
  88. package/src/config.ts +226 -0
  89. package/src/contract.ts +107 -0
  90. package/src/extension/index.ts +9 -0
  91. package/src/find-params.ts +21 -0
  92. package/src/note.ts +195 -0
  93. package/src/outline.ts +702 -0
  94. package/src/output.ts +134 -0
  95. package/src/permissions.ts +111 -0
  96. package/src/platform/architecture.ts +23 -0
  97. package/src/platform/coerce.ts +16 -0
  98. package/src/platform/index.ts +61 -0
  99. package/src/platform/linux/backend.ts +186 -0
  100. package/src/platform/linux/helper.ts +238 -0
  101. package/src/platform/macos/backend.ts +147 -0
  102. package/src/platform/macos/browser.ts +110 -0
  103. package/src/platform/macos/helper.ts +369 -0
  104. package/src/platform/macos/permissions.ts +146 -0
  105. package/src/platform/types.ts +229 -0
  106. package/src/platform/windows/backend.ts +142 -0
  107. package/src/platform/windows/helper.ts +140 -0
  108. package/src/root-selection.ts +25 -0
  109. package/src/runtime.ts +129 -0
  110. package/src/state.ts +146 -0
  111. package/src/view.ts +147 -0
package/src/config.ts ADDED
@@ -0,0 +1,226 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+
5
+ export interface ComputerUseConfig {
6
+ browser_use: boolean;
7
+ headless: boolean;
8
+ cursor_overlay: boolean;
9
+ activity_glow: boolean;
10
+ managed_browser: "helium" | "chrome";
11
+ }
12
+
13
+ export interface ComputerUseConfigSource {
14
+ path: string;
15
+ exists: boolean;
16
+ values?: Partial<ComputerUseConfig>;
17
+ error?: string;
18
+ }
19
+
20
+ export interface LoadedComputerUseConfig {
21
+ config: ComputerUseConfig;
22
+ sources: ComputerUseConfigSource[];
23
+ env: Partial<ComputerUseConfig>;
24
+ }
25
+
26
+ const DEFAULT_CONFIG: ComputerUseConfig = {
27
+ browser_use: true,
28
+ headless: false,
29
+ cursor_overlay: true,
30
+ activity_glow: false,
31
+ managed_browser: "chrome",
32
+ };
33
+
34
+ let activeConfig: ComputerUseConfig = { ...DEFAULT_CONFIG };
35
+ let activeLoadedConfig: LoadedComputerUseConfig = { config: activeConfig, sources: [], env: {} };
36
+
37
+ function parseBoolean(value: unknown): boolean | undefined {
38
+ if (typeof value === "boolean") return value;
39
+ if (typeof value === "number") return value === 1 ? true : value === 0 ? false : undefined;
40
+ if (typeof value !== "string") return undefined;
41
+ const normalized = value.trim().toLowerCase();
42
+ if (["1", "true", "yes", "on", "enabled"].includes(normalized)) return true;
43
+ if (["0", "false", "no", "off", "disabled"].includes(normalized)) return false;
44
+ return undefined;
45
+ }
46
+
47
+ function normalizePartial(raw: unknown): Partial<ComputerUseConfig> {
48
+ if (!raw || typeof raw !== "object") return {};
49
+ const source = (raw as any).computer_use && typeof (raw as any).computer_use === "object" ? (raw as any).computer_use : raw;
50
+ const out: Partial<ComputerUseConfig> = {};
51
+ const browserUse = parseBoolean((source as any).browser_use);
52
+ const headless = parseBoolean((source as any).headless);
53
+ const cursorOverlay = parseBoolean((source as any).cursor_overlay);
54
+ const activityGlow = parseBoolean((source as any).activity_glow);
55
+ if (browserUse !== undefined) out.browser_use = browserUse;
56
+ if (headless !== undefined) out.headless = headless;
57
+ if (cursorOverlay !== undefined) out.cursor_overlay = cursorOverlay;
58
+ if (activityGlow !== undefined) out.activity_glow = activityGlow;
59
+ const managedBrowser = (source as any).managed_browser;
60
+ if (managedBrowser === "helium" || managedBrowser === "chrome") out.managed_browser = managedBrowser;
61
+ return out;
62
+ }
63
+
64
+ function readConfigFile(filePath: string): ComputerUseConfigSource {
65
+ if (!existsSync(filePath)) return { path: filePath, exists: false };
66
+ try {
67
+ const parsed = JSON.parse(readFileSync(filePath, "utf-8"));
68
+ return { path: filePath, exists: true, values: normalizePartial(parsed) };
69
+ } catch (error) {
70
+ return { path: filePath, exists: true, error: error instanceof Error ? error.message : String(error) };
71
+ }
72
+ }
73
+
74
+ function readEnv(): Partial<ComputerUseConfig> {
75
+ const out: Partial<ComputerUseConfig> = {};
76
+ const browserUse = parseBoolean(process.env.PI_COMPUTER_USE_BROWSER_USE);
77
+ const headless = parseBoolean(process.env.PI_COMPUTER_USE_HEADLESS);
78
+ const cursorOverlay = parseBoolean(process.env.PI_COMPUTER_USE_CURSOR_OVERLAY);
79
+ const activityGlow = parseBoolean(process.env.PI_COMPUTER_USE_ACTIVITY_GLOW);
80
+ if (browserUse !== undefined) out.browser_use = browserUse;
81
+ if (headless !== undefined) out.headless = headless;
82
+ if (cursorOverlay !== undefined) out.cursor_overlay = cursorOverlay;
83
+ if (activityGlow !== undefined) out.activity_glow = activityGlow;
84
+ const managedBrowser = process.env.PI_COMPUTER_USE_MANAGED_BROWSER;
85
+ if (managedBrowser === "helium" || managedBrowser === "chrome") out.managed_browser = managedBrowser;
86
+ return out;
87
+ }
88
+
89
+ export function loadComputerUseConfig(cwd: string): LoadedComputerUseConfig {
90
+ const sources = [
91
+ readConfigFile(path.join(getAgentDir(), "extensions", "pi-computer-use.json")),
92
+ readConfigFile(path.join(cwd, ".pi", "computer-use.json")),
93
+ ];
94
+ const env = readEnv();
95
+ const config = { ...DEFAULT_CONFIG };
96
+ for (const source of sources) {
97
+ if (source.values) Object.assign(config, source.values);
98
+ }
99
+ Object.assign(config, env);
100
+ activeConfig = config;
101
+ activeLoadedConfig = { config, sources, env };
102
+ return activeLoadedConfig;
103
+ }
104
+
105
+ export function getComputerUseConfig(): ComputerUseConfig {
106
+ return activeConfig;
107
+ }
108
+
109
+ export function getLoadedComputerUseConfig(): LoadedComputerUseConfig {
110
+ return activeLoadedConfig;
111
+ }
112
+
113
+ export function isHeadlessMode(): boolean {
114
+ return activeConfig.headless;
115
+ }
116
+
117
+ export function isBrowserUseEnabled(): boolean {
118
+ return activeConfig.browser_use;
119
+ }
120
+
121
+ /*
122
+ PI_DOCS_REFERENCE_BEGIN reference/configuration
123
+
124
+ Configuration controls browser access, strict accessibility execution, the macOS agent cursor, and the macOS activity glow.
125
+
126
+ ## Files
127
+
128
+ Global config:
129
+
130
+ ```text
131
+ ~/.pi/agent/extensions/pi-computer-use.json
132
+ ```
133
+
134
+ Project config:
135
+
136
+ ```text
137
+ .pi/computer-use.json
138
+ ```
139
+
140
+ Project config overrides global config. Environment variables override both.
141
+
142
+ Example:
143
+
144
+ ```json
145
+ {
146
+ "browser_use": true,
147
+ "managed_browser": "chrome",
148
+ "headless": false,
149
+ "cursor_overlay": true,
150
+ "activity_glow": true
151
+ }
152
+ ```
153
+
154
+ Run `/computer-use` in Pi to show the active config and its source.
155
+
156
+ ## Options
157
+
158
+ ### `browser_use`
159
+
160
+ Default: `{{config-default:browser_use}}`
161
+
162
+ When `false`, the extension refuses known browser windows. This is useful for projects that should not control browsers.
163
+
164
+ Known browser families include Safari, Chrome and Chromium-family browsers, Firefox, Arc, Brave, Edge, Vivaldi, and Helium.
165
+
166
+ ### `managed_browser`
167
+
168
+ Default: `{{config-default:managed_browser}}`
169
+
170
+ Selects `"helium"` or `"chrome"` for `launch_browser`. The debugging port is always allocated internally and isn't part of the model-facing contract.
171
+
172
+ ### `headless`
173
+
174
+ Default: `{{config-default:headless}}`
175
+
176
+ When `true`, actions must remain in the background. Raw pointer events, raw keyboard events, foreground focus fallback, cursor takeover, the agent cursor overlay, and the activity glow are blocked. On macOS, actions that would need synthesized pointer or keyboard input, including every `typeText` and `keypress`, fail with `foreground_required` ([macOS reference](./platforms/macos/actions.mdx#headless-policy)). When `false` (the default), Pi prefers verified semantic activation when it is credible, preserves the focus established by editable clicks for dependent keyboard input, and may retry keyboard input in the foreground when a background attempt conclusively produced no value change. Ambiguous pointer actions are never replayed blindly.
177
+
178
+ ### `cursor_overlay`
179
+
180
+ Default: `{{config-default:cursor_overlay}}`
181
+
182
+ When `true`, macOS pointer actions enqueue a click-through agent cursor animation to the native grounded point during non-headless background delivery. Foreground actions that control the physical cursor don't display the overlay. The overlay doesn't move the system pointer, accept input, or delay the action. Set it to `false` for invisible automation. `headless: true` always suppresses it regardless of this setting ([macOS reference](./platforms/macos/actions.mdx#agent-cursor-overlay)).
183
+
184
+ ### `activity_glow`
185
+
186
+ Default: `{{config-default:activity_glow}}`
187
+
188
+ When `true`, macOS displays a click-through pulsing border on every screen while a Pi agent is using one of the extension's tools. The border stays visible until the agent run ends. Each Pi session owns its indicator state, so one session cannot hide another session's active indicator. The helper removes a session's state if its connection closes unexpectedly.
189
+
190
+ The activity glow appears in user screen recordings, but never in the agent's own observations: helper captures always target a single window, so screen-edge overlays are not included. The glow is excluded from accessibility discovery. Other platforms ignore this setting, and `headless: true` always suppresses it ([macOS reference](./platforms/macos/implementation.mdx#activity-glow)).
191
+
192
+ ## Environment variables
193
+
194
+ ```bash
195
+ PI_COMPUTER_USE_BROWSER_USE=0
196
+ PI_COMPUTER_USE_BROWSER_USE=1
197
+ PI_COMPUTER_USE_MANAGED_BROWSER=helium
198
+ PI_COMPUTER_USE_MANAGED_BROWSER=chrome
199
+ PI_COMPUTER_USE_CHROME_EXECUTABLE=/absolute/path/to/chrome
200
+ PI_COMPUTER_USE_HELIUM_EXECUTABLE=/absolute/path/to/helium
201
+ PI_COMPUTER_USE_HEADLESS=0
202
+ PI_COMPUTER_USE_HEADLESS=1
203
+ PI_COMPUTER_USE_CURSOR_OVERLAY=0
204
+ PI_COMPUTER_USE_CURSOR_OVERLAY=1
205
+ PI_COMPUTER_USE_ACTIVITY_GLOW=0
206
+ PI_COMPUTER_USE_ACTIVITY_GLOW=1
207
+ PI_COMPUTER_USE_DELIVERY_POLICY=default
208
+ PI_COMPUTER_USE_DELIVERY_POLICY=foreground
209
+ PI_COMPUTER_USE_CDP_PORT=9222
210
+ ```
211
+
212
+ `PI_COMPUTER_USE_HEADLESS=1` prohibits foreground fallback. `PI_COMPUTER_USE_DELIVERY_POLICY` is a debugging input; normal policy belongs in configuration rather than individual model calls.
213
+
214
+ `launch_browser` searches common platform install locations and `PATH`. Use `PI_COMPUTER_USE_CHROME_EXECUTABLE` or `PI_COMPUTER_USE_HELIUM_EXECUTABLE` for an AppImage, portable install, or any non-standard location. An explicit override is authoritative and must name an executable file.
215
+
216
+ ## CDP browser support
217
+
218
+ `PI_COMPUTER_USE_CDP_PORT` enables Chrome DevTools Protocol support for Chromium-family browsers. Launch the browser with `--remote-debugging-port=<port>` and set this variable to the same port.
219
+
220
+ Use a dedicated, non-default profile with `--user-data-dir=<directory>`. Chrome 136 and later ignore remote-debugging switches for the default data directory as a security measure. `launch_browser` already creates a temporary, separate CDP profile and binds discovery to a randomly allocated loopback port.
221
+
222
+ When CDP is active, discovered pages participate in the same root and state system as desktop UI. `launch_browser` configures CDP automatically and returns an observed page state. `navigate_browser` and `evaluate_browser` accept only CDP browser-page states; native browser windows continue to use the normal desktop observe/act tools.
223
+
224
+ With the variable unset, CDP is inactive.
225
+ PI_DOCS_REFERENCE_END
226
+ */
@@ -0,0 +1,107 @@
1
+ export type RootSelector = string;
2
+ export type ImageMode = "auto" | "always" | "never";
3
+ export type MouseButtonName = "left" | "right" | "middle";
4
+ export type ObserveDetail = "compact" | "outline";
5
+
6
+ export interface ObserveTargetParams {
7
+ root?: RootSelector;
8
+ }
9
+
10
+ export interface FindParams {
11
+ text?: string;
12
+ app?: string;
13
+ bundleId?: string;
14
+ /** Exact positive process id. */
15
+ pid?: number;
16
+ /** Filters on the platform's best-effort presentation hint; only window vs transient is guaranteed. */
17
+ kind?: "window" | "menu" | "sheet" | "popover" | "dialog" | "browser_page";
18
+ }
19
+
20
+ export interface StateTargetParams {
21
+ stateId?: string;
22
+ }
23
+
24
+ export interface NavigateBrowserParams extends StateTargetParams {
25
+ url: string;
26
+ }
27
+
28
+ export interface LaunchBrowserParams {
29
+ url?: string;
30
+ }
31
+
32
+ export interface EvaluateBrowserParams {
33
+ stateId: string;
34
+ expression: string;
35
+ }
36
+
37
+ export interface ObserveParams extends ObserveTargetParams {
38
+ mode?: "semantic" | "visual" | "fused";
39
+ detail?: ObserveDetail;
40
+ /** Internal capture override; not part of the model-facing schema. */
41
+ readText?: "auto" | "always" | "never";
42
+ }
43
+
44
+ export interface SearchUiParams extends StateTargetParams {
45
+ text?: string;
46
+ role?: string;
47
+ capability?: string;
48
+ }
49
+
50
+ export interface ExpandUiParams extends StateTargetParams {
51
+ ref: string;
52
+ depth?: number;
53
+ }
54
+
55
+ export interface InspectUiParams extends StateTargetParams {
56
+ ref: string;
57
+ }
58
+
59
+ export interface UiCondition {
60
+ ref?: string;
61
+ scopeRef?: string;
62
+ text?: string;
63
+ role?: string;
64
+ value?: string;
65
+ until?: "present" | "absent";
66
+ timeoutMs?: number;
67
+ }
68
+
69
+ export interface UiAction {
70
+ action: "press" | "click" | "setText" | "typeText" | "keypress" | "scroll" | "drag" | "moveMouse";
71
+ ref?: string;
72
+ x?: number;
73
+ y?: number;
74
+ text?: string;
75
+ keys?: string[];
76
+ scrollX?: number;
77
+ scrollY?: number;
78
+ path?: Array<{ x: number; y: number } | [number, number]>;
79
+ button?: MouseButtonName;
80
+ clickCount?: number;
81
+ }
82
+
83
+ export interface ActParams extends StateTargetParams {
84
+ actions: UiAction[];
85
+ expect?: UiCondition;
86
+ }
87
+
88
+ export interface ReadTextParams extends StateTargetParams {
89
+ ref: string;
90
+ offset?: number;
91
+ }
92
+
93
+ export interface WaitForParams extends StateTargetParams, UiCondition {}
94
+
95
+ export const AGENT_TOOL_NAMES = new Set([
96
+ "find_roots",
97
+ "read_text",
98
+ "wait_for",
99
+ "observe_ui",
100
+ "search_ui",
101
+ "expand_ui",
102
+ "inspect_ui",
103
+ "act_ui",
104
+ "navigate_browser",
105
+ "evaluate_browser",
106
+ "launch_browser",
107
+ ]);
@@ -0,0 +1,9 @@
1
+ // Extension seam: all extended logic in this package should import the agent
2
+ // SDK through this module, never from `@earendil-works/pi-coding-agent` or
3
+ // `@roam-agent/roam-sdk` directly. Core code under `src/` (outside this folder)
4
+ // keeps importing `@earendil-works/pi-coding-agent` unchanged.
5
+ //
6
+ // The SDK is re-exported from `@roam-agent/roam-sdk`, which pins the underlying
7
+ // `@earendil-works/pi-coding-agent` version and is loadable under every module
8
+ // loader pi uses (jiti at runtime, tsx in check scripts, plain Node ESM).
9
+ export * from "@roam-agent/roam-sdk";
@@ -0,0 +1,21 @@
1
+ import type { FindParams } from "./contract.ts";
2
+
3
+ export function normalizeFindParams(params: FindParams | null | undefined): FindParams {
4
+ const rawParams = params ?? {};
5
+ if (rawParams.pid !== undefined && (!Number.isFinite(rawParams.pid) || !Number.isInteger(rawParams.pid) || rawParams.pid <= 0)) {
6
+ throw new Error("find_roots.pid must be a positive integer when provided.");
7
+ }
8
+ return {
9
+ text: trimOrUndefined(rawParams.text),
10
+ app: trimOrUndefined(rawParams.app),
11
+ bundleId: trimOrUndefined(rawParams.bundleId),
12
+ pid: rawParams.pid,
13
+ kind: rawParams.kind,
14
+ };
15
+ }
16
+
17
+ function trimOrUndefined(value: string | undefined): string | undefined {
18
+ if (typeof value !== "string") return undefined;
19
+ const trimmed = value.trim();
20
+ return trimmed.length > 0 ? trimmed : undefined;
21
+ }
package/src/note.ts ADDED
@@ -0,0 +1,195 @@
1
+ import { nodeByRef, outlineNodeLabel, type Outline, type OutlineNode } from "./outline.ts";
2
+
3
+ interface NoteRegion {
4
+ key: string;
5
+ label: string;
6
+ status: "seen" | "changed" | "never-looked";
7
+ detail?: string;
8
+ }
9
+
10
+ export interface WindowNote {
11
+ windowRef: string;
12
+ title: string;
13
+ pairing: "exact" | "high" | "low";
14
+ lastLookId?: string;
15
+ regions: NoteRegion[];
16
+ }
17
+
18
+ interface NoteWindowInput {
19
+ windowRef?: string;
20
+ title: string;
21
+ pairing?: "exact" | "high" | "low";
22
+ pairingScore?: number;
23
+ }
24
+
25
+ interface NoteRefreshOutcome {
26
+ window: NoteWindowInput;
27
+ windowChanged?: boolean;
28
+ newWindowLabel?: string;
29
+ rootDelta?: Array<{ change: string; kind: string; title?: string; ref?: string }>;
30
+ }
31
+
32
+ function normalizedLabel(value: string): string {
33
+ return value.toLowerCase().replace(/\s+/g, " ").trim();
34
+ }
35
+
36
+ function nodeLabel(node: OutlineNode): string {
37
+ return outlineNodeLabel(node) || node.role || node.ref;
38
+ }
39
+
40
+ function regionKey(node: OutlineNode): string {
41
+ return `${node.role || "AXUnknown"}:${node.identifier || normalizedLabel(nodeLabel(node)) || node.ref}`;
42
+ }
43
+
44
+ function regionLabel(node: OutlineNode): string {
45
+ const label = nodeLabel(node);
46
+ return normalizedLabel(label) || normalizedLabel(node.role) || node.ref;
47
+ }
48
+
49
+ function topLevelRegions(outline: Outline): Array<{ node: OutlineNode; key: string; label: string }> {
50
+ const nodes = outline.root.children.length ? outline.root.children : [outline.root];
51
+ return nodes.map((node) => ({ node, key: regionKey(node), label: regionLabel(node) }));
52
+ }
53
+
54
+ function topLevelAncestor(node: OutlineNode, outline: Outline): OutlineNode {
55
+ let current = node;
56
+ while (current.parent && current.parent !== outline.root) current = current.parent;
57
+ return current;
58
+ }
59
+
60
+ function uniqueRegions(regions: NoteRegion[]): NoteRegion[] {
61
+ const seen = new Set<string>();
62
+ const output: NoteRegion[] = [];
63
+ for (const region of regions) {
64
+ const dedupeKey = `${region.key}:${region.status}:${region.detail ?? ""}`;
65
+ if (seen.has(dedupeKey)) continue;
66
+ seen.add(dedupeKey);
67
+ output.push(region);
68
+ }
69
+ return output;
70
+ }
71
+
72
+ function frontierRegions(outline: Outline, topLevels: Array<{ node: OutlineNode; key: string; label: string }>): NoteRegion[] {
73
+ const output: NoteRegion[] = [];
74
+ for (const node of outline.nodes) {
75
+ if (node.scrollExtent && node.scrollExtent.seen < node.scrollExtent.total) {
76
+ const ancestor = topLevelAncestor(node, outline);
77
+ const top = topLevels.find((candidate) => candidate.node === ancestor);
78
+ output.push({
79
+ key: `${top?.key ?? regionKey(ancestor)}:scroll:${node.ref}`,
80
+ label: top?.label ?? regionLabel(ancestor),
81
+ status: "never-looked",
82
+ detail: `${node.scrollExtent.total} rows, ${node.scrollExtent.seen} seen`,
83
+ });
84
+ }
85
+ if (node.truncated) {
86
+ const ancestor = topLevelAncestor(node, outline);
87
+ const top = topLevels.find((candidate) => candidate.node === ancestor);
88
+ output.push({
89
+ key: `${top?.key ?? regionKey(ancestor)}:truncated:${node.ref}`,
90
+ label: top?.label ?? regionLabel(ancestor),
91
+ status: "never-looked",
92
+ detail: "subtree not walked",
93
+ });
94
+ }
95
+ }
96
+ return output;
97
+ }
98
+
99
+ export function noteFromLook(prev: WindowNote | undefined, outline: Outline, window: NoteWindowInput): WindowNote {
100
+ const topLevels = topLevelRegions(outline);
101
+ const currentKeys = new Set(topLevels.map((region) => region.key));
102
+ const regions: NoteRegion[] = topLevels.map((region) => ({
103
+ key: region.key,
104
+ label: region.label,
105
+ status: "seen",
106
+ }));
107
+
108
+ if (prev) {
109
+ for (const old of prev.regions) {
110
+ if (old.status === "never-looked") continue;
111
+ if (!currentKeys.has(old.key)) {
112
+ regions.push({ ...old, status: "changed", detail: "not matched in latest look" });
113
+ }
114
+ }
115
+ }
116
+
117
+ if (!window.windowRef || window.pairingScore === Number.NEGATIVE_INFINITY) {
118
+ regions.push({
119
+ key: "window:unpaired",
120
+ label: "window capture",
121
+ status: "never-looked",
122
+ detail: "AX window without capture pairing",
123
+ });
124
+ }
125
+
126
+ regions.push(...frontierRegions(outline, topLevels));
127
+
128
+ return {
129
+ windowRef: window.windowRef ?? "(unpaired)",
130
+ title: window.title,
131
+ pairing: window.pairing ?? "low",
132
+ lastLookId: outline.lookId,
133
+ regions: uniqueRegions(regions),
134
+ };
135
+ }
136
+
137
+ export function noteAfterAct(prev: WindowNote | undefined, targetRef: string | undefined, outline: Outline, refreshOutcome: NoteRefreshOutcome): WindowNote {
138
+ const note = noteFromLook(prev, outline, refreshOutcome.window);
139
+ if (targetRef) {
140
+ const target = nodeByRef(outline, targetRef);
141
+ if (target) {
142
+ const ancestor = topLevelAncestor(target, outline);
143
+ const key = regionKey(ancestor);
144
+ const region = note.regions.find((candidate) => candidate.key === key);
145
+ if (region) {
146
+ region.status = "changed";
147
+ region.detail = "acted here";
148
+ } else {
149
+ note.regions.unshift({ key, label: regionLabel(ancestor), status: "changed", detail: "acted here" });
150
+ }
151
+ }
152
+ }
153
+ for (const delta of refreshOutcome.rootDelta ?? []) {
154
+ note.regions.unshift({
155
+ key: `root:${delta.change}:${delta.ref ?? delta.kind}:${delta.title ?? ""}`,
156
+ label: `${delta.kind}${delta.title ? ` ${delta.title}` : ""}`,
157
+ status: delta.change === "closed" ? "changed" : "never-looked",
158
+ detail: `root ${delta.change}`,
159
+ });
160
+ }
161
+ if (refreshOutcome.windowChanged) {
162
+ for (const region of note.regions) {
163
+ if (region.status === "seen") region.status = "changed";
164
+ }
165
+ note.regions.push({
166
+ key: `window:changed:${note.lastLookId ?? "unknown"}`,
167
+ label: refreshOutcome.newWindowLabel ?? "new sheet/window",
168
+ status: "never-looked",
169
+ detail: "appeared after act",
170
+ });
171
+ }
172
+ return { ...note, regions: uniqueRegions(note.regions) };
173
+ }
174
+
175
+ export function noteRegionKeyForRef(outline: Outline, ref: string): string | undefined {
176
+ const node = nodeByRef(outline, ref);
177
+ return node ? regionKey(topLevelAncestor(node, outline)) : undefined;
178
+ }
179
+
180
+ export function renderNote(note: WindowNote | undefined): string {
181
+ if (!note) return "";
182
+ const looked = note.lastLookId ? "looked just now" : "not looked";
183
+ const lines = [`note ${note.windowRef} ${JSON.stringify(note.title.slice(0, 512))} (pairing ${note.pairing}, ${looked})`];
184
+ const visible = note.regions.slice(0, 64);
185
+ for (const region of visible) {
186
+ const detail = region.detail ? ` (${region.detail.slice(0, 256)})` : "";
187
+ lines.push(` ${region.label.slice(0, 512).padEnd(14, " ")} ${region.status}${detail}`);
188
+ }
189
+ if (note.regions.length > visible.length) lines.push(` … ${note.regions.length - visible.length} more note regions; use search_ui or expand_ui`);
190
+ const encoded = new TextEncoder().encode(lines.join("\n"));
191
+ if (encoded.byteLength <= 8 * 1024) return new TextDecoder().decode(encoded);
192
+ let end = 8 * 1024;
193
+ while (end > 0 && (encoded[end] & 0xc0) === 0x80) end -= 1;
194
+ return `${new TextDecoder().decode(encoded.subarray(0, end))}\n… note byte budget reached`;
195
+ }