@parcha/agentrun-computer 0.1.0-beta.36 → 0.1.0-beta.38
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.
- package/NOTICE +2 -0
- package/README.md +547 -478
- package/box/Dockerfile +18 -1
- package/box/README.md +13 -0
- package/box/build-agent37.mjs +158 -0
- package/box/build-daytona.py +2 -2
- package/box/build-e2b.mjs +41 -18
- package/box/recipe.mjs +43 -0
- package/dist/agent37-ssh.d.ts +89 -0
- package/dist/agent37-ssh.js +445 -0
- package/dist/agent37.d.ts +104 -0
- package/dist/agent37.js +402 -0
- package/dist/attach.d.ts +146 -0
- package/dist/attach.js +469 -0
- package/dist/browserbase.d.ts +2 -10
- package/dist/browserbase.js +3 -6
- package/dist/client.d.ts +45 -4
- package/dist/client.js +92 -4
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/computerd.json +4 -0
- package/dist/conformance/agent37.d.ts +96 -0
- package/dist/conformance/agent37.js +154 -0
- package/dist/conformance/cases/apps.d.ts +11 -0
- package/dist/conformance/cases/apps.js +173 -73
- package/dist/conformance/cases/health.js +14 -0
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/isolation.d.ts +7 -5
- package/dist/conformance/cases/isolation.js +44 -14
- package/dist/conformance/cases/mount.js +1 -1
- package/dist/conformance/cases/provider.js +27 -1
- package/dist/conformance/cases/screen.d.ts +3 -0
- package/dist/conformance/cases/screen.js +18 -0
- package/dist/conformance/cases/settings.d.ts +29 -23
- package/dist/conformance/cases/settings.js +76 -58
- package/dist/conformance/cases/touch.js +19 -17
- package/dist/conformance/cases/ui.d.ts +2 -0
- package/dist/conformance/cases/ui.js +475 -0
- package/dist/conformance/cli.d.ts +9 -0
- package/dist/conformance/cli.js +94 -9
- package/dist/conformance/daytona.d.ts +9 -20
- package/dist/conformance/daytona.js +12 -21
- package/dist/conformance/e2b.d.ts +6 -0
- package/dist/conformance/e2b.js +9 -2
- package/dist/conformance/exec-stream.d.ts +45 -0
- package/dist/conformance/exec-stream.js +486 -0
- package/dist/conformance/fixture.d.ts +1 -1
- package/dist/conformance/fixture.js +25 -1
- package/dist/conformance/modal.d.ts +17 -13
- package/dist/conformance/modal.js +18 -9
- package/dist/conformance/orgo.d.ts +3 -3
- package/dist/conformance/orgo.js +6 -8
- package/dist/conformance/phone-harness.d.ts +6 -2
- package/dist/conformance/phone-harness.js +21 -4
- package/dist/conformance/report.js +1 -1
- package/dist/conformance/runner.js +23 -4
- package/dist/conformance/sweep.d.ts +50 -0
- package/dist/conformance/sweep.js +187 -0
- package/dist/conformance/types.d.ts +13 -5
- package/dist/conformance/ui-fixture.d.ts +56 -0
- package/dist/conformance/ui-fixture.js +43 -0
- package/dist/create-requests.d.ts +51 -0
- package/dist/create-requests.js +121 -0
- package/dist/daytona.d.ts +20 -133
- package/dist/daytona.js +405 -1449
- package/dist/descriptor.d.ts +11 -1
- package/dist/descriptor.js +9 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/daytona.d.ts +6 -5
- package/dist/descriptors/daytona.js +9 -5
- package/dist/descriptors/index.d.ts +42 -7
- package/dist/descriptors/index.js +4 -2
- package/dist/descriptors/orgo.d.ts +2 -1
- package/dist/descriptors/orgo.js +3 -2
- package/dist/descriptors/phone-harness.d.ts +1 -1
- package/dist/descriptors/phone-harness.js +2 -2
- package/dist/descriptors/shared.d.ts +1 -1
- package/dist/descriptors/shared.js +2 -2
- package/dist/desktop.d.ts +18 -4
- package/dist/desktop.js +89 -9
- package/dist/docker.d.ts +7 -10
- package/dist/docker.js +272 -34
- package/dist/drift.js +4 -4
- package/dist/e2b.d.ts +16 -290
- package/dist/e2b.js +230 -1393
- package/dist/fake-ui-driver.d.ts +97 -0
- package/dist/fake-ui-driver.js +717 -0
- package/dist/host.d.ts +201 -0
- package/dist/host.js +8 -0
- package/dist/hosted/process.d.ts +81 -0
- package/dist/hosted/process.js +259 -0
- package/dist/hosted/provider.d.ts +160 -0
- package/dist/hosted/provider.js +1415 -0
- package/dist/hosted/rest.d.ts +66 -0
- package/dist/hosted/rest.js +121 -0
- package/dist/hosted/scripts.d.ts +82 -0
- package/dist/{child.js → hosted/scripts.js} +118 -12
- package/dist/hosted/values.d.ts +5 -0
- package/dist/hosted/values.js +8 -0
- package/dist/index.d.ts +7 -3
- package/dist/index.js +7 -4
- package/dist/kernel.d.ts +2 -10
- package/dist/kernel.js +3 -6
- package/dist/kinds.d.ts +11 -2
- package/dist/kinds.js +20 -4
- package/dist/local-chrome.d.ts +2 -10
- package/dist/local-chrome.js +3 -6
- package/dist/modal.d.ts +22 -257
- package/dist/modal.js +183 -1280
- package/dist/mount-archil.d.ts +8 -4
- package/dist/mount-archil.js +22 -11
- package/dist/mount.d.ts +10 -4
- package/dist/mount.js +8 -4
- package/dist/orgo-channel.d.ts +3 -2
- package/dist/orgo-channel.js +5 -2
- package/dist/orgo-desktop.d.ts +9 -4
- package/dist/orgo-desktop.js +33 -13
- package/dist/orgo-workspaces.d.ts +47 -0
- package/dist/orgo-workspaces.js +94 -0
- package/dist/orgo.d.ts +10 -13
- package/dist/orgo.js +32 -21
- package/dist/phone-harness.d.ts +31 -28
- package/dist/phone-harness.js +510 -702
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +339 -33
- package/dist/protocol.js +97 -3
- package/dist/provider.d.ts +36 -8
- package/dist/provider.js +16 -0
- package/dist/providers.d.ts +11 -12
- package/dist/result.d.ts +1 -1
- package/dist/screen-watch.js +34 -6
- package/dist/surface/api.d.ts +260 -0
- package/dist/surface/api.js +1 -0
- package/dist/surface/core.d.ts +55 -0
- package/dist/surface/core.js +475 -0
- package/dist/surface/index.d.ts +5 -0
- package/dist/surface/index.js +3 -0
- package/dist/surface/outline.d.ts +10 -0
- package/dist/surface/outline.js +51 -0
- package/dist/surface/script.d.ts +10 -0
- package/dist/surface/script.js +94 -0
- package/dist/ui-engine.d.ts +114 -0
- package/dist/ui-engine.js +814 -0
- package/package.json +18 -3
- package/dist/child.d.ts +0 -42
- package/dist/conformance/daytona-sweep.d.ts +0 -18
- package/dist/conformance/daytona-sweep.js +0 -126
- package/dist/conformance/e2b-diagnose.d.ts +0 -16
- package/dist/conformance/e2b-diagnose.js +0 -61
- package/dist/conformance/e2b-sweep.d.ts +0 -18
- package/dist/conformance/e2b-sweep.js +0 -132
- package/dist/conformance/modal-sweep.d.ts +0 -22
- package/dist/conformance/modal-sweep.js +0 -213
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
import { MAX_CHUNK_BYTES } from "../protocol.js";
|
|
2
|
+
import { outlineOf, quoted } from "./outline.js";
|
|
3
|
+
export const SURFACE_OPS = ["observe", "act", "screenshot", "input.act", "apps.list", "apps.open", "shell.run", "processes.start", "files.read", "files.write", "files.list", "files.stat"];
|
|
4
|
+
/** A call the computer refused or failed: `kind` is the protocol's error kind (stale, unsupported, ...) or the
|
|
5
|
+
* connection's (gone, timeout). */
|
|
6
|
+
export class SurfaceError extends Error {
|
|
7
|
+
kind;
|
|
8
|
+
constructor(kind, message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "SurfaceError";
|
|
11
|
+
this.kind = kind;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The most bytes files.read gathers into one answer. */
|
|
15
|
+
export const MAX_READ_BYTES = 16 * 1024 * 1024;
|
|
16
|
+
/** The most characters of a value's JSON an answer's text holds. */
|
|
17
|
+
const MAX_TEXT_CHARS = 40_000;
|
|
18
|
+
/** The default and longest a shell command runs. */
|
|
19
|
+
const DEFAULT_RUN_MS = 60_000;
|
|
20
|
+
const MAX_RUN_MS = 600_000;
|
|
21
|
+
/** The most pages of files.list one list gathers. */
|
|
22
|
+
const MAX_LIST_PAGES = 10;
|
|
23
|
+
/** How long raw input waits before the screenshot of an act's observe, so the screen can redraw. */
|
|
24
|
+
const INPUT_SETTLE_MS = 500;
|
|
25
|
+
/** A scroll of `distance` pixels as wheel clicks: about 120 pixels each, at least one, at most the most a driver takes in one. */
|
|
26
|
+
const WHEEL_PX = 120;
|
|
27
|
+
const MAX_WHEEL_CLICKS = 50;
|
|
28
|
+
const wheelClicks = (distance) => Math.sign(distance) * Math.min(MAX_WHEEL_CLICKS, Math.max(1, Math.round(Math.abs(distance) / WHEEL_PX)));
|
|
29
|
+
/** The card of a hello. */
|
|
30
|
+
export function cardOf(hello) {
|
|
31
|
+
return {
|
|
32
|
+
kind: hello.kind,
|
|
33
|
+
os: hello.os,
|
|
34
|
+
...(hello.osVersion ? { osVersion: hello.osVersion } : {}),
|
|
35
|
+
arch: hello.arch,
|
|
36
|
+
...(hello.screen ? { screen: hello.screen } : {}),
|
|
37
|
+
groups: [...hello.groups],
|
|
38
|
+
features: { ...(hello.features ?? {}) },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** The ops a computer with these groups answers. */
|
|
42
|
+
export function opsOf(groups) {
|
|
43
|
+
const has = (group) => groups.includes(group);
|
|
44
|
+
const input = has("input.pointer") || has("input.touch") || has("input.keys");
|
|
45
|
+
const offered = {
|
|
46
|
+
observe: has("ui") || has("screen"),
|
|
47
|
+
act: has("ui") || input,
|
|
48
|
+
screenshot: has("screen"),
|
|
49
|
+
"input.act": input,
|
|
50
|
+
"apps.list": has("apps"),
|
|
51
|
+
"apps.open": has("apps"),
|
|
52
|
+
"shell.run": has("exec"),
|
|
53
|
+
"processes.start": has("processes"),
|
|
54
|
+
"files.read": has("files"),
|
|
55
|
+
"files.write": has("files"),
|
|
56
|
+
"files.list": has("files"),
|
|
57
|
+
"files.stat": has("files"),
|
|
58
|
+
};
|
|
59
|
+
return SURFACE_OPS.filter((op) => offered[op]);
|
|
60
|
+
}
|
|
61
|
+
const imageOf = (image) => ({ type: "image", mimeType: image.format === "png" ? "image/png" : "image/jpeg", data: image.data, width: image.width, height: image.height });
|
|
62
|
+
/** A value's JSON for a model, cut at MAX_TEXT_CHARS. */
|
|
63
|
+
function jsonText(value) {
|
|
64
|
+
const text = JSON.stringify(value) ?? "null";
|
|
65
|
+
return text.length > MAX_TEXT_CHARS ? `${text.slice(0, MAX_TEXT_CHARS)}… (${text.length - MAX_TEXT_CHARS} more characters: return less)` : text;
|
|
66
|
+
}
|
|
67
|
+
/** The name of a step: its first key ("press", "click", ...). */
|
|
68
|
+
export const stepName = (step) => Object.keys(step)[0] ?? "step";
|
|
69
|
+
/** The element a step acts on, by its ref: press's, set's, perform's, and click's or scroll's when they name one, or
|
|
70
|
+
* type's `into`. None for a step at a point or with no element. */
|
|
71
|
+
function stepRef(step) {
|
|
72
|
+
const at = "type" in step ? step.into : "press" in step ? step.press : "set" in step ? step.set : "perform" in step ? step.perform : "click" in step ? step.click : "scroll" in step ? step.scroll : undefined;
|
|
73
|
+
return typeof at === "string" ? at : undefined;
|
|
74
|
+
}
|
|
75
|
+
/** The most elements a surface remembers the names of, past which the oldest seen go first. */
|
|
76
|
+
const MAX_NAMED = 4000;
|
|
77
|
+
/** A step as its line in an act's answer names it: its name, then the element it acted on as the outline names it
|
|
78
|
+
* (`press @e3 button "Save"`, `type into @e4 textbox "PIN" [secure]`), where that element was seen in an observation;
|
|
79
|
+
* `[secure]` is that element's own flag. A type with no element names none: where the focus is when it runs (which
|
|
80
|
+
* app, which field, after what the steps before it, a person, or the system did) is not known here, so no reader of
|
|
81
|
+
* its line can tell it went to an ordinary field, and none shows what was typed. */
|
|
82
|
+
export function stepWords(step, named) {
|
|
83
|
+
const ref = stepRef(step);
|
|
84
|
+
const node = ref === undefined ? undefined : named(ref);
|
|
85
|
+
if (ref === undefined || node === undefined)
|
|
86
|
+
return stepName(step);
|
|
87
|
+
const target = [ref, node.role, ...(node.name ? [quoted(node.name)] : []), ...(node.secure ? ["[secure]"] : [])].join(" ");
|
|
88
|
+
return `${stepName(step)}${"type" in step ? " into" : ""} ${target}`;
|
|
89
|
+
}
|
|
90
|
+
/** An act's answer as lines: one per step (named by `names`, stepWords), then the expect, then whether it changed and
|
|
91
|
+
* the new state, then the new observation's outline when there is one. */
|
|
92
|
+
export function actText(names, result) {
|
|
93
|
+
const lines = result.steps.map((outcome, index) => {
|
|
94
|
+
const name = names[index] ?? "step";
|
|
95
|
+
return "error" in outcome
|
|
96
|
+
? `${index + 1}. ${name}: refused (${outcome.error.kind}): ${outcome.error.message}`
|
|
97
|
+
: `${index + 1}. ${name}: ${outcome.route}${outcome.verified ? ", verified" : ""}`;
|
|
98
|
+
});
|
|
99
|
+
const refused = result.steps.some((outcome) => "error" in outcome);
|
|
100
|
+
const skipped = names.length - result.steps.length;
|
|
101
|
+
if (skipped > 0)
|
|
102
|
+
lines.push(refused ? `${skipped} later steps did not run` : `${skipped} steps did not run`);
|
|
103
|
+
if (result.expect)
|
|
104
|
+
lines.push(`expect: ${result.expect}`);
|
|
105
|
+
if (result.changed !== undefined || result.state !== undefined) {
|
|
106
|
+
lines.push([result.changed === undefined ? "" : result.changed ? "changed" : "unchanged", result.state ? `state ${result.state}` : ""].filter(Boolean).join(" · "));
|
|
107
|
+
}
|
|
108
|
+
if (names.length === 0 && !result.expect)
|
|
109
|
+
lines.push("no steps");
|
|
110
|
+
if (result.after)
|
|
111
|
+
lines.push("", result.after.outline);
|
|
112
|
+
return lines.join("\n");
|
|
113
|
+
}
|
|
114
|
+
/** A chord's keys: "ctrl+shift+t" is ctrl, shift, t; a trailing "+" is the plus key ("ctrl++"). */
|
|
115
|
+
export const chordKeys = (chord) => chord.split(/\+(?=.)/).filter((key) => key !== "");
|
|
116
|
+
/** The surface of one computer, over its connection. */
|
|
117
|
+
export function createSurface(client, hello) {
|
|
118
|
+
const card = cardOf(hello);
|
|
119
|
+
const has = (group) => card.groups.includes(group);
|
|
120
|
+
const ops = opsOf(card.groups);
|
|
121
|
+
const touchOnly = has("input.touch") && !has("input.pointer");
|
|
122
|
+
/** The last state observed, by app, and the last app: an act at points defaults to its app's last state. */
|
|
123
|
+
const lastState = new Map();
|
|
124
|
+
let lastApp;
|
|
125
|
+
/** The app each observed state belongs to: an act that names a state and no app was run on that state's app. */
|
|
126
|
+
const appOfState = new Map();
|
|
127
|
+
/** Every element observed, by ref, as an act's step line names it (stepWords): a ref stays good across states. */
|
|
128
|
+
const named = new Map();
|
|
129
|
+
/** Remembers an observation's elements. One with no name of its own (an Android row, a container whose text is in
|
|
130
|
+
* its children) takes its first named element's within a few levels, as a person reading the row would say it. */
|
|
131
|
+
function remember(nodes) {
|
|
132
|
+
const parentOf = new Map();
|
|
133
|
+
for (const node of nodes) {
|
|
134
|
+
parentOf.set(node.ref, node.parent);
|
|
135
|
+
named.delete(node.ref);
|
|
136
|
+
named.set(node.ref, { role: node.role, ...(node.name ? { name: node.name } : {}), secure: node.flags?.includes("secure") === true });
|
|
137
|
+
}
|
|
138
|
+
for (const node of nodes) {
|
|
139
|
+
if (!node.name)
|
|
140
|
+
continue;
|
|
141
|
+
let up = node.parent;
|
|
142
|
+
for (let level = 0; up !== undefined && level < 3; level += 1, up = parentOf.get(up)) {
|
|
143
|
+
const above = named.get(up);
|
|
144
|
+
if (above === undefined || above.name !== undefined)
|
|
145
|
+
break;
|
|
146
|
+
above.name = node.name;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for (const ref of named.keys()) {
|
|
150
|
+
if (named.size <= MAX_NAMED)
|
|
151
|
+
break;
|
|
152
|
+
named.delete(ref);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function call(method, params, signal) {
|
|
156
|
+
const result = await client.call(method, params, { signal });
|
|
157
|
+
if (!result.ok)
|
|
158
|
+
throw new SurfaceError(result.error.code, result.error.message);
|
|
159
|
+
return result.value;
|
|
160
|
+
}
|
|
161
|
+
async function shot(region, signal) {
|
|
162
|
+
const first = await call("screen.shot", region ? { region } : {}, signal);
|
|
163
|
+
const parts = [Buffer.from(first.data, "base64")];
|
|
164
|
+
let read = parts[0].length;
|
|
165
|
+
let eof = first.eof;
|
|
166
|
+
while (!eof) {
|
|
167
|
+
const next = await call("screen.read", { id: first.id, offset: read }, signal);
|
|
168
|
+
const bytes = Buffer.from(next.data, "base64");
|
|
169
|
+
if (bytes.length === 0 && !next.eof)
|
|
170
|
+
throw new SurfaceError("invalid", "the computer's screenshot stopped short of its end");
|
|
171
|
+
parts.push(bytes);
|
|
172
|
+
read += bytes.length;
|
|
173
|
+
eof = next.eof;
|
|
174
|
+
}
|
|
175
|
+
const data = parts.length === 1 ? first.data : Buffer.concat(parts).toString("base64");
|
|
176
|
+
return { type: "image", mimeType: "image/png", data, width: first.width, height: first.height };
|
|
177
|
+
}
|
|
178
|
+
function stateOf(result) {
|
|
179
|
+
const window = result.window;
|
|
180
|
+
const head = [`state ${result.state}`, `${result.app.id}${result.app.name ? ` "${result.app.name}"` : ""}`, `window${window.title ? ` "${window.title}"` : ""} ${window.bounds[2]}×${window.bounds[3]} pt`].join(" · ");
|
|
181
|
+
lastState.set(result.app.id, result.state);
|
|
182
|
+
appOfState.set(result.state, result.app.id);
|
|
183
|
+
lastApp = result.app.id;
|
|
184
|
+
remember(result.nodes);
|
|
185
|
+
const outline = outlineOf(head, result.nodes, result.truncated, result.empty);
|
|
186
|
+
const imageNote = result.image ? `\nimage: ${result.image.width}×${result.image.height} px of the window's ${window.bounds[2]}×${window.bounds[3]} points` : "";
|
|
187
|
+
return {
|
|
188
|
+
id: result.state,
|
|
189
|
+
app: { id: result.app.id, name: result.app.name },
|
|
190
|
+
window: { id: window.id, ...(window.title ? { title: window.title } : {}), bounds: window.bounds },
|
|
191
|
+
elements: result.nodes,
|
|
192
|
+
truncated: result.truncated,
|
|
193
|
+
outline: `${outline}${imageNote}`,
|
|
194
|
+
...(result.image ? { image: imageOf(result.image) } : {}),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/** On a computer with no ui group, input goes to what is in front: an app a look or an act names is opened, or brought
|
|
198
|
+
* in front, first (apps.launch), so the per-step tools open an app as a script's computer.apps.open does. */
|
|
199
|
+
async function inFront(app, signal) {
|
|
200
|
+
if (app && has("apps"))
|
|
201
|
+
await call("apps.launch", { id: app }, signal);
|
|
202
|
+
}
|
|
203
|
+
/** The screen as a state, for a computer with no ui group: its image, no elements. With nothing in front, the head
|
|
204
|
+
* lists the apps to name. */
|
|
205
|
+
async function screenState(signal) {
|
|
206
|
+
const image = await shot(undefined, signal);
|
|
207
|
+
const listed = has("apps") ? await call("apps.list", {}, signal) : undefined;
|
|
208
|
+
const app = listed?.foreground ?? "";
|
|
209
|
+
const front = app ? ` · ${app} in front` : listed ? ` · no app in front; name one as app to open it: ${listed.apps.map((one) => one.id).join(", ")}` : "";
|
|
210
|
+
const head = `screen ${image.width}×${image.height} px${front} · this computer has no ui group: no elements; act at points of this image`;
|
|
211
|
+
return { id: "screen", app: { id: app, name: "" }, window: { id: "screen", bounds: [0, 0, image.width, image.height] }, elements: [], truncated: false, outline: head, image };
|
|
212
|
+
}
|
|
213
|
+
async function observe(args, signal) {
|
|
214
|
+
if (!has("ui")) {
|
|
215
|
+
await inFront(args.app, signal);
|
|
216
|
+
return screenState(signal);
|
|
217
|
+
}
|
|
218
|
+
const imageInUi = args.image === true && card.features["ui.image"] === true;
|
|
219
|
+
const result = await call("ui.observe", { ...(args.app ? { target: { app: args.app } } : {}), ...(imageInUi ? { image: true } : {}), ...(args.full ? { full: true } : {}) }, signal);
|
|
220
|
+
const state = stateOf(result);
|
|
221
|
+
if (args.image === true && !imageInUi && has("screen")) {
|
|
222
|
+
// No window image here (ui.image is off): the whole screen instead, which the outline says.
|
|
223
|
+
const image = await shot(undefined, signal);
|
|
224
|
+
return { ...state, image, outline: `${state.outline}\nimage: the whole screen, ${image.width}×${image.height} px (this computer gives no window image)` };
|
|
225
|
+
}
|
|
226
|
+
return state;
|
|
227
|
+
}
|
|
228
|
+
const observeAnswer = (state) => ({ value: state, text: state.outline, images: state.image ? [state.image] : [] });
|
|
229
|
+
/** Steps at points on a computer without the ui group: input.actions, or a refusal naming the step that can't map. */
|
|
230
|
+
function inputActionsOf(steps) {
|
|
231
|
+
const atPoint = (at, index) => {
|
|
232
|
+
if (Array.isArray(at))
|
|
233
|
+
return at;
|
|
234
|
+
throw new SurfaceError("unsupported", `step ${index + 1} names an element (${String(at)}): this computer has no ui group, so steps act at points of the screenshot's pixels`);
|
|
235
|
+
};
|
|
236
|
+
return steps.map((step, index) => {
|
|
237
|
+
if ("click" in step) {
|
|
238
|
+
const at = atPoint(step.click, index);
|
|
239
|
+
if (touchOnly)
|
|
240
|
+
return step.button === "right" ? { type: "long_press", at } : { type: "tap", at, ...(step.count && step.count > 1 ? { count: 2 } : {}) };
|
|
241
|
+
return { type: "click", at, ...(step.button ? { button: step.button } : {}), ...(step.count ? { count: step.count } : {}) };
|
|
242
|
+
}
|
|
243
|
+
if ("type" in step) {
|
|
244
|
+
if (step.into !== undefined)
|
|
245
|
+
throw new SurfaceError("unsupported", `step ${index + 1} types into an element: this computer has no ui group; click the field first, then type`);
|
|
246
|
+
return { type: "type", text: step.type };
|
|
247
|
+
}
|
|
248
|
+
if ("key" in step)
|
|
249
|
+
return { type: "key", keys: chordKeys(step.key) };
|
|
250
|
+
if ("nav" in step)
|
|
251
|
+
return { type: "button", name: step.nav };
|
|
252
|
+
if ("scroll" in step && touchOnly) {
|
|
253
|
+
// A touch-only phone has no wheel: the finger moves the other way, over the distance (dy > 0 shows what is below).
|
|
254
|
+
const [x, y] = atPoint(step.scroll, index);
|
|
255
|
+
return { type: "swipe", path: [[x, y], [Math.max(0, x - (step.dx ?? 0)), Math.max(0, y - (step.dy ?? 0))]] };
|
|
256
|
+
}
|
|
257
|
+
// By wheel clicks: every driver takes them, and several (X11's, Orgo's) refuse pixels. A click is about 120 pixels.
|
|
258
|
+
if ("scroll" in step)
|
|
259
|
+
return { type: "scroll", at: atPoint(step.scroll, index), unit: "clicks", ...(step.dx ? { dx: wheelClicks(step.dx) } : {}), ...(step.dy ? { dy: wheelClicks(step.dy) } : {}) };
|
|
260
|
+
if ("drag" in step)
|
|
261
|
+
return touchOnly ? { type: "swipe", path: step.drag, ...(step.ms ? { ms: step.ms } : {}) } : { type: "drag", path: step.drag };
|
|
262
|
+
throw new SurfaceError("unsupported", `step ${index + 1} (${stepName(step)}) needs the ui group, which this computer does not have: click, type, key, scroll and drag at points instead`);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
async function runInput(actions, observeAfter, signal) {
|
|
266
|
+
const result = await call("input.actions", { actions }, signal);
|
|
267
|
+
const steps = [];
|
|
268
|
+
for (let index = 0; index < Math.min(result.done, actions.length); index += 1)
|
|
269
|
+
steps.push({ route: "input", verified: false });
|
|
270
|
+
// A batch the computer refused whole (a full batch, past the limit) says so: its reason is the one step's error.
|
|
271
|
+
if (result.failed)
|
|
272
|
+
steps.push({ error: { kind: result.failed.kind, message: result.failed.message } });
|
|
273
|
+
const done = { steps };
|
|
274
|
+
if (observeAfter && !result.failed) {
|
|
275
|
+
// The settling wait is a batch of its own, so a full batch of actions still fits the computer's limit.
|
|
276
|
+
await call("input.actions", { actions: [{ type: "wait", ms: INPUT_SETTLE_MS }] }, signal);
|
|
277
|
+
done.after = await screenState(signal);
|
|
278
|
+
}
|
|
279
|
+
return done;
|
|
280
|
+
}
|
|
281
|
+
const hasPoint = (steps) => steps.some((step) => ("click" in step && Array.isArray(step.click)) || ("scroll" in step && Array.isArray(step.scroll)) || "drag" in step);
|
|
282
|
+
async function act(args, signal) {
|
|
283
|
+
const steps = args.steps ?? [];
|
|
284
|
+
if (!Array.isArray(steps))
|
|
285
|
+
throw new SurfaceError("invalid", "steps is a list of steps");
|
|
286
|
+
if (!has("ui")) {
|
|
287
|
+
if (args.expect)
|
|
288
|
+
throw new SurfaceError("unsupported", "this computer has no ui group, so it can't check an expect: take a screenshot to see the effect");
|
|
289
|
+
const actions = inputActionsOf(steps);
|
|
290
|
+
await inFront(args.app, signal);
|
|
291
|
+
return runInput(actions, Boolean(args.observe), signal);
|
|
292
|
+
}
|
|
293
|
+
const app = args.app;
|
|
294
|
+
const state = args.state ?? (hasPoint(steps) ? lastState.get(app ?? lastApp ?? "") : undefined);
|
|
295
|
+
const result = await call("ui.act", {
|
|
296
|
+
...(app ? { target: { app } } : {}),
|
|
297
|
+
...(state ? { state } : {}),
|
|
298
|
+
steps,
|
|
299
|
+
...(args.expect ? { expect: args.expect } : {}),
|
|
300
|
+
...(args.foreground ? { foreground: true } : {}),
|
|
301
|
+
}, signal);
|
|
302
|
+
const done = { steps: result.steps, ...(result.expect ? { expect: result.expect } : {}), changed: result.changed, state: result.state };
|
|
303
|
+
// The default state of a later point step stays the last observation's (stateOf): a state this act returned was never seen.
|
|
304
|
+
// A script may ask observe as options ({ image: true }); the tool's schema offers only true.
|
|
305
|
+
const again = args.observe;
|
|
306
|
+
// The window the act finished on: its app, else the app of the state it named, never the one in front.
|
|
307
|
+
const target = app ?? (args.state ? appOfState.get(args.state) : undefined);
|
|
308
|
+
if (again)
|
|
309
|
+
done.after = await observe({ ...(typeof again === "object" ? again : {}), ...(target ? { app: target } : {}) }, signal);
|
|
310
|
+
return done;
|
|
311
|
+
}
|
|
312
|
+
async function readFile(path, encoding, signal) {
|
|
313
|
+
const parts = [];
|
|
314
|
+
let offset = 0;
|
|
315
|
+
for (;;) {
|
|
316
|
+
const chunk = await call("files.read", { path, offset, length: MAX_CHUNK_BYTES }, signal);
|
|
317
|
+
const bytes = Buffer.from(chunk.data, "base64");
|
|
318
|
+
parts.push(bytes);
|
|
319
|
+
offset += bytes.length;
|
|
320
|
+
if (chunk.eof || bytes.length === 0)
|
|
321
|
+
break;
|
|
322
|
+
if (offset >= MAX_READ_BYTES)
|
|
323
|
+
throw new SurfaceError("limit", `${path} is past ${MAX_READ_BYTES} bytes: read it with the shell in parts`);
|
|
324
|
+
}
|
|
325
|
+
const all = Buffer.concat(parts);
|
|
326
|
+
return encoding === "base64" ? all.toString("base64") : all.toString("utf8");
|
|
327
|
+
}
|
|
328
|
+
async function writeFile(path, data, encoding, signal) {
|
|
329
|
+
const bytes = encoding === "base64" ? Buffer.from(data, "base64") : Buffer.from(data, "utf8");
|
|
330
|
+
let offset = 0;
|
|
331
|
+
do {
|
|
332
|
+
const part = bytes.subarray(offset, offset + MAX_CHUNK_BYTES);
|
|
333
|
+
await call("files.write", { path, data: part.toString("base64"), parents: true, ...(offset > 0 ? { offset } : {}) }, signal);
|
|
334
|
+
offset += part.length;
|
|
335
|
+
} while (offset < bytes.length);
|
|
336
|
+
}
|
|
337
|
+
const infoOf = (path, stat) => ({ path, type: stat.type, size: stat.size, mtimeMs: stat.mtimeMs });
|
|
338
|
+
async function listFiles(path, signal) {
|
|
339
|
+
const entries = [];
|
|
340
|
+
for (let page = 0; page < MAX_LIST_PAGES; page += 1) {
|
|
341
|
+
const result = await call("files.list", { path, ...(entries.length > 0 ? { offset: entries.length } : {}) }, signal);
|
|
342
|
+
entries.push(...result.entries);
|
|
343
|
+
if (!result.truncated || result.entries.length === 0)
|
|
344
|
+
break;
|
|
345
|
+
// Pages used up with more behind: a partial listing is never returned as the whole.
|
|
346
|
+
if (page === MAX_LIST_PAGES - 1)
|
|
347
|
+
throw new SurfaceError("limit", `${path} has more than ${entries.length} entries: list it with the shell in parts`);
|
|
348
|
+
}
|
|
349
|
+
return entries.map((entry) => infoOf(entry.path, entry));
|
|
350
|
+
}
|
|
351
|
+
/** A command's argv: a string in the shell (cmd on Windows), a list as given. */
|
|
352
|
+
function argvOf(command) {
|
|
353
|
+
const argv = typeof command === "string" ? (card.os === "windows" ? ["cmd.exe", "/d", "/s", "/c", command] : ["sh", "-c", command]) : Array.isArray(command) && command.every((part) => typeof part === "string") ? command : undefined;
|
|
354
|
+
if (!argv || argv.length === 0)
|
|
355
|
+
throw new SurfaceError("invalid", "command is a string (run by the shell) or a list: the program and its arguments");
|
|
356
|
+
return argv;
|
|
357
|
+
}
|
|
358
|
+
/** A program's env: on a desktop with an X display, its DISPLAY (the daemon gives its programs none: protocol.ts
|
|
359
|
+
* ExecRunParams), so an app opens where the screen is; the call's own variables over it. */
|
|
360
|
+
function envOf(given) {
|
|
361
|
+
const env = { ...(hello.display ? { DISPLAY: hello.display } : {}), ...(given ?? {}) };
|
|
362
|
+
return Object.keys(env).length > 0 ? { env } : {};
|
|
363
|
+
}
|
|
364
|
+
async function run(args, signal) {
|
|
365
|
+
const argv = argvOf(args.command);
|
|
366
|
+
const timeoutMs = Math.min(Math.max(1, args.timeoutMs ?? DEFAULT_RUN_MS), MAX_RUN_MS);
|
|
367
|
+
const result = await call("exec.run", { argv, timeoutMs, ...(args.cwd ? { cwd: args.cwd } : {}), ...envOf(args.env) }, signal);
|
|
368
|
+
return {
|
|
369
|
+
stdout: Buffer.from(result.stdout, "base64").toString("utf8"),
|
|
370
|
+
stderr: Buffer.from(result.stderr, "base64").toString("utf8"),
|
|
371
|
+
exitCode: result.exitCode,
|
|
372
|
+
timedOut: result.timedOut,
|
|
373
|
+
truncated: result.truncated,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const pathOf = (args) => {
|
|
377
|
+
if (typeof args.path !== "string" || args.path === "")
|
|
378
|
+
throw new SurfaceError("invalid", "path is an absolute path on the computer");
|
|
379
|
+
return args.path;
|
|
380
|
+
};
|
|
381
|
+
async function answer(op, args, signal) {
|
|
382
|
+
switch (op) {
|
|
383
|
+
case "observe":
|
|
384
|
+
return observeAnswer(await observe(args, signal));
|
|
385
|
+
case "act": {
|
|
386
|
+
// Each step named as its element was before the act: what it pressed, not what the press made of it.
|
|
387
|
+
const given = args.steps;
|
|
388
|
+
const names = Array.isArray(given) ? given.map((step) => stepWords(step, (ref) => named.get(ref))) : [];
|
|
389
|
+
const result = await act(args, signal);
|
|
390
|
+
return { value: result, text: actText(names, result), images: result.after?.image ? [result.after.image] : [] };
|
|
391
|
+
}
|
|
392
|
+
case "input.act": {
|
|
393
|
+
const actions = args.actions;
|
|
394
|
+
if (!Array.isArray(actions))
|
|
395
|
+
throw new SurfaceError("invalid", "actions is a list of input actions");
|
|
396
|
+
const result = await runInput(actions, false, signal);
|
|
397
|
+
return { value: result, text: actText(actions.map((action) => String(action?.type ?? "action")), result), images: [] };
|
|
398
|
+
}
|
|
399
|
+
case "screenshot": {
|
|
400
|
+
const image = await shot(args.region, signal);
|
|
401
|
+
return { value: image, text: `screenshot ${image.width}×${image.height} px`, images: [image] };
|
|
402
|
+
}
|
|
403
|
+
case "apps.list": {
|
|
404
|
+
const result = await call("apps.list", {}, signal);
|
|
405
|
+
const apps = result.apps.map((app) => ({ id: app.id, ...(app.name ? { name: app.name } : {}) }));
|
|
406
|
+
const value = { apps, foreground: result.foreground };
|
|
407
|
+
return { value, text: jsonText(value), images: [] };
|
|
408
|
+
}
|
|
409
|
+
case "apps.open": {
|
|
410
|
+
if (typeof args.id !== "string" || args.id === "")
|
|
411
|
+
throw new SurfaceError("invalid", "id is the app's bundle id or package name");
|
|
412
|
+
await call("apps.launch", { id: args.id, ...(typeof args.url === "string" ? { url: args.url } : {}), ...(args.background === true ? { background: true } : {}) }, signal);
|
|
413
|
+
return { value: { id: args.id }, text: `opened ${args.id}`, images: [] };
|
|
414
|
+
}
|
|
415
|
+
case "shell.run": {
|
|
416
|
+
const value = await run(args, signal);
|
|
417
|
+
return { value, text: jsonText(value), images: [] };
|
|
418
|
+
}
|
|
419
|
+
case "processes.start": {
|
|
420
|
+
const argv = argvOf(args.command);
|
|
421
|
+
// orphans "keep": what the program starts (a launcher that forks its app and exits) runs on too.
|
|
422
|
+
const started = await call("process.start", { argv, ...(typeof args.cwd === "string" && args.cwd ? { cwd: args.cwd } : {}), ...envOf(args.env), orphans: "keep" }, signal);
|
|
423
|
+
return { value: { pid: started.pid }, text: `started ${argv.join(" ")} (pid ${started.pid})`, images: [] };
|
|
424
|
+
}
|
|
425
|
+
case "files.read": {
|
|
426
|
+
const value = await readFile(pathOf(args), args.encoding, signal);
|
|
427
|
+
return { value, text: value.length > MAX_TEXT_CHARS ? `${value.slice(0, MAX_TEXT_CHARS)}… (${value.length - MAX_TEXT_CHARS} more characters)` : value, images: [] };
|
|
428
|
+
}
|
|
429
|
+
case "files.write": {
|
|
430
|
+
if (typeof args.data !== "string")
|
|
431
|
+
throw new SurfaceError("invalid", "data is the file's text, or its bytes as base64");
|
|
432
|
+
const path = pathOf(args);
|
|
433
|
+
await writeFile(path, args.data, args.encoding, signal);
|
|
434
|
+
return { value: null, text: `wrote ${path}`, images: [] };
|
|
435
|
+
}
|
|
436
|
+
case "files.list": {
|
|
437
|
+
const value = await listFiles(pathOf(args), signal);
|
|
438
|
+
return { value, text: jsonText(value), images: [] };
|
|
439
|
+
}
|
|
440
|
+
case "files.stat": {
|
|
441
|
+
const path = pathOf(args);
|
|
442
|
+
const value = infoOf(path, await call("files.stat", { path }, signal));
|
|
443
|
+
return { value, text: jsonText(value), images: [] };
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return {
|
|
448
|
+
card,
|
|
449
|
+
ops,
|
|
450
|
+
async call(op, args, options = {}) {
|
|
451
|
+
if (!SURFACE_OPS.includes(op))
|
|
452
|
+
throw new SurfaceError("invalid", `no such call: ${op}`);
|
|
453
|
+
const known = op;
|
|
454
|
+
if (!ops.includes(known))
|
|
455
|
+
throw new SurfaceError("unsupported", `this computer can't ${op}: it offers ${card.groups.join(", ") || "no groups"}`);
|
|
456
|
+
const given = args === undefined || args === null ? {} : args;
|
|
457
|
+
if (typeof given !== "object" || Array.isArray(given))
|
|
458
|
+
throw new SurfaceError("invalid", `${op} takes an object of arguments`);
|
|
459
|
+
return answer(known, given, options.signal);
|
|
460
|
+
},
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
/** A value with its images' data left out: the structured half of an answer whose images travel beside it. */
|
|
464
|
+
export function withoutImageData(value) {
|
|
465
|
+
if (Array.isArray(value))
|
|
466
|
+
return value.map(withoutImageData);
|
|
467
|
+
if (value === null || typeof value !== "object")
|
|
468
|
+
return value;
|
|
469
|
+
const record = value;
|
|
470
|
+
if (record.type === "image" && typeof record.data === "string") {
|
|
471
|
+
const { data: _data, ...rest } = record;
|
|
472
|
+
return rest;
|
|
473
|
+
}
|
|
474
|
+
return Object.fromEntries(Object.entries(record).map(([key, entry]) => [key, withoutImageData(entry)]));
|
|
475
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type * from "./api.js";
|
|
2
|
+
export { actText, cardOf, chordKeys, createSurface, MAX_READ_BYTES, opsOf, stepName, SURFACE_OPS, SurfaceError, withoutImageData } from "./core.js";
|
|
3
|
+
export type { Surface, SurfaceAnswer, SurfaceOp } from "./core.js";
|
|
4
|
+
export { lineOf, OUTLINE_MAX_CHARS, outlineOf } from "./outline.js";
|
|
5
|
+
export { bindComputer, COMPUTER_CALL_GLOBAL, scriptPrelude } from "./script.js";
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { actText, cardOf, chordKeys, createSurface, MAX_READ_BYTES, opsOf, stepName, SURFACE_OPS, SurfaceError, withoutImageData } from "./core.js";
|
|
2
|
+
export { lineOf, OUTLINE_MAX_CHARS, outlineOf } from "./outline.js";
|
|
3
|
+
export { bindComputer, COMPUTER_CALL_GLOBAL, scriptPrelude } from "./script.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { UiNode } from "../protocol.js";
|
|
2
|
+
/** The most characters an outline takes: past it, the last line counts the elements left out. */
|
|
3
|
+
export declare const OUTLINE_MAX_CHARS = 12000;
|
|
4
|
+
/** A name or value as the outline shows it: on one line, cut, in JSON's quotes. */
|
|
5
|
+
export declare const quoted: (text: string) => string;
|
|
6
|
+
/** One element's line: `@e4 button "Save" = "value" ("what else it says") [focused]`. */
|
|
7
|
+
export declare function lineOf(node: UiNode): string;
|
|
8
|
+
/** The outline of an observation: `head`, then the elements within OUTLINE_MAX_CHARS, each indented under its parent,
|
|
9
|
+
* then a line saying what was left out (by the driver, `truncated`, or here for room). */
|
|
10
|
+
export declare function outlineOf(head: string, nodes: readonly UiNode[], truncated: boolean, empty?: string): string;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** The most characters an outline takes: past it, the last line counts the elements left out. */
|
|
2
|
+
export const OUTLINE_MAX_CHARS = 12_000;
|
|
3
|
+
/** The most characters of an element's name or value the outline shows. */
|
|
4
|
+
const TEXT_CHARS = 80;
|
|
5
|
+
/** The deepest indent, in levels: deeper elements line up at it. */
|
|
6
|
+
const MAX_INDENT = 8;
|
|
7
|
+
const clip = (text) => (text.length > TEXT_CHARS ? `${text.slice(0, TEXT_CHARS - 1)}…` : text);
|
|
8
|
+
/** A name or value as the outline shows it: on one line, cut, in JSON's quotes. */
|
|
9
|
+
export const quoted = (text) => JSON.stringify(clip(text.replace(/\s+/g, " ").trim()));
|
|
10
|
+
/** One element's line: `@e4 button "Save" = "value" ("what else it says") [focused]`. */
|
|
11
|
+
export function lineOf(node) {
|
|
12
|
+
const parts = [node.ref, node.role];
|
|
13
|
+
if (node.name)
|
|
14
|
+
parts.push(quoted(node.name));
|
|
15
|
+
if (node.value !== undefined && node.value !== "" && node.value !== node.name)
|
|
16
|
+
parts.push(`= ${quoted(node.value)}`);
|
|
17
|
+
if (node.desc && node.desc !== node.name)
|
|
18
|
+
parts.push(`(${quoted(node.desc)})`);
|
|
19
|
+
if (node.flags && node.flags.length > 0)
|
|
20
|
+
parts.push(`[${node.flags.join(" ")}]`);
|
|
21
|
+
return parts.join(" ");
|
|
22
|
+
}
|
|
23
|
+
/** The outline of an observation: `head`, then the elements within OUTLINE_MAX_CHARS, each indented under its parent,
|
|
24
|
+
* then a line saying what was left out (by the driver, `truncated`, or here for room). */
|
|
25
|
+
export function outlineOf(head, nodes, truncated, empty) {
|
|
26
|
+
const depth = new Map();
|
|
27
|
+
const lines = [head];
|
|
28
|
+
let room = OUTLINE_MAX_CHARS - head.length - 100;
|
|
29
|
+
let shown = 0;
|
|
30
|
+
for (const node of nodes) {
|
|
31
|
+
const level = node.parent === undefined ? 0 : (depth.get(node.parent) ?? -1) + 1;
|
|
32
|
+
depth.set(node.ref, level);
|
|
33
|
+
const next = `${" ".repeat(Math.min(level, MAX_INDENT))}${lineOf(node)}`;
|
|
34
|
+
if (next.length + 1 > room)
|
|
35
|
+
break;
|
|
36
|
+
lines.push(next);
|
|
37
|
+
room -= next.length + 1;
|
|
38
|
+
shown += 1;
|
|
39
|
+
}
|
|
40
|
+
const cut = nodes.length - shown;
|
|
41
|
+
if (cut > 0)
|
|
42
|
+
lines.push(`… ${cut} more elements not shown: find() them in a script, or act on a scrollarea to see others`);
|
|
43
|
+
else if (truncated)
|
|
44
|
+
lines.push("… the computer left out more elements: scroll to see others, or observe with full");
|
|
45
|
+
// The computer can't read this window's elements (ui.tree off): its words, and the image it sent instead.
|
|
46
|
+
if (nodes.length === 0 && empty)
|
|
47
|
+
lines.push(`(no elements: ${empty}; act at points in the window's image)`);
|
|
48
|
+
else if (nodes.length === 0)
|
|
49
|
+
lines.push("(no elements: the window shows nothing with a name; observe with image: true to see it)");
|
|
50
|
+
return lines.join("\n");
|
|
51
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Card, Computer } from "./api.js";
|
|
2
|
+
type Call = (op: string, args: unknown) => Promise<unknown>;
|
|
3
|
+
/** The `computer` object over `call`, with only the namespaces `card.groups` offers. Self-contained: see scriptPrelude. */
|
|
4
|
+
export declare function bindComputer(call: Call, card: Card): Computer;
|
|
5
|
+
/** The global a script's isolate holds the host's call under. */
|
|
6
|
+
export declare const COMPUTER_CALL_GLOBAL = "__computerCall";
|
|
7
|
+
/** One line that binds `computer` in a script, over the global COMPUTER_CALL_GLOBAL: put it before the script's first
|
|
8
|
+
* line (as `${scriptPrelude(card)} ${code}`) and the script's line numbers stay its own. */
|
|
9
|
+
export declare function scriptPrelude(card: Card): string;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/** The `computer` object over `call`, with only the namespaces `card.groups` offers. Self-contained: see scriptPrelude. */
|
|
2
|
+
export function bindComputer(call, card) {
|
|
3
|
+
const has = (group) => card.groups.indexOf(group) >= 0;
|
|
4
|
+
const freeze = Object.freeze;
|
|
5
|
+
const bind = (id) => {
|
|
6
|
+
let last;
|
|
7
|
+
const act = async (steps, options = {}) => {
|
|
8
|
+
const args = { steps };
|
|
9
|
+
if (id !== undefined)
|
|
10
|
+
args.app = id;
|
|
11
|
+
const state = options.state ?? last?.id;
|
|
12
|
+
const atPoint = steps.some((step) => ("click" in step && Array.isArray(step.click)) || ("scroll" in step && Array.isArray(step.scroll)) || "drag" in step);
|
|
13
|
+
if (options.state !== undefined || (atPoint && state !== undefined))
|
|
14
|
+
args.state = state;
|
|
15
|
+
if (options.expect !== undefined)
|
|
16
|
+
args.expect = options.expect;
|
|
17
|
+
if (options.foreground === true)
|
|
18
|
+
args.foreground = true;
|
|
19
|
+
if (options.observe)
|
|
20
|
+
args.observe = options.observe;
|
|
21
|
+
const result = (await call("act", args));
|
|
22
|
+
if (result.after)
|
|
23
|
+
last = result.after;
|
|
24
|
+
// A refused step is the last one run (api.ts ActResult): the script stops there, as computer_script's words say, so
|
|
25
|
+
// no later action lands on a screen it did not expect.
|
|
26
|
+
for (let index = 0; index < result.steps.length; index += 1) {
|
|
27
|
+
const step = result.steps[index];
|
|
28
|
+
if (step.error)
|
|
29
|
+
throw new Error(`step ${index + 1} was refused (${step.error.kind}): ${step.error.message}`);
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
};
|
|
33
|
+
const app = {
|
|
34
|
+
get id() {
|
|
35
|
+
return id ?? last?.app.id ?? "";
|
|
36
|
+
},
|
|
37
|
+
async observe(options = {}) {
|
|
38
|
+
last = (await call("observe", { ...(id !== undefined ? { app: id } : {}), ...options }));
|
|
39
|
+
return last;
|
|
40
|
+
},
|
|
41
|
+
find(query) {
|
|
42
|
+
if (!last)
|
|
43
|
+
throw new Error("find() reads the app's last observation: call observe() first");
|
|
44
|
+
const text = query.text;
|
|
45
|
+
const holds = (value) => value !== undefined && (typeof text === "string" ? value.toLowerCase().indexOf(text.toLowerCase()) >= 0 : text instanceof RegExp ? ((text.lastIndex = 0), text.test(value)) : true);
|
|
46
|
+
return last.elements.filter((node) => (query.role === undefined || node.role === query.role) && (query.id === undefined || node.id === query.id) && (text === undefined || holds(node.name) || holds(node.value) || holds(node.desc)));
|
|
47
|
+
},
|
|
48
|
+
act,
|
|
49
|
+
press: (ref, options) => act([{ press: ref }], options),
|
|
50
|
+
set: (ref, value, options) => act([{ set: ref, value }], options),
|
|
51
|
+
click: (at, options = {}) => act([{ click: at, ...(options.button ? { button: options.button } : {}), ...(options.count ? { count: options.count } : {}) }], options),
|
|
52
|
+
type: (text, options = {}) => act([{ type: text, ...(options.into !== undefined ? { into: options.into } : {}) }], options),
|
|
53
|
+
key: (chord, options) => act([{ key: chord }], options),
|
|
54
|
+
scroll: (at, delta, options) => act([{ scroll: at, ...delta }], options),
|
|
55
|
+
waitFor: (expect) => act([], { expect }),
|
|
56
|
+
};
|
|
57
|
+
return freeze(app);
|
|
58
|
+
};
|
|
59
|
+
const computer = { card: freeze(card) };
|
|
60
|
+
if (has("apps"))
|
|
61
|
+
computer.apps = freeze({
|
|
62
|
+
list: () => call("apps.list", {}),
|
|
63
|
+
async open(id, options = {}) {
|
|
64
|
+
await call("apps.open", { id, ...options });
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
if (has("ui"))
|
|
68
|
+
computer.app = (id) => bind(id);
|
|
69
|
+
if (has("screen"))
|
|
70
|
+
computer.screen = freeze({ shot: (options = {}) => call("screenshot", options) });
|
|
71
|
+
if (has("input.pointer") || has("input.touch") || has("input.keys"))
|
|
72
|
+
computer.input = freeze({ act: (actions) => call("input.act", { actions }) });
|
|
73
|
+
if (has("exec"))
|
|
74
|
+
computer.shell = freeze({ run: (command, options = {}) => call("shell.run", { ...options, command }) });
|
|
75
|
+
if (has("processes"))
|
|
76
|
+
computer.processes = freeze({ start: (command, options = {}) => call("processes.start", { ...options, command }) });
|
|
77
|
+
if (has("files"))
|
|
78
|
+
computer.files = freeze({
|
|
79
|
+
read: (path, options = {}) => call("files.read", { ...options, path }),
|
|
80
|
+
write: async (path, data, options = {}) => {
|
|
81
|
+
await call("files.write", { ...options, path, data });
|
|
82
|
+
},
|
|
83
|
+
list: (path) => call("files.list", { path }),
|
|
84
|
+
stat: (path) => call("files.stat", { path }),
|
|
85
|
+
});
|
|
86
|
+
return freeze(computer);
|
|
87
|
+
}
|
|
88
|
+
/** The global a script's isolate holds the host's call under. */
|
|
89
|
+
export const COMPUTER_CALL_GLOBAL = "__computerCall";
|
|
90
|
+
/** One line that binds `computer` in a script, over the global COMPUTER_CALL_GLOBAL: put it before the script's first
|
|
91
|
+
* line (as `${scriptPrelude(card)} ${code}`) and the script's line numbers stay its own. */
|
|
92
|
+
export function scriptPrelude(card) {
|
|
93
|
+
return `const computer = (0, eval)(${JSON.stringify(`(${String(bindComputer)})`)})(${COMPUTER_CALL_GLOBAL}, ${JSON.stringify(card)});`;
|
|
94
|
+
}
|