screenhand 0.1.0

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.
@@ -0,0 +1,283 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const execFileAsync = promisify(execFile);
4
+ const POLL_INTERVAL_MS = 100;
5
+ /** Apps known to have AppleScript scripting dictionaries. */
6
+ const SCRIPTABLE_APPS = {
7
+ "com.apple.finder": "Finder",
8
+ "com.apple.Safari": "Safari",
9
+ "com.apple.mail": "Mail",
10
+ "com.apple.iWork.Pages": "Pages",
11
+ "com.apple.iWork.Keynote": "Keynote",
12
+ "com.apple.iWork.Numbers": "Numbers",
13
+ "com.apple.Notes": "Notes",
14
+ "com.apple.reminders": "Reminders",
15
+ "com.apple.iCal": "Calendar",
16
+ "com.apple.TextEdit": "TextEdit",
17
+ "com.apple.Preview": "Preview",
18
+ "com.apple.systempreferences": "System Preferences",
19
+ "com.apple.Terminal": "Terminal",
20
+ "com.apple.Music": "Music",
21
+ "com.apple.TV": "TV",
22
+ "com.apple.Podcasts": "Podcasts",
23
+ };
24
+ export class AppleScriptAdapter {
25
+ sessions = new Map();
26
+ sessionsByProfile = new Map();
27
+ /** Check if a bundle ID is scriptable. */
28
+ static isScriptable(bundleId) {
29
+ return bundleId in SCRIPTABLE_APPS;
30
+ }
31
+ async attach(profile) {
32
+ const existing = this.sessionsByProfile.get(profile);
33
+ if (existing)
34
+ return existing.info;
35
+ const info = {
36
+ sessionId: `as_session_${profile}_${Date.now()}`,
37
+ profile,
38
+ createdAt: new Date().toISOString(),
39
+ adapterType: "applescript",
40
+ };
41
+ // Default to Finder
42
+ const state = {
43
+ info,
44
+ appName: "Finder",
45
+ bundleId: "com.apple.finder",
46
+ };
47
+ this.sessions.set(info.sessionId, state);
48
+ this.sessionsByProfile.set(profile, state);
49
+ return info;
50
+ }
51
+ async getAppContext(sessionId) {
52
+ const state = this.requireSession(sessionId);
53
+ const windowTitle = await this.runScript(`tell application "${state.appName}" to get name of front window`).catch(() => state.appName);
54
+ const pidStr = await this.runScript(`tell application "System Events" to get unix id of (first process whose bundle identifier is "${state.bundleId}")`).catch(() => "0");
55
+ return {
56
+ bundleId: state.bundleId,
57
+ appName: state.appName,
58
+ pid: parseInt(pidStr, 10) || 0,
59
+ windowTitle,
60
+ };
61
+ }
62
+ async getPageMeta(sessionId) {
63
+ const ctx = await this.getAppContext(sessionId);
64
+ let url = `app://${ctx.bundleId}`;
65
+ // For Safari, get the current URL
66
+ if (ctx.bundleId === "com.apple.Safari") {
67
+ try {
68
+ url = await this.runScript('tell application "Safari" to get URL of current tab of front window');
69
+ }
70
+ catch {
71
+ // Ignore
72
+ }
73
+ }
74
+ return { url, title: ctx.windowTitle };
75
+ }
76
+ async navigate(sessionId, url, _timeoutMs) {
77
+ const state = this.requireSession(sessionId);
78
+ if (url.startsWith("app://")) {
79
+ const bundleId = url.slice(6);
80
+ const appName = SCRIPTABLE_APPS[bundleId] ?? bundleId;
81
+ state.bundleId = bundleId;
82
+ state.appName = appName;
83
+ await this.runScript(`tell application "${appName}" to activate`);
84
+ }
85
+ else if (state.bundleId === "com.apple.Safari") {
86
+ await this.runScript(`tell application "Safari" to set URL of current tab of front window to "${this.escapeAS(url)}"`);
87
+ }
88
+ else if (state.bundleId === "com.apple.finder") {
89
+ // Open path in Finder
90
+ await this.runScript(`tell application "Finder" to open POSIX file "${this.escapeAS(url)}"`);
91
+ }
92
+ return this.getPageMeta(sessionId);
93
+ }
94
+ async locate(sessionId, target, timeoutMs) {
95
+ const state = this.requireSession(sessionId);
96
+ const deadline = Date.now() + timeoutMs;
97
+ while (Date.now() < deadline) {
98
+ try {
99
+ const script = this.buildLocateScript(state, target);
100
+ const result = await this.runScript(script);
101
+ if (result && result !== "missing value") {
102
+ return {
103
+ handleId: `as_${result.replace(/\s+/g, "_").slice(0, 50)}`,
104
+ locatorUsed: `applescript:${target.type}`,
105
+ label: result,
106
+ };
107
+ }
108
+ }
109
+ catch {
110
+ // Not found yet
111
+ }
112
+ await sleep(POLL_INTERVAL_MS);
113
+ }
114
+ return null;
115
+ }
116
+ async click(sessionId, element) {
117
+ const state = this.requireSession(sessionId);
118
+ await this.runScript(`tell application "System Events" to tell process "${state.appName}" to click button "${this.escapeAS(element.label ?? element.handleId)}" of front window`);
119
+ }
120
+ async setValue(sessionId, element, text, _clear) {
121
+ const state = this.requireSession(sessionId);
122
+ await this.runScript(`tell application "System Events" to tell process "${state.appName}" to set value of text field "${this.escapeAS(element.label ?? "")}" of front window to "${this.escapeAS(text)}"`);
123
+ }
124
+ async getValue(sessionId, element) {
125
+ const state = this.requireSession(sessionId);
126
+ return this.runScript(`tell application "System Events" to tell process "${state.appName}" to get value of text field "${this.escapeAS(element.label ?? "")}" of front window`);
127
+ }
128
+ async waitFor(sessionId, condition, timeoutMs) {
129
+ const deadline = Date.now() + timeoutMs;
130
+ while (Date.now() < deadline) {
131
+ try {
132
+ if (condition.type === "text_appears") {
133
+ const found = await this.locate(sessionId, { type: "text", value: condition.text }, 200);
134
+ if (found)
135
+ return true;
136
+ }
137
+ else if (condition.type === "window_title_matches") {
138
+ const ctx = await this.getAppContext(sessionId);
139
+ if (new RegExp(condition.regex).test(ctx.windowTitle))
140
+ return true;
141
+ }
142
+ }
143
+ catch {
144
+ // Keep trying
145
+ }
146
+ await sleep(POLL_INTERVAL_MS);
147
+ }
148
+ return false;
149
+ }
150
+ async extract(sessionId, target, format) {
151
+ const state = this.requireSession(sessionId);
152
+ if (state.bundleId === "com.apple.finder" && format === "json") {
153
+ // Get selected files
154
+ const result = await this.runScript('tell application "Finder" to get name of every item of (target of front window) as list');
155
+ return { items: result.split(", ") };
156
+ }
157
+ // Generic: extract UI element text
158
+ const element = await this.locate(sessionId, target, 1500);
159
+ if (!element)
160
+ throw new Error("Extract target not found");
161
+ return element.label ?? "";
162
+ }
163
+ async screenshot(_sessionId, _region) {
164
+ const path = `/tmp/as_screenshot_${Date.now()}.png`;
165
+ await this.runScript(`do shell script "screencapture -x '${path}'"`);
166
+ return path;
167
+ }
168
+ // ── Desktop methods ──
169
+ async launchApp(sessionId, bundleId) {
170
+ const state = this.requireSession(sessionId);
171
+ const appName = SCRIPTABLE_APPS[bundleId] ?? bundleId;
172
+ await this.runScript(`tell application "${appName}" to activate`);
173
+ state.bundleId = bundleId;
174
+ state.appName = appName;
175
+ return this.getAppContext(sessionId);
176
+ }
177
+ async focusApp(sessionId, bundleId) {
178
+ const appName = SCRIPTABLE_APPS[bundleId] ?? bundleId;
179
+ await this.runScript(`tell application "${appName}" to activate`);
180
+ const state = this.requireSession(sessionId);
181
+ state.bundleId = bundleId;
182
+ state.appName = appName;
183
+ }
184
+ async listApps(_sessionId) {
185
+ const result = await this.runScript('tell application "System Events" to get {bundle identifier, name, unix id, frontmost} of every application process whose background only is false');
186
+ // Parse the AppleScript list output
187
+ const parts = result.split(", ");
188
+ const count = Math.floor(parts.length / 4);
189
+ const apps = [];
190
+ for (let i = 0; i < count; i++) {
191
+ apps.push({
192
+ bundleId: parts[i] ?? "unknown",
193
+ name: parts[count + i] ?? "Unknown",
194
+ pid: parseInt(parts[2 * count + i] ?? "0", 10),
195
+ isActive: parts[3 * count + i] === "true",
196
+ });
197
+ }
198
+ return apps;
199
+ }
200
+ async listWindows(_sessionId) {
201
+ // Simplified — AppleScript window listing is limited
202
+ const result = await this.runScript('tell application "System Events" to get {name, position, size} of every window of (first process whose frontmost is true)');
203
+ return [{
204
+ windowId: 0,
205
+ title: result,
206
+ bundleId: "",
207
+ pid: 0,
208
+ bounds: { x: 0, y: 0, width: 0, height: 0 },
209
+ isOnScreen: true,
210
+ }];
211
+ }
212
+ async menuClick(sessionId, menuPath) {
213
+ const state = this.requireSession(sessionId);
214
+ if (menuPath.length === 0)
215
+ throw new Error("menuPath must not be empty");
216
+ let script = `tell application "System Events" to tell process "${state.appName}"\n`;
217
+ if (menuPath.length === 1) {
218
+ script += ` click menu item "${this.escapeAS(menuPath[0])}" of menu bar 1\n`;
219
+ }
220
+ else if (menuPath.length === 2) {
221
+ script += ` click menu item "${this.escapeAS(menuPath[1])}" of menu "${this.escapeAS(menuPath[0])}" of menu bar 1\n`;
222
+ }
223
+ else {
224
+ // Deep menu path
225
+ script += ` click menu item "${this.escapeAS(menuPath[menuPath.length - 1])}" of menu "${this.escapeAS(menuPath[menuPath.length - 2])}"`;
226
+ for (let i = menuPath.length - 3; i >= 0; i--) {
227
+ script += ` of menu item "${this.escapeAS(menuPath[i])}" of menu "${this.escapeAS(menuPath[i])}"`;
228
+ }
229
+ script += ` of menu bar 1\n`;
230
+ }
231
+ script += `end tell`;
232
+ await this.runScript(script);
233
+ }
234
+ async keyCombo(_sessionId, keys) {
235
+ const modifiers = [];
236
+ let keyChar = "";
237
+ for (const key of keys) {
238
+ const lower = key.toLowerCase();
239
+ if (lower === "cmd" || lower === "command")
240
+ modifiers.push("command down");
241
+ else if (lower === "shift")
242
+ modifiers.push("shift down");
243
+ else if (lower === "alt" || lower === "option")
244
+ modifiers.push("option down");
245
+ else if (lower === "ctrl" || lower === "control")
246
+ modifiers.push("control down");
247
+ else
248
+ keyChar = lower;
249
+ }
250
+ const modStr = modifiers.length > 0 ? ` using {${modifiers.join(", ")}}` : "";
251
+ await this.runScript(`tell application "System Events" to keystroke "${this.escapeAS(keyChar)}"${modStr}`);
252
+ }
253
+ // ── Private helpers ──
254
+ requireSession(sessionId) {
255
+ const state = this.sessions.get(sessionId);
256
+ if (!state)
257
+ throw new Error(`Session not found: ${sessionId}`);
258
+ return state;
259
+ }
260
+ async runScript(script) {
261
+ const { stdout } = await execFileAsync("osascript", ["-e", script], {
262
+ timeout: 10_000,
263
+ });
264
+ return stdout.trim();
265
+ }
266
+ buildLocateScript(state, target) {
267
+ const proc = state.appName;
268
+ if (target.type === "text" || target.type === "role") {
269
+ const searchText = target.type === "text" ? target.value : target.name;
270
+ return `tell application "System Events" to tell process "${proc}" to get name of first UI element of front window whose name contains "${this.escapeAS(searchText)}"`;
271
+ }
272
+ if (target.type === "selector") {
273
+ return `tell application "System Events" to tell process "${proc}" to get name of first UI element of front window whose description contains "${this.escapeAS(target.value)}"`;
274
+ }
275
+ throw new Error(`AppleScript adapter does not support target type: ${target.type}`);
276
+ }
277
+ escapeAS(str) {
278
+ return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
279
+ }
280
+ }
281
+ function sleep(ms) {
282
+ return new Promise((resolve) => setTimeout(resolve, ms));
283
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Maps web ARIA roles to macOS Accessibility roles.
3
+ * Used to translate web-style role targets to native AX queries.
4
+ */
5
+ export const WEB_TO_AX_ROLE = {
6
+ // Interactive
7
+ button: "AXButton",
8
+ link: "AXLink",
9
+ textbox: "AXTextField",
10
+ checkbox: "AXCheckBox",
11
+ radio: "AXRadioButton",
12
+ combobox: "AXComboBox",
13
+ slider: "AXSlider",
14
+ switch: "AXCheckBox",
15
+ tab: "AXRadioButton",
16
+ menuitem: "AXMenuItem",
17
+ menu: "AXMenu",
18
+ menubar: "AXMenuBar",
19
+ option: "AXMenuItem",
20
+ listbox: "AXList",
21
+ spinbutton: "AXIncrementor",
22
+ scrollbar: "AXScrollBar",
23
+ // Structure
24
+ heading: "AXHeading",
25
+ list: "AXList",
26
+ listitem: "AXGroup",
27
+ table: "AXTable",
28
+ row: "AXRow",
29
+ cell: "AXCell",
30
+ grid: "AXTable",
31
+ treegrid: "AXOutline",
32
+ tree: "AXOutline",
33
+ treeitem: "AXOutlineRow",
34
+ toolbar: "AXToolbar",
35
+ tablist: "AXTabGroup",
36
+ tabpanel: "AXGroup",
37
+ group: "AXGroup",
38
+ region: "AXGroup",
39
+ dialog: "AXSheet",
40
+ alertdialog: "AXSheet",
41
+ // Semantic
42
+ img: "AXImage",
43
+ image: "AXImage",
44
+ progressbar: "AXProgressIndicator",
45
+ separator: "AXSplitter",
46
+ status: "AXStaticText",
47
+ tooltip: "AXHelpTag",
48
+ banner: "AXGroup",
49
+ navigation: "AXGroup",
50
+ main: "AXGroup",
51
+ contentinfo: "AXGroup",
52
+ complementary: "AXGroup",
53
+ article: "AXGroup",
54
+ document: "AXGroup",
55
+ // Text
56
+ statictext: "AXStaticText",
57
+ textarea: "AXTextArea",
58
+ text: "AXStaticText",
59
+ // Window-level
60
+ window: "AXWindow",
61
+ application: "AXApplication",
62
+ };
63
+ /**
64
+ * Maps macOS AX roles back to web ARIA roles.
65
+ */
66
+ export const AX_TO_WEB_ROLE = {};
67
+ for (const [web, ax] of Object.entries(WEB_TO_AX_ROLE)) {
68
+ if (!(ax in AX_TO_WEB_ROLE)) {
69
+ AX_TO_WEB_ROLE[ax] = web;
70
+ }
71
+ }
72
+ /**
73
+ * Convert a web-style role to macOS AX role.
74
+ * If already an AX role (starts with "AX"), pass through.
75
+ */
76
+ export function toAXRole(role) {
77
+ if (role.startsWith("AX"))
78
+ return role;
79
+ return WEB_TO_AX_ROLE[role.toLowerCase()] ?? role;
80
+ }
@@ -0,0 +1,36 @@
1
+ export class PlaceholderBrowserAdapter {
2
+ async connect(profile) {
3
+ return {
4
+ sessionId: `session_${profile}_${Date.now()}`,
5
+ profile,
6
+ createdAt: new Date().toISOString(),
7
+ };
8
+ }
9
+ async getPageMeta(_sessionId) {
10
+ return { url: "about:blank", title: "Placeholder Session" };
11
+ }
12
+ async navigate(_sessionId, url, _timeoutMs) {
13
+ return { url, title: "Placeholder Navigation" };
14
+ }
15
+ async locate(_sessionId, _target, _timeoutMs) {
16
+ throw new Error("Browser adapter not implemented: locate");
17
+ }
18
+ async click(_sessionId, _element) {
19
+ throw new Error("Browser adapter not implemented: click");
20
+ }
21
+ async setValue(_sessionId, _element, _text, _clear) {
22
+ throw new Error("Browser adapter not implemented: setValue");
23
+ }
24
+ async getValue(_sessionId, _element) {
25
+ throw new Error("Browser adapter not implemented: getValue");
26
+ }
27
+ async waitFor(_sessionId, _condition, _timeoutMs) {
28
+ throw new Error("Browser adapter not implemented: waitFor");
29
+ }
30
+ async extract(_sessionId, _target, _format) {
31
+ throw new Error("Browser adapter not implemented: extract");
32
+ }
33
+ async screenshot(_sessionId, _region) {
34
+ throw new Error("Browser adapter not implemented: screenshot");
35
+ }
36
+ }