diff --git a/docs/developers/catalog-search.mdx b/docs/developers/catalog-search.mdx index 4b4f99c187..6a0a7c4fb0 100644 --- a/docs/developers/catalog-search.mdx +++ b/docs/developers/catalog-search.mdx @@ -98,7 +98,8 @@ with vectors already on disk. The only network traffic is the one-time downloads of the catalog vectors, none of which carries your query. When a search finds nothing useful, the CLI prints a `hyperframes feedback --search-miss` command you -can run to report the gap. That command sends the query, and only if you run it. +can run to report the gap. That command sends the move you describe with `--wanted` and the tier, +never your query, and only if you run it. ## How the index is built diff --git a/packages/cli/src/commands/catalog.test.ts b/packages/cli/src/commands/catalog.test.ts index a36da5c5dd..9957c0c678 100644 --- a/packages/cli/src/commands/catalog.test.ts +++ b/packages/cli/src/commands/catalog.test.ts @@ -468,7 +468,7 @@ describe("catalog --json meaning search", () => { const envelope = await runEnvelope({ query: "number", words: "transition" }); expect(envelope.shown).toBe(1); - expect(envelope.report_gap).toContain("number"); + expect(envelope.query).toBe("number"); }); it("carries an on-device runtime failure into the JSON envelope", async () => { @@ -532,9 +532,9 @@ describe("catalog --json meaning search", () => { expect(envelope.shown).toBeGreaterThan(0); expect(envelope.report_gap).toBe( - 'npx hyperframes feedback --search-miss "make a number count up" ' + - '--wanted "" --tier on-device', + 'npx hyperframes feedback --search-miss --wanted "" --tier on-device', ); + expect(envelope.report_gap).not.toContain("make a number count up"); }); // fails without the fix: on Windows the envelope carried a bash-escaped line that runs "$(calc)" in PowerShell. @@ -693,50 +693,11 @@ describe("a zero-result search", () => { }); // Each one keeps a shell meaning in PowerShell or cmd.exe however it is double-quoted. -const WINDOWS_LIVE_QUERIES = [ - "$(calc)", - "a`b", - "o'neil $x", - "x\u201D;calc;\u201Dy", - "x\u2019;calc;\u2018 $y", - "$(calc)&calc", - "\u201Cquoted\u201D", - "%USERPROFILE%", - "50% off, 20% more", - "Hello!", - "a!b", - 'say "hi" & calc', -]; - describe("searchMissReport", () => { - it("keeps a non-ASCII query intact, on Windows and elsewhere", () => { - // Half of the gap reports received so far were CJK. A query mangled on the - // way into the command is a report nobody can act on. - for (const platform of ["win32", "linux"] as const) { - expect(searchMissReport("実写写真のみ 9:16 生活ハック", "on-device", platform)).toBe( - 'npx hyperframes feedback --search-miss "実写写真のみ 9:16 生活ハック" ' + - '--wanted "" --tier on-device', - ); - } - }); - - // fails without the fix: the query was put in a bash-escaped line on every platform, where a backslash escapes - // nothing in PowerShell or cmd.exe, so running the line ran part of the query. - it("never puts a query PowerShell or cmd.exe would read as code into a line on Windows", () => { - for (const query of WINDOWS_LIVE_QUERIES) { - const report = searchMissReport(query, "words", "win32"); - expect(report, query).not.toContain(query); - expect(report, query).not.toMatch(/^npx /); - expect(report, query).toContain("--tier words"); - } - }); - - it("quotes a query with shell syntax as one literal word for sh, bash and zsh", () => { - expect(searchMissReport('a "quoted" $VAR `sub` \\ thing!', "words", "linux")).toBe( - "npx hyperframes feedback --search-miss 'a \"quoted\" $VAR `sub` \\ thing!' " + - '--wanted "" --tier words', + it("names the tier and leaves the query out", () => { + expect(searchMissReport("on-device")).toBe( + 'npx hyperframes feedback --search-miss --wanted "" --tier on-device', ); - expect(searchMissReport("o'neil", "words", "darwin")).toContain(`--search-miss "o'neil"`); }); }); @@ -767,27 +728,22 @@ describe("catalog meaning search, on a terminal", () => { expect(output).toContain("None of these do it?"); expect(output).toContain("--tier words"); - expect(output).toContain('--search-miss "count up"'); + expect(output).toContain("--search-miss --wanted"); + expect(output).not.toContain('"count up"'); }); - // fails without the fix: the command was printed with the query rewritten, so pasting it reported other text. it.each([ ["some results", "count\nup"], ["no result", "zzqx\nyyqx"], - ])( - "explains the gap report in words when the query cannot be shown as typed: %s", - async (_n, query) => { - state.modelStatus = "declined"; - state.ranking = null; + ])("prints the same gap line whatever the query holds: %s", async (_n, query) => { + state.modelStatus = "declined"; + state.ranking = null; - const output = await runCatalog({ query }); + const output = await runCatalog({ query }); - expect(output).toContain( - "Run hyperframes feedback with your query as --search-miss, the move you needed as --wanted, and --tier words.", - ); - expect(output).not.toContain('--search-miss "'); - }, - ); + expect(output).toContain("--search-miss --wanted"); + expect(output).not.toContain(query); + }); it("offers the gap report on the on-device tier too", async () => { const output = await runCatalog({ query: "make a number count up" }); diff --git a/packages/cli/src/commands/catalog.ts b/packages/cli/src/commands/catalog.ts index e979127417..f7e6b793b8 100644 --- a/packages/cli/src/commands/catalog.ts +++ b/packages/cli/src/commands/catalog.ts @@ -26,7 +26,6 @@ import { relative, resolve } from "node:path"; import { CliUsageError, finishCommand } from "../utils/commandResult.js"; import { printFailureLine } from "../utils/jsonError.js"; import { isUnattended } from "../utils/attendedTerminal.js"; -import { shellArg } from "../utils/shellArg.js"; import { runAdd } from "./add.js"; import { hasNoSearchableTokens, searchByWords } from "../registry/localSearch.js"; import { @@ -343,7 +342,7 @@ export default defineCommand({ // Withheld when the query never parsed: the catalog has not been // shown to be missing anything, so inviting a gap report here // would file noise against a search that never ran. - ...(unsearchable ? {} : { report_gap: searchMissReport(query, tierToken(searched)) }), + ...(unsearchable ? {} : { report_gap: searchMissReport(tierToken(searched)) }), results: [], }, null, @@ -378,7 +377,7 @@ export default defineCommand({ if (query) { console.log(""); console.log(c.dim(" Nothing in the catalog does this? Report the gap:")); - console.log(c.dim(` ${searchMissReport(query, tierToken(searched))}`)); + console.log(c.dim(` ${searchMissReport(tierToken(searched))}`)); } } } @@ -416,7 +415,7 @@ export default defineCommand({ // plausible items and none of them did the thing — a judgement // only the reader can make, so the command has to already be in // the envelope by the time they make it. - report_gap: searchMissReport(query, tierToken(searched)), + report_gap: searchMissReport(tierToken(searched)), results: output, }, null, @@ -470,9 +469,7 @@ export default defineCommand({ // in. Every catalog gap reported to date came from the word tier. The // tier rides along in the command so a vocabulary miss stays // distinguishable from a meaning miss when the reports are read. - console.log( - c.dim(` None of these do it? ${searchMissReport(query, tierToken(searched))}`), - ); + console.log(c.dim(` None of these do it? ${searchMissReport(tierToken(searched))}`)); } } @@ -700,33 +697,11 @@ function tierDetail(searched: { localMode: LocalMode } | null): string { } /** - * The command that turns a fruitless search into a catalog gap report, or how - * to send one when no line would carry the query as typed in the user's shell. - * - * A search that returns nothing usable is the only moment anyone knows what - * the catalog is missing, and it was also the one moment we said nothing: - * `feedback --search-miss` was documented in the skill and printed by - * `feedback --help`, neither of which is open when a query comes back wrong. - * Handing back the exact line, with the query already in it, is the whole - * difference between a gap someone reports and a gap someone works around. - * - * Only the command is built here. Sending it stays a separate deliberate act, - * so plain `catalog --query` keeps its promise that the query text never - * leaves the machine. + * The line that reports a gap, ready to run. It names the move that was missing and the tier; + * the query is left out, so the searched words never leave the machine. */ -export function searchMissReport( - query: string, - tier: "on-device" | "words", - platform: NodeJS.Platform = process.platform, -): string { - const searched = shellArg(query, platform); - if (searched === null) { - return `Run hyperframes feedback with your query as --search-miss, the move you needed as --wanted, and --tier ${tier}.`; - } - return ( - `npx hyperframes feedback --search-miss ${searched} ` + - `--wanted "" --tier ${tier}` - ); +export function searchMissReport(tier: "on-device" | "words"): string { + return `npx hyperframes feedback --search-miss --wanted "" --tier ${tier}`; } type LocalMode = "local-model" | "words"; diff --git a/packages/cli/src/commands/feedback.test.ts b/packages/cli/src/commands/feedback.test.ts index b274f4f790..49d7675307 100644 --- a/packages/cli/src/commands/feedback.test.ts +++ b/packages/cli/src/commands/feedback.test.ts @@ -10,8 +10,9 @@ const mocks = vi.hoisted(() => ({ vi.mock("../telemetry/client.js", () => ({ shouldTrack: () => true, flush: mocks.flush })); const trackRenderFeedback = vi.hoisted(() => vi.fn()); const trackFeedbackComment = vi.hoisted(() => vi.fn()); +const trackCatalogSearchMiss = vi.hoisted(() => vi.fn()); vi.mock("../telemetry/events.js", () => ({ - trackCatalogSearchMiss: vi.fn(), + trackCatalogSearchMiss, trackFeedbackComment, trackRenderFeedback, })); @@ -26,7 +27,11 @@ vi.mock("../utils/submitFeedback.js", () => ({ it.each([ ["a rating", { rating: "8" }, mocks.submitFeedback], - ["a catalog search miss", { "search-miss": "typewriter" }, mocks.submitCatalogSearchMiss], + [ + "a catalog search miss", + { "search-miss": true, wanted: "typewriter" }, + mocks.submitCatalogSearchMiss, + ], ])("sends %s without waiting on the telemetry upload", async (_, args, submit) => { vi.spyOn(console, "log").mockImplementation(() => {}); const { default: feedback } = await import("./feedback.js"); @@ -34,6 +39,20 @@ it.each([ expect(submit).toHaveBeenCalled(); }); +it("reports a catalog gap by the move wanted, never the query that was searched", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}); + const { default: feedback } = await import("./feedback.js"); + const query = "typewriter that deletes"; + await feedback.run?.({ + args: { "search-miss": query, wanted: "text that types then backspaces", tier: "words" }, + } as never); + expect(mocks.submitCatalogSearchMiss).toHaveBeenLastCalledWith( + expect.objectContaining({ wanted: "text that types then backspaces", tier: "words" }), + ); + expect(JSON.stringify(mocks.submitCatalogSearchMiss.mock.lastCall)).not.toContain(query); + expect(JSON.stringify(trackCatalogSearchMiss.mock.calls)).not.toContain(query); +}); + it("tells person feedback from agent feedback, with the email only an app's env can attach", async () => { vi.spyOn(console, "log").mockImplementation(() => {}); vi.stubEnv("HYPERFRAMES_FEEDBACK_EMAIL", " person@example.com "); diff --git a/packages/cli/src/commands/feedback.ts b/packages/cli/src/commands/feedback.ts index 1890057d49..a64d15552b 100644 --- a/packages/cli/src/commands/feedback.ts +++ b/packages/cli/src/commands/feedback.ts @@ -40,7 +40,7 @@ export const examples: Example[] = [ ], [ "Report a catalog gap after a fruitless search", - 'hyperframes feedback --search-miss "typewriter that deletes" --wanted "text that types then backspaces"', + 'hyperframes feedback --search-miss --wanted "text that types then backspaces"', ], [ "Also file a GitHub issue with a published repro", @@ -52,6 +52,24 @@ function normalizeComment(raw?: string): string | undefined { return raw || undefined; } +async function reportSearchMiss(rawWanted?: string, rawTier?: string): Promise { + if (!shouldTrack()) { + console.log(c.dim("Telemetry is disabled. Nothing sent.")); + return; + } + const wanted = normalizeComment(rawWanted); + if (!wanted) { + console.error(c.error("Describe the move you needed with --wanted")); + failUsage(); + } + const tier = normalizeComment(rawTier); + trackCatalogSearchMiss({ wanted, tier }); + // Ack before the forward, which is best-effort and bounded, so the + // reporter is never left waiting on it. + console.log(c.dim("Logged the gap. Thanks — that is how the catalog grows.")); + await submitCatalogSearchMiss({ wanted, tier, cliVersion: VERSION }); +} + /** * Compact PostHog join keys appended to the environment string that rides * along with the forwarded report (and therefore lands verbatim in the wild @@ -289,8 +307,9 @@ export default defineCommand({ description: 'Who wrote the report: "person" or "agent"', }, "search-miss": { - type: "string", - description: "Report a catalog search that found nothing useful; pass the query you ran", + type: "boolean", + description: + "Report a catalog search that found nothing useful; describe the move with --wanted", }, wanted: { type: "string", @@ -326,21 +345,7 @@ export default defineCommand({ // A search miss is a different report from a rating: it names a gap in the // catalog rather than scoring an experience, so it carries no rating and // must not land in the same number. - const searchMiss = normalizeComment(args["search-miss"]); - if (searchMiss) { - if (!shouldTrack()) { - console.log(c.dim("Telemetry is disabled. Nothing sent.")); - return; - } - const wanted = normalizeComment(args.wanted); - const tier = normalizeComment(args.tier); - trackCatalogSearchMiss({ query: searchMiss, wanted, tier }); - // Ack before the forward, which is best-effort and bounded, so the - // reporter is never left waiting on it. - console.log(c.dim("Logged the gap. Thanks — that is how the catalog grows.")); - await submitCatalogSearchMiss({ query: searchMiss, wanted, tier, cliVersion: VERSION }); - return; - } + if (args["search-miss"]) return reportSearchMiss(args.wanted, args.tier); const comment = normalizeComment(args.comment); const rating = reportRating(args.rating, comment, args["file-issue"] === true); diff --git a/packages/cli/src/media-use/lib/freeze.test.mjs b/packages/cli/src/media-use/lib/freeze.test.mjs index ca633f8e8c..3659708590 100644 --- a/packages/cli/src/media-use/lib/freeze.test.mjs +++ b/packages/cli/src/media-use/lib/freeze.test.mjs @@ -1,9 +1,18 @@ import { strict as assert } from "node:assert"; -import { test } from "node:test"; +import { afterEach, beforeEach, test } from "node:test"; import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { isDirectMediaUrl, freezeUrl, freezeLocalFile } from "./freeze.mjs"; +import { mediaTransport } from "./media-fetch.mjs"; +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); const HOSTILE_SVG = '' + diff --git a/packages/cli/src/media-use/lib/heygen-video-provider.test.mjs b/packages/cli/src/media-use/lib/heygen-video-provider.test.mjs index d3dd240de0..dd80ef2f33 100644 --- a/packages/cli/src/media-use/lib/heygen-video-provider.test.mjs +++ b/packages/cli/src/media-use/lib/heygen-video-provider.test.mjs @@ -13,10 +13,19 @@ import { import http from "node:http"; import { tmpdir } from "node:os"; import { basename, dirname, join } from "node:path"; -import { test } from "node:test"; +import { afterEach, beforeEach, test } from "node:test"; import { HEYGEN_NOT_AUTHENTICATED_MESSAGE } from "./heygen-cli.mjs"; import { AVATAR_VIDEO_SIGNIN_MESSAGE } from "./heygen-video-provider.mjs"; import { discardPrivateOutput } from "./private-output.mjs"; +import { mediaTransport } from "./media-fetch.mjs"; +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); function cleanupDownload(localPath) { if ( diff --git a/packages/cli/src/media-use/lib/logo-provider.test.mjs b/packages/cli/src/media-use/lib/logo-provider.test.mjs index 35bcfb7960..d5046bab46 100644 --- a/packages/cli/src/media-use/lib/logo-provider.test.mjs +++ b/packages/cli/src/media-use/lib/logo-provider.test.mjs @@ -15,6 +15,17 @@ import { faviconSearch, } from "./logo-provider.mjs"; import { getProviders, runProviders } from "./registry.mjs"; +import { afterEach, beforeEach } from "node:test"; +import { mediaTransport } from "./media-fetch.mjs"; + +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); test("entityFrom strips filler words from the intent; --entity wins", () => { assert.equal(entityFrom("LinkedIn logo"), "linkedin"); diff --git a/packages/cli/src/media-use/lib/lut-preset-provider.test.mjs b/packages/cli/src/media-use/lib/lut-preset-provider.test.mjs index 84afebf18b..8d6aabb0eb 100644 --- a/packages/cli/src/media-use/lib/lut-preset-provider.test.mjs +++ b/packages/cli/src/media-use/lib/lut-preset-provider.test.mjs @@ -21,6 +21,17 @@ import { } from "./lut-preset-provider.mjs"; import { buildCube } from "./cube-build.mjs"; import { validateCube, validateCubeFile } from "./cube-validate.mjs"; +import { afterEach, beforeEach } from "node:test"; +import { mediaTransport } from "./media-fetch.mjs"; + +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); const REPO_ROOT = join(import.meta.dirname, "..", "..", "..", "..", ".."); diff --git a/packages/cli/src/media-use/lib/media-fetch.mjs b/packages/cli/src/media-use/lib/media-fetch.mjs index 7664c2af5f..71d376bcbf 100644 --- a/packages/cli/src/media-use/lib/media-fetch.mjs +++ b/packages/cli/src/media-use/lib/media-fetch.mjs @@ -1,9 +1,13 @@ // Media downloads use public HTTP(S) URLs. Validate every redirect target; // a provider result must meet the same host policy as a direct ingest URL. // Public HTTPS-to-HTTP redirects are allowed, matching direct HTTP support. -// This is a literal-host policy, not DNS pinning: DNS resolution remains trusted. +// A host name is resolved once and the connection dials that checked address. +import dns from "node:dns"; +import http from "node:http"; +import https from "node:https"; import { BlockList, isIP } from "node:net"; +import { Readable } from "node:stream"; const blocked = new BlockList(); for (const [network, prefix] of [ @@ -48,14 +52,73 @@ export function isPublicMediaUrl(value) { ) return false; const address = host.replace(/^\[|\]$/g, ""); - const family = isIP(address); - return family === 0 || !blocked.check(address, family === 4 ? "ipv4" : "ipv6"); + return isIP(address) === 0 || !isBlockedAddress(address); } catch { return false; } } -export async function fetchMedia(url, { method = "GET", signal, fetchImpl = fetch } = {}) { +function isBlockedAddress(address) { + const bare = address.split("%")[0]; + const family = isIP(bare); + return family === 0 || blocked.check(bare, family === 4 ? "ipv4" : "ipv6"); +} + +function publicOnlyLookup(hostname, options, callback) { + dns.lookup(hostname, { ...options, all: true }, (error, answers) => { + if (error) return callback(error); + if (answers.length === 0 || answers.some((a) => isBlockedAddress(a.address))) + return callback(new Error("Media download blocked: host resolves to a non-public address")); + if (options.all) return callback(null, answers); + callback(null, answers[0].address, answers[0].family); + }); +} + +function publicFetch(url, { method = "GET", signal } = {}) { + return new Promise((resolve, reject) => { + const target = new URL(url); + const client = target.protocol === "https:" ? https : http; + const request = client.request( + target, + { + method, + signal, + agent: false, + lookup: publicOnlyLookup, + headers: { accept: "*/*", "user-agent": "node" }, + }, + (res) => { + const headers = new Headers(); + for (const [name, value] of Object.entries(res.headers)) + for (const one of [value].flat()) if (one !== undefined) headers.append(name, one); + const empty = method === "HEAD" || [204, 205, 304].includes(res.statusCode); + try { + resolve( + new Response(empty ? null : Readable.toWeb(res), { + status: res.statusCode, + statusText: res.statusMessage, + headers, + }), + ); + if (empty) res.resume(); + } catch (error) { + res.destroy(); + reject(error); + } + }, + ); + request.on("error", reject); + request.end(); + }); +} + +// Tests replace `fetch` here; every default download goes through it. +export const mediaTransport = { fetch: publicFetch }; + +export async function fetchMedia( + url, + { method = "GET", signal, fetchImpl = mediaTransport.fetch } = {}, +) { let current = String(url); for (let hop = 0; hop <= 5; hop++) { if (!isPublicMediaUrl(current)) diff --git a/packages/cli/src/media-use/lib/media-fetch.test.mjs b/packages/cli/src/media-use/lib/media-fetch.test.mjs index 219b510510..422114ce72 100644 --- a/packages/cli/src/media-use/lib/media-fetch.test.mjs +++ b/packages/cli/src/media-use/lib/media-fetch.test.mjs @@ -1,9 +1,12 @@ import assert from "node:assert/strict"; +import dns from "node:dns"; import { mkdtempSync, readdirSync, rmSync } from "node:fs"; +import http, { createServer } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; -import { fetchMedia, isPublicMediaUrl, readCappedBody } from "./media-fetch.mjs"; +import { fetchMedia, isPublicMediaUrl, mediaTransport, readCappedBody } from "./media-fetch.mjs"; +import { mediaTransport as skillMediaTransport } from "../../../../../skills/media-use/scripts/lib/media-fetch.mjs"; import { freezeUrl } from "./freeze.mjs"; import { downloadTo } from "../../audio/scripts/lib/heygen.mjs"; import { synthesizeHeygen } from "../../audio/scripts/lib/tts.mjs"; @@ -91,6 +94,61 @@ test("rejects private redirect targets before requesting them and cancels redire assert.equal(cancelled, true); }); +test("refuses a public-looking name that resolves to a private address without connecting", async (t) => { + let served = 0; + const server = createServer((_req, res) => { + served++; + res.end("private"); + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + t.after(() => { + server.closeAllConnections(); + server.close(); + }); + const realLookup = dns.lookup; + t.mock.method(dns, "lookup", (host, options, callback) => + host === "media.example" + ? callback(null, options?.all ? [{ address: "127.0.0.1", family: 4 }] : "127.0.0.1", 4) + : realLookup(host, options, callback), + ); + await assert.rejects( + fetchMedia(`http://media.example:${server.address().port}/clip.mp4`), + /non-public address/, + ); + assert.equal(served, 0); +}); + +test("every download opens its own connection, so a reused socket never skips the address check", async (t) => { + const server = createServer((_req, res) => res.end("media")); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + t.after(() => { + server.closeAllConnections(); + server.close(); + }); + const realLookup = dns.lookup; + t.mock.method(dns, "lookup", (host, options, callback) => + host === "media.example" + ? callback(null, options?.all ? [{ address: "127.0.0.1", family: 4 }] : "127.0.0.1", 4) + : realLookup(host, options, callback), + ); + const seen = []; + const request = http.request; + t.mock.method(http, "request", (url, options, callback) => { + seen.push(options); + return request(url, options, callback); + }); + for (let i = 0; i < 2; i++) + await assert.rejects( + fetchMedia(`http://media.example:${server.address().port}/a`), + /non-public/, + ); + assert.equal(seen.length, 2); + for (const options of seen) { + assert.equal(options.agent, false); + assert.equal(typeof options.lookup, "function"); + } +}); + test("bounds redirect loops", async () => { let calls = 0; await assert.rejects( @@ -106,6 +164,7 @@ test("bounds redirect loops", async () => { }); test("freeze refuses a public-to-private redirect without writing response bytes", async (t) => { + routeDownloadsToFetch(t); const dir = mkdtempSync(join(tmpdir(), "hf-freeze-redirect-")); t.mock.method(globalThis, "fetch", async (_url, options) => options?.redirect === "manual" @@ -122,6 +181,7 @@ test("freeze refuses a public-to-private redirect without writing response bytes for (const entry of ["heygen audio", "tts mp3", "tts wav", "favicon"]) { test(`${entry} blocks private redirects before saving or transcoding`, async (t) => { + routeDownloadsToFetch(t); const dir = mkdtempSync(join(tmpdir(), "hf-provider-redirect-")); const requests = []; const fetchImpl = t.mock.method(globalThis, "fetch", async (url, options) => { @@ -168,6 +228,12 @@ for (const entry of ["heygen audio", "tts mp3", "tts wav", "favicon"]) { }); } +// Both copies of the media fetch (CLI lib and skill scripts) send downloads to the test's fetch stub. +function routeDownloadsToFetch(t) { + for (const transport of [mediaTransport, skillMediaTransport]) + t.mock.method(transport, "fetch", (url, init) => globalThis.fetch(url, init)); +} + function streamed(sizes, contentLength = null) { let pulled = 0; const body = (async function* () { diff --git a/packages/cli/src/media-use/resolve.test.mjs b/packages/cli/src/media-use/resolve.test.mjs index 480d2dd6de..98d933ee02 100644 --- a/packages/cli/src/media-use/resolve.test.mjs +++ b/packages/cli/src/media-use/resolve.test.mjs @@ -12,6 +12,7 @@ import { } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; +import { pathToFileURL } from "node:url"; import { createServer } from "node:http"; import { execFileSync, spawn, spawnSync } from "node:child_process"; import { appendRecord, findByPrompt, readManifest } from "./lib/manifest.mjs"; @@ -24,6 +25,10 @@ import { validateCubeFile } from "./lib/cube-validate.mjs"; const REPO_ROOT = join(import.meta.dirname, "..", "..", "..", ".."); const RESOLVE_CLI = join(import.meta.dirname, "resolve.mjs"); +// Appended to a spawned resolve's fetch stub: its media downloads reach the same stub. +const ROUTE_DOWNLOADS = ` +const { mediaTransport } = await import(${JSON.stringify(pathToFileURL(join(import.meta.dirname, "lib", "media-fetch.mjs")).href)}); +mediaTransport.fetch = (url, init) => globalThis.fetch(url, init);`; // The "Test: skills" CI job has no ffmpeg on PATH (by design). The smart-grade // test shells to ffmpeg, so it's skipped there and runs where ffmpeg exists. const HAS_FFMPEG = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0; @@ -126,7 +131,7 @@ globalThis.fetch = async (url, init) => { if (u.startsWith("https://cdn.openverse.test/")) return new Response("ID3 openverse bytes"); return real(url, init); };`; - return [`--import=data:text/javascript,${encodeURIComponent(stub)}`]; + return [`--import=data:text/javascript,${encodeURIComponent(stub + ROUTE_DOWNLOADS)}`]; } function makeFrame(dir, name, color) { @@ -228,7 +233,7 @@ syncBuiltinESMExports(); const prior = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("https://cdn.openverse.test/") ? new Response("ID3 " + url) : prior(url, init);`; - return [`--import=data:text/javascript,${encodeURIComponent(stub)}`]; + return [`--import=data:text/javascript,${encodeURIComponent(stub + ROUTE_DOWNLOADS)}`]; } test("two SFX resolves at once each keep their Openverse credit line", async () => { @@ -1922,7 +1927,7 @@ globalThis.fetch = async (url, init) => { if (u.includes("/public/icons/slack/")) return new Response(""); return real(url, init); };`; - const nodeArgs = [`--import=data:text/javascript,${encodeURIComponent(stub)}`]; + const nodeArgs = [`--import=data:text/javascript,${encodeURIComponent(stub + ROUTE_DOWNLOADS)}`]; const base = ["--type", "logo", "--intent", "Slack logo", "--entity", "Slack", "--json"]; const variant = JSON.parse( spawnResolve([...base, "--variant", "wordmark", "--project", tmp], { nodeArgs }).stdout.trim(), diff --git a/packages/cli/src/telemetry/client.test.ts b/packages/cli/src/telemetry/client.test.ts index 03a7547ec7..5aa83d312b 100644 --- a/packages/cli/src/telemetry/client.test.ts +++ b/packages/cli/src/telemetry/client.test.ts @@ -123,7 +123,7 @@ describe("telemetry queue delivery", () => { const { trackRenderFeedback, trackCatalogSearchMiss } = await import("./events.js"); trackEvent("cli_command", { command: "lint" }); trackRenderFeedback({ rating: 9 }); - trackCatalogSearchMiss({ query: "confetti" }); + trackCatalogSearchMiss({ wanted: "confetti" }); await flush(); expect(sentBatch(fetchMock).map((e) => [e.event, e.properties.client])).toEqual([ ["cli_command", "example-app/1.2.3/stable"], diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.ts index 09f0603552..679c823a0b 100644 --- a/packages/cli/src/telemetry/events.ts +++ b/packages/cli/src/telemetry/events.ts @@ -1152,22 +1152,13 @@ export function trackRenderFeedback(props: { } /** - * A catalog search that found nothing worth installing. - * - * This is the only path that ever sends a query anywhere, and it is a separate - * deliberate command rather than something `catalog --query` does on its own: - * plain search stays entirely local, which is what the CLI promises. The query - * is the point of the report — it names a move the catalog does not have yet, - * so the gaps can be read directly rather than guessed from install counts. + * A catalog search that found nothing worth installing, sent only by a deliberate + * `feedback --search-miss`. It names the move the catalog lacks, in the agent's words; + * the searched words stay on the machine. */ -export function trackCatalogSearchMiss(props: { - query: string; - wanted?: string; - tier?: string; -}): void { +export function trackCatalogSearchMiss(props: { wanted: string; tier?: string }): void { trackEvent("cli_catalog_search_miss", { - query: props.query, - ...(props.wanted ? { wanted: props.wanted } : {}), + wanted: props.wanted, ...(props.tier ? { tier: props.tier } : {}), }); } diff --git a/packages/cli/src/utils/submitFeedback.test.ts b/packages/cli/src/utils/submitFeedback.test.ts index 021f98383f..c89cdafeaf 100644 --- a/packages/cli/src/utils/submitFeedback.test.ts +++ b/packages/cli/src/utils/submitFeedback.test.ts @@ -137,7 +137,6 @@ describe("submitCatalogSearchMiss", () => { vi.stubGlobal("fetch", fetchMock); await submitCatalogSearchMiss({ - query: "typewriter that deletes", wanted: "text that types then backspaces", tier: "on-device", cliVersion: "0.7.106", @@ -147,7 +146,6 @@ describe("submitCatalogSearchMiss", () => { const [url, init] = fetchMock.mock.calls[0]!; expect(url).toBe("https://api.example.com/v1/hyperframes/catalog_search_miss"); expect(JSON.parse(String(init?.body))).toEqual({ - query: "typewriter that deletes", wanted: "text that types then backspaces", tier: "on-device", cli_version: "0.7.106", @@ -158,10 +156,10 @@ describe("submitCatalogSearchMiss", () => { const fetchMock = vi.fn(async () => new Response(null, { status: 202 })); vi.stubGlobal("fetch", fetchMock); - await submitCatalogSearchMiss({ query: "q".repeat(900), cliVersion: "0.7.106" }); + await submitCatalogSearchMiss({ wanted: "w".repeat(900), cliVersion: "0.7.106" }); const [, init] = fetchMock.mock.calls[0]!; - expect(JSON.parse(String(init?.body)).query).toHaveLength(500); + expect(JSON.parse(String(init?.body)).wanted).toHaveLength(500); }); it("never throws when the forward fails", async () => { @@ -173,7 +171,7 @@ describe("submitCatalogSearchMiss", () => { ); await expect( - submitCatalogSearchMiss({ query: "a query", cliVersion: "0.7.106" }), + submitCatalogSearchMiss({ wanted: "a move", cliVersion: "0.7.106" }), ).resolves.toBeUndefined(); }); }); diff --git a/packages/cli/src/utils/submitFeedback.ts b/packages/cli/src/utils/submitFeedback.ts index 64d9674152..a3820f61f8 100644 --- a/packages/cli/src/utils/submitFeedback.ts +++ b/packages/cli/src/utils/submitFeedback.ts @@ -45,7 +45,6 @@ export async function submitFeedback(input: { } } -const MAX_QUERY = 500; const MAX_WANTED = 500; const MAX_TIER = 50; @@ -58,8 +57,7 @@ const MAX_TIER = 50; * `submitFeedback` — a gap report must never fail the command that sent it. */ export async function submitCatalogSearchMiss(input: { - query: string; - wanted?: string; + wanted: string; tier?: string; cliVersion: string; }): Promise { @@ -68,7 +66,6 @@ export async function submitCatalogSearchMiss(input: { await fetch(`${apiBaseUrl}/v1/hyperframes/catalog_search_miss`, { method: "POST", body: JSON.stringify({ - query: cap(input.query, MAX_QUERY), wanted: cap(input.wanted, MAX_WANTED), tier: cap(input.tier, MAX_TIER), cli_version: cap(input.cliVersion, MAX_CLI_VERSION), diff --git a/scripts/check-core-skills.mjs b/scripts/check-core-skills.mjs index 83856e147f..1e74372570 100644 --- a/scripts/check-core-skills.mjs +++ b/scripts/check-core-skills.mjs @@ -11,22 +11,23 @@ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); // Every installed skill's description is listed on every turn; an entry is read in full when it opens. export const DESCRIPTION_MAX = 320; -// Each budget carries +192 B for the usage beacon line (`beaconProblems`) and +160 B for the line +// Each budget carries +256 B for the usage note line (`beaconProblems`) and +160 B for the line // that has every CLI command run through the launcher (`launcherProblems`). export const CORE_SKILLS = { // +128 B for the routing rows to the video rebuilds and to a reference's style, which only trigger when the entry hands them on. // +64 B for the lane pointer to format.md. - hyperframes: 7712, + hyperframes: 7776, // +256 B for the `_meta.updateNotice` line: the agent relays it, the person updates. // +256 B for the unattended pointer: a script or CI job with no TTY pins the release. - "hyperframes-cli": 8032, - "hyperframes-registry": 5472, - "media-use": 5472, - figma: 7520, - slideshow: 5472, - "remotion-to-hyperframes": 5472, - "reverse-any-video": 5472, - "style-sampling": 5472, + // +64 B for the rating line naming the person's no to usage notes. + "hyperframes-cli": 8160, + "hyperframes-registry": 5536, + "media-use": 5536, + figma: 7584, + slideshow: 5536, + "remotion-to-hyperframes": 5536, + "reverse-any-video": 5536, + "style-sampling": 5536, }; /** @param {string} skill */ diff --git a/skills-manifest.json b/skills-manifest.json index 03e6a41c69..d32ed36ccc 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -2,39 +2,39 @@ "source": "heygen-com/hyperframes", "skills": { "figma": { - "hash": "757f5a8b9b35d9ec", + "hash": "a130028ed1fee137", "files": 3 }, "hyperframes": { - "hash": "cca611faf7aaea9a", + "hash": "81c1845c8bab6410", "files": 81 }, "hyperframes-cli": { - "hash": "132e56038dbd2365", + "hash": "1c07f61f895849bb", "files": 14 }, "hyperframes-registry": { - "hash": "763e9fc772b54dbe", + "hash": "3f1f608741d537fd", "files": 13 }, "media-use": { - "hash": "defe29366d34a42b", + "hash": "0a11d0e163d34f5b", "files": 131 }, "remotion-to-hyperframes": { - "hash": "52ec1ac28a9251ae", + "hash": "f68ca68c0e8b246b", "files": 76 }, "reverse-any-video": { - "hash": "e429671078249b3e", + "hash": "d2f7f1c2f3967e5e", "files": 5 }, "slideshow": { - "hash": "c022f24e53ce376a", + "hash": "85dd76ed51ef78ab", "files": 2 }, "style-sampling": { - "hash": "59e52f3f688b9277", + "hash": "995ce900ea5b358f", "files": 2 } } diff --git a/skills/figma/SKILL.md b/skills/figma/SKILL.md index 23b93a839a..b56f8c5e5e 100644 --- a/skills/figma/SKILL.md +++ b/skills/figma/SKILL.md @@ -5,7 +5,7 @@ description: Bring Figma into a HyperFrames video - rendered assets, brand token **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=figma` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=figma` once as this skill starts. # Figma → HyperFrames @@ -31,7 +31,7 @@ Every import happens at build time and freezes a local file with its source reco ## Motion (connector) -Usage beacon: these phases have no CLI touchpoint, so run `npx hyperframes events --skill=figma-motion` when you begin and `npx hyperframes events --skill=figma-motion --event=skill_completed --outcome=success|error` when done. Same for shaders (`figma-shaders`) and storyboards (`figma-storyboard`). +Usage note (unless the person said no): these phases have no CLI touchpoint, so run `npx hyperframes events --skill=figma-motion` when you begin and `npx hyperframes events --skill=figma-motion --event=skill_completed --outcome=success|error` when done. Same for shaders (`figma-shaders`) and storyboards (`figma-storyboard`). 1. Fetch motion context for the parent frame in one recursive request; cache the raw JSON in `.media/figma-cache/`. 2. Normalise with `motionContextToDocs(raw, { selectorFor, repeat })` from `@hyperframes/core/figma`, never by transcribing keyframes. It reads the motion.dev snippets (the CSS snippets stretch durations), drops loop-wrap tail keyframes and keeps bezier eases. `selectorFor` returns the ids from the component import. diff --git a/skills/hyperframes-cli/SKILL.md b/skills/hyperframes-cli/SKILL.md index e3b8ab3e12..98dde45536 100644 --- a/skills/hyperframes-cli/SKILL.md +++ b/skills/hyperframes-cli/SKILL.md @@ -5,7 +5,7 @@ description: HyperFrames CLI - scaffold, check frames, edit timelines, preview, **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=hyperframes-cli` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=hyperframes-cli` once as this skill starts. # HyperFrames CLI @@ -71,7 +71,7 @@ Every write is kept and can be undone. At the start of a turn, `npx hyperframes A 30 s film renders in a minute or two: run it in the foreground. Detach only a render longer than your tool's timeout (`HYPERFRAMES_RENDER_DETACHED=1`, its own group, output to a log) and wait with `until grep -qE 'Render (complete|failed)' render.log; do sleep 5; done`, never `pgrep -f`, which matches its own loop and waits until the tool times out. -After a verified render, send one `feedback --rating`, plus a report for anything the person asked for that HyperFrames can't do, unless telemetry is off: `references/feedback.md`. +After a verified render, send one `feedback --rating`, plus a report for anything the person asked for that HyperFrames can't do, unless telemetry is off or they said no to usage notes: `references/feedback.md`. ## When a command fails diff --git a/skills/hyperframes-cli/references/cloudrun.md b/skills/hyperframes-cli/references/cloudrun.md index 083a71b625..17b190b5e0 100644 --- a/skills/hyperframes-cli/references/cloudrun.md +++ b/skills/hyperframes-cli/references/cloudrun.md @@ -18,6 +18,8 @@ npx hyperframes cloudrun progress npx hyperframes cloudrun destroy --project ``` +Ask the person before `destroy` and run it only after they say yes: it deletes their deployed Cloud Run stack. + `deploy` enables the required Google APIs, builds or accepts a container image, applies the bundled Terraform module, and stores the resulting coordinates in `~/.hyperframes/cloudrun-state.json`. Use deploy flags such as `--image`, `--repo`, `--cpu`, `--memory`, `--max-instances`, and `--timeout` only when the infrastructure needs those overrides. `sites create` uploads a content-addressed project archive for reuse by `render-batch`; pass its `--site-id` to that command to skip the batch upload. Single `cloudrun render` currently resolves the project from its directory and does not consume `--site-id`. Both render commands require `--width` and `--height`; supported output formats are `mp4`, `mov`, `png-sequence`, and `webm`. Use `--output-resolution 4k` to supersample an authored composition without changing its layout dimensions. diff --git a/skills/hyperframes-cli/references/feedback.md b/skills/hyperframes-cli/references/feedback.md index 76e69ed048..dacb2a6a4c 100644 --- a/skills/hyperframes-cli/references/feedback.md +++ b/skills/hyperframes-cli/references/feedback.md @@ -1,6 +1,6 @@ # Feedback reports -After verifying a successful render, send one feedback report unless telemetry is disabled or the user opted out: +After verifying a successful render, send one feedback report unless telemetry is disabled or the person said no to usage notes: ```bash npx hyperframes feedback --rating <0-10> --comment "" @@ -8,7 +8,7 @@ npx hyperframes feedback --rating <0-10> --comment " | WORKAROUND: "`. The report is about the capability they wanted, never their content or anything private. A catalog search that found nothing goes to `--search-miss` instead. - **Host app.** When `HYPERFRAMES_CLIENT` is set, the CLI is running inside a host app. When that app itself gets in the way (a panel, button, preview or export that misbehaves), send `npx hyperframes feedback --comment "HOST APP: "` with the reproduction packet. diff --git a/skills/hyperframes-cli/references/lambda.md b/skills/hyperframes-cli/references/lambda.md index 84630dd7d2..a2afd80141 100644 --- a/skills/hyperframes-cli/references/lambda.md +++ b/skills/hyperframes-cli/references/lambda.md @@ -23,6 +23,8 @@ npx hyperframes lambda render ./my-project --width 1920 --height 1080 --wait npx hyperframes lambda destroy ``` +`destroy` deletes their deployed stack: ask the person first and run it only after they say yes. + ## Choose Lambda or local rendering - **Local `render`** — dev-loop iteration, single host, anything under a few minutes at 1080p. @@ -156,6 +158,8 @@ Prints one snapshot — overall percent, frames rendered, Lambda invocations, ac npx hyperframes lambda destroy ``` +Ask the person before `destroy` and run it only after they say yes: it deletes their deployed Lambda stack. + Calls `sam delete --no-prompts` and drops the local state file. **The render S3 bucket is configured `Retain`** so it survives stack destruction — empty + delete it via the AWS console / CLI if you want the storage back. ### Non-retryable errors diff --git a/skills/hyperframes-registry/SKILL.md b/skills/hyperframes-registry/SKILL.md index dbbead3929..4c41be231c 100644 --- a/skills/hyperframes-registry/SKILL.md +++ b/skills/hyperframes-registry/SKILL.md @@ -5,7 +5,7 @@ description: About 450 ready-made HyperFrames blocks and components installed as **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=hyperframes-registry` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=hyperframes-registry` once as this skill starts. # HyperFrames registry @@ -23,7 +23,7 @@ npx hyperframes add --json # prints the written files and the moun - Query in English even when the video is not: the catalog is indexed in English, and another script returns `No searchable words in query`, which is not a gap. - Search is local and sends nothing. The default `words` tier only finds items that reuse your words; `--on-device` ranks by meaning after a one-time ~33 MB download. Offer that download and let the person decide; never enable it silently. The `--json` envelope names the tier that answered. - Narrow with `--type block|component` and `--tag `. `add ` installs every block with that tag; dependencies install first. `add` needs the network even for an item installed before; search works offline from the cached manifest. -- Nothing fits: report it before you hand-build, on either tier. `catalog --query` prints the line pre-filled (`report_gap` in `--json`): `npx hyperframes feedback --search-miss "" --wanted "" --tier `. When the query holds text your shell would run, `report_gap` is a sentence instead: build the line from `query` and `tier`, quoted for your shell. Describe the effect, not an item name you imagined. +- Nothing fits: report it before you hand-build, on either tier, unless the person said no to usage notes. `catalog --query` prints the line (`report_gap` in `--json`): `npx hyperframes feedback --search-miss --wanted "" --tier `. Describe the effect in your own words, not their query or an item name you imagined; their query is never sent. Tiers, `dropped` and `unindexed`, stale indexes, offline behaviour: `references/search.md`. diff --git a/skills/hyperframes-registry/references/search.md b/skills/hyperframes-registry/references/search.md index 33a2159804..0d6c9404b7 100644 --- a/skills/hyperframes-registry/references/search.md +++ b/skills/hyperframes-registry/references/search.md @@ -34,12 +34,12 @@ The normal table and `--json` modes only list matches; install a selected name w When the search comes back and nothing in it does the job, say so before you hand-author the move: ```bash -npx hyperframes feedback --search-miss "" --wanted "" --tier +npx hyperframes feedback --search-miss --wanted "" --tier ``` -`catalog --query` prints this line for you, pre-filled, and `--json` carries it as `report_gap` — so it is already in hand at the moment you decide nothing fits. When the query holds characters your shell would read as code (on Windows, `$(`, `"`, a backtick, `!` or `%NAME%`), no line is pre-filled: `report_gap` says how to report instead, and you pass the envelope's `query` and `tier` as separate arguments, quoted for your own shell. +`catalog --query` prints this line for you with the tier filled in, and `--json` carries it as `report_gap`, so it is already in hand at the moment you decide nothing fits. Skip it when the person said no to usage notes. -**Report whenever nothing in the results does the job, on either tier.** Do not wait for the on-device tier to have answered: it needs a consented 33 MB download, so an agent run is on `words` unless it explicitly opted in, and gating on `on-device` would silence almost every report. The `--tier` value rides along so a vocabulary miss stays distinguishable from a meaning miss when these are read. Describe the effect you wanted, not the item name you imagined: what comes back is a list of moves worth building, and a report naming a non-existent item teaches nothing. This is the only path that sends a query anywhere, which is exactly why it is a separate deliberate command rather than something the search does on its own. It carries no rating and never lands in the rating metric. +**Report whenever nothing in the results does the job, on either tier.** Do not wait for the on-device tier to have answered: it needs a consented 33 MB download, so an agent run is on `words` unless it explicitly opted in, and gating on `on-device` would silence almost every report. The `--tier` value rides along so a vocabulary miss stays distinguishable from a meaning miss when these are read. Describe the effect you wanted, not the item name you imagined: what comes back is a list of moves worth building, and a report naming a non-existent item teaches nothing. The report holds your description and the tier, never the person's query: their search stays on their machine. It carries no rating and never lands in the rating metric. This is the whole demand signal for the catalog. Skipping it means the gap you hit gets guessed at from install counts instead, which cannot see a move nobody could install. @@ -63,5 +63,5 @@ See [discovery.md](./discovery.md) for details on filtering by type and tags. - **Query in English even when the video is not.** Both tiers index an English catalog, so a query in another script produces no searchable terms and returns nothing. Describe the move in English; the on-screen copy stays in whatever language the video needs. `No searchable words in query` means exactly this and is not a missing component, so do not report it as a catalog gap. - **Read which tier answered; never infer it from results appearing.** With `--json` the envelope carries `query`, `tier` (`on-device` or `words`), `tier_detail`, `dropped`, `unindexed`, `shown`, `total` and `results`, plus `top_score` when the answering tier produces one and `warnings` when a tier was asked for and could not run, or when a search returned nothing and a better tier is still waiting on someone's consent. A weak result on `words` is expected; the same result on `on-device` is a bug. `top_score` is on-device only and has no threshold behind it: the ranker returns the whole catalog in some order for every query, so read it as evidence rather than as a pass or fail. - **`dropped` and `unindexed` are opposite skews between the registry and the on-device index, and rewording the query fixes neither.** `dropped` counts ranked names this registry cannot install, so the strongest matches are the ones being lost. `unindexed` counts registry moves the index cannot see at all, which no query can ever return. Refreshing the registry is not the answer to either: its manifest carries a 24h TTL and heals itself, while the vectors are a separately published artifact fetched into `~/.hyperframes/catalog/`. Re-running with `--on-device` refetches that index when `unindexed` is above zero, so that is the remedy to hand the user. A pure over-coverage skew (`dropped` above zero while `unindexed` is zero) does not trigger the refetch; clearing `~/.hyperframes/catalog/` is the only way out of that one. Both counts are of names rather than of results, so either can exceed `total`. -- **When a search comes back with nothing worth installing, say so.** `npx hyperframes feedback --search-miss "" --wanted "" --tier `. You do not have to assemble that line: `catalog --query` prints it pre-filled, and every `--json` search envelope carries it as `report_gap` with the query and tier already correct — fill in `--wanted` and send. When `report_gap` is a sentence rather than a line, build the line yourself from `query` and `tier`, quoted for your shell. This is the only path that sends a query anywhere, and it is a separate deliberate command precisely so plain `catalog --query` keeps its promise of sending nothing. **Report on either tier**, whenever the results do not do the thing; do not hold out for the on-device tier, which needs a consented 33 MB download and is therefore off in most agent runs — waiting for it means never reporting at all. The tier rides along in the report, so a vocabulary miss stays distinguishable from a meaning miss without you having to judge which one you hit. What comes back is a list of moves the catalog does not have yet, read directly rather than guessed from install counts, so the phrasing that matters is the effect you wanted, not the item name you imagined. It carries no rating and never lands in the rating metric. +- **When a search comes back with nothing worth installing, say so.** `npx hyperframes feedback --search-miss --wanted "" --tier `, unless the person said no to usage notes. You do not have to assemble that line: `catalog --query` prints it, and every `--json` search envelope carries it as `report_gap` with the tier already correct; fill in `--wanted` in your own words and send. The report never carries the person's query, so plain `catalog --query` keeps its promise of sending nothing. **Report on either tier**, whenever the results do not do the thing; do not hold out for the on-device tier, which needs a consented 33 MB download and is therefore off in most agent runs — waiting for it means never reporting at all. The tier rides along in the report, so a vocabulary miss stays distinguishable from a meaning miss without you having to judge which one you hit. What comes back is a list of moves the catalog does not have yet, read directly rather than guessed from install counts, so the phrasing that matters is the effect you wanted, not the item name you imagined. It carries no rating and never lands in the rating metric. - **Offer the offline tier; never enable it silently.** A one-time ~33 MB download (a quantized ONNX build of `bge-small-en-v1.5` plus its tokenizer, pinned to a fixed revision) and the catalog vectors from the registry, both cached under `~/.hyperframes/`, neither added to the project or any package. Once cached it ranks by meaning with nothing sent. Say the size out loud and let the person decide, then pass `--on-device` (with `-y` to skip the prompt) once they agree. The interactive offer only fires on a TTY. Under `--json` there is no prompt, but a search that found nothing puts the same ask in `warnings`, so read that array and put the decision to the user yourself. When the person asks what the download is, why this model, or what leaves the machine, point them to https://hyperframes.heygen.com/developers/catalog-search. diff --git a/skills/hyperframes/SKILL.md b/skills/hyperframes/SKILL.md index 02a781b146..729e73521a 100644 --- a/skills/hyperframes/SKILL.md +++ b/skills/hyperframes/SKILL.md @@ -5,7 +5,7 @@ description: Read first to make, edit, animate or render any video with HyperFra **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=hyperframes` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=hyperframes` once as this skill starts. # HyperFrames diff --git a/skills/media-use/SKILL.md b/skills/media-use/SKILL.md index 80ced5e1d0..2ec9a59a43 100644 --- a/skills/media-use/SKILL.md +++ b/skills/media-use/SKILL.md @@ -5,7 +5,7 @@ description: Get or make any media for a HyperFrames video - music, sound effect **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=media-use` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=media-use` once as this skill starts. # Media in HyperFrames diff --git a/skills/media-use/audio/scripts/audio.test.mjs b/skills/media-use/audio/scripts/audio.test.mjs index 81fd33aaf2..2a91cf92c5 100644 --- a/skills/media-use/audio/scripts/audio.test.mjs +++ b/skills/media-use/audio/scripts/audio.test.mjs @@ -15,6 +15,17 @@ import { tmpdir } from "node:os"; import { fileURLToPath } from "node:url"; import { recordInManifest } from "./lib/media-record.mjs"; import { resolveSfx } from "./lib/sfx.mjs"; +import { afterEach, beforeEach } from "node:test"; +import { mediaTransport } from "../../scripts/lib/media-fetch.mjs"; + +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); // Proves the relocated engine (skills/media-use/audio/) still resolves its // bundled SFX library from the moved location — the path most likely to break diff --git a/skills/media-use/audio/scripts/heygen-tts.test.mjs b/skills/media-use/audio/scripts/heygen-tts.test.mjs index 10a0e25f00..89740ce4fe 100644 --- a/skills/media-use/audio/scripts/heygen-tts.test.mjs +++ b/skills/media-use/audio/scripts/heygen-tts.test.mjs @@ -51,7 +51,9 @@ globalThis.fetch = async (url) => String(url).endsWith("/voices/speech") ? new Response(JSON.stringify({ data: { audio_url: "https://audio.example/a", word_timestamps: [{ word: "Hello", start: 0, end: 0.4 }] } }), { headers: { "content-type": "application/json" } }) - : new Response(readFileSync(process.env.TTS_AUDIO));`; + : new Response(readFileSync(process.env.TTS_AUDIO)); +const { mediaTransport } = await import(${JSON.stringify(new URL("../../scripts/lib/media-fetch.mjs", import.meta.url).href)}); +mediaTransport.fetch = (url, init) => globalThis.fetch(url, init);`; const hasFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0; const canLink = (() => { diff --git a/skills/media-use/audio/scripts/lib/sfx.test.mjs b/skills/media-use/audio/scripts/lib/sfx.test.mjs index 2b437d640e..404e9e3ce3 100644 --- a/skills/media-use/audio/scripts/lib/sfx.test.mjs +++ b/skills/media-use/audio/scripts/lib/sfx.test.mjs @@ -5,6 +5,17 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import { appendRecord } from "../../../scripts/lib/manifest.mjs"; import { BUNDLED_SFX_DIR, findSoundEffect, resolveSfx } from "./sfx.mjs"; +import { afterEach, beforeEach } from "node:test"; +import { mediaTransport } from "../../../scripts/lib/media-fetch.mjs"; + +// These tests stub globalThis.fetch; media downloads reach the same stub. +const transportFetch = mediaTransport.fetch; +beforeEach(() => { + mediaTransport.fetch = (url, init) => globalThis.fetch(url, init); +}); +afterEach(() => { + mediaTransport.fetch = transportFetch; +}); // No real network: each test serves Openverse's answers; by default it is unreachable. const offline = async () => { diff --git a/skills/media-use/audio/scripts/lib/tts.mjs b/skills/media-use/audio/scripts/lib/tts.mjs index f28748d371..3c2ca1354c 100644 --- a/skills/media-use/audio/scripts/lib/tts.mjs +++ b/skills/media-use/audio/scripts/lib/tts.mjs @@ -367,7 +367,7 @@ export function synthResult(r, wavAbs, label) { export async function synthesizeHeygen({ text, voiceId, lang, speed, wavAbs }, deps = {}) { const requestJSON = deps.heygenJSON ?? heygenJSON; const authHeaders = deps.heygenAuthHeaders ?? heygenAuthHeaders; - const fetchImpl = deps.fetch ?? fetch; + const fetchImpl = deps.fetch; const transcode = deps.transcodeToWav ?? transcodeToWav; try { refuseUnderLimit(deps.projectDir ?? process.cwd(), "a HeyGen voice", "voice"); diff --git a/skills/media-use/scripts/lib/media-fetch.mjs b/skills/media-use/scripts/lib/media-fetch.mjs index 7664c2af5f..71d376bcbf 100644 --- a/skills/media-use/scripts/lib/media-fetch.mjs +++ b/skills/media-use/scripts/lib/media-fetch.mjs @@ -1,9 +1,13 @@ // Media downloads use public HTTP(S) URLs. Validate every redirect target; // a provider result must meet the same host policy as a direct ingest URL. // Public HTTPS-to-HTTP redirects are allowed, matching direct HTTP support. -// This is a literal-host policy, not DNS pinning: DNS resolution remains trusted. +// A host name is resolved once and the connection dials that checked address. +import dns from "node:dns"; +import http from "node:http"; +import https from "node:https"; import { BlockList, isIP } from "node:net"; +import { Readable } from "node:stream"; const blocked = new BlockList(); for (const [network, prefix] of [ @@ -48,14 +52,73 @@ export function isPublicMediaUrl(value) { ) return false; const address = host.replace(/^\[|\]$/g, ""); - const family = isIP(address); - return family === 0 || !blocked.check(address, family === 4 ? "ipv4" : "ipv6"); + return isIP(address) === 0 || !isBlockedAddress(address); } catch { return false; } } -export async function fetchMedia(url, { method = "GET", signal, fetchImpl = fetch } = {}) { +function isBlockedAddress(address) { + const bare = address.split("%")[0]; + const family = isIP(bare); + return family === 0 || blocked.check(bare, family === 4 ? "ipv4" : "ipv6"); +} + +function publicOnlyLookup(hostname, options, callback) { + dns.lookup(hostname, { ...options, all: true }, (error, answers) => { + if (error) return callback(error); + if (answers.length === 0 || answers.some((a) => isBlockedAddress(a.address))) + return callback(new Error("Media download blocked: host resolves to a non-public address")); + if (options.all) return callback(null, answers); + callback(null, answers[0].address, answers[0].family); + }); +} + +function publicFetch(url, { method = "GET", signal } = {}) { + return new Promise((resolve, reject) => { + const target = new URL(url); + const client = target.protocol === "https:" ? https : http; + const request = client.request( + target, + { + method, + signal, + agent: false, + lookup: publicOnlyLookup, + headers: { accept: "*/*", "user-agent": "node" }, + }, + (res) => { + const headers = new Headers(); + for (const [name, value] of Object.entries(res.headers)) + for (const one of [value].flat()) if (one !== undefined) headers.append(name, one); + const empty = method === "HEAD" || [204, 205, 304].includes(res.statusCode); + try { + resolve( + new Response(empty ? null : Readable.toWeb(res), { + status: res.statusCode, + statusText: res.statusMessage, + headers, + }), + ); + if (empty) res.resume(); + } catch (error) { + res.destroy(); + reject(error); + } + }, + ); + request.on("error", reject); + request.end(); + }); +} + +// Tests replace `fetch` here; every default download goes through it. +export const mediaTransport = { fetch: publicFetch }; + +export async function fetchMedia( + url, + { method = "GET", signal, fetchImpl = mediaTransport.fetch } = {}, +) { let current = String(url); for (let hop = 0; hop <= 5; hop++) { if (!isPublicMediaUrl(current)) diff --git a/skills/remotion-to-hyperframes/SKILL.md b/skills/remotion-to-hyperframes/SKILL.md index d4cce653a5..ffc05c17d2 100644 --- a/skills/remotion-to-hyperframes/SKILL.md +++ b/skills/remotion-to-hyperframes/SKILL.md @@ -5,7 +5,7 @@ description: Bring existing video code or footage into HyperFrames and verify it **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=remotion-to-hyperframes` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=remotion-to-hyperframes` once as this skill starts. # Import into HyperFrames diff --git a/skills/reverse-any-video/SKILL.md b/skills/reverse-any-video/SKILL.md index 7d39b7d462..3c3fd29bf8 100644 --- a/skills/reverse-any-video/SKILL.md +++ b/skills/reverse-any-video/SKILL.md @@ -5,7 +5,7 @@ description: Rebuild any video file as an editable HyperFrames project - motion **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=reverse-any-video` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=reverse-any-video` once as this skill starts. # Reverse a video diff --git a/skills/reverse-any-video/references/start.md b/skills/reverse-any-video/references/start.md index cf923a94a1..ef51da60b0 100644 --- a/skills/reverse-any-video/references/start.md +++ b/skills/reverse-any-video/references/start.md @@ -6,7 +6,7 @@ these instructions: the only links are pages they need to open. You run every co is theirs: any page they need goes in your message as a plain link they can click, sign-in in case the browser did not open, upgrade and add-on credits for them to open and pay themselves. -For you, not them: run `npx hyperframes events --skill=reverse-any-video --event=skill_completed --outcome=success` +For you, not them: unless they said no to usage notes, run `npx hyperframes events --skill=reverse-any-video --event=skill_completed --outcome=success` when you hand over the video (`--outcome=error` when you stop without one). Also for you: `npx hyperframes reverse start ), and I'll carry -> on as soon as you're in. +> Reversing a video needs a HyperFrames Pro sign-in. To rebuild this one at its best, I'll work with HeyGen: it re-shoots +> the people in it, so they move and speak just like the original. Your HyperFrames account is your HeyGen account: sign +> in here (code ), and I'll carry on as soon as you're in. > > Then it takes about 20–50 minutes: I study the video frame by frame, rebuild every layer as a project you can edit, > and check it against the original until it matches. diff --git a/skills/slideshow/SKILL.md b/skills/slideshow/SKILL.md index 03b76f2c81..506d7cea85 100644 --- a/skills/slideshow/SKILL.md +++ b/skills/slideshow/SKILL.md @@ -5,7 +5,7 @@ description: Build a HyperFrames slideshow to present live - slides, fragment re **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=slideshow` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=slideshow` once as this skill starts. # HyperFrames slideshow diff --git a/skills/style-sampling/SKILL.md b/skills/style-sampling/SKILL.md index c20aba6793..9cdfd04cbe 100644 --- a/skills/style-sampling/SKILL.md +++ b/skills/style-sampling/SKILL.md @@ -5,7 +5,7 @@ description: Make a new episode in a proven video style - Collage Explainer, Fin **Running the CLI:** every `npx hyperframes ` here, the beacon included, means `node /hyperframes/scripts/plugin-cli.mjs ` run in the project, where `` holds this skill's folder ([rules](../hyperframes/references/plugin-installation.md)). -**Usage beacon:** run `npx hyperframes events --skill=style-sampling` once as this skill starts. It sends the skill's name with the CLI's usual telemetry (account-linked when signed in) and honours the opt-out. +**Usage note:** before the first one, tell the person once: "I'll send HyperFrames a usage note (linked to your account if signed in); say no to skip." Unless they say no, run `npx hyperframes events --skill=style-sampling` once as this skill starts. # A new episode from a style template