Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
refactor(inspector)!: drop the predefined agent tools; harnesses define their own (#5570)
Xuanru Liabe97f6e4c70
diff --git a/packages/inspector/INSPECT-TIMELINE.md b/packages/inspector/INSPECT-TIMELINE.mddeleted file mode 100644index 846fad55b8..0000000000--- a/packages/inspector/INSPECT-TIMELINE.md+++ /dev/null@@ -1,44 +0,0 @@-# inspect_timeline--The existing inspector MCP server exposes `inspect_timeline` beside `inspect_components`.-Both share one browser, page, source fingerprint and generation. This query does not seek,-render images or alter authored files. The original component tool and its time/seek semantics-are unchanged.--Inputs: optional `component` (`{selector}`, `{hfId}` or `{ref}`, identical target resolution),-and at most one of `at`, `range: [start,end]`, `boundary`. All times are **global seconds**.-Selectors must match exactly one element; ambiguity returns candidates. Omit component to-inspect all registered HF timelines. Omit time for observed schedule overview.-`at` uses start-inclusive/end-exclusive intervals; `range` uses half-open intersection and-preserves full event times. `boundary` separately labels `crosses`, `starts`, `ends`, and-zero-duration `instant`, with a 1e-7-second endpoint tolerance.--Results are short text grouped by component, containing event time, target, properties and-source locations. `generation` and `offset` provide 60-group continuation. Refs expire on source-changes/page disposal. Component inspection can retrieve complete source blocks from those refs.-Overlapping targets/properties are reported as facts, never diagnosed as errors.--HF's existing timing resolver handles explicit HF item windows. GSAP parent-chain intervals-expand repeat/yoyo/timeScale, including repeatDelay. Stagger/internal timeline intervals are expanded per target, so gaps are not reported as active. Root HF timelines-are normally paused and use the player's global clock. No extra host offset is added to the-auto-nested GSAP parent chain.--Coverage: only currently registered DOM-target GSAP animations and explicit HF items. Callbacks,-object tweens, unexecuted paths and non-GSAP animation systems are not inspected. Scheduled-activity does not imply visibility inside a scene. Infinite/>1000 repeats, zero-speed/paused-nested animations and expansion limits report incomplete coverage, not a guessed answer.--## CLI--Existing unfiltered `hyperframes timeline` stays unchanged. Runtime queries use the existing-service specified by `HF_INSPECT_URL` (must belong to the same project):--```-cd PROJECT-hyperframes timeline --component '#title' --boundary 7.9-hyperframes timeline --range 7,8-hyperframes timeline --component '{"hfId":"title-hf"}' --at 7.9-```--The CLI does not start a new browser. Start the existing inspector service once through the-harness or `bun packages/inspector/src/server.ts PROJECT`; use its returned local URL.diff --git a/packages/inspector/README.md b/packages/inspector/README.mdindex 3c83e7187e..d11af9a216 100644--- a/packages/inspector/README.md+++ b/packages/inspector/README.md@@ -2,7 +2,7 @@Recover original HTML/CSS/GSAP context for **known elements before an edit**. This is not a video check, screenshot, diff, or affected-component verifier. It combines the I002 runtime/compiler provenance approach with the I003 HF-owned service boundary. The agent adapter holds no DOM or animation state.-This source-only experimental package is private. It does not modify the shared installation or register itself in a harness. Base: HF 0.8.127, commit `b3d2b82fe`.+Published as `@hyperframes/inspector`. It does not modify the shared installation or register itself in a harness.## Start@@ -17,13 +17,9 @@ export HF_INSPECT_CHROME=/absolute/path/to/chromebun packages/inspector/src/server.ts /absolute/video/project```-The service prints its loopback URL. Starting it does **not** start a browser. First inspection loads the project once. Configure the harness's MCP server to execute:+The service prints its loopback URL. Starting it does **not** start a browser. First inspection loads the project once.-```sh-HF_INSPECT_URL=http://127.0.0.1:PRINTED_PORT bun packages/inspector/src/mcp.ts-```--Tool: `inspect_components`. Direct HTTP equivalent: `POST /inspect` with the same JSON. The service is bound to one project at startup, so no per-call project path is needed. `GET /info` returns project identity and startup/query counters. Stop with SIGINT/SIGTERM; the service disposes its own pages/browser.+The package ships the capability, not agent tools: a harness defines its own tool names, descriptions and schemas, and calls `POST /inspect` with the JSON below. The service is bound to one project at startup, so no per-call project path is needed. `GET /info` returns project identity and startup/query counters. Stop with SIGINT/SIGTERM; the service disposes its own pages/browser.## Input@@ -83,7 +79,25 @@ Code blocks are atomic. `omitted`, `omittedCount`, and `nextOffset` describe mis`maxBytes` can be raised explicitly (2,048–256,000). A block larger than the budget is not cut in half: request that ID with a larger budget or read its file/range. Pagination can therefore remain at the same offset until the budget increases. Old-generation continuations are rejected.-Full runtime evidence is only available by an explicit HTTP request with `debug: true`; it is deliberately not part of the agent tool schema or its default output budget.+Full runtime evidence is only available by an explicit HTTP request with `debug: true`; it is deliberately not part of the default request or its output budget.++## Timeline++`POST /timeline` answers which animations are scheduled when, from the same browser, page and generation as `/inspect`. It never seeks, renders or edits files.++```json+{ "component": { "selector": "#title" }, "boundary": 7.9 }+```++`component` is optional and resolves like an `/inspect` target; omit it for every registered HF timeline. Give at most one of `at`, `range: [start, end]` or `boundary`, in global seconds; omit all three for the schedule overview. Results are short text grouped by component, with event times, targets, properties and source locations; `generation` and `offset` page through them. Coverage is registered DOM-target GSAP animations and explicit HF items only; anything outside that, or past the expansion limits, is reported as incomplete coverage rather than guessed.++## Element map++`POST /element-map` returns the composition's element map from the same page. It reads no query fields. A project with no `index.html` answers `404` `{ "error": "no-composition", "code": "no-composition" }`.++## Errors++Every refusal is JSON `{ "error", "code" }`. `code` is the stable token (`no-composition`, `stale_generation`, `source_changed_during_query`, `request_too_large`); a sentence with no token is `invalid_request`. A missing browser is `503` `browser_unavailable`, and an unexpected failure is `500` `internal_error`. Importing the module does not listen; `createInspectorServer(project)` builds one. An unknown route is `404` `{ "error": "not_found", "code": "not_found" }`. `GET /info` adds `version`, this package's version. The process listens on `127.0.0.1` and refuses a `Host` that is not loopback, so a rebinding request cannot read the project path. Install the server with the package: `hyperframes-inspector <project> [port]`, or `node dist/server.js`.## Lifecycle and overheaddiff --git a/packages/inspector/build.mjs b/packages/inspector/build.mjsindex fff000526c..7ddf9f223f 100644--- a/packages/inspector/build.mjs+++ b/packages/inspector/build.mjs@@ -25,8 +25,23 @@ const node = { bundle: true, platform: "node", format: "esm", target: "node22",await Promise.all([build({ ...node, entryPoints: [at("./src/live.ts")], outfile: at("./dist/live.js") }),build({ ...node, entryPoints: [at("./src/service.ts")], outfile: at("./dist/service.js") }),- build({ ...node, entryPoints: [at("./src/server.ts")], outfile: at("./dist/server.js") }),- build({ ...node, entryPoints: [at("./src/mcp.ts")], outfile: at("./dist/mcp.js") }),+ build({+ ...node,+ entryPoints: [at("./src/server.ts")],+ outfile: at("./dist/server.js"),+ banner: { js: `#!/usr/bin/env node\n${banner.js}` },+ plugins: [+ {+ name: "external-service",+ setup(build) {+ build.onResolve({ filter: /^\.\/service$/ }, () => ({+ path: "./service.js",+ external: true,+ }));+ },+ },+ ],+ }),build({entryPoints: [at("./src/liveRuntime.ts")],outfile: at("./dist/inspection.js"),diff --git a/packages/inspector/package-subpaths.json b/packages/inspector/package-subpaths.jsonindex 4bd50db91a..de23b68c53 100644--- a/packages/inspector/package-subpaths.json+++ b/packages/inspector/package-subpaths.json@@ -15,6 +15,14 @@},"types": "./dist/types/inspector/src/live.d.ts","environments": ["node"]+ },+ "./server": {+ "source": "./src/server.ts",+ "runtime": {+ "default": "./dist/server.js"+ },+ "types": "./dist/types/inspector/src/server.d.ts",+ "environments": ["bun", "node"]}}}diff --git a/packages/inspector/package.json b/packages/inspector/package.jsonindex 4c4a33fd28..feb619e85b 100644--- a/packages/inspector/package.json+++ b/packages/inspector/package.json@@ -6,9 +6,13 @@"url": "https://github.com/heygen-com/hyperframes","directory": "packages/inspector"},+ "bin": {+ "hyperframes-inspector": "./dist/server.js"+ },"files": ["dist/service.js","dist/live.js",+ "dist/server.js","dist/inspection.js","dist/types","README.md"@@ -24,6 +28,12 @@"./live": {"types": "./dist/types/inspector/src/live.d.ts","default": "./dist/live.js"+ },+ "./server": {+ "bun": "./src/server.ts",+ "import": "./src/server.ts",+ "types": "./src/server.ts",+ "default": "./dist/server.js"}},"publishConfig": {@@ -36,6 +46,10 @@"./live": {"types": "./dist/types/inspector/src/live.d.ts","default": "./dist/live.js"+ },+ "./server": {+ "types": "./dist/types/inspector/src/server.d.ts",+ "default": "./dist/server.js"}}},@@ -44,7 +58,6 @@"test": "vitest run","typecheck": "tsc --noEmit","serve": "bun run build && bun src/server.ts",- "mcp": "bun run build && bun src/mcp.ts","test:timeline": "bun tests/timeline.ts","test:timeline-compositions": "bun tests/timelineCompositions.ts","test:live": "bun run build && bun tests/live.ts",diff --git a/packages/inspector/src/live.ts b/packages/inspector/src/live.tsindex 2ba8d077ec..3934be30c5 100644--- a/packages/inspector/src/live.ts+++ b/packages/inspector/src/live.ts@@ -100,5 +100,11 @@ export function previewGeneration(runner: PageRunner): Promise<string | null> {}export { fingerprint } from "./sources";-export { componentsTool, timelineTool, toolContent, type InspectionTool } from "./tools";-export type { ComponentReport, ElementMapReport, PageRunner, TimelineReport };+export type {+ ComponentReport,+ ElementMapReport,+ InspectRequest,+ PageRunner,+ TimelineReport,+ TimelineRequest,+};diff --git a/packages/inspector/src/mcp.ts b/packages/inspector/src/mcp.tsdeleted file mode 100644index 2ded5924d9..0000000000--- a/packages/inspector/src/mcp.ts+++ /dev/null@@ -1,68 +0,0 @@-import { createInterface } from "node:readline";-import { componentsTool, timelineTool as timelineDefinition, toolContent } from "./tools";--const url = process.env.HF_INSPECT_URL;-if (!url || !/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(url))- throw new Error("Set HF_INSPECT_URL to the local HF inspection service URL.");-const tool = { name: "inspect_components", ...componentsTool };-const timelineTool = { name: "inspect_timeline", ...timelineDefinition };-const input = createInterface({ input: process.stdin });-for await (const line of input) {- let id: string | number | null = null;- try {- const message = JSON.parse(line);- if (message.id == null) continue;- id = message.id;- let result: unknown;- if (message.method === "initialize")- result = {- protocolVersion: "2024-11-05",- capabilities: { tools: {} },- serverInfo: { name: "hyperframes-inspector", version: "0.1.0" },- };- else if (message.method === "ping") result = {};- else if (message.method === "tools/list") result = { tools: [tool, timelineTool] };- else if (- message.method === "tools/call" &&- [tool.name, timelineTool.name].includes(message.params?.name)- ) {- const response = await fetch(- `${url}/${message.params.name === timelineTool.name ? "timeline" : "inspect"}`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(message.params.arguments),- signal: AbortSignal.timeout(60_000),- },- );- const body = await response.text();- result = response.ok- ? {- ...toolContent(- message.params.name === timelineTool.name ? "timeline" : "components",- JSON.parse(body),- ),- isError: false,- }- : { content: [{ type: "text", text: body }], isError: true };- } else {- process.stdout.write(- JSON.stringify({- jsonrpc: "2.0",- id: message.id,- error: { code: -32601, message: "Method not found" },- }) + "\n",- );- continue;- }- process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\n");- } catch (error) {- process.stdout.write(- JSON.stringify({- jsonrpc: "2.0",- id,- error: { code: -32603, message: error instanceof Error ? error.message : String(error) },- }) + "\n",- );- }-}diff --git a/packages/inspector/src/outputSchemas.ts b/packages/inspector/src/outputSchemas.tsdeleted file mode 100644index 1bd2257931..0000000000--- a/packages/inspector/src/outputSchemas.ts+++ /dev/null@@ -1,98 +0,0 @@-const string = { type: "string" };-const number = { type: "number" };-const boolean = { type: "boolean" };-const array = (items: object) => ({ type: "array", items });-const nullable = (schema: object) => ({ oneOf: [schema, { type: "null" }] });-const object = (properties: Record<string, object>, optional: string[] = []) => ({- type: "object",- properties,- required: Object.keys(properties).filter((key) => !optional.includes(key)),- additionalProperties: false,-});-const element = object({- ref: string,- tag: string,- id: string,- hfId: nullable(string),- classes: array(string),- composition: nullable(string),-});-const snippet = object({- id: string,- file: string,- startLine: number,- endLine: number,- kind: array(string),- targets: array(number),- code: string,- uniqueInFile: boolean,-});-export const componentOutputSchema = object(- {- generation: string,- sourceVersion: string,- reused: boolean,- visualState: object({ time: number, duration: number }, ["time", "duration"]),- results: array(- object({- target: number,- status: {- type: "string",- enum: ["found", "missing", "ambiguous", "stale-ref", "invalid-selector"],- },- candidates: array(element),- candidatesOmitted: number,- animations: number,- coTargets: array(element),- unmappedAnimations: number,- scopeTruncated: boolean,- }),- ),- snippets: array(snippet),- omitted: array(object({ id: string, bytes: number })),- omittedCount: number,- nextOffset: nullable(number),- coverage: array(string),- recordLimitReached: boolean,- hooked: boolean,- debugAvailable: boolean,- elapsedMs: number,- },- ["visualState"],-);-const declaredValue = object({- kind: { type: "string", enum: ["literal", "relative", "expression", "unknown"] },- value: { oneOf: [number, string, { type: "null" }] },-});-const animationValues = object({- basis: { type: "string", enum: ["authored-tween"] },- properties: array(object({ property: string, from: declaredValue, to: declaredValue })),- ease: declaredValue,-});-export const timelineOutputSchema = object({- text: string,- generation: string,- reused: boolean,- status: string,- candidates: array(element),- events: array(- object(- {- kind: { type: "string", enum: ["animation", "item"] },- relation: string,- component: nullable(element),- targets: array(element),- properties: array(string),- values: animationValues,- start: number,- end: number,- sources: array(object({ file: string, line: number })),- },- ["values"],- ),- ),- eventCount: number,- groupCount: number,- nextOffset: nullable(number),- warnings: array(string),-});diff --git a/packages/inspector/src/server.ts b/packages/inspector/src/server.tsindex 107df68e3b..215f183596 100644--- a/packages/inspector/src/server.ts+++ b/packages/inspector/src/server.ts@@ -1,68 +1,156 @@-import { createServer } from "node:http";+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";+import { readFileSync, realpathSync } from "node:fs";+import { pathToFileURL } from "node:url";import { Inspector } from "./service";import type { InspectRequest } from "./types";-const project = process.argv[2];-if (!project)- throw new Error("Usage: server PROJECT [PORT] (bun src/server.ts, or node dist/server.js)");-const inspector = new Inspector(project);-const server = createServer(async (req, res) => {- res.setHeader("Content-Type", "application/json");- if (req.headers.origin) {- res.writeHead(403).end(JSON.stringify({ error: "browser_origin_not_allowed" }));- return;+const version = (+ JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as {+ version: string;}- if (req.method === "GET" && req.url === "/info") {- res.end(- JSON.stringify({- project: inspector.project,- capability: "inspect_components",- stats: inspector.stats,- }),- );- return;- }- if (req.method !== "POST" || !["/inspect", "/timeline", "/element-map"].includes(req.url ?? "")) {- res.writeHead(404).end();- return;- }- try {+).version;+const MAX_BODY = 64_000;+const BROWSER_MISSING = "Set HF_INSPECT_CHROME";++function codeOf(message: string) {+ return /^[a-z][a-z0-9_-]*(?=:|$)/.exec(message)?.[0] ?? "invalid_request";+}++function send(res: ServerResponse, status: number, message: string) {+ res.writeHead(status).end(JSON.stringify({ error: message, code: codeOf(message) }));+}++function failureOf(error: unknown) {+ if (error instanceof TypeError) return { status: 500, message: "internal_error" };+ const message = error instanceof Error ? error.message : "internal_error";+ if (message.startsWith(BROWSER_MISSING)) return { status: 503, message: "browser_unavailable" };+ if (!(error instanceof Error)) return { status: 500, message: "internal_error" };+ return { status: message === "no-composition" ? 404 : 400, message };+}++function loopback(host: string | undefined) {+ if (!host) return true;+ const name = host+ .replace(/:\d+$/, "")+ .replace(/^\[|\]$/g, "")+ .toLowerCase();+ return name === "127.0.0.1" || name === "localhost" || name === "::1";+}++function readBody(req: IncomingMessage): Promise<Buffer | "too_large"> {+ return new Promise((resolve, reject) => {const chunks: Buffer[] = [];let size = 0;- for await (const chunk of req) {- size += chunk.length;- if (size > 64_000) throw new Error("request_too_large");- chunks.push(chunk);+ let settled = false;+ const finish = (value: Buffer | "too_large") => {+ if (settled) return;+ settled = true;+ resolve(value);+ };+ req.on("data", (chunk: Buffer | string) => {+ if (settled) return;+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ size += bytes.length;+ if (size > MAX_BODY) {+ settled = true;+ const done = () => resolve("too_large");+ req.on("end", done);+ req.on("error", done);+ req.resume();+ if (req.readableEnded) done();+ return;+ }+ chunks.push(bytes);+ });+ req.on("end", () => finish(Buffer.concat(chunks)));+ req.on("error", (error) => {+ if (!settled) reject(error);+ });+ });+}++export function createInspectorServer(project: string) {+ const inspector = new Inspector(project);+ const server = createServer(async (req, res) => {+ res.setHeader("Content-Type", "application/json");+ if (!loopback(req.headers.host)) {+ send(res, 403, "host_not_allowed");+ return;+ }+ if (req.headers.origin) {+ send(res, 403, "browser_origin_not_allowed");+ return;+ }+ if (req.method === "GET" && req.url === "/info") {+ res.end(+ JSON.stringify({+ project: inspector.project,+ version,+ capability: "inspection",+ stats: inspector.stats,+ }),+ );+ return;}- const request: InspectRequest = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");- if (req.url === "/element-map") res.end(JSON.stringify(await inspector.elementMap()));- else if (req.url === "/timeline") res.end(JSON.stringify(await inspector.timeline(request)));- else res.end(JSON.stringify(await inspector.inspect(request)));- } catch (error) {- res.writeHead(error instanceof Error && error.message === "no-composition" ? 404 : 400).end(- JSON.stringify({- error: error instanceof Error ? error.message : String(error),- ...(error instanceof Error && error.message === "no-composition"- ? { code: "no-composition" }- : {}),- }),- );+ if (+ req.method !== "POST" ||+ !["/inspect", "/timeline", "/element-map"].includes(req.url ?? "")+ ) {+ send(res, 404, "not_found");+ return;+ }+ try {+ const body = await readBody(req);+ if (body === "too_large") {+ send(res, 400, "request_too_large");+ return;+ }+ const request: InspectRequest = JSON.parse(body.toString("utf8") || "{}");+ if (req.url === "/element-map") res.end(JSON.stringify(await inspector.elementMap()));+ else if (req.url === "/timeline") res.end(JSON.stringify(await inspector.timeline(request)));+ else res.end(JSON.stringify(await inspector.inspect(request)));+ } catch (error) {+ const failure = failureOf(error);+ send(res, failure.status, failure.message);+ }+ });+ return { inspector, server };+}++function runCli() {+ const project = process.argv[2];+ if (!project)+ throw new Error("Usage: server PROJECT [PORT] (bun src/server.ts, or node dist/server.js)");+ const { inspector, server } = createInspectorServer(project);+ server.listen(Number(process.argv[3] ?? 0), "127.0.0.1", () => {+ const address = server.address();+ if (address && typeof address !== "string")+ console.log(+ JSON.stringify({+ url: `http://127.0.0.1:${address.port}`,+ project: inspector.project,+ }),+ );+ });+ async function close() {+ server.close();+ await inspector.dispose();+ }+ process.once("SIGINT", () => {+ void close();+ });+ process.once("SIGTERM", () => {+ void close();+ });+}++function launchedAsCli(entry: string | undefined) {+ if (!entry) return false;+ try {+ return import.meta.url === pathToFileURL(realpathSync(entry)).href;+ } catch {+ return false;}-});-server.listen(Number(process.argv[3] ?? 0), "127.0.0.1", () => {- const address = server.address();- if (address && typeof address !== "string")- console.log(- JSON.stringify({ url: `http://127.0.0.1:${address.port}`, project: inspector.project }),- );-});-async function close() {- server.close();- await inspector.dispose();}-process.once("SIGINT", () => {- void close();-});-process.once("SIGTERM", () => {- void close();-});++if (launchedAsCli(process.argv[1])) runCli();diff --git a/packages/inspector/src/service.ts b/packages/inspector/src/service.tsindex eb5b0a16dd..1c6dab1930 100644--- a/packages/inspector/src/service.ts+++ b/packages/inspector/src/service.ts@@ -51,7 +51,13 @@ export interface InspectorOptions {instrument?: boolean;}function chromePath() {- if (process.env.HF_INSPECT_CHROME) return process.env.HF_INSPECT_CHROME;+ const configured = process.env.HF_INSPECT_CHROME;+ if (configured) {+ if (existsSync(configured)) return configured;+ throw new Error(+ "Set HF_INSPECT_CHROME to an installed Chrome executable; inspection does not download a browser.",+ );+ }const root = join(homedir(), ".cache/hyperframes/chrome/chrome-headless-shell");if (existsSync(root))for (const version of readdirSync(root).sort().reverse()) {@@ -326,3 +332,5 @@ export class Inspector {});}}++export type { InspectRequest, TimelineRequest };diff --git a/packages/inspector/src/tools.ts b/packages/inspector/src/tools.tsdeleted file mode 100644index a4e08e4305..0000000000--- a/packages/inspector/src/tools.ts+++ /dev/null@@ -1,146 +0,0 @@-import { componentOutputSchema, timelineOutputSchema } from "./outputSchemas";--export interface InspectionTool {- readonly description: string;- readonly inputSchema: Record<string, unknown>;- readonly outputSchema: Record<string, unknown>;-}--const within = {- type: "string",- description: "Optional CSS selector restricting target lookup; omit for an unambiguous target.",-};-const target = {- oneOf: [- {- type: "object",- required: ["selector"],- additionalProperties: false,- properties: {- selector: { type: "string", description: "CSS selector, such as #title or .word." },- within,- },- },- {- type: "object",- required: ["hfId"],- additionalProperties: false,- properties: {- hfId: { type: "string", description: "Existing element data-hf-id value." },- within,- },- },- {- type: "object",- required: ["ref"],- additionalProperties: false,- properties: {- ref: {- type: "string",- description:- "Element ref returned by this inspector session; do not invent it. Rediscover after reload.",- },- },- },- ],-};-const generation = {- type: "string",- description:- "Generation returned by the previous query. Use for continuation; if stale, query targets again.",-};-const offset = {- type: "integer",- minimum: 0,- description: "Returned nextOffset for continuation; repeat the same query with its generation.",-};--export const componentsTool: InspectionTool = {- description:- "HyperFrames-native grep for element-related source. Retrieve related HTML/CSS/GSAP snippets with file paths and line numbers to understand, debug, or edit known elements without whole-file lookup. Batch targets. Shared code may affect other elements; unknown animation origins are explicit.",- inputSchema: {- type: "object",- required: ["targets"],- additionalProperties: false,- properties: {- targets: {- type: "array",- maxItems: 20,- description: "Batch 1–20 targets. Use an empty array only when retrieving snippets by ID.",- items: target,- },- descendants: {- type: "boolean",- default: true,- description: "Include source related to descendant elements.",- },- maxBytes: {- type: "integer",- minimum: 2048,- maximum: 256000,- default: 12000,- description:- "Response budget in bytes. Whole snippets may be omitted; use returned continuation data or increase the budget.",- },- snippets: {- type: "array",- items: { type: "string" },- description:- "Snippet IDs returned by a prior query; requires its generation. May use targets: [].",- },- generation,- offset,- time: {- type: "number",- minimum: 0,- description:- "Optional exact preview seek in global seconds. Does not filter animations by time; omit for ordinary source lookup.",- },- },- },- outputSchema: componentOutputSchema,-};--export const timelineTool: InspectionTool = {- description:- "HyperFrames-native structured search for animation timing and activity. Use to find animations by time or boundary, including when the target element is unknown. Return scheduled HF entries and observed DOM-target GSAP timing, targets, properties and source locations, not full source blocks. Use at, range or boundary (at most one); omit all for the full schedule. Does not seek. Callbacks and unexecuted animation code are outside coverage.",- inputSchema: {- type: "object",- additionalProperties: false,- properties: {- component: {- ...target,- description:- "Optional element/component scope including descendants; omit for the full project. Uses the same target format as the components tool.",- },- at: {- type: "number",- minimum: 0,- description:- "Global second: active scheduled intervals use start <= at < end; includes instantaneous actions at that time.",- },- range: {- type: "array",- items: { type: "number", minimum: 0 },- minItems: 2,- maxItems: 2,- description:- "Global [start, end) seconds, start < end. Return intersecting scheduled intervals and instantaneous actions inside the range.",- },- boundary: {- type: "number",- minimum: 0,- description:- "Global second: return only actions crossing, starting, ending or instantaneous here. Later stagger members are excluded. Group spans are not simultaneous per-target schedules; match target labels and member intervals before inferring overlap.",- },- generation,- offset,- },- },- outputSchema: timelineOutputSchema,-};--export function toolContent(tool: "components" | "timeline", report: object & { text?: string }) {- const text = tool === "timeline" && report.text ? report.text : JSON.stringify(report);- return { content: [{ type: "text" as const, text }], structuredContent: report };-}diff --git a/packages/inspector/tests/httpContract.test.ts b/packages/inspector/tests/httpContract.test.tsnew file mode 100644index 0000000000..a849534d70--- /dev/null+++ b/packages/inspector/tests/httpContract.test.ts@@ -0,0 +1,168 @@+import { spawn } from "node:child_process";+import { Agent, request as httpRequest } from "node:http";+import { mkdtempSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { expect, it } from "vitest";+import { createInspectorServer } from "../src/server";++const project = mkdtempSync(join(tmpdir(), "hf-inspector-"));++function start(env?: NodeJS.ProcessEnv) {+ const server = spawn("bun", ["src/server.ts", project, "0"], {+ cwd: new URL("..", import.meta.url).pathname,+ stdio: ["ignore", "pipe", "pipe"],+ env,+ });+ const lines = createInterface({ input: server.stdout! });+ const ready = new Promise<string>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("service startup timeout")), 10000);+ lines.once("line", (line) => {+ clearTimeout(timer);+ resolve(JSON.parse(line).url as string);+ });+ });+ return {+ url: ready,+ stop: async () => {+ server.kill("SIGTERM");+ await new Promise<void>((resolve) => server.once("exit", () => resolve()));+ lines.close();+ },+ };+}++it("answers info with a version, codes every refusal, and does not turn a large body into an empty 200", async () => {+ const server = start();+ try {+ const url = await server.url;+ const info = await (await fetch(url + "/info")).json();+ expect(info.capability).toBe("inspection");+ expect(info.version).toMatch(/^\d+\.\d+\.\d+/);+ const missing = await fetch(url + "/nope");+ expect(missing.status).toBe(404);+ expect(await missing.json()).toEqual({+ error: "not_found",+ code: "not_found",+ });+ // fetch refuses to send a foreign Host, so this one request is raw HTTP.+ const rebound = await new Promise<{ status: number; body: unknown }>((resolve, reject) => {+ const req = httpRequest(url + "/info", { headers: { host: "evil.example" } }, (res) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk) => chunks.push(chunk as Buffer));+ res.on("end", () =>+ resolve({+ status: res.statusCode ?? 0,+ body: JSON.parse(Buffer.concat(chunks).toString("utf8")),+ }),+ );+ });+ req.on("error", reject);+ req.end();+ });+ expect(rebound.status).toBe(403);+ expect(rebound.body).toEqual({+ error: "host_not_allowed",+ code: "host_not_allowed",+ });+ const oversized = await fetch(url + "/inspect", {+ method: "POST",+ body: "x".repeat(64_001),+ });+ expect(oversized.status).toBe(400);+ expect(await oversized.json()).toEqual({+ error: "request_too_large",+ code: "request_too_large",+ });+ const agent = new Agent({ keepAlive: true });+ const again = await new Promise<{ status: number }>((resolve, reject) => {+ const first = httpRequest(+ url + "/inspect",+ {+ method: "POST",+ agent,+ headers: { "content-type": "application/json" },+ },+ (res) => {+ res.resume();+ res.on("end", () => {+ const second = httpRequest(url + "/info", { agent }, (next) => {+ next.resume();+ resolve({ status: next.statusCode ?? 0 });+ });+ second.on("error", reject);+ second.end();+ });+ },+ );+ first.on("error", reject);+ first.end("x".repeat(64_001));+ });+ agent.destroy();+ expect(again.status).toBe(200);+ const empty = await fetch(url + "/inspect", {+ method: "POST",+ body: "null",+ });+ expect(empty.status).toBe(500);+ expect(await empty.json()).toEqual({+ error: "internal_error",+ code: "internal_error",+ });+ } finally {+ await server.stop();+ }+});++it("importing the server does not listen", () => {+ expect(typeof createInspectorServer).toBe("function");+});++it("starts when the entry path is a symlink", async () => {+ const dir = mkdtempSync(join(tmpdir(), "hf-bin-"));+ const link = join(dir, "hyperframes-inspector");+ symlinkSync(new URL("../src/server.ts", import.meta.url).pathname, link);+ const child = spawn("bun", [link, project, "0"], {+ cwd: new URL("..", import.meta.url).pathname,+ stdio: ["ignore", "pipe", "pipe"],+ });+ const lines = createInterface({ input: child.stdout! });+ try {+ const url = await new Promise<string>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("symlink entry did not listen")), 10000);+ lines.once("line", (line) => {+ clearTimeout(timer);+ resolve(JSON.parse(line).url as string);+ });+ child.once("exit", (code) => reject(new Error(`symlink entry exited ${code}`)));+ });+ expect((await fetch(url + "/info")).status).toBe(200);+ } finally {+ child.kill("SIGTERM");+ await new Promise<void>((resolve) => child.once("exit", () => resolve()));+ lines.close();+ }+});++it("a project with no browser answers 503 browser_unavailable", async () => {+ const home = mkdtempSync(join(tmpdir(), "hf-home-"));+ writeFileSync(join(project, "index.html"), "<!doctype html><html><body></body></html>");+ for (const env of [+ { ...process.env, HOME: home, HF_INSPECT_CHROME: "" },+ { ...process.env, HF_INSPECT_CHROME: join(home, "missing-chrome") },+ ]) {+ const server = start(env);+ try {+ const url = await server.url;+ const map = await fetch(url + "/element-map", { method: "POST", body: "{}" });+ expect(map.status).toBe(503);+ expect(await map.json()).toEqual({+ error: "browser_unavailable",+ code: "browser_unavailable",+ });+ } finally {+ await server.stop();+ }+ }+});diff --git a/packages/inspector/tests/outputSchemas.ts b/packages/inspector/tests/outputSchemas.tsdeleted file mode 100644index 19710ac64c..0000000000--- a/packages/inspector/tests/outputSchemas.ts+++ /dev/null@@ -1,95 +0,0 @@-import { spawn } from "node:child_process";-import { createInterface } from "node:readline";-import { mkdtempSync, writeFileSync, copyFileSync, rmSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import assert from "node:assert/strict";-const { assertSupportedJsonSchema, validateJsonSchemaValue, renderToolsSdk } = await import(- process.env.DSH_TOOLS_MODULE!-);-const project = mkdtempSync(join(tmpdir(), "hf-output-"));-copyFileSync(process.argv[2], join(project, "gsap.min.js"));-writeFileSync(- join(project, "index.html"),- `<html><head><script src="gsap.min.js"></script></head><body><div data-composition-id="root" data-duration="3" data-width="1920" data-height="1080"><h1 id="title">Hello</h1></div><script>const tl=gsap.timeline({paused:true});tl.to('#title',{x:100,duration:1},0);window.__timelines={root:tl};</script></body></html>`,-);-const server = spawn(- process.execPath,- [new URL("../src/server.ts", import.meta.url).pathname, project],- { stdio: ["ignore", "pipe", "inherit"] },-);-const lines = createInterface({ input: server.stdout! });-let client;-try {- const first = await new Promise<string>((resolve) => lines.once("line", resolve));- const { url } = JSON.parse(first);- client = spawn(process.execPath, [new URL("../src/mcp.ts", import.meta.url).pathname], {- env: { ...process.env, HF_INSPECT_URL: url },- stdio: ["pipe", "pipe", "inherit"],- });- const responses = createInterface({ input: client.stdout! });- let id = 0;- const pending = new Map();- responses.on("line", (line) => {- const r = JSON.parse(line);- pending.get(r.id)?.(r);- pending.delete(r.id);- });- const call = (method: string, params?: object) =>- new Promise<any>((resolve, reject) => {- const n = ++id;- pending.set(n, resolve);- client!.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: n, method, params }) + "\n");- setTimeout(() => reject(Error("timeout")), 30000).unref();- });- const {- result: { tools },- } = await call("tools/list");- for (const tool of tools) {- assertSupportedJsonSchema(tool.outputSchema);- const args =- tool.name === "inspect_components"- ? { targets: [{ selector: "#title" }] }- : { range: [0, 2] };- const { result } = await call("tools/call", { name: tool.name, arguments: args });- assert(!result.isError, JSON.stringify(result));- const validation = validateJsonSchemaValue(tool.outputSchema, result.structuredContent);- assert.deepEqual(validation, [], JSON.stringify(validation));- if (tool.name === "inspect_components")- assert.deepEqual(JSON.parse(result.content[0].text), result.structuredContent);- else assert.equal(result.content[0].text, result.structuredContent.text);- const selected =- tool.name === "inspect_components"- ? result.structuredContent.snippets.map((s: any) => s.file)- : result.structuredContent.events- .filter((e: any) => e.kind === "animation")- .map((e: any) => e.start);- assert(selected.length > 0);- const sdk = renderToolsSdk([- {- name: tool.name,- parameters: tool.inputSchema,- output: {- type: "object",- properties: { structuredContent: tool.outputSchema },- required: ["structuredContent"],- additionalProperties: false,- },- },- ]);- assert(!sdk.includes(`${tool.name}: unknown`));- console.log(tool.name, JSON.stringify(selected));- }- const bad = await call("tools/call", { name: "inspect_components", arguments: { targets: [] } });- assert(bad.result.isError);- assert(!("structuredContent" in bad.result));- console.log(- "PASS live browser/MCP output contracts, unchanged text, SDK types, field filtering, error response",- );-} finally {- client?.kill();- server.kill();- lines.close();- await new Promise((resolve) => server.once("exit", resolve));- rmSync(project, { recursive: true, force: true });-}diff --git a/packages/inspector/tests/transport.ts b/packages/inspector/tests/transport.tsindex 9a92a7951a..458a002559 100644--- a/packages/inspector/tests/transport.ts+++ b/packages/inspector/tests/transport.ts@@ -14,41 +14,16 @@ const [first] = await Promise.race([),]);const { url } = JSON.parse(first);-let client: ReturnType<typeof spawn> | undefined;try {const info = await (await fetch(url + "/info")).json();assert.equal(info.stats.browserStarts, 0);- client = spawn(process.execPath, ["run", new URL("../src/mcp.ts", import.meta.url).pathname], {- env: { ...process.env, HF_INSPECT_URL: url },- stdio: ["pipe", "pipe", "inherit"],+ const response = await fetch(url + "/inspect", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ targets: [{ selector: "#flow-title" }] }),});- const responses = createInterface({ input: client.stdout! });- const pending = new Map<number, (value: unknown) => void>();- responses.on("line", (line) => {- const value = JSON.parse(line);- pending.get(value.id)?.(value);- pending.delete(value.id);- });- const call = (id: number, method: string, params?: unknown) =>- new Promise<{ result: { content?: { text: string }[]; tools?: { name: string }[] } }>(- (resolve, reject) => {- pending.set(id, resolve as (value: unknown) => void);- client!.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");- setTimeout(() => reject(new Error("MCP call timeout")), 30000).unref();- },- );- await call(1, "initialize", {- protocolVersion: "2024-11-05",- capabilities: {},- clientInfo: { name: "test", version: "1" },- });- const list = await call(2, "tools/list");- assert.equal(list.result.tools?.[0].name, "inspect_components");- const inspected = await call(3, "tools/call", {- name: "inspect_components",- arguments: { targets: [{ selector: "#flow-title" }] },- });- const output = JSON.parse(inspected.result.content![0].text);+ const text = await response.text();+ const output = JSON.parse(text);assert.equal(output.results[0].status, "found");assert.equal(output.results[0].unmappedAnimations, 0);const next = await (await fetch(url + "/info")).json();@@ -57,14 +32,12 @@ try {console.log(JSON.stringify({http: true,- mcp: true,lazyBrowser: true,- bytes: Buffer.byteLength(inspected.result.content![0].text),+ bytes: Buffer.byteLength(text),stats: next.stats,}),);} finally {- client?.kill("SIGTERM");server.kill("SIGTERM");await new Promise<void>((resolve) => server.once("exit", () => resolve()));lines.close();diff --git a/packages/inspector/tsconfig.types.json b/packages/inspector/tsconfig.types.jsonindex 9feafe7c29..4a2984b3a1 100644--- a/packages/inspector/tsconfig.types.json+++ b/packages/inspector/tsconfig.types.json@@ -8,5 +8,5 @@"outDir": "dist/types"},"include": [],- "files": ["src/live.ts", "src/service.ts"]+ "files": ["src/live.ts", "src/service.ts", "src/server.ts"]}diff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjsindex 28bddb607f..38a34bf548 100644--- a/scripts/check-no-main-deletions.mjs+++ b/scripts/check-no-main-deletions.mjs@@ -48,7 +48,18 @@ const CATALOG_FONT_REASON =const DESIGN_NOTES_REASON ="plan and contract notes are working notes kept out of the repo; docs/contracts/ and docs/plans/ are gitignored";+const INSPECTOR_TOOLS_REASON =+ "the inspector ships the capability, not agent tools; each harness defines its own tool names, descriptions and schemas";+export const ALLOWED_DELETIONS = new Map([+ ["packages/inspector/src/mcp.ts", INSPECTOR_TOOLS_REASON],+ ["packages/inspector/src/outputSchemas.ts", INSPECTOR_TOOLS_REASON],+ ["packages/inspector/src/tools.ts", INSPECTOR_TOOLS_REASON],+ ["packages/inspector/tests/outputSchemas.ts", INSPECTOR_TOOLS_REASON],+ [+ "packages/inspector/INSPECT-TIMELINE.md",+ "described the deleted MCP tool; the README's Timeline section covers POST /timeline",+ ],["docs/public/catalog/vendor/BufferGeometryUtils.json","bundled into three-modules.json so catalog scripts run under the docs host policy",