Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat(provider-hypihub): upload reference artifacts
rpone4421b1990892
diff --git a/packages/provider-hypihub/README.md b/packages/provider-hypihub/README.mdindex 59a5fd3a..f481ca37 100644--- a/packages/provider-hypihub/README.md+++ b/packages/provider-hypihub/README.md@@ -33,5 +33,7 @@ Gemini VLM callers can use the exported `createHypiHubGeminiGenerator` without cprovider-facing code. Set `HYPIHUB_API_KEY` (and optionally `HYPIHUB_BASE_URL`; either the origin oran existing `/v1`/`/v1beta` base is accepted) only when choosing HypiHub. The Runtime Provider alsoaccepts the origin or either versioned base and normalizes it to `/v1`; missing or insufficient user-credentials should be resolved at [hypit.ai](https://hypit.ai). Video/audio reference artifacts need-an operator-supplied `publicAssetUrl` callback because HypiHub must fetch those references over HTTPS.+credentials should be resolved at [hypit.ai](https://hypit.ai). Referenced image, audio and video+Artifacts are uploaded automatically through `POST /v1/files`, then their returned HTTPS capability+URLs are used in image and video requests. Uploads are deduplicated by Artifact digest within one+Runtime operation. Embedded callers may override that transport with `publicAssetUrl`.diff --git a/packages/provider-hypihub/package.json b/packages/provider-hypihub/package.jsonindex 7a0fca4c..5e52fc3b 100644--- a/packages/provider-hypihub/package.json+++ b/packages/provider-hypihub/package.json@@ -12,5 +12,9 @@"@hypit/protocol": "workspace:*","@hypit/runtime": "workspace:*","@hypit/runtime-kit": "workspace:*"+ },+ "devDependencies": {+ "@hypit/driver-node": "workspace:*",+ "@hypit/seedance": "workspace:*"}}diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.tsindex a5f2cb79..ee23e93f 100644--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@ -17,7 +17,7 @@ export type CreateHypiHubProviderOptions = {readonly pollIntervalMs?: number;readonly requestTimeoutMs?: number;readonly fetch?: typeof globalThis.fetch;- /** Uploads a Runtime artifact to a public URL for video/audio references. */+ /** Overrides the default POST /v1/files upload for referenced artifacts. */readonly publicAssetUrl?: (artifact: BlobRef, artifacts: ArtifactStore) => Promise<string>;};@@ -67,25 +67,21 @@ function dataUrl(bytes: Uint8Array, mediaType: string): string {return `data:${mediaType};base64,${Buffer.from(bytes).toString("base64")}`;}-async function resolveArtifactAsDataUrl(- artifacts: ArtifactStore,- artifact: BlobRef,- publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"],- allowBinaryInline: boolean,-): Promise<string> {- if (!allowBinaryInline && /^(?:video|audio)\//u.test(artifact.mediaType)) {- if (publicAssetUrl !== undefined) {- const url = (await publicAssetUrl(artifact, artifacts)).trim();- assert(/^https:\/\//iu.test(url), "publicAssetUrl must return an https URL for HypiHub references");- return url;- }- throw new Error("HypiHub video/audio references require a public HTTPS URL; configure publicAssetUrl on the provider");- }+async function resolveArtifactInline(artifacts: ArtifactStore, artifact: BlobRef): Promise<string> {const bytes = await artifacts.get(artifact.digest);assert(bytes !== undefined, `HypiHub reference artifact ${artifact.digest} is unavailable`);return dataUrl(bytes, artifact.mediaType);}+function mediaExtension(mediaType: string): string {+ const known: Readonly<Record<string, string>> = {+ "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp",+ "video/mp4": "mp4", "video/quicktime": "mov",+ "audio/mpeg": "mp3", "audio/wav": "wav", "audio/x-wav": "wav", "audio/mp4": "m4a",+ };+ return known[mediaType] ?? "bin";+}+class HypiHubClient {readonly baseUrl: string;readonly timeout: number;@@ -104,8 +100,33 @@ class HypiHubClient {} finally { clearTimeout(timer); }}async download(url: string): Promise<{ readonly bytes: Uint8Array; readonly mediaType: string }> {- const response = await this.fetcher(url); if (!response.ok) throw new Error(`HypiHub asset returned HTTP ${response.status}`);- return { bytes: new Uint8Array(await response.arrayBuffer()), mediaType: response.headers.get("content-type")?.split(";", 1)[0] ?? "application/octet-stream" };+ let lastError: unknown;+ for (let attempt = 0; attempt < 3; attempt += 1) {+ try {+ const response = await this.fetcher(url);+ if (!response.ok) throw new Error(`HypiHub asset returned HTTP ${response.status}`);+ return { bytes: new Uint8Array(await response.arrayBuffer()), mediaType: response.headers.get("content-type")?.split(";", 1)[0] ?? "application/octet-stream" };+ } catch (error) {+ lastError = error;+ if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));+ }+ }+ throw lastError instanceof Error ? lastError : new Error(String(lastError));+ }+ async upload(artifact: BlobRef, artifacts: ArtifactStore, apiKey: string): Promise<string> {+ const bytes = await artifacts.get(artifact.digest);+ assert(bytes !== undefined, `HypiHub reference artifact ${artifact.digest} is unavailable`);+ assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.digest} size differs`);+ const form = new FormData();+ const copy = new ArrayBuffer(bytes.byteLength);+ new Uint8Array(copy).set(bytes);+ form.append("file", new Blob([copy], { type: artifact.mediaType }),+ `${artifact.digest.slice("sha256:".length)}.${mediaExtension(artifact.mediaType)}`);+ form.append("purpose", "reference");+ const response = await this.json("/files", apiKey, { method: "POST", body: form });+ assert(typeof response.url === "string" && /^https:\/\//iu.test(response.url),+ "HypiHub file upload returned no HTTPS URL");+ return response.url;}async binary(path: string, apiKey: string, body: Record<string, unknown>): Promise<{ readonly bytes: Uint8Array; readonly mediaType: string }> {const response = await this.fetcher(`${this.baseUrl}${path}`, { method: "POST", headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, body: JSON.stringify(body) });@@ -124,8 +145,9 @@ async function complete(client: HypiHubClient, apiKey: string, route: (typeof hyasync function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {const route = hypiHubRouteForCapability(context.need.capability);assert(route !== undefined && route.media === "audio", "HypiHub does not implement this exact capability");- const compiled = await route.compile(context.need.constraints,- (artifact) => resolveArtifactAsDataUrl(context.artifacts, artifact, publicAssetUrl, true));+ const compiled = await route.compile(context.need.constraints, async (artifact) => publicAssetUrl === undefined+ ? await resolveArtifactInline(context.artifacts, artifact)+ : await publicAssetUrl(artifact, context.artifacts));await verifyModelRoute(client, credential(context), compiled.model, "audio_speech");const audio = await client.binary("/audio/speech", credential(context), { model: compiled.model, ...(compiled.input as Record<string, unknown>) });const artifact = await context.artifacts.put(audio.bytes, audio.mediaType);@@ -138,8 +160,17 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:try {const route = hypiHubRouteForCapability(context.need.capability);assert(route !== undefined, "HypiHub does not implement this exact capability"); const apiKey = credential(context);- const compiled = await route.compile(context.need.constraints,- (artifact) => resolveArtifactAsDataUrl(context.artifacts, artifact, publicAssetUrl, false));+ const uploaded = new Map<string, Promise<string>>();+ const resolve = (artifact: BlobRef): Promise<string> => {+ const existing = uploaded.get(artifact.digest);+ if (existing !== undefined) return existing;+ const promise = publicAssetUrl === undefined+ ? client.upload(artifact, context.artifacts, apiKey)+ : publicAssetUrl(artifact, context.artifacts);+ uploaded.set(artifact.digest, promise);+ return promise;+ };+ const compiled = await route.compile(context.need.constraints, resolve);assert(route.media !== "audio", "HypiHub audio capabilities use an immediate endpoint");const input = compiled.input as Record<string, unknown>;const hasReferences = Object.entries(input).some(([key, value]) => {@@ -164,7 +195,11 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:if (Date.now() - handle.startedAt > maxOperationMs) throw new Error("HypiHub operation timed out");const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, credential(context)); const status = job.status;if (status === "queued" || status === "running" || status === "in_progress") return wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: String(status) });- if (status === "failed" || status === "queue_expired") throw new Error(`HypiHub job ${status}`);+ if (status === "failed" || status === "queue_expired") {+ const detail = [job.error, job.message, job.reason, job.detail]+ .find((value) => typeof value === "string" && value.length > 0);+ throw new Error(`HypiHub job ${status}${typeof detail === "string" ? `: ${detail}` : ""}`);+ }if (status !== "succeeded" && status !== "completed") throw new Error(`HypiHub returned unknown job status ${String(status)}`);return await complete(client, credential(context), route, handle.jobId, context.artifacts);} catch (error) { return failure(error); }diff --git a/packages/provider-hypihub/src/routes.ts b/packages/provider-hypihub/src/routes.tsindex 70085094..0bc281bd 100644--- a/packages/provider-hypihub/src/routes.ts+++ b/packages/provider-hypihub/src/routes.ts@@ -78,20 +78,9 @@ function normalizeHypiHubRequest(throw new Error("HypiHub unified video API does not support video continuation sourceTaskId");}- // HypiHub's upstream relay exposes vendor-specific reference arrays through- // its documented `extra` passthrough. Unknown top-level fields are ignored- // by the public JSON decoder, while `extra` is handed to the selected- // upstream adaptor and becomes its provider-neutral reference vocabulary.- const extra = input.extra !== null && typeof input.extra === "object" && !Array.isArray(input.extra)- ? { ...(input.extra as Record<string, unknown>) } : {};- if (Array.isArray(imageRefs) && imageRefs.length > 0) extra.reference_image_urls = imageRefs;- if (Array.isArray(genericImageRefs) && genericImageRefs.length > 0) {- const urls = genericImageRefs.map((item) => item !== null && typeof item === "object"- ? (item as Record<string, unknown>).url : item).filter((item): item is string => typeof item === "string" && item.length > 0);- if (urls.length > 0) extra.reference_image_urls = urls;- }- if (Array.isArray(videoRefs) && videoRefs.length > 0) extra.reference_videos = videoRefs;- if (Array.isArray(audioRefs) && audioRefs.length > 0) extra.reference_audios = audioRefs;+ // References are public HypiHub media inputs, not vendor passthrough. They+ // must remain top-level so Async V2 stages the uploaded capability URLs+ // before choosing an upstream adaptor.delete input.reference_image_urls;delete input.reference_images;delete input.reference_videos;@@ -99,10 +88,17 @@ function normalizeHypiHubRequest(delete input.first_image_url;delete input.last_image_url;delete input.source_task_id;- delete input.extra;- if (typeof firstFrame === "string" && firstFrame.length > 0) input.input_reference = firstFrame;+ if (typeof firstFrame === "string" && firstFrame.length > 0) input.first_frame = firstFrame;if (typeof lastFrame === "string" && lastFrame.length > 0) input.last_frame = lastFrame;- if (Object.keys(extra).length > 0) input.extra = extra;+ if (Array.isArray(imageRefs) && imageRefs.length > 0) input.reference_image_urls = imageRefs;+ if (Array.isArray(genericImageRefs) && genericImageRefs.length > 0) {+ const urls = genericImageRefs.map((item) => item !== null && typeof item === "object"+ ? (item as Record<string, unknown>).url : item).filter((item): item is string => typeof item === "string" && item.length > 0);+ if (urls.length > 0) input.reference_image_urls = urls;+ }+ if (Array.isArray(videoRefs) && videoRefs.length === 1) input.ref_video_url = videoRefs[0];+ else if (Array.isArray(videoRefs) && videoRefs.length > 1) input.reference_videos = videoRefs;+ if (Array.isArray(audioRefs) && audioRefs.length > 0) input.reference_audios = audioRefs;return { model: request.model, input: canonicalize(input) };}diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.tsnew file mode 100644index 00000000..f8db4800--- /dev/null+++ b/packages/provider-hypihub/test/provider.test.ts@@ -0,0 +1,93 @@+import assert from "node:assert/strict";+import test from "node:test";++import { EndpointRegistry, MemoryArtifactStore } from "@hypit/driver-node";+import type { AsyncEndpoint } from "@hypit/endpoint-kit";+import type { CanonicalValue, Need } from "@hypit/protocol";+import { sealSeedanceRequest, seedanceEndpoints } from "@hypit/seedance";++import { createHypiHubProvider } from "../src/provider.js";++function need(constraints: CanonicalValue): Need {+ return {+ id: "need:hypihub-test",+ capability: seedanceEndpoints.mini!.capability,+ returns: seedanceEndpoints.mini!.returns,+ constraints,+ result: "record:hypihub-test",+ };+}++async function endpointFor(request: Need, fetch: typeof globalThis.fetch): Promise<AsyncEndpoint> {+ const registry = new EndpointRegistry();+ await createHypiHubProvider({ fetch, pollIntervalMs: 0, requestTimeoutMs: 1_000 }).install(registry);+ const resolution = registry.resolve(request);+ assert.equal(resolution.status, "resolved");+ assert.equal(resolution.registration.kind, "asynchronous");+ return resolution.registration.endpoint;+}++test("HypiHub uploads referenced Artifacts once, submits their HTTPS URLs, and persists the result", async () => {+ const artifacts = new MemoryArtifactStore();+ const reference = await artifacts.put(new Uint8Array([1, 2, 3]), "image/png");+ const request = need(sealSeedanceRequest("seedance-2-mini", {+ prompt: ["A presenter turns toward camera."],+ referenceImage: [+ { role: "image", artifact: reference },+ { role: "image", artifact: reference },+ ],+ resolution: ["720p"], aspectRatio: ["16:9"], duration: [5],+ generateAudio: [false], webSearch: [false],+ }) as unknown as CanonicalValue);+ const calls: string[] = [];+ const fakeFetch: typeof globalThis.fetch = async (input, init) => {+ const url = String(input);+ calls.push(url);+ if (url.endsWith("/v1/files")) {+ assert.equal(init?.method, "POST");+ assert.equal((init?.headers as Record<string, string>).authorization, "Bearer test-key");+ assert.ok(init?.body instanceof FormData);+ assert.equal(init.body.get("purpose"), "reference");+ const file = init.body.get("file");+ assert.ok(file instanceof File);+ assert.equal(file.type, "image/png");+ assert.deepEqual(new Uint8Array(await file.arrayBuffer()), new Uint8Array([1, 2, 3]));+ return Response.json({ url: "https://hypit.ai/files/as_reference.png" });+ }+ if (url.endsWith("/v1/models/bytedance%2Fseedance-2-mini")) {+ return Response.json({ endpoints: ["videos"] });+ }+ if (url.endsWith("/v1/videos")) {+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;+ assert.equal(body.model, "bytedance/seedance-2-mini");+ assert.deepEqual(body.reference_image_urls, [+ "https://hypit.ai/files/as_reference.png",+ "https://hypit.ai/files/as_reference.png",+ ]);+ return Response.json({ id: "job_hypihub_test", status: "queued" });+ }+ if (url.endsWith("/v1/jobs/job_hypihub_test")) {+ return Response.json({ id: "job_hypihub_test", status: "succeeded" });+ }+ if (url.endsWith("/v1/jobs/job_hypihub_test/assets")) {+ return Response.json({ items: [{ url: "https://download.hypit.test/result.mp4" }] });+ }+ if (url === "https://download.hypit.test/result.mp4") {+ return new Response(new Uint8Array([9, 8, 7]), { headers: { "content-type": "video/mp4" } });+ }+ throw new Error(`Unexpected URL ${url}`);+ };+ const endpoint = await endpointFor(request, fakeFetch);+ const common = {+ command: { kind: "fulfill-need", id: "command:hypihub-test", need: request } as const,+ need: request, artifacts, credentials: { apiKey: { secret: "test-key" } },+ operation: "operation:hypihub-test",+ };+ const started = await endpoint.start(common);+ assert.equal(started.status, "pending");+ assert.equal(calls.filter((url) => url.endsWith("/v1/files")).length, 1);+ if (started.status !== "pending") return;+ const completed = await endpoint.poll({ ...common, handle: started.handle });+ assert.equal(completed.status, "completed");+ assert.equal(calls.length, 6);+});diff --git a/packages/provider-hypihub/test/routes.test.ts b/packages/provider-hypihub/test/routes.test.tsindex e91081f9..e0e8099c 100644--- a/packages/provider-hypihub/test/routes.test.ts+++ b/packages/provider-hypihub/test/routes.test.ts@@ -33,7 +33,7 @@ test("HypiHub GPT image requests use canonical edit references and size dimensio});});-test("HypiHub image-to-video requests use input_reference", async () => {+test("HypiHub image-to-video requests preserve Hypit's first-frame semantics", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "minimax-h3");assert.ok(route);const result = await route.compile({@@ -48,11 +48,11 @@ test("HypiHub image-to-video requests use input_reference", async () => {prompt: "animate",seconds: 5,resolution: "2k",- input_reference: "data:image/png;base64,AQID",+ first_frame: "data:image/png;base64,AQID",});});-test("HypiHub preserves video/audio reference arrays for its upstream passthrough", async () => {+test("HypiHub sends audio references through the public top-level field", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "minimax-h3");assert.ok(route);const result = await route.compile({@@ -64,11 +64,11 @@ test("HypiHub preserves video/audio reference arrays for its upstream passthroug}, resolveAudio);assert.deepEqual(result.input, {prompt: "animate", seconds: 5, resolution: "2k",- extra: { reference_audios: ["data:audio/wav;base64,AQID"] },+ reference_audios: ["data:audio/wav;base64,AQID"],});});-test("HypiHub Seedance multimodal references ride in the public extra passthrough", async () => {+test("HypiHub Seedance sends reference images through the public top-level field", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "seedance-2");assert.ok(route);const result = await route.compile({@@ -93,11 +93,11 @@ test("HypiHub Seedance multimodal references ride in the public extra passthrougaspect_ratio: "16:9",generate_audio: true,web_search: false,- extra: { reference_image_urls: ["data:image/png;base64,AQID", "data:image/png;base64,AQID"] },+ reference_image_urls: ["data:image/png;base64,AQID", "data:image/png;base64,AQID"],});});-test("HypiHub MiniMax reference mode preserves image arrays in extra", async () => {+test("HypiHub MiniMax reference mode preserves the public image array", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "minimax-h3");assert.ok(route);const result = await route.compile({ ports: {@@ -108,7 +108,35 @@ test("HypiHub MiniMax reference mode preserves image arrays in extra", async ()assert.deepEqual(result.input, {prompt: "animate", seconds: 6, aspect_ratio: "16:9",resolution: "2k",- extra: { reference_image_urls: ["data:image/png;base64,AQID"] },+ reference_image_urls: ["data:image/png;base64,AQID"],+ });+});++test("HypiHub uses ref_video_url for one video and the public array for multiple videos", async () => {+ const route = hypiHubRoutes.find((item) => item.capability.name === "minimax-h3");+ assert.ok(route);+ const video = { ...image, mediaType: "video/mp4" };+ const resolveVideo = async (artifact: typeof video) => `https://hypit.ai/files/${artifact.digest.slice(-1)}.mp4`;++ const single = await route.compile({ ports: {+ prompt: ["animate"], duration: [6],+ referenceVideo: [{ role: "video", artifact: video }],+ } }, resolveVideo);+ assert.deepEqual(single.input, {+ prompt: "animate", seconds: 6, resolution: "2k",+ ref_video_url: "https://hypit.ai/files/1.mp4",+ });++ const multiple = await route.compile({ ports: {+ prompt: ["animate"], duration: [6],+ referenceVideo: [+ { role: "video", artifact: video },+ { role: "video", artifact: { ...video, digest: `sha256:${"2".repeat(64)}` } },+ ],+ } }, resolveVideo);+ assert.deepEqual(multiple.input, {+ prompt: "animate", seconds: 6, resolution: "2k",+ reference_videos: ["https://hypit.ai/files/1.mp4", "https://hypit.ai/files/2.mp4"],});});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 57123a37..427b8fd4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1960,6 +1960,13 @@ importers:'@hypit/runtime-kit':specifier: workspace:*version: link:../runtime-kit+ devDependencies:+ '@hypit/driver-node':+ specifier: workspace:*+ version: link:../driver-node+ '@hypit/seedance':+ specifier: workspace:*+ version: link:../seedancepackages/provider-image-opencv-local:dependencies: