@reticlehq/computer 0.0.0-stage → 3.11.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 (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +237 -2
  4. package/bin/attach.mjs +333 -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 +16 -0
  54. package/dist/win/helper-launch.js +57 -0
  55. package/native/linux/Dockerfile +22 -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,355 @@
1
+ /**
2
+ * The macOS driver: it runs the `reticle-ax` helper and turns its answers into the driver port.
3
+ */
4
+ import { spawn } from 'node:child_process';
5
+ import { rmSync } from 'node:fs';
6
+ import { Socket } from 'node:net';
7
+ import { tmpdir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import { RETICLE_CAPTURE_FILE_PREFIX } from '@reticlehq/core';
10
+ import { z } from 'zod';
11
+ import { ActRefusal, Reach } from '../driver.js';
12
+ import { AxNodeSchema, fromAx } from './from-ax.js';
13
+ const Command = {
14
+ TREE: 'tree',
15
+ ACT: 'act',
16
+ REACH: 'reach',
17
+ CAPTURE: 'capture',
18
+ TEXTS: 'texts',
19
+ SWITCH: 'web-tree',
20
+ };
21
+ const TRY_SWITCH = 'try';
22
+ /** The word that asks the helper for the whole display, and not the window only. */
23
+ const SCREEN = 'screen';
24
+ const HelperError = {
25
+ NOT_TRUSTED: 'not-trusted',
26
+ APP_GONE: 'app-gone',
27
+ SCREEN_LOCKED: 'screen-locked',
28
+ OWN_WINDOW: 'own-window',
29
+ };
30
+ const ErrorSchema = z.object({ error: z.string() });
31
+ const TreeSchema = z.object({
32
+ tree: AxNodeSchema,
33
+ unread: z.number(),
34
+ windowsNotOnScreen: z.number().optional(),
35
+ });
36
+ const TextsSchema = z.object({
37
+ texts: z.array(z.object({ text: z.string(), box: z.array(z.number()).length(4), confidence: z.number() })),
38
+ });
39
+ const CaptureSchema = z.object({
40
+ ok: z.boolean(),
41
+ reason: z.string().optional(),
42
+ window: z.array(z.number()).optional(),
43
+ scale: z.number().optional(),
44
+ appWindow: z.array(z.number()).optional(),
45
+ });
46
+ const ReachSchema = z.object({ reach: z.enum(Reach), detail: z.string().optional() });
47
+ const RefusedSchema = z.object({ refused: z.enum(ActRefusal), detail: z.string().optional() });
48
+ const ActedSchema = z.object({
49
+ delivered: z.boolean(),
50
+ reachable: z.boolean(),
51
+ settled: z.boolean(),
52
+ before: AxNodeSchema,
53
+ after: AxNodeSchema,
54
+ unreadBefore: z.number(),
55
+ unreadAfter: z.number(),
56
+ appGone: z.boolean().optional(),
57
+ bytesWritten: z.number().optional(),
58
+ clipboardChanged: z.boolean().optional(),
59
+ pixels: z
60
+ .object({
61
+ changed: z.number(),
62
+ box: z.array(z.number()).length(4).optional(),
63
+ moving: z.number().optional(),
64
+ })
65
+ .optional(),
66
+ windowState: z
67
+ .object({
68
+ minimized: z.boolean(),
69
+ fullscreen: z.boolean(),
70
+ frame: z.array(z.number()).length(4).optional(),
71
+ wanted: z.array(z.number()).length(4).optional(),
72
+ })
73
+ .optional(),
74
+ settingsChanged: z
75
+ .array(z.object({
76
+ key: z.string(),
77
+ old: z.string(),
78
+ new: z.string(),
79
+ cut: z.boolean().optional(),
80
+ }))
81
+ .optional(),
82
+ });
83
+ /** The state of an arranged window, with its frame as a tuple when the helper read one. */
84
+ function windowStateOf(state) {
85
+ const tuple = (values) => {
86
+ const [x, y, width, height] = values ?? [];
87
+ return x === undefined || y === undefined || width === undefined || height === undefined
88
+ ? undefined
89
+ : [x, y, width, height];
90
+ };
91
+ const frame = tuple(state.frame);
92
+ const wanted = tuple(state.wanted);
93
+ return {
94
+ minimized: state.minimized,
95
+ fullscreen: state.fullscreen,
96
+ ...(frame === undefined ? {} : { frame }),
97
+ ...(wanted === undefined ? {} : { wanted }),
98
+ };
99
+ }
100
+ const SERVE = 'serve';
101
+ const HELPER_EXITED = JSON.stringify({ error: 'the helper process ended' });
102
+ /**
103
+ * One helper process for the life of a driver. A command is one line to it, and its answer is one
104
+ * line back.
105
+ *
106
+ * A process for each command took about 70 ms to read a small window, and 5 ms of that was the
107
+ * read: the rest was the start of the process and its first word with the application.
108
+ *
109
+ * Commands go one at a time. The helper answers in order, and an answer has no name on it.
110
+ */
111
+ export function servingHelper(prefix = []) {
112
+ let child;
113
+ let buffered = '';
114
+ const waiting = [];
115
+ let last = Promise.resolve();
116
+ const start = (file) => {
117
+ const started = spawn(file, [...prefix, SERVE]);
118
+ started.stdout.setEncoding('utf8');
119
+ started.stdout.on('data', (chunk) => {
120
+ buffered += chunk;
121
+ for (let end = buffered.indexOf('\n'); end !== -1; end = buffered.indexOf('\n')) {
122
+ waiting.shift()?.(buffered.slice(0, end));
123
+ buffered = buffered.slice(end + 1);
124
+ }
125
+ });
126
+ started.on('exit', () => {
127
+ child = undefined;
128
+ buffered = '';
129
+ for (const answer of waiting.splice(0)) {
130
+ answer(HELPER_EXITED);
131
+ }
132
+ });
133
+ return started;
134
+ };
135
+ // The helper keeps the program open while a command waits for its answer, and only then. A
136
+ // program whose one open thing was a helper with no hold on it ended in the middle of a read.
137
+ const hold = (on) => {
138
+ if (child === undefined) {
139
+ return;
140
+ }
141
+ for (const part of [child, child.stdin, child.stdout, child.stderr]) {
142
+ if (part instanceof Socket || part === child) {
143
+ if (on) {
144
+ part.ref();
145
+ }
146
+ else {
147
+ part.unref();
148
+ }
149
+ }
150
+ }
151
+ };
152
+ return (file, args) => {
153
+ const answer = last.then(() => new Promise((resolve) => {
154
+ child ??= start(file);
155
+ hold(true);
156
+ waiting.push((line) => {
157
+ hold(waiting.length > 0);
158
+ resolve(line);
159
+ });
160
+ child.stdin.write(`${JSON.stringify(args)}\n`);
161
+ }));
162
+ last = answer;
163
+ return answer;
164
+ };
165
+ }
166
+ function toRead(tree, unread) {
167
+ const { root, unmapped } = fromAx(tree);
168
+ return { root, unread, unmapped };
169
+ }
170
+ function refused(reason, read, detail) {
171
+ return {
172
+ refused: reason,
173
+ ...(detail === undefined ? {} : { detail }),
174
+ delivered: false,
175
+ reachable: false,
176
+ settled: true,
177
+ before: read,
178
+ after: read,
179
+ };
180
+ }
181
+ /** The pictures this process wrote. The daemon deletes a picture it reads; this removes the rest. */
182
+ const written = new Set();
183
+ /** Removes every picture this process wrote. It runs when the process ends. */
184
+ export function removeCaptures() {
185
+ for (const path of written) {
186
+ rmSync(path, { force: true });
187
+ }
188
+ written.clear();
189
+ }
190
+ const NOTHING = { root: fromAx({ role: '', children: [] }).root, unread: 0, unmapped: [] };
191
+ export class MacDriver {
192
+ #input;
193
+ #run;
194
+ #captures = 0;
195
+ /** The tree as the helper last gave it. An action names its element from this read. */
196
+ #last;
197
+ #switchTried = false;
198
+ constructor(input) {
199
+ this.#input = input;
200
+ this.#run = input.run ?? servingHelper();
201
+ }
202
+ subject() {
203
+ return { app: this.#input.app, pid: this.#input.pid };
204
+ }
205
+ async #ask(args) {
206
+ const answer = JSON.parse(await this.#run(this.#input.helper, args));
207
+ const failed = ErrorSchema.safeParse(answer);
208
+ if (failed.success && failed.data.error === HelperError.SCREEN_LOCKED) {
209
+ throw new Error('The screen is locked. macOS gives no window of an application while the screen is locked. Unlock the screen, and try again.');
210
+ }
211
+ if (failed.success && failed.data.error === HelperError.OWN_WINDOW) {
212
+ throw new Error('This is the window of Reticle itself. The realm does not read it and does not act on it: Pause in that window is for the person at the machine.');
213
+ }
214
+ if (failed.success && failed.data.error === HelperError.APP_GONE) {
215
+ throw new Error(`${this.#input.app} (${String(this.#input.pid)}) is not running. It was closed, or it ended by itself. Open it and join it again.`);
216
+ }
217
+ if (failed.success) {
218
+ throw new Error(failed.data.error === HelperError.NOT_TRUSTED
219
+ ? 'reticle-ax has no Accessibility permission. Allow the terminal in System Settings, Privacy & Security, Accessibility.'
220
+ : `reticle-ax: ${failed.data.error}`);
221
+ }
222
+ return answer;
223
+ }
224
+ async read() {
225
+ let answer = TreeSchema.parse(await this.#ask([Command.TREE, String(this.#input.pid)]));
226
+ const hasWindow = answer.tree.children.some((child) => 'AXWindow' === child.role);
227
+ if (true === this.#input.screenReaderSwitch && !this.#switchTried && hasWindow) {
228
+ this.#switchTried = true;
229
+ await this.#ask([Command.SWITCH, String(this.#input.pid), TRY_SWITCH]);
230
+ answer = TreeSchema.parse(await this.#ask([Command.TREE, String(this.#input.pid)]));
231
+ }
232
+ this.#last = answer.tree;
233
+ return {
234
+ ...toRead(answer.tree, answer.unread),
235
+ ...(answer.windowsNotOnScreen === undefined
236
+ ? {}
237
+ : { windowsNotOnScreen: answer.windowsNotOnScreen }),
238
+ };
239
+ }
240
+ /** The element as the helper last gave it, at the place of `path`. */
241
+ #rawAt(path) {
242
+ let raw = this.#last;
243
+ for (const index of path) {
244
+ // A child that has "i" is found by it: the helper left some of its siblings out.
245
+ raw = raw?.children.find((child, order) => (child.i ?? order) === index);
246
+ }
247
+ return raw;
248
+ }
249
+ async capture(how) {
250
+ this.#captures += 1;
251
+ // In the temporary folder and with the prefix the daemon asks for: it reads no other file.
252
+ const path = join(tmpdir(), `${RETICLE_CAPTURE_FILE_PREFIX}cu-${String(this.#input.pid)}-${String(this.#captures)}.png`);
253
+ if (0 === written.size) {
254
+ process.once('exit', removeCaptures);
255
+ }
256
+ written.add(path);
257
+ const answer = CaptureSchema.safeParse(await this.#ask([
258
+ Command.CAPTURE,
259
+ String(this.#input.pid),
260
+ path,
261
+ ...(true === how?.screen ? [SCREEN] : []),
262
+ ]));
263
+ if (!answer.success) {
264
+ return { ok: false, reason: 'the helper gave no picture' };
265
+ }
266
+ if (!answer.data.ok) {
267
+ return { ok: false, reason: answer.data.reason ?? 'the capture failed' };
268
+ }
269
+ const [x = 0, y = 0, width = 0, height = 0] = answer.data.window ?? [];
270
+ const app = answer.data.appWindow;
271
+ return {
272
+ ok: true,
273
+ path,
274
+ window: [x, y, width, height],
275
+ scale: answer.data.scale ?? 1,
276
+ ...(app === undefined
277
+ ? {}
278
+ : { appWindow: [app[0] ?? 0, app[1] ?? 0, app[2] ?? 0, app[3] ?? 0] }),
279
+ };
280
+ }
281
+ /** The words of a picture file. Undefined from a helper that has no reader (Windows, Linux). */
282
+ async texts(path) {
283
+ const answer = TextsSchema.safeParse(await this.#ask([Command.TEXTS, path]));
284
+ return answer.success ? answer.data.texts : undefined;
285
+ }
286
+ async reach(target) {
287
+ const raw = this.#rawAt(target.path);
288
+ if (raw === undefined) {
289
+ return { reach: Reach.UNKNOWN, detail: 'the element is not in the last read' };
290
+ }
291
+ const answer = await this.#ask([
292
+ Command.REACH,
293
+ String(this.#input.pid),
294
+ target.path.join('.'),
295
+ raw.role,
296
+ raw.title ?? raw.description ?? '',
297
+ ]);
298
+ const known = ReachSchema.safeParse(answer);
299
+ if (!known.success) {
300
+ // A refusal: the element moved or the application did not answer.
301
+ return { reach: Reach.UNKNOWN, detail: 'the element is not where it was' };
302
+ }
303
+ return {
304
+ reach: known.data.reach,
305
+ ...(known.data.detail === undefined ? {} : { detail: known.data.detail }),
306
+ };
307
+ }
308
+ async act(request) {
309
+ const raw = this.#rawAt(request.target.path);
310
+ if (raw === undefined) {
311
+ return refused(ActRefusal.STALE, NOTHING);
312
+ }
313
+ const answer = await this.#ask([
314
+ Command.ACT,
315
+ String(this.#input.pid),
316
+ request.target.path.join('.'),
317
+ raw.role,
318
+ raw.title ?? raw.description ?? '',
319
+ request.kind,
320
+ request.value ?? '',
321
+ String(request.budgetMs),
322
+ request.quietMs === undefined
323
+ ? request.delivery
324
+ : `${request.delivery}:${String(request.quietMs)}`,
325
+ ...request.watch,
326
+ ]);
327
+ const no = RefusedSchema.safeParse(answer);
328
+ if (no.success) {
329
+ return refused(no.data.refused, NOTHING, no.data.detail);
330
+ }
331
+ const acted = ActedSchema.parse(answer);
332
+ const pixelsOf = (seen) => ({
333
+ changed: seen.changed,
334
+ ...(seen.box === undefined ? {} : { box: seen.box }),
335
+ ...(seen.moving === undefined ? {} : { moving: seen.moving }),
336
+ });
337
+ return {
338
+ delivered: acted.delivered,
339
+ reachable: acted.reachable,
340
+ settled: acted.settled,
341
+ ...(true === acted.appGone ? { appGone: true } : {}),
342
+ before: toRead(acted.before, acted.unreadBefore),
343
+ after: toRead(acted.after, acted.unreadAfter),
344
+ ...(acted.bytesWritten === undefined ? {} : { bytesWritten: acted.bytesWritten }),
345
+ ...(acted.clipboardChanged === undefined ? {} : { clipboardChanged: acted.clipboardChanged }),
346
+ ...(acted.pixels === undefined ? {} : { pixels: pixelsOf(acted.pixels) }),
347
+ ...(acted.windowState === undefined ? {} : { windowState: windowStateOf(acted.windowState) }),
348
+ ...(acted.settingsChanged === undefined
349
+ ? {}
350
+ : {
351
+ settingsChanged: acted.settingsChanged.map(({ cut, ...change }) => true === cut ? { ...change, cut } : change),
352
+ }),
353
+ };
354
+ }
355
+ }
@@ -0,0 +1,10 @@
1
+ import type { HudPort } from '../hud/port.js';
2
+ /** The glide of the pointer to a near control, and the longest one, across the screen. */
3
+ export declare const GLIDE_SHORTEST = 80;
4
+ export declare const GLIDE_LONGEST = 250;
5
+ /**
6
+ * How long the pointer takes to go from one place to another, as a hand takes longer for a longer
7
+ * way. From no place (the pointer is not on the screen yet) it shows at the place at once.
8
+ */
9
+ export declare function glideMs(from: readonly [number, number] | undefined, to: readonly [number, number]): number;
10
+ export declare function macHud(program: string, onStop?: () => void): HudPort;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The HUD on macOS: the `reticle-hud` program draws it. One line of JSON goes to the program for
3
+ * each thing to show, and the program writes one line when the person presses "Pause", "Stop", or
4
+ * "Done" at the end of their turn.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { z } from 'zod';
8
+ const Say = {
9
+ APP: 'app',
10
+ MOVE: 'move',
11
+ GLOW: 'glow',
12
+ ACT: 'act',
13
+ EFFECT: 'effect',
14
+ TURN: 'turn',
15
+ };
16
+ const SaidSchema = z.object({
17
+ paused: z.boolean().optional(),
18
+ stopped: z.boolean().optional(),
19
+ done: z.boolean().optional(),
20
+ });
21
+ /** The glide of the pointer to a near control, and the longest one, across the screen. */
22
+ export const GLIDE_SHORTEST = 80;
23
+ export const GLIDE_LONGEST = 250;
24
+ /** How much longer the glide is for each point of the way. */
25
+ const GLIDE_MS_PER_POINT = 0.12;
26
+ /**
27
+ * How long the pointer takes to go from one place to another, as a hand takes longer for a longer
28
+ * way. From no place (the pointer is not on the screen yet) it shows at the place at once.
29
+ */
30
+ export function glideMs(from, to) {
31
+ if (from === undefined) {
32
+ return 0;
33
+ }
34
+ const way = Math.hypot(to[0] - from[0], to[1] - from[1]);
35
+ return Math.round(Math.min(GLIDE_LONGEST, GLIDE_SHORTEST + way * GLIDE_MS_PER_POINT));
36
+ }
37
+ /** The most times the program is started again: one that ends at each start is left ended. */
38
+ const RESTARTS = 5;
39
+ export function macHud(program, onStop) {
40
+ let paused = false;
41
+ let stopped = false;
42
+ let closed = false;
43
+ let restarts = 0;
44
+ /** The application the HUD shows. A program that is started again is told it again. */
45
+ let app;
46
+ /** Where the pointer is. Absent: it is not on the screen yet. */
47
+ let at;
48
+ const onDone = [];
49
+ const hear = (line) => {
50
+ try {
51
+ const said = SaidSchema.safeParse(JSON.parse(line));
52
+ if (said.success) {
53
+ paused = said.data.paused ?? paused;
54
+ if (true === said.data.done) {
55
+ onDone.forEach((listener) => {
56
+ listener();
57
+ });
58
+ }
59
+ if (true === said.data.stopped && !stopped) {
60
+ stopped = true;
61
+ onStop?.();
62
+ }
63
+ }
64
+ }
65
+ catch {
66
+ // Not a line of the program's protocol: nothing to learn from it.
67
+ }
68
+ };
69
+ const start = () => {
70
+ const started = spawn(program, [], { stdio: ['pipe', 'pipe', 'ignore'] });
71
+ // The window must not keep the command open, and a window that is gone must not break an action.
72
+ started.unref();
73
+ started.on('error', () => undefined);
74
+ started.stdin.on('error', () => undefined);
75
+ let rest = '';
76
+ started.stdout.on('data', (chunk) => {
77
+ const lines = (rest + chunk.toString('utf8')).split('\n');
78
+ rest = lines.pop() ?? '';
79
+ lines.forEach(hear);
80
+ });
81
+ // The pointer is the program's window. A program that ended (it crashed, or it was quit) took
82
+ // the pointer away for the rest of the session. It is started again, unless the person
83
+ // stopped Reticle or the session closed it.
84
+ started.on('exit', () => {
85
+ if (closed || stopped || restarts >= RESTARTS) {
86
+ return;
87
+ }
88
+ restarts += 1;
89
+ child = start();
90
+ if (app !== undefined) {
91
+ send({ t: Say.APP, name: app });
92
+ }
93
+ });
94
+ return started;
95
+ };
96
+ let child = start();
97
+ const send = (message) => {
98
+ if (child.stdin.writable) {
99
+ child.stdin.write(`${JSON.stringify(message)}\n`);
100
+ }
101
+ };
102
+ return {
103
+ app: (name) => {
104
+ app = name;
105
+ send({ t: Say.APP, name });
106
+ },
107
+ move: (x, y) => {
108
+ const ms = glideMs(at, [x, y]);
109
+ at = [x, y];
110
+ send({ t: Say.MOVE, x, y, ms });
111
+ return new Promise((resolve) => {
112
+ setTimeout(resolve, ms).unref();
113
+ });
114
+ },
115
+ glow: ([x, y, w, h]) => {
116
+ send({ t: Say.GLOW, x, y, w, h });
117
+ },
118
+ act: (text) => {
119
+ send({ t: Say.ACT, text });
120
+ },
121
+ effect: (text, kind) => {
122
+ send({ t: Say.EFFECT, text, kind });
123
+ },
124
+ turn: ({ state, tone, text }) => {
125
+ send({
126
+ t: Say.TURN,
127
+ state,
128
+ ...(tone === undefined ? {} : { tone }),
129
+ ...(text === undefined ? {} : { text }),
130
+ });
131
+ },
132
+ onDone: (listener) => {
133
+ onDone.push(listener);
134
+ },
135
+ paused: () => paused,
136
+ stopped: () => stopped,
137
+ close: () => {
138
+ closed = true;
139
+ child.stdin.end();
140
+ },
141
+ };
142
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * What an action left that the realm can see, beside the elements: the pixels, the settings, the
3
+ * clipboard and the disk.
4
+ */
5
+ import type { ActOutcome } from '../driver.js';
6
+ /** The pixels in the answer: what changed, and what moved by itself and cannot be read. */
7
+ export declare function pixelEffect({ pixels }: ActOutcome): Record<string, number>;
8
+ /** True when an action left nothing that this realm can see. */
9
+ export declare function sawNothing(outcome: ActOutcome, changesOnScreen: number): boolean;
@@ -0,0 +1,13 @@
1
+ /** The pixels in the answer: what changed, and what moved by itself and cannot be read. */
2
+ export function pixelEffect({ pixels }) {
3
+ const moving = 0 < (pixels?.moving ?? 0) ? { pixelsMovingByItself: pixels?.moving ?? 0 } : {};
4
+ return pixels === undefined ? {} : { pixelsChanged: pixels.changed, ...moving };
5
+ }
6
+ /** True when an action left nothing that this realm can see. */
7
+ export function sawNothing(outcome, changesOnScreen) {
8
+ return (0 === changesOnScreen &&
9
+ 0 === (outcome.settingsChanged ?? []).length &&
10
+ true !== outcome.clipboardChanged &&
11
+ !((outcome.pixels?.changed ?? 0) > 0) &&
12
+ 0 === (outcome.bytesWritten ?? 0));
13
+ }
@@ -0,0 +1,87 @@
1
+ import type { WorkspacePort } from '@reticlehq/terminal';
2
+ import { EventType } from '@reticlehq/core';
3
+ import type { UiDriver } from '../driver.js';
4
+ import type { WriteTimeOf } from '../files.js';
5
+ import type { HudPort } from '../hud/port.js';
6
+ import { PEER_ACTIONS } from './form.js';
7
+ export type Emit = (type: EventType, data: Record<string, unknown>) => void;
8
+ export interface PeerCommandsDeps {
9
+ driver: UiDriver;
10
+ /** Sends one event to the bridge. Called before the answer to the action that caused it. */
11
+ emit: Emit;
12
+ /**
13
+ * Folders to watch. A file that changes there during an action is sent as a signal, so a claim
14
+ * can require the file and not only the words the application shows.
15
+ */
16
+ workspace?: WorkspacePort;
17
+ /** When a file was last written. The default asks the file system. A test gives its own. */
18
+ writeTimeOf?: WriteTimeOf;
19
+ /**
20
+ * The quiet time for an action. The peer goes on looking after an action (`sendTreeChanges`), so
21
+ * an action can be called finished sooner than a caller that looks once must wait.
22
+ */
23
+ quietMs?: number;
24
+ /**
25
+ * A known reason why a press can do nothing in this application. The answer to a press with
26
+ * no effect carries it as `note`. An Electron application with its switch off is the case.
27
+ */
28
+ noEffectNote?: string;
29
+ /**
30
+ * False: the realm never brings the application to the front and never uses the real pointer,
31
+ * also when a caller asks. The person who joined the application said so.
32
+ */
33
+ foreground?: boolean;
34
+ /** What the person at the machine sees of the realm. Absent: nothing is shown. */
35
+ hud?: HudPort;
36
+ }
37
+ /**
38
+ * One signal for each file an action changed. The name is `file.` and the kind of change:
39
+ * `file.written`, `file.modified`, `file.deleted`, `file.mode-changed`. A file that was written
40
+ * again with the same bytes is `file.written` too, with `kind: "rewritten"`. The data is the file name,
41
+ * its path and its size.
42
+ */
43
+ /** What the agent reads when the person presses "Done" on the HUD at the end of their turn. */
44
+ export declare const HUMAN_DONE = "Done: the person finished what you asked for on the HUD. Read the screen again.";
45
+ export declare const FILE_SIGNAL_PREFIX = "file.";
46
+ /**
47
+ * The signal for an action in which the application's process wrote bytes to disk, in any folder.
48
+ * The operating system counts the bytes. No folder has to be watched for it.
49
+ */
50
+ export declare const DISK_WROTE_SIGNAL = "disk.wrote";
51
+ /** The signal for one setting of the application that an action changed: its key and its values. */
52
+ export declare const SETTINGS_CHANGED_SIGNAL = "settings.changed";
53
+ /** The signal for an action that put something on the clipboard. It does not carry the content. */
54
+ export declare const CLIPBOARD_CHANGED_SIGNAL = "clipboard.changed";
55
+ /** The commands this realm answers. The peer declares exactly these to the bridge. */
56
+ export declare const PEER_COMMANDS: readonly ["snapshot", "query", "match", "inspect", "act", "act_sequence", "scroll", "capabilities", "capture", "narrate"];
57
+ type Args = Record<string, unknown>;
58
+ export { PEER_ACTIONS };
59
+ export declare class PeerCommands {
60
+ #private;
61
+ constructor(deps: PeerCommandsDeps);
62
+ /**
63
+ * Sends what changed in the tree since the last look, when no action is in progress.
64
+ *
65
+ * An action sends its own changes before it answers. An application also changes after that: a
66
+ * second step of an effect, a save that ends late. With no look between actions those changes
67
+ * were sent by nobody, and a caller that waited for them had only its own questions to go on.
68
+ * The peer calls this on a timer.
69
+ */
70
+ sendTreeChanges(): Promise<void>;
71
+ /**
72
+ * Sends one signal for each file in the watched folders that changed since the last look.
73
+ *
74
+ * It is called after each action, and the peer calls it on a timer too. An application can
75
+ * write a file a moment after the action is finished. A signal that is sent only inside the
76
+ * action misses that file, and a claim that waits for it then fails for a file that is there.
77
+ */
78
+ sendFileChanges(): void;
79
+ /**
80
+ * The answer to one command. It throws when the command fails; the peer sends the words on.
81
+ *
82
+ * `outward` comes with a command the Harness sent: the outward actions (send, delete, pay) its
83
+ * journey asks for. No other outward control is pressed. Absent: an agent or a saved flow sent
84
+ * the command, and there is no limit here.
85
+ */
86
+ answer(name: string, args: Args, outward?: readonly string[]): Promise<unknown>;
87
+ }