@0perator/operator 0.2.1 → 0.2.2-next.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.
- package/README.md +1 -1
- package/dist/auth/byo.js +1 -1
- package/dist/auth/commands.js +8 -2
- package/dist/autonomy/agent-cli.js +1 -1
- package/dist/autonomy/headless.js +30 -6
- package/dist/autonomy/pr-isolation.js +92 -0
- package/dist/autonomy/pr-preflight.js +474 -0
- package/dist/autonomy/session-factory.js +2 -0
- package/dist/browser/capture.js +505 -0
- package/dist/browser/engine.js +4 -3
- package/dist/browser/page-capture.js +167 -0
- package/dist/browser/png.js +116 -0
- package/dist/browser/visual-compare.js +229 -0
- package/dist/bus/beam-drop.js +55 -0
- package/dist/bus/inbox.js +7 -1
- package/dist/cli.js +130 -26
- package/dist/config/managed.js +40 -1
- package/dist/config/persona.js +86 -41
- package/dist/config/product-hosts.js +2 -0
- package/dist/config/settings.js +30 -13
- package/dist/config/skills-index.js +37 -14
- package/dist/engine/agent.js +1 -1
- package/dist/engine/aurora.js +18 -9
- package/dist/engine/continuation.js +36 -0
- package/dist/engine/identity.js +42 -0
- package/dist/engine/moa.js +7 -0
- package/dist/engine/net-error.js +15 -0
- package/dist/engine/rolling-summary.js +142 -93
- package/dist/engine/waterfall.js +33 -0
- package/dist/gateway-cli.js +10 -1
- package/dist/memory/session-index.js +3 -3
- package/dist/permissions/index.js +2 -1
- package/dist/permissions/policy.js +9 -2
- package/dist/permissions/tier.js +9 -1
- package/dist/products/craft.js +90 -1
- package/dist/products/temple.js +20 -1
- package/dist/products/voice.js +112 -0
- package/dist/router/free-models.js +5 -9
- package/dist/router/models.js +58 -14
- package/dist/router/provider-models.js +78 -0
- package/dist/router/router.js +15 -3
- package/dist/selfimprove/lessons.js +23 -0
- package/dist/session.js +192 -87
- package/dist/skills/catalogue.js +5 -2
- package/dist/skills/finder.js +4 -4
- package/dist/skills/install-guard.js +1 -1
- package/dist/tools/beam.js +246 -0
- package/dist/tools/craft.js +23 -0
- package/dist/tools/deferred.js +7 -3
- package/dist/tools/doc-text.js +1 -1
- package/dist/tools/registry.js +55 -9
- package/dist/tools/sandbox.js +6 -6
- package/dist/ui/App.js +3 -3
- package/dist/ui/ApprovalPrompt.js +1 -1
- package/dist/ui/Composer.js +44 -2
- package/dist/ui/StatusRule.js +2 -1
- package/dist/ui/Transcript.js +5 -0
- package/dist/ui/modelPicker.js +10 -6
- package/dist/ui/phase.js +4 -2
- package/dist/ui/slashCommands.js +1 -0
- package/dist/ui/voice.js +185 -0
- package/dist/update.js +1 -2
- package/dist/util/audio-io.js +82 -0
- package/dist/util/slash.js +2 -2
- package/dist/vision/pairs.js +239 -0
- package/package.json +1 -1
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// Page capture core shared by page_capture and visual_compare: a throwaway headless Chrome (its own temp profile,
|
|
2
|
+
// so no cookies or logins from the `browser` session and no profile-lock clash with it), one tab per viewport,
|
|
3
|
+
// computed-style extraction from the live DOM, and viewport-height PNG tiles of the whole page.
|
|
4
|
+
// Why DOM + tiles and not vision alone: _ai-docs/decisions/2026-11-24-page-capture-and-visual-compare.md.
|
|
5
|
+
// Loaded only through the registry's by-variable import, so node builtins are imported directly here.
|
|
6
|
+
import { createServer } from "node:http";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { basename, dirname, extname, join, normalize, resolve, sep } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { lookup } from "node:dns/promises";
|
|
12
|
+
import { isIP } from "node:net";
|
|
13
|
+
import { checkNavigationUrl, launchBrowser, BROWSER_CONSTANTS } from "./engine.js";
|
|
14
|
+
const LINK_LOCAL = /^(169\.254\.|fe[89ab][0-9a-f]:|::ffff:169\.254\.)/i;
|
|
15
|
+
const METADATA_NAMES = new Set(["metadata.google.internal", "metadata", "instance-data", "metadata.azure.com"]);
|
|
16
|
+
/** Why a page URL may not be opened by the capture browser, or null. A page on this machine or a dev box is fine
|
|
17
|
+
* (that is how a reproduction is checked); what is refused is the link-local range and the cloud metadata names,
|
|
18
|
+
* which hold credentials, whether written as a literal or reached through a name that resolves there. */
|
|
19
|
+
export async function captureBlockedReason(raw, resolveAddrs) {
|
|
20
|
+
let host;
|
|
21
|
+
try {
|
|
22
|
+
host = new URL(raw).hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if (!host || host === "localhost")
|
|
28
|
+
return null;
|
|
29
|
+
if (METADATA_NAMES.has(host))
|
|
30
|
+
return `capture: ${host} is a cloud metadata address and is not opened`;
|
|
31
|
+
if (isIP(host))
|
|
32
|
+
return LINK_LOCAL.test(host) ? "capture: link-local and cloud metadata addresses are not opened" : null;
|
|
33
|
+
let addrs = [];
|
|
34
|
+
try {
|
|
35
|
+
addrs = resolveAddrs ? await resolveAddrs(host) : (await lookup(host, { all: true, verbatim: true })).map((a) => a.address);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
} // the navigation reports an unresolvable name itself
|
|
40
|
+
return addrs.some((a) => LINK_LOCAL.test(a)) ? `capture: ${host} resolves to a link-local or cloud metadata address and is not opened` : null;
|
|
41
|
+
}
|
|
42
|
+
export const MAX_TILES = 12;
|
|
43
|
+
const MAX_VIEWPORT = 3840;
|
|
44
|
+
export function parseViewports(raw) {
|
|
45
|
+
const list = Array.isArray(raw) && raw.length ? raw : ["desktop", "phone"];
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const v of list.slice(0, 4)) {
|
|
48
|
+
const s = String(v).trim().toLowerCase();
|
|
49
|
+
let w, h;
|
|
50
|
+
if (s === "desktop")
|
|
51
|
+
w = 1440;
|
|
52
|
+
else if (s === "tablet")
|
|
53
|
+
w = 768;
|
|
54
|
+
else if (s === "phone" || s === "mobile")
|
|
55
|
+
w = 390;
|
|
56
|
+
else {
|
|
57
|
+
const m = s.match(/^(\d{3,4})(?:\s*[x×]\s*(\d{3,4}))?$/);
|
|
58
|
+
if (!m)
|
|
59
|
+
throw new Error(`viewport '${v}' — use desktop, tablet, phone, a width (1280) or WxH (1280x800)`);
|
|
60
|
+
w = Number(m[1]);
|
|
61
|
+
h = m[2] ? Number(m[2]) : undefined;
|
|
62
|
+
}
|
|
63
|
+
w = Math.min(Math.max(w, 280), MAX_VIEWPORT);
|
|
64
|
+
h = Math.min(Math.max(h ?? (w >= 1024 ? 900 : w >= 600 ? 1024 : 844), 400), 2400);
|
|
65
|
+
const name = w === 1440 ? "desktop-1440" : w === 768 ? "tablet-768" : w === 390 ? "phone-390" : `w${w}`;
|
|
66
|
+
if (!out.some((o) => o.width === w && o.height === h))
|
|
67
|
+
out.push({ name, width: w, height: h });
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
// ── In-page extraction (runs inside the captured page; plain ES2020, no template literals) ──────────────────
|
|
72
|
+
export const EXTRACT_SCRIPT = String.raw `(() => {
|
|
73
|
+
const vw = innerWidth, vh = innerHeight, sy = scrollY;
|
|
74
|
+
const cv = document.createElement("canvas"); cv.width = cv.height = 1;
|
|
75
|
+
const cx = cv.getContext("2d", { willReadFrequently: true });
|
|
76
|
+
const cache = new Map();
|
|
77
|
+
const hex = (c) => {
|
|
78
|
+
if (!c || c === "transparent" || c === "rgba(0, 0, 0, 0)") return null;
|
|
79
|
+
if (cache.has(c)) return cache.get(c);
|
|
80
|
+
let out = null;
|
|
81
|
+
try {
|
|
82
|
+
cx.clearRect(0, 0, 1, 1); cx.fillStyle = "#000"; cx.fillStyle = c; cx.fillRect(0, 0, 1, 1);
|
|
83
|
+
const d = cx.getImageData(0, 0, 1, 1).data;
|
|
84
|
+
const h2 = (n) => n.toString(16).padStart(2, "0");
|
|
85
|
+
if (d[3] > 0) out = "#" + h2(d[0]) + h2(d[1]) + h2(d[2]) + (d[3] < 255 ? h2(d[3]) : "");
|
|
86
|
+
} catch (e) {}
|
|
87
|
+
cache.set(c, out);
|
|
88
|
+
return out;
|
|
89
|
+
};
|
|
90
|
+
const px = (v) => { const n = parseFloat(v); return isFinite(n) ? Math.round(n * 100) / 100 : null; };
|
|
91
|
+
const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "META", "LINK", "HEAD", "TITLE", "BR", "WBR"]);
|
|
92
|
+
const vis = (el, cs) => {
|
|
93
|
+
if (SKIP.has(el.tagName)) return false;
|
|
94
|
+
if (el.checkVisibility && !el.checkVisibility({ opacityProperty: true, visibilityProperty: true })) return false;
|
|
95
|
+
const st = cs || getComputedStyle(el);
|
|
96
|
+
if (st.display === "none" || st.visibility === "hidden" || st.opacity === "0") return false;
|
|
97
|
+
const r = el.getBoundingClientRect();
|
|
98
|
+
return r.width > 0 && r.height > 0;
|
|
99
|
+
};
|
|
100
|
+
const withOpacity = (el, c) => {
|
|
101
|
+
let o = 1;
|
|
102
|
+
for (let e = el; e && e.nodeType === 1; e = e.parentElement) o *= parseFloat(getComputedStyle(e).opacity) || 0;
|
|
103
|
+
if (o >= 0.999 || !c) return c;
|
|
104
|
+
const a = c.length === 9 ? parseInt(c.slice(7), 16) / 255 : 1;
|
|
105
|
+
return c.slice(0, 7) + Math.round(a * o * 255).toString(16).padStart(2, "0");
|
|
106
|
+
};
|
|
107
|
+
const ownText = (el) => { let n = 0; for (const k of el.childNodes) if (k.nodeType === 3) n += k.textContent.trim().length; return n; };
|
|
108
|
+
const els = [];
|
|
109
|
+
let seen = 0;
|
|
110
|
+
const all = document.body ? [document.documentElement, document.body, ...document.body.querySelectorAll("*")] : [];
|
|
111
|
+
for (const el of all) {
|
|
112
|
+
if (++seen > 8000 || els.length >= 4000) break;
|
|
113
|
+
const cs = getComputedStyle(el);
|
|
114
|
+
if (!vis(el, cs)) continue;
|
|
115
|
+
const r = el.getBoundingClientRect();
|
|
116
|
+
const txt = ownText(el);
|
|
117
|
+
const fs = px(cs.fontSize) || 16;
|
|
118
|
+
const bw = px(cs.borderTopWidth) + px(cs.borderRightWidth) + px(cs.borderBottomWidth) + px(cs.borderLeftWidth);
|
|
119
|
+
const sp = [];
|
|
120
|
+
for (const k of ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft", "marginTop", "marginRight", "marginBottom", "marginLeft", "rowGap", "columnGap"]) {
|
|
121
|
+
const n = px(cs[k]);
|
|
122
|
+
if (n && n > 0 && n <= 240) sp.push(Math.round(n));
|
|
123
|
+
}
|
|
124
|
+
const lh = cs.lineHeight === "normal" ? null : px(cs.lineHeight);
|
|
125
|
+
const ls = cs.letterSpacing === "normal" ? null : px(cs.letterSpacing);
|
|
126
|
+
const mw = cs.maxWidth === "none" || cs.maxWidth.endsWith("%") ? null : px(cs.maxWidth);
|
|
127
|
+
const centred = r.width >= vw * 0.4 && r.width < vw - 2 && Math.abs(r.left - (vw - r.right)) < 2;
|
|
128
|
+
els.push({
|
|
129
|
+
t: el.tagName.toLowerCase(), y0: Math.round(r.top + sy), y1: Math.round(r.bottom + sy), x0: Math.round(r.left), x1: Math.round(r.right),
|
|
130
|
+
txt: txt, c: txt ? withOpacity(el, hex(cs.color)) : null, bg: hex(cs.backgroundColor), bc: bw > 0 ? hex(cs.borderTopColor) : null,
|
|
131
|
+
ff: cs.fontFamily, fw: Number(cs.fontWeight) || 400, fs: fs, lh: lh, ls: ls,
|
|
132
|
+
r: cs.borderRadius !== "0px" ? cs.borderRadius : null, sh: cs.boxShadow !== "none" ? cs.boxShadow : null,
|
|
133
|
+
sp: sp, mw: mw, cw: centred,
|
|
134
|
+
an: cs.animationName && cs.animationName !== "none" ? cs.animationName + " " + cs.animationDuration : null,
|
|
135
|
+
tr: cs.transitionDuration && cs.transitionDuration.split(",").some((d) => parseFloat(d) > 0) ? (cs.transitionProperty + " " + cs.transitionDuration).slice(0, 80) : null,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const ownBg = (el) => { const cs = getComputedStyle(el); return !!hex(cs.backgroundColor) || cs.backgroundImage !== "none"; };
|
|
139
|
+
const effBg = (el) => {
|
|
140
|
+
for (let e = el; e; e = e.parentElement) { const b = hex(getComputedStyle(e).backgroundColor); if (b && b.length === 7) return b; }
|
|
141
|
+
return "#ffffff";
|
|
142
|
+
};
|
|
143
|
+
const big = (el) => { const r = el.getBoundingClientRect(); return r.height >= 24 && r.width >= Math.min(vw * 0.5, 320); };
|
|
144
|
+
const TEXTY = new Set(["P", "H1", "H2", "H3", "H4", "H5", "H6", "UL", "OL", "LI", "DL", "BLOCKQUOTE", "A", "SPAN", "IMG", "SVG", "PICTURE", "VIDEO", "BUTTON", "LABEL", "PRE", "CODE", "TABLE", "STRONG", "EM", "SMALL"]);
|
|
145
|
+
const stacked = (kids) => {
|
|
146
|
+
const rs = kids.map((k) => k.getBoundingClientRect()).sort((a, b) => a.top - b.top);
|
|
147
|
+
return rs.every((r, i) => i === 0 || r.top >= rs[i - 1].bottom - 2);
|
|
148
|
+
};
|
|
149
|
+
const LANDMARK = new Set(["HEADER", "NAV", "SECTION", "FOOTER", "ASIDE", "ARTICLE", "FORM"]);
|
|
150
|
+
const ROLES = new Set(["banner", "navigation", "contentinfo", "region", "complementary", "main"]);
|
|
151
|
+
const layoutOf = (root) => {
|
|
152
|
+
const queue = [[root, 0]];
|
|
153
|
+
while (queue.length) {
|
|
154
|
+
const [el, d] = queue.shift();
|
|
155
|
+
const cs = getComputedStyle(el);
|
|
156
|
+
const kids = Array.from(el.children).filter((k) => vis(k));
|
|
157
|
+
if (kids.length >= 2 && (cs.display.includes("grid") || cs.display.includes("flex"))) {
|
|
158
|
+
if (cs.display.includes("grid")) {
|
|
159
|
+
const cols = cs.gridTemplateColumns.split(" ").filter((x) => x && x !== "none").length;
|
|
160
|
+
return "grid " + cols + " col" + (cols === 1 ? "" : "s") + " ×" + kids.length;
|
|
161
|
+
}
|
|
162
|
+
const dir = cs.flexDirection.startsWith("column") ? "col" : "row";
|
|
163
|
+
if (dir === "row" && cs.flexWrap !== "nowrap") {
|
|
164
|
+
const top = kids[0].getBoundingClientRect().top;
|
|
165
|
+
const perRow = kids.filter((k) => Math.abs(k.getBoundingClientRect().top - top) < 4).length;
|
|
166
|
+
return "flex-row wrap " + perRow + "/row ×" + kids.length;
|
|
167
|
+
}
|
|
168
|
+
return "flex-" + dir + " ×" + kids.length;
|
|
169
|
+
}
|
|
170
|
+
if (d < 3) for (const k of kids) queue.push([k, d + 1]);
|
|
171
|
+
}
|
|
172
|
+
return "block";
|
|
173
|
+
};
|
|
174
|
+
const imgOf = (el) => {
|
|
175
|
+
const r = el.getBoundingClientRect();
|
|
176
|
+
const kind = el.tagName.toLowerCase();
|
|
177
|
+
const alt = kind === "svg" ? (el.getAttribute("aria-label") || (el.querySelector("title") || {}).textContent || "") : (el.getAttribute("alt") || "");
|
|
178
|
+
const src = kind === "img" ? (el.currentSrc || el.src || "") : kind === "video" ? (el.currentSrc || el.poster || "") : "";
|
|
179
|
+
return { kind: kind, alt: String(alt).trim().slice(0, 80), w: Math.round(r.width), h: Math.round(r.height), src: src.slice(0, 160) };
|
|
180
|
+
};
|
|
181
|
+
const sectionOf = (el) => {
|
|
182
|
+
const r = el.getBoundingClientRect();
|
|
183
|
+
const hd = el.querySelector("h1, h2, h3, h4");
|
|
184
|
+
const imgs = Array.from(el.querySelectorAll("img, svg, video")).filter((k) => vis(k) && !(k.parentElement && k.parentElement.closest("svg")));
|
|
185
|
+
return {
|
|
186
|
+
tag: el.tagName.toLowerCase(), role: el.getAttribute("role"), id: el.id || null,
|
|
187
|
+
cls: typeof el.className === "string" && el.className.trim() ? el.className.trim().split(/\s+/).slice(0, 2).join(" ") : null,
|
|
188
|
+
heading: hd ? hd.textContent.trim().replace(/\s+/g, " ").slice(0, 80) : (el.getAttribute("aria-label") || null),
|
|
189
|
+
y: Math.round(r.top + sy), x: Math.round(r.left), w: Math.round(r.width), h: Math.round(r.height),
|
|
190
|
+
bg: effBg(el), bgImage: getComputedStyle(el).backgroundImage !== "none", layout: layoutOf(el),
|
|
191
|
+
images: imgs.slice(0, 8).map(imgOf), imageCount: imgs.length,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
let sections = [];
|
|
195
|
+
const walk = (el, depth) => {
|
|
196
|
+
for (const ch of el.children) {
|
|
197
|
+
if (sections.length >= 40) return;
|
|
198
|
+
if (!vis(ch) || !big(ch)) continue;
|
|
199
|
+
const role = ch.getAttribute("role");
|
|
200
|
+
const landmark = LANDMARK.has(ch.tagName) || (role && ROLES.has(role) && role !== "main");
|
|
201
|
+
const kids = Array.from(ch.children).filter((k) => vis(k) && big(k));
|
|
202
|
+
const r = ch.getBoundingClientRect();
|
|
203
|
+
const kidsH = kids.reduce((n, k) => n + k.getBoundingClientRect().height, 0);
|
|
204
|
+
// a wrapper is descended into: its big children are containers stacked top to bottom (not text, not columns)
|
|
205
|
+
const containers = kids.length >= 1 && stacked(kids) && !kids.some((k) => TEXTY.has(k.tagName.toUpperCase()));
|
|
206
|
+
const wrapper = !landmark && containers && kidsH >= r.height * 0.8 && (kids.length === 1 || !ownBg(ch));
|
|
207
|
+
const main = ch.tagName === "MAIN" || role === "main";
|
|
208
|
+
if (depth < 8 && (wrapper || (main && containers))) { walk(ch, depth + 1); continue; }
|
|
209
|
+
sections.push(sectionOf(ch));
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
if (document.body) {
|
|
213
|
+
walk(document.body, 0);
|
|
214
|
+
// a page whose blocks are all text (paragraphs straight in the body) is one section: the body
|
|
215
|
+
if (!sections.length || sections.every((x) => TEXTY.has(x.tag.toUpperCase()))) sections = [sectionOf(document.body)];
|
|
216
|
+
}
|
|
217
|
+
sections.sort((a, b) => a.y - b.y || a.x - b.x);
|
|
218
|
+
const grounding = [];
|
|
219
|
+
for (const el of document.querySelectorAll("a, button, input, select, textarea, label, h1, h2, h3, h4, h5, h6, p, li, img, [role=button]")) {
|
|
220
|
+
if (grounding.length >= 400) break;
|
|
221
|
+
if (!vis(el)) continue;
|
|
222
|
+
const r = el.getBoundingClientRect();
|
|
223
|
+
const tag = el.tagName.toLowerCase();
|
|
224
|
+
let text = "";
|
|
225
|
+
if (tag === "img") text = el.getAttribute("alt") || "";
|
|
226
|
+
else if (tag === "input" || tag === "textarea" || tag === "select") text = el.getAttribute("placeholder") || el.getAttribute("aria-label") || (el.getAttribute("type") || tag);
|
|
227
|
+
else text = (el.innerText || "").trim().replace(/\s+/g, " ");
|
|
228
|
+
if (!text && tag !== "img") continue;
|
|
229
|
+
grounding.push({ k: el.getAttribute("role") === "button" ? "button" : tag, text: text.slice(0, 80), x: Math.round(r.left), y: Math.round(r.top + sy), w: Math.round(r.width), h: Math.round(r.height) });
|
|
230
|
+
}
|
|
231
|
+
const images = Array.from(document.querySelectorAll("img, svg, video")).filter((k) => vis(k) && !k.parentElement.closest("svg")).slice(0, 80).map(imgOf);
|
|
232
|
+
const bps = new Set(), keyframes = new Set(), unreadable = [];
|
|
233
|
+
const rules = (list) => {
|
|
234
|
+
for (const rule of list) {
|
|
235
|
+
if (rule.media && rule.conditionText !== undefined || rule.type === 4) {
|
|
236
|
+
const t = rule.conditionText || (rule.media && rule.media.mediaText) || "";
|
|
237
|
+
const re = /(min|max)-width\s*:\s*([\d.]+)(px|em|rem)/g;
|
|
238
|
+
let m;
|
|
239
|
+
while ((m = re.exec(t))) bps.add(Math.round(parseFloat(m[2]) * (m[3] === "px" ? 1 : 16)));
|
|
240
|
+
}
|
|
241
|
+
if (rule.type === 7 && rule.name) keyframes.add(rule.name);
|
|
242
|
+
if (rule.cssRules) rules(rule.cssRules);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
for (const sh of document.styleSheets) {
|
|
246
|
+
let list = null;
|
|
247
|
+
try { list = sh.cssRules; } catch (e) { unreadable.push(sh.href || "(inline)"); continue; }
|
|
248
|
+
if (list) rules(list);
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
title: document.title, url: location.href, pageHeight: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0),
|
|
252
|
+
vw: vw, vh: vh, els: els, sections: sections, grounding: grounding, images: images,
|
|
253
|
+
breakpoints: Array.from(bps).sort((a, b) => a - b), keyframes: Array.from(keyframes).slice(0, 40), unreadableSheets: unreadable.slice(0, 10),
|
|
254
|
+
};
|
|
255
|
+
})()`;
|
|
256
|
+
const PRELOAD_SCRIPT = `(async () => {
|
|
257
|
+
const h = () => document.documentElement.scrollHeight;
|
|
258
|
+
for (let y = 0, i = 0; y < h() && i < 40; y += innerHeight, i++) { scrollTo(0, y); await new Promise((r) => setTimeout(r, 120)); }
|
|
259
|
+
scrollTo(0, 0);
|
|
260
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
261
|
+
return h();
|
|
262
|
+
})()`;
|
|
263
|
+
// Applied after extraction, before the tiles: animations jump to their end state so two captures are comparable.
|
|
264
|
+
const SETTLE_CSS = "*,*::before,*::after{animation-delay:-1ms!important;animation-duration:1ms!important;animation-iteration-count:1!important;transition-duration:0s!important;transition-delay:0s!important;scroll-behavior:auto!important;caret-color:transparent!important}";
|
|
265
|
+
function tally(m, v, by = 1) { m.set(v, (m.get(v) ?? 0) + by); }
|
|
266
|
+
function top(m, k, total) {
|
|
267
|
+
return [...m].sort((a, b) => b[1] - a[1]).slice(0, k)
|
|
268
|
+
.map(([v, n]) => (total ? { v, n, share: Math.round((n / total) * 1000) / 1000 } : { v, n }));
|
|
269
|
+
}
|
|
270
|
+
const firstFamily = (stack) => (stack.split(",")[0] ?? "").trim().replace(/^["']|["']$/g, "");
|
|
271
|
+
const HEADING = /^h[1-6]$/;
|
|
272
|
+
export function aggregateTokens(els, band) {
|
|
273
|
+
const inBand = band ? els.filter((e) => e.y1 > band.y0 && e.y0 < band.y1) : els;
|
|
274
|
+
const text = new Map(), bg = new Map(), border = new Map();
|
|
275
|
+
const fams = new Map();
|
|
276
|
+
const sizes = new Map(), radii = new Map(), shadows = new Map();
|
|
277
|
+
const spacing = new Map(), maxW = new Map(), anim = new Map(), trans = new Map();
|
|
278
|
+
const styleBy = new Map();
|
|
279
|
+
let textTotal = 0, bgTotal = 0, centred = 0;
|
|
280
|
+
for (const e of inBand) {
|
|
281
|
+
const y0 = band ? Math.max(e.y0, band.y0) : e.y0, y1 = band ? Math.min(e.y1, band.y1) : e.y1;
|
|
282
|
+
const area = Math.max(0, y1 - y0) * Math.max(0, e.x1 - e.x0);
|
|
283
|
+
if (e.txt && e.c) {
|
|
284
|
+
tally(text, e.c, e.txt);
|
|
285
|
+
textTotal += e.txt;
|
|
286
|
+
}
|
|
287
|
+
if (e.bg) {
|
|
288
|
+
tally(bg, e.bg, area);
|
|
289
|
+
bgTotal += area;
|
|
290
|
+
}
|
|
291
|
+
if (e.bc)
|
|
292
|
+
tally(border, e.bc);
|
|
293
|
+
if (e.txt) {
|
|
294
|
+
const fam = firstFamily(e.ff);
|
|
295
|
+
const f = fams.get(fam) ?? { stack: e.ff, n: 0, weights: new Set(), sizes: new Set() };
|
|
296
|
+
f.n += e.txt;
|
|
297
|
+
f.weights.add(e.fw);
|
|
298
|
+
f.sizes.add(Math.round(e.fs));
|
|
299
|
+
fams.set(fam, f);
|
|
300
|
+
tally(sizes, Math.round(e.fs), 1);
|
|
301
|
+
const key = HEADING.test(e.t) ? e.t : "body";
|
|
302
|
+
const style = JSON.stringify([Math.round(e.fs), e.fw, e.lh == null ? null : Math.round((e.lh / e.fs) * 100) / 100,
|
|
303
|
+
e.ls == null ? null : Math.round((e.ls / e.fs) * 1000) / 1000, fam]);
|
|
304
|
+
const sm = styleBy.get(key) ?? new Map();
|
|
305
|
+
tally(sm, style, key === "body" ? e.txt : 1);
|
|
306
|
+
styleBy.set(key, sm);
|
|
307
|
+
}
|
|
308
|
+
if (e.r)
|
|
309
|
+
tally(radii, e.r);
|
|
310
|
+
if (e.sh)
|
|
311
|
+
tally(shadows, e.sh);
|
|
312
|
+
for (const s of e.sp)
|
|
313
|
+
tally(spacing, s);
|
|
314
|
+
if (e.mw && e.mw >= 320)
|
|
315
|
+
tally(maxW, Math.round(e.mw));
|
|
316
|
+
if (e.cw)
|
|
317
|
+
centred = Math.max(centred, e.x1 - e.x0);
|
|
318
|
+
if (e.an)
|
|
319
|
+
tally(anim, e.an);
|
|
320
|
+
if (e.tr)
|
|
321
|
+
tally(trans, e.tr);
|
|
322
|
+
}
|
|
323
|
+
const styleOf = (key) => {
|
|
324
|
+
const m = styleBy.get(key);
|
|
325
|
+
if (!m)
|
|
326
|
+
return null;
|
|
327
|
+
const [size, weight, lineHeight, letterSpacingEm, family] = JSON.parse(top(m, 1)[0].v);
|
|
328
|
+
return { size, weight, lineHeight, letterSpacingEm, family };
|
|
329
|
+
};
|
|
330
|
+
const headings = {};
|
|
331
|
+
for (const h of ["h1", "h2", "h3", "h4", "h5", "h6"]) {
|
|
332
|
+
const s = styleOf(h);
|
|
333
|
+
if (s)
|
|
334
|
+
headings[h] = s;
|
|
335
|
+
}
|
|
336
|
+
const mw = top(maxW, 1)[0];
|
|
337
|
+
return {
|
|
338
|
+
palette: { text: top(text, 10, textTotal), background: top(bg, 10, bgTotal), border: top(border, 6) },
|
|
339
|
+
fonts: [...fams].sort((a, b) => b[1].n - a[1].n).slice(0, 6).map(([family, f]) => ({
|
|
340
|
+
family, stack: f.stack.slice(0, 120), n: f.n, weights: [...f.weights].sort((a, b) => a - b), sizes: [...f.sizes].sort((a, b) => b - a),
|
|
341
|
+
})),
|
|
342
|
+
typeScale: [...sizes].sort((a, b) => b[0] - a[0]).map(([v, n]) => ({ v, n })),
|
|
343
|
+
headings,
|
|
344
|
+
body: styleOf("body"),
|
|
345
|
+
radii: top(radii, 8),
|
|
346
|
+
shadows: top(shadows, 5),
|
|
347
|
+
spacing: top(spacing, 14),
|
|
348
|
+
maxContentWidth: mw ? { px: mw.v, from: "max-width" } : centred ? { px: Math.round(centred), from: "centred-container" } : null,
|
|
349
|
+
motion: { animations: top(anim, 8), transitions: top(trans, 8) },
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
// ── Local pages: served from a loopback HTTP server (the browser policy blocks file://) ─────────────────────
|
|
353
|
+
const CONTENT_TYPES = {
|
|
354
|
+
".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8",
|
|
355
|
+
".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".json": "application/json",
|
|
356
|
+
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
357
|
+
".webp": "image/webp", ".avif": "image/avif", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2",
|
|
358
|
+
".ttf": "font/ttf", ".otf": "font/otf", ".mp4": "video/mp4", ".webm": "video/webm",
|
|
359
|
+
};
|
|
360
|
+
function listen(server) {
|
|
361
|
+
return new Promise((res, rej) => {
|
|
362
|
+
server.once("error", rej);
|
|
363
|
+
server.listen(0, "127.0.0.1", () => res(server.address().port));
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
/** A URL, a file:// URL, a path to an .html file or folder, or raw HTML → a URL the browser may open.
|
|
367
|
+
* Local files are served read-only from their folder: web asset types only, no dotfiles, no escaping the folder. */
|
|
368
|
+
export async function resolvePage(input, cwd = process.cwd()) {
|
|
369
|
+
const s = input.trim();
|
|
370
|
+
if (/^https?:\/\//i.test(s))
|
|
371
|
+
return { url: s, local: false, close: async () => { } };
|
|
372
|
+
if (s.startsWith("<")) {
|
|
373
|
+
const server = createServer((req, res) => {
|
|
374
|
+
if ((req.url ?? "/").split("?")[0] === "/") {
|
|
375
|
+
res.writeHead(200, { "content-type": CONTENT_TYPES[".html"] });
|
|
376
|
+
res.end(s);
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
res.writeHead(404);
|
|
380
|
+
res.end();
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
const port = await listen(server);
|
|
384
|
+
return { url: `http://127.0.0.1:${port}/`, local: true, close: () => new Promise((r) => server.close(() => r())) };
|
|
385
|
+
}
|
|
386
|
+
let path = s.startsWith("file://") ? fileURLToPath(s) : s.startsWith("~/") ? join(homedir(), s.slice(2)) : resolve(cwd, s);
|
|
387
|
+
if (!existsSync(path))
|
|
388
|
+
throw new Error(`no page at ${path} (pass an http(s) URL, a file path or raw HTML)`);
|
|
389
|
+
if (statSync(path).isDirectory())
|
|
390
|
+
path = join(path, "index.html");
|
|
391
|
+
if (!/\.html?$/i.test(path) || !existsSync(path))
|
|
392
|
+
throw new Error(`${path} is not an .html file`);
|
|
393
|
+
const root = dirname(path);
|
|
394
|
+
const server = createServer((req, res) => {
|
|
395
|
+
let rel;
|
|
396
|
+
try {
|
|
397
|
+
rel = decodeURIComponent((req.url ?? "/").split("?")[0]);
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
res.writeHead(400);
|
|
401
|
+
res.end();
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const file = normalize(join(root, rel === "/" ? basename(path) : rel));
|
|
405
|
+
const type = CONTENT_TYPES[extname(file).toLowerCase()];
|
|
406
|
+
const inside = file.startsWith(root + sep) && !file.slice(root.length).split(sep).some((seg) => seg.startsWith("."));
|
|
407
|
+
if (!inside || !type || !existsSync(file) || !statSync(file).isFile()) {
|
|
408
|
+
res.writeHead(404);
|
|
409
|
+
res.end();
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
res.writeHead(200, { "content-type": type });
|
|
413
|
+
res.end(readFileSync(file));
|
|
414
|
+
});
|
|
415
|
+
const port = await listen(server);
|
|
416
|
+
return { url: `http://127.0.0.1:${port}/${encodeURIComponent(basename(path))}`, local: true, close: () => new Promise((r) => server.close(() => r())) };
|
|
417
|
+
}
|
|
418
|
+
async function evaluate(cdp, expression, awaitPromise = false) {
|
|
419
|
+
const raw = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise });
|
|
420
|
+
if (raw?.exceptionDetails)
|
|
421
|
+
throw new Error(`page js error: ${raw.exceptionDetails.exception?.description ?? raw.exceptionDetails.text}`);
|
|
422
|
+
return raw?.result?.value;
|
|
423
|
+
}
|
|
424
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
425
|
+
const PHONE_UA = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36";
|
|
426
|
+
export class CaptureBrowser {
|
|
427
|
+
browser;
|
|
428
|
+
ua;
|
|
429
|
+
constructor(browser, ua) {
|
|
430
|
+
this.browser = browser;
|
|
431
|
+
this.ua = ua;
|
|
432
|
+
}
|
|
433
|
+
/** A throwaway profile always: the browser tool may hold the persistent one. */
|
|
434
|
+
static async start() {
|
|
435
|
+
const browser = await launchBrowser({ throwaway: true });
|
|
436
|
+
try {
|
|
437
|
+
const page = await browser.context.newPage();
|
|
438
|
+
const ua = String(await page.evaluate("navigator.userAgent"));
|
|
439
|
+
await page.close();
|
|
440
|
+
return new CaptureBrowser(browser, ua.replace("HeadlessChrome", "Chrome"));
|
|
441
|
+
}
|
|
442
|
+
catch (e) {
|
|
443
|
+
await browser.close().catch(() => undefined);
|
|
444
|
+
throw e;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/** Load `url` at one viewport, extract tokens and outline, then write viewport-height tiles into `outDir`. */
|
|
448
|
+
async capture(url, vp, outDir, prefix) {
|
|
449
|
+
const blocked = checkNavigationUrl(url) ?? (await captureBlockedReason(url));
|
|
450
|
+
if (blocked)
|
|
451
|
+
throw new Error(blocked);
|
|
452
|
+
const page = await this.browser.context.newPage();
|
|
453
|
+
try {
|
|
454
|
+
const cdp = await this.browser.context.newCDPSession(page);
|
|
455
|
+
const mobile = vp.width < 768;
|
|
456
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", { width: vp.width, height: vp.height, deviceScaleFactor: 1, mobile });
|
|
457
|
+
await cdp.send("Emulation.setUserAgentOverride", { userAgent: mobile ? PHONE_UA : this.ua });
|
|
458
|
+
await cdp.send("Emulation.setScrollbarsHidden", { hidden: true }).catch(() => undefined);
|
|
459
|
+
if (mobile)
|
|
460
|
+
await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
|
|
461
|
+
await page.goto(url, { waitUntil: "load", timeout: BROWSER_CONSTANTS.NAV_TIMEOUT_MS }).catch(() => undefined); // capture what loaded
|
|
462
|
+
await evaluate(cdp, "document.fonts ? document.fonts.ready.then(() => 1) : 1", true).catch(() => undefined);
|
|
463
|
+
await evaluate(cdp, PRELOAD_SCRIPT, true).catch(() => undefined);
|
|
464
|
+
const ex = await evaluate(cdp, EXTRACT_SCRIPT);
|
|
465
|
+
await evaluate(cdp, `(() => { const s = document.createElement("style"); s.textContent = ${JSON.stringify(SETTLE_CSS)}; document.documentElement.appendChild(s); return 1; })()`);
|
|
466
|
+
await sleep(150);
|
|
467
|
+
mkdirSync(outDir, { recursive: true });
|
|
468
|
+
const want = Math.max(1, Math.ceil(ex.pageHeight / vp.height));
|
|
469
|
+
const n = Math.min(want, MAX_TILES);
|
|
470
|
+
const tiles = [];
|
|
471
|
+
let lastY = -1;
|
|
472
|
+
for (let i = 0; i < n; i++) {
|
|
473
|
+
const y = await evaluate(cdp, `(() => { scrollTo(0, ${i * vp.height}); return Math.round(scrollY); })()`);
|
|
474
|
+
await sleep(150);
|
|
475
|
+
let shot;
|
|
476
|
+
if (y === lastY || (i > 0 && y < i * vp.height - vp.height)) {
|
|
477
|
+
// the window does not scroll (an inner scroller, overflow:hidden): clip the page instead
|
|
478
|
+
shot = await cdp.send("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, clip: { x: 0, y: i * vp.height, width: vp.width, height: vp.height, scale: 1 } });
|
|
479
|
+
lastY = i * vp.height;
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
shot = await cdp.send("Page.captureScreenshot", { format: "png" });
|
|
483
|
+
lastY = y;
|
|
484
|
+
}
|
|
485
|
+
const path = join(outDir, `${prefix}-${vp.name}-${i}.png`);
|
|
486
|
+
writeFileSync(path, Buffer.from(shot.data, "base64"));
|
|
487
|
+
tiles.push({ index: i, path, y: lastY, height: vp.height });
|
|
488
|
+
}
|
|
489
|
+
return { ...ex, viewport: vp, tiles, truncated: want > n };
|
|
490
|
+
}
|
|
491
|
+
finally {
|
|
492
|
+
await page.close().catch(() => undefined);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
async close() {
|
|
496
|
+
await this.browser.close().catch(() => undefined);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
/** `<name>-<UTC stamp>` under the Operator cache, mirroring the browser tool's screenshot folder. */
|
|
500
|
+
export async function captureDir(kind, label) {
|
|
501
|
+
const { operatorPath } = await import("../config/home.js");
|
|
502
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
503
|
+
const slug = label.replace(/^https?:\/\//, "").replace(/[^A-Za-z0-9.-]+/g, "_").slice(0, 60) || "page";
|
|
504
|
+
return operatorPath("cache", kind, `${slug}-${stamp}`);
|
|
505
|
+
}
|
package/dist/browser/engine.js
CHANGED
|
@@ -84,8 +84,9 @@ export function browserCandidates(env, platform, fs) {
|
|
|
84
84
|
}
|
|
85
85
|
const MISSING = /Executable doesn't exist|ENOENT|no such file/i;
|
|
86
86
|
/** Headless, and a throwaway profile unless KODE_BROWSER_PROFILE=persistent (then `<operator home>/browser`, never the
|
|
87
|
-
* owner's Chrome profile).
|
|
88
|
-
|
|
87
|
+
* owner's Chrome profile). `throwaway` forces a fresh profile (page_capture runs beside the browser tool, and two
|
|
88
|
+
* Chromes cannot share one). Tries each candidate binary until one starts; the error names every one tried and the fix. */
|
|
89
|
+
export async function launchBrowser(opts = {}) {
|
|
89
90
|
let pw;
|
|
90
91
|
try {
|
|
91
92
|
pw = await nodeImport("playwright-core");
|
|
@@ -109,7 +110,7 @@ export async function launchBrowser() {
|
|
|
109
110
|
return [];
|
|
110
111
|
} },
|
|
111
112
|
});
|
|
112
|
-
const persistent = proc.env.KODE_BROWSER_PROFILE === "persistent";
|
|
113
|
+
const persistent = !opts.throwaway && proc.env.KODE_BROWSER_PROFILE === "persistent";
|
|
113
114
|
const tried = [];
|
|
114
115
|
for (const executablePath of candidates) {
|
|
115
116
|
const name = executablePath ?? "playwright's chromium";
|