@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
@@ -0,0 +1,62 @@
1
+ import { ActKind } from '../driver.js';
2
+ import type { ActOutcome } from '../driver.js';
3
+ import type { Placed, UiNode } from '../ui-node.js';
4
+ import type { WindowAnswer } from './window.js';
5
+ import type { Seen } from './seen.js';
6
+ /** The keys that select all the text of a field, and that remove what is selected. */
7
+ export declare const SELECT_ALL = "Meta+a";
8
+ export declare const DELETE = "Backspace";
9
+ export declare const ESCAPE = "Escape";
10
+ /** The choices a refusal names. A long menu is not put in an error. */
11
+ export declare const CHOICES_NAMED = 20;
12
+ /** The roles whose value is the text a fill asks for. A slider's value is a number in another form. */
13
+ export declare const TEXT_ROLES: ReadonlySet<string>;
14
+ /** The value an element holds after an action. */
15
+ export declare function heldBy(outcome: ActOutcome, key: string): string;
16
+ /**
17
+ * Where a field is after it took a value, when it is not at its key any more: an application can
18
+ * put the field in another group as it shows results. The answer is the one element with the
19
+ * same role, name and identifier that holds exactly the value that was set. With two such
20
+ * elements, or none, there is no answer: a guess would give the ref to another element.
21
+ */
22
+ export declare function movedTo(outcome: ActOutcome, target: Placed, value: string): Placed | undefined;
23
+ export declare const KIND_OF: Readonly<Partial<Record<string, ActKind>>>;
24
+ /**
25
+ * The kinds that use the real pointer or bring the application to the front. Each takes the
26
+ * pointer or the keyboard of the person at the machine, so a caller asks for it by name.
27
+ */
28
+ export declare const FOREGROUND_ONLY: ReadonlySet<string>;
29
+ /** The actions that carry their own value: a caller gives none. */
30
+ export declare const VALUE_OF: Readonly<Partial<Record<string, string>>>;
31
+ /** The state each of these actions asks for. */
32
+ export declare const WANTS_CHECKED: Readonly<Partial<Record<string, boolean>>>;
33
+ export declare const BOX_ROLES: ReadonlySet<string>;
34
+ export declare const isChecked: (node: UiNode) => boolean;
35
+ /** The actions this realm does. The peer declares exactly these to the bridge. */
36
+ export declare const PEER_ACTIONS: readonly string[];
37
+ /**
38
+ * The identifier of the target, as the server reads it to anchor a saved step. When several
39
+ * elements on the screen share it, how many, and which of them the target is.
40
+ */
41
+ export declare function testidOf(target: Seen, before: UiNode): Record<string, unknown>;
42
+ export declare const SettleReason: {
43
+ readonly TIMEOUT: "timeout";
44
+ };
45
+ /** The answer to one action, in the shape the server reads. */
46
+ export interface ActResult {
47
+ ok: true;
48
+ ref: string;
49
+ action: string;
50
+ /** False when nothing was sent: the element was in the state the caller asked for. */
51
+ dispatched: boolean;
52
+ settled: boolean;
53
+ settleReason: string | null;
54
+ effect: Record<string, unknown>;
55
+ role: string;
56
+ name: string;
57
+ testid?: string;
58
+ testidOf?: number;
59
+ testidNth?: number;
60
+ /** For `window`: the window after the change. */
61
+ window?: WindowAnswer;
62
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * What the peer knows about the actions of a form: which action of a tool is which kind of
3
+ * action of the realm, what a field holds after an action, and the identifier of an element.
4
+ */
5
+ import { ActionType, ElementState } from '@reticlehq/core';
6
+ import { ActKind } from '../driver.js';
7
+ import { UiRole, place } from '../ui-node.js';
8
+ import { see } from './seen.js';
9
+ /** The keys that select all the text of a field, and that remove what is selected. */
10
+ export const SELECT_ALL = 'Meta+a';
11
+ export const DELETE = 'Backspace';
12
+ export const ESCAPE = 'Escape';
13
+ /** The choices a refusal names. A long menu is not put in an error. */
14
+ export const CHOICES_NAMED = 20;
15
+ /** The roles whose value is the text a fill asks for. A slider's value is a number in another form. */
16
+ export const TEXT_ROLES = new Set([UiRole.TEXTBOX, UiRole.COMBOBOX]);
17
+ /** The value an element holds after an action. */
18
+ export function heldBy(outcome, key) {
19
+ return place(outcome.after.root).find((p) => p.key === key)?.node.value ?? '';
20
+ }
21
+ /**
22
+ * Where a field is after it took a value, when it is not at its key any more: an application can
23
+ * put the field in another group as it shows results. The answer is the one element with the
24
+ * same role, name and identifier that holds exactly the value that was set. With two such
25
+ * elements, or none, there is no answer: a guess would give the ref to another element.
26
+ */
27
+ export function movedTo(outcome, target, value) {
28
+ const after = place(outcome.after.root);
29
+ if (after.some((p) => p.key === target.key)) {
30
+ return undefined;
31
+ }
32
+ const same = after.filter((p) => p.node.role === target.node.role &&
33
+ p.node.name === target.node.name &&
34
+ p.node.id === target.node.id &&
35
+ p.node.value === value);
36
+ return 1 === same.length ? same[0] : undefined;
37
+ }
38
+ export const KIND_OF = {
39
+ [ActionType.CLICK]: ActKind.PRESS,
40
+ [ActionType.FILL]: ActKind.SET,
41
+ [ActionType.TYPE]: ActKind.TYPE,
42
+ [ActionType.PRESS]: ActKind.KEY,
43
+ [ActionType.CLEAR]: ActKind.SET,
44
+ [ActionType.CHECK]: ActKind.PRESS,
45
+ [ActionType.UNCHECK]: ActKind.PRESS,
46
+ [ActionType.SUBMIT]: ActKind.KEY,
47
+ [ActionType.DBLCLICK]: ActKind.DBLCLICK,
48
+ [ActionType.HOVER]: ActKind.HOVER,
49
+ [ActionType.DRAG]: ActKind.DRAG,
50
+ [ActionType.FOCUS]: ActKind.RAISE,
51
+ };
52
+ /**
53
+ * The kinds that use the real pointer or bring the application to the front. Each takes the
54
+ * pointer or the keyboard of the person at the machine, so a caller asks for it by name.
55
+ */
56
+ export const FOREGROUND_ONLY = new Set([
57
+ ActKind.CLICK,
58
+ ActKind.DBLCLICK,
59
+ ActKind.RIGHTCLICK,
60
+ ActKind.HOVER,
61
+ ActKind.DRAG,
62
+ ActKind.RAISE,
63
+ ActKind.WHEEL,
64
+ ]);
65
+ /** The actions that carry their own value: a caller gives none. */
66
+ export const VALUE_OF = {
67
+ [ActionType.CLEAR]: '',
68
+ [ActionType.SUBMIT]: 'Return',
69
+ };
70
+ /** The state each of these actions asks for. */
71
+ export const WANTS_CHECKED = {
72
+ [ActionType.CHECK]: true,
73
+ [ActionType.UNCHECK]: false,
74
+ };
75
+ export const BOX_ROLES = new Set([UiRole.CHECKBOX, UiRole.RADIO]);
76
+ export const isChecked = (node) => node.states.includes(ElementState.CHECKED);
77
+ /** The actions this realm does. The peer declares exactly these to the bridge. */
78
+ export const PEER_ACTIONS = [
79
+ ...Object.keys(KIND_OF),
80
+ ActionType.SCROLL,
81
+ ActionType.SELECT,
82
+ ActionType.WINDOW,
83
+ ];
84
+ /**
85
+ * The identifier of the target, as the server reads it to anchor a saved step. When several
86
+ * elements on the screen share it, how many, and which of them the target is.
87
+ */
88
+ export function testidOf(target, before) {
89
+ const id = target.node.id;
90
+ if (id === undefined) {
91
+ return {};
92
+ }
93
+ const sharing = see(before).filter((s) => s.node.id === id);
94
+ if (sharing.length < 2) {
95
+ return { testid: id };
96
+ }
97
+ return {
98
+ testid: id,
99
+ testidOf: sharing.length,
100
+ testidNth: sharing.findIndex((s) => s.key === target.key),
101
+ };
102
+ }
103
+ export const SettleReason = { TIMEOUT: 'timeout' };
@@ -0,0 +1,12 @@
1
+ import type { UiNode } from '../ui-node.js';
2
+ /** Why the action is refused, or undefined when it may go. */
3
+ export declare function linkSwitchRefusal(node: Pick<UiNode, 'role' | 'name' | 'id'>, action: string, more: Record<string, unknown>): string | undefined;
4
+ /**
5
+ * Why the action on the target is refused, or undefined when it may go: a switch that links the
6
+ * machine, or an outward action that the journey (`allowed`) does not ask for. The dialog's name is
7
+ * part of the meaning: "OK" in "Delete the project?" is a delete.
8
+ */
9
+ export declare function refusalOf(target: {
10
+ node: Pick<UiNode, 'role' | 'name' | 'id'>;
11
+ dialog: string;
12
+ }, action: string, more: Record<string, unknown>, allowed: readonly string[] | undefined): string | undefined;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The switches that link the machine to the world: Wi-Fi, Bluetooth, Airplane Mode, the network.
3
+ * Control Centre is readable, so a check or a click reaches them. Off, Wi-Fi cuts the link of the
4
+ * agent in the middle of its task, and Bluetooth can take the keyboard and the mouse of the person
5
+ * at the machine. An action that can turn one off is refused unless the caller confirms it. To
6
+ * turn one on is not refused.
7
+ */
8
+ import { ActionType, DANGEROUS_ACTION_CONFIRM_ARG, outwardActionOf, outwardRefusal, } from '@reticlehq/core';
9
+ import { UiRole } from '../ui-node.js';
10
+ const LINK = /^(?:wi[‑-]?fi|bluetooth|airplane mode|network|ethernet)\b/i;
11
+ /** The identifiers Control Centre gives these switches. They are the same in every language. */
12
+ const LINK_ID = /^controlcenter-(?:wifi|bluetooth|airplane|network|ethernet)\b/;
13
+ /** Why the action is refused, or undefined when it may go. */
14
+ export function linkSwitchRefusal(node, action, more) {
15
+ if (action === ActionType.CHECK ||
16
+ // Only the switch. The item of the menu bar ("Wi-Fi, connected") opens a menu and cuts nothing.
17
+ node.role !== UiRole.CHECKBOX ||
18
+ // The words, and the identifier: macOS names Wi-Fi "WLAN" in German.
19
+ !(LINK.test(node.name.trim()) || LINK_ID.test(node.id ?? '')) ||
20
+ true === more[DANGEROUS_ACTION_CONFIRM_ARG]) {
21
+ return undefined;
22
+ }
23
+ return `${node.role} "${node.name}" links this machine to the network or to its keyboard and mouse. Turned off, it can cut your own link in the middle of the task. Do it only when the person asked for it, and then send args.${DANGEROUS_ACTION_CONFIRM_ARG}: true.`;
24
+ }
25
+ /**
26
+ * Why the action on the target is refused, or undefined when it may go: a switch that links the
27
+ * machine, or an outward action that the journey (`allowed`) does not ask for. The dialog's name is
28
+ * part of the meaning: "OK" in "Delete the project?" is a delete.
29
+ */
30
+ export function refusalOf(target, action, more, allowed) {
31
+ const outward = allowed === undefined
32
+ ? undefined
33
+ : outwardActionOf(`${target.node.name} ${target.dialog}`, target.node.role);
34
+ if (outward !== undefined && allowed?.includes(outward) !== true) {
35
+ return outwardRefusal(outward);
36
+ }
37
+ return linkSwitchRefusal(target.node, action, more);
38
+ }
@@ -0,0 +1,43 @@
1
+ import type { WorkspacePort } from '@reticlehq/terminal';
2
+ import type { UiDriver } from '../driver.js';
3
+ import type { HudPort } from '../hud/port.js';
4
+ /**
5
+ * How long to wait before the next look at the tree.
6
+ *
7
+ * A look is a whole read. For a small window it takes a few milliseconds. For a window with
8
+ * thousands of elements it takes hundreds, and four of those in a second would load the
9
+ * application more than the agent does. So the wait is at least ten times the last read: the
10
+ * looks take a tenth of the time at most, and a large window is looked at less often.
11
+ */
12
+ export declare function nextLookMs(everyMs: number, lastReadMs: number): number;
13
+ export interface PeerInput {
14
+ /** `ws://localhost:4400/reticle`. */
15
+ url: string;
16
+ /** The pairing token of the bridge, when it has one. */
17
+ token?: string;
18
+ sessionId: string;
19
+ /** Always given: two applications have no web origin to tell them apart. */
20
+ projectId: string;
21
+ driver: UiDriver;
22
+ /** Folders to watch for files an action writes. */
23
+ workspace?: WorkspacePort;
24
+ /** How often the watched folders are looked at between actions. The default is one second. */
25
+ filesEveryMs?: number;
26
+ /** How often the tree is looked at between actions. The default is a quarter of a second. */
27
+ treeEveryMs?: number;
28
+ /** A known reason why a press can do nothing in this application. See `PeerCommandsDeps`. */
29
+ noEffectNote?: string;
30
+ /** False: never the foreground, whatever a caller asks. See `PeerCommandsDeps`. */
31
+ foreground?: boolean;
32
+ /** What the person at the machine sees of the realm. See `PeerCommandsDeps`. */
33
+ hud?: HudPort;
34
+ /** How long to wait before the first new dial when the bridge goes away. The default is one second. */
35
+ retryMs?: number;
36
+ now: () => number;
37
+ }
38
+ export interface Peer {
39
+ /** Resolves when the socket is open and the peer has announced itself. */
40
+ ready: Promise<void>;
41
+ close(): void;
42
+ }
43
+ export declare function connectPeer(input: PeerInput): Peer;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Joins the bridge as a peer, the way the SDK in a web page does, so every tool an agent has for
3
+ * a page reaches a desktop application. There is no code in the application.
4
+ */
5
+ import { COMPUTER_RUNTIME, CONTRACT_FINGERPRINT, CONTRACT_PARTS, EventType, MessageKind, PlatformProfile, RETICLE_PROTOCOL_VERSION, } from '@reticlehq/core';
6
+ import { WebSocket } from 'ws';
7
+ import { PEER_ACTIONS, PEER_COMMANDS, PeerCommands } from './commands.js';
8
+ /** For a bridge with no token: it admits a dial with no Origin only when it has one. */
9
+ const ORIGIN = 'http://localhost';
10
+ const ADAPTER = 'computer';
11
+ /** A session with no word for 12 s reads as throttled. The SDK in a page sends this at the same rate. */
12
+ const HEARTBEAT_MS = 5000;
13
+ const FILES_EVERY_MS = 1000;
14
+ const TREE_EVERY_MS = 250;
15
+ /** A look may take one part in this many of the time. */
16
+ const LOOK_SHARE = 10;
17
+ const RETRY_MS = 1000;
18
+ const MAX_RETRY_MS = 10_000;
19
+ /** The bridge drops a result whose error is longer than 4,096 characters, and the command then waits. */
20
+ const MAX_ERROR = 4000;
21
+ const HealthReason = { CONNECT: 'connect', HEARTBEAT: 'heartbeat' };
22
+ const EVENTS = [
23
+ EventType.DOM_ADDED,
24
+ EventType.DOM_REMOVED,
25
+ EventType.DOM_ATTR,
26
+ EventType.PAGE_HEALTH,
27
+ ];
28
+ /**
29
+ * How long to wait before the next look at the tree.
30
+ *
31
+ * A look is a whole read. For a small window it takes a few milliseconds. For a window with
32
+ * thousands of elements it takes hundreds, and four of those in a second would load the
33
+ * application more than the agent does. So the wait is at least ten times the last read: the
34
+ * looks take a tenth of the time at most, and a large window is looked at less often.
35
+ */
36
+ export function nextLookMs(everyMs, lastReadMs) {
37
+ return Math.max(everyMs, lastReadMs * LOOK_SHARE);
38
+ }
39
+ /** The names this peer speaks that the bridge also knows. An unknown name reads as version skew. */
40
+ function known(mine, theirs) {
41
+ return mine.filter((name) => theirs.includes(name));
42
+ }
43
+ export function connectPeer(input) {
44
+ let socket;
45
+ let closed = false;
46
+ let joinedOnce = false;
47
+ let retryMs = input.retryMs ?? RETRY_MS;
48
+ let retry;
49
+ let heartbeat;
50
+ let files;
51
+ let tree;
52
+ const send = (message) => {
53
+ if (socket?.readyState === WebSocket.OPEN) {
54
+ socket.send(JSON.stringify(message));
55
+ }
56
+ };
57
+ const emit = (type, data) => {
58
+ send({
59
+ kind: MessageKind.EVENT,
60
+ event: { t: input.now(), type, sessionId: input.sessionId, data },
61
+ });
62
+ };
63
+ // One for the life of the peer, not one for each connection: a ref that the agent holds must
64
+ // still be the same element after the bridge comes back.
65
+ const commands = new PeerCommands({
66
+ driver: input.driver,
67
+ emit,
68
+ ...(input.workspace === undefined ? {} : { workspace: input.workspace }),
69
+ ...(input.noEffectNote === undefined ? {} : { noEffectNote: input.noEffectNote }),
70
+ ...(input.foreground === undefined ? {} : { foreground: input.foreground }),
71
+ ...(input.hud === undefined ? {} : { hud: input.hud }),
72
+ });
73
+ const health = (reason) => {
74
+ emit(EventType.PAGE_HEALTH, {
75
+ hidden: false,
76
+ focused: true,
77
+ reason,
78
+ runtime: COMPUTER_RUNTIME,
79
+ });
80
+ };
81
+ const stopTimers = () => {
82
+ clearInterval(heartbeat);
83
+ clearInterval(files);
84
+ clearTimeout(tree);
85
+ };
86
+ const announce = () => {
87
+ const { app, pid } = input.driver.subject();
88
+ send({
89
+ kind: MessageKind.HELLO,
90
+ protocolVersion: RETICLE_PROTOCOL_VERSION,
91
+ sessionId: input.sessionId,
92
+ url: `app://${encodeURIComponent(app)}/`,
93
+ title: `${app} (${String(pid)})`,
94
+ adapters: [ADAPTER],
95
+ projectId: input.projectId,
96
+ ...(input.token === undefined ? {} : { token: input.token }),
97
+ platform: PlatformProfile.NATIVE,
98
+ hasCapabilities: false,
99
+ sourceMapping: false,
100
+ commands: [...PEER_COMMANDS],
101
+ contract: CONTRACT_FINGERPRINT,
102
+ contractParts: {
103
+ commands: known(PEER_COMMANDS, CONTRACT_PARTS.commands),
104
+ events: known(EVENTS, CONTRACT_PARTS.events),
105
+ actions: known(PEER_ACTIONS, CONTRACT_PARTS.actions),
106
+ },
107
+ });
108
+ health(HealthReason.CONNECT);
109
+ heartbeat = setInterval(() => {
110
+ health(HealthReason.HEARTBEAT);
111
+ }, HEARTBEAT_MS);
112
+ heartbeat.unref();
113
+ const look = (waitMs) => {
114
+ tree = setTimeout(() => {
115
+ const started = input.now();
116
+ const again = () => {
117
+ look(nextLookMs(input.treeEveryMs ?? TREE_EVERY_MS, input.now() - started));
118
+ };
119
+ commands.sendTreeChanges().then(again, again);
120
+ }, waitMs);
121
+ tree.unref();
122
+ };
123
+ look(input.treeEveryMs ?? TREE_EVERY_MS);
124
+ if (input.workspace !== undefined) {
125
+ // ponytail: a whole look at the folders each time. Watch them for changes when a folder
126
+ // is large enough for the look to cost more than the wait.
127
+ files = setInterval(() => {
128
+ commands.sendFileChanges();
129
+ }, input.filesEveryMs ?? FILES_EVERY_MS);
130
+ files.unref();
131
+ }
132
+ };
133
+ const onMessage = (raw) => {
134
+ if (!Buffer.isBuffer(raw)) {
135
+ return;
136
+ }
137
+ const message = JSON.parse(raw.toString('utf8'));
138
+ const id = message['id'];
139
+ const name = message['name'];
140
+ if (message['kind'] !== MessageKind.COMMAND ||
141
+ typeof id !== 'string' ||
142
+ typeof name !== 'string') {
143
+ return;
144
+ }
145
+ const args = message['args'];
146
+ const outward = message['outward'];
147
+ const allowed = 'object' === typeof outward &&
148
+ outward !== null &&
149
+ 'allowed' in outward &&
150
+ Array.isArray(outward.allowed)
151
+ ? outward.allowed.map(String)
152
+ : undefined;
153
+ commands
154
+ .answer(name, 'object' === typeof args && args !== null ? args : {}, allowed)
155
+ .then((result) => {
156
+ send({ kind: MessageKind.COMMAND_RESULT, id, ok: true, result });
157
+ }, (error) => {
158
+ const words = error instanceof Error ? error.message : String(error);
159
+ send({
160
+ kind: MessageKind.COMMAND_RESULT,
161
+ id,
162
+ ok: false,
163
+ error: words.slice(0, MAX_ERROR),
164
+ });
165
+ });
166
+ };
167
+ /**
168
+ * Dials the bridge. When the bridge goes away after the peer joined it once, the peer dials
169
+ * again, and waits longer each time up to ten seconds. The daemon ends when it is idle and
170
+ * starts again on the next tool call, and a peer that stayed gone made the application
171
+ * disappear for the agent with no word.
172
+ */
173
+ const dial = (onFirst) => {
174
+ // With a token, no Origin: the bridge then knows that a program dialled, and not a page. A
175
+ // page cannot leave the Origin out, so it cannot be taken for this realm. A bridge with no
176
+ // token admits only a dial that has an Origin; the session then gets no rule of its own.
177
+ const next = new WebSocket(input.url, input.token === undefined ? { origin: ORIGIN } : {});
178
+ socket = next;
179
+ next.once('open', () => {
180
+ joinedOnce = true;
181
+ retryMs = input.retryMs ?? RETRY_MS;
182
+ announce();
183
+ onFirst?.resolve();
184
+ });
185
+ next.on('message', onMessage);
186
+ // An error before the first join is the caller's to know: the bridge is not there. After
187
+ // it, the close that follows starts the next dial.
188
+ next.on('error', (error) => {
189
+ if (!joinedOnce) {
190
+ onFirst?.reject(error);
191
+ }
192
+ });
193
+ next.on('close', () => {
194
+ stopTimers();
195
+ if (closed || !joinedOnce) {
196
+ return;
197
+ }
198
+ retry = setTimeout(() => {
199
+ dial();
200
+ }, retryMs);
201
+ retryMs = Math.min(retryMs * 2, MAX_RETRY_MS);
202
+ });
203
+ };
204
+ const ready = new Promise((resolve, reject) => {
205
+ dial({ resolve, reject });
206
+ });
207
+ return {
208
+ ready,
209
+ close: () => {
210
+ closed = true;
211
+ clearTimeout(retry);
212
+ stopTimers();
213
+ socket?.close();
214
+ },
215
+ };
216
+ }
@@ -0,0 +1,97 @@
1
+ import { ActKind } from '../driver.js';
2
+ import type { PictureText } from '../driver.js';
3
+ import type { UiNode } from '../ui-node.js';
4
+ /** Where a picture of the window was taken, and its pixels for each point of the screen. */
5
+ export interface Picture {
6
+ /** What the picture shows on the screen: the window, or the whole display. */
7
+ window: readonly [number, number, number, number];
8
+ scale: number;
9
+ /** The application's window when the picture was taken. */
10
+ appWindow: readonly [number, number, number, number];
11
+ /** Where each element on the screen was when the picture was taken, by its key. */
12
+ places?: ReadonlyMap<string, readonly number[]>;
13
+ /** Where each window of the application was when the picture was taken. */
14
+ windows?: readonly (readonly number[])[];
15
+ }
16
+ /**
17
+ * True when the window that holds the target is not at a place where a window of the application
18
+ * was when the picture was taken. Any window: an application with several windows (Finder) was
19
+ * refused for each one but its largest, which is the one the picture remembered.
20
+ */
21
+ export declare function windowMoved(picture: Picture | undefined, now: readonly number[] | undefined): boolean;
22
+ /** The frame of each window of the application. */
23
+ export declare function windowFramesOf(root: UiNode): (readonly number[])[];
24
+ /** The place of each element on the screen, by its key. */
25
+ export declare function placesOf(root: UiNode): Map<string, readonly number[]>;
26
+ /**
27
+ * True when the content of the window moved after the picture: an element that has the same
28
+ * size is at another place, as the rows of a list that scrolled. A value that changes in its
29
+ * place, as a clock, does not move the content.
30
+ */
31
+ export declare function contentMoved(then: ReadonlyMap<string, readonly number[]> | undefined, now: ReadonlyMap<string, readonly number[]>): boolean;
32
+ /**
33
+ * The point on the screen for a point of the last picture, in its pixels (`args.point`).
34
+ * Only the kinds that use the real pointer take a point. Absent answer: no point was given.
35
+ */
36
+ export declare function pointOnScreen(picture: Picture | undefined, at: unknown, kind: ActKind): string | undefined;
37
+ /** What the helper says when the terminal may not record the screen. */
38
+ export declare const NO_SCREEN_RECORDING = "no-screen-recording-permission";
39
+ /** The kinds that can go to a point of a picture, and not to the middle of an element. */
40
+ export declare const POINT_KINDS: ReadonlySet<string>;
41
+ type Frame = readonly [number, number, number, number];
42
+ /** Whether the act names a point of a picture: the picture can be old, so it is checked. */
43
+ export declare function usesPicture(more: Record<string, unknown>): boolean;
44
+ /**
45
+ * Where the pointer goes, as "x,y" on the screen: a point of the last picture (`point`), or a
46
+ * point of the element's box (`at`, fractions from 0 to 1, as in a page). Absent: the middle.
47
+ */
48
+ export declare function pointFor(picture: Picture | undefined, more: Record<string, unknown>, kind: ActKind, frame: Frame | undefined): string | undefined;
49
+ /**
50
+ * The value of a drag for the helper: "x,y" of the end, or "x,y,x,y" from a start to the end. The
51
+ * end is a point of the last picture (`toPoint`), the middle of another element (`toRef`), or a
52
+ * point of the element's own box (`to`), as a slider is dragged.
53
+ */
54
+ export declare function dragValue(picture: Picture | undefined, more: Record<string, unknown>, frame: Frame | undefined, ontoFrame: Frame | undefined): string;
55
+ /**
56
+ * The kind of action of the realm for an action of a tool. A click with the right button is the
57
+ * menu a right-click gives: asked for by name in the background, and the real button in the
58
+ * foreground. A click in the foreground is the real pointer.
59
+ */
60
+ export declare function kindFor(action: string, more: Record<string, unknown>, foreground: boolean): ActKind | undefined;
61
+ /** What to say when an action needs the real pointer and the caller did not ask for it. */
62
+ export declare function needsForeground(action: string, app: string): string;
63
+ type Spot = readonly [number, number];
64
+ /**
65
+ * Where the pointer of the HUD goes for an action: the place it starts, and for a drag the place
66
+ * it ends, as a hand presses at one place and lets go at another. The start is the point of the
67
+ * action when it has one, or the middle of the element. A drag gives "x,y" (the end) or "x,y,x,y"
68
+ * (the start and the end), and a wheel gives "lines,x,y".
69
+ */
70
+ export declare function pointerPath(kind: ActKind, value: string | undefined, frame: readonly [number, number, number, number] | undefined): {
71
+ start?: Spot;
72
+ end?: Spot;
73
+ };
74
+ /** A drag along points of the picture. */
75
+ export declare const PATH_ARG = "path";
76
+ /** How long the button stays down before the pointer moves or lets go, in milliseconds. */
77
+ export declare const HOLD_ARG = "holdMs";
78
+ /**
79
+ * Whether the helper compares pictures of the window for this action. Only for a point of a
80
+ * picture or an element that can be a canvas: each picture costs a wait for the window to draw,
81
+ * and a button shows its effect in its elements.
82
+ */
83
+ export declare function wantsPixels(role: string, more: Record<string, unknown>): boolean;
84
+ export declare function handOf(kind: ActKind, more: Record<string, unknown>, pixels?: boolean): string;
85
+ /**
86
+ * The words of a picture for the answer: a canvas has no elements, and the box of a word is a
87
+ * point an agent can click. Declared: `textsCut` counts the words left out, unsure or past the
88
+ * most.
89
+ */
90
+ export declare function wordsOfPicture(read: readonly PictureText[] | undefined): {
91
+ texts?: {
92
+ text: string;
93
+ box: readonly number[];
94
+ }[];
95
+ textsCut?: number;
96
+ };
97
+ export {};