@reticlehq/computer 0.0.0-stage → 3.11.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.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +217 -2
  4. package/bin/attach.mjs +330 -0
  5. package/dist/attach.d.ts +105 -0
  6. package/dist/attach.js +234 -0
  7. package/dist/channels.d.ts +42 -0
  8. package/dist/channels.js +46 -0
  9. package/dist/computer-realm.d.ts +54 -0
  10. package/dist/computer-realm.js +487 -0
  11. package/dist/doctor.d.ts +32 -0
  12. package/dist/doctor.js +42 -0
  13. package/dist/driver.d.ts +227 -0
  14. package/dist/driver.js +73 -0
  15. package/dist/effect.d.ts +60 -0
  16. package/dist/effect.js +158 -0
  17. package/dist/files.d.ts +16 -0
  18. package/dist/files.js +40 -0
  19. package/dist/hud/port.d.ts +44 -0
  20. package/dist/hud/port.js +6 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lines.d.ts +34 -0
  24. package/dist/lines.js +80 -0
  25. package/dist/mac/from-ax.d.ts +27 -0
  26. package/dist/mac/from-ax.js +275 -0
  27. package/dist/mac/mac-driver.d.ts +42 -0
  28. package/dist/mac/mac-driver.js +355 -0
  29. package/dist/mac/mac-hud.d.ts +10 -0
  30. package/dist/mac/mac-hud.js +142 -0
  31. package/dist/peer/act-effect.d.ts +9 -0
  32. package/dist/peer/act-effect.js +13 -0
  33. package/dist/peer/commands.d.ts +87 -0
  34. package/dist/peer/commands.js +811 -0
  35. package/dist/peer/form.d.ts +62 -0
  36. package/dist/peer/form.js +103 -0
  37. package/dist/peer/link-switch.d.ts +12 -0
  38. package/dist/peer/link-switch.js +38 -0
  39. package/dist/peer/peer.d.ts +43 -0
  40. package/dist/peer/peer.js +216 -0
  41. package/dist/peer/pointer.d.ts +97 -0
  42. package/dist/peer/pointer.js +289 -0
  43. package/dist/peer/scroll.d.ts +12 -0
  44. package/dist/peer/scroll.js +157 -0
  45. package/dist/peer/seen.d.ts +18 -0
  46. package/dist/peer/seen.js +61 -0
  47. package/dist/peer/select.d.ts +27 -0
  48. package/dist/peer/select.js +78 -0
  49. package/dist/peer/window.d.ts +25 -0
  50. package/dist/peer/window.js +111 -0
  51. package/dist/ui-node.d.ts +93 -0
  52. package/dist/ui-node.js +192 -0
  53. package/dist/win/helper-launch.d.ts +10 -0
  54. package/dist/win/helper-launch.js +34 -0
  55. package/native/linux/Dockerfile +12 -0
  56. package/native/linux/reticle-atspi.py +933 -0
  57. package/native/linux/sandbox.mjs +127 -0
  58. package/native/mac/build/reticle-ax +0 -0
  59. package/native/mac/build/reticle-hud +0 -0
  60. package/native/mac/hud.swift +749 -0
  61. package/native/mac/reticle-ax.swift +1786 -0
  62. package/native/win/reticle-uia.ps1 +620 -0
  63. package/package.json +65 -3
package/bin/attach.mjs ADDED
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+ // reticle-computer: joins a running application to the Reticle bridge, so the tools an agent
3
+ // has for a web page work on it: macOS, Windows and Linux. Nothing is installed in the application.
4
+ // With --host (or RETICLE_HOST) it joins a daemon on another machine: run it in a container or a
5
+ // virtual machine of its own, and the agent works there while the person keeps their screen.
6
+ //
7
+ // reticle-computer --app <name> [--project <folder>] [--port <port>] [--host <host>] [--watch <folder>]...
8
+ // [--no-electron-switch] [--background-only] [--no-hud] [--open]
9
+ // reticle-computer --sandbox linux --app <name> --open "<command>" (a Linux desktop of its own)
10
+ // reticle-computer --sandbox stop
11
+ // reticle-computer --list (the applications that are open, as JSON)
12
+ // reticle-computer --app <name> --doctor (checks that it can work, and says what to do)
13
+ //
14
+ // The terminal needs Accessibility permission. The command stays open until you stop it.
15
+ import { execFileSync } from 'node:child_process';
16
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
17
+ import { connect } from 'node:net';
18
+ import { homedir } from 'node:os';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ import { nodeWorkspace } from '@reticlehq/terminal';
22
+
23
+ import {
24
+ MacDriver,
25
+ attachPlan,
26
+ connectPeer,
27
+ OWNER_SETTINGS_FILE,
28
+ STOPPED_FILE,
29
+ doctorReport,
30
+ electronWarning,
31
+ helperLaunch,
32
+ isElectron,
33
+ joinedAnswer,
34
+ macHud,
35
+ pickApp,
36
+ servingHelper,
37
+ withOwnerLimits,
38
+ } from '../dist/index.js';
39
+
40
+ const say = (line) => process.stderr.write(`${line}\n`);
41
+ const read = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : undefined);
42
+
43
+ // A Linux desktop of its own for the agent, in a container: native/linux/sandbox.mjs.
44
+ if (process.argv.includes('--sandbox')) {
45
+ const { sandbox } = await import('../native/linux/sandbox.mjs');
46
+ process.exit(await sandbox(process.argv.slice(2)));
47
+ }
48
+
49
+ // The limits of the person at the machine, from files of their own. No flag lifts them.
50
+ const ownerDir = `${homedir()}/.reticle`;
51
+ const stoppedPath = `${ownerDir}/${STOPPED_FILE}`;
52
+ const asked = attachPlan(process.argv.slice(2), process.env, homedir(), read);
53
+ const plan =
54
+ 'error' in asked
55
+ ? asked
56
+ : withOwnerLimits(
57
+ asked,
58
+ read(`${ownerDir}/${OWNER_SETTINGS_FILE}`),
59
+ read(stoppedPath),
60
+ stoppedPath,
61
+ );
62
+ const LIST = process.argv.includes('--list');
63
+ if ('error' in plan && !LIST) {
64
+ say(plan.error);
65
+ process.exit(2);
66
+ }
67
+ const native = fileURLToPath(new URL('../native/mac/', import.meta.url));
68
+ const windows = 'win32' === process.platform;
69
+ // macOS runs the Swift helper; Windows runs the UI Automation script in PowerShell. Both answer in
70
+ // one shape, so the rest of this command is the same.
71
+ const launch = helperLaunch(
72
+ process.platform,
73
+ fileURLToPath(new URL('../native/', import.meta.url)),
74
+ );
75
+ const helper = launch?.file ?? `${native}build/reticle-ax`;
76
+ const source = `${native}reticle-ax.swift`;
77
+
78
+ const quiet = (file, args) => {
79
+ try {
80
+ return execFileSync(file, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
81
+ } catch {
82
+ return undefined;
83
+ }
84
+ };
85
+ /** One command to the helper, with the words that start it on this operating system. */
86
+ const ask = (args) => quiet(helper, [...(launch?.prefix ?? []), ...args]);
87
+ /** The application by the name a person sees or the name of its process. Needs the helper. */
88
+ const findApp = (app) => {
89
+ const listed = JSON.parse(ask(['apps']) ?? '{}').apps;
90
+ if (!Array.isArray(listed)) {
91
+ // The helper did not answer: fall back to the name of the process.
92
+ const found = Number((quiet('pgrep', ['-x', app]) ?? '').split('\n')[0]);
93
+ return Number.isInteger(found) && found > 0
94
+ ? { pid: found }
95
+ : { error: `No application named ${app} is open.` };
96
+ }
97
+ return pickApp(app, listed);
98
+ };
99
+ /**
100
+ * The helper, built when it is not there or when its source is newer. A helper from before an
101
+ * update would answer in the old way, and nothing would say so.
102
+ * The published package holds both programs, built by `prepack` (native/mac/build-release.mjs),
103
+ * so a person needs no Swift compiler. In a checkout they are built on first use.
104
+ */
105
+ const hudProgram = `${native}build/reticle-hud`;
106
+ const buildOne = (program, from, stdio) => {
107
+ if (existsSync(program) && statSync(program).mtimeMs >= statSync(from).mtimeMs) return true;
108
+ mkdirSync(`${native}build`, { recursive: true });
109
+ try {
110
+ execFileSync('swiftc', ['-O', from, '-o', program], { stdio });
111
+ return true;
112
+ } catch {
113
+ return false;
114
+ }
115
+ };
116
+ // Only macOS builds: the helper of Windows and of Linux is a script.
117
+ const buildHelper = (stdio) => 'darwin' !== process.platform || buildOne(helper, source, stdio);
118
+ const answers = (url) =>
119
+ new Promise((resolve) => {
120
+ const { hostname, port } = new URL(url);
121
+ const socket = connect({ host: hostname, port: Number(port) });
122
+ const done = (ok) => {
123
+ socket.destroy();
124
+ resolve(ok);
125
+ };
126
+ socket.setTimeout(1000, () => done(false));
127
+ socket.once('connect', () => done(true));
128
+ socket.once('error', () => done(false));
129
+ });
130
+
131
+ if (LIST) {
132
+ // For an agent: the names it can give to --app. Names only.
133
+ if (launch === undefined || !buildHelper('ignore')) {
134
+ say('reticle-computer runs on macOS, Windows and Linux (X, with python3-gi and xdotool).');
135
+ process.exit(2);
136
+ }
137
+ const listed = JSON.parse(ask(['apps']) ?? '{}').apps ?? [];
138
+ process.stdout.write(
139
+ `${JSON.stringify({ apps: listed.filter((app) => true === app.regular).map(({ name, process: program }) => ({ name, process: program })) })}\n`,
140
+ );
141
+ process.exit(0);
142
+ }
143
+
144
+ if (process.argv.includes('--doctor')) {
145
+ const darwin = 'darwin' === process.platform;
146
+ const compiler = darwin && buildHelper('ignore');
147
+ const picked = darwin && compiler ? findApp(plan.app) : { error: undefined };
148
+ const appPid = picked.pid;
149
+ let trusted;
150
+ let screenLocked;
151
+ let windows;
152
+ let windowsNotOnScreen;
153
+ if (compiler) {
154
+ // Any process will do to learn if the permission is there. The application's own, when open.
155
+ const read = JSON.parse(ask(['tree', String(appPid ?? process.pid)]) ?? '{}');
156
+ trusted = 'not-trusted' !== read.error;
157
+ screenLocked = 'screen-locked' === read.error;
158
+ if (appPid !== undefined && read.tree !== undefined) {
159
+ windows = read.tree.children.filter((child) => 'AXWindow' === child.role).length;
160
+ windowsNotOnScreen = read.windowsNotOnScreen;
161
+ }
162
+ }
163
+ const report = doctorReport({
164
+ platform: process.platform,
165
+ compiler,
166
+ trusted,
167
+ screenLocked,
168
+ app: plan.app,
169
+ appOpen: appPid !== undefined,
170
+ appHint: picked.error,
171
+ windows,
172
+ windowsNotOnScreen,
173
+ bridge: await answers(plan.url),
174
+ token: plan.token !== undefined,
175
+ });
176
+ for (const line of report.lines) say(line);
177
+ say(report.ready ? `\nReady. Run it again with no --doctor to join ${plan.app}.` : '');
178
+ process.exit(report.ready ? 0 : 1);
179
+ }
180
+
181
+ if (launch === undefined) {
182
+ say('reticle-computer runs on macOS, Windows and Linux (X, with python3-gi and xdotool).');
183
+ process.exit(2);
184
+ }
185
+
186
+ if (!buildHelper('inherit')) {
187
+ say('The helper could not be built. Run with --doctor to see why.');
188
+ process.exit(1);
189
+ }
190
+ let picked = findApp(plan.app);
191
+ if (picked.pid === undefined && plan.open && windows) {
192
+ say(`--open starts an application on macOS only for now. Start ${plan.app}, and run this again.`);
193
+ process.exit(1);
194
+ }
195
+ if (picked.pid === undefined && plan.open) {
196
+ // -g leaves the application that is in front where it is. `open` takes the name as an argument
197
+ // of its own, so a name with a space or a dash is a name and nothing else.
198
+ if (quiet('open', ['-g', '-a', plan.app]) === undefined) {
199
+ say(`macOS found no application named ${plan.app} to start.`);
200
+ process.exit(1);
201
+ }
202
+ const until = Date.now() + 15_000;
203
+ while (Date.now() < until && picked.pid === undefined) {
204
+ await new Promise((done) => setTimeout(done, 300));
205
+ picked = findApp(plan.app);
206
+ }
207
+ }
208
+ if (picked.pid === undefined) {
209
+ const how = plan.open ? '' : ' To start it and join it, add --open.';
210
+ say(`${picked.error}${how} Run with --doctor to check the rest.`);
211
+ process.exit(1);
212
+ }
213
+ const pid = picked.pid;
214
+
215
+ const warning = electronWarning(
216
+ quiet('ps', ['-o', 'comm=', '-p', String(pid)]) ?? '',
217
+ plan,
218
+ existsSync,
219
+ );
220
+ if (warning !== undefined) {
221
+ say(warning);
222
+ }
223
+ // The daemon ends when it is idle, and the next tool call starts it again. An agent that runs
224
+ // this command first found no daemon and gave up. So the command waits for the bridge for a time.
225
+ const WAIT_FOR_BRIDGE_MS = 30_000;
226
+ if (!(await answers(plan.url))) {
227
+ say(`Waiting for the Reticle daemon at ${plan.url}. Call a Reticle tool, or run: reticle serve`);
228
+ const until = Date.now() + WAIT_FOR_BRIDGE_MS;
229
+ while (Date.now() < until && !(await answers(plan.url))) {
230
+ await new Promise((resolve) => setTimeout(resolve, 1000));
231
+ }
232
+ }
233
+ // The pointer and the window of the realm. Not having them is no reason to stop.
234
+ const hud =
235
+ plan.hud && 'darwin' === process.platform && buildOne(hudProgram, `${native}hud.swift`, 'ignore')
236
+ ? macHud(hudProgram, () => {
237
+ // Stop in the window: leave the application, as Ctrl-C does.
238
+ // Stop is for good: the file stays until the person removes it, and no join works before.
239
+ mkdirSync(ownerDir, { recursive: true });
240
+ writeFileSync(stoppedPath, `${new Date().toISOString()}\n`);
241
+ say(
242
+ `Stopped in the window of Reticle. No application is joined until you remove the file: rm ${stoppedPath}`,
243
+ );
244
+ leave();
245
+ })
246
+ : undefined;
247
+ let leave = () => process.exit(0);
248
+ const program = quiet('ps', ['-o', 'comm=', '-p', String(pid)]) ?? '';
249
+ const electron = isElectron(program, existsSync);
250
+ // A native application can build part of its tree only for a screen reader (the sheet of
251
+ // Numbers). The driver tries that switch at its first read that shows a window, and keeps it only
252
+ // when it fills a container that was empty.
253
+ const screenReader = plan.electronSwitch && !electron && !windows;
254
+ const sessionId = `cu-${plan.app}-${String(pid)}`.replace(/[^\w.-]/g, '-');
255
+ const peer = connectPeer({
256
+ url: plan.url,
257
+ ...(plan.token === undefined ? {} : { token: plan.token }),
258
+ sessionId,
259
+ projectId: plan.projectId ?? `cu-${plan.app}`.replace(/[^\w.-]/g, '-'),
260
+ driver: new MacDriver({
261
+ helper,
262
+ app: plan.app,
263
+ pid,
264
+ screenReaderSwitch: screenReader,
265
+ ...(launch === undefined || 0 === launch.prefix.length
266
+ ? {}
267
+ : { run: servingHelper(launch.prefix) }),
268
+ }),
269
+ ...(warning === undefined ? {} : { noEffectNote: warning }),
270
+ foreground: plan.foreground,
271
+ ...(hud === undefined ? {} : { hud }),
272
+ ...(0 === plan.watch.length ? {} : { workspace: nodeWorkspace(plan.watch, { exclude: [] }) }),
273
+ now: () => Date.now(),
274
+ });
275
+
276
+ try {
277
+ await peer.ready;
278
+ } catch (error) {
279
+ say(`Could not reach the bridge at ${plan.url}: ${String(error)}. Start it with: reticle serve`);
280
+ process.exit(1);
281
+ }
282
+ // Only after the bridge answered: a command that ends before this leaves the application as it was.
283
+ const switched = plan.electronSwitch && electron;
284
+ if (switched) {
285
+ ask(['web-tree', String(pid), 'on']);
286
+ }
287
+ say(`${plan.app} (${String(pid)}) is joined to ${plan.url}.`);
288
+ // What can be read now. An application that was started behind a full-screen Space has its
289
+ // window on another Space, and the answer must say so before the first look gives nothing.
290
+ let seen;
291
+ try {
292
+ const first = JSON.parse(ask(['tree', String(pid)]) ?? '{}');
293
+ const windows = (first.tree?.children ?? []).filter((c) => 'AXWindow' === c.role).length;
294
+ seen = { windows, windowsNotOnScreen: first.windowsNotOnScreen ?? 0 };
295
+ } catch {
296
+ seen = undefined;
297
+ }
298
+ const joined = joinedAnswer(plan, sessionId, pid, seen);
299
+ if (false === joined.readable) {
300
+ say(joined.why);
301
+ }
302
+ say(
303
+ joined.needsSessionId
304
+ ? `Give this on each tool call: sessionId "${sessionId}". Stop with Ctrl-C.`
305
+ : 'The session is in the project you named. When a browser tab of that project is connected too, give the sessionId on each call. Stop with Ctrl-C.',
306
+ );
307
+ // One line for an agent that started this command: what was joined, and what to call next.
308
+ process.stdout.write(`${JSON.stringify(joined)}\n`);
309
+ if (plan.token === undefined) {
310
+ say(
311
+ 'No pairing token was found. The session is joined, but a file or a setting that changes with nothing else is then not proof: the bridge cannot tell this command from a page. Start the daemon with `reticle serve`, which writes the token.',
312
+ );
313
+ }
314
+ const stop = () => {
315
+ hud?.close();
316
+ // Off also when the driver only tried the screen reader switch: off is nothing for a switch
317
+ // that was never on.
318
+ if (switched || screenReader) {
319
+ ask(['web-tree', String(pid), 'off']);
320
+ }
321
+ peer.close();
322
+ process.exit(0);
323
+ };
324
+ leave = stop;
325
+ process.on('SIGINT', stop);
326
+ process.on('SIGTERM', stop);
327
+ // The terminal was closed.
328
+ process.on('SIGHUP', stop);
329
+ // The heartbeat timer does not hold the process open, so this one does.
330
+ setInterval(() => {}, 60_000);
@@ -0,0 +1,105 @@
1
+ export interface AttachPlan {
2
+ app: string;
3
+ url: string;
4
+ /** Absent when the bridge has no token file. A bridge with a token then refuses the dial. */
5
+ token?: string;
6
+ watch: string[];
7
+ /**
8
+ * The project the application belongs to, from the `.reticle.json` in the folder that
9
+ * `--project` names. Absent: no folder was named, which is the usual case: a desktop
10
+ * application is driven for itself, and it is in no project. The command does NOT take the
11
+ * project of the folder it runs in: a browser tab of that project would then share its scope,
12
+ * and a call with no sessionId that was meant for the page could go to the application. The runs and flows of the session then go to
13
+ * a folder for sessions with no project, and they do not reach the dashboard.
14
+ */
15
+ projectId?: string;
16
+ /**
17
+ * Turn on the accessibility switch of an Electron application, and turn it off at the end.
18
+ * With the switch off, an Electron application shows its elements and does nothing for a press.
19
+ * On unless the person says `--no-electron-switch`: the switch costs that application some
20
+ * speed, and an agent that joins one must not have to know about it.
21
+ */
22
+ electronSwitch: boolean;
23
+ /**
24
+ * The realm may bring the application to the front and use the real pointer, when a caller asks
25
+ * for it on an action. False with `--background-only`: the person at the machine keeps the
26
+ * pointer and the application in front, whatever a caller asks.
27
+ */
28
+ foreground: boolean;
29
+ /**
30
+ * Show the realm's own pointer and its small window on the screen. False with `--no-hud`: a
31
+ * machine with nobody at it has no use for them.
32
+ */
33
+ hud: boolean;
34
+ /**
35
+ * Start the application when it is not open, and then join it. False unless the caller says
36
+ * `--open`: a command that joins must not start a program that nobody asked for.
37
+ */
38
+ open: boolean;
39
+ }
40
+ export declare function attachPlan(argv: readonly string[], env: Readonly<Record<string, string | undefined>>, home: string, readFile: (path: string) => string | undefined): AttachPlan | {
41
+ error: string;
42
+ };
43
+ /**
44
+ * True when the program of a process is in the bundle of an Electron application or of a
45
+ * Chromium browser. Both show a page, and both need the accessibility switch: without it a press
46
+ * on the page is answered with "done" and does not reach the page.
47
+ *
48
+ * A Chromium browser has no Electron in it. Its mark is a framework with the name of its own
49
+ * program: `Google Chrome Framework.framework` beside the program `Google Chrome`.
50
+ */
51
+ export declare function isElectron(given: string, exists: (path: string) => boolean): boolean;
52
+ /**
53
+ * What to say when an Electron application is joined with its switch off. `program` is the path
54
+ * of the program of the process. Absent answer: the application is not Electron, or the switch
55
+ * is on.
56
+ */
57
+ export declare function electronWarning(program: string, plan: Pick<AttachPlan, 'app' | 'electronSwitch'>, exists: (path: string) => boolean): string | undefined;
58
+ /**
59
+ * What the command says on standard output when it has joined: one line of JSON, for an agent
60
+ * that started it. `sessionId` is needed on a tool call only when the session is in no project:
61
+ * a session in the project of the folder is found without it.
62
+ */
63
+ export declare function joinedAnswer(plan: Pick<AttachPlan, 'app' | 'projectId' | 'foreground'>, sessionId: string, pid: number, seen?: {
64
+ windows: number;
65
+ windowsNotOnScreen: number;
66
+ }): Record<string, unknown>;
67
+ /** One application that is open, as the helper lists it. */
68
+ export interface RunningApp {
69
+ /** The name a person sees in the Dock and the menu bar. */
70
+ name: string;
71
+ /** The name of the program of the process. */
72
+ process: string;
73
+ pid: number;
74
+ /** When it was started, in seconds. Absent: not known. */
75
+ launched?: number;
76
+ /** An application a person opens, with a place in the Dock. Absent: not known. */
77
+ regular?: boolean;
78
+ }
79
+ /**
80
+ * The application a person means by a name. The name a person sees is often not the name of the
81
+ * process: "Visual Studio Code" runs as "Code". A name that fits nothing gets the names that are
82
+ * near it, or the names of what is open.
83
+ */
84
+ export declare function pickApp(wanted: string, running: readonly RunningApp[]): {
85
+ pid: number;
86
+ } | {
87
+ error: string;
88
+ };
89
+ /** The file of the person at the machine: limits that no flag of the command can lift. */
90
+ export declare const OWNER_SETTINGS_FILE = "computer.json";
91
+ /** The file that is there after Stop in the window: no application is joined while it is. */
92
+ export declare const STOPPED_FILE = "computer.stopped";
93
+ /**
94
+ * The plan with the limits of the person at the machine. An agent starts the command, so an
95
+ * agent picks its flags. These limits are in a file of the person's own and a flag cannot lift
96
+ * them: `backgroundOnly` forbids the real pointer, and `hud` keeps the window and the pointer of
97
+ * the realm on the screen. After Stop in the window, no application is joined until the person
98
+ * removes the file that Stop wrote.
99
+ *
100
+ * ponytail: a file in the home folder. A program with a shell can change a file, so this states
101
+ * what the person wants and makes a change to it a deliberate act. It is not a wall.
102
+ */
103
+ export declare function withOwnerLimits(plan: AttachPlan, settingsText: string | undefined, stoppedAt: string | undefined, stoppedPath: string): AttachPlan | {
104
+ error: string;
105
+ };
package/dist/attach.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * What `reticle-computer` needs to join a bridge: which application, which bridge, the token
3
+ * of that bridge, and the folders to watch. Pure, so a test gives it arguments and files.
4
+ */
5
+ import { basename, join } from 'node:path';
6
+ import { RETICLE_DEFAULT_PORT, bridgeWsUrl } from '@reticlehq/core';
7
+ const Flag = {
8
+ APP: '--app',
9
+ PORT: '--port',
10
+ HOST: '--host',
11
+ WATCH: '--watch',
12
+ PROJECT: '--project',
13
+ NO_ELECTRON_SWITCH: '--no-electron-switch',
14
+ LIST: '--list',
15
+ BACKGROUND_ONLY: '--background-only',
16
+ NO_HUD: '--no-hud',
17
+ OPEN: '--open',
18
+ };
19
+ const Env = {
20
+ TOKEN: 'RETICLE_TOKEN',
21
+ PORT: 'RETICLE_PORT',
22
+ HOST: 'RETICLE_HOST',
23
+ TOKEN_DIR: 'RETICLE_PAIRING_TOKEN_DIR',
24
+ };
25
+ const STATE_DIR = '.reticle';
26
+ const TOKEN_FILE = 'pairing-token';
27
+ /** The file that ties a folder to a project. `reticle init` writes it. */
28
+ const PROJECT_FILE = '.reticle.json';
29
+ function projectIdIn(text) {
30
+ if (text === undefined) {
31
+ return undefined;
32
+ }
33
+ try {
34
+ const parsed = JSON.parse(text);
35
+ const id = 'object' === typeof parsed && parsed !== null && 'projectId' in parsed
36
+ ? parsed.projectId
37
+ : undefined;
38
+ return 'string' === typeof id && id.length > 0 ? id : undefined;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ export function attachPlan(argv, env, home, readFile) {
45
+ const valuesOf = (flag) => argv.flatMap((arg, index) => (arg === flag ? [argv[index + 1] ?? ''] : []));
46
+ const app = valuesOf(Flag.APP)[0];
47
+ if (app === undefined || 0 === app.length) {
48
+ return {
49
+ error: `Name the application: ${Flag.APP} <name>. To see the names that are open: ${Flag.LIST}.`,
50
+ };
51
+ }
52
+ const folder = valuesOf(Flag.PROJECT)[0];
53
+ let projectId;
54
+ if (folder !== undefined) {
55
+ projectId = projectIdIn(readFile(join(folder, PROJECT_FILE)));
56
+ if (projectId === undefined) {
57
+ return {
58
+ error: `${join(folder, PROJECT_FILE)} has no projectId. Run \`reticle init\` in that folder, or give the folder of the application's source.`,
59
+ };
60
+ }
61
+ }
62
+ const port = Number(valuesOf(Flag.PORT)[0] ?? env[Env.PORT] ?? RETICLE_DEFAULT_PORT);
63
+ // Another host when the agent's computer is a container or a virtual machine, and the daemon
64
+ // runs on the person's machine. The token then comes from RETICLE_TOKEN.
65
+ const host = valuesOf(Flag.HOST)[0] ?? env[Env.HOST];
66
+ const token = env[Env.TOKEN] ??
67
+ readFile(join(env[Env.TOKEN_DIR] ?? join(home, STATE_DIR), TOKEN_FILE))?.trim();
68
+ return {
69
+ app,
70
+ url: host === undefined || 0 === host.length ? bridgeWsUrl(port) : bridgeWsUrl(port, host),
71
+ ...(token === undefined || 0 === token.length ? {} : { token }),
72
+ watch: valuesOf(Flag.WATCH),
73
+ ...(projectId === undefined ? {} : { projectId }),
74
+ electronSwitch: !argv.includes(Flag.NO_ELECTRON_SWITCH),
75
+ foreground: !argv.includes(Flag.BACKGROUND_ONLY),
76
+ hud: !argv.includes(Flag.NO_HUD),
77
+ open: argv.includes(Flag.OPEN),
78
+ };
79
+ }
80
+ /** The file that every Electron application has in its bundle. */
81
+ const ELECTRON_MARK = 'Contents/Frameworks/Electron Framework.framework';
82
+ /**
83
+ * Frameworks that carry Chromium with no Electron: the embedded framework (Spotify), and the one
84
+ * of Arc and Dia. Read from the bundles; only Chrome and Electron were driven.
85
+ */
86
+ const CHROMIUM_MARKS = [
87
+ 'Contents/Frameworks/Chromium Embedded Framework.framework',
88
+ 'Contents/Frameworks/ArcCore.framework',
89
+ ];
90
+ const BUNDLE = /^(.*?\.app)\//;
91
+ /**
92
+ * True when the program of a process is in the bundle of an Electron application or of a
93
+ * Chromium browser. Both show a page, and both need the accessibility switch: without it a press
94
+ * on the page is answered with "done" and does not reach the page.
95
+ *
96
+ * A Chromium browser has no Electron in it. Its mark is a framework with the name of its own
97
+ * program: `Google Chrome Framework.framework` beside the program `Google Chrome`.
98
+ */
99
+ export function isElectron(given, exists) {
100
+ // A program as `ps` gives it ends with a newline, and the name of the program is part of a mark.
101
+ const program = given.trim();
102
+ const bundle = BUNDLE.exec(program)?.[1];
103
+ if (bundle === undefined) {
104
+ return false;
105
+ }
106
+ const name = basename(program);
107
+ return [ELECTRON_MARK, ...CHROMIUM_MARKS, `Contents/Frameworks/${name} Framework.framework`].some((mark) => exists(join(bundle, mark)));
108
+ }
109
+ /**
110
+ * What to say when an Electron application is joined with its switch off. `program` is the path
111
+ * of the program of the process. Absent answer: the application is not Electron, or the switch
112
+ * is on.
113
+ */
114
+ export function electronWarning(program, plan, exists) {
115
+ if (plan.electronSwitch || !isElectron(program, exists)) {
116
+ return undefined;
117
+ }
118
+ return `${plan.app} is an Electron application. It shows its elements, and it does NOTHING for a press while its accessibility switch is off. Run again without ${Flag.NO_ELECTRON_SWITCH}: the switch is then set, and it is set back when you stop.`;
119
+ }
120
+ /**
121
+ * The Chromium browsers whose page `reticle_attach_tab` can join, by the name a person sees. The
122
+ * computer reads the window of the browser; the browser realm reads the page in it.
123
+ */
124
+ const CHROMIUM_BROWSER = /\b(chrome|chromium|edge|brave|arc|dia|opera|vivaldi)\b/i;
125
+ /** What to say to an agent that joined a browser: the page in it can be joined as well. */
126
+ function pageOf(app) {
127
+ if (!CHROMIUM_BROWSER.test(app)) {
128
+ return [];
129
+ }
130
+ return [
131
+ `${app} is a web browser. This session reads its window: the tabs, the address bar and the dialogs of the browser. For the network, state, console and source of a page, also join its tab: reticle_run { tool: "reticle_attach_tab", args: { match: "<part of its address>" } }. The browser must run with --remote-debugging-port. Use both: the page to prove what the app did, the computer for what is outside the page.`,
132
+ ];
133
+ }
134
+ /**
135
+ * What the command says on standard output when it has joined: one line of JSON, for an agent
136
+ * that started it. `sessionId` is needed on a tool call only when the session is in no project:
137
+ * a session in the project of the folder is found without it.
138
+ */
139
+ export function joinedAnswer(plan, sessionId, pid, seen) {
140
+ const inProject = plan.projectId !== undefined;
141
+ const away = seen !== undefined && 0 === seen.windows && seen.windowsNotOnScreen > 0;
142
+ const bring = plan.foreground
143
+ ? `Send the action \`focus\` on the line of the application with args: { foreground: true }. It brings ${plan.app} to the front, and the screen of the person goes to it.`
144
+ : `Ask the person at the machine to bring ${plan.app} to the Space in front.`;
145
+ const session = inProject ? '' : `, sessionId: "${sessionId}"`;
146
+ return {
147
+ joined: true,
148
+ app: plan.app,
149
+ pid,
150
+ sessionId,
151
+ needsSessionId: !inProject,
152
+ foreground: plan.foreground,
153
+ ...(away
154
+ ? {
155
+ readable: false,
156
+ why: `The window of ${plan.app} is on another Space, in another set of Stage Manager, or made small, and the operating system gives no elements there. ${bring}`,
157
+ }
158
+ : {}),
159
+ next: [
160
+ `reticle_look { action: "page"${session} } gives the window as lines with refs.`,
161
+ `reticle_act_and_wait { ref, action, until${session} } acts and proves the consequence in one call.`,
162
+ 'Actions: click, fill, type, press, clear, check, uncheck, select, submit, scroll. With args.foreground: true also dblclick, hover, drag, focus and a real click.',
163
+ 'Prefer a signal for `until` when the action writes a file or changes a setting: file.written, disk.wrote, settings.changed, clipboard.changed.',
164
+ `${plan.app} is on the computer of a person, with their real mail, money and files. Do not press a control that sends, pays, buys, posts or deletes unless the person asked for it.`,
165
+ ...pageOf(plan.app),
166
+ ],
167
+ };
168
+ }
169
+ /** The names a refusal gives when nothing is near the name that was asked for. */
170
+ const NAMES_GIVEN = 12;
171
+ /**
172
+ * The application a person means by a name. The name a person sees is often not the name of the
173
+ * process: "Visual Studio Code" runs as "Code". A name that fits nothing gets the names that are
174
+ * near it, or the names of what is open.
175
+ */
176
+ export function pickApp(wanted, running) {
177
+ const fold = (text) => text.toLowerCase();
178
+ const is = (app, same) => same(app.name, wanted) || same(app.process, wanted);
179
+ // Of several with the same name, the one that was started last: it is the one a person just
180
+ // opened, and an old one can be an application that is ending.
181
+ const newest = [...running].sort((a, b) => (b.launched ?? 0) - (a.launched ?? 0));
182
+ const found = newest.find((app) => is(app, (a, b) => a === b)) ??
183
+ newest.find((app) => is(app, (a, b) => fold(a) === fold(b)));
184
+ if (found !== undefined) {
185
+ return { pid: found.pid };
186
+ }
187
+ // The applications a person opens come first: the helpers of the system are many, and a list
188
+ // that is cut after them names nothing that can be joined.
189
+ const person = [...running].sort((a, b) => Number(true === b.regular) - Number(true === a.regular));
190
+ const names = [...new Set(person.map((app) => app.name).filter((name) => name.length > 0))];
191
+ const near = names.filter((name) => fold(name).includes(fold(wanted)));
192
+ const hint = near.length > 0
193
+ ? `Did you mean: ${near.join(', ')}?`
194
+ : `These are open: ${names.slice(0, NAMES_GIVEN).join(', ')}.`;
195
+ return { error: `No application named ${wanted} is open. ${hint}` };
196
+ }
197
+ /** The file of the person at the machine: limits that no flag of the command can lift. */
198
+ export const OWNER_SETTINGS_FILE = 'computer.json';
199
+ /** The file that is there after Stop in the window: no application is joined while it is. */
200
+ export const STOPPED_FILE = 'computer.stopped';
201
+ function ownerSettings(text) {
202
+ let parsed;
203
+ try {
204
+ parsed = text === undefined ? {} : JSON.parse(text);
205
+ }
206
+ catch {
207
+ parsed = {};
208
+ }
209
+ const record = 'object' === typeof parsed && null !== parsed ? parsed : {};
210
+ return { backgroundOnly: true === record['backgroundOnly'], hud: true === record['hud'] };
211
+ }
212
+ /**
213
+ * The plan with the limits of the person at the machine. An agent starts the command, so an
214
+ * agent picks its flags. These limits are in a file of the person's own and a flag cannot lift
215
+ * them: `backgroundOnly` forbids the real pointer, and `hud` keeps the window and the pointer of
216
+ * the realm on the screen. After Stop in the window, no application is joined until the person
217
+ * removes the file that Stop wrote.
218
+ *
219
+ * ponytail: a file in the home folder. A program with a shell can change a file, so this states
220
+ * what the person wants and makes a change to it a deliberate act. It is not a wall.
221
+ */
222
+ export function withOwnerLimits(plan, settingsText, stoppedAt, stoppedPath) {
223
+ if (stoppedAt !== undefined) {
224
+ return {
225
+ error: `The person at this machine stopped Reticle in its window (${stoppedAt.trim()}). Reticle joins no application until they remove the file ${stoppedPath}. Do not remove it for them: tell them what you wanted to do.`,
226
+ };
227
+ }
228
+ const limits = ownerSettings(settingsText);
229
+ return {
230
+ ...plan,
231
+ foreground: plan.foreground && !limits.backgroundOnly,
232
+ hud: plan.hud || limits.hud,
233
+ };
234
+ }