Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(page): read, audit and restyle page themes

Shahriar9bf472f40e94
diff --git a/lib/actions/page/apply-theme.ts b/lib/actions/page/apply-theme.ts
new file mode 100644
index 0000000..1313757
--- /dev/null
+++ b/lib/actions/page/apply-theme.ts
@@ -0,0 +1,252 @@
+import { z } from 'zod';
+import { ActionError, defineAction } from '../core';
+import {
+ brightnessFor,
+ invertColor,
+ parseColor,
+ relativeLuminance,
+ toHex,
+ WHITE,
+ type FilterChain,
+} from './color';
+import {
+ injectTheme,
+ measureTheme,
+ recordFilter,
+ removeInjectedTheme,
+ scanStyleSheets,
+ type ThemeHook,
+} from './theme';
+
+const MAX_RULES = 20000;
+const MAX_TOKENS = 40;
+const TOKEN_NAME = /^--[A-Za-z0-9_-]+$/;
+const UNSAFE_VALUE = /[;{}<>\\]|@import|url\(|expression\(/i;
+const DARK_TARGET = 0.05;
+const LIGHT_TARGET = 0.92;
+const TOLERANCE = 0.08;
+const MEDIA = 'img, picture, video, canvas, svg, iframe, embed, object';
+const UNINVERT = 'invert(1) hue-rotate(180deg)';
+
+export const applyTheme = defineAction({
+ name: 'page.applyTheme',
+ description:
+ 'Retheme the page, or put it back. Prefers the page’s own terms — it switches on the dark/light hook its stylesheets ' +
+ 'already define (a ".dark" class, a [data-theme] attribute), sets color-scheme, and overrides the design tokens you name. ' +
+ 'Only when that leaves the page at the wrong luminance does it fall back to repainting through a CSS filter. ' +
+ 'Reports the measured background luminance and text contrast before and after, so the change can be checked rather than assumed. ' +
+ 'The filter fallback creates a containing block on <html>, which re-anchors position:fixed elements, and it re-inverts images ' +
+ 'so photos stay right way round. Nothing here survives a reload — call it again, or with mode "revert", to undo it.',
+ input: z.object({
+ mode: z
+ .enum(['keep', 'dark', 'light', 'revert'])
+ .default('keep')
+ .describe(
+ 'Which way to push the page: "dark" or "light" retheme it, "revert" removes everything Browsentic applied and ' +
+ 'restores the page’s own theme, "keep" leaves the light/dark decision alone and applies only the colours below',
+ ),
+ targetLuminance: z
+ .number()
+ .min(0)
+ .max(1)
+ .optional()
+ .describe(
+ 'Relative luminance to bring the page background to, 0 black to 1 white, as reported by page.readTheme. ' +
+ 'Overrides the luminance "dark" and "light" imply. Reached by filtering, so it repaints images and text alike',
+ ),
+ background: z
+ .string()
+ .optional()
+ .describe('CSS colour for the page background, e.g. "#0f172a" or "rgb(15 23 42)"; suppresses the luminance a mode would imply'),
+ text: z.string().optional().describe('CSS colour for body text; elements that set their own colour keep it'),
+ accent: z.string().optional().describe('CSS colour for links and form-control accents'),
+ tokens: z
+ .record(z.string(), z.string())
+ .optional()
+ .describe(
+ 'CSS custom properties to override on :root, e.g. {"--background": "#0f172a"}. Names come from page.readTheme’s ' +
+ 'tokens — this is the cleanest way to retheme a page that is built on design tokens, because its own rules do the work',
+ ),
+ saturation: z
+ .number()
+ .min(0)
+ .max(3)
+ .optional()
+ .describe('Colour intensity multiplier: 0 greyscale, 1 unchanged, above 1 more vivid'),
+ contrast: z
+ .number()
+ .min(0)
+ .max(3)
+ .optional()
+ .describe('Contrast multiplier: 1 unchanged, above 1 pushes lights and darks apart'),
+ transitionMs: z
+ .number()
+ .int()
+ .nonnegative()
+ .max(2000)
+ .default(200)
+ .describe('How long the page takes to cross-fade into the new theme; 0 switches instantly'),
+ }),
+ execute({ mode, targetLuminance, background, text, accent, tokens, saturation, contrast, transitionMs }) {
+ const colors = {
+ background: asColor(background, 'background'),
+ text: asColor(text, 'text'),
+ accent: asColor(accent, 'accent'),
+ };
+ const overrides = tokenOverrides(tokens);
+ const adjusts = saturation !== undefined || contrast !== undefined;
+ if (mode === 'keep' && targetLuminance === undefined && !adjusts && !overrides.length && !Object.values(colors).some(Boolean)) {
+ throw new ActionError(
+ 'Nothing to apply — pass a "mode", a "targetLuminance", a colour, or "tokens".',
+ 'INVALID_INPUT',
+ );
+ }
+
+ const replaced = removeInjectedTheme();
+ const before = measureTheme();
+ if (mode === 'revert') return { reverted: replaced, theme: before };
+
+ const hook = mode === 'dark' || mode === 'light' ? bestHook(mode) : undefined;
+ const style = injectTheme(baseCss({ mode, colors, overrides, transitionMs }), hook);
+ const settled = measureTheme();
+
+ const target = targetLuminance ?? (colors.background ? undefined : impliedTarget(mode, settled.luminance));
+ const chain = filterChain(target, settled.background, saturation, contrast);
+ if (chain) {
+ style.textContent += `\n${filterCss(chain, settled.background, transitionMs)}`;
+ recordFilter(style, chain);
+ }
+
+ const after = measureTheme();
+ return {
+ replaced,
+ strategy: chain ? 'filter' : hook || mode !== 'keep' ? 'stylesheet' : 'colors',
+ applied: {
+ mode,
+ hook,
+ ...colors,
+ tokens: overrides.length ? overrides.map(([name]) => name) : undefined,
+ filter: chain ? filterFunctions(chain).join(' ') : undefined,
+ targetLuminance: target,
+ },
+ css: (style.textContent ?? '').slice(0, 4000),
+ before,
+ after,
+ ...(target === undefined ? {} : { reachedTarget: Math.abs(after.luminance - target) <= TOLERANCE }),
+ };
+ },
+});
+
+function asColor(value: string | undefined, field: string): string | undefined {
+ if (value === undefined) return undefined;
+ const color = parseColor(value);
+ if (!color) {
+ throw new ActionError(
+ `"${field}" is not a colour this browser understands — pass something like "#0f172a", "rgb(15 23 42)" or "midnightblue".`,
+ 'INVALID_INPUT',
+ );
+ }
+ return toHex(color);
+}
+
+function tokenOverrides(tokens: Record<string, string> | undefined): [string, string][] {
+ const entries = Object.entries(tokens ?? {});
+ if (entries.length > MAX_TOKENS) {
+ throw new ActionError(
+ `Too many tokens — ${entries.length} given and ${MAX_TOKENS} is the limit. Override only the ones that carry the theme.`,
+ 'INVALID_INPUT',
+ );
+ }
+ return entries.map(([name, value]) => {
+ if (!TOKEN_NAME.test(name)) {
+ throw new ActionError(`"${name}" is not a custom property — names look like "--brand-500".`, 'INVALID_INPUT');
+ }
+ const trimmed = value.trim();
+ if (!trimmed || UNSAFE_VALUE.test(trimmed)) {
+ throw new ActionError(
+ `The value for "${name}" is not a plain CSS value — it cannot be empty or carry ";", "{", "}", "\\" or "url(".`,
+ 'INVALID_INPUT',
+ );
+ }
+ return [name, trimmed];
+ });
+}
+
+function bestHook(scheme: 'dark' | 'light'): ThemeHook | undefined {
+ return scanStyleSheets(MAX_RULES)
+ .hooks.filter((hook) => hook.scheme === scheme)
+ .sort((one, other) => rankHook(one) - rankHook(other))[0];
+}
+
+function rankHook(hook: ThemeHook): number {
+ if (hook.kind === 'attribute') return hook.name === 'data-theme' ? 0 : 1;
+ return hook.name.toLowerCase() === hook.scheme ? 2 : 3;
+}
+
+interface Plan {
+ mode: 'keep' | 'dark' | 'light';
+ colors: { background?: string; text?: string; accent?: string };
+ overrides: [string, string][];
+ transitionMs: number;
+}
+
+function baseCss({ mode, colors, overrides, transitionMs }: Plan): string {
+ const rules: string[] = [];
+ if (mode !== 'keep') rules.push(`:root { color-scheme: ${mode}; }`);
+ if (overrides.length) {
+ rules.push(`:root { ${overrides.map(([name, value]) => `${name}: ${value};`).join(' ')} }`);
+ }
+ if (colors.background) rules.push(`html, body { background-color: ${colors.background} !important; }`);
+ if (colors.text) rules.push(`html, body { color: ${colors.text} !important; }`);
+ if (colors.accent) {
+ rules.push(`:root { accent-color: ${colors.accent} !important; }`, `a { color: ${colors.accent} !important; }`);
+ }
+ if (transitionMs > 0) {
+ rules.push(
+ `html, body { transition: background-color ${transitionMs}ms linear, color ${transitionMs}ms linear, filter ${transitionMs}ms linear; }`,
+ );
+ }
+ return rules.join('\n');
+}
+
+function impliedTarget(mode: 'keep' | 'dark' | 'light', luminance: number): number | undefined {
+ if (mode === 'dark') return luminance > 0.5 ? DARK_TARGET : undefined;
+ if (mode === 'light') return luminance < 0.5 ? LIGHT_TARGET : undefined;
+ return undefined;
+}
+
+function filterChain(
+ target: number | undefined,
+ background: string,
+ saturate: number | undefined,
+ contrast: number | undefined,
+): FilterChain | undefined {
+ const current = parseColor(background) ?? WHITE;
+ const luminance = relativeLuminance(current);
+ const invert = target !== undefined && (target < 0.5) !== (luminance < 0.5);
+ const reachable = invert ? relativeLuminance(invertColor(current)) : luminance;
+ const brightness =
+ target === undefined || reachable <= 0.004
+ ? 1
+ : brightnessFor(invert ? invertColor(current) : current, target);
+ if (!invert && brightness === 1 && saturate === undefined && contrast === undefined) return undefined;
+ return { invert, brightness, saturate, contrast };
+}
+
+function filterFunctions({ invert, brightness, saturate, contrast }: FilterChain): string[] {
+ return [
+ invert ? UNINVERT : '',
+ brightness === 1 ? '' : `brightness(${brightness})`,
+ saturate === undefined ? '' : `saturate(${saturate})`,
+ contrast === undefined ? '' : `contrast(${contrast})`,
+ ].filter(Boolean);
+}
+
+function filterCss(chain: FilterChain, background: string, transitionMs: number): string {
+ const rules = [
+ `html { background-color: ${background}; filter: ${filterFunctions(chain).join(' ')}; }`,
+ ];
+ if (chain.invert) rules.push(`${MEDIA} { filter: ${UNINVERT}; }`);
+ if (transitionMs > 0) rules.push(`${MEDIA} { transition: filter ${transitionMs}ms linear; }`);
+ return rules.join('\n');
+}
diff --git a/lib/actions/page/audit-contrast.ts b/lib/actions/page/audit-contrast.ts
new file mode 100644
index 0000000..a193bea
--- /dev/null
+++ b/lib/actions/page/audit-contrast.ts
@@ -0,0 +1,126 @@
+import { z } from 'zod';
+import { defineAction } from '../core';
+import {
+ contrastRatio,
+ effectiveBackground,
+ effectiveForeground,
+ isLargeText,
+ requiredRatio,
+ round,
+ toHex,
+ type Rgb,
+} from './color';
+import { cssPath, documentBounds, isExposed, resolveTarget, targetSchema } from './dom';
+import { asRendered } from './theme';
+
+const TEXT_CLIP = 60;
+
+interface Check {
+ selector: string;
+ text: string;
+ foreground: string;
+ background: string;
+ ratio: number;
+ required: number;
+ passes: boolean;
+ fontSizePx: number;
+ weight: number;
+ large: boolean;
+ bounds: { x: number; y: number; width: number; height: number };
+}
+
+export const auditContrast = defineAction({
+ name: 'page.auditContrast',
+ description:
+ 'Score the readability of the page against WCAG contrast rules. Walks the visible text, resolves each run’s ' +
+ 'foreground against the real background painted behind it — blending translucent layers up the ancestor chain — ' +
+ 'and reports the ratio, the ratio the level requires, and whether it passes. ' +
+ 'The score is the share of sampled text runs that pass, so it is directly comparable before and after page.applyTheme.',
+ input: z.object({
+ target: targetSchema.optional().describe('Subtree to audit; defaults to the whole page'),
+ level: z
+ .enum(['AA', 'AAA'])
+ .default('AA')
+ .describe('WCAG level: AA needs 4.5:1 for body text and 3:1 for large text, AAA needs 7:1 and 4.5:1'),
+ maxSamples: z
+ .number()
+ .int()
+ .positive()
+ .max(2000)
+ .default(400)
+ .describe('Text-bearing elements to check, in document order'),
+ maxFailures: z
+ .number()
+ .int()
+ .nonnegative()
+ .max(200)
+ .default(20)
+ .describe('Failures listed, worst ratio first; the counts always cover everything sampled'),
+ }),
+ execute({ target, level, maxSamples, maxFailures }) {
+ const root = target ? resolveTarget(target) : (document.body ?? document.documentElement);
+ const checks = sampleText(root, level, maxSamples, asRendered());
+ const failures = checks.filter((check) => !check.passes).sort((one, other) => one.ratio - other.ratio);
+ const passed = checks.length - failures.length;
+
+ return {
+ url: location.href,
+ level,
+ required: { normalText: requiredRatio(false, level), largeText: requiredRatio(true, level) },
+ ...(checks.length ? { score: Math.round((passed / checks.length) * 100) } : {}),
+ summary: {
+ sampled: checks.length,
+ passed,
+ failed: failures.length,
+ worstRatio: checks.length ? Math.min(...checks.map((check) => check.ratio)) : undefined,
+ },
+ failures: failures.slice(0, maxFailures),
+ source: cssPath(root),
+ };
+ },
+});
+
+function sampleText(
+ root: Element,
+ level: 'AA' | 'AAA',
+ maxSamples: number,
+ shown: (color: Rgb) => Rgb,
+): Check[] {
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ const seen = new Set<Element>();
+ const checks: Check[] = [];
+ for (let node = walker.nextNode(); node && checks.length < maxSamples; node = walker.nextNode()) {
+ const text = (node.textContent ?? '').replace(/\s+/g, ' ').trim();
+ const el = node.parentElement;
+ if (!text || !el || seen.has(el)) continue;
+ seen.add(el);
+ if (!isExposed(el)) continue;
+ checks.push(evaluate(el, text, level, shown));
+ }
+ return checks;
+}
+
+function evaluate(el: HTMLElement, text: string, level: 'AA' | 'AAA', shown: (color: Rgb) => Rgb): Check {
+ const style = getComputedStyle(el);
+ const painted = effectiveBackground(el);
+ const background = shown(painted);
+ const foreground = shown(effectiveForeground(el, painted));
+ const fontSizePx = round(parseFloat(style.fontSize), 1);
+ const weight = Number(style.fontWeight) || 400;
+ const large = isLargeText(fontSizePx, weight);
+ const ratio = round(contrastRatio(foreground, background), 2);
+ const required = requiredRatio(large, level);
+ return {
+ selector: cssPath(el),
+ text: text.slice(0, TEXT_CLIP),
+ foreground: toHex(foreground),
+ background: toHex(background),
+ ratio,
+ required,
+ passes: ratio >= required,
+ fontSizePx,
+ weight,
+ large,
+ bounds: documentBounds(el),
+ };
+}
diff --git a/lib/actions/page/color.ts b/lib/actions/page/color.ts
new file mode 100644
index 0000000..466f376
--- /dev/null
+++ b/lib/actions/page/color.ts
@@ -0,0 +1,222 @@
+export interface Rgb {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+
+export const TRANSPARENT: Rgb = { r: 0, g: 0, b: 0, a: 0 };
+export const WHITE: Rgb = { r: 255, g: 255, b: 255, a: 1 };
+export const DARK_CANVAS: Rgb = { r: 18, g: 18, b: 18, a: 1 };
+
+const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
+const RGB_FUNCTION = /^rgba?\(([^)]+)\)$/i;
+const NUMBER = /-?\d*\.?\d+(?:e-?\d+)?%?/gi;
+
+const parsed = new Map<string, Rgb | null>();
+
+export function parseColor(value: string | null | undefined): Rgb | null {
+ const text = value?.trim();
+ if (!text) return null;
+ if (!parsed.has(text)) parsed.set(text, computeColor(text));
+ return parsed.get(text) ?? null;
+}
+
+function computeColor(text: string): Rgb | null {
+ if (text === 'transparent') return TRANSPARENT;
+ return fromHex(text) ?? fromRgbFunction(text) ?? fromEngine(text);
+}
+
+function fromHex(text: string): Rgb | null {
+ if (!HEX.test(text)) return null;
+ const digits = text.slice(1);
+ const wide = digits.length > 4;
+ const step = wide ? 2 : 1;
+ const channel = (index: number) => {
+ const part = digits.slice(index * step, index * step + step);
+ return parseInt(wide ? part : part + part, 16);
+ };
+ const alpha = digits.length === 4 || digits.length === 8 ? channel(3) / 255 : 1;
+ return { r: channel(0), g: channel(1), b: channel(2), a: alpha };
+}
+
+function fromRgbFunction(text: string): Rgb | null {
+ const body = RGB_FUNCTION.exec(text)?.[1];
+ const parts = body?.match(NUMBER);
+ if (!parts || parts.length < 3) return null;
+ const scaled = (part: string, full: number) =>
+ part.endsWith('%') ? (parseFloat(part) / 100) * full : parseFloat(part);
+ return {
+ r: clampByte(scaled(parts[0], 255)),
+ g: clampByte(scaled(parts[1], 255)),
+ b: clampByte(scaled(parts[2], 255)),
+ a: parts[3] === undefined ? 1 : clamp01(scaled(parts[3], 1)),
+ };
+}
+
+let probe: CanvasRenderingContext2D | null | undefined;
+
+function probeContext(): CanvasRenderingContext2D | null {
+ probe ??= document.createElement('canvas').getContext('2d', { willReadFrequently: true });
+ return probe;
+}
+
+function fromEngine(text: string): Rgb | null {
+ const context = probeContext();
+ if (!context) return null;
+ context.fillStyle = '#000000';
+ context.fillStyle = text;
+ const darkGuess = context.fillStyle;
+ context.fillStyle = '#ffffff';
+ context.fillStyle = text;
+ if (darkGuess !== context.fillStyle) return null;
+ return fromHex(context.fillStyle) ?? fromRgbFunction(context.fillStyle) ?? fromPixel(context, text);
+}
+
+function fromPixel(context: CanvasRenderingContext2D, text: string): Rgb | null {
+ context.clearRect(0, 0, 1, 1);
+ context.fillStyle = text;
+ context.fillRect(0, 0, 1, 1);
+ const [r, g, b, alpha] = context.getImageData(0, 0, 1, 1).data;
+ return { r, g, b, a: alpha / 255 };
+}
+
+export function toHex({ r, g, b, a }: Rgb): string {
+ const pair = (channel: number) => clampByte(channel).toString(16).padStart(2, '0');
+ const opacity = a >= 1 ? '' : pair(Math.round(a * 255));
+ return `#${pair(r)}${pair(g)}${pair(b)}${opacity}`;
+}
+
+export function invertColor({ r, g, b, a }: Rgb): Rgb {
+ return { r: 255 - r, g: 255 - g, b: 255 - b, a };
+}
+
+export function relativeLuminance({ r, g, b }: Rgb): number {
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
+}
+
+function linear(channel: number): number {
+ const scaled = clampByte(channel) / 255;
+ return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
+}
+
+export function contrastRatio(one: Rgb, other: Rgb): number {
+ const first = relativeLuminance(one);
+ const second = relativeLuminance(other);
+ const lighter = Math.max(first, second);
+ const darker = Math.min(first, second);
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+export function blend(over: Rgb, under: Rgb): Rgb {
+ const alpha = over.a + under.a * (1 - over.a);
+ if (alpha === 0) return TRANSPARENT;
+ const mix = (top: number, bottom: number) =>
+ Math.round((top * over.a + bottom * under.a * (1 - over.a)) / alpha);
+ return { r: mix(over.r, under.r), g: mix(over.g, under.g), b: mix(over.b, under.b), a: alpha };
+}
+
+export function resolvedScheme(): 'light' | 'dark' {
+ const declared = getComputedStyle(document.documentElement).colorScheme || 'normal';
+ if (!declared.includes('dark')) return 'light';
+ if (!declared.includes('light')) return 'dark';
+ return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
+}
+
+export function canvasBackdrop(): Rgb {
+ return resolvedScheme() === 'dark' ? DARK_CANVAS : WHITE;
+}
+
+export function effectiveBackground(el: Element): Rgb {
+ let stacked = TRANSPARENT;
+ for (let node: Element | null = el; node; node = node.parentElement) {
+ const layer = parseColor(getComputedStyle(node).backgroundColor);
+ if (!layer || layer.a === 0) continue;
+ stacked = blend(stacked, layer);
+ if (stacked.a >= 1) return stacked;
+ }
+ return blend(stacked, canvasBackdrop());
+}
+
+export function effectiveForeground(el: Element, background: Rgb): Rgb {
+ const own = parseColor(getComputedStyle(el).color) ?? TRANSPARENT;
+ return own.a >= 1 ? own : blend(own, background);
+}
+
+export function isLargeText(fontSizePx: number, weight: number): boolean {
+ return fontSizePx >= 24 || (fontSizePx >= 18.66 && weight >= 700);
+}
+
+export function requiredRatio(large: boolean, level: 'AA' | 'AAA'): number {
+ if (level === 'AAA') return large ? 4.5 : 7;
+ return large ? 3 : 4.5;
+}
+
+export function round(value: number, places: number): number {
+ const factor = 10 ** places;
+ return Math.round(value * factor) / factor;
+}
+
+function clamp01(value: number): number {
+ return Math.min(1, Math.max(0, value));
+}
+
+function clampByte(value: number): number {
+ return Math.min(255, Math.max(0, Math.round(value)));
+}
+
+export interface FilterChain {
+ invert: boolean;
+ brightness: number;
+ saturate?: number;
+ contrast?: number;
+}
+
+const INVERTED_HUE = [
+ [-0.574, 1.43, 0.144],
+ [0.426, 0.43, 0.144],
+ [0.426, 1.43, -0.856],
+];
+
+export function applyFilters(color: Rgb, chain: FilterChain): Rgb {
+ let channels = [color.r, color.g, color.b];
+ if (chain.invert) channels = matrix(channels.map((value) => 255 - value), INVERTED_HUE);
+ channels = channels.map((value) => value * chain.brightness);
+ if (chain.saturate !== undefined) channels = matrix(channels, saturateMatrix(chain.saturate));
+ if (chain.contrast !== undefined) {
+ channels = channels.map((value) => (value - 127.5) * chain.contrast! + 127.5);
+ }
+ const [r, g, b] = channels.map(clampByte);
+ return { r, g, b, a: color.a };
+}
+
+function matrix(channels: number[], rows: number[][]): number[] {
+ return rows.map((row) => row[0] * channels[0] + row[1] * channels[1] + row[2] * channels[2]);
+}
+
+/**
+ * The brightness multiplier that lands `color` on `target` luminance. Solved by bisection
+ * rather than by inverting a gamma, because the sRGB curve has a linear toe that a plain
+ * power misses by up to 0.025 — enough to overshoot a luminance the caller asked for.
+ */
+export function brightnessFor(color: Rgb, target: number, min = 0.05, max = 4): number {
+ let low = min;
+ let high = max;
+ for (let step = 0; step < 24; step += 1) {
+ const middle = (low + high) / 2;
+ if (relativeLuminance(applyFilters(color, { invert: false, brightness: middle })) < target) {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ return round((low + high) / 2, 3);
+}
+
+function saturateMatrix(amount: number): number[][] {
+ return [
+ [0.213 + 0.787 * amount, 0.715 - 0.715 * amount, 0.072 - 0.072 * amount],
+ [0.213 - 0.213 * amount, 0.715 + 0.285 * amount, 0.072 - 0.072 * amount],
+ [0.213 - 0.213 * amount, 0.715 - 0.715 * amount, 0.072 + 0.928 * amount],
+ ];
+}
diff --git a/lib/actions/page/read-theme.ts b/lib/actions/page/read-theme.ts
new file mode 100644
index 0000000..4d27721
--- /dev/null
+++ b/lib/actions/page/read-theme.ts
@@ -0,0 +1,302 @@
+import { z } from 'zod';
+import { defineAction } from '../core';
+import {
+ contrastRatio,
+ effectiveBackground,
+ effectiveForeground,
+ parseColor,
+ relativeLuminance,
+ round,
+ toHex,
+ type Rgb,
+} from './color';
+import { computedRole, cssPath } from './dom';
+import { asRendered, measureTheme, resolveTokens, scanStyleSheets } from './theme';
+
+const MAX_RULES = 20000;
+const MIN_SURFACE_SHARE = 0.02;
+
+type Shown = (color: Rgb) => Rgb;
+
+interface Sample {
+ el: HTMLElement;
+ style: CSSStyleDeclaration;
+ area: number;
+ ownText: boolean;
+}
+
+interface Swatch {
+ color: string;
+ luminance: number;
+ count: number;
+ area: number;
+}
+
+interface Surface {
+ selector: string;
+ tag: string;
+ role?: string;
+ background: string;
+ text: string;
+ luminance: number;
+ contrast: number;
+ area: number;
+ children: Surface[];
+}
+
+export const readTheme = defineAction({
+ name: 'page.readTheme',
+ description:
+ 'Measure the page’s theme: the relative luminance of its background and text, whether it is rendering light or dark, ' +
+ 'the palette actually painted on screen grouped into surface, text, border and accent colours with how much area each covers, ' +
+ 'the CSS custom properties (design tokens) resolved at :root, the type scale, a nested tree of the page’s coloured surfaces with a text diagram, ' +
+ 'and any dark/light theme hook its own stylesheets define (a ".dark" class or a [data-theme] attribute). ' +
+ 'Read this before page.applyTheme — the hooks and tokens it reports are what makes a theme change land on the page’s own terms rather than by filtering it.',
+ input: z.object({
+ maxScan: z
+ .number()
+ .int()
+ .positive()
+ .max(4000)
+ .default(1200)
+ .describe('Elements to measure; a larger document is sampled at an even stride across it'),
+ maxPerGroup: z
+ .number()
+ .int()
+ .positive()
+ .max(30)
+ .default(8)
+ .describe('Colours listed per palette group, widest coverage first'),
+ maxTokens: z
+ .number()
+ .int()
+ .nonnegative()
+ .max(200)
+ .default(40)
+ .describe('CSS custom properties listed, sorted by name; 0 skips them'),
+ maxSurfaces: z
+ .number()
+ .int()
+ .positive()
+ .max(60)
+ .default(20)
+ .describe('Coloured surfaces kept in the surface tree, largest region first'),
+ }),
+ execute({ maxScan, maxPerGroup, maxTokens, maxSurfaces }) {
+ const root = document.documentElement;
+ const rootStyle = getComputedStyle(root);
+ const { samples, scanned, total } = collect(maxScan);
+ const shown = asRendered();
+ const measured = measureTheme();
+ const sheets = scanStyleSheets(MAX_RULES);
+
+ return {
+ url: location.href,
+ scheme: {
+ declared: rootStyle.colorScheme || 'normal',
+ prefers: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light',
+ resolved: measured.colorScheme,
+ hooks: sheets.hooks,
+ },
+ luminance: {
+ background: measured.luminance,
+ text: round(relativeLuminance(parseColor(measured.text) ?? { r: 0, g: 0, b: 0, a: 1 }), 4),
+ mean: meanLuminance(samples, shown),
+ mode: measured.luminance < 0.5 ? 'dark' : 'light',
+ },
+ colors: {
+ background: measured.background,
+ text: measured.text,
+ contrast: measured.contrast,
+ },
+ palette: palette(samples, maxPerGroup, shown),
+ tokens: maxTokens === 0 ? { total: sheets.properties.length, listed: [] } : resolveTokens(sheets.properties, maxTokens),
+ typography: typography(samples),
+ stylesheets: { ...sheets.sheets, rules: sheets.rules, truncated: sheets.truncated },
+ surfaces: surfaces(samples, maxSurfaces, shown),
+ sampled: { elements: samples.length, scanned, of: total },
+ };
+ },
+});
+
+function collect(maxScan: number): { samples: Sample[]; scanned: number; total: number } {
+ const all = [...document.querySelectorAll<HTMLElement>('body, body *')];
+ const stride = Math.max(1, Math.ceil(all.length / maxScan));
+ const samples: Sample[] = [];
+ let scanned = 0;
+ for (let index = 0; index < all.length; index += stride) {
+ const el = all[index];
+ scanned += 1;
+ const rect = el.getBoundingClientRect();
+ if (rect.width === 0 || rect.height === 0) continue;
+ const style = getComputedStyle(el);
+ if (style.visibility === 'hidden' || style.display === 'none' || style.opacity === '0') continue;
+ samples.push({ el, style, area: Math.round(rect.width * rect.height), ownText: hasOwnText(el) });
+ }
+ return { samples, scanned, total: all.length };
+}
+
+function hasOwnText(el: Element): boolean {
+ return [...el.childNodes].some(
+ (node) => node.nodeType === Node.TEXT_NODE && (node.textContent ?? '').trim() !== '',
+ );
+}
+
+function meanLuminance(samples: Sample[], shown: Shown): number {
+ const painted = samples
+ .map((sample) => ({ area: sample.area, color: rendered(sample.style.backgroundColor, shown) }))
+ .filter((entry): entry is { area: number; color: Rgb } => !!entry.color && entry.color.a > 0.5);
+ const area = painted.reduce((sum, entry) => sum + entry.area, 0);
+ if (area === 0) return 0;
+ return round(
+ painted.reduce((sum, entry) => sum + relativeLuminance(entry.color) * entry.area, 0) / area,
+ 4,
+ );
+}
+
+function rendered(value: string, shown: Shown): Rgb | null {
+ const color = parseColor(value);
+ return color && color.a > 0 ? shown(color) : color;
+}
+
+function palette(samples: Sample[], cap: number, shown: Shown) {
+ const groups = {
+ surface: new Map<string, Swatch>(),
+ text: new Map<string, Swatch>(),
+ border: new Map<string, Swatch>(),
+ accent: new Map<string, Swatch>(),
+ };
+ for (const sample of samples) {
+ add(groups.surface, sample.style.backgroundColor, sample.area, shown);
+ if (sample.ownText) add(groups.text, sample.style.color, sample.area, shown);
+ for (const side of ['Top', 'Right', 'Bottom', 'Left'] as const) {
+ const width = parseFloat(sample.style[`border${side}Width`]);
+ if (width > 0 && sample.style[`border${side}Style`] !== 'none') {
+ add(groups.border, sample.style[`border${side}Color`], sample.area, shown);
+ }
+ }
+ if (sample.el.matches('a[href]')) add(groups.accent, sample.style.color, sample.area, shown);
+ if (sample.el.matches('button,[role="button"],input[type="submit"]')) {
+ add(groups.accent, sample.style.backgroundColor, sample.area, shown);
+ }
+ }
+ return {
+ surface: rank(groups.surface, cap),
+ text: rank(groups.text, cap),
+ border: rank(groups.border, cap),
+ accent: rank(groups.accent, cap),
+ };
+}
+
+function add(group: Map<string, Swatch>, value: string, area: number, shown: Shown) {
+ const color = rendered(value, shown);
+ if (!color || color.a === 0) return;
+ const hex = toHex(color);
+ const swatch = group.get(hex) ?? {
+ color: hex,
+ luminance: round(relativeLuminance(color), 3),
+ count: 0,
+ area: 0,
+ };
+ swatch.count += 1;
+ swatch.area += area;
+ group.set(hex, swatch);
+}
+
+function rank(group: Map<string, Swatch>, cap: number): Swatch[] {
+ return [...group.values()]
+ .sort((one, other) => other.area - one.area || other.count - one.count || (one.color < other.color ? -1 : 1))
+ .slice(0, cap);
+}
+
+function typography(samples: Sample[]) {
+ const body = document.body ?? document.documentElement;
+ const base = getComputedStyle(body);
+ const families = new Map<string, number>();
+ const sizes = new Map<number, number>();
+ for (const sample of samples) {
+ if (!sample.ownText) continue;
+ tally(families, firstFamily(sample.style.fontFamily));
+ tally(sizes, Math.round(parseFloat(sample.style.fontSize)));
+ }
+ return {
+ base: {
+ family: firstFamily(base.fontFamily),
+ sizePx: round(parseFloat(base.fontSize), 1),
+ lineHeight: base.lineHeight,
+ weight: base.fontWeight,
+ },
+ families: byCount(families).map(([family, count]) => ({ family, count })),
+ sizes: byCount(sizes).map(([sizePx, count]) => ({ sizePx, count })),
+ };
+}
+
+function firstFamily(value: string): string {
+ return value.split(',')[0]?.replace(/["']/g, '').trim() || 'unknown';
+}
+
+function tally<T>(counts: Map<T, number>, key: T) {
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+}
+
+function byCount<T extends string | number>(counts: Map<T, number>): [T, number][] {
+ return [...counts.entries()]
+ .sort((one, other) => other[1] - one[1] || (one[0] < other[0] ? -1 : 1))
+ .slice(0, 10);
+}
+
+function surfaces(samples: Sample[], cap: number, shown: Shown) {
+ const minArea = innerWidth * innerHeight * MIN_SURFACE_SHARE;
+ const painted = samples
+ .filter((sample) => sample.area >= minArea && (parseColor(sample.style.backgroundColor)?.a ?? 0) > 0.05)
+ .sort((one, other) => other.area - one.area)
+ .slice(0, cap)
+ .sort((one, other) => (one.el.compareDocumentPosition(other.el) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
+
+ const tree: Surface[] = [];
+ const owners = new Map<HTMLElement, Surface>();
+ for (const sample of painted) {
+ const surface = describeSurface(sample, shown);
+ owners.set(sample.el, surface);
+ let ancestor = sample.el.parentElement;
+ while (ancestor && !owners.has(ancestor)) ancestor = ancestor.parentElement;
+ (ancestor ? owners.get(ancestor)!.children : tree).push(surface);
+ }
+ return { tree, diagram: renderDiagram(tree) };
+}
+
+function describeSurface({ el, area }: Sample, shown: Shown): Surface {
+ const painted = effectiveBackground(el);
+ const background = shown(painted);
+ const text = shown(effectiveForeground(el, painted));
+ return {
+ selector: cssPath(el),
+ tag: el.tagName.toLowerCase(),
+ role: computedRole(el),
+ background: toHex(background),
+ text: toHex(text),
+ luminance: round(relativeLuminance(background), 3),
+ contrast: round(contrastRatio(text, background), 2),
+ area,
+ children: [],
+ };
+}
+
+function renderDiagram(tree: Surface[]): string {
+ const measured = measureTheme();
+ const lines = [
+ `page ${measured.background} · luminance ${measured.luminance} · text ${measured.text} · contrast ${measured.contrast}:1 · ${measured.colorScheme}`,
+ ];
+ const walk = (nodes: Surface[], indent: string) => {
+ nodes.forEach((surface, index) => {
+ const last = index === nodes.length - 1;
+ const name = surface.role ? `${surface.tag}[${surface.role}]` : surface.tag;
+ lines.push(
+ `${indent}${last ? '└' : '├'} ${name} · ${surface.background} · L ${surface.luminance} · text ${surface.text} · ${surface.contrast}:1`,
+ );
+ walk(surface.children, indent + (last ? ' ' : '│ '));
+ });
+ };
+ walk(tree, '');
+ return lines.join('\n');
+}
diff --git a/lib/actions/page/theme.ts b/lib/actions/page/theme.ts
new file mode 100644
index 0000000..e775334
--- /dev/null
+++ b/lib/actions/page/theme.ts
@@ -0,0 +1,239 @@
+import {
+ applyFilters,
+ contrastRatio,
+ effectiveBackground,
+ effectiveForeground,
+ parseColor,
+ relativeLuminance,
+ resolvedScheme,
+ round,
+ toHex,
+ type FilterChain,
+ type Rgb,
+} from './color';
+
+export const THEME_STYLE_ID = 'browsentic-theme';
+
+const ADDED_CLASS = 'data-browsentic-added-class';
+const HOOK_ATTRIBUTE = 'data-browsentic-hook-attribute';
+const HOOK_HOST = 'data-browsentic-hook-host';
+const HOOK_FILTER = 'data-browsentic-filter';
+const PREVIOUS_VALUE = 'data-browsentic-previous-value';
+
+const CLASS_HOOK = /\.((?:theme-|mode-)?(dark|light)(?:-mode|-theme)?)(?![\w-])/i;
+const ATTRIBUTE_HOOK = /\[([\w-]*(?:theme|mode|scheme))\s*[~|^$*]?=\s*["']?(dark|light)["']?\s*[is]?\]/i;
+
+export interface ThemeHook {
+ kind: 'class' | 'attribute';
+ name: string;
+ value?: string;
+ scheme: 'dark' | 'light';
+ host: 'root' | 'body';
+ selector: string;
+}
+
+export interface SheetScan {
+ sheets: { total: number; readable: number; crossOrigin: number; inline: number };
+ rules: number;
+ properties: string[];
+ hooks: ThemeHook[];
+ truncated: boolean;
+}
+
+export function scanStyleSheets(maxRules: number): SheetScan {
+ const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
+ const properties = new Set<string>();
+ const hooks = new Map<string, ThemeHook>();
+ const counts = { total: sheets.length, readable: 0, crossOrigin: 0, inline: 0 };
+ let rules = 0;
+
+ const visit = (rule: CSSRule) => {
+ if (rules >= maxRules) return;
+ rules += 1;
+ if (rule instanceof CSSStyleRule) {
+ for (const name of rule.style) if (name.startsWith('--')) properties.add(name);
+ noteHooks(rule.selectorText, hooks);
+ return;
+ }
+ if (rule instanceof CSSGroupingRule) for (const nested of rule.cssRules) visit(nested);
+ if (rule instanceof CSSImportRule) for (const nested of readable(rule.styleSheet) ?? []) visit(nested);
+ };
+
+ for (const sheet of sheets) {
+ if (!sheet.href) counts.inline += 1;
+ const list = readable(sheet);
+ if (!list) {
+ counts.crossOrigin += 1;
+ continue;
+ }
+ counts.readable += 1;
+ for (const rule of list) visit(rule);
+ }
+
+ return {
+ sheets: counts,
+ rules,
+ properties: [...properties],
+ hooks: [...hooks.values()],
+ truncated: rules >= maxRules,
+ };
+}
+
+function readable(sheet: CSSStyleSheet | null): CSSRuleList | null {
+ try {
+ return sheet?.cssRules ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function noteHooks(selectorText: string, into: Map<string, ThemeHook>) {
+ for (const part of selectorText.split(',')) {
+ const selector = part.trim();
+ const head = selector.split(/[\s>+~]+/)[0];
+ const host = /^body\b/i.test(head) ? 'body' : 'root';
+ const attribute = ATTRIBUTE_HOOK.exec(head);
+ if (attribute) {
+ const [, name, scheme] = attribute;
+ remember(into, {
+ kind: 'attribute',
+ name: name.toLowerCase(),
+ value: scheme.toLowerCase(),
+ scheme: scheme.toLowerCase() as 'dark' | 'light',
+ host,
+ selector,
+ });
+ continue;
+ }
+ const className = CLASS_HOOK.exec(head);
+ if (className) {
+ const [, name, scheme] = className;
+ remember(into, {
+ kind: 'class',
+ name,
+ scheme: scheme.toLowerCase() as 'dark' | 'light',
+ host,
+ selector,
+ });
+ }
+ }
+}
+
+function remember(into: Map<string, ThemeHook>, hook: ThemeHook) {
+ into.set(`${hook.kind}:${hook.host}:${hook.name}:${hook.value ?? ''}`, hook);
+}
+
+export interface Token {
+ name: string;
+ value: string;
+ color?: string;
+ luminance?: number;
+}
+
+export function resolveTokens(names: string[], limit: number): { total: number; listed: Token[] } {
+ const rootStyle = getComputedStyle(document.documentElement);
+ const resolved = names
+ .map((name) => ({ name, value: rootStyle.getPropertyValue(name).trim().slice(0, 120) }))
+ .filter(({ value }) => value !== '')
+ .sort((one, other) => (one.name < other.name ? -1 : 1));
+ return { total: resolved.length, listed: resolved.slice(0, limit).map(describeToken) };
+}
+
+function describeToken({ name, value }: { name: string; value: string }): Token {
+ const color = parseColor(value);
+ if (!color || color.a === 0) return { name, value };
+ return { name, value, color: toHex(color), luminance: round(relativeLuminance(color), 3) };
+}
+
+export function activeFilter(): FilterChain | undefined {
+ const declared = document.getElementById(THEME_STYLE_ID)?.getAttribute(HOOK_FILTER);
+ if (!declared) return undefined;
+ try {
+ return JSON.parse(declared) as FilterChain;
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * A CSS filter repaints the page without touching any computed style, so every colour
+ * read out of the CSSOM is the one underneath it. This maps a read colour to the one
+ * actually on screen, and is the identity when Browsentic has not filtered the page.
+ */
+export function asRendered(): (color: Rgb) => Rgb {
+ const chain = activeFilter();
+ return chain ? (color) => applyFilters(color, chain) : (color) => color;
+}
+
+export function recordFilter(style: HTMLStyleElement, chain: FilterChain) {
+ style.setAttribute(HOOK_FILTER, JSON.stringify(chain));
+}
+
+export interface ThemeMeasurement {
+ colorScheme: 'light' | 'dark';
+ background: string;
+ text: string;
+ luminance: number;
+ contrast: number;
+ filtered?: boolean;
+}
+
+export function measureTheme(): ThemeMeasurement {
+ const surface = document.body ?? document.documentElement;
+ const shown = asRendered();
+ const painted = effectiveBackground(surface);
+ const background = shown(painted);
+ const text = shown(effectiveForeground(surface, painted));
+ return {
+ colorScheme: resolvedScheme(),
+ background: toHex(background),
+ text: toHex(text),
+ luminance: round(relativeLuminance(background), 4),
+ contrast: round(contrastRatio(text, background), 2),
+ ...(activeFilter() ? { filtered: true } : {}),
+ };
+}
+
+function hostElement(host: 'root' | 'body'): HTMLElement {
+ return host === 'body' ? (document.body ?? document.documentElement) : document.documentElement;
+}
+
+export function removeInjectedTheme(): boolean {
+ const style = document.getElementById(THEME_STYLE_ID);
+ if (!style) return false;
+ const host = hostElement(style.getAttribute(HOOK_HOST) === 'body' ? 'body' : 'root');
+ const addedClass = style.getAttribute(ADDED_CLASS);
+ if (addedClass) host.classList.remove(addedClass);
+ const attribute = style.getAttribute(HOOK_ATTRIBUTE);
+ if (attribute) {
+ const previous = style.getAttribute(PREVIOUS_VALUE);
+ if (previous === null) host.removeAttribute(attribute);
+ else host.setAttribute(attribute, previous);
+ }
+ style.remove();
+ return true;
+}
+
+export function injectTheme(css: string, hook?: ThemeHook): HTMLStyleElement {
+ const style = document.createElement('style');
+ style.id = THEME_STYLE_ID;
+ style.textContent = css;
+ if (hook) applyHook(style, hook);
+ document.documentElement.append(style);
+ return style;
+}
+
+function applyHook(style: HTMLStyleElement, hook: ThemeHook) {
+ const host = hostElement(hook.host);
+ style.setAttribute(HOOK_HOST, hook.host);
+ if (hook.kind === 'class') {
+ if (host.classList.contains(hook.name)) return;
+ host.classList.add(hook.name);
+ style.setAttribute(ADDED_CLASS, hook.name);
+ return;
+ }
+ const previous = host.getAttribute(hook.name);
+ style.setAttribute(HOOK_ATTRIBUTE, hook.name);
+ if (previous !== null) style.setAttribute(PREVIOUS_VALUE, previous);
+ host.setAttribute(hook.name, hook.value ?? '');
+}
diff --git a/mcp/skills/page-theming.md b/mcp/skills/page-theming.md
new file mode 100644
index 0000000..9bb4a08
--- /dev/null
+++ b/mcp/skills/page-theming.md
@@ -0,0 +1,56 @@
+---
+name: page-theming
+description: Read what the page is actually painting — luminance, palette, design tokens, contrast — and retheme it on its own terms.
+triggers: [dark mode, light mode, theme, retheme, colour scheme, color scheme, too bright, too dark, hurts my eyes, easier on the eyes, night mode, contrast, hard to read, unreadable, accessibility, wcag, luminance, brightness, colours, colors, palette, design tokens, make it darker, make it lighter, tone it down, warmer, calmer]
+---
+
+You are changing how a page looks, and looks are the one thing you cannot see. Every step here is measured: read the numbers, change the page, read them again.
+
+## 1. Measure first
+
+`page_readTheme` is the snapshot. It reports what is actually painted, not what the stylesheet says:
+
+- `luminance.background` — 0 is black, 1 is white. This is the number the user means by "too bright" or "too dark".
+- `colors` and `palette` — the hexes on screen, grouped into surface, text, border and accent, ordered by how much area each covers. The first surface swatch is the page's real background.
+- `tokens` — the CSS custom properties resolved at `:root`. On a page built from design tokens these are the theme, and overriding them is the clean way in.
+- `scheme.hooks` — dark/light switches the page's **own** stylesheets already define, like a `.dark` class or `[data-theme="dark"]`. A hook means the page has a real theme you can turn on instead of faking one.
+- `surfaces.diagram` — a text tree of the coloured regions with each one's luminance and text contrast, so you can see which panel is the odd one out.
+
+`page_auditContrast` is the readability score: the share of visible text runs that pass WCAG, plus the worst offenders with their ratios and selectors. Take it **before** you change anything — it is only meaningful next to the same number afterwards.
+
+## 2. Turn the user's words into a number
+
+The user says "too bright", not "0.05". Translate, then act on the translation:
+
+| They say | You do |
+| --- | --- |
+| dark mode, night mode, too bright | `mode: "dark"` |
+| back to normal, undo that, revert | `mode: "revert"` |
+| a bit darker / a bit lighter | `targetLuminance` shifted from the measured one, not a guess |
+| washed out, dull, more alive | `saturation` above 1 |
+| too loud, calmer, muted | `saturation` below 1 |
+| I can't read this | fix the contrast: read the audit, then change the colours the failures name |
+
+For "a bit", move `targetLuminance` by roughly a third of the way to the extreme and re-measure. Two small measured steps beat one large blind one.
+
+## 3. Change it on the page's own terms
+
+`page_applyTheme` tries the least invasive thing that works, in this order, and tells you which one it used in `strategy`:
+
+1. **`stylesheet`** — it switched on the hook the page already ships and set `color-scheme`. Nothing is faked; the page renders its own dark theme. This is the good outcome.
+2. **`colors`** — your explicit `background`, `text`, `accent` or `tokens` were applied as overrides.
+3. **`filter`** — the page had no dark theme of its own, so the whole document is repainted through a CSS filter. It works everywhere and it has a real cost: `<html>` becomes a containing block, so `position: fixed` headers and modals re-anchor to it and can move. Images are re-inverted so photos stay right way round. Say so if the page visibly shifts.
+
+When `tokens` came back from `page_readTheme`, prefer them. `{"--background": "#0f172a", "--foreground": "#e2e8f0"}` lets the page's own rules do the work and leaves fixed positioning alone — far better than filtering the whole document.
+
+## 4. Confirm it landed
+
+The result carries `before` and `after`, each with the measured background hex, its luminance and the body text contrast — and `reachedTarget` when you asked for a specific luminance. Check them. A filter changes nothing in the CSSOM, so the other tools would normally read straight through it; Browsentic maps every colour it reports through the active filter, which means `page_readTheme` and `page_auditContrast` keep telling the truth after a theme change. Re-run the audit and compare scores.
+
+If `reachedTarget` is false, the page fought back — usually a surface with a hard-coded background. `surfaces.diagram` names it; override its token or set `background` outright.
+
+## 5. Put it back
+
+`page_applyTheme { mode: "revert" }` removes everything Browsentic applied — the injected stylesheet, the class or attribute it set, the filter — and restores whatever the page had before. `reverted: false` means there was nothing to undo.
+
+Two things to remember. A theme **does not survive a reload or a navigation**; if the user navigates and asks why it went away, that is why — reapply it. And applying a theme twice does not stack: each call replaces the last one, so re-applying with adjusted numbers is the right way to iterate.