Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/src/serve-commands.ts?version=0&format=json
383 linesFirst import 100%Last change First import in version 0, 1 version changed it

You're reading version 0. The newest is 318, and 5 versions since then changed this file. Go to the newestCompare with 318

1// abso serve, shot and fetch: previews, screenshots and files out of a box.
2
3import { mkdirSync, writeFileSync } from "node:fs";
4import { join, relative, resolve } from "node:path";
5import { bool, type Parsed, str, UsageError } from "./args.ts";
6import { boxOf, runRun, shellWord, undoGitBashPaths } from "./box-commands.ts";
7import { type Env, EXIT, type Output, open } from "./command-env.ts";
8import { fetchedText, fetchFromBox } from "./fetch.ts";
9import { untarGz } from "./tar.ts";
11/** abso serve [--version N]: a preview of one version of shared at a stable URL, built once on the server (#37, Playtester 1). */
12export async function runServe(args: Parsed, env: Env): Promise<Output> {
13 const raw = str(args, "version");
14 if (raw !== undefined && !/^\d+$/.test(raw))
15 throw new UsageError(`--version is a version number (got ${JSON.stringify(raw)})`);
16 const { api } = open(env);
17 if (raw === undefined)
18 (env.writeErr ?? env.write)(
19 "avcs: building a preview of the newest version of shared (once per version; a minute the first time)…\n",
20 );
21 const s = await api.serve(raw === undefined ? undefined : Number(raw), str(args, "build"), str(args, "out"));
22 if (!s.built || !s.url) {
23 return {
24 exit: EXIT.error,
25 text: `The preview of version ${s.version} didn't build${s.exitCode !== undefined ? ` (exit ${s.exitCode})` : ""}: ${s.error ?? "see its output"}.${s.output ? `\nIts output ends:\n${s.output.trimEnd()}` : ""}`,
26 json: { ...s },
27 };
28 }
29 return {
30 text: [
31 `Version ${s.version} of shared: ${s.url}`,
32 `${s.cached ? "Already built" : `Built in ${s.seconds} s`}: ${s.files} files, ${Math.round((s.bytes ?? 0) / 1024)} KB. The link needs no token and never changes; it serves exactly this version.`,
33 ].join("\n"),
34 json: { ...s },
35 };
38/**
39 * The script abso shot runs in the box (from /w/.avcs-shot, so 'playwright' is
40 * the project's own). It reads its setup from AVCS_SHOT and prints marked
41 * lines the client picks out: AVCS_SHOT_IMAGE {json}, blocks between
42 * AVCS_SHOT_BEGIN <name> and AVCS_SHOT_END, and "eval: ", "page error: ",
43 * "console " lines. No backticks or dollar-braces in here: it's a raw string.
44 */
45const SHOOTER = String.raw`import { chromium } from 'playwright';
46import { writeFileSync } from 'node:fs';
47const c = JSON.parse(process.env.AVCS_SHOT);
48const b = await chromium.launch();
49const p = await b.newPage({ viewport: { width: c.w, height: c.h } });
50const logged = [];
51let dropped = 0;
52// vite's own connection chatter isn't the game's.
53p.on('console', (m) => { if (m.text().startsWith('[vite]')) return; if (logged.length < 30) logged.push(m.type() + ': ' + m.text().split('\n')[0].slice(0, 200)); else dropped++; });
54p.on('pageerror', (e) => console.log('page error: ' + String(e).split('\n')[0]));
55// Every element in document order, numbered from 1: the same page in the same state gives the same refs.
56const inPage = (o) => {
57 const skip = ['SCRIPT', 'STYLE', 'HEAD', 'META', 'LINK', 'TITLE', 'NOSCRIPT', 'TEMPLATE', 'HTML'];
58 const els = [...document.querySelectorAll('*')].filter((e) => !skip.includes(e.tagName.toUpperCase()));
59 if (o.ref !== undefined) {
60 const e = els[o.ref - 1];
61 if (!e) return null;
62 e.scrollIntoView({ block: 'center', inline: 'center' });
63 const r = e.getBoundingClientRect();
64 return [Math.round(r.x + r.width / 2), Math.round(r.y + r.height / 2)];
65 }
66 const ROLE = { A: 'link', BUTTON: 'button', SELECT: 'combobox', TEXTAREA: 'textbox', IMG: 'img', SVG: 'img', NAV: 'navigation', MAIN: 'main', UL: 'list', OL: 'list', LI: 'listitem', TABLE: 'table', TR: 'row', TD: 'cell', TH: 'columnheader', FORM: 'form', DIALOG: 'dialog', CANVAS: 'canvas', LABEL: 'label', SUMMARY: 'button', P: 'paragraph', H1: 'heading', H2: 'heading', H3: 'heading', H4: 'heading', H5: 'heading', H6: 'heading', HEADER: 'banner', FOOTER: 'contentinfo', ARTICLE: 'article', SECTION: 'region', VIDEO: 'video', PROGRESS: 'progressbar', OPTION: 'option' };
67 const INPUT = { checkbox: 'checkbox', radio: 'radio', range: 'slider', button: 'button', submit: 'button', reset: 'button', image: 'button' };
68 const role = (e) => e.getAttribute('role') || (e.tagName === 'INPUT' ? INPUT[e.type] || 'textbox' : ROLE[e.tagName.toUpperCase()] || 'generic');
69 const squash = (s) => (s || '').replace(/\s+/g, ' ').trim();
70 const own = (e) => squash([...e.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join(' '));
71 const name = (e, r) => squash(e.getAttribute('aria-label') || e.getAttribute('alt') || e.getAttribute('title') || e.getAttribute('placeholder') || (e.tagName === 'INPUT' ? e.value : '') || own(e) || (/^(button|link|heading|option|tab|menuitem)$/.test(r) ? e.textContent : '')).slice(0, 100);
72 const INTERACTIVE = /^(button|link|checkbox|radio|tab|menuitem|slider|switch|option|textbox|combobox|canvas)$/;
73 const interactive = (e, r) => INTERACTIVE.test(r) || e.hasAttribute('onclick') || e.hasAttribute('tabindex') || getComputedStyle(e).cursor === 'pointer';
74 const depthOf = (e) => { let d = 0; for (let x = e.parentElement; x && x !== document.body; x = x.parentElement) d++; return d; };
75 const where = (b) => '(' + Math.round(b.x) + ',' + Math.round(b.y) + ' ' + Math.round(b.width) + 'x' + Math.round(b.height) + ')';
76 const q = o.find ? o.find.toLowerCase() : null;
77 const out = [];
78 els.forEach((e, i) => {
79 if (e === document.body) return;
80 const b = e.getBoundingClientRect();
81 if (b.width === 0 || b.height === 0 || getComputedStyle(e).visibility === 'hidden') return;
82 const r = role(e);
83 const n = name(e, r);
84 const line = r + (n ? ' "' + n.replace(/"/g, "'") + '"' : '') + ' [ref_' + (i + 1) + '] ' + where(b);
85 if (q !== null) {
86 if ((r + ' ' + n + ' ' + own(e)).toLowerCase().includes(q) && out.length < 20) out.push(line);
87 return;
88 }
89 if (o.interactive) {
90 if (interactive(e, r)) out.push(line);
91 return;
92 }
93 if (r === 'generic' && !n) return;
94 const d = depthOf(e);
95 if (o.depth === null || d <= o.depth) out.push(' '.repeat(d) + line);
96 });
97 return out;
98};
99const block = (name, text, max) => {
100 console.log('AVCS_SHOT_BEGIN ' + name);
101 console.log(text.length > max ? text.slice(0, max) + '\n... (' + (text.length - max) + ' more characters; --max-chars raises the cap)' : text);
102 console.log('AVCS_SHOT_END');
103};
104const at = async (spec) => {
105 if (spec.ref === undefined) return [spec.x, spec.y];
106 const pt = await p.evaluate(inPage, { ref: spec.ref });
107 if (!pt) { console.log('page error: there is no ref_' + spec.ref + ' on the page (refs come from --tree or --find on the same page and state)'); process.exit(3); }
108 return pt;
109};
110await p.goto(c.url, { waitUntil: 'load' });
111if (c.eval !== null || c.clicks.length > 0 || c.mouse !== null) await p.waitForTimeout(1000);
112if (c.eval !== null) { const r = await p.evaluate(c.eval); if (r !== undefined) console.log('eval: ' + JSON.stringify(r).slice(0, 300)); }
113// Two frames after --eval, so what it changed is drawn before anything clicks it.
114if (c.eval !== null) await p.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
115for (const k of c.clicks) { if (k.ms > 0) await p.waitForTimeout(k.ms); const [x, y] = await at(k); await p.mouse.click(x, y); await p.waitForTimeout(300); }
116// In small steps from the corner, so the page sees mousemove on the way, as a hand would make it.
117if (c.mouse !== null) { const [x, y] = await at(c.mouse); await p.mouse.move(x, y, { steps: 10 }); }
118await p.waitForTimeout(c.wait);
119if (c.text) block('text', await p.evaluate(() => document.body ? document.body.innerText : ''), c.maxChars);
120if (c.tree) block(c.interactive ? 'tree (interactive elements)' : 'tree', (await p.evaluate(inPage, { interactive: c.interactive, depth: c.depth })).join('\n'), c.maxChars);
121if (c.find !== null) {
122 const found = await p.evaluate(inPage, { find: c.find });
123 block('find', found.length > 0 ? found.join('\n') : 'nothing on the page matches', c.maxChars);
125if (c.image) {
126 const clip = c.region ? { x: c.region[0], y: c.region[1], width: c.region[2] - c.region[0], height: c.region[3] - c.region[1] } : null;
127 let png = await p.screenshot(clip ? { clip } : {});
128 let w = clip ? clip.width : c.w;
129 let h = clip ? clip.height : c.h;
130 if (c.scale < 1) {
131 // Downscaled in a blank page's canvas, so the game's page renders as it would for a player.
132 const sw = Math.max(1, Math.round(w * c.scale));
133 const sh = Math.max(1, Math.round(h * c.scale));
134 const q = await b.newPage();
135 const b64 = await q.evaluate(async ([data, sw, sh]) => {
136 const img = await createImageBitmap(await (await fetch('data:image/png;base64,' + data)).blob());
137 const cv = new OffscreenCanvas(sw, sh);
138 const g = cv.getContext('2d');
139 g.imageSmoothingQuality = 'high';
140 g.drawImage(img, 0, 0, sw, sh);
141 const a = new Uint8Array(await (await cv.convertToBlob({ type: 'image/png' })).arrayBuffer());
142 let s = '';
143 for (let i = 0; i < a.length; i += 0x8000) s += String.fromCharCode(...a.subarray(i, i + 0x8000));
144 return btoa(s);
145 }, [png.toString('base64'), sw, sh]);
146 png = Buffer.from(b64, 'base64');
147 w = sw;
148 h = sh;
149 }
150 writeFileSync(c.out, png);
151 console.log('AVCS_SHOT_IMAGE ' + JSON.stringify({ w, h, bytes: png.length }));
153for (const l of logged) console.log('console ' + l);
154if (dropped > 0) console.log('console (' + dropped + ' more messages not shown)');
155await b.close();`;
157/** A click or pointer target: page x,y, or an element's ref from --tree or --find, then (for clicks) ms to wait first. */
158interface ShotPoint {
159 x?: number;
160 y?: number;
161 ref?: number;
162 ms: number;
165function shotPoint(s: string, flag: string, wait: boolean): ShotPoint {
166 const m = /^(?:(\d{1,5}),\s*(\d{1,5})|ref_(\d{1,6}))(?:\s*[@@]\s*(\d{1,6}))?$/.exec(s.trim());
167 if (!m || (!wait && m[4] !== undefined)) {
168 throw new UsageError(
169 `${flag} is x,y in page pixels or ref_N (from --tree or --find)${wait ? ", or either with @ms to wait first; several separated by ;" : ""} (got ${JSON.stringify(s)})`,
170 );
171 }
172 const ms = Number(m[4] ?? 0);
173 return m[3] !== undefined ? { ref: Number(m[3]), ms } : { x: Number(m[1]), y: Number(m[2]), ms };
176/** What reading an image costs a model, roughly: about one token per 750 pixels. */
177export function imageTokens(w: number, h: number): number {
178 return Math.ceil((w * h) / 750);
181/**
182 * abso shot <path>: a look at the folder's game, taken in the box (#37, #39).
183 * The box runs the project's vite dev server and Playwright on
184 * http://127.0.0.1:4173<path>. By default a PNG comes back to .avcs/shots/
185 * (never recorded) or --out. --scale and --region make it smaller; --text,
186 * --tree and --find read the page with no image at all. Coordinates are
187 * always the page's, whatever the scale or region.
188 */
189export async function runShot(args: Parsed, env: Env): Promise<Output> {
190 // Git Bash turns a bare "/" (or "/x") into a Windows path before abso sees it; take it back.
191 const page = undoGitBashPaths(args.positionals, env.env).words[0] ?? "/";
192 if (args.positionals.length > 1 || !page.startsWith("/"))
193 throw new UsageError('give the page as a path: abso shot "/?mute&t=240"');
194 const wait = str(args, "wait") ?? "3000";
195 if (!/^\d{1,6}$/.test(wait)) throw new UsageError("--wait is milliseconds after load, like 3000");
196 const size = str(args, "size") ?? "1280x720";
197 if (!/^\d{2,5}x\d{2,5}$/.test(size)) throw new UsageError("--size is WIDTHxHEIGHT, like 1280x720");
198 const [width, height] = size.split("x").map(Number) as [number, number];
199 // --eval and --click set the page up before the shot (#37, Builder 7): JS first, then each click, in order.
200 const evalJs = str(args, "eval");
201 // x,y@ms waits ms before that click (#37, Writer 1): a card --eval or an earlier click brings up may need a draw or two.
202 const clicks = (str(args, "click") ?? "")
203 .split(";")
204 .map((s) => s.trim())
205 .filter((s) => s !== "")
206 .map((s) => shotPoint(s, "--click", true));
207 // --mouse leaves the pointer over a point for the shot, for hover cards (#37, Builder 7).
208 const mouseSpec = str(args, "mouse");
209 const mouse = mouseSpec === undefined ? null : shotPoint(mouseSpec, "--mouse", false);
210 for (const pt of [...clicks, ...(mouse ? [mouse] : [])]) {
211 if (pt.x !== undefined && (pt.x >= width || pt.y! >= height))
212 throw new UsageError(
213 `${pt.x},${pt.y} is off the ${size} page; points are page pixels, whatever --scale or --region`,
214 );
215 }
216 // Smaller images (#39): --scale shrinks it, --region takes part of the page at full detail.
217 const scaleText = str(args, "scale") ?? "1";
218 const scale = Number(scaleText);
219 if (!/^(0(\.\d+)?|1(\.0+)?)$/.test(scaleText) || scale < 0.1 || scale > 1)
220 throw new UsageError(
221 `--scale is 0.1-1, like 0.5 for half the width and height, a quarter of the tokens (got ${JSON.stringify(scaleText)})`,
222 );
223 const regionSpec = str(args, "region");
224 let region: [number, number, number, number] | null = null;
225 if (regionSpec !== undefined) {
226 const m = /^(\d{1,5}),\s*(\d{1,5}),\s*(\d{1,5}),\s*(\d{1,5})$/.exec(regionSpec.trim());
227 const r = m ? ([Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])] as [number, number, number, number]) : null;
228 if (!r || r[2] <= r[0] || r[3] <= r[1] || r[2] > width || r[3] > height) {
229 throw new UsageError(
230 `--region is x0,y0,x1,y1 in page pixels, inside the ${size} page, with x1 > x0 and y1 > y0 (got ${JSON.stringify(regionSpec)})`,
231 );
232 }
233 region = r;
234 }
235 // Reading without an image (#39): the page's text, its elements, or the ones matching some text.
236 const text = bool(args, "text");
237 const tree = bool(args, "tree") || bool(args, "interactive");
238 const interactive = bool(args, "interactive");
239 const find = str(args, "find") ?? null;
240 if (find !== null && find.trim() === "") throw new UsageError("--find needs some text to look for");
241 const depthText = str(args, "depth");
242 if (depthText !== undefined && !/^\d{1,3}$/.test(depthText))
243 throw new UsageError(`--depth is a number of levels (got ${JSON.stringify(depthText)})`);
244 const maxText = str(args, "max-chars") ?? "5000";
245 if (!/^\d{2,7}$/.test(maxText))
246 throw new UsageError(`--max-chars is a number, like 5000 (got ${JSON.stringify(maxText)})`);
247 const reads = text || tree || find !== null;
248 const image =
249 bool(args, "image") ||
250 !reads ||
251 region !== null ||
252 str(args, "scale") !== undefined ||
253 str(args, "out") !== undefined;
254 const name = `shot-${str(args, "at") !== undefined ? `v${str(args, "at")}-` : ""}${new Date().toISOString().replace(/[:.]/g, "-")}.png`;
255 const setup = {
256 url: `http://127.0.0.1:4173${page}`,
257 w: width,
258 h: height,
259 wait: Number(wait),
260 eval: evalJs ?? null,
261 clicks,
262 mouse,
263 out: `.avcs-shot/${name}`,
264 image,
265 scale,
266 region,
267 text,
268 tree,
269 interactive,
270 depth: depthText === undefined ? null : Number(depthText),
271 find,
272 maxChars: Number(maxText),
273 };
274 const script = [
275 "set -e",
276 'stop() { pkill -f "vite --host 127.0.0.1 --port 4173" 2>/dev/null || true; }',
277 "stop; trap stop EXIT",
278 "[ -d node_modules ] || npm ci --no-audit --no-fund >/tmp/shot-npm.log 2>&1 || { tail -20 /tmp/shot-npm.log; exit 1; }",
279 'npx --no-install playwright --version >/dev/null 2>&1 || { echo "abso shot needs playwright in the project\'s devDependencies"; exit 1; }',
280 "ls ~/.cache/ms-playwright 2>/dev/null | grep -q chromium || npx --no-install playwright install chromium >/tmp/shot-pw.log 2>&1 || { tail -20 /tmp/shot-pw.log; exit 1; }",
281 "(npx --no-install vite --host 127.0.0.1 --port 4173 --strictPort >/tmp/shot-vite.log 2>&1 &)",
282 "for i in $(seq 120); do curl -sf -o /dev/null http://127.0.0.1:4173/ && break; sleep 0.5; done",
283 'curl -sf -o /dev/null http://127.0.0.1:4173/ || { echo "the vite dev server did not start:"; tail -20 /tmp/shot-vite.log; exit 1; }',
284 "mkdir -p .avcs-shot",
285 `cat > .avcs-shot/shoot.mjs <<'AVCS_SHOT_EOF'\n${SHOOTER}\nAVCS_SHOT_EOF`,
286 `AVCS_SHOT=${shellWord(JSON.stringify(setup))} node .avcs-shot/shoot.mjs`,
287 ].join("\n");
288 const said: string[] = [];
289 const keep = (t: string) => void said.push(t);
290 const flags = new Map<string, string | boolean>();
291 const box = str(args, "box");
292 if (box !== undefined) flags.set("box", box);
293 // --at shoots a version of the folder's space instead of the folder, as abso run --at runs one (#37, Builder 5).
294 const at = str(args, "at");
295 if (at !== undefined && !/^\d+$/.test(at))
296 throw new UsageError(`--at is a version number (got ${JSON.stringify(at)})`);
297 if (at !== undefined) flags.set("at", at);
298 const ran = await runRun({ positionals: [script], flags }, { ...env, write: keep, writeErr: keep, runKind: "shot" });
299 const lines = said.join("").split("\n");
300 // What the page said: --eval's result, uncaught errors and console messages.
301 const notes = lines.filter((l) => l.startsWith("eval: ") || l.startsWith("page error: ") || l.startsWith("console "));
302 if ((ran.exit ?? 0) !== 0) {
303 return {
304 exit: ran.exit ?? EXIT.error,
305 text: `No shot (exit ${ran.exit}). The box said:\n${said.join("").trimEnd()}`,
306 json: { exit: ran.exit, notes },
307 };
308 }
309 const blocks: { name: string; text: string }[] = [];
310 for (let i = 0; i < lines.length; i++) {
311 if (!lines[i]!.startsWith("AVCS_SHOT_BEGIN ")) continue;
312 const end = lines.indexOf("AVCS_SHOT_END", i + 1);
313 blocks.push({
314 name: lines[i]!.slice("AVCS_SHOT_BEGIN ".length),
315 text: lines.slice(i + 1, end < 0 ? undefined : end).join("\n"),
316 });
317 if (end > i) i = end;
318 }
319 const steps = [
320 ...(evalJs !== undefined ? ["--eval"] : []),
321 ...(clicks.length > 0 ? [`${clicks.length === 1 ? "1 click" : `${clicks.length} clicks`}`] : []),
322 ...(mouse !== null
323 ? [`the pointer at ${mouse.ref !== undefined ? `ref_${mouse.ref}` : `${mouse.x},${mouse.y}`}`]
324 : []),
325 ];
326 const head = `${page}${at !== undefined ? ` at version ${at}` : ""}, page ${size}${steps.length > 0 ? `, after ${steps.join(" and ")}` : ""}, ${wait} ms after load`;
327 const out: string[] = [];
328 let shot: { path: string; w: number; h: number; bytes: number; tokens: number } | null = null;
329 if (image) {
330 const info = lines.find((l) => l.startsWith("AVCS_SHOT_IMAGE "));
331 const { root, api } = open(env);
332 void root;
333 api.box = boxOf(args, env);
334 const gz = await api.boxFiles(`.avcs-shot/${name}`);
335 const png = gz === null ? undefined : untarGz(gz).find((e) => e.path === `.avcs-shot/${name}`);
336 if (!png || !info)
337 return { exit: EXIT.error, text: "The screenshot ran but its file was not in the box.", json: { notes } };
338 const { w, h } = JSON.parse(info.slice("AVCS_SHOT_IMAGE ".length)) as { w: number; h: number };
339 const path = resolve(env.cwd, str(args, "out") ?? join(".avcs", "shots", name));
340 mkdirSync(join(path, ".."), { recursive: true });
341 writeFileSync(path, png.data);
342 shot = { path, w, h, bytes: png.data.length, tokens: imageTokens(w, h) };
343 const what = [
344 region ? `region ${region.join(",")}` : "the whole page",
345 ...(scale < 1 ? [`scale ${scale}`] : []),
346 ].join(" at ");
347 out.push(`Screenshot of ${head}: ${relative(env.cwd, path) || path}`);
348 out.push(
349 ` ${w}x${h} pixels (${what}), ${Math.max(1, Math.round(png.data.length / 1024))} KB; about ${shot.tokens} tokens if read. Clicks take page pixels, whatever the scale or region.`,
350 );
351 } else {
352 out.push(`Read ${head} (no image):`);
353 }
354 for (const b of blocks)
355 out.push(`${b.name[0]!.toUpperCase()}${b.name.slice(1)}${b.name === "find" ? ` "${find}"` : ""}:`, b.text);
356 if (blocks.some((b) => b.name !== "text"))
357 out.push("Click one with --click ref_N (or --mouse ref_N) on the same page and state.");
358 out.push(...notes.map((n) => ` ${n}`));
359 return {
360 text: out.join("\n"),
361 json: {
362 ...(shot ?? {}),
363 page,
364 pageSize: { w: width, h: height },
365 region,
366 scale,
367 at: at === undefined ? null : Number(at),
368 wait: Number(wait),
369 eval: evalJs ?? null,
370 clicks,
371 ...Object.fromEntries(blocks.map((b) => [b.name.split(" ")[0], b.text])),
372 notes,
373 },
374 };
377export async function runFetch(args: Parsed, env: Env): Promise<Output> {
378 const { root, api } = open(env);
379 api.box = boxOf(args, env);
380 const f = await fetchFromBox(root, api, args.positionals);
381 const lines = fetchedText(f);
382 return { text: lines.length > 0 ? lines.join("\n") : "Nothing fetched.", json: { ...f } };