Merge pull request #2933 from heygen-com/docs/studio-5419-capture-skill-guards

docs(skills): gate blocked website captures
This commit is contained in:
Miguel Ángel
2026-07-31 22:32:51 +02:00
committed by GitHub
21 changed files with 1797 additions and 190 deletions
@@ -1,5 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { isPrivateUrl, safeFetch, toStandaloneSvg } from "./assetDownloader.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
downloadAndRewriteFonts,
isPrivateUrl,
safeFetch,
toStandaloneSvg,
} from "./assetDownloader.js";
describe("isPrivateUrl — SSRF denylist (security: F-003)", () => {
it("blocks loopback, private, and metadata IPv4", () => {
@@ -127,3 +135,52 @@ describe("toStandaloneSvg — scraped inline SVGs must survive as .svg files", (
expect(toStandaloneSvg("<div>not an svg</div>")).toBe("<div>not an svg</div>");
});
});
describe("downloadAndRewriteFonts — attempt caps", () => {
afterEach(() => vi.unstubAllGlobals());
async function expectFailedFontAttempts(css: string, expectedAttempts: number): Promise<void> {
const dir = mkdtempSync(join(tmpdir(), "hf-font-attempts-"));
const fetchMock = vi.fn(async () => new Response("failed", { status: 503 }));
vi.stubGlobal("fetch", fetchMock);
try {
await downloadAndRewriteFonts(css, dir);
expect(fetchMock).toHaveBeenCalledTimes(expectedAttempts);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
it("counts failed requests toward the global 30-font cap", async () => {
const css = Array.from(
{ length: 35 },
(_, i) =>
`@font-face { font-family: Family${i}; src: url(https://fonts${i}.example/font-${i}.woff2); }`,
).join("\n");
await expectFailedFontAttempts(css, 30);
});
it("counts failed requests toward the six-attempt per-family cap", async () => {
const css = Array.from(
{ length: 10 },
(_, i) =>
`@font-face { font-family: Shared; src: url(https://fonts.example/font-${i}.woff2); }`,
).join("\n");
await expectFailedFontAttempts(css, 6);
});
it("does not start a font request after the capture budget is exhausted", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-font-budget-"));
const css = "@font-face { font-family: Budget; src: url(https://fonts.example/budget.woff2); }";
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
try {
await downloadAndRewriteFonts(css, dir, { remainingMs: () => 0 });
expect(fetchMock).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
+32 -11
View File
@@ -11,6 +11,10 @@ import { createHash } from "node:crypto";
import type { DesignTokens, DownloadedAsset } from "./types.js";
import type { CatalogedAsset } from "./assetCataloger.js";
interface DownloadBudgetOptions {
remainingMs?: () => number;
}
// SVGs: hash-of-bytes filename so it can't drift from content; label-derived names mis-assigned brands.
function svgContentHashSlug(svgSource: string | Buffer, isLogo: boolean): string {
const hash = createHash("sha1").update(svgSource).digest("hex").slice(0, 8);
@@ -43,11 +47,13 @@ export function toStandaloneSvg(outerHTML: string): string {
return outerHTML.replace(original, tag);
}
// fallow-ignore-next-line complexity
export async function downloadAssets(
tokens: DesignTokens,
outputDir: string,
catalogedAssets?: CatalogedAsset[],
faviconLinks?: Array<{ rel: string; href: string }>,
options: DownloadBudgetOptions = {},
): Promise<DownloadedAsset[]> {
const assetsDir = join(outputDir, "assets");
mkdirSync(assetsDir, { recursive: true });
@@ -82,12 +88,14 @@ export async function downloadAssets(
// 2. Favicon
for (const icon of faviconLinks || []) {
const remainingMs = options.remainingMs?.() ?? 10_000;
if (remainingMs <= 0) break;
if (!icon.href) continue;
try {
const ext = extname(new URL(icon.href).pathname) || ".ico";
const name = `favicon${ext}`;
const localPath = `assets/${name}`;
const buffer = await fetchBuffer(icon.href);
const buffer = await fetchBuffer(icon.href, Math.min(10_000, remainingMs));
if (buffer) {
writeFileSync(join(outputDir, localPath), buffer);
assets.push({ url: icon.href, localPath, type: "favicon" });
@@ -149,13 +157,15 @@ export async function downloadAssets(
let imgIdx = 0;
const usedNames = new Set<string>();
for (let i = 0; i < toDownload.length; i += BATCH_SIZE) {
const remainingMs = options.remainingMs?.() ?? 10_000;
if (remainingMs <= 0) break;
const batch = toDownload.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(async ({ url, isPoster, catalog }) => {
const parsedUrl = new URL(url);
const pathExt = extname(parsedUrl.pathname);
const ext = pathExt && pathExt.length <= 5 ? pathExt : ".jpg";
const buffer = await fetchBuffer(url);
const buffer = await fetchBuffer(url, Math.min(10_000, remainingMs));
if (!buffer) return null;
const isSvg = ext === ".svg" || url.includes(".svg");
const minSize = isSvg ? 200 : 10000;
@@ -198,10 +208,12 @@ export async function downloadAssets(
// 4. OG image (if not already downloaded)
if (tokens.ogImage && !downloadedUrls.has(normalizeUrl(tokens.ogImage))) {
const remainingMs = options.remainingMs?.() ?? 10_000;
try {
const ext = extname(new URL(tokens.ogImage).pathname) || ".jpg";
const localPath = `assets/og-image${ext}`;
const buffer = await fetchBuffer(tokens.ogImage);
const buffer =
remainingMs > 0 ? await fetchBuffer(tokens.ogImage, Math.min(10_000, remainingMs)) : null;
if (buffer && buffer.length > 5000) {
writeFileSync(join(outputDir, localPath), buffer);
assets.push({ url: tokens.ogImage, localPath, type: "image" });
@@ -234,7 +246,12 @@ function normalizeUrl(u: string): string {
* Download fonts referenced in CSS and rewrite URLs to local paths.
* Returns the modified CSS string with local font paths.
*/
export async function downloadAndRewriteFonts(css: string, outputDir: string): Promise<string> {
// fallow-ignore-next-line complexity
export async function downloadAndRewriteFonts(
css: string,
outputDir: string,
options: DownloadBudgetOptions = {},
): Promise<string> {
const assetsDir = join(outputDir, "assets", "fonts");
mkdirSync(assetsDir, { recursive: true });
@@ -247,8 +264,10 @@ export async function downloadAndRewriteFonts(css: string, outputDir: string): P
if (fontUrls.size === 0) return css;
// Limit font downloads to avoid bloat. Google Fonts serves 20+ unicode-range
// subsets per weight — we only need a few per family for video production.
// Limit font download attempts to bound worst-case egress and latency. Google Fonts serves
// 20+ unicode-range subsets per weight, so successes alone cannot be the bound: six transient
// failures can intentionally suppress later URLs in that family. Latin-priority sorting below
// makes the limited attempts useful while keeping this failure tradeoff explicit.
const MAX_FONTS_PER_FAMILY = 6;
const MAX_TOTAL_FONTS = 30;
const familyCounts = new Map<string, number>();
@@ -275,10 +294,14 @@ export async function downloadAndRewriteFonts(css: string, outputDir: string): P
let count = 0;
for (const fontUrl of sortedUrls) {
const remainingMs = options.remainingMs?.() ?? 10_000;
if (remainingMs <= 0) break;
if (count >= MAX_TOTAL_FONTS) break;
const family = getFamilyForUrl(fontUrl);
const familyCount = familyCounts.get(family) || 0;
if (familyCount >= MAX_FONTS_PER_FAMILY) continue;
familyCounts.set(family, familyCount + 1);
count++;
try {
const urlObj = new URL(fontUrl);
@@ -286,12 +309,10 @@ export async function downloadAndRewriteFonts(css: string, outputDir: string): P
const localPath = join(assetsDir, filename);
const relativePath = `assets/fonts/${filename}`;
const buffer = await fetchBuffer(fontUrl);
const buffer = await fetchBuffer(fontUrl, Math.min(10_000, remainingMs));
if (buffer) {
writeFileSync(localPath, buffer);
rewritten = rewritten.split(fontUrl).join(relativePath);
familyCounts.set(family, familyCount + 1);
count++;
}
} catch {
/* skip */
@@ -391,10 +412,10 @@ export async function safeFetch(url: string, init?: RequestInit): Promise<Respon
return null; // too many redirects
}
async function fetchBuffer(url: string): Promise<Buffer | null> {
async function fetchBuffer(url: string, timeoutMs = 10_000): Promise<Buffer | null> {
try {
const res = await safeFetch(url, {
signal: AbortSignal.timeout(10000),
signal: AbortSignal.timeout(timeoutMs),
headers: { "User-Agent": "HyperFrames/1.0" },
});
if (!res || !res.ok) return null;
+67 -2
View File
@@ -1,9 +1,13 @@
import { mkdtempSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import sharp from "sharp";
import { describe, expect, it } from "vitest";
import { createContactSheet } from "./contactSheet.js";
import {
createContactSheet,
createScrollContactSheet,
createSvgContactSheet,
} from "./contactSheet.js";
function tempDir(): string {
return mkdtempSync(join(tmpdir(), "hf-contact-sheet-test-"));
@@ -58,3 +62,64 @@ describe("createContactSheet", () => {
}
}, 60_000);
});
describe("contact-sheet capture budget", () => {
it("does not start another Sharp page after the budget is exhausted", async () => {
const dir = tempDir();
try {
for (let i = 0; i < 10; i++) {
await sharp({
create: {
width: 4,
height: 4,
channels: 3,
background: { r: i, g: i, b: i },
},
})
.png()
.toFile(join(dir, `scroll-${String(i).padStart(3, "0")}.png`));
}
let checks = 0;
const output = join(dir, "contact-sheet.jpg");
const sheets = await createScrollContactSheet(dir, output, {
remainingMs: () => (checks++ === 0 ? 1000 : 0),
});
expect(sheets).toEqual([join(dir, "contact-sheet-1.jpg")]);
expect(existsSync(join(dir, "contact-sheet-2.jpg"))).toBe(false);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}, 60_000);
it("stops SVG thumbnail rasterization before the next native operation", async () => {
const dir = tempDir();
try {
const svgs = join(dir, "svgs");
const { mkdirSync } = await import("node:fs");
mkdirSync(svgs);
writeFileSync(
join(svgs, "a.svg"),
'<svg xmlns="http://www.w3.org/2000/svg"><rect width="4" height="4"/></svg>',
);
writeFileSync(
join(svgs, "b.svg"),
'<svg xmlns="http://www.w3.org/2000/svg"><circle cx="2" cy="2" r="2"/></svg>',
);
let checks = 0;
const sheets = await createSvgContactSheet(
svgs,
join(dir, "svg-contact-sheet.jpg"),
undefined,
{ remainingMs: () => (checks++ === 0 ? 1000 : 0) },
);
expect(sheets).toEqual([]);
expect(checks).toBeGreaterThanOrEqual(2);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}, 60_000);
});
+16 -3
View File
@@ -18,6 +18,8 @@ interface ContactSheetOptions {
quality?: number;
/** Target width per cell in pixels (default: 600) */
cellWidth?: number;
/** Cooperative boundary checked before starting each native Sharp page. */
remainingMs?: () => number;
}
/**
@@ -39,6 +41,8 @@ export async function createContactSheet(
cellWidth = 600,
} = opts;
if ((opts.remainingMs?.() ?? 1) <= 0) return null;
const files = imagePaths.slice(0, maxImages);
if (files.length === 0) return null;
@@ -125,6 +129,7 @@ function escapeXml(s: string): string {
* Output files: basePath → base-1.jpg, base-2.jpg, ...
* Returns the list of written file paths (empty if no images).
*/
// fallow-ignore-next-line complexity
async function createContactSheetPages(
imagePaths: string[],
outputBasePath: string,
@@ -133,7 +138,7 @@ async function createContactSheetPages(
customLabels?: string[],
): Promise<string[]> {
if (imagePaths.length === 0) return [];
const { pageSize = imagePaths.length, ...sheetOpts } = opts;
const { pageSize = imagePaths.length, remainingMs, ...sheetOpts } = opts;
const ext = outputBasePath.match(/\.[^.]+$/)?.[0] ?? ".jpg";
const base = outputBasePath.slice(0, -ext.length);
@@ -141,6 +146,7 @@ async function createContactSheetPages(
const results: string[] = [];
for (let p = 0; p < pages; p++) {
if ((remainingMs?.() ?? 1) <= 0) break;
const chunk = imagePaths.slice(p * pageSize, (p + 1) * pageSize);
const chunkLabels = customLabels?.slice(p * pageSize, (p + 1) * pageSize);
const outPath = pages === 1 ? outputBasePath : `${base}-${p + 1}${ext}`;
@@ -170,6 +176,7 @@ async function createContactSheetPages(
export async function createScrollContactSheet(
screenshotsDir: string,
outputPath: string,
budget: Pick<ContactSheetOptions, "remainingMs"> = {},
): Promise<string[]> {
if (!existsSync(screenshotsDir)) return [];
@@ -189,7 +196,7 @@ export async function createScrollContactSheet(
return createContactSheetPages(
paths,
outputPath,
{ cols: 3, cellWidth: 600, pageSize: 9 },
{ cols: 3, cellWidth: 600, pageSize: 9, ...budget },
0,
labels,
);
@@ -203,6 +210,7 @@ export async function createScrollContactSheet(
export async function createSnapshotContactSheet(
snapshotsDir: string,
outputPath: string,
budget: Pick<ContactSheetOptions, "remainingMs"> = {},
): Promise<string[]> {
if (!existsSync(snapshotsDir)) return [];
@@ -222,7 +230,7 @@ export async function createSnapshotContactSheet(
return createContactSheetPages(
paths,
outputPath,
{ cols: 3, cellWidth: 600, pageSize: 9 },
{ cols: 3, cellWidth: 600, pageSize: 9, ...budget },
0,
labels,
);
@@ -236,6 +244,7 @@ export async function createSnapshotContactSheet(
export async function createAssetContactSheet(
assetsDir: string,
outputPath: string,
budget: Pick<ContactSheetOptions, "remainingMs"> = {},
): Promise<string[]> {
if (!existsSync(assetsDir)) return [];
@@ -254,6 +263,7 @@ export async function createAssetContactSheet(
cellWidth: 480,
labelMode: "filename",
pageSize: 12,
...budget,
});
}
@@ -271,6 +281,7 @@ export async function createSvgContactSheet(
svgsDir: string,
outputPath: string,
assetsRootDir?: string,
budget: Pick<ContactSheetOptions, "remainingMs"> = {},
): Promise<string[]> {
const dirsToScan = [svgsDir, assetsRootDir].filter(
(d): d is string => d !== undefined && existsSync(d),
@@ -302,6 +313,7 @@ export async function createSvgContactSheet(
const labels: string[] = [];
for (let i = 0; i < svgPaths.length; i++) {
if ((budget.remainingMs?.() ?? 1) <= 0) break;
const svgPath = svgPaths[i]!;
const tmpPath = join(tmpDir, `.thumb-${i}.png`);
try {
@@ -334,6 +346,7 @@ export async function createSvgContactSheet(
cols: 5,
cellWidth: thumbSize,
pageSize: 15,
...budget,
},
0,
labels,
+325 -11
View File
@@ -2,19 +2,35 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { captionImagesWithGemini } from "./contentExtractor.js";
import {
captionImagesWithGemini,
resolveVisionPhaseCompletion,
type VisionCaptionOutcome,
} from "./contentExtractor.js";
const { generateContentMock } = vi.hoisted(() => ({
generateContentMock: vi.fn(),
}));
vi.mock("@google/genai", () => ({
GoogleGenAI: class {
models = { generateContent: generateContentMock };
},
}));
// These tests exercise the OpenRouter provider path only — it makes a plain
// `fetch` call we can stub, with no native (`sharp`) or `@google/genai`
// dependency. OpenRouter wins over Gemini when OPENROUTER_API_KEY is set, so we
// don't need to clear the Gemini keys for the OpenRouter cases.
function makeProjectWithImage(): string {
function makeProjectWithImages(files = ["hero.png"]): string {
const dir = mkdtempSync(join(tmpdir(), "hf-caption-"));
mkdirSync(join(dir, "assets"), { recursive: true });
// Contents are irrelevant to the OpenRouter path (it just base64-encodes the
// bytes); only the .png extension matters for the image filter.
writeFileSync(join(dir, "assets", "hero.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
for (const file of files) {
writeFileSync(join(dir, "assets", file), Buffer.from([0x89, 0x50, 0x4e, 0x47]));
}
return dir;
}
@@ -28,7 +44,7 @@ describe("captionImagesWithGemini — OpenRouter provider", () => {
});
it("captions via OpenRouter when OPENROUTER_API_KEY is set", async () => {
const dir = makeProjectWithImage();
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-test-key");
vi.stubEnv("HYPERFRAMES_OPENROUTER_MODEL", "google/gemini-3.1-flash-lite");
@@ -63,28 +79,267 @@ describe("captionImagesWithGemini — OpenRouter provider", () => {
});
it("degrades gracefully (no throw, no captions) when OpenRouter returns a non-OK status", async () => {
const dir = makeProjectWithImage();
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-bad-key");
vi.stubGlobal(
"fetch",
vi.fn(
async () => new Response("invalid api key", { status: 401, statusText: "Unauthorized" }),
async () =>
new Response("provider detail containing or-bad-key", {
status: 401,
statusText: "Unauthorized",
}),
),
);
const warnings: string[] = [];
// captionOne throws on !res.ok, but the throw is per-image inside
// Promise.allSettled, so it's filtered out as a rejected result rather than
// bubbling up — same silent degradation as the existing Gemini path.
const captions = await captionImagesWithGemini(dir, () => {}, warnings);
let outcome: VisionCaptionOutcome | undefined;
const captions = await captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
});
expect(captions).toEqual({});
expect(warnings).toEqual(["OpenRouter vision failed for 1 asset(s); captions omitted."]);
expect(warnings.join(" ")).not.toContain("or-bad-key");
expect(outcome).toEqual({
timedOutRequests: 0,
failedRequests: 1,
budgetExhausted: false,
});
if (!outcome) throw new Error("Expected vision caption outcome");
expect(resolveVisionPhaseCompletion(outcome, 10_000)).toEqual({
status: "degraded",
reason: "provider-error",
});
});
it("terminates captioning when the vision provider never responds", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-hanging-key");
vi.stubEnv("HYPERFRAMES_VISION_TIMEOUT_MS", "20");
vi.stubGlobal(
"fetch",
vi.fn((_url: string, init?: RequestInit) => {
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
once: true,
});
});
}),
);
const warnings: string[] = [];
const result = await Promise.race([
captionImagesWithGemini(dir, () => {}, warnings),
new Promise<"hung">((resolve) => setTimeout(() => resolve("hung"), 250)),
]);
expect(result).toEqual({});
});
it.each([
{ label: "success JSON", status: 200, partialBody: '{"choices":[' },
{ label: "failure text", status: 500, partialBody: "upstream failed: " },
])(
"terminates captioning when OpenRouter $label body never ends",
async ({ status, partialBody }) => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-stalled-body-key");
vi.stubEnv("HYPERFRAMES_VISION_TIMEOUT_MS", "20");
vi.stubGlobal(
"fetch",
vi.fn(async () => {
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode(partialBody));
},
});
return new Response(body, {
status,
headers: { "content-type": "application/json" },
});
}),
);
const warnings: string[] = [];
let outcome: VisionCaptionOutcome | undefined;
const result = await Promise.race([
captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
}),
new Promise<"hung">((resolve) => setTimeout(() => resolve("hung"), 250)),
]);
expect(result).toEqual({});
expect(warnings).toEqual(["OpenRouter vision timed out for 1 asset(s); captions omitted."]);
expect(outcome).toEqual({
timedOutRequests: 1,
failedRequests: 0,
budgetExhausted: false,
});
},
);
it("keeps successful captions while reporting a failed sibling request", async () => {
const dir = makeProjectWithImages(["failed.png", "success.png"]);
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-mixed-failure-key");
let requestCount = 0;
vi.stubGlobal(
"fetch",
vi.fn(async () => {
requestCount++;
if (requestCount === 1) {
return new Response("upstream exploded with or-mixed-failure-key", {
status: 500,
statusText: "Internal Server Error",
});
}
return new Response(
JSON.stringify({ choices: [{ message: { content: "Successful image." } }] }),
{ status: 200, headers: { "content-type": "application/json" } },
);
}),
);
const warnings: string[] = [];
let outcome: VisionCaptionOutcome | undefined;
const captions = await captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
});
expect(captions).toEqual({ "success.png": "Successful image." });
expect(warnings).toEqual(["OpenRouter vision failed for 1 asset(s); captions omitted."]);
expect(warnings.join(" ")).not.toContain("or-mixed-failure-key");
expect(outcome).toEqual({
timedOutRequests: 0,
failedRequests: 1,
budgetExhausted: false,
});
});
it("keeps a successful sibling caption when another request times out", async () => {
const dir = makeProjectWithImages(["hang.png", "success.png"]);
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-mixed-key");
vi.stubEnv("HYPERFRAMES_VISION_TIMEOUT_MS", "20");
vi.stubGlobal(
"fetch",
vi.fn((_url: string, init?: RequestInit) => {
const body = JSON.parse(typeof init?.body === "string" ? init.body : "{}");
const imageUrl = body.messages?.[0]?.content?.[1]?.image_url?.url;
if (typeof imageUrl === "string" && imageUrl.includes("iVBORw==")) {
// Both fixtures contain the same bytes, so use call order: the first
// request hangs while the second succeeds independently.
const fetchMock = vi.mocked(fetch);
if (fetchMock.mock.calls.length === 1) return new Promise<Response>(() => {});
}
return Promise.resolve(
new Response(
JSON.stringify({ choices: [{ message: { content: "Successful image." } }] }),
{
status: 200,
headers: { "content-type": "application/json" },
},
),
);
}),
);
const warnings: string[] = [];
let outcome: VisionCaptionOutcome | undefined;
const captions = await captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
});
expect(captions).toEqual({ "success.png": "Successful image." });
expect(outcome).toEqual({
timedOutRequests: 1,
failedRequests: 0,
budgetExhausted: false,
});
if (!outcome) throw new Error("Expected vision caption outcome");
expect(resolveVisionPhaseCompletion(outcome, 10_000)).toEqual({
status: "degraded",
reason: "request-timeout",
});
});
it("does not call a configured provider when vision is skipped", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-unused-key");
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const captions = await captionImagesWithGemini(dir, () => {}, [], { skipVision: true });
expect(captions).toEqual({});
expect(fetchMock).not.toHaveBeenCalled();
});
it("does not start a vision batch after the capture budget is exhausted", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-budget-key");
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const captions = await captionImagesWithGemini(dir, () => {}, [], {
remainingMs: () => 0,
});
expect(captions).toEqual({});
expect(fetchMock).not.toHaveBeenCalled();
});
it("classifies non-provider pipeline failures without leaking the local path", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-caption-no-assets-"));
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "or-unused-key");
const warnings: string[] = [];
let outcome: VisionCaptionOutcome | undefined;
const captions = await captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
});
expect(captions).toEqual({});
expect(warnings).toEqual(["OpenRouter captioning failed internally; captions omitted."]);
expect(warnings.join(" ")).not.toContain(dir);
expect(outcome).toEqual({
timedOutRequests: 0,
failedRequests: 0,
budgetExhausted: false,
internalError: true,
});
if (!outcome) throw new Error("Expected vision caption outcome");
expect(resolveVisionPhaseCompletion(outcome, 10_000)).toEqual({
status: "degraded",
reason: "internal-error",
});
});
it("skips captioning entirely when no provider key is present", async () => {
const dir = makeProjectWithImage();
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "");
vi.stubEnv("GEMINI_API_KEY", "");
@@ -100,3 +355,62 @@ describe("captionImagesWithGemini — OpenRouter provider", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("captionImagesWithGemini — Gemini provider", () => {
const dirs: string[] = [];
afterEach(() => {
generateContentMock.mockReset();
vi.unstubAllEnvs();
for (const d of dirs) rmSync(d, { recursive: true, force: true });
dirs.length = 0;
});
it("terminates captioning when Gemini never settles even if the SDK ignores abort", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "");
vi.stubEnv("GEMINI_API_KEY", "gemini-hanging-key");
vi.stubEnv("HYPERFRAMES_VISION_TIMEOUT_MS", "20");
generateContentMock.mockImplementation(() => new Promise(() => {}));
const result = await Promise.race([
captionImagesWithGemini(dir, () => {}, []),
new Promise<"hung">((resolve) => setTimeout(() => resolve("hung"), 250)),
]);
expect(result).toEqual({});
});
it("reports a rejected Gemini request without leaking its error detail", async () => {
const dir = makeProjectWithImages();
dirs.push(dir);
vi.stubEnv("OPENROUTER_API_KEY", "");
vi.stubEnv("GEMINI_API_KEY", "gemini-secret-key");
generateContentMock.mockRejectedValue(
new Error("provider echoed gemini-secret-key in its response"),
);
const warnings: string[] = [];
let outcome: VisionCaptionOutcome | undefined;
const captions = await captionImagesWithGemini(dir, () => {}, warnings, {
onOutcome: (value) => {
outcome = value;
},
});
expect(captions).toEqual({});
expect(warnings).toEqual(["Gemini vision failed for 1 asset(s); captions omitted."]);
expect(warnings.join(" ")).not.toContain("gemini-secret-key");
expect(outcome).toEqual({
timedOutRequests: 0,
failedRequests: 1,
budgetExhausted: false,
});
if (!outcome) throw new Error("Expected vision caption outcome");
expect(resolveVisionPhaseCompletion(outcome, 10_000)).toEqual({
status: "degraded",
reason: "provider-error",
});
});
});
+209 -52
View File
@@ -15,6 +15,80 @@ import type sharpType from "sharp";
import type { CatalogedAsset } from "./assetCataloger.js";
import type { DesignTokens } from "./types.js";
const DEFAULT_VISION_REQUEST_TIMEOUT_MS = 30_000;
export interface VisionCaptionOutcome {
timedOutRequests: number;
failedRequests: number;
budgetExhausted: boolean;
/** Failure outside provider request handling (filesystem, module, or programming error). */
internalError?: boolean;
}
interface VisionCaptionOptions {
skipVision?: boolean;
remainingMs?: () => number;
onOutcome?: (outcome: VisionCaptionOutcome) => void;
}
export function resolveVisionPhaseCompletion(
outcome: VisionCaptionOutcome,
remainingMs: number,
):
| { status: "completed" }
| {
status: "degraded";
reason: "budget-exhausted" | "request-timeout" | "provider-error" | "internal-error";
} {
if (outcome.budgetExhausted || remainingMs <= 0) {
return { status: "degraded", reason: "budget-exhausted" };
}
if (outcome.internalError) {
return { status: "degraded", reason: "internal-error" };
}
if (outcome.timedOutRequests > 0) {
return { status: "degraded", reason: "request-timeout" };
}
if (outcome.failedRequests > 0) {
return { status: "degraded", reason: "provider-error" };
}
return { status: "completed" };
}
class VisionRequestTimeoutError extends Error {
constructor(timeoutMs: number) {
super(`Vision request timed out after ${timeoutMs}ms`);
this.name = "VisionRequestTimeoutError";
}
}
function resolveVisionRequestTimeoutMs(): number {
const configured = Number(process.env.HYPERFRAMES_VISION_TIMEOUT_MS);
return Number.isFinite(configured) && configured > 0
? configured
: DEFAULT_VISION_REQUEST_TIMEOUT_MS;
}
async function runBoundedVisionRequest<T>(
request: (signal: AbortSignal) => Promise<T>,
timeoutMs: number,
): Promise<T> {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => {
reject(new VisionRequestTimeoutError(timeoutMs));
controller.abort();
}, timeoutMs);
});
try {
return await Promise.race([request(controller.signal), timeout]);
} finally {
if (timer) clearTimeout(timer);
}
}
/**
* Detect JS libraries via window globals, DOM fingerprints, script URLs,
* and WebGL shader analysis.
@@ -165,15 +239,37 @@ export async function extractVisibleText(page: Page): Promise<string> {
* Batches requests to stay under free-tier rate limits.
* Returns a map of filename -> caption string.
*/
// fallow-ignore-next-line complexity
export async function captionImagesWithGemini(
outputDir: string,
progress: (stage: string, detail?: string) => void,
warnings: string[],
options: VisionCaptionOptions = {},
): Promise<Record<string, string>> {
const geminiCaptions: Record<string, string> = {};
let timedOutCount = 0;
let failedRequestCount = 0;
let budgetExhausted = false;
let internalError = false;
const reportOutcome = (): void => {
const outcome: VisionCaptionOutcome = {
timedOutRequests: timedOutCount,
failedRequests: failedRequestCount,
budgetExhausted,
};
if (internalError) outcome.internalError = true;
options.onOutcome?.(outcome);
};
if (options.skipVision) {
reportOutcome();
return geminiCaptions;
}
const openRouterKey = process.env.OPENROUTER_API_KEY;
const geminiKey = process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;
if (!openRouterKey && !geminiKey) return geminiCaptions;
if (!openRouterKey && !geminiKey) {
reportOutcome();
return geminiCaptions;
}
// OpenRouter takes priority when both keys are set — it's the explicit opt-in
// for users without Google access. Both providers satisfy the same
@@ -186,6 +282,7 @@ export async function captionImagesWithGemini(
const model = useOpenRouter
? process.env.HYPERFRAMES_OPENROUTER_MODEL || "google/gemini-3.1-flash-lite"
: process.env.HYPERFRAMES_GEMINI_MODEL || "gemini-3.1-flash-lite-preview";
const requestTimeoutMs = resolveVisionRequestTimeoutMs();
progress("design", `Captioning images with ${providerName} vision...`);
try {
@@ -196,53 +293,71 @@ export async function captionImagesWithGemini(
base64: string;
prompt: string;
maxTokens: number;
timeoutMs: number;
}) => Promise<string>;
let captionOne: CaptionOne;
if (openRouterKey) {
captionOne = async ({ mimeType, base64, prompt, maxTokens }) => {
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${openRouterKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64}` } },
],
},
],
max_tokens: maxTokens,
}),
});
if (!res.ok) {
const detail = await res.text().catch(() => "");
throw new Error(`OpenRouter ${res.status} ${res.statusText}: ${detail.slice(0, 200)}`);
}
const data = (await res.json()) as {
choices?: Array<{ message?: { content?: string } }>;
};
return data.choices?.[0]?.message?.content?.trim() || "";
captionOne = async ({ mimeType, base64, prompt, maxTokens, timeoutMs }) => {
return runBoundedVisionRequest(async (signal) => {
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${openRouterKey}`,
"Content-Type": "application/json",
},
signal,
body: JSON.stringify({
model,
messages: [
{
role: "user",
content: [
{ type: "text", text: prompt },
{
type: "image_url",
image_url: { url: `data:${mimeType};base64,${base64}` },
},
],
},
],
max_tokens: maxTokens,
}),
});
if (!res.ok) {
await res.text();
throw new Error(`OpenRouter request failed with HTTP ${res.status}`);
}
const data = (await res.json()) as {
choices?: Array<{ message?: { content?: string } }>;
};
return data.choices?.[0]?.message?.content?.trim() || "";
}, timeoutMs);
};
} else {
// Unreachable when geminiKey is unset (guarded above); re-narrow for TS.
if (!geminiKey) return geminiCaptions;
const { GoogleGenAI } = await import("@google/genai");
const ai = new GoogleGenAI({ apiKey: geminiKey });
captionOne = async ({ mimeType, base64, prompt, maxTokens }) => {
const response = await ai.models.generateContent({
model,
contents: [
{ role: "user", parts: [{ inlineData: { mimeType, data: base64 } }, { text: prompt }] },
],
config: { maxOutputTokens: maxTokens },
});
captionOne = async ({ mimeType, base64, prompt, maxTokens, timeoutMs }) => {
const response = await runBoundedVisionRequest(
(signal) =>
ai.models.generateContent({
model,
contents: [
{
role: "user",
parts: [{ inlineData: { mimeType, data: base64 } }, { text: prompt }],
},
],
config: {
maxOutputTokens: maxTokens,
abortSignal: signal,
httpOptions: { timeout: timeoutMs },
},
}),
timeoutMs,
);
return response.text?.trim() || "";
};
}
@@ -253,10 +368,35 @@ export async function captionImagesWithGemini(
// Caption in parallel batches. Gemini free tier is ~5 RPM (slow but $0),
// paid/OpenRouter ~2000 RPM. We batch 20 with a 2s inter-batch pause and rely
// on Promise.allSettled so a rate-limited image degrades to "" rather than
// failing the batch.
// on Promise.allSettled so one rate-limited image does not fail its siblings;
// rejected requests are aggregated into a sanitized warning below.
const BATCH_SIZE = 20;
const collectCaptionResults = (
results: PromiseSettledResult<{ file: string; caption: string }>[],
): { timeouts: number; failures: number } => {
let timeouts = 0;
let failures = 0;
for (const result of results) {
if (result.status === "fulfilled" && result.value.caption) {
geminiCaptions[result.value.file] = result.value.caption;
} else if (
result.status === "rejected" &&
result.reason instanceof VisionRequestTimeoutError
) {
timeouts++;
} else if (result.status === "rejected") {
failures++;
}
}
return { timeouts, failures };
};
for (let i = 0; i < imageFiles.length; i += BATCH_SIZE) {
const remainingMs = options.remainingMs?.() ?? Number.POSITIVE_INFINITY;
if (remainingMs <= 0) {
budgetExhausted = true;
break;
}
const timeoutMs = Math.max(1, Math.min(requestTimeoutMs, remainingMs));
const batch = imageFiles.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(async (file: string) => {
@@ -273,15 +413,14 @@ export async function captionImagesWithGemini(
prompt:
"Describe this website image in ONE short sentence for a video storyboard. Focus on: what it shows, dominant colors, whether background is light or dark. Be factual, not creative.",
maxTokens: 500,
timeoutMs,
});
return { file, caption };
}),
);
for (const result of results) {
if (result.status === "fulfilled" && result.value.caption) {
geminiCaptions[result.value.file] = result.value.caption;
}
}
const counts = collectCaptionResults(results);
timedOutCount += counts.timeouts;
failedRequestCount += counts.failures;
// Pace requests between batches (paid tier: 2000+ RPM, free tier: rate-limited)
if (i + BATCH_SIZE < imageFiles.length) {
await new Promise((r) => setTimeout(r, 2000)); // 2s pause between batches — paid tier handles 2000 RPM, free tier retries via Promise.allSettled
@@ -322,6 +461,7 @@ export async function captionImagesWithGemini(
`Skipped ${svgFiles.length} SVG caption(s): sharp could not load (${(err as Error).message}). ` +
`Reinstall with optional dependencies enabled (e.g. \`npm i sharp\`) to caption SVG assets.`,
);
reportOutcome();
return geminiCaptions;
}
progress("design", `Rasterizing + captioning ${svgFiles.length} SVGs via vision API...`);
@@ -329,6 +469,12 @@ export async function captionImagesWithGemini(
const SVG_RENDER_SIZE = 256; // px — enough resolution for Gemini to read wordmarks, small enough to keep payload sub-MB
let svgsSkipped = 0;
for (let i = 0; i < svgFiles.length; i += SVG_BATCH) {
const remainingMs = options.remainingMs?.() ?? Number.POSITIVE_INFINITY;
if (remainingMs <= 0) {
budgetExhausted = true;
break;
}
const timeoutMs = Math.max(1, Math.min(requestTimeoutMs, remainingMs));
const batch = svgFiles.slice(i, i + SVG_BATCH);
const results = await Promise.allSettled(
batch.map(async ({ relPath }) => {
@@ -373,15 +519,14 @@ export async function captionImagesWithGemini(
"If you see a wordmark, READ THE LETTERS LITERALLY — do not guess a brand from context. " +
"Be factual.",
maxTokens: 300,
timeoutMs,
});
return { file: relPath, caption };
}),
);
for (const result of results) {
if (result.status === "fulfilled" && result.value.caption) {
geminiCaptions[result.value.file] = result.value.caption;
}
}
const counts = collectCaptionResults(results);
timedOutCount += counts.timeouts;
failedRequestCount += counts.failures;
if (i + SVG_BATCH < svgFiles.length) {
await new Promise((r) => setTimeout(r, 2000));
}
@@ -398,10 +543,22 @@ export async function captionImagesWithGemini(
);
}
}
} catch (err) {
warnings.push(`${providerName} captioning failed: ${err}`);
if (timedOutCount > 0) {
warnings.push(
`${providerName} vision timed out for ${timedOutCount} asset(s); captions omitted.`,
);
}
if (failedRequestCount > 0) {
warnings.push(
`${providerName} vision failed for ${failedRequestCount} asset(s); captions omitted.`,
);
}
} catch {
internalError = true;
warnings.push(`${providerName} captioning failed internally; captions omitted.`);
}
reportOutcome();
return geminiCaptions;
}
+232 -72
View File
@@ -37,12 +37,17 @@ import {
extractVisibleText,
captionImagesWithGemini,
generateAssetDescriptions,
resolveVisionPhaseCompletion,
} from "./contentExtractor.js";
import type { VisionCaptionOutcome } from "./contentExtractor.js";
import { loadEnvFile, generateProjectScaffold } from "./scaffolding.js";
import type { CaptureOptions, CaptureResult } from "./types.js";
import { detectBlockedPage } from "./pageBlockDetection.js";
import type { CaptureOptions, CapturePhase, CapturePhaseProgress, CaptureResult } from "./types.js";
export type { CaptureOptions, CaptureResult } from "./types.js";
const DEFAULT_POST_NAVIGATION_BUDGET_MS = 120_000;
// fallow-ignore-next-line complexity
export async function captureWebsite(
opts: CaptureOptions,
@@ -57,12 +62,49 @@ export async function captureWebsite(
settleTime = 3000,
maxScreenshots: _maxScreenshots = 24,
skipAssets = false,
skipVision = false,
postNavigationBudgetMs = DEFAULT_POST_NAVIGATION_BUDGET_MS,
onPhase,
} = opts;
const warnings: string[] = [];
const progress = (stage: string, detail?: string) => {
onProgress?.(stage, detail);
};
const budgetMs =
Number.isFinite(postNavigationBudgetMs) && postNavigationBudgetMs > 0
? postNavigationBudgetMs
: DEFAULT_POST_NAVIGATION_BUDGET_MS;
let postNavigationDeadline: number | undefined;
const remainingMs = (): number =>
postNavigationDeadline === undefined
? budgetMs
: Math.max(0, postNavigationDeadline - Date.now());
let lastPhase: CapturePhaseProgress = {
schema: "hyperframes.capture.phase.v1",
phase: "browser",
status: "started",
remainingMs: null,
};
const phase = (
name: CapturePhase,
status: CapturePhaseProgress["status"],
reason?: CapturePhaseProgress["reason"],
): void => {
const remaining = postNavigationDeadline === undefined ? null : remainingMs();
lastPhase = reason
? {
schema: "hyperframes.capture.phase.v1",
phase: name,
status,
remainingMs: remaining,
reason,
}
: { schema: "hyperframes.capture.phase.v1", phase: name, status, remainingMs: remaining };
onPhase?.(lastPhase);
};
phase("browser", "started");
// Load .env file from repo root if it exists (for GEMINI_API_KEY, etc.)
loadEnvFile(outputDir);
@@ -102,6 +144,8 @@ export async function captureWebsite(
// Goal: Catalog animations + take screenshots (with JS rendering)
// ═══════════════════════════════════════════════════════════════
phase("browser", "completed");
phase("navigation", "started");
progress("animations", "Cataloging animations (full JS)...");
const page1 = await chromeBrowser.newPage();
@@ -197,12 +241,13 @@ export async function captureWebsite(
// Use networkidle2 (allows 2 ongoing connections) instead of networkidle0 —
// modern SPAs often have persistent WebSocket/analytics connections that
// prevent networkidle0 from ever resolving.
await page1.goto(url, { waitUntil: "networkidle2", timeout });
const navigationResponse = await page1.goto(url, { waitUntil: "networkidle2", timeout });
postNavigationDeadline = Date.now() + budgetMs;
await new Promise((r) => setTimeout(r, settleTime));
// Check if the page loaded real content or an anti-bot challenge
// Use structural detection (DOM elements + cookies), not text regex matching —
// text matching causes false positives on sites that mention "blocked" or "verify" in copy
// Combine structural evidence with the main response status/title. Low text
// alone stays non-fatal so image-led sites are not rejected.
const pageContentCheck = (await page1.evaluate(`(() => {
var text = (document.body.innerText || "").trim();
var title = document.title || "";
@@ -210,19 +255,31 @@ export async function captureWebsite(
var hasCfTurnstile = !!document.querySelector('.cf-turnstile, [data-sitekey], iframe[src*="challenges.cloudflare.com"], #challenge-running, #challenge-form');
// Structural: page is almost empty (challenge pages have minimal DOM)
var bodyChildCount = document.body.children.length;
var isMinimalDom = bodyChildCount <= 5 && text.length < 500;
// Title-based: only check title on near-empty pages
var hasChallengeTitle = isMinimalDom && /just a moment|attention required|access denied/i.test(title);
var isChallenged = hasCfTurnstile || hasChallengeTitle;
return { textLength: text.length, title: title, isChallenged: isChallenged, bodyChildCount: bodyChildCount };
})()`)) as { textLength: number; title: string; isChallenged: boolean; bodyChildCount: number };
return { textLength: text.length, title: title, hasChallengeElement: hasCfTurnstile, bodyChildCount: bodyChildCount };
})()`)) as {
textLength: number;
title: string;
hasChallengeElement: boolean;
bodyChildCount: number;
};
if (pageContentCheck.isChallenged || pageContentCheck.textLength < 100) {
const reason = pageContentCheck.isChallenged
? "Anti-bot protection detected (Cloudflare challenge or similar)"
: "Page has very little text content (" +
pageContentCheck.textLength +
" chars) — may be blocked or a client-rendered SPA that needs more time";
const blockedReason = detectBlockedPage({
httpStatus: navigationResponse?.status() ?? null,
...pageContentCheck,
});
if (blockedReason) {
phase("navigation", "degraded", "blocked");
throw new Error(blockedReason);
}
phase("navigation", "completed");
phase("core-extraction", "started");
if (pageContentCheck.textLength < 100) {
const reason =
"Page has very little text content (" +
pageContentCheck.textLength +
" chars) — may be blocked or a client-rendered SPA that needs more time";
warnings.push(reason);
progress("warn", reason);
}
@@ -231,29 +288,36 @@ export async function captureWebsite(
// Framer and other modern sites use IntersectionObserver — images only load
// when scrolled into view. We scroll the full page, then wait for all images
// to finish loading before proceeding.
await page1.evaluate(`(async () => {
const lazyLoadBudgetMs = Math.min(15_000, remainingMs());
if (lazyLoadBudgetMs > 0) {
await page1.evaluate(`(async () => {
var lazyLoadDeadline = Date.now() + ${lazyLoadBudgetMs};
var h = document.body.scrollHeight;
for (var y = 0; y < h; y += window.innerHeight * 0.7) {
if (Date.now() >= lazyLoadDeadline) break;
window.scrollTo(0, y);
await new Promise(function(r) { setTimeout(r, 400); });
}
// Scroll to very bottom to catch footer lazy-loads
window.scrollTo(0, document.body.scrollHeight);
await new Promise(function(r) { setTimeout(r, 800); });
if (Date.now() < lazyLoadDeadline) {
window.scrollTo(0, document.body.scrollHeight);
await new Promise(function(r) { setTimeout(r, Math.min(800, Math.max(0, lazyLoadDeadline - Date.now()))); });
}
// Wait for all images to finish loading
var imgs = Array.from(document.querySelectorAll('img'));
var pending = imgs.filter(function(img) { return !img.complete; });
if (pending.length > 0) {
var imageWaitMs = Math.min(5000, Math.max(0, lazyLoadDeadline - Date.now()));
if (pending.length > 0 && imageWaitMs > 0) {
await Promise.race([
Promise.all(pending.map(function(img) {
return new Promise(function(r) { img.onload = r; img.onerror = r; });
})),
new Promise(function(r) { setTimeout(r, 5000); })
new Promise(function(r) { setTimeout(r, imageWaitMs); })
]);
}
window.scrollTo(0, 0);
await new Promise(function(r) { setTimeout(r, 500); });
})()`);
}
await page1.evaluate(`window.scrollTo(0, 0)`);
await new Promise((r) => setTimeout(r, 300));
@@ -289,13 +353,14 @@ export async function captureWebsite(
/* DOM scan failed — non-critical */
}
if (discoveredLotties.length > 0) {
if (discoveredLotties.length > 0 && remainingMs() > 0) {
const lottieDir = join(outputDir, "assets", "lottie");
mkdirSync(lottieDir, { recursive: true });
const savedCount = await saveLottieAnimations(discoveredLotties, lottieDir);
const lottieBudget = { remainingMs };
const savedCount = await saveLottieAnimations(discoveredLotties, lottieDir, lottieBudget);
// Generate manifest + preview thumbnails so the agent can SEE what each animation is
if (savedCount > 0) {
await renderLottiePreviews(chromeBrowser, lottieDir, outputDir);
if (savedCount > 0 && remainingMs() > 0) {
await renderLottiePreviews(chromeBrowser, lottieDir, outputDir, lottieBudget);
progress("lottie", `${savedCount} Lottie animation(s) saved`);
}
}
@@ -368,7 +433,7 @@ export async function captureWebsite(
// Capture scroll-position viewport screenshots
progress("screenshots", "Capturing scroll screenshots...");
const { captureScrollScreenshots } = await import("./screenshotCapture.js");
const screenshots = await captureScrollScreenshots(page1, outputDir);
const screenshots = await captureScrollScreenshots(page1, outputDir, { remainingMs });
progress("screenshots", `${screenshots.length} scroll screenshots captured`);
// Catalog all assets (must run before extractHtml which converts img src to data URLs)
@@ -437,10 +502,15 @@ export async function captureWebsite(
// Generate video manifest — screenshot each <video> element + extract surrounding context
// so Claude Code can SEE what each video shows and WHERE it was used on the page.
try {
await captureVideoManifest(page1, outputDir, progress, {
networkVideoUrls: discoveredVideoUrls, // Layer 1 (live Set, read after sampling)
sampleMs: 12000, // Layer 2: poll DOM ≤12s so auto-rotating carousels reveal each slide
});
const videoBudgetMs = remainingMs();
if (videoBudgetMs > 0) {
await captureVideoManifest(page1, outputDir, progress, {
networkVideoUrls: discoveredVideoUrls, // Layer 1 (live Set, read after sampling)
sampleMs: Math.min(12000, videoBudgetMs), // Layer 2: poll DOM within the shared budget
downloadBudgetMs: videoBudgetMs,
remainingMs,
});
}
} catch {
/* non-blocking — video manifest is best-effort */
}
@@ -459,8 +529,25 @@ export async function captureWebsite(
await page1.close();
phase("core-extraction", "completed");
// Download fonts and rewrite URLs to local paths
extracted.headHtml = await downloadAndRewriteFonts(extracted.headHtml, outputDir);
if (remainingMs() > 0) {
phase("fonts", "started");
extracted.headHtml = await downloadAndRewriteFonts(extracted.headHtml, outputDir, {
remainingMs,
});
phase(
"fonts",
remainingMs() > 0 ? "completed" : "degraded",
remainingMs() > 0 ? undefined : "budget-exhausted",
);
} else {
warnings.push(
"Capture budget exhausted before font downloads; extracted font tokens were preserved.",
);
phase("fonts", "degraded", "budget-exhausted");
}
// Identify each downloaded font by reading its OpenType name table.
// Modern frameworks hash font filenames; this manifest tells the
@@ -518,8 +605,23 @@ export async function captureWebsite(
// Download assets — single pass using the catalog for best image quality
let assets: CaptureResult["assets"] = [];
if (!skipAssets) {
progress("assets", "Downloading assets...");
assets = await downloadAssets(tokens, outputDir, catalogedAssets, faviconLinks);
if (remainingMs() > 0) {
phase("assets", "started");
progress("assets", "Downloading assets...");
assets = await downloadAssets(tokens, outputDir, catalogedAssets, faviconLinks, {
remainingMs,
});
phase(
"assets",
remainingMs() > 0 ? "completed" : "degraded",
remainingMs() > 0 ? undefined : "budget-exhausted",
);
} else {
warnings.push("Capture budget exhausted before asset downloads; extraction continued.");
phase("assets", "degraded", "budget-exhausted");
}
} else {
phase("assets", "degraded", "disabled");
}
// Join in-section media URLs → downloaded local paths, then re-write
@@ -573,7 +675,34 @@ export async function captureWebsite(
// detected-libraries and assets-catalog removed — 0/8 agents read them in v6 testing
// AI-powered image captioning via Gemini (optional — enriches asset descriptions)
const geminiCaptions = await captionImagesWithGemini(outputDir, progress, warnings);
let geminiCaptions: Record<string, string> = {};
if (skipVision) {
phase("vision", "degraded", "disabled");
} else if (remainingMs() <= 0) {
warnings.push(
"Capture budget exhausted before vision captioning; catalog descriptions were preserved.",
);
phase("vision", "degraded", "budget-exhausted");
} else {
phase("vision", "started");
let visionOutcome: VisionCaptionOutcome = {
timedOutRequests: 0,
failedRequests: 0,
budgetExhausted: false,
};
geminiCaptions = await captionImagesWithGemini(outputDir, progress, warnings, {
remainingMs,
onOutcome: (outcome) => {
visionOutcome = outcome;
},
});
const completion = resolveVisionPhaseCompletion(visionOutcome, remainingMs());
phase(
"vision",
completion.status,
completion.status === "degraded" ? completion.reason : undefined,
);
}
// Generate asset descriptions for the AI agent
progress("design", "Generating asset descriptions...");
@@ -581,8 +710,13 @@ export async function captureWebsite(
const lines = generateAssetDescriptions(outputDir, tokens, catalogedAssets, geminiCaptions);
if (lines.length > 0) {
const hasGeminiKey = !!(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
const header = hasGeminiKey
const hasVisionKey = !!(
!skipVision &&
(process.env.OPENROUTER_API_KEY ||
process.env.GEMINI_API_KEY ||
process.env.GOOGLE_API_KEY)
);
const header = hasVisionKey
? "# Asset Descriptions\n\nOne line per file. Read this instead of opening every image individually.\n\nTo find a specific brand or icon, **grep this file for the brand name in the description text** (e.g. `grep -i 'autodesk' asset-descriptions.md`). The Gemini Vision captions identify what's actually in each file — that's the agent's selector.\n\nThe `logo-<hash>.svg` filename prefix is a cheap structural hint (DOM said this SVG was inside a `<header>`, home-link `<a>`, or had an aria-label matching the page brand). It is NOT a content claim — many `logo-*` files are nav icons or decorative shapes. Trust the captions, not the filename prefix.\n\n"
: "# Asset Descriptions\n\n⚠️ GEMINI_API_KEY not set — descriptions below are catalog-derived (alt text, headings, section context, filename) instead of Vision-generated. To get richer Vision descriptions on the next capture, set GEMINI_API_KEY (or GOOGLE_API_KEY) and re-run.\n\nThe `logo-<hash>.svg` filename prefix is a structural hint (DOM said this SVG was inside a `<header>`, home-link `<a>`, or had an aria-label matching the page brand). To pick the actual brand logo without Vision, open the `logo-*` candidates in a previewer or rasterize them with `sharp` before referencing — composing a fake logo ships off-brand in the final video.\n\n";
writeFileSync(
@@ -592,7 +726,7 @@ export async function captureWebsite(
);
progress(
"design",
`${lines.length} asset descriptions written${hasGeminiKey ? "" : " (no Gemini key — catalog-fallback mode)"}`,
`${lines.length} asset descriptions written${hasVisionKey ? "" : " (no vision provider — catalog-fallback mode)"}`,
);
}
} catch {
@@ -603,51 +737,74 @@ export async function captureWebsite(
// Generate contact sheets (saves AI agents 50-65% tokens vs reading images individually)
// All functions return string[] — paginated so every image is covered
try {
const { createScrollContactSheet, createAssetContactSheet, createSvgContactSheet } =
await import("./contactSheet.js");
if (remainingMs() > 0) {
phase("contact-sheets", "started");
try {
const { createScrollContactSheet, createAssetContactSheet, createSvgContactSheet } =
await import("./contactSheet.js");
const scrollSheets = await createScrollContactSheet(
join(outputDir, "screenshots"),
join(outputDir, "screenshots", "contact-sheet.jpg"),
);
if (scrollSheets.length > 0)
progress(
"design",
`Screenshot contact sheet generated (${scrollSheets.length} page${scrollSheets.length > 1 ? "s" : ""})`,
);
const contactSheetBudget = { remainingMs };
const assetsImgDir = join(outputDir, "assets");
if (existsSync(assetsImgDir)) {
const assetSheets = await createAssetContactSheet(
assetsImgDir,
join(outputDir, "assets", "contact-sheet.jpg"),
const scrollSheets = await createScrollContactSheet(
join(outputDir, "screenshots"),
join(outputDir, "screenshots", "contact-sheet.jpg"),
contactSheetBudget,
);
if (assetSheets.length > 0)
if (scrollSheets.length > 0)
progress(
"design",
`Asset contact sheet generated (${assetSheets.length} page${assetSheets.length > 1 ? "s" : ""})`,
`Screenshot contact sheet generated (${scrollSheets.length} page${scrollSheets.length > 1 ? "s" : ""})`,
);
}
// Scan assets/svgs/ (inline SVGs) AND assets/ root (external SVGs from <img src="*.svg">)
// so sites like huly.io that only use external SVGs still get a grid
const svgsDir = join(outputDir, "assets", "svgs");
const assetsRootDir = join(outputDir, "assets");
const svgOutputPath = existsSync(svgsDir)
? join(outputDir, "assets", "svgs", "contact-sheet.jpg")
: join(outputDir, "assets", "contact-sheet-svgs.jpg");
const svgSheets = await createSvgContactSheet(svgsDir, svgOutputPath, assetsRootDir);
if (svgSheets.length > 0)
progress(
"design",
`SVG contact sheet generated (${svgSheets.length} page${svgSheets.length > 1 ? "s" : ""})`,
const assetsImgDir = join(outputDir, "assets");
if (existsSync(assetsImgDir)) {
const assetSheets = await createAssetContactSheet(
assetsImgDir,
join(outputDir, "assets", "contact-sheet.jpg"),
contactSheetBudget,
);
if (assetSheets.length > 0)
progress(
"design",
`Asset contact sheet generated (${assetSheets.length} page${assetSheets.length > 1 ? "s" : ""})`,
);
}
// Scan assets/svgs/ (inline SVGs) AND assets/ root (external SVGs from <img src="*.svg">)
// so sites like huly.io that only use external SVGs still get a grid
const svgsDir = join(outputDir, "assets", "svgs");
const assetsRootDir = join(outputDir, "assets");
const svgOutputPath = existsSync(svgsDir)
? join(outputDir, "assets", "svgs", "contact-sheet.jpg")
: join(outputDir, "assets", "contact-sheet-svgs.jpg");
const svgSheets = await createSvgContactSheet(
svgsDir,
svgOutputPath,
assetsRootDir,
contactSheetBudget,
);
} catch {
/* contact sheets are non-critical — agent can still read images individually */
if (svgSheets.length > 0)
progress(
"design",
`SVG contact sheet generated (${svgSheets.length} page${svgSheets.length > 1 ? "s" : ""})`,
);
} catch {
/* contact sheets are non-critical — agent can still read images individually */
}
phase(
"contact-sheets",
remainingMs() > 0 ? "completed" : "degraded",
remainingMs() > 0 ? undefined : "budget-exhausted",
);
} else {
warnings.push(
"Capture budget exhausted before contact sheets; source images were preserved.",
);
phase("contact-sheets", "degraded", "budget-exhausted");
}
// Generate project scaffold (index.html, meta.json, CLAUDE.md)
phase("scaffold", "started");
await generateProjectScaffold(
outputDir,
url,
@@ -661,8 +818,10 @@ export async function captureWebsite(
warnings,
detectedLibraries,
);
phase("scaffold", "completed");
progress("done", "Capture complete");
phase("complete", "completed");
return {
ok: true,
@@ -675,6 +834,7 @@ export async function captureWebsite(
assets,
animationCatalog,
warnings,
lastPhase,
};
} finally {
await chromeBrowser.close();
@@ -0,0 +1,187 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Browser, Page } from "puppeteer-core";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
captureVideoManifest,
remainingVideoDownloadTimeoutMs,
renderLottiePreviews,
saveLottieAnimations,
} from "./mediaCapture.js";
const tempDirs: string[] = [];
function tempDir(): string {
const dir = mkdtempSync(join(tmpdir(), "hf-media-budget-"));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true });
tempDirs.length = 0;
});
describe("Lottie capture budget", () => {
it("does not start another Lottie fetch after the live budget expires", async () => {
const dir = tempDir();
let remainingMs = 10_000;
const fetchMock = vi.fn(async () => {
remainingMs = 0;
return new Response(JSON.stringify({ w: 100, h: 100, layers: [] }), { status: 200 });
});
vi.stubGlobal("fetch", fetchMock);
const saved = await saveLottieAnimations(
[{ url: "https://one.example/a.json" }, { url: "https://two.example/b.json" }],
dir,
{ remainingMs: () => remainingMs },
);
expect(saved).toBe(1);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("does not open another Lottie preview page after the live budget expires", async () => {
const dir = tempDir();
const lottieDir = join(dir, "assets", "lottie");
mkdirSync(join(dir, "extracted"), { recursive: true });
mkdirSync(lottieDir, { recursive: true });
const lottie = JSON.stringify({ w: 100, h: 100, fr: 30, ip: 0, op: 30, layers: [] });
writeFileSync(join(lottieDir, "a.json"), lottie);
writeFileSync(join(lottieDir, "b.json"), lottie);
let remainingMs = 10_000;
const previewPage = {
setViewport: vi.fn(async () => undefined),
setContent: vi.fn(async () => undefined),
evaluate: vi.fn(async () => undefined),
waitForFunction: vi.fn(async () => undefined),
screenshot: vi.fn(async () => undefined),
close: vi.fn(async () => undefined),
};
const newPage = vi.fn(async () => {
remainingMs = 0;
return previewPage;
});
const browser = { newPage } as unknown as Browser;
await renderLottiePreviews(browser, lottieDir, dir, { remainingMs: () => remainingMs });
expect(newPage).toHaveBeenCalledTimes(1);
expect(previewPage.setViewport).not.toHaveBeenCalled();
expect(previewPage.screenshot).not.toHaveBeenCalled();
});
it("omits a preview path when the budget expires after Lottie readiness", async () => {
const dir = tempDir();
const lottieDir = join(dir, "assets", "lottie");
mkdirSync(join(dir, "extracted"), { recursive: true });
mkdirSync(lottieDir, { recursive: true });
writeFileSync(
join(lottieDir, "logo.json"),
JSON.stringify({
nm: "Logo",
w: 100,
h: 100,
fr: 30,
ip: 0,
op: 30,
layers: [],
}),
);
const screenshot = vi.fn(async () => undefined);
const previewPage = {
setViewport: vi.fn(async () => undefined),
setContent: vi.fn(async () => undefined),
evaluate: vi.fn(async () => undefined),
waitForFunction: vi.fn(async () => undefined),
screenshot,
close: vi.fn(async () => undefined),
};
const browser = { newPage: vi.fn(async () => previewPage) } as unknown as Browser;
let budgetChecks = 0;
await renderLottiePreviews(browser, lottieDir, dir, {
remainingMs: () => (++budgetChecks < 4 ? 10_000 : 0),
});
const manifest = JSON.parse(
readFileSync(join(dir, "extracted", "lottie-manifest.json"), "utf-8"),
);
expect(screenshot).not.toHaveBeenCalled();
expect(manifest).toHaveLength(1);
expect(manifest[0]).toMatchObject({
file: "assets/lottie/logo.json",
name: "Logo",
width: 100,
height: 100,
});
expect(manifest[0]).not.toHaveProperty("preview");
expect(existsSync(join(lottieDir, "previews", "logo-preview.png"))).toBe(false);
});
});
describe("video capture live budget", () => {
it("does not preview or download when the budget expires during DOM sampling", async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const dir = tempDir();
mkdirSync(join(dir, "extracted"), { recursive: true });
const descriptor = {
src: "https://video.example/hero.mp4",
filename: "hero.mp4",
width: 640,
height: 360,
sourceWidth: 640,
sourceHeight: 360,
top: 0,
left: 0,
heading: "Hero",
caption: "Demo",
ariaLabel: "",
};
const screenshot = vi.fn(async () => Buffer.from("preview"));
const evaluate = vi.fn(async (expression: unknown) =>
typeof expression === "function" ? { x: 0, y: 0, width: 640, height: 360 } : [descriptor],
);
const page = { evaluate, screenshot } as unknown as Page;
const fetchMock = vi.fn(
async () =>
new Response(Buffer.alloc(2048), {
status: 200,
headers: { "content-type": "video/mp4" },
}),
);
vi.stubGlobal("fetch", fetchMock);
const capture = captureVideoManifest(page, dir, () => {}, {
sampleMs: 10_000,
downloadBudgetMs: 10_000,
remainingMs: () => Math.max(0, 1_000 - Date.now()),
});
await vi.runAllTimersAsync();
await capture;
expect(screenshot).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("remainingVideoDownloadTimeoutMs", () => {
it("caps a video request to the remaining capture budget", () => {
expect(remainingVideoDownloadTimeoutMs(1_000, 5_000, 4_500)).toBe(1_500);
});
it("returns zero after the aggregate budget is exhausted", () => {
expect(remainingVideoDownloadTimeoutMs(1_000, 5_000, 6_001)).toBe(0);
});
it("retains the existing per-request ceiling when more budget remains", () => {
expect(remainingVideoDownloadTimeoutMs(1_000, 300_000, 2_000)).toBe(120_000);
});
});
+80 -26
View File
@@ -20,6 +20,14 @@ export interface DiscoveredLottie {
frameRate?: number;
}
interface RemainingBudget {
remainingMs?: () => number;
}
function liveRemainingMs(budget: RemainingBudget, fallbackMs: number): number {
return budget.remainingMs?.() ?? fallbackMs;
}
/**
* Download and save discovered Lottie animations to disk.
*
@@ -30,11 +38,13 @@ export interface DiscoveredLottie {
export async function saveLottieAnimations(
discoveredLotties: DiscoveredLottie[],
lottieDir: string,
budget: RemainingBudget = {},
): Promise<number> {
let savedCount = 0;
const savedHashes = new Set<string>(); // Deduplicate by content
for (let li = 0; li < discoveredLotties.length && li < 10; li++) {
if (liveRemainingMs(budget, 10_000) <= 0) break;
const lottieItem = discoveredLotties[li]!;
try {
let jsonData: string | undefined;
@@ -43,9 +53,11 @@ export async function saveLottieAnimations(
// Already have the JSON data from network interception
jsonData = JSON.stringify(lottieItem.data);
} else if (lottieItem.url) {
const requestTimeoutMs = Math.min(10_000, liveRemainingMs(budget, 10_000));
if (requestTimeoutMs <= 0) break;
// SSRF guard — safeFetch re-checks the denylist on every redirect hop
const res = await safeFetch(lottieItem.url, {
signal: AbortSignal.timeout(10000),
signal: AbortSignal.timeout(requestTimeoutMs),
headers: { "User-Agent": "HyperFrames/1.0" },
});
if (!res || !res.ok) continue;
@@ -110,17 +122,18 @@ export async function saveLottieAnimations(
*
* Opens each Lottie JSON in a headless Chrome page via lottie-web,
* seeks to ~30% through the animation, and takes a transparent screenshot.
* Writes a lottie-manifest.json with metadata + preview paths.
* Writes a lottie-manifest.json with metadata and successfully rendered preview paths.
*/
// fallow-ignore-next-line complexity
export async function renderLottiePreviews(
chromeBrowser: Browser,
lottieDir: string,
outputDir: string,
budget: RemainingBudget = {},
): Promise<void> {
const manifest: Array<{
file: string;
preview: string;
preview?: string;
name: string;
width: number;
height: number;
@@ -133,11 +146,13 @@ export async function renderLottiePreviews(
for (const file of readdirSync(lottieDir)) {
if (!file.endsWith(".json")) continue;
if (liveRemainingMs(budget, 1) <= 0) break;
try {
const raw = JSON.parse(readFileSync(join(lottieDir, file), "utf-8"));
const fr = raw.fr || 30;
const dur = ((raw.op || 0) - (raw.ip || 0)) / fr;
const previewName = file.replace(".json", "-preview.png");
let preview: string | undefined;
// Render a mid-frame thumbnail using Puppeteer + lottie-web
// Skip huge Lottie files for preview (CDP has a ~256MB message limit)
@@ -146,7 +161,9 @@ export async function renderLottiePreviews(
let previewPage;
try {
if (liveRemainingMs(budget, 1) <= 0) break;
previewPage = await chromeBrowser.newPage();
if (liveRemainingMs(budget, 1) <= 0) break;
await previewPage.setViewport({ width: 400, height: 400 });
const animData = JSON.parse(readFileSync(join(lottieDir, file), "utf-8"));
const midFrame = Math.floor(((raw.op || 0) - (raw.ip || 0)) * 0.3);
@@ -180,11 +197,14 @@ export async function renderLottiePreviews(
await previewPage
.waitForFunction(() => (window as any).__READY === true, { timeout: 5000 })
.catch(() => {});
await previewPage.screenshot({
path: join(previewDir, previewName),
type: "png",
omitBackground: true,
});
if (liveRemainingMs(budget, 1) > 0) {
await previewPage.screenshot({
path: join(previewDir, previewName),
type: "png",
omitBackground: true,
});
preview = `assets/lottie/previews/${previewName}`;
}
} catch {
/* preview rendering failed — non-critical */
} finally {
@@ -193,7 +213,7 @@ export async function renderLottiePreviews(
manifest.push({
file: `assets/lottie/${file}`,
preview: `assets/lottie/previews/${previewName}`,
...(preview ? { preview } : {}),
name: raw.nm || file,
width: raw.w || 0,
height: raw.h || 0,
@@ -216,6 +236,15 @@ export async function renderLottiePreviews(
const MAX_VIDEO_BYTES = 75 * 1024 * 1024; // 75 MB — hero/demo clips, not full films
const DOWNLOADABLE_VIDEO_EXTS = new Set([".mp4", ".webm", ".mov", ".m4v"]);
const VIDEO_DOWNLOAD_TIMEOUT_MS = 120_000;
export function remainingVideoDownloadTimeoutMs(
budgetStartedAt: number,
budgetMs: number,
now = Date.now(),
): number {
return Math.max(0, Math.min(VIDEO_DOWNLOAD_TIMEOUT_MS, budgetMs - (now - budgetStartedAt)));
}
/**
* Download a <video> body to assets/videos/<file>, returning the
@@ -234,6 +263,7 @@ async function downloadVideoBody(
srcUrl: string,
filename: string,
videosDir: string,
timeoutMs: number,
): Promise<string | null> {
if (isPrivateUrl(srcUrl)) return null; // cheap pre-check; safeFetch re-checks every hop
let ext = "";
@@ -247,7 +277,7 @@ async function downloadVideoBody(
// safeFetch resolves redirects manually and re-runs isPrivateUrl on each
// Location hop, so a public URL cannot 30x to an internal/metadata host.
const res = await safeFetch(srcUrl, {
signal: AbortSignal.timeout(120000), // up to ~75 MB on a slow link; aborts cleanly → still-frame fallback
signal: AbortSignal.timeout(timeoutMs), // bounded by both per-request and aggregate capture budgets
headers: { "User-Agent": "HyperFrames/1.0" },
});
if (!res || !res.ok || !res.body) return null;
@@ -352,11 +382,12 @@ async function sampleVideoDom(
page: Page,
budgetMs: number,
netSet: Set<string>,
budget: RemainingBudget,
): Promise<VideoDescriptor[]> {
const seen = new Map<string, VideoDescriptor>();
const start = Date.now();
let stale = 0;
while (Date.now() - start < budgetMs && stale < 3) {
while (Date.now() - start < budgetMs && stale < 3 && liveRemainingMs(budget, 1) > 0) {
let grew = false;
const netBefore = netSet.size;
for (const d of await scanVideoDom(page)) {
@@ -367,7 +398,12 @@ async function sampleVideoDom(
}
if (netSet.size > netBefore) grew = true;
stale = grew ? 0 : stale + 1;
await new Promise((r) => setTimeout(r, 2000));
const waitMs = Math.min(
2000,
Math.max(0, budgetMs - (Date.now() - start)),
Math.max(0, liveRemainingMs(budget, 2000)),
);
if (waitMs > 0) await new Promise((r) => setTimeout(r, waitMs));
}
return [...seen.values()];
}
@@ -397,7 +433,12 @@ export async function captureVideoManifest(
page: Page,
outputDir: string,
progress: (stage: string, detail?: string) => void,
opts?: { networkVideoUrls?: Set<string>; sampleMs?: number; downloadBudgetMs?: number },
opts?: {
networkVideoUrls?: Set<string>;
sampleMs?: number;
downloadBudgetMs?: number;
remainingMs?: () => number;
},
): Promise<void> {
const netSet = opts?.networkVideoUrls ?? new Set<string>();
const sampleMs = opts?.sampleMs ?? 0;
@@ -406,7 +447,9 @@ export async function captureVideoManifest(
// DOM scan, optionally sampled over time (Layer 2) when videos are present.
const initial = await scanVideoDom(page);
const domVideos =
initial.length > 0 && sampleMs > 0 ? await sampleVideoDom(page, sampleMs, netSet) : initial;
initial.length > 0 && sampleMs > 0
? await sampleVideoDom(page, sampleMs, netSet, opts ?? {})
: initial;
// Merge DOM (rich) + network-only (thin, Layer 1), deduped by download
// filename so a clip seen in both lands once. netSet is read here — AFTER
@@ -462,6 +505,11 @@ export async function captureVideoManifest(
const dlStart = Date.now();
for (let vi = 0; vi < merged.length && vi < 20; vi++) {
const iterationRemainingMs = liveRemainingMs(
opts ?? {},
remainingVideoDownloadTimeoutMs(dlStart, downloadBudgetMs),
);
if (iterationRemainingMs <= 0) break;
const v = merged[vi]!;
let preview: string | undefined;
@@ -485,16 +533,18 @@ export async function captureVideoManifest(
}, v.filename)) as { x: number; y: number; width: number; height: number } | null;
if (rect && rect.width >= 10) {
await new Promise((r) => setTimeout(r, 200)); // let decoder settle
await page.screenshot({
path: join(previewDir, previewName),
clip: {
x: Math.max(0, rect.x),
y: Math.max(0, rect.y),
width: Math.min(rect.width, 1920),
height: Math.min(rect.height, 1080),
},
});
preview = `assets/videos/previews/${previewName}`;
if (liveRemainingMs(opts ?? {}, 1) > 0) {
await page.screenshot({
path: join(previewDir, previewName),
clip: {
x: Math.max(0, rect.x),
y: Math.max(0, rect.y),
width: Math.min(rect.width, 1920),
height: Math.min(rect.height, 1080),
},
});
preview = `assets/videos/previews/${previewName}`;
}
}
} catch {
/* preview failed — non-critical */
@@ -505,9 +555,13 @@ export async function captureVideoManifest(
// direct file. Cumulative budget caps total download time so a throttled
// host or many large clips can't stall capture — over budget, keep the
// preview (if any) and stop fetching bodies.
const downloadTimeoutMs = Math.min(
remainingVideoDownloadTimeoutMs(dlStart, downloadBudgetMs),
liveRemainingMs(opts ?? {}, VIDEO_DOWNLOAD_TIMEOUT_MS),
);
const savedPath =
Date.now() - dlStart < downloadBudgetMs
? await downloadVideoBody(v.src, v.filename, videoManifestDir)
downloadTimeoutMs > 0
? await downloadVideoBody(v.src, v.filename, videoManifestDir, downloadTimeoutMs)
: null;
// A network-only video with neither a preview nor a downloaded body carries
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import { detectBlockedPage } from "./pageBlockDetection.js";
describe("detectBlockedPage", () => {
it.each([
{
label: "local Fuji response",
evidence: {
httpStatus: 403,
title: "403 - Forbidden",
textLength: 50,
bodyChildCount: 1,
hasChallengeElement: false,
},
},
{
label: "EC2-style soft-block response",
evidence: {
httpStatus: 200,
title: "Access denied",
textLength: 18,
bodyChildCount: 2,
hasChallengeElement: false,
},
},
{
label: "classic Cloudflare interstitial",
evidence: {
httpStatus: 503,
title: "Attention Required! | Cloudflare",
textLength: 120,
bodyChildCount: 3,
hasChallengeElement: false,
},
},
])("rejects a minimal protection page: $label", ({ evidence }) => {
expect(detectBlockedPage(evidence)).toMatch(/capture blocked/i);
});
it("rejects a structural challenge on a minimal page", () => {
expect(
detectBlockedPage({
httpStatus: 200,
title: "Please verify you are human",
textLength: 300,
bodyChildCount: 3,
hasChallengeElement: true,
}),
).toMatch(/capture blocked/i);
});
it.each([
{
label: "an image-led page with little text",
evidence: {
httpStatus: 200,
title: "Photography portfolio",
textLength: 18,
bodyChildCount: 4,
hasChallengeElement: false,
},
},
{
label: "a real page discussing access denial",
evidence: {
httpStatus: 200,
title: "Why websites say Access Denied",
textLength: 2_000,
bodyChildCount: 20,
hasChallengeElement: false,
},
},
{
label: "a full page with an embedded CAPTCHA",
evidence: {
httpStatus: 200,
title: "Contact us",
textLength: 2_000,
bodyChildCount: 20,
hasChallengeElement: true,
},
},
{
label: "a minimal photography page named Forbidden Fruit Photography",
evidence: {
httpStatus: 200,
title: "Forbidden Fruit Photography",
textLength: 40,
bodyChildCount: 4,
hasChallengeElement: false,
},
},
{
label: "a minimal photo essay named Attention Required",
evidence: {
httpStatus: 200,
title: "Attention Required: A Photo Essay",
textLength: 60,
bodyChildCount: 5,
hasChallengeElement: false,
},
},
])("allows $label", ({ evidence }) => {
expect(detectBlockedPage(evidence)).toBeUndefined();
});
});
@@ -0,0 +1,34 @@
export interface PageLoadEvidence {
httpStatus: number | null;
title: string;
textLength: number;
bodyChildCount: number;
hasChallengeElement: boolean;
}
/**
* Returns an actionable failure only for strong protection-page signals.
* Low text by itself is intentionally not fatal because image-led sites and
* client-rendered applications can legitimately have very little body copy.
*/
export function detectBlockedPage(evidence: PageLoadEvidence): string | undefined {
const isMinimalDom = evidence.bodyChildCount <= 5 && evidence.textLength < 500;
const hasBlockedStatus =
evidence.httpStatus === 401 || evidence.httpStatus === 403 || evidence.httpStatus === 429;
const hasBlockedTitle =
/^(?:(?:error\s*)?(?:401|403|429)(?:\s*(?:[-:—]\s*)?(?:forbidden|unauthorized|access denied|too many requests))?|forbidden|access denied|attention required!?|just a moment(?:\.{3})?)(?:\s*[|—-]\s*(?:cloudflare|sucuri website firewall))?$/i.test(
evidence.title.trim(),
);
if (!isMinimalDom || (!evidence.hasChallengeElement && !hasBlockedStatus && !hasBlockedTitle)) {
return undefined;
}
const statusDetail =
evidence.httpStatus === null ? "no HTTP status" : `HTTP ${evidence.httpStatus}`;
return (
`Website capture blocked: the loaded page matched an access-protection response ` +
`(${statusDetail}, title ${JSON.stringify(evidence.title)}, ${evidence.textLength} text chars). ` +
"The site may reject automated or data-center traffic; retry from an allowed network or provide source assets directly."
);
}
@@ -3,7 +3,12 @@ import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Page } from "puppeteer-core";
import { captureFullPagePlate, MAX_PLATE_HEIGHT_PX, pngHeight } from "./screenshotCapture.js";
import {
captureFullPagePlate,
captureScrollScreenshots,
MAX_PLATE_HEIGHT_PX,
pngHeight,
} from "./screenshotCapture.js";
// A real 1920x800 PNG header, so the produced-height guard sees something valid.
function pngBuffer(height: number, width = 1920): Buffer {
@@ -104,6 +109,76 @@ describe("captureFullPagePlate — the scroll shot's plate", () => {
});
});
describe("captureScrollScreenshots — capture budget", () => {
it("does not begin page work when the post-navigation budget is exhausted", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-scroll-budget-"));
const evaluate = vi.fn(async () => 1080);
const screenshot = vi.fn(async () => pngBuffer(1080));
const page = { evaluate, screenshot } as unknown as Page;
const files = await captureScrollScreenshots(page, dir, { remainingMs: () => 0 });
expect(files).toEqual([]);
expect(evaluate).not.toHaveBeenCalled();
expect(screenshot).not.toHaveBeenCalled();
});
it("re-checks the budget after settling and before each viewport screenshot", async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const dir = mkdtempSync(join(tmpdir(), "hf-scroll-expiring-budget-"));
const evaluate = vi.fn(async (expression: unknown) => {
const source = String(expression);
if (source.includes("Math.max(document.body.scrollHeight")) return 1080;
if (source === "window.innerHeight") return 1080;
return undefined;
});
const screenshot = vi.fn(async () => pngBuffer(1080));
const page = { evaluate, screenshot } as unknown as Page;
try {
const capture = captureScrollScreenshots(page, dir, {
remainingMs: () => Math.max(0, 600 - Date.now()),
});
await vi.runAllTimersAsync();
const files = await capture;
expect(files).toEqual([]);
expect(screenshot).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
});
describe("captureFullPagePlate — capture budget", () => {
it("re-checks the budget immediately before the full-page screenshot", async () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const dir = mkdtempSync(join(tmpdir(), "hf-plate-expiring-budget-"));
const screenshot = vi.fn(async () => pngBuffer(8000));
const evaluate = vi.fn(async (expression: unknown) => {
if (String(expression).includes("scrollHeight")) {
vi.setSystemTime(100);
return 8000;
}
return undefined;
});
const page = { evaluate, screenshot } as unknown as Page;
try {
const plate = await captureFullPagePlate(page, dir, {
remainingMs: () => Math.max(0, 50 - Date.now()),
});
expect(plate).toBeNull();
expect(screenshot).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
});
describe("captureFullPagePlate — guards against a silently clipped plate", () => {
it("measures the height itself, after lazy content has grown the page", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-plate-"));
+16 -3
View File
@@ -59,6 +59,7 @@ export function pngHeight(buf: Uint8Array): number | null {
export async function captureFullPagePlate(
page: Page,
screenshotsDir: string,
budget: { remainingMs?: () => number } = {},
): Promise<string | null> {
// Record the inline value before overwriting so the page is handed back unchanged — the
// caller keeps using it (asset extraction, DOM reads) after this returns.
@@ -81,6 +82,7 @@ export async function captureFullPagePlate(
`Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)`,
)) as number;
if (docHeight > MAX_PLATE_HEIGHT_PX) return null;
if ((budget.remainingMs?.() ?? 1) <= 0) return null;
const buffer = await page.screenshot({ type: "png", fullPage: true });
// Confirm what Chrome produced instead of trusting the measurement: the capture itself can
@@ -107,13 +109,20 @@ export async function captureFullPagePlate(
}
}
export async function captureScrollScreenshots(page: Page, outputDir: string): Promise<string[]> {
// fallow-ignore-next-line complexity
export async function captureScrollScreenshots(
page: Page,
outputDir: string,
budget: { remainingMs?: () => number } = {},
): Promise<string[]> {
const screenshotsDir = join(outputDir, "screenshots");
mkdirSync(screenshotsDir, { recursive: true });
const MAX_SCREENSHOTS = 20;
const filePaths: string[] = [];
if ((budget.remainingMs?.() ?? 1) <= 0) return filePaths;
try {
// Dismiss marketing banners, cookie consents, and popups before scrolling.
// These overlay content and contaminate screenshots with UI that doesn't
@@ -220,6 +229,7 @@ export async function captureScrollScreenshots(page: Page, outputDir: string): P
}
for (let i = 0; i < finalPositions.length; i++) {
if ((budget.remainingMs?.() ?? 1) <= 0) break;
await page.evaluate(`window.scrollTo(0, ${finalPositions[i]})`);
await new Promise((r) => setTimeout(r, 400));
@@ -228,6 +238,7 @@ export async function captureScrollScreenshots(page: Page, outputDir: string): P
);
const filename = `scroll-${String(Math.min(pct, 100)).padStart(3, "0")}.png`;
const filePath = join(screenshotsDir, filename);
if ((budget.remainingMs?.() ?? 1) <= 0) break;
const buffer = await page.screenshot({ type: "png" });
writeFileSync(filePath, buffer);
filePaths.push(`screenshots/${filename}`);
@@ -242,8 +253,10 @@ export async function captureScrollScreenshots(page: Page, outputDir: string): P
// dropped because 1/8 agents read it and the contact sheet covered the same ground — that
// was about it as a *comprehension* artifact. The scroll shot is a different consumer: it
// needs one continuous plate, which no set of viewport tiles can substitute for.)
const plate = await captureFullPagePlate(page, screenshotsDir);
if (plate) filePaths.push(plate);
if ((budget.remainingMs?.() ?? 1) > 0) {
const plate = await captureFullPagePlate(page, screenshotsDir, budget);
if (plate) filePaths.push(plate);
}
} catch {
/* scroll screenshots are non-critical */
}
+34
View File
@@ -9,6 +9,32 @@
// ── Phase 1: Capture ────────────────────────────────────────────────────────
export type CapturePhase =
| "browser"
| "navigation"
| "core-extraction"
| "fonts"
| "assets"
| "vision"
| "contact-sheets"
| "scaffold"
| "complete";
export interface CapturePhaseProgress {
schema: "hyperframes.capture.phase.v1";
phase: CapturePhase;
status: "started" | "completed" | "degraded";
/** Null before the post-navigation budget begins. */
remainingMs: number | null;
reason?:
| "budget-exhausted"
| "disabled"
| "request-timeout"
| "provider-error"
| "internal-error"
| "blocked";
}
export interface CaptureOptions {
/** URL to capture */
url: string;
@@ -26,6 +52,12 @@ export interface CaptureOptions {
maxScreenshots?: number;
/** Skip asset downloads */
skipAssets?: boolean;
/** Skip optional vision captioning */
skipVision?: boolean;
/** Cooperative post-navigation budget in ms (default: 120000). */
postNavigationBudgetMs?: number;
/** Stable, non-sensitive progress records for watchdog diagnostics. */
onPhase?: (event: CapturePhaseProgress) => void;
/** Output JSON for programmatic use */
json?: boolean;
}
@@ -51,6 +83,8 @@ export interface CaptureResult {
animationCatalog?: import("./animationCataloger.js").AnimationCatalog;
/** Errors/warnings encountered during capture */
warnings: string[];
/** Final structured phase record emitted by a successful capture. */
lastPhase: CapturePhaseProgress;
}
export interface ExtractedHtml {
+195
View File
@@ -0,0 +1,195 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CliRuntimeError } from "../utils/commandResult.js";
const { captureWebsiteMock } = vi.hoisted(() => ({
captureWebsiteMock: vi.fn(async (options: unknown) => {
if (typeof options === "object" && options !== null) {
const onPhase = Reflect.get(options, "onPhase");
if (typeof onPhase === "function") {
onPhase({
schema: "hyperframes.capture.phase.v1",
phase: "vision",
status: "degraded",
remainingMs: 0,
reason: "budget-exhausted",
});
}
}
return {
ok: true,
projectDir: "/tmp/capture",
url: "https://example.com",
title: "Example",
extracted: {},
screenshots: [],
tokens: { sections: [], fonts: [] },
assets: [],
warnings: [],
};
}),
}));
vi.mock("../capture/index.js", () => ({ captureWebsite: captureWebsiteMock }));
import captureCommand from "./capture.js";
describe("capture command — vision control", () => {
afterEach(() => {
captureWebsiteMock.mockClear();
vi.restoreAllMocks();
});
it("declares --skip-vision as an opt-in boolean", () => {
const skipVisionArg = captureCommand.args
? Reflect.get(captureCommand.args, "skip-vision")
: undefined;
expect(skipVisionArg).toMatchObject({
type: "boolean",
default: false,
});
});
it("declares --capture-budget separately from navigation --timeout", () => {
const captureBudgetArg = captureCommand.args
? Reflect.get(captureCommand.args, "capture-budget")
: undefined;
expect(captureBudgetArg).toMatchObject({ type: "string" });
const description = captureBudgetArg?.description.toLowerCase();
expect(description).toContain("post-navigation");
expect(description).toContain("cooperative");
expect(description).toContain("not a hard wall-clock timeout");
expect(description).toContain("already-started native/core work");
expect(captureBudgetArg?.description).toContain("--timeout");
});
it("plumbs --skip-vision into capture options", async () => {
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
await captureCommand.run!({
args: {
url: "https://example.com",
output: "/tmp/hf-skip-vision-test",
"skip-assets": false,
"skip-vision": true,
json: true,
},
} as never);
expect(captureWebsiteMock).toHaveBeenCalledWith(
expect.objectContaining({ skipVision: true }),
undefined,
);
});
it.each([
["1", 1],
["45000", 45_000],
])(
"plumbs positive integer --capture-budget %s into the post-navigation budget",
async (captureBudget, expectedBudget) => {
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
await captureCommand.run!({
args: {
url: "https://example.com",
output: "/tmp/hf-capture-budget-test",
"skip-assets": false,
"skip-vision": false,
"capture-budget": captureBudget,
json: true,
},
} as never);
expect(captureWebsiteMock).toHaveBeenCalledWith(
expect.objectContaining({ postNavigationBudgetMs: expectedBudget }),
undefined,
);
},
);
it.each(["0", "-1", "0.5", "Infinity", "not-a-number"])(
"rejects invalid --capture-budget %s before capture starts",
async (captureBudget) => {
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
await expect(
captureCommand.run!({
args: {
url: "https://example.com",
output: "/tmp/hf-invalid-capture-budget-test",
"skip-assets": false,
"skip-vision": false,
"capture-budget": captureBudget,
json: true,
},
} as never),
).rejects.toBeInstanceOf(CliRuntimeError);
expect(captureWebsiteMock).not.toHaveBeenCalled();
},
);
it("emits a versioned phase record without the captured URL", async () => {
vi.spyOn(console, "log").mockImplementation(() => {});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
await captureCommand.run!({
args: {
url: "https://user:secret@example.com/private",
output: "/tmp/hf-phase-progress-test",
"skip-assets": false,
"skip-vision": false,
json: true,
},
} as never);
const line = error.mock.calls.find(
([value]) => typeof value === "string" && value.startsWith("HYPERFRAMES_CAPTURE_PHASE "),
)?.[0];
expect(typeof line).toBe("string");
if (typeof line !== "string") throw new Error("Expected capture phase diagnostic");
const event = JSON.parse(line.slice("HYPERFRAMES_CAPTURE_PHASE ".length));
expect(event).toEqual({
schema: "hyperframes.capture.phase.v1",
phase: "vision",
status: "degraded",
remainingMs: 0,
reason: "budget-exhausted",
});
expect(line).not.toContain("secret");
expect(line).not.toContain("/private");
});
it("keeps required capture failures nonzero", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-capture-failure-"));
const log = vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
captureWebsiteMock.mockRejectedValueOnce(new Error("required extraction failed"));
try {
await expect(
captureCommand.run!({
args: {
url: "https://example.com",
output: dir,
"skip-assets": false,
"skip-vision": false,
json: true,
},
} as never),
).rejects.toBeInstanceOf(CliRuntimeError);
const payload = log.mock.calls.at(-1)?.[0];
expect(typeof payload).toBe("string");
if (typeof payload !== "string") throw new Error("Expected JSON failure payload");
expect(JSON.parse(payload)).toMatchObject({ ok: false, error: "required extraction failed" });
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
+34
View File
@@ -3,6 +3,24 @@ import { defineCommand } from "citty";
import { resolve } from "node:path";
import type { Example } from "./_examples.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { diag } from "../ui/diagnostics.js";
import type { CapturePhaseProgress } from "../capture/types.js";
const CAPTURE_PHASE_PREFIX = "HYPERFRAMES_CAPTURE_PHASE ";
function emitCapturePhase(event: CapturePhaseProgress): void {
diag.notice(`${CAPTURE_PHASE_PREFIX}${JSON.stringify(event)}`);
}
function parseCaptureBudget(raw: string | undefined): number | undefined {
if (raw === undefined) return undefined;
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed <= 0) {
console.error("--capture-budget must be a positive integer in milliseconds.");
failCommand();
}
return parsed;
}
export const examples: Example[] = [
["Capture a website into ./capture/", "hyperframes capture https://stripe.com"],
@@ -39,6 +57,11 @@ export default defineCommand({
description: "Skip downloading assets (images, SVGs)",
default: false,
},
"skip-vision": {
type: "boolean",
description: "Skip optional AI image captioning",
default: false,
},
"max-screenshots": {
type: "string",
description: "Maximum screenshots to capture (default: 24)",
@@ -47,6 +70,11 @@ export default defineCommand({
type: "string",
description: "Page load timeout in ms (default: 120000)",
},
"capture-budget": {
type: "string",
description:
"Cooperative post-navigation budget in ms (default: 120000), separate from page-load --timeout; not a hard wall-clock timeout and cannot interrupt already-started native/core work",
},
json: {
type: "boolean",
description: "Output JSON (for AI agents / programmatic use)",
@@ -99,6 +127,8 @@ export default defineCommand({
failCommand();
}
const captureBudgetMs = parseCaptureBudget(args["capture-budget"] as string | undefined);
const isDefaultOutput = !args.output;
let outputName = (args.output as string | undefined) ?? "capture";
let outputDir = resolve(outputName);
@@ -139,11 +169,14 @@ export default defineCommand({
url,
outputDir,
skipAssets: args["skip-assets"] as boolean,
skipVision: args["skip-vision"] as boolean,
maxScreenshots: args["max-screenshots"]
? parseInt(args["max-screenshots"] as string)
: undefined,
timeout: args.timeout ? parseInt(args.timeout as string) : undefined,
postNavigationBudgetMs: captureBudgetMs,
json: isJson,
onPhase: emitCapturePhase,
},
isJson
? undefined
@@ -179,6 +212,7 @@ export default defineCommand({
fontsDetailed: result.tokens.fonts,
animations: result.animationCatalog?.summary,
warnings: result.warnings,
lastPhase: result.lastPhase,
},
null,
2,
+4 -4
View File
@@ -26,7 +26,7 @@
"files": 121
},
"hyperframes-cli": {
"hash": "42b621ca580541b6",
"hash": "3eab4c5fc1ae8e26",
"files": 11
},
"hyperframes-core": {
@@ -50,7 +50,7 @@
"files": 152
},
"motion-graphics": {
"hash": "0212a19069119e72",
"hash": "50db172cad89b1c7",
"files": 23
},
"music-to-video": {
@@ -62,8 +62,8 @@
"files": 30
},
"product-launch-video": {
"hash": "a0f6b1f4c8131ed2",
"files": 27
"hash": "01fc75da8492f749",
"files": 28
},
"remotion-to-hyperframes": {
"hash": "3a0e6c2affb9f74e",
@@ -37,12 +37,32 @@ npx hyperframes capture https://stripe.com # scaffold from a we
npx hyperframes capture https://linear.app -o linear-video # custom output directory
npx hyperframes capture https://example.com --json # JSON output for agents
npx hyperframes capture https://example.com --skip-assets # skip image/SVG download
npx hyperframes capture https://example.com --skip-vision # skip optional AI captions
npx hyperframes capture https://example.com --max-screenshots 12
npx hyperframes capture https://example.com --timeout 60000 # page-load timeout in ms
npx hyperframes capture https://example.com --capture-budget 90000 # post-navigation budget
```
Captures a live URL as an editable HyperFrames project: screenshots become layered scenes, assets are downloaded locally, and the result is a normal project you can `lint` / `preview` / `render`. Use this when the user supplies a URL as the starting point for a video.
`--timeout` bounds page navigation; `--capture-budget` is the separate cooperative budget for work
after navigation (fonts, assets, vision, and contact sheets). The latter is not a hard wall-clock
watchdog and cannot interrupt native work already in flight. An outer caller deadline is therefore a
third, distinct timeout. An outer caller timeout leaves the capture result unknown; it does not prove
HyperFrames hung or that the navigation timeout should be increased. Preserve the last phase and
classify the boundary that fired. `--skip-vision` disables only optional AI image captioning.
For agents, use `--json`. The result includes `ok`, warnings, and `lastPhase`. The command also emits
stable `HYPERFRAMES_CAPTURE_PHASE` records so a watchdog can report the last started, completed, or
degraded phase without retaining sensitive payloads.
Treat a non-zero exit, JSON `ok: false`, or an output `BLOCKED.md` as a **hard stop**. Do not render,
build, or infer brand/design data from partial files in a blocked capture. A successful capture may
degrade an optional phase within budget, but its structural output still has to satisfy the owning
workflow's gate. Exit zero and file existence alone are not semantic success: require the current
invocation's JSON `ok: true`, no `BLOCKED.md`, and artifacts usable for that workflow. Run each retry
into a fresh output directory; never merge or reuse a blocked attempt's partial output.
## skills
```bash
@@ -4,7 +4,16 @@
## Source (Step 2)
Fetch the page via `hyperframes capture` (DOM + screenshots) or a provided screenshot → frozen project-local image(s)/DOM. `asset_needs`: `{ kind: web, source: <url>, treatment: none }`.
Fetch the page via `hyperframes capture --json` (DOM + screenshots) or a provided screenshot → frozen project-local image(s)/DOM. `asset_needs`: `{ kind: web, source: <url>, treatment: none }`.
Inspect the capture result before building. If `BLOCKED.md` exists, JSON reports `ok: false`, or the
command exits non-zero, stop the URL-capture path and report the reason. Continue with a provided
screenshot only when it was an explicit source from the user (or the user explicitly chooses it
after the failure). Do not animate a blocked partial capture, invent missing DOM, or eyeball element
coordinates from protection/challenge pages.
This web need cannot use the generic asset-free fallback: it requires a usable captured screenshot
or DOM, or a provided screenshot explicitly selected by the user. If none is available, stop.
## Vocabulary / leans on
+23 -3
View File
@@ -52,15 +52,35 @@ Goal: Collect the source material, brand signals, and usable assets for the vide
Classify the input and choose the path. Explicit URL -> capture it and use the site for narration and assets. Pasted script/brief -> save verbatim as `user_script.txt`; `VO_MODE` (verbatim or restructured) comes from `BRIEF.md` — the intent layer asks it when a script arrives (ask once here only if the brief somehow lacks it). Then resolve capture target: URL in text -> use it; brand name only -> `WebSearch`, confirm URL in one line, then crawl; no URL/site (or the brief says don't scrape) -> no-capture path.
Run capture with: `npx hyperframes capture "<URL>" -o ./capture`
Run capture with: `npx hyperframes capture "<URL>" -o ./capture --json`. Keep the default
post-navigation budget unless the caller owns a smaller deadline; then pass a positive
`--capture-budget <milliseconds>` that leaves time for downstream work. `--timeout` controls page
navigation only. Use `--skip-vision` only when optional image captioning is intentionally disabled.
For a site tour or show-it-as-is brief, the captured page is the visual source of truth. Use the real screenshot instead of rebuilding the full website in HTML. If the shot needs internal movement, keep the screenshot as the base and overlay real captured assets at measured positions, or rebuild only the one component that moves. For a scroll shot, animate the viewport over `capture/screenshots/full-page.png` — the 1x plate of the whole document, pixel-exact for a 1920-wide viewport travelling down it. It is absent when the page was too tall to capture in one piece; fall back to the overlapping scroll-position shots in the same directory. Pushing in past 1:1 wants its own 2x capture of that region instead, since the plate has no headroom above 1x. Recreate the whole page only when the user explicitly asks for a stylized interpretation or the capture is unusable.
Inspect the command result and output directory immediately. A non-zero exit, JSON `ok: false`, or
`capture/BLOCKED.md` is a **hard stop** for the capture path: report the recorded reason and do not
consume partial screenshots, DOM, tokens, or assets. Do not manufacture a synthetic no-capture
fallback after a failed URL capture. Continue through the no-capture path only when the original
brief supplied the source material, or when the user explicitly switches to a provided screenshot
or brief after the failure.
Warnings such as `very little text content` together with an empty asset catalog are not proof of a
usable page. For a site tour or show-it-as-is brief, require trustworthy captured structure or a
provided screenshot; if neither exists, stop. Do not invent or rebuild the page merely because the
capture is unusable.
For a site tour or show-it-as-is brief, the captured page is the visual source of truth. Use the real screenshot instead of rebuilding the full website in HTML. If the shot needs internal movement, keep the screenshot as the base and overlay real captured assets at measured positions, or rebuild only the one component that moves. For a scroll shot, animate the viewport over `capture/screenshots/full-page.png` — the 1x plate of the whole document, pixel-exact for a 1920-wide viewport travelling down it. It is absent when the page was too tall to capture in one piece; fall back to the overlapping scroll-position shots in the same directory. Pushing in past 1:1 wants its own 2x capture of that region instead, since the plate has no headroom above 1x. Recreate the whole page only when the user explicitly asks for a stylized interpretation; an unusable capture alone is not authorization.
If `GEMINI_API_KEY`, `GOOGLE_API_KEY`, or an OpenRouter key exists, capture auto-captions assets into `capture/extracted/asset-descriptions.md`. This is not a review gate. Without a vision key, use DOM context and continue.
No-capture path: create `capture/extracted/tokens.json`, `capture/extracted/visible-text.txt`, `capture/extracted/asset-descriptions.md`, and `capture/assets/` by hand. `tokens.json` should be `{ "title": "", "description": "", "colors": [], "fonts": [] }`; fill title/description from the brief when possible. `visible-text.txt` contains the full brief or script. `asset-descriptions.md` should say no assets were captured unless the user gave asset notes.
**Gate:** `capture/extracted/tokens.json`, `capture/extracted/visible-text.txt`, `capture/extracted/asset-descriptions.md`, and `capture/assets/` exist; you can state the brand in one clear sentence. Treat `asset-descriptions.md` as the main asset inventory. If it is missing after real capture, stop and report capture incomplete. If `capture/BLOCKED.md` exists, follow it.
**Gate:** capture JSON reported `ok: true`; `capture/BLOCKED.md` does not exist;
`capture/extracted/tokens.json`, `capture/extracted/visible-text.txt`,
`capture/extracted/asset-descriptions.md`, and `capture/assets/` exist; and you can state the brand in
one clear sentence. Treat `asset-descriptions.md` as the main asset inventory. If it is missing after
real capture, stop and report capture incomplete. Warnings about a degraded optional phase are
acceptable only when this structural gate still passes.
---
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { fileURLToPath } from "node:url";
function read(relativePath) {
return readFileSync(fileURLToPath(new URL(relativePath, import.meta.url)), "utf8");
}
test("product launch capture treats blocked output as a hard gate", () => {
const skill = read("../SKILL.md");
assert.match(skill, /hyperframes capture[^\n]+--json/);
assert.match(skill, /capture\/BLOCKED\.md[^\n]+hard stop/i);
assert.match(skill, /do not[\s\S]{0,120}synthetic[\s\S]{0,120}fallback/i);
assert.match(skill, /very little text[\s\S]{0,180}empty asset/i);
assert.match(skill, /show-it-as-is[\s\S]{0,240}provided screenshot/i);
});
test("CLI capture reference documents the two budgets and machine diagnostics", () => {
const reference = read("../../hyperframes-cli/references/init-and-scaffold.md");
assert.match(reference, /--capture-budget/);
assert.match(reference, /--skip-vision/);
assert.match(reference, /HYPERFRAMES_CAPTURE_PHASE/);
assert.match(reference, /BLOCKED\.md[^\n]+hard stop/i);
assert.match(reference, /--timeout[^\n]+navigation[^\n]+--capture-budget/i);
assert.match(reference, /fresh output directory/i);
assert.match(reference, /outer caller timeout[\s\S]{0,180}does not prove/i);
});
test("webpage motion workflow refuses blocked capture artifacts", () => {
const module = read("../../motion-graphics/categories/webpage/module.md");
assert.match(module, /BLOCKED\.md[\s\S]{0,120}stop/i);
assert.match(module, /provided[\s\S]{0,120}screenshot[\s\S]{0,120}explicit/i);
assert.match(module, /do not[^\n]+blocked[^\n]+capture/i);
assert.match(module, /asset-free fallback/i);
});