@omacode/micromanager 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
package/src/look.ts ADDED
@@ -0,0 +1,390 @@
1
+ // The `look` tool of the visual workers: a page, a drawing or an image of their directory as a picture, rendered by the
2
+ // plugin on the host.
3
+ //
4
+ // A browser cannot run in the worker sandbox (found 2026-10-27): Chromium's own sandbox needs user namespaces, which
5
+ // bubblewrap refuses inside, and its process singleton needs socket(AF_UNIX), which sandbox-runtime's seccomp filter
6
+ // blocks for every worker (unblocking it would open D-Bus, Docker and agent sockets to all of them). So the plugin
7
+ // renders: headless Chromium with its own sandbox on, a throwaway profile, the worker's directory served from
8
+ // 127.0.0.1, and a resolver that knows no host but that one and the hosts the job may reach. Full-page shots go through
9
+ // the DevTools protocol over --remote-debugging-pipe (spike, 2026-10-27: 0.3 s for a 1000 x 2219 page).
10
+
11
+ import { spawn } from "node:child_process"
12
+ import { accessSync, closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"
13
+ import { createServer, type Server } from "node:http"
14
+ import { homedir, tmpdir } from "node:os"
15
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path"
16
+
17
+ const IMAGES: Readonly<Record<string, string>> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif" }
18
+ const PAGES = new Set([".html", ".htm", ".svg"])
19
+ const MIME: Readonly<Record<string, string>> = {
20
+ ...IMAGES, ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".svg": "image/svg+xml", ".css": "text/css",
21
+ ".js": "text/javascript", ".mjs": "text/javascript", ".json": "application/json", ".woff": "font/woff", ".woff2": "font/woff2",
22
+ ".ttf": "font/ttf", ".otf": "font/otf", ".ico": "image/x-icon", ".avif": "image/avif", ".mp4": "video/mp4", ".webm": "video/webm", ".txt": "text/plain",
23
+ }
24
+
25
+ // The tallest full-page shot: a vision model scales it down anyway, and an endless page should not make a huge file.
26
+ export const MAX_HEIGHT = 8000
27
+ export const MAX_IMAGE_BYTES = 12 * 1024 * 1024
28
+
29
+ // The browser to render with: the first executable Chromium found on PATH, in Playwright's cache, or the macOS app.
30
+ // Existence alone is not enough: a broken or non-executable path must not be chosen and then fail every screenshot.
31
+ export function findChromium(env: NodeJS.ProcessEnv = process.env): string | undefined {
32
+ const executable = (file: string): boolean => {
33
+ try {
34
+ accessSync(file, constants.X_OK)
35
+ return statSync(file).isFile()
36
+ } catch {
37
+ return false
38
+ }
39
+ }
40
+ const names = ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome", "brave-browser", "brave"]
41
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) {
42
+ for (const n of names) {
43
+ const file = join(dir, n)
44
+ if (executable(file)) return file
45
+ }
46
+ }
47
+ const pw = join(env.HOME ?? homedir(), ".cache", "ms-playwright")
48
+ try {
49
+ for (const d of readdirSync(pw).filter((x) => x.startsWith("chromium-")).sort().reverse()) {
50
+ for (const sub of ["chrome-linux/chrome", "chrome-linux64/chrome"]) {
51
+ const file = join(pw, d, sub)
52
+ if (executable(file)) return file
53
+ }
54
+ }
55
+ } catch {
56
+ // no Playwright cache
57
+ }
58
+ const mac = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
59
+ return executable(mac) ? mac : undefined
60
+ }
61
+
62
+ // Whether a host matches what the job may reach: "api.example.com" or "*.example.com".
63
+ export function hostAllowed(host: string, allowed: readonly string[]): boolean {
64
+ const split = (value: string): [string, string | undefined] => {
65
+ const m = /^(.*):(\d+)$/.exec(value.toLowerCase())
66
+ return m ? [m[1]!, m[2]] : [value.toLowerCase(), undefined]
67
+ }
68
+ const [h, port] = split(host)
69
+ return allowed.some((a) => {
70
+ const [p, wanted] = split(a)
71
+ if (wanted !== undefined && wanted !== port) return false
72
+ return p.startsWith("*.") ? h.endsWith(p.slice(1)) && h !== p.slice(2) : h === p
73
+ })
74
+ }
75
+
76
+ // Chromium's resolver: nothing resolves but the plugin's own server and the allowed hosts.
77
+ export function resolverRules(allowed: readonly string[]): string {
78
+ return ["MAP * ~NOTFOUND", "EXCLUDE 127.0.0.1", ...allowed.map((a) => `EXCLUDE ${a.replace(/:\d+$/, "")}`)].join(", ")
79
+ }
80
+
81
+ export type Target =
82
+ | { readonly kind: "image"; readonly file: string; readonly mime: string }
83
+ | { readonly kind: "page"; readonly root: string; readonly path: string; readonly label: string } // served from 127.0.0.1
84
+ | { readonly kind: "url"; readonly url: string }
85
+ | { readonly kind: "error"; readonly text: string }
86
+
87
+ // A real path stays inside its real root. Lexical checks alone are not containment: a worker can create a symlink.
88
+ function within(root: string, file: string): boolean {
89
+ return file === root || file.startsWith(root + sep)
90
+ }
91
+
92
+ // URL path segments, so a file called `a#b.html` or `a?b.html` is a file and not a fragment or query.
93
+ function urlPath(parts: readonly string[]): string {
94
+ return "/" + parts.map((part) => encodeURIComponent(part)).join("/")
95
+ }
96
+
97
+ // What a look asks for, checked: a path inside the worker's directory, or a URL on a host the job may reach.
98
+ export function lookTarget(input: { path?: string; url?: string }, dir: string, allowed: readonly string[]): Target {
99
+ const path = input.path?.trim()
100
+ const url = input.url?.trim()
101
+ if (!path && !url) return { kind: "error", text: "Name a path in your directory (a page, an svg, an image, or a directory with an index.html) or a url." }
102
+ if (url) {
103
+ let u: URL
104
+ try {
105
+ u = new URL(url)
106
+ } catch {
107
+ return { kind: "error", text: `${url} is no URL.` }
108
+ }
109
+ if (!/^https?:$/.test(u.protocol)) return { kind: "error", text: "Only http and https URLs; a file of yours goes in path." }
110
+ if (!hostAllowed(u.host, allowed)) return { kind: "error", text: `${u.host} is not a host this job may reach. Build the page and look at it by its path, or ask for the host with request_network.` }
111
+ return { kind: "url", url: u.toString() }
112
+ }
113
+ const root = resolve(dir)
114
+ const full = resolve(root, path!)
115
+ if (!within(root, full)) return { kind: "error", text: `${path} is outside your directory.` }
116
+ if (!existsSync(full)) return { kind: "error", text: `${path} does not exist. Build the page first (e.g. npm run build) and look at its output.` }
117
+ let realRoot: string
118
+ let realFull: string
119
+ try {
120
+ realRoot = realpathSync(root)
121
+ realFull = realpathSync(full)
122
+ } catch {
123
+ return { kind: "error", text: `${path} cannot be resolved.` }
124
+ }
125
+ if (!within(realRoot, realFull)) return { kind: "error", text: `${path} resolves outside your directory.` }
126
+ const rel = relative(realRoot, realFull).split(sep).join("/")
127
+ if (forbidden(rel)) return { kind: "error", text: `${path} is not shown.` }
128
+ if (statSync(realFull).isDirectory()) {
129
+ const index = join(realFull, "index.html")
130
+ if (!existsSync(index)) return { kind: "error", text: `${path} has no index.html; name the page.` }
131
+ try {
132
+ if (!within(realRoot, realpathSync(index))) return { kind: "error", text: `${path}/index.html resolves outside your directory.` }
133
+ } catch {
134
+ return { kind: "error", text: `${path}/index.html cannot be resolved.` }
135
+ }
136
+ // The directory is the document root, so a built deck's /assets/... paths resolve there.
137
+ return { kind: "page", root: realFull, path: "/", label: rel ? `${rel}/` : "" }
138
+ }
139
+ const ext = extname(realFull).toLowerCase()
140
+ if (IMAGES[ext]) return { kind: "image", file: realFull, mime: IMAGES[ext]! }
141
+ if (PAGES.has(ext)) {
142
+ // A page is served with its own directory as root; /assets/... then means the production output's assets.
143
+ return { kind: "page", root: dirname(realFull), path: urlPath([basename(realFull)]), label: rel }
144
+ }
145
+ return { kind: "error", text: `${path} is no page or image (html, svg, png, jpg, gif, webp).` }
146
+ }
147
+
148
+ // Files the static server never hands out: environment files, git's own and the plugin's.
149
+ function forbidden(rel: string): boolean {
150
+ return rel.split("/").some((part) => /^\.env(\..*)?$/.test(part) && !/^\.env\.example$/.test(part) || part === ".git" || part === ".micromanager" || part === ".jev-micromanager")
151
+ }
152
+
153
+ // The worker's directory over http on 127.0.0.1, read-only, so absolute asset paths (/assets/x.css) resolve.
154
+ // fallback: a path without a file extension and no file of its own is the single-page app's index.html, so a worker can
155
+ // drive a route (/dashboard) that only the client router knows.
156
+ export async function serveDir(dir: string, options: { fallback?: boolean } = {}): Promise<{ origin: string; close(): Promise<void> }> {
157
+ const root = resolve(dir)
158
+ const realRoot = realpathSync(root)
159
+ const server: Server = createServer((req, res) => {
160
+ let path: string
161
+ try {
162
+ path = decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname)
163
+ } catch {
164
+ res.writeHead(400).end()
165
+ return
166
+ }
167
+ const full = resolve(root, `.${path}`)
168
+ if (!within(root, full) || forbidden(relative(root, full).split(sep).join("/"))) {
169
+ res.writeHead(403).end()
170
+ return
171
+ }
172
+ try {
173
+ // Resolve first, then read the resolved path: a symlink must not escape the served directory after the check.
174
+ let real = realpathSync(full)
175
+ if (!within(realRoot, real)) {
176
+ res.writeHead(403).end()
177
+ return
178
+ }
179
+ if (statSync(real).isDirectory()) real = realpathSync(join(real, "index.html"))
180
+ if (!within(realRoot, real) || forbidden(relative(realRoot, real).split(sep).join("/"))) {
181
+ res.writeHead(403).end()
182
+ return
183
+ }
184
+ const body = readFileSync(real)
185
+ res.writeHead(200, { "content-type": MIME[extname(real).toLowerCase()] ?? "application/octet-stream", "cache-control": "no-store" })
186
+ res.end(body)
187
+ } catch {
188
+ if (options.fallback && !extname(path)) {
189
+ try {
190
+ const index = realpathSync(join(realRoot, "index.html"))
191
+ if (within(realRoot, index) && !forbidden(relative(realRoot, index).split(sep).join("/"))) {
192
+ res.writeHead(200, { "content-type": MIME[".html"], "cache-control": "no-store" })
193
+ res.end(readFileSync(index))
194
+ return
195
+ }
196
+ } catch {
197
+ // no index either, then
198
+ }
199
+ }
200
+ res.writeHead(404).end()
201
+ }
202
+ })
203
+ await new Promise<void>((ok, fail) => {
204
+ server.once("error", fail)
205
+ server.listen(0, "127.0.0.1", () => ok())
206
+ })
207
+ const port = (server.address() as { port: number }).port
208
+ return { origin: `http://127.0.0.1:${port}`, close: () => new Promise((ok) => server.close(() => ok())) }
209
+ }
210
+
211
+ export interface Shot {
212
+ readonly width: number
213
+ readonly height?: number // the viewport; a full-page shot takes the page's height
214
+ readonly fullPage: boolean
215
+ readonly settleMs?: number // after load and fonts; animations can use more
216
+ readonly timeoutMs?: number
217
+ }
218
+
219
+ // One screenshot of url, PNG bytes. The browser is started for it and gone afterwards, its profile with it.
220
+ export async function screenshot(chromium: string, url: string, shot: Shot, allowed: readonly string[]): Promise<Buffer> {
221
+ const profile = mkdtempSync(join(tmpdir(), "mm-look-"))
222
+ const browser = spawn(chromium, [
223
+ "--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check",
224
+ "--disable-extensions", "--disable-sync", "--disable-background-networking", "--hide-scrollbars", "--mute-audio",
225
+ `--host-resolver-rules=${resolverRules(allowed)}`, "about:blank",
226
+ ], { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] })
227
+ let stderr = ""
228
+ browser.stderr!.on("data", (d: Buffer) => (stderr = (stderr + d.toString()).slice(-2000)))
229
+ const toBrowser = browser.stdio[3] as NodeJS.WritableStream
230
+ const fromBrowser = browser.stdio[4] as NodeJS.ReadableStream
231
+ let id = 0
232
+ let buf = ""
233
+ const localOrigin = new URL(url).origin
234
+ let protocolFailed: (err: Error) => void = () => undefined
235
+ const protocol = new Promise<never>((_, fail) => (protocolFailed = fail))
236
+ const pending = new Map<number, (m: { result?: Record<string, unknown>; error?: { message: string } }) => void>()
237
+ const events: { method: string; sessionId?: string }[] = []
238
+ const waiters: { method: string; sessionId?: string; ok: () => void }[] = []
239
+ fromBrowser.on("data", (d: Buffer) => {
240
+ buf += d.toString()
241
+ let i: number
242
+ while ((i = buf.indexOf("\0")) >= 0) {
243
+ const raw = buf.slice(0, i)
244
+ buf = buf.slice(i + 1)
245
+ let m: { id?: number; method?: string; sessionId?: string; params?: Record<string, unknown>; result?: Record<string, unknown>; error?: { message: string } }
246
+ try {
247
+ m = JSON.parse(raw) as typeof m
248
+ } catch {
249
+ protocolFailed(new Error("the browser sent malformed protocol data"))
250
+ continue
251
+ }
252
+ if (m.id !== undefined && pending.has(m.id)) {
253
+ pending.get(m.id)!(m)
254
+ pending.delete(m.id)
255
+ } else if (m.method) {
256
+ if (m.method === "Fetch.requestPaused" && m.sessionId) {
257
+ // Resolver rules are not a boundary for subresources, redirects or literal loopback addresses. Check every
258
+ // request here and let only the served page and the job's granted hosts through.
259
+ const requestId = String(m.params?.requestId ?? "")
260
+ const raw = String((m.params?.request as { url?: unknown } | undefined)?.url ?? "")
261
+ let allowedRequest = false
262
+ try {
263
+ const u = new URL(raw)
264
+ allowedRequest = ["about:", "data:", "blob:"].includes(u.protocol) || u.origin === localOrigin || hostAllowed(u.host, allowed)
265
+ } catch {
266
+ allowedRequest = false
267
+ }
268
+ const call = allowedRequest ? send("Fetch.continueRequest", { requestId }, m.sessionId) : send("Fetch.failRequest", { requestId, errorReason: "BlockedByClient" }, m.sessionId)
269
+ void call.catch(() => undefined)
270
+ continue
271
+ }
272
+ const w = waiters.findIndex((x) => x.method === m.method && x.sessionId === m.sessionId)
273
+ if (w >= 0) waiters.splice(w, 1)[0]!.ok()
274
+ else events.push({ method: m.method, sessionId: m.sessionId })
275
+ }
276
+ }
277
+ })
278
+ const send = (method: string, params: Record<string, unknown> = {}, sessionId?: string) =>
279
+ new Promise<Record<string, unknown>>((ok, fail) => {
280
+ const n = ++id
281
+ pending.set(n, (m) => (m.error ? fail(new Error(`${method}: ${m.error.message}`)) : ok(m.result ?? {})))
282
+ toBrowser.write(`${JSON.stringify({ id: n, method, params, ...(sessionId ? { sessionId } : {}) })}\0`)
283
+ })
284
+ const event = (method: string, sessionId: string) =>
285
+ new Promise<void>((ok) => {
286
+ const i = events.findIndex((e) => e.method === method && e.sessionId === sessionId)
287
+ if (i >= 0) {
288
+ events.splice(i, 1)
289
+ ok()
290
+ } else waiters.push({ method, sessionId, ok })
291
+ })
292
+ const broken = new Promise<never>((_, fail) => browser.once("error", (err) => fail(new Error(`the browser could not start: ${err.message}`))))
293
+ browser.on("error", () => undefined) // handled by the race; a later error must not become an uncaught event
294
+ const exited = new Promise<never>((_, fail) => browser.once("exit", (code) => fail(new Error(`the browser ended (${code}): ${stderr.trim().split("\n").pop() ?? ""}`))))
295
+ const timeout = new Promise<never>((_, fail) => setTimeout(() => fail(new Error(`no picture within ${(shot.timeoutMs ?? 30_000) / 1000} s`)), shot.timeoutMs ?? 30_000).unref())
296
+ const work = (async () => {
297
+ const { targetId } = (await send("Target.createTarget", { url: "about:blank" })) as { targetId: string }
298
+ const { sessionId } = (await send("Target.attachToTarget", { targetId, flatten: true })) as { sessionId: string }
299
+ await send("Page.enable", {}, sessionId)
300
+ await send("Fetch.enable", { patterns: [{ urlPattern: "*", requestStage: "Request" }] }, sessionId)
301
+ const height = shot.height ?? 800
302
+ await send("Emulation.setDeviceMetricsOverride", { width: shot.width, height, deviceScaleFactor: 1, mobile: false }, sessionId)
303
+ const loaded = event("Page.loadEventFired", sessionId)
304
+ const nav = (await send("Page.navigate", { url }, sessionId)) as { errorText?: string }
305
+ if (nav.errorText) throw new Error(`${url} did not load: ${nav.errorText}`)
306
+ await loaded
307
+ // Web fonts first, then an explicit settle for late layout and animations. Both are bounded by the global timeout.
308
+ await send("Runtime.evaluate", {
309
+ expression: "document.fonts && document.fonts.ready ? Promise.race([document.fonts.ready.then(() => true), new Promise((r) => setTimeout(() => r(false), 3000))]) : true",
310
+ awaitPromise: true,
311
+ returnByValue: true,
312
+ }, sessionId)
313
+ await new Promise((r) => setTimeout(r, clamp(shot.settleMs ?? 300, 0, 10_000)))
314
+ let clipHeight = height
315
+ if (shot.fullPage) {
316
+ const m = (await send("Page.getLayoutMetrics", {}, sessionId)) as { cssContentSize?: { height: number } }
317
+ clipHeight = Math.min(MAX_HEIGHT, Math.max(height, Math.ceil(m.cssContentSize?.height ?? height)))
318
+ }
319
+ const r = (await send("Page.captureScreenshot", { format: "png", captureBeyondViewport: shot.fullPage, clip: { x: 0, y: 0, width: shot.width, height: clipHeight, scale: 1 } }, sessionId)) as { data: string }
320
+ return Buffer.from(r.data, "base64")
321
+ })()
322
+ try {
323
+ return await Promise.race([work, broken, protocol, exited, timeout])
324
+ } finally {
325
+ broken.catch(() => undefined)
326
+ exited.catch(() => undefined)
327
+ protocol.catch(() => undefined)
328
+ browser.kill("SIGKILL")
329
+ // Wait briefly for the process to go, so the next capture does not inherit a live orphan.
330
+ if (browser.exitCode === null) await new Promise<void>((ok) => {
331
+ const timer = setTimeout(ok, 1000)
332
+ browser.once("close", () => {
333
+ clearTimeout(timer)
334
+ ok()
335
+ })
336
+ })
337
+ rmSync(profile, { recursive: true, force: true })
338
+ }
339
+ }
340
+
341
+ export interface LookResult {
342
+ readonly text: string
343
+ readonly image?: { readonly data: Buffer; readonly mime: string }
344
+ }
345
+
346
+ // A visual writer owes a picture, not just a successful shell command.
347
+ export function missingVisualEvidence(role: string | undefined, looked: boolean): boolean {
348
+ return role === "visual" && !looked
349
+ }
350
+
351
+ // One look: the checks, then the picture. dir: the worker's directory; allowed: the hosts its job may reach.
352
+ // chromium: the browser to use, null for none.
353
+ export async function look(input: { path?: string; url?: string; width?: string; height?: string; full?: string; settle?: string }, dir: string, allowed: readonly string[], chromium: string | null = findChromium() ?? null): Promise<LookResult> {
354
+ const target = lookTarget(input, dir, allowed)
355
+ if (target.kind === "error") return { text: target.text }
356
+ if (target.kind === "image") {
357
+ let fd: number | undefined
358
+ try {
359
+ fd = openSync(target.file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
360
+ const size = fstatSync(fd).size
361
+ if (size > MAX_IMAGE_BYTES) return { text: `${relative(dir, target.file)} is ${size} bytes; a look is limited to ${MAX_IMAGE_BYTES} bytes.` }
362
+ const data = readFileSync(fd)
363
+ return { text: `${relative(dir, target.file)} (${data.length} bytes)`, image: { data, mime: target.mime } }
364
+ } catch (err) {
365
+ return { text: `${relative(dir, target.file)} could not be read safely: ${String(err)}` }
366
+ } finally {
367
+ if (fd !== undefined) closeSync(fd)
368
+ }
369
+ }
370
+ if (!chromium) return { text: "No browser is installed where the plugin runs (chromium, google-chrome or Playwright's chromium), so pages cannot be shown. Images still can." }
371
+ const width = clamp(Number(input.width) || 1280, 320, 2560)
372
+ const height = input.height ? clamp(Number(input.height) || 800, 240, 4000) : 800
373
+ const fullPage = !/^(false|no|0)$/i.test(input.full?.trim() ?? "")
374
+ const settleMs = input.settle === undefined || input.settle === "" ? 300 : clamp(Number(input.settle) || 0, 0, 10_000)
375
+ if (target.kind === "url") {
376
+ const data = await screenshot(chromium, target.url, { width, height, fullPage, settleMs }, allowed)
377
+ if (data.length > MAX_IMAGE_BYTES) return { text: `${target.url} rendered to ${data.length} bytes; a look is limited to ${MAX_IMAGE_BYTES}. Use a smaller width or full: no.` }
378
+ return { text: `${target.url} at ${width} px${fullPage ? ", the whole page" : ""}`, image: { data, mime: "image/png" } }
379
+ }
380
+ const server = await serveDir(target.root)
381
+ try {
382
+ const data = await screenshot(chromium, `${server.origin}${target.path}`, { width, height, fullPage, settleMs }, allowed)
383
+ if (data.length > MAX_IMAGE_BYTES) return { text: `${target.label || "index.html"} rendered to ${data.length} bytes; a look is limited to ${MAX_IMAGE_BYTES}. Use a smaller width or full: no.` }
384
+ return { text: `${target.label || "index.html"} at ${width} px${fullPage ? ", the whole page" : ""}; only your directory and the hosts this job may reach load`, image: { data, mime: "image/png" } }
385
+ } finally {
386
+ await server.close()
387
+ }
388
+ }
389
+
390
+ const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, Math.round(n)))
package/src/memory.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "@omacode/context/project-memory"