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