@omacode/micromanager 0.0.0-stage → 1.0.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 (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
@@ -0,0 +1,679 @@
1
+ // The `playwright` tool of the visual workers: a real Playwright browser on the host, driving the page a worker built.
2
+ // `look` answers "what does it look like"; this answers "what happens when I click it", and records the run.
3
+ //
4
+ // Same boundary as `look` (src/look.ts): the page is served from the worker's own directory on 127.0.0.1, Chromium runs
5
+ // outside the worker sandbox, and every request is checked against the job's granted hosts. Unlike `look`, the worker
6
+ // does not hand over JavaScript: it names steps, and this module maps each to a Playwright call. A worker-written script
7
+ // would run with the user's rights in the plugin's process — the hole the whole sandbox exists to close — so the step
8
+ // list is the interface, and Playwright stays the engine behind it.
9
+ import { spawn } from "node:child_process";
10
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync } from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import { homedir } from "node:os";
13
+ import { basename, dirname, join, resolve, sep } from "node:path";
14
+ import { findChromium, hostAllowed, lookTarget, MAX_IMAGE_BYTES, resolverRules, serveDir } from "./look.js";
15
+ import { findTool } from "./which.js";
16
+ // A run is bounded in every dimension a worker could spend the host's time and space on.
17
+ export const MAX_STEPS = 80;
18
+ export const MAX_SHOTS = 6;
19
+ export const MAX_IMAGES = 8;
20
+ export const MAX_ARTIFACT_BYTES = 40 * 1024 * 1024;
21
+ export const MAX_SHOT_HEIGHT = 8000;
22
+ export const DEFAULT_TIMEOUT_MS = 120_000;
23
+ export const MAX_TIMEOUT_MS = 300_000;
24
+ const MAX_TEXT = 4000; // one eval result or one console line, in characters
25
+ const fail = (text) => ({ text, images: [], artifacts: [] });
26
+ const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, Math.round(n)));
27
+ const truthy = (value) => /^(true|yes|1|on)$/i.test((value ?? "").trim());
28
+ const within = (root, file) => file === root || file.startsWith(root + sep);
29
+ const message = (err) => (err instanceof Error ? err.message : String(err)).split("\n")[0];
30
+ // The step language. Deliberately a list of verbs, not code: each maps to one Playwright call, so the engine keeps its
31
+ // auto-waiting and selector syntax (css, text=, role=, [data-testid=…]) without handing the worker the process.
32
+ const SELECTOR_ACTIONS = new Set(["click", "dblclick", "hover", "focus", "check", "uncheck", "waitFor", "waitHidden", "scrollTo"]);
33
+ const POINT_ACTIONS = new Set(["scroll", "wheel", "viewport"]);
34
+ const FLAG_ACTIONS = new Set(["back", "forward", "reload"]);
35
+ const ACTIONS = [
36
+ "goto", "click", "dblclick", "hover", "focus", "check", "uncheck", "fill", "type", "press", "select", "upload",
37
+ "waitFor", "waitHidden", "waitText", "sleep", "idle", "scroll", "wheel", "scrollTo", "viewport", "eval", "shot",
38
+ "pdf", "back", "forward", "reload",
39
+ ];
40
+ // "goto": "/dashboard" | "https://granted.host/x" — a path is the served directory, a URL must be a granted host.
41
+ // Every other value shape is checked here, before a browser starts, so a typo costs a sentence and not a minute.
42
+ export function parseSteps(text) {
43
+ const raw = (text ?? "").trim();
44
+ if (!raw)
45
+ return [];
46
+ let value;
47
+ try {
48
+ value = JSON.parse(raw);
49
+ }
50
+ catch {
51
+ throw new Error("steps is not JSON; give an array like [{\"click\":\"#start\"},{\"shot\":\"after.png\"}]");
52
+ }
53
+ if (!Array.isArray(value))
54
+ throw new Error("steps must be a JSON array of objects, one action per object");
55
+ if (value.length > MAX_STEPS)
56
+ throw new Error(`steps has ${value.length} actions; a run is limited to ${MAX_STEPS}`);
57
+ return value.map((entry, i) => {
58
+ const at = `step ${i + 1}`;
59
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
60
+ throw new Error(`${at}: every step is an object like {"click":"#start"}`);
61
+ const keys = Object.keys(entry);
62
+ if (keys.length !== 1)
63
+ throw new Error(`${at}: one action per step, got ${keys.length ? keys.join(", ") : "none"}`);
64
+ const action = keys[0];
65
+ if (!ACTIONS.includes(action))
66
+ throw new Error(`${at}: unknown action "${action}"; one of ${ACTIONS.join(", ")}`);
67
+ return { action, args: argsOf(action, entry[action], at) };
68
+ });
69
+ }
70
+ function argsOf(action, value, at) {
71
+ const bad = (wanted) => {
72
+ const got = typeof value === "string" ? JSON.stringify(value) : Array.isArray(value) ? JSON.stringify(value) : String(value);
73
+ return new Error(`${at}: ${action} takes ${wanted}, got ${got}`);
74
+ };
75
+ const text = (v) => {
76
+ if (typeof v !== "string" || !v.trim())
77
+ throw bad("a non-empty string");
78
+ return v;
79
+ };
80
+ const count = (v) => {
81
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0)
82
+ throw bad("a number of milliseconds");
83
+ return v;
84
+ };
85
+ const pair = (v, what) => {
86
+ if (!Array.isArray(v) || v.length !== 2 || v.some((x) => typeof x !== "string"))
87
+ throw bad(`[${what}, …]`);
88
+ return v;
89
+ };
90
+ const point = (v) => {
91
+ if (!Array.isArray(v) || v.length !== 2 || v.some((x) => typeof x !== "number"))
92
+ throw bad("[x, y] numbers");
93
+ return v;
94
+ };
95
+ if (SELECTOR_ACTIONS.has(action))
96
+ return [text(value)];
97
+ if (action === "fill" || action === "waitText") {
98
+ const [a, b] = pair(value, "selector");
99
+ return [a, b];
100
+ }
101
+ if (action === "press" || action === "select" || action === "upload") {
102
+ const [a, b] = pair(value, action === "upload" ? "selector, path" : "selector, value");
103
+ return [a, b];
104
+ }
105
+ if (action === "type") {
106
+ if (!Array.isArray(value) || value.length < 2 || value.length > 3 || typeof value[0] !== "string" || typeof value[1] !== "string")
107
+ throw bad('[selector, text] or [selector, text, delay]');
108
+ const delay = value[2] === undefined ? 0 : Number(value[2]);
109
+ if (!Number.isFinite(delay) || delay < 0)
110
+ throw bad('[selector, text] or [selector, text, delay]');
111
+ return [value[0], value[1], Math.round(delay)];
112
+ }
113
+ if (POINT_ACTIONS.has(action))
114
+ return point(value);
115
+ if (action === "sleep" || action === "idle")
116
+ return [value === true ? 0 : count(value)];
117
+ if (action === "shot") {
118
+ if (Array.isArray(value)) {
119
+ const [a, b] = pair(value, "selector, name");
120
+ return [a, b];
121
+ }
122
+ return [text(value)];
123
+ }
124
+ if (FLAG_ACTIONS.has(action)) {
125
+ if (value !== true && value !== "")
126
+ throw bad('true (for example {"back":true})');
127
+ return [];
128
+ }
129
+ // goto, eval, pdf and anything else with a single string
130
+ return [text(value)];
131
+ }
132
+ // One step's worth of extra network access: hostAllowed counts a port that the granted host names, as `look` does.
133
+ function navAllowed(url, localOrigin, allowed) {
134
+ let u;
135
+ try {
136
+ u = new URL(url);
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ if (!/^https?:$/.test(u.protocol))
142
+ return false;
143
+ return u.origin === localOrigin || hostAllowed(u.host, allowed);
144
+ }
145
+ // Where the tool's files go: the worker's named directory, or the job's media folder (outside every worktree, so a
146
+ // recording never lands in a commit by accident).
147
+ function artifactDirFor(out, dir, base, label) {
148
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
149
+ if (out?.trim()) {
150
+ const root = realpathSync(dir);
151
+ const full = resolve(root, out.trim());
152
+ if (!within(root, full))
153
+ throw new Error(`${out} is outside your directory.`);
154
+ mkdirSync(full, { recursive: true });
155
+ const real = realpathSync(full);
156
+ if (!within(root, real))
157
+ throw new Error(`${out} resolves outside your directory.`);
158
+ return real;
159
+ }
160
+ const name = `${label ? `${label.replace(/[^\w.-]+/g, "-")}-` : ""}${stamp}`;
161
+ const full = join(base, name);
162
+ mkdirSync(full, { recursive: true });
163
+ return full;
164
+ }
165
+ // A file inside the artifact directory, checked after its parent is made real: a worker can plant a symlink there.
166
+ function artifactFile(root, name, fallback) {
167
+ const clean = name.trim() || fallback;
168
+ const full = resolve(root, clean);
169
+ if (!within(root, full))
170
+ throw new Error(`${name} leaves the artifact directory.`);
171
+ mkdirSync(dirname(full), { recursive: true });
172
+ const parent = realpathSync(dirname(full));
173
+ if (!within(realpathSync(root), parent))
174
+ throw new Error(`${name} resolves outside the artifact directory.`);
175
+ return full;
176
+ }
177
+ // Playwright records video through its own ffmpeg build, which `playwright install` puts beside the browsers. A system
178
+ // ffmpeg is enough for that role (spike, 2026-10-30: a 1.9 s WebM, frames readable), so a missing download is filled
179
+ // with a link to the one on PATH rather than a 150 MB browser install.
180
+ export function ffmpegRevision() {
181
+ try {
182
+ const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
183
+ const json = JSON.parse(readFileSync(join(dirname(pkg), "browsers.json"), "utf8"));
184
+ return json.browsers?.find((b) => b.name === "ffmpeg")?.revision;
185
+ }
186
+ catch {
187
+ return undefined;
188
+ }
189
+ }
190
+ const FFMEG_NAMES = { linux: "ffmpeg-linux", darwin: "ffmpeg-mac", win32: "ffmpeg-win64.exe" };
191
+ const ffmpegName = () => FFMEG_NAMES[process.platform];
192
+ export function ensureFfmpeg(env = process.env) {
193
+ const exe = ffmpegName();
194
+ const revision = ffmpegRevision();
195
+ if (!exe || !revision)
196
+ return { ok: false, why: "this platform or Playwright build has no ffmpeg" };
197
+ const home = env.HOME || homedir();
198
+ // Playwright reads PLAYWRIGHT_BROWSERS_PATH when it is loaded, and its default is this cache. A link for the one
199
+ // binary video needs belongs exactly where `npx playwright install ffmpeg` would have put it; the browsers themselves
200
+ // are never touched, because the system Chromium is launched by path.
201
+ const root = env.PLAYWRIGHT_BROWSERS_PATH?.trim() || join(home, ".cache", "ms-playwright");
202
+ const target = join(root, `ffmpeg-${revision}`, exe);
203
+ if (existsSync(target))
204
+ return { ok: true, bin: findTool("ffmpeg", env) ?? target };
205
+ const system = findTool("ffmpeg", env);
206
+ if (!system)
207
+ return { ok: false, why: "no ffmpeg on PATH and Playwright's own ffmpeg is not installed" };
208
+ try {
209
+ mkdirSync(dirname(target), { recursive: true });
210
+ try {
211
+ symlinkSync(system, target);
212
+ }
213
+ catch {
214
+ copyFileSync(system, target);
215
+ }
216
+ return { ok: true, bin: system };
217
+ }
218
+ catch (err) {
219
+ return { ok: false, why: `could not place ffmpeg at ${target}: ${message(err)}` };
220
+ }
221
+ }
222
+ // A still from a video, so the model sees what the recording shows; the file itself is for the user.
223
+ async function keyframes(bin, video, dir, limit) {
224
+ const probe = findTool("ffprobe") ?? join(dirname(bin), process.platform === "win32" ? "ffprobe.exe" : "ffprobe");
225
+ if (!existsSync(probe))
226
+ return [];
227
+ const duration = await new Promise((ok) => {
228
+ const child = spawn(probe, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", video], { stdio: ["ignore", "pipe", "ignore"] });
229
+ let out = "";
230
+ child.stdout.on("data", (d) => (out += d.toString()));
231
+ child.once("error", () => ok(0));
232
+ child.once("close", () => ok(Number(out.trim()) || 0));
233
+ });
234
+ if (!(duration > 0))
235
+ return [];
236
+ const out = [];
237
+ for (const fraction of [0.15, 0.4, 0.65, 0.9].slice(0, limit)) {
238
+ const file = join(dir, `frame-${Math.round(fraction * 100)}.png`);
239
+ const at = (duration * fraction).toFixed(2);
240
+ const made = await new Promise((ok) => {
241
+ const child = spawn(bin, ["-v", "error", "-ss", at, "-i", video, "-frames:v", "1", "-y", file], { stdio: "ignore" });
242
+ child.once("error", () => ok(false));
243
+ child.once("close", (code) => ok(code === 0 && existsSync(file)));
244
+ });
245
+ if (!made)
246
+ continue;
247
+ try {
248
+ const data = readFileSync(file);
249
+ if (data.length <= MAX_IMAGE_BYTES)
250
+ out.push({ data, mime: "image/png" });
251
+ }
252
+ catch {
253
+ // a missing frame is not a failed run
254
+ }
255
+ }
256
+ return out;
257
+ }
258
+ // Two recordings at once are plenty for a machine that also runs workers; a third waits by asking again.
259
+ let active = 0;
260
+ export async function runBrowser(raw, dir, allowed, opts) {
261
+ if (active >= 2)
262
+ return fail("two browser runs are already going; try again when one has finished");
263
+ active++;
264
+ try {
265
+ return await drive(raw, dir, allowed, opts);
266
+ }
267
+ finally {
268
+ active--;
269
+ }
270
+ }
271
+ // The page as a worker drives it: one browser, one context, steps in order. opts.base is where artifacts go.
272
+ async function drive(raw, dir, allowed, opts) {
273
+ const target = lookTarget({ path: raw.path, url: raw.url }, dir, allowed);
274
+ if (target.kind === "error")
275
+ return fail(target.text);
276
+ if (target.kind === "image")
277
+ return fail("playwright drives a page, not an image; use look for an image.");
278
+ let steps;
279
+ try {
280
+ steps = parseSteps(raw.steps);
281
+ }
282
+ catch (err) {
283
+ return fail(message(err));
284
+ }
285
+ const chromium = opts.chromium === undefined ? (findChromium() ?? null) : opts.chromium;
286
+ if (!chromium)
287
+ return fail("No browser is installed where the plugin runs (chromium, google-chrome or Playwright's chromium), so a page cannot be driven.");
288
+ const width = clamp(Number(raw.width) || 1280, 320, 2560);
289
+ const height = clamp(Number(raw.height) || 800, 240, 4000);
290
+ const fullPage = !/^(false|no|0)$/i.test((raw.full ?? "").trim());
291
+ // An empty field means "not given": the tool hands every field over as a string, "" included.
292
+ const settleMs = raw.settle?.trim() ? clamp(Number(raw.settle) || 0, 0, 10_000) : 300;
293
+ const timeoutMs = clamp((raw.timeout?.trim() ? Number(raw.timeout) || DEFAULT_TIMEOUT_MS / 1000 : DEFAULT_TIMEOUT_MS / 1000) * 1000, 5000, MAX_TIMEOUT_MS);
294
+ const video = truthy(raw.video);
295
+ const mp4 = (raw.format ?? "").trim().toLowerCase() === "mp4";
296
+ let ffmpeg = { ok: false };
297
+ if (video) {
298
+ ffmpeg = ensureFfmpeg(opts.env);
299
+ if (!ffmpeg.ok)
300
+ return fail(`video was asked for, but recording needs ffmpeg: ${ffmpeg.why ?? "not found"}. Run "npx playwright install ffmpeg" once, or install ffmpeg, then look again. A run without video still works.`);
301
+ }
302
+ let artifactDir;
303
+ try {
304
+ artifactDir = artifactDirFor(raw.out, dir, opts.base, opts.label);
305
+ }
306
+ catch (err) {
307
+ return fail(message(err));
308
+ }
309
+ const images = [];
310
+ const artifacts = [];
311
+ const problems = []; // console errors and page exceptions
312
+ const failed = []; // requests that never completed
313
+ const results = []; // eval answers, in order
314
+ let shots = 0;
315
+ let server;
316
+ let browser;
317
+ let context;
318
+ let recording;
319
+ let videoFile;
320
+ let outcome = "";
321
+ const started = Date.now();
322
+ const push = (list, line) => {
323
+ if (list.length < 20)
324
+ list.push(line.slice(0, MAX_TEXT));
325
+ };
326
+ try {
327
+ const { chromium: engine, devices } = await import("playwright-core").catch(() => {
328
+ throw new Error("playwright-core is not installed where the plugin runs; install the plugin's dependencies (npm install)");
329
+ });
330
+ let startUrl;
331
+ let localOrigin;
332
+ if (target.kind === "page") {
333
+ server = await serveDir(target.root, { fallback: true });
334
+ localOrigin = server.origin;
335
+ startUrl = `${server.origin}${target.path}`;
336
+ }
337
+ else {
338
+ startUrl = target.url;
339
+ localOrigin = new URL(target.url).origin;
340
+ }
341
+ const device = raw.device?.trim() ? devices[raw.device.trim()] : undefined;
342
+ if (raw.device?.trim() && !device)
343
+ throw new Error(`unknown device "${raw.device}"; try "iPhone 13", "Pixel 7" or "iPad Pro 11"`);
344
+ browser = await engine.launch({
345
+ executablePath: chromium,
346
+ headless: true,
347
+ chromiumSandbox: true,
348
+ args: [`--host-resolver-rules=${resolverRules(allowed)}`, "--disable-background-networking", "--hide-scrollbars", "--mute-audio"],
349
+ });
350
+ // A named device brings its own viewport, scale and user agent; explicit width/height win only without one.
351
+ const screen = device?.viewport;
352
+ context = await browser.newContext({
353
+ ...(device ?? {}),
354
+ ...(device ? {} : { viewport: { width, height } }),
355
+ deviceScaleFactor: 1, // a 3x phone screenshot is 9x the tokens of the same picture at 1x
356
+ serviceWorkers: "block",
357
+ acceptDownloads: false,
358
+ ...(video ? { recordVideo: { dir: artifactDir, size: screen ? { width: screen.width, height: screen.height } : { width, height } } } : {}),
359
+ });
360
+ context.setDefaultTimeout(timeoutMs);
361
+ context.setDefaultNavigationTimeout(timeoutMs);
362
+ // The allow-list, at the one place every request passes: the served page, data/blob, and the job's granted hosts.
363
+ // Chromium's resolver rules are the second line, not the first: they do not cover redirects or literal IPs.
364
+ await context.route("**/*", (route) => {
365
+ const request = route.request();
366
+ const url = request.url();
367
+ const ok = /^(about|data|blob):/.test(url) || navAllowed(url, localOrigin, allowed);
368
+ return (ok ? route.continue() : route.abort("blockedbyclient")).catch(() => undefined);
369
+ });
370
+ // A WebSocket is not an HTTP request, so route() never sees it; without this a page could reach a daemon on
371
+ // 127.0.0.1 that the resolver exclusions keep reachable. Ungranted sockets are closed, granted ones pass through.
372
+ try {
373
+ await context.routeWebSocket(/.*/, (ws) => {
374
+ if (navAllowed(ws.url(), localOrigin, allowed))
375
+ ws.connectToServer();
376
+ else
377
+ void ws.close().catch(() => undefined);
378
+ });
379
+ }
380
+ catch {
381
+ // an older Playwright without WebSocket routing: the launch flags still confine DNS
382
+ }
383
+ const page = await context.newPage();
384
+ recording = page.video() ?? undefined;
385
+ page.on("console", (m) => {
386
+ if (m.type() === "error")
387
+ push(problems, `console: ${m.text()}`);
388
+ });
389
+ page.on("pageerror", (err) => push(problems, `exception: ${err.message}`));
390
+ page.on("requestfailed", (r) => push(failed, `${r.url()} ${r.failure()?.errorText ?? ""}`.trim()));
391
+ page.on("dialog", (d) => void d.dismiss().catch(() => undefined));
392
+ page.on("popup", (p) => void p.close().catch(() => undefined));
393
+ // A page can be tens of thousands of pixels tall; `look` stops at 8000 and so does this, with a clip instead of a
394
+ // picture the provider would reject.
395
+ const snap = async (file) => {
396
+ if (!fullPage) {
397
+ await page.screenshot({ path: file });
398
+ return;
399
+ }
400
+ const size = await page.evaluate(() => ({
401
+ width: Math.max(document.documentElement.scrollWidth, document.body?.scrollWidth ?? 0),
402
+ height: Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0),
403
+ })).catch(() => ({ width, height }));
404
+ if (size.height > MAX_SHOT_HEIGHT) {
405
+ await page.screenshot({ path: file, clip: { x: 0, y: 0, width: Math.min(size.width || width, MAX_SHOT_HEIGHT), height: MAX_SHOT_HEIGHT } });
406
+ return;
407
+ }
408
+ await page.screenshot({ path: file, fullPage: true });
409
+ };
410
+ const settle = async () => {
411
+ await page.evaluate("document.fonts && document.fonts.ready ? document.fonts.ready.then(() => true) : true").catch(() => undefined);
412
+ if (settleMs)
413
+ await page.waitForTimeout(settleMs);
414
+ };
415
+ const go = async (url) => {
416
+ if (!navAllowed(url, localOrigin, allowed))
417
+ throw new Error(`${url} is not a host this job may reach`);
418
+ const r = await page.goto(url, { waitUntil: "load" });
419
+ if (r && r.status() >= 400)
420
+ throw new Error(`${url} answered ${r.status()}`);
421
+ await settle();
422
+ };
423
+ const resolvePath = (where) => {
424
+ if (/^https?:\/\//i.test(where))
425
+ return where; // go() checks the host list
426
+ if (!localOrigin)
427
+ throw new Error("this page was opened by URL; a goto needs a full URL");
428
+ let u;
429
+ try {
430
+ u = new URL(where, `${localOrigin}/`);
431
+ }
432
+ catch {
433
+ throw new Error(`"${where}" is no path`);
434
+ }
435
+ if (u.origin !== localOrigin)
436
+ throw new Error(`${where} leaves the served directory`);
437
+ return u.toString();
438
+ };
439
+ const save = (name, fallback) => artifactFile(artifactDir, name, fallback);
440
+ await go(startUrl);
441
+ for (const [i, step] of steps.entries()) {
442
+ const at = `step ${i + 1} (${step.action})`;
443
+ const sel = String(step.args[0] ?? "");
444
+ const locator = () => page.locator(sel).first();
445
+ try {
446
+ switch (step.action) {
447
+ case "goto":
448
+ await go(resolvePath(step.args[0]));
449
+ break;
450
+ case "click":
451
+ await locator().click();
452
+ break;
453
+ case "dblclick":
454
+ await locator().dblclick();
455
+ break;
456
+ case "hover":
457
+ await locator().hover();
458
+ break;
459
+ case "focus":
460
+ await locator().focus();
461
+ break;
462
+ case "check":
463
+ await locator().check();
464
+ break;
465
+ case "uncheck":
466
+ await locator().uncheck();
467
+ break;
468
+ case "fill":
469
+ await locator().fill(String(step.args[1]));
470
+ break;
471
+ case "type":
472
+ await locator().pressSequentially(String(step.args[1]), { delay: Number(step.args[2] ?? 0) });
473
+ break;
474
+ case "press":
475
+ if (sel)
476
+ await locator().press(String(step.args[1]));
477
+ else
478
+ await page.keyboard.press(String(step.args[1]));
479
+ break;
480
+ case "select":
481
+ await locator().selectOption(String(step.args[1]));
482
+ break;
483
+ case "upload": {
484
+ const file = confine(dir, String(step.args[1]));
485
+ await locator().setInputFiles(file);
486
+ break;
487
+ }
488
+ case "waitFor":
489
+ await locator().waitFor({ state: "visible" });
490
+ break;
491
+ case "waitHidden":
492
+ await locator().waitFor({ state: "hidden" });
493
+ break;
494
+ case "waitText": {
495
+ const [selector, wanted] = [String(step.args[0]), String(step.args[1])];
496
+ await page.waitForFunction(([s, t]) => [...document.querySelectorAll(s)].some((e) => (e.textContent ?? "").includes(t)), [selector, wanted]);
497
+ break;
498
+ }
499
+ case "sleep":
500
+ await page.waitForTimeout(Number(step.args[0]));
501
+ break;
502
+ case "idle":
503
+ await page.waitForLoadState("networkidle", { timeout: Number(step.args[0]) || timeoutMs });
504
+ break;
505
+ case "scroll":
506
+ await page.evaluate(([x, y]) => window.scrollTo(x, y), [Number(step.args[0]), Number(step.args[1])]);
507
+ break;
508
+ case "wheel":
509
+ await page.mouse.wheel(Number(step.args[0]), Number(step.args[1]));
510
+ break;
511
+ case "scrollTo":
512
+ await locator().scrollIntoViewIfNeeded();
513
+ break;
514
+ case "viewport":
515
+ await page.setViewportSize({ width: clamp(Number(step.args[0]), 200, 3840), height: clamp(Number(step.args[1]), 200, 4000) });
516
+ break;
517
+ case "eval": {
518
+ const value = await page.evaluate(String(step.args[0]));
519
+ results.push(`eval ${i + 1}: ${JSON.stringify(value ?? null).slice(0, MAX_TEXT)}`);
520
+ break;
521
+ }
522
+ case "shot": {
523
+ if (shots >= MAX_SHOTS)
524
+ throw new Error(`a run takes at most ${MAX_SHOTS} screenshots`);
525
+ const element = step.args.length > 1 ? String(step.args[0]) : undefined;
526
+ const name = String(step.args[step.args.length - 1] ?? "");
527
+ const file = save(name, `shot-${shots + 1}.png`);
528
+ if (element)
529
+ await page.locator(element).first().screenshot({ path: file });
530
+ else
531
+ await snap(file);
532
+ shots++;
533
+ artifacts.push(file);
534
+ const data = readFileSync(file);
535
+ if (data.length > MAX_IMAGE_BYTES)
536
+ problems.push(`shot ${basename(file)} is ${data.length} bytes; not attached`);
537
+ else if (images.length < MAX_IMAGES)
538
+ images.push({ data, mime: "image/png" });
539
+ break;
540
+ }
541
+ case "pdf": {
542
+ const file = save(String(step.args[0]), "page.pdf");
543
+ await page.pdf({ path: file, format: "a4", printBackground: true });
544
+ artifacts.push(file);
545
+ break;
546
+ }
547
+ case "back":
548
+ await page.goBack({ waitUntil: "load" });
549
+ await settle();
550
+ break;
551
+ case "forward":
552
+ await page.goForward({ waitUntil: "load" });
553
+ await settle();
554
+ break;
555
+ case "reload":
556
+ await page.reload({ waitUntil: "load" });
557
+ await settle();
558
+ break;
559
+ default: throw new Error(`unknown action`);
560
+ }
561
+ }
562
+ catch (err) {
563
+ // A picture of the failure is worth more than the stack: the worker sees what the page showed.
564
+ try {
565
+ const file = save("failed.png", "failed.png");
566
+ await snap(file);
567
+ artifacts.push(file);
568
+ const data = readFileSync(file);
569
+ if (data.length <= MAX_IMAGE_BYTES && images.length < MAX_IMAGES)
570
+ images.push({ data, mime: "image/png" });
571
+ }
572
+ catch {
573
+ // no picture either, then
574
+ }
575
+ throw new Error(`${at} failed: ${message(err)}`);
576
+ }
577
+ }
578
+ if (shots === 0) {
579
+ const file = save("final.png", "final.png");
580
+ await snap(file);
581
+ artifacts.push(file);
582
+ const data = readFileSync(file);
583
+ if (data.length <= MAX_IMAGE_BYTES && images.length < MAX_IMAGES)
584
+ images.push({ data, mime: "image/png" });
585
+ }
586
+ const title = await page.title().catch(() => "");
587
+ outcome = [`done: ${steps.length} step${steps.length === 1 ? "" : "s"} in ${((Date.now() - started) / 1000).toFixed(1)} s`, `page: ${page.url()} — "${title.slice(0, 120)}"`].join("\n");
588
+ }
589
+ catch (err) {
590
+ outcome = `failed: ${message(err)}`;
591
+ }
592
+ finally {
593
+ // Closing the context writes the recording; it survives a failed run too, which is often the interesting part.
594
+ if (context)
595
+ await context.close().catch(() => undefined);
596
+ if (recording)
597
+ videoFile = await recording.path().catch(() => undefined);
598
+ if (browser)
599
+ await browser.close().catch(() => undefined);
600
+ if (server)
601
+ await server.close();
602
+ }
603
+ // The video's own name is random; give the file a name the user can find again.
604
+ if (videoFile && existsSync(videoFile)) {
605
+ const wanted = join(artifactDir, `run${mp4 ? ".mp4" : ".webm"}`);
606
+ try {
607
+ if (mp4) {
608
+ if (!(await convert(ffmpeg.bin, videoFile, wanted)))
609
+ throw new Error("conversion failed");
610
+ rmSync(videoFile, { force: true });
611
+ }
612
+ else {
613
+ renameSync(videoFile, wanted);
614
+ }
615
+ videoFile = wanted;
616
+ artifacts.push(wanted);
617
+ }
618
+ catch {
619
+ artifacts.push(videoFile);
620
+ outcome += `\nthe recording is ${basename(videoFile)} (could not be renamed${mp4 ? " or converted to mp4" : ""})`;
621
+ }
622
+ }
623
+ if (videoFile && ffmpeg.bin && existsSync(videoFile)) {
624
+ const frames = await keyframes(ffmpeg.bin, videoFile, artifactDir, Math.max(0, MAX_IMAGES - images.length));
625
+ images.push(...frames);
626
+ }
627
+ const lines = [outcome];
628
+ if (results.length)
629
+ lines.push("results:", ...results.map((r) => ` ${r}`));
630
+ if (problems.length)
631
+ lines.push(`console (${problems.length}):`, ...problems.map((p) => ` ${p}`));
632
+ if (failed.length)
633
+ lines.push(`blocked or failed requests (${failed.length}):`, ...failed.map((f) => ` ${f}`));
634
+ if (artifacts.length) {
635
+ lines.push("files:", ...artifacts.map((f) => ` ${f} (${bytes(f)})`));
636
+ const total = artifacts.reduce((n, f) => n + sizeOf(f), 0);
637
+ if (total > MAX_ARTIFACT_BYTES)
638
+ lines.push(`these files total ${Math.round(total / 1024 / 1024)} MB; keep a run's output under ${MAX_ARTIFACT_BYTES / 1024 / 1024} MB`);
639
+ }
640
+ if (server)
641
+ lines.push("only your directory and the hosts this job may reach loaded");
642
+ if (images.length)
643
+ lines.push(`${images.length} picture${images.length === 1 ? "" : "s"} follow${videoFile ? "; the recording's keyframes stand in for watching it" : ""}`);
644
+ return { text: lines.join("\n"), images, artifacts };
645
+ }
646
+ // A file of the worker's own for an upload: inside its directory, real path, not a directory.
647
+ function confine(dir, path) {
648
+ const root = realpathSync(dir);
649
+ const full = resolve(root, path);
650
+ if (!within(root, full))
651
+ throw new Error(`${path} is outside your directory`);
652
+ const real = realpathSync(full);
653
+ if (!within(root, real))
654
+ throw new Error(`${path} resolves outside your directory`);
655
+ if (!statSync(real).isFile())
656
+ throw new Error(`${path} is no file`);
657
+ return real;
658
+ }
659
+ async function convert(ffmpeg, from, to) {
660
+ if (!ffmpeg)
661
+ return false;
662
+ return await new Promise((ok) => {
663
+ const child = spawn(ffmpeg, ["-v", "error", "-y", "-i", from, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart", to], { stdio: "ignore" });
664
+ child.once("error", () => ok(false));
665
+ child.once("close", (code) => ok(code === 0 && existsSync(to)));
666
+ });
667
+ }
668
+ function sizeOf(file) {
669
+ try {
670
+ return statSync(file).size;
671
+ }
672
+ catch {
673
+ return 0;
674
+ }
675
+ }
676
+ function bytes(file) {
677
+ const n = sizeOf(file);
678
+ return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`;
679
+ }