Skip to content

armgit / hypit

Public Imported from GitHub
0

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.

fix(providers): resolve requests before transfers and retain execution evidence

kashorinfb811976f5d5
diff --git a/examples/provider-package/README.md b/examples/provider-package/README.md
index 0d61a35d..19afa7f3 100644
--- a/examples/provider-package/README.md
+++ b/examples/provider-package/README.md
@@ -23,6 +23,18 @@ The example service uses Bearer authentication for these API operations:
| Read rates | `GET /rates?model=gpt-image-2` → service-owned fields and a `description` stating rates, units and conditions |
| Collect result | GET the signed image URL without the account key |
+HTTP failures expose a public `{ "error": { "code": "…", "message": "…" } }` and optional
+`X-Request-Id`; failed tasks carry the same `error` object. The Provider preserves these fields,
+the failed API operation or task ID, and omits unrelated response fields and signed URLs.
+This example schema is not a universal service-error format: adapt the interpretation to the chosen API.
+
+Known request limits and model identity are resolved before the media URL resolver can upload.
+This service exposes no model-catalogue endpoint, so the example invents none. Services with a
+documented query can use it before transferring references. Request preparation, submission and
+collection report live activity through `reportProgress`; queued/running task responses supply
+pending progress between calls. The Provider follows the selected mapping without substituting
+another model or account after a failure.
+
`start` records the received task ID through `checkpoint` before returning it. Runtime owns polling,
capacity and durable operation state. `poll` returns `ready` for completed remote work; `collect`
stores the image through `context.resources` and returns the Model's declared value. The Provider
diff --git a/examples/provider-package/packages/provider-images/src/provider.ts b/examples/provider-package/packages/provider-images/src/provider.ts
index 47827300..7fc3e23f 100644
--- a/examples/provider-package/packages/provider-images/src/provider.ts
+++ b/examples/provider-package/packages/provider-images/src/provider.ts
@@ -1,6 +1,6 @@
import { canonicalize, defineEndpointPackage, wakeAfter } from "@hypit/hypit/endpoint-kit";
import type { AsyncEndpoint, CredentialRef, EndpointRequest } from "@hypit/hypit/endpoint-kit";
-import { compileWireRequest, generationTypes, sealGeneratedImageSet } from "@hypit/hypit/generation";
+import { compileWireRequest, generationTypes, sealGeneratedImageSet, selectWireModelForRequest } from "@hypit/hypit/generation";
import type { GenerationRequest, GenerationWireMapping } from "@hypit/hypit/generation";
export const providerModule = { name: "@example/provider-images", version: "1" } as const;
@@ -25,6 +25,13 @@ function text(value: unknown): string {
if (typeof value !== "string" || value.length === 0) throw new Error("Expected nonempty service text");
return value;
}
+// This illustrative service documents these fields as its public failure evidence.
+function publicFailure(value: unknown): { code: string; message: string } | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const error = value as Record<string, unknown>;
+ if (typeof error.code !== "string" || typeof error.message !== "string") return undefined;
+ return { code: error.code, message: error.message.replace(/https?:\/\/\S+/giu, "[redacted-url]") };
+}
function address(value: string): string {
const url = new URL(value);
if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) {
@@ -57,7 +64,16 @@ export function createImageProvider(options: {
...init, headers: { ...init.headers, authorization: `Bearer ${secret}` },
signal: AbortSignal.timeout(30_000),
});
- if (!response.ok) throw new Error(`Image service ${path} returned HTTP ${response.status}`);
+ if (!response.ok) {
+ let error: ReturnType<typeof publicFailure>;
+ try { error = publicFailure(object(await response.json()).error); }
+ catch { /* A missing public error body leaves the HTTP evidence intact. */ }
+ const requestId = response.headers.get("x-request-id");
+ throw Object.assign(new Error(`Image service ${init.method ?? "GET"} ${path} returned HTTP ${response.status}`
+ + (requestId === null ? "" : `; request=${requestId}`)
+ + (error === undefined ? "" : `; ${error.code}: ${error.message}`)),
+ error === undefined ? {} : { code: error.code });
+ }
return object(await response.json());
}
const endpoint: AsyncEndpoint = {
@@ -65,7 +81,11 @@ export function createImageProvider(options: {
const supported = support(context.need);
if (supported.status === "unsupported") throw new Error(supported.reason);
const secret = key(context.credentials);
- const request = await compileWireRequest(mapping, context.need.constraints as unknown as GenerationRequest,
+ const authored = context.need.constraints as unknown as GenerationRequest;
+ const model = selectWireModelForRequest(mapping, authored);
+ // This service has no catalogue query; its known request limits were checked above.
+ await context.reportProgress?.({ phase: `Preparing image request: ${model}` });
+ const request = await compileWireRequest(mapping, authored,
async (artifact) => {
const bytes = await context.resources.get(artifact.resource);
if (bytes === undefined) throw new Error("Reference image is unavailable");
@@ -74,6 +94,7 @@ export function createImageProvider(options: {
});
return address(text(upload.url));
});
+ await context.reportProgress?.({ phase: `Submitting image request: ${model}` });
const task = await json("/tasks", secret, {
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(request),
});
@@ -87,15 +108,20 @@ export function createImageProvider(options: {
if (task.state === "queued" || task.state === "running") {
return wakeAfter({ id }, interval, Date.now(), { phase: task.state });
}
- if (task.state === "failed") return {
- status: "failed", failure: { code: "IMAGE_SERVICE_FAILED", message: "Image service task failed" },
- };
+ if (task.state === "failed") {
+ const error = publicFailure(task.error);
+ return { status: "failed", receipt: { id }, failure: {
+ code: error?.code ?? "IMAGE_SERVICE_FAILED",
+ message: `Image service task ${id} failed${error === undefined ? "" : `: ${error.message}`}`,
+ } };
+ }
if (task.state !== "succeeded") throw new Error("Image service returned an unknown task state");
return { status: "ready", handle: { id, url: address(text(task.url)) } };
},
async collect(context) {
// The service returns a signed asset URL; account credentials go only to its API.
const url = address(text(object(context.handle).url));
+ await context.reportProgress?.({ phase: "Receiving generated image" });
const response = await fetcher(url, { signal: AbortSignal.timeout(60_000) });
if (!response.ok) throw new Error(`Image download returned HTTP ${response.status}`);
const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();
@@ -113,8 +139,11 @@ export function createImageProvider(options: {
actionLimits: { submit: { concurrency: 1 }, poll: { concurrency: 4 }, collect: { concurrency: 1 } },
pricing: { kind: "page", url: `${base}/pricing` },
async readPricing(context) {
- const source = `${base}/rates?model=gpt-image-2`;
- const rates = await json("/rates?model=gpt-image-2", key(await context.credentials()));
+ const model = selectWireModelForRequest(mapping, context.request.constraints as unknown as GenerationRequest,
+ context.request.pendingInputs?.map((input) => input.input));
+ const path = `/rates?model=${encodeURIComponent(model)}`;
+ const source = `${base}${path}`;
+ const rates = await json(path, key(await context.credentials()));
return [{ source, data: canonicalize(rates), summary: text(rates.description) }];
},
capabilities: [{ capability, returns: generationTypes.imageSet, lifecycle: "asynchronous", supports: support, endpoint }],
diff --git a/examples/provider-package/packages/provider-images/test/provider.test.ts b/examples/provider-package/packages/provider-images/test/provider.test.ts
index e59f9227..1d460393 100644
--- a/examples/provider-package/packages/provider-images/test/provider.test.ts
+++ b/examples/provider-package/packages/provider-images/test/provider.test.ts
@@ -11,6 +11,7 @@ test("project Provider maps a reference, retains its receipt and collects throug
const resources = new MemoryResourceStore();
const source = await resources.put(new Uint8Array([1, 2, 3]), "image/png");
const calls: string[] = [];
+ const progress: string[] = [];
let checkpoint: unknown;
const provider = createImageProvider({
instance: "images.personal", pool: "images.personal", baseUrl: "https://images.example",
@@ -19,15 +20,18 @@ test("project Provider maps a reference, retains its receipt and collects throug
const url = new URL(String(input)); calls.push(url.pathname);
if (url.hostname === "assets.example") {
assert.equal(init?.headers, undefined);
+ assert.equal(progress.at(-1), "Receiving generated image");
return new Response(new Uint8Array([4, 5, 6]), { headers: { "content-type": "image/webp" } });
}
assert.equal((init?.headers as Record<string, string>).authorization, "Bearer test-key");
if (url.pathname === "/rates") return Response.json({ description: "$0.05 per 1K image", unit: "image", usd: 0.05 });
if (url.pathname === "/uploads") {
+ assert.equal(progress.at(-1), "Preparing image request: gpt-image-2");
assert.deepEqual(new Uint8Array(await (init?.body as Blob).arrayBuffer()), new Uint8Array([1, 2, 3]));
return Response.json({ url: "https://assets.example/reference.png" });
}
if (url.pathname === "/tasks") {
+ assert.equal(progress.at(-1), "Submitting image request: gpt-image-2");
assert.deepEqual(JSON.parse(String(init?.body)), {
model: "gpt-image-2", input: { prompt: "A portrait", ratio: "9:16", size: "1K", references: ["https://assets.example/reference.png"] },
});
@@ -53,6 +57,7 @@ test("project Provider maps a reference, retains its receipt and collects throug
need, command: { kind: "fulfill-need", id: "command:example", need }, operation: "operation:example",
resources, credentials: { apiKey: { secret: "test-key" } },
checkpoint: async (value) => { checkpoint = value; },
+ reportProgress: async (value) => { progress.push(value.phase); },
};
const pricing = await provider.readPricing!({ request: need, credentials: async () => context.credentials });
assert.equal(pricing[0]?.summary, "$0.05 per 1K image");
@@ -64,7 +69,64 @@ test("project Provider maps a reference, retains its receipt and collects throug
assert.equal(images[0]?.mediaType, "image/webp");
assert.deepEqual(await resources.get(images[0]!.resource), new Uint8Array([4, 5, 6]));
assert.deepEqual(calls, ["/rates", "/uploads", "/tasks", "/tasks/received-task", "/output.webp"]);
+ assert.deepEqual(progress, ["Preparing image request: gpt-image-2", "Submitting image request: gpt-image-2", "Receiving generated image"]);
assert.equal(provider.offers[0]!.supports!({ ...need, constraints: canonicalize(sealGptImage2Request({
prompt: ["A portrait"], aspectRatio: ["9:16"], resolution: ["2K"],
})) }).status, "unsupported");
});
+
+test("project Provider retains public submission and task errors without suggesting a different account", async () => {
+ for (const failureAt of ["submission", "task"] as const) {
+ const calls: string[] = [];
+ let checkpointed = false;
+ const provider = createImageProvider({
+ instance: "images.personal", pool: "images.personal", baseUrl: "https://images.example",
+ apiKey: { store: "os", key: "images.personal" }, pollIntervalMs: 0,
+ fetch: async (input) => {
+ const path = new URL(String(input)).pathname;
+ calls.push(path);
+ const error = { code: "request_rejected", message: "This request is unavailable; resource https://assets.example/private?token=hidden" };
+ if (failureAt === "submission") return Response.json({ error, debug: { secret: "not-public" } }, {
+ status: 403, headers: { "x-request-id": "request-one" },
+ });
+ if (path === "/tasks") return Response.json({ id: "task-one" });
+ return Response.json({ state: "failed", error, debug: { secret: "not-public" } });
+ },
+ });
+ const need = { id: "need:failure", capability, returns: generationTypes.imageSet,
+ constraints: canonicalize(sealGptImage2Request({ prompt: ["A portrait"], aspectRatio: ["1:1"], resolution: ["1K"] })),
+ result: "result:failure" };
+ const registry = new EndpointRegistry();
+ await provider.install(registry);
+ const resolved = registry.resolve(need);
+ assert.equal(resolved.status, "resolved");
+ assert.equal(resolved.registration.kind, "asynchronous");
+ const endpoint = resolved.registration.endpoint;
+ const context: EndpointStartContext = {
+ command: { kind: "fulfill-need", id: "command:failure", need }, need, operation: "operation:failure",
+ resources: new MemoryResourceStore(), credentials: { apiKey: { secret: "test-key" } },
+ checkpoint: async () => { checkpointed = true; },
+ };
+ if (failureAt === "submission") {
+ await assert.rejects(async () => await endpoint.start(context), (error: Error & { code?: string }) => {
+ assert.equal(error.code, "request_rejected");
+ assert.match(error.message, /POST \/tasks returned HTTP 403; request=request-one; request_rejected: This request is unavailable/u);
+ assert.doesNotMatch(error.message, /not-public|token=hidden|test-key/u);
+ return true;
+ });
+ assert.equal(checkpointed, false);
+ assert.deepEqual(calls, ["/tasks"]);
+ } else {
+ const started = await endpoint.start(context);
+ assert.equal(started.status, "pending");
+ const failed = await endpoint.poll({ ...context, handle: started.handle });
+ assert.equal(failed.status, "failed");
+ assert.equal(failed.failure.code, "request_rejected");
+ assert.match(failed.failure.message, /task task-one failed: This request is unavailable/u);
+ assert.doesNotMatch(failed.failure.message, /not-public|token=hidden|test-key/u);
+ assert.deepEqual(failed.receipt, { id: "task-one" });
+ assert.equal(checkpointed, true);
+ assert.deepEqual(calls, ["/tasks", "/tasks/task-one"]);
+ }
+ }
+});
diff --git a/packages/driver-node/README.md b/packages/driver-node/README.md
index e9826e96..f3987ccf 100644
--- a/packages/driver-node/README.md
+++ b/packages/driver-node/README.md
@@ -17,6 +17,11 @@ Build. Credentials are resolved only for slots declared by the selected endpoint
of the same credential are coalesced. Cancellation is best effort and never rolls back completed work.
A failed action retains its receipt and error for the Result; the Driver does not retry or reconcile it.
+Immediate calls and asynchronous submit, poll and collect actions receive the same progress and
+diagnostic callbacks. Progress reaches the caller while the action is running; changes of phase also
+enter the execution log. The Endpoint supplies the content, and the Driver forwards it with the
+selected Endpoint identity without interpreting service-specific phases or treating progress as a receipt.
+
`acceptOperation()` validates an already received value without making a remote call. Runtime can
retain such a sibling result when another Need fails, without polling unfinished jobs to completion.
The Driver validates returned values before offering a command result to Core. It does not load
diff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.ts
index e3076193..f409ad64 100644
--- a/packages/driver-node/src/driver.ts
+++ b/packages/driver-node/src/driver.ts
@@ -22,6 +22,7 @@ import type {
CredentialStore,
CredentialValue,
OperationSnapshot,
+ OperationProgress,
OperationStore,
RuntimeExecutionContext,
RuntimeExecutionResult,
@@ -349,6 +350,23 @@ export class NodeDriver {
return result;
}
+ #endpointObservers(endpoint: string, context?: RuntimeExecutionContext) {
+ let phase: string | undefined;
+ return {
+ reportProgress: async (progress: OperationProgress) => {
+ await context?.reportProgress?.({ endpoint, progress });
+ if (progress.phase !== phase) {
+ phase = progress.phase;
+ await context?.recordExecution?.({ endpoint, kind: "phase", phase });
+ }
+ },
+ ...(context?.recordExecution === undefined ? {} : {
+ reportDiagnostic: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) =>
+ context.recordExecution!({ endpoint, kind: "diagnostic", ...diagnostic }),
+ }),
+ };
+ }
+
async #advanceOperationStep(
operation: OperationSnapshot,
registration: EndpointRegistration,
@@ -374,10 +392,7 @@ export class NodeDriver {
command: structuredClone(command), need: structuredClone(command.need),
resources: this.#resourceStore(operation.build), operation: operation.id,
credentials: await this.#endpointCredentials({ ...registration, credentials: operation.credentials ?? registration.credentials ?? {} }),
- ...(runtimeContext.recordExecution === undefined ? {} : {
- reportDiagnostic: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) =>
- runtimeContext.recordExecution!({ endpoint: operation.endpoint, kind: "diagnostic", ...diagnostic }),
- }),
+ ...this.#endpointObservers(operation.endpoint, runtimeContext),
checkpoint: async (checkpoint: import("@hypit/endpoint-kit").EndpointCheckpoint) => {
await operations.update(operation.id, { status: "pending", ...checkpoint,
submission: "accepted", acknowledgedAt: operation.acknowledgedAt ?? Date.now(), wakeAt: Date.now(), progress: { phase: checkpoint.remoteEnded ? "collecting" : "submitted" } });
@@ -493,7 +508,6 @@ export class NodeDriver {
);
}
}
- let phase: string | undefined;
await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "started" });
try {
const result = await executable.registration.handler({
@@ -501,16 +515,7 @@ export class NodeDriver {
need: structuredClone(executable.command.need),
resources: this.#resourceStore(context?.build),
credentials: await this.#endpointCredentials(executable.registration),
- reportProgress: async (progress) => {
- await context?.reportProgress?.({ endpoint: executable.endpointId, progress });
- if (progress.phase !== phase) {
- phase = progress.phase;
- await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "phase", phase });
- }
- },
- ...(context?.recordExecution === undefined ? {} : {
- reportDiagnostic: (diagnostic) => context.recordExecution!({ endpoint: executable.endpointId, kind: "diagnostic", ...diagnostic }),
- }),
+ ...this.#endpointObservers(executable.endpointId, context),
});
const event = await this.#endpointEvent(state, executable, result);
await context?.recordExecution?.({ endpoint: executable.endpointId, kind: "completed" });
diff --git a/packages/driver-node/test/scheduler.test.ts b/packages/driver-node/test/scheduler.test.ts
index 266e1078..552f8b3e 100644
--- a/packages/driver-node/test/scheduler.test.ts
+++ b/packages/driver-node/test/scheduler.test.ts
@@ -10,7 +10,7 @@ import type { AsyncEndpoint } from "@hypit/endpoint-kit";
import {
LocalBuildScheduler,
} from "@hypit/runtime";
-import type { OperationSnapshot, OperationStore, OperationUpdate } from "@hypit/runtime";
+import type { OperationSnapshot, OperationStore, OperationUpdate, RuntimeExecutionContext } from "@hypit/runtime";
import { capabilities, createGreetingBuild, createParallelGreetingBuild, producers as greetingProducers, types } from "../../core/test/greeting-fixture.js";
function memoryOperations(): OperationStore {
@@ -270,6 +270,63 @@ test("an asynchronous Endpoint starts once and is polled until complete", async
assert.equal((await operations.read(pending.operation))?.status, "completed");
});
+test("asynchronous actions expose progress before returning without treating it as acknowledgement", async () => {
+ const operations = memoryOperations();
+ const progress: unknown[] = [];
+ const log: unknown[] = [];
+ let reportReady!: () => void;
+ let finishAction!: () => void;
+ const reported = new Promise<void>((resolve) => { reportReady = resolve; });
+ const finish = new Promise<void>((resolve) => { finishAction = resolve; });
+ const executor = asyncExecutor({
+ async start(context) {
+ await context.reportProgress?.({ phase: "Preparing inputs", completed: 0, total: 2, unit: "files" });
+ await context.reportProgress?.({ phase: "Preparing inputs", completed: 1, total: 2, unit: "files" });
+ reportReady();
+ await finish;
+ return { status: "pending", handle: { job: "one" }, receipt: { id: "one" } };
+ },
+ async poll(context) {
+ await context.reportProgress?.({ phase: "Reading remote result" });
+ return { status: "ready", handle: context.handle };
+ },
+ async collect(context) {
+ await context.reportProgress?.({ phase: "Receiving output" });
+ return { status: "completed", result: { value: { kind: "inline", value: "done" } } };
+ },
+ }, operations);
+ const context: RuntimeExecutionContext = {
+ build: "progress-build",
+ reportProgress: async (value) => { progress.push(value); },
+ recordExecution: async (value) => { log.push(value); },
+ };
+ const running = executor.run(createGreetingBuild(), context);
+ try {
+ await reported;
+ assert.deepEqual(progress, [0, 1].map((completed) => ({ endpoint: "generation.local",
+ progress: { phase: "Preparing inputs", completed, total: 2, unit: "files" },
+ })));
+ assert.deepEqual(log, [
+ { endpoint: "generation.local", kind: "started" },
+ { endpoint: "generation.local", kind: "phase", phase: "Preparing inputs" },
+ ]);
+ const [pending] = await operations.list({ build: context.build });
+ assert.equal(pending!.submission, "started");
+ assert.equal(pending!.handle, undefined);
+ assert.equal(pending!.receipt, undefined);
+ } finally { finishAction(); }
+ await running;
+ const [submitted] = await operations.list({ build: context.build });
+ assert.equal(submitted!.receipt!.id, "one");
+ const ready = await executor.advanceOperation(submitted!, context);
+ const completed = await executor.advanceOperation(ready, context);
+ assert.deepEqual(completed.completion, { value: { kind: "inline", value: "done" } });
+ assert.equal(completed.remoteEnded, true);
+ assert.deepEqual(progress.slice(2), ["Reading remote result", "Receiving output"].map((phase) => ({
+ endpoint: "generation.local", progress: { phase },
+ })));
+});
+
test("a submission error ends its attempt and a new Build can submit normally", async () => {
const operations = memoryOperations();
let starts = 0;
diff --git a/packages/endpoint-kit/README.md b/packages/endpoint-kit/README.md
index bfc5dae9..7faeab45 100644
--- a/packages/endpoint-kit/README.md
+++ b/packages/endpoint-kit/README.md
@@ -35,12 +35,21 @@ without changing Core demand. Each resource declares a `limit` and optional `uni
A capability may add `resources` and a pure `unitsForRequest(request)` resolver for quantities of
already declared resources. Runtime admits all claims atomically for one `fulfill-need` Command.
-A long immediate call can report its current activity with
+A running immediate call or asynchronous action can report its current activity with
`await context.reportProgress?.({ phase: "processing", completed: 12, total: 40, unit: "items" })`.
The Provider chooses meaningful phases and quantities and reports non-secret, human-readable facts.
The Runtime attaches them to the currently executing Command; they do not change its outcome,
scheduling or Core facts. Completion clears the live activity. Direct callers may omit the callback.
-For asynchronous work, return `progress` in the existing pending outcome instead.
+For asynchronous work, these callbacks describe work inside `start`, `poll` or `collect`, such as
+preparing references or downloading results. A returned `pending.progress` describes the acknowledged
+remote task between actions. Neither form of progress substitutes for a received task ID or receipt.
+
+Separate facts available from the request from actions needed to fulfill it. Check known input
+limits and determine the requested service operation before transferring its resources. If the
+service exposes account-specific capability information, use that evidence for the selected request;
+an API without such a query needs no invented discovery step. A Provider owns the meaning of its
+public error codes and reasons. Preserve the failed operation and that evidence, distinguishing what
+was never submitted from a submission whose remote outcome is unknown.
Asynchronous execution moves forward through `start`, `poll`, and optional `collect`. `start` returns
a task handle; `pending` means an acknowledged task is still running. `ready` records remote completion
diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.ts
index 8a612692..878dd5ce 100644
--- a/packages/endpoint-kit/src/index.ts
+++ b/packages/endpoint-kit/src/index.ts
@@ -101,7 +101,7 @@ export type EndpointInvocationContext = {
readonly credentials: Readonly<Record<string, EndpointCredential>>;
/** Explicit non-secret diagnostic output. The Provider owns its content, never its storage. */
readonly reportDiagnostic?: (diagnostic: import("@hypit/runtime").ExecutionDiagnostic) => Promise<void>;
- /** Report non-secret activity of a long local call without creating a remote Operation. */
+ /** Report non-secret activity while an immediate call or asynchronous action is still running. */
readonly reportProgress?: (progress: OperationProgress) => Promise<void>;
};
diff --git a/packages/generation/README.md b/packages/generation/README.md
index 9b1262c2..00b1c83f 100644
--- a/packages/generation/README.md
+++ b/packages/generation/README.md
@@ -9,6 +9,16 @@ implementations. `sealGenerationPortTable` describes a model's inputs; `Generati
`selectWireModelForRequest` applies the same route selection without resolving media bytes. During
planning, a Provider may add the model-port names already attached as future graph inputs; the
selector does not inspect graph structure or interpret media roles.
+Route selection here applies declared input-mode mappings for the already chosen exact capability;
+it does not search for an alternative model, service or account.
+
+`compileWireRequest` awaits its media URL resolver, so compilation can have external effects when
+that resolver uploads files. Use `selectWireModelForRequest` for request identity and known-port
+checks before those effects; pricing and execution can share the same mapping. A Provider can also
+describe its API operation from the authored ports. Service-specific support queries belong to that
+Provider and only use operations its API actually exposes. The generic helper neither queries a
+catalogue nor switches to another route after a failure. Actual URL resolution belongs to request
+execution, not to discovering a model name or making a planning placeholder.
The package owns `GenerationRequest`, `GeneratedImageSet` and `GeneratedVideoSet` identities,
schemas, validators and graph facets. Generated sets are atomic Products: a Provider persists the
diff --git a/packages/provider-hypihub/README.md b/packages/provider-hypihub/README.md
index aaa10ed8..9e6e993e 100644
--- a/packages/provider-hypihub/README.md
+++ b/packages/provider-hypihub/README.md
@@ -36,6 +36,32 @@ route, and Grok 1.5 Preview remains the Preview model. A deployment's current ca
newer models or omit one implemented here. Availability and unsupported-input errors retain their
service explanation; they do not imply expired credentials or authorize substituting another model.
+Before resolving or uploading references, the Provider prepares the exact model and operation from
+the authored ports and its mapping, then queries that model's authenticated directory entry. Image
+editing is determined from the mapped media inputs, without manufacturing placeholder URLs or
+uploading to discover the request mode. The same preparation serves images, videos and speech.
+The request is then translated with real reference URLs and submitted to the selected operation.
+These are internal Provider functions; Author Sources, CLI commands and Runtime scheduling are unchanged.
+
+Progress identifies the directory query, request preparation and submission. A directory failure
+retains the model, operation and service evidence, and states that this invocation uploaded no
+references and submitted no generation. A missing or malformed operation list leaves support unknown;
+an explicit list without the requested operation reports the actual list. No alternative model,
+operation or account is attempted. Directory support alone does not establish balance, every input
+combination or eventual generation success. Preparation failure also reports that generation was not
+submitted; an interrupted submission retains its actual evidence without claiming no remote work exists.
+
+The Provider interprets HypiHub's [HTTP errors](https://hypit.ai/api-reference/errors/) and
+[job errors](https://hypit.ai/api-reference/jobs/) locally. Failures retain the service code,
+HTTP method/route/status, requested model and `X-Request-Id` when available, plus the public reason.
+`Retry-After` remains evidence and does not start another generation attempt. Job failures retain
+`error_code`, `error` and their receipt even when the create response is already terminal.
+Known error messages are not cut to a fixed prefix; only an unstructured non-JSON response uses
+a marked excerpt. Unrelated response fields and signed asset URLs are not diagnostic content.
+Runtime and Result retain ordinary failure codes/messages without interpreting HypiHub fields.
+Immediate Endpoint exceptions keep the same evidence in their message. A `401` alone does not
+choose OAuth over API-key configuration or establish that another login will fix the account.
+
For moving portraits, [Volcengine Matting](../volcengine-matting/README.md) maps
`@hypit/volcengine-matting@1#matte-portrait-video` to `POST /v1/videos` with
`model: "matte-portrait-video"`, `ref_video_url` and `format` (`WEBM` by default, or `MOV`).
@@ -148,7 +174,7 @@ Execution policy remains local to this Provider:
| `requestTimeoutMs` | 300 seconds | ordinary Provider HTTP requests |
| `oauthRequestTimeoutMs` | 30 seconds | OAuth token exchange and refresh |
| `pricingRequestTimeoutMs` | 30 seconds | authenticated pricing requests |
-| `operationTimeoutMs` | 20 minutes | one remote asynchronous operation |
+| `operationTimeoutMs` | 20 minutes | how long this Provider observes one asynchronous operation; expiry does not cancel the remote job |
| `uploadConcurrency` | 8 | whole file sessions per origin/credential within this process |
| `uploadPartTimeoutMs` | 5 minutes | one upload part |
| `uploadPartAttempts` | 3 | attempts for one upload part |
diff --git a/packages/provider-hypihub/src/errors.ts b/packages/provider-hypihub/src/errors.ts
new file mode 100644
index 00000000..1d5ca876
--- /dev/null
+++ b/packages/provider-hypihub/src/errors.ts
@@ -0,0 +1,61 @@
+/** HypiHub's public error envelope, kept at the service boundary. */
+function record(value: unknown): Record<string, unknown> | undefined {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown> : undefined;
+}
+function text(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
+}
+
+// Responses may mention a signed asset URL. Keep the reason, not its access capability.
+export function safeHypiHubReason(value: string): string {
+ return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");
+}
+
+export class HypiHubServiceError extends Error {
+ constructor(readonly code: string, message: string) { super(message); }
+}
+
+export class HypiHubHttpError extends HypiHubServiceError {
+ readonly retryAfterMs?: number;
+ constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,
+ request: { readonly method: string; readonly url: string; readonly model?: string }) {
+ let body: Record<string, unknown> | undefined;
+ try { body = record(JSON.parse(bodyText)); } catch { /* Non-JSON gateway failures still have HTTP evidence. */ }
+ const error = record(body?.error);
+ const flatError = text(body?.error);
+ const code = text(error?.code)
+ ?? (flatError !== undefined && /^[a-z][a-z0-9_]*$/iu.test(flatError) ? flatError : "HYPIHUB_HTTP_ERROR");
+ const reason = text(error?.message) ?? text(body?.error_description)
+ ?? (flatError !== code ? flatError : undefined)
+ ?? (body === undefined ? text(bodyText.slice(0, 2000)) : undefined);
+ const url = new URL(request.url);
+ const model = request.model ?? url.searchParams.get("model")
+ ?? (url.pathname.includes("/models/") ? decodeURIComponent(url.pathname.split("/models/")[1]!) : undefined);
+ const requestId = text(response.headers.get("x-request-id"));
+ const retryAfter = text(response.headers.get("retry-after"));
+ const facts = [
+ `HypiHub HTTP ${status}`, code, `${request.method} ${url.origin}${url.pathname}`,
+ ...(model == null ? [] : [`model=${model}`]),
+ ...(requestId === undefined ? [] : [`request=${requestId}`]),
+ ...(retryAfter === undefined ? [] : [`retry-after=${retryAfter}`]),
+ ];
+ super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeHypiHubReason(reason)}`}`
+ + (body === undefined && bodyText.length > 2000 ? " [response excerpt truncated]" : ""));
+ const delay = retryAfter === undefined ? NaN : /^\d+$/u.test(retryAfter)
+ ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();
+ if (Number.isFinite(delay)) this.retryAfterMs = Math.max(0, delay);
+ }
+}
+
+export function hypiHubJobFailure(job: Record<string, unknown>, id: string): HypiHubServiceError | undefined {
+ const status = job.status;
+ if (!["failed", "queue_expired", "canceled", "cancelled"].includes(String(status))) return undefined;
+ const error = record(job.error);
+ const code = text(job.error_code) ?? text(error?.code) ?? "HYPIHUB_JOB_FAILED";
+ const reason = text(job.error) ?? text(error?.message) ?? text(job.message) ?? text(job.reason) ?? text(job.detail);
+ const model = text(job.model);
+ return new HypiHubServiceError(code,
+ `HypiHub job ${id} ${status}; ${code}${model === undefined ? "" : `; model=${model}`}`
+ + (reason === undefined ? "" : `: ${safeHypiHubReason(reason)}`));
+}
diff --git a/packages/provider-hypihub/src/oauth.ts b/packages/provider-hypihub/src/oauth.ts
index 95f6125f..e6b8c0b7 100644
--- a/packages/provider-hypihub/src/oauth.ts
+++ b/packages/provider-hypihub/src/oauth.ts
@@ -1,6 +1,7 @@
import type { EndpointCredential } from "@hypit/endpoint-kit";
import { decodeOAuth2Credential, encodeOAuth2Credential } from "@hypit/runtime";
import { requestDeadline } from "@hypit/runtime-kit";
+import { HypiHubHttpError } from "./errors.js";
const OAUTH_CLIENT_ID = "hyc_d5d5e8e7131b0c877756e66c";
const REFRESH_SKEW_MS = 60_000;
@@ -78,10 +79,12 @@ export function createHypiHubAuth(options: {
signal: deadline.signal,
}));
const text = await deadline.wait(response.text());
+ if (!response.ok) throw new HypiHubHttpError(response.status, response, text, {
+ method: "POST", url: tokenEndpoint,
+ });
let body: OAuthTokenResponse;
try { body = JSON.parse(text) as OAuthTokenResponse; }
catch { throw new Error(`HypiHub OAuth refresh returned invalid JSON (${response.status})`); }
- if (!response.ok) throw new Error(`HypiHub OAuth refresh failed (${response.status}): ${text.slice(0, 200)}`);
assert(typeof body.access_token === "string" && body.access_token.length > 0,
"HypiHub OAuth refresh returned no access token");
accessToken = body.access_token;
diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.ts
index 90700b0a..4550872f 100644
--- a/packages/provider-hypihub/src/provider.ts
+++ b/packages/provider-hypihub/src/provider.ts
@@ -16,10 +16,12 @@ import {
} from "@hypit/whisperx";
import type { WhisperXTranscriptResponse } from "@hypit/whisperx";
import { hypiHubRouteForCapability, hypiHubRoutes } from "./routes.js";
+import type { HypiHubModelOperation } from "./routes.js";
import { HypiHubUploader } from "./upload.js";
import type { RuntimeDoctorDiagnostic } from "@hypit/runtime-kit";
import { createHypiHubAuth, hypiHubCredentialNeedsRefresh } from "./oauth.js";
import type { HypiHubAuth } from "./oauth.js";
+import { HypiHubHttpError, HypiHubServiceError, hypiHubJobFailure } from "./errors.js";
export const hypiHubProviderModuleRef = { name: "@hypit/provider-hypihub", version: "1" } as const;
@@ -64,18 +66,15 @@ function apiBaseUrl(value: string): string {
}
function credential(credentials: Readonly<Record<string, EndpointCredential>>) {
const value = credentials.apiKey?.secret;
- assert(typeof value === "string" && value.length > 0, "HypiHub login is unavailable; run hypit auth login for HypiHub");
+ assert(typeof value === "string" && value.length > 0, "HypiHub apiKey credential is unavailable; configure this Endpoint's credential with a HypiHub API key or OAuth login");
return credentials.apiKey!;
}
-function guidedMessage(error: unknown): string {
- const message = error instanceof Error ? error.message : String(error);
- return /API key is unavailable|HypiHub login is unavailable|HTTP 401\b/iu.test(message)
- ? `${message}. Sign in to HypiHub at https://hypit.ai with hypit auth login`
- : message;
+function failureMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
}
function failure(error: unknown): EndpointOutcome {
- const message = guidedMessage(error);
- return { status: "failed", failure: { code: "HYPIHUB_ERROR", message } };
+ const message = failureMessage(error);
+ return { status: "failed", failure: { code: error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR", message } };
}
function jobId(value: Record<string, unknown>): string {
@@ -84,17 +83,13 @@ function jobId(value: Record<string, unknown>): string {
return id;
}
-type HypiHubModelOperation = "images" | "image_edits" | "videos" | "audio_speech" | "transcriptions";
-
async function verifyModelRoute(client: HypiHubClient, auth: HypiHubAuth, model: string, operation: HypiHubModelOperation): Promise<void> {
const card = await client.json(`/models/${encodeURIComponent(model)}`, auth);
const endpoints = card.endpoints;
- assert(Array.isArray(endpoints) && endpoints.includes(operation),
- `HypiHub model ${model} is not enabled for ${operation} with this API key`);
-}
-
-class HypiHubHttpError extends Error {
- constructor(readonly status: number, message: string) { super(message); }
+ assert(Array.isArray(endpoints) && endpoints.every((value) => typeof value === "string"),
+ `HypiHub model ${model} returned no valid operation list; support for ${operation} is unknown`);
+ assert(endpoints.includes(operation),
+ `HypiHub model ${model} does not list operation ${operation}; listed operations: ${endpoints.join(", ") || "none"}`);
}
class HypiHubClient {
@@ -141,7 +136,13 @@ class HypiHubClient {
await auth.refresh();
return await this.json(path, auth, init, false, onResponse);
}
- if (!response.ok) throw new HypiHubHttpError(response.status, `HypiHub returned HTTP ${response.status}: ${text.slice(0, 300)}`);
+ if (!response.ok) {
+ const input = typeof init.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : undefined;
+ throw new HypiHubHttpError(response.status, response, text, {
+ method: init.method ?? "GET", url: `${this.baseUrl}${path}`,
+ ...(typeof input?.model === "string" ? { model: input.model } : {}),
+ });
+ }
try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`HypiHub returned invalid JSON (${response.status})`); }
return object(body, "HypiHub response");
} finally { deadline.finish(); }
@@ -210,7 +211,10 @@ class HypiHubClient {
return await this.speech(auth, body, false);
}
if (!response.ok) {
- throw new Error(`HypiHub returned HTTP ${response.status}: ${Buffer.from(bytes).toString("utf8").slice(0, 300)}`);
+ throw new HypiHubHttpError(response.status, response, Buffer.from(bytes).toString("utf8"), {
+ method: "POST", url: `${this.baseUrl}/audio/speech`,
+ ...(typeof body.model === "string" ? { model: body.model } : {}),
+ });
}
const responseType = response.headers.get("content-type")?.split(";", 1)[0] ?? "audio/mpeg";
if (!responseType.includes("json")) return [{ bytes, mediaType: responseType }];
@@ -325,7 +329,7 @@ export async function diagnoseHypiHubProvider(
},
): Promise<readonly RuntimeDoctorDiagnostic[]> {
const apiKey = context.credentials.apiKey?.secret;
- assert(typeof apiKey === "string" && apiKey.length > 0, "HypiHub login is unavailable");
+ assert(typeof apiKey === "string" && apiKey.length > 0, "HypiHub credential is unavailable");
if (hypiHubCredentialNeedsRefresh(apiKey)) return [{
severity: "warning",
code: "HYPIHUB_OAUTH_REFRESH_UNCHECKED",
@@ -377,23 +381,13 @@ export async function diagnoseHypiHubProvider(
if (!available) diagnostics.push({
severity: "error",
code: "HYPIHUB_CAPABILITY_UNAVAILABLE",
- message: `HypiHub login cannot currently route ${capabilityKey(capability)}`,
+ message: `The HypiHub catalogue returned for this credential does not list a route for ${capabilityKey(capability)}`,
subject: capabilityKey(capability),
});
}
return diagnostics;
}
-function generationOperation(route: (typeof hypiHubRoutes)[number], input: Record<string, unknown>): HypiHubModelOperation {
- if (route.media === "audio") return "audio_speech";
- if (route.media === "video") return "videos";
- const hasReferences = Object.entries(input).some(([key, value]) => {
- if (!["images", "reference_images", "reference_image_urls", "reference_videos", "reference_audios", "first_frame", "last_frame"].includes(key)) return false;
- return Array.isArray(value) ? value.length > 0 : typeof value === "string" && value.length > 0;
- });
- return hasReferences ? "image_edits" : "images";
-}
-
async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ResourceStore): Promise<EndpointOutcome> {
const response = await client.json(`/jobs/${encodeURIComponent(id)}/assets`, auth); const items = response.items;
assert(Array.isArray(items) && items.length > 0, "HypiHub job has no assets"); const blobs: BlobRef[] = [];
@@ -401,14 +395,44 @@ async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof
return { status: "completed", result: { value: route.packageResult(blobs) } };
}
-async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {
+async function prepareGeneration(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]) {
const route = hypiHubRouteForCapability(context.need.capability);
- assert(route !== undefined && route.media === "audio", "HypiHub does not implement this exact capability");
+ assert(route !== undefined, "HypiHub does not implement this exact capability");
+ const request = route.prepare(context.need.constraints);
const auth = authFor(context, client);
- const compiled = await route.compile(context.need.constraints, async (artifact, fields) => publicAssetUrl === undefined
- ? await client.upload(artifact, context.resources, auth, fields)
- : await publicAssetUrl(artifact, context.resources, fields));
- await verifyModelRoute(client, auth, compiled.model, "audio_speech");
+ await context.reportProgress?.({ phase: `Reading HypiHub model catalogue: ${request.model} (${request.operation})` });
+ try {
+ await verifyModelRoute(client, auth, request.model, request.operation);
+ } catch (error) {
+ throw new HypiHubServiceError(error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR",
+ `HypiHub model catalogue check failed; model=${request.model}; operation=${request.operation}; references uploaded=0; generation not submitted: ${failureMessage(error)}`);
+ }
+ await context.reportProgress?.({ phase: `Preparing HypiHub request: ${request.model} (${request.operation})` });
+ const uploaded = new Map<string, Promise<string>>();
+ const resolve = (artifact: BlobRef, fields?: Readonly<Record<string, string | number | boolean>>): Promise<string> => {
+ const key = JSON.stringify([artifact.resource, canonicalize(fields ?? {})]);
+ const existing = uploaded.get(key);
+ if (existing !== undefined) return existing;
+ const promise = publicAssetUrl === undefined
+ ? client.upload(artifact, context.resources, auth, fields)
+ : publicAssetUrl(artifact, context.resources, fields);
+ uploaded.set(key, promise);
+ return promise;
+ };
+ let compiled;
+ try {
+ compiled = await request.compile(resolve);
+ } catch (error) {
+ throw new HypiHubServiceError(error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR",
+ `HypiHub request preparation failed; model=${request.model}; operation=${request.operation}; generation not submitted: ${failureMessage(error)}`);
+ }
+ return { route, auth, compiled, operation: request.operation };
+}
+
+async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {
+ const { route, auth, compiled, operation } = await prepareGeneration(client, context, publicAssetUrl);
+ assert(route.media === "audio", "HypiHub audio capabilities use an immediate endpoint");
+ await context.reportProgress?.({ phase: `Submitting HypiHub request: ${compiled.model} (${operation})` });
const audio = await client.speech(auth, { model: compiled.model, ...(compiled.input as Record<string, unknown>) });
const artifacts = await Promise.all(audio.map(async (item) => await context.resources.put(item.bytes, item.mediaType)));
return { value: route.packageResult(artifacts) };
@@ -418,33 +442,20 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
return {
async start(context: EndpointStartContext) {
try {
- const route = hypiHubRouteForCapability(context.need.capability);
- assert(route !== undefined, "HypiHub does not implement this exact capability");
- const auth = authFor(context, client);
- const uploaded = new Map<string, Promise<string>>();
- const resolve = (artifact: BlobRef, fields?: Readonly<Record<string, string | number | boolean>>): Promise<string> => {
- const key = JSON.stringify([artifact.resource, canonicalize(fields ?? {})]);
- const existing = uploaded.get(key);
- if (existing !== undefined) return existing;
- const promise = publicAssetUrl === undefined
- ? client.upload(artifact, context.resources, auth, fields)
- : publicAssetUrl(artifact, context.resources, fields);
- uploaded.set(key, promise);
- return promise;
- };
- const compiled = await route.compile(context.need.constraints, resolve);
+ const { route, auth, compiled, operation } = await prepareGeneration(client, context, publicAssetUrl);
assert(route.media !== "audio", "HypiHub audio capabilities use an immediate endpoint");
const input = compiled.input as Record<string, unknown>;
- const operation = generationOperation(route, input);
const path = operation === "image_edits" ? "/images/edits"
: operation === "images" ? "/images/generations" : "/videos";
- await verifyModelRoute(client, auth, compiled.model, operation);
+ await context.reportProgress?.({ phase: `Submitting HypiHub request: ${compiled.model} (${operation})` });
const response = await client.json(path, auth, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": context.operation }, body: JSON.stringify({ model: compiled.model, ...input }) });
const status = response.status;
const remoteEnded = status === "succeeded" || status === "completed";
const handle: Handle = { contract: "hypit.hypihub-operation@1", jobId: jobId(response), route: capabilityKey(route.capability), startedAt: Date.now() };
const receipt = { id: handle.jobId };
await context.checkpoint?.({ handle: canonicalize(handle), receipt, ...(remoteEnded ? { remoteEnded: true as const } : {}) });
+ const rejected = hypiHubJobFailure(response, handle.jobId);
+ if (rejected !== undefined) return { ...failure(rejected), receipt };
return remoteEnded ? { status: "ready", handle: canonicalize(handle), receipt }
: { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "submitted" }), receipt };
} catch (error) {
@@ -457,15 +468,13 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
assert(route !== undefined && handle.contract === "hypit.hypihub-operation@1" && handle.route === capabilityKey(route.capability), "HypiHub handle is invalid");
if (Date.now() - handle.startedAt > maxOperationMs) {
return { status: "failed",
- failure: { code: "HYPIHUB_OPERATION_TIMEOUT", message: "HypiHub operation timed out" } };
+ receipt: { id: handle.jobId },
+ failure: { code: "HYPIHUB_OPERATION_TIMEOUT", message: `HypiHub job ${handle.jobId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };
}
const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, authFor(context, client)); 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" || status === "cancelled") {
- 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}` : ""}`);
- }
+ const rejected = hypiHubJobFailure(job, handle.jobId);
+ if (rejected !== undefined) return { ...failure(rejected), receipt: { id: handle.jobId } };
if (status !== "succeeded" && status !== "completed") throw new Error(`HypiHub returned unknown job status ${String(status)}`);
return { status: "ready", handle: context.handle, receipt: { id: handle.jobId } };
} catch (error) {
@@ -473,10 +482,12 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
}
},
async collect(context) {
- const handle = object(context.handle, "HypiHub handle") as unknown as Handle;
- const route = hypiHubRouteForCapability(context.need.capability);
- assert(route !== undefined && handle.route === capabilityKey(route.capability), "HypiHub collection route differs");
- return await complete(client, authFor(context, client), route, handle.jobId, context.resources);
+ try {
+ const handle = object(context.handle, "HypiHub handle") as unknown as Handle;
+ const route = hypiHubRouteForCapability(context.need.capability);
+ assert(route !== undefined && handle.route === capabilityKey(route.capability), "HypiHub collection route differs");
+ return await complete(client, authFor(context, client), route, handle.jobId, context.resources);
+ } catch (error) { return failure(error); }
},
};
@@ -529,13 +540,8 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
fetcher: options.fetch ?? globalThis.fetch,
});
const asyncEndpoint = endpoint(client, options.pollIntervalMs ?? 10_000, operationTimeoutMs, options.publicAssetUrl);
- const audioEndpoint: ImmediateEndpointHandler = async (context) => {
- try {
- return await synthesizeAudio(client, context, options.publicAssetUrl);
- } catch (error) {
- throw new Error(guidedMessage(error), { cause: error });
- }
- };
+ const audioEndpoint: ImmediateEndpointHandler = async (context) =>
+ await synthesizeAudio(client, context, options.publicAssetUrl);
const transcriptionModel = options.transcriptionModel?.trim() || "victor-upmeet/whisperx";
const whisperXEndpoint: ImmediateEndpointHandler = async (context) => {
try {
@@ -564,7 +570,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
await context.reportProgress?.({ phase: "Word timing ready" });
return { value: { kind: "inline", value: canonicalize(evidence) } };
} catch (error) {
- throw new Error(guidedMessage(error), { cause: error });
+ throw new Error(failureMessage(error), { cause: error });
}
};
const oauthOrigin = new URL(options.baseUrl ?? "https://hypit.ai").origin;
@@ -574,7 +580,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
readPricing: hypiHubPricingReader(pricingClient, transcriptionModel),
credentials: { apiKey: options.apiKey ?? credentialRef("os", "hypihub.oauth") },
credentialInputs: { apiKey: {
- label: "HypiHub login",
+ label: "HypiHub credential",
acquisition: {
kind: "oauth2-pkce",
authorizationEndpoint: new URL("/oauth/consent", oauthOrigin).toString(),
diff --git a/packages/provider-hypihub/src/routes.ts b/packages/provider-hypihub/src/routes.ts
index a50e9ff3..de2d7ce2 100644
--- a/packages/provider-hypihub/src/routes.ts
+++ b/packages/provider-hypihub/src/routes.ts
@@ -1,5 +1,6 @@
import {
compileWireRequest,
+ selectWireModelForRequest,
generationTypes,
sealGeneratedAudioSet,
sealGeneratedImageSet,
@@ -11,12 +12,21 @@ import type { BlobRef, CapabilityRef, CanonicalValue, StoredValue, TypeRef } fro
import type { EndpointRequest, EndpointSupport } from "@hypit/endpoint-kit";
import { hypiHubMappings } from "./mapping.js";
+export type HypiHubModelOperation = "images" | "image_edits" | "videos" | "audio_speech" | "transcriptions";
+
+/** Request identity is available before resolving any reference into a service URL. */
+export type HypiHubPreparedRequest = {
+ readonly model: string;
+ readonly operation: HypiHubModelOperation;
+ readonly compile: (resolve: GenerationArtifactUrlResolver) => Promise<{ readonly model: string; readonly input: CanonicalValue }>;
+};
+
export type HypiHubRoute = (typeof hypiHubMappings)[number] & {
readonly key: string;
readonly returns: TypeRef;
readonly media: "image" | "video" | "audio";
readonly supports?: (request: EndpointRequest) => EndpointSupport;
- readonly compile: (constraints: CanonicalValue, resolve: GenerationArtifactUrlResolver) => Promise<{ readonly model: string; readonly input: CanonicalValue }>;
+ readonly prepare: (constraints: CanonicalValue) => HypiHubPreparedRequest;
readonly packageResult: (artifacts: readonly BlobRef[]) => StoredValue;
};
@@ -60,11 +70,22 @@ export const hypiHubRoutes: readonly HypiHubRoute[] = hypiHubMappings.map((mappi
return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };
},
} : {}),
- compile: async (constraints, resolve) => {
+ prepare: (constraints) => {
const request = constraints as unknown as GenerationRequest;
const rejection = hypiHubGenerationRejection(mapping, request);
if (rejection !== undefined) throw new Error(rejection);
- return normalizeHypiHubRequest(mapping, await compileWireRequest(mapping, request, resolve));
+ const model = selectWireModelForRequest(mapping, request);
+ // Image editing is determined by authored media ports, before their URLs exist.
+ const hasReferences = Object.entries(mapping.fields).some(([port, field]) =>
+ (field.as === "url" || field.as === "urlArray" || field.as === "itemObject")
+ && (request.ports[port]?.length ?? 0) > 0);
+ const operation = mapping.result === "audio" ? "audio_speech" : mapping.result === "video" ? "videos"
+ : hasReferences ? "image_edits" : "images";
+ return {
+ model,
+ operation,
+ compile: async (resolve) => normalizeHypiHubRequest(mapping, await compileWireRequest(mapping, request, resolve)),
+ };
},
packageResult: (artifacts) => ({
kind: "inline",
diff --git a/packages/provider-hypihub/src/upload.ts b/packages/provider-hypihub/src/upload.ts
index 0860a6b2..942eb13e 100644
--- a/packages/provider-hypihub/src/upload.ts
+++ b/packages/provider-hypihub/src/upload.ts
@@ -2,6 +2,7 @@ import { requestDeadline } from "@hypit/runtime-kit";
import { createHash } from "node:crypto";
import type { HypiHubAuth } from "./oauth.js";
+import { HypiHubHttpError, HypiHubServiceError, safeHypiHubReason } from "./errors.js";
type UploadAuth = HypiHubAuth | string;
@@ -47,12 +48,6 @@ function apiBaseUrl(value: string): string {
return `${trimmed.replace(/\/(?:v1beta|v1)$/iu, "")}/v1`;
}
-class HypiHubHTTPError extends Error {
- constructor(readonly status: number, message: string, readonly retryAfterMs?: number, readonly code?: string) {
- super(message);
- }
-}
-
export type HypiHubUploaderOptions = {
readonly baseUrl: string;
readonly requestTimeoutMs: number;
@@ -149,7 +144,7 @@ export class HypiHubUploader {
private safeReason(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
- return message.replace(/https?:\/\/\S+/giu, "[redacted-url]").slice(0, 300);
+ return safeHypiHubReason(message);
}
private async json(path: string, auth: UploadAuth, init: RequestInit = {}): Promise<Record<string, unknown>> {
@@ -159,7 +154,7 @@ export class HypiHubUploader {
try {
return await this.jsonOnce(path, auth, init, Math.max(1, deadline - Date.now()));
} catch (error) {
- const http = error instanceof HypiHubHTTPError ? error : undefined;
+ const http = error instanceof HypiHubHttpError ? error : undefined;
// Existing-session operations are idempotent. A new session may only
// be retried after an explicit 429 rejection, never an unknown result.
const retryable = http !== undefined
@@ -200,14 +195,9 @@ export class HypiHubUploader {
if (response.ok) throw new Error(`HypiHub returned invalid JSON (${response.status})`);
}
if (!response.ok) {
- const errorBody = body !== null && typeof body === "object" && "error" in body ? body.error : undefined;
- const code = errorBody !== null && typeof errorBody === "object" && "code" in errorBody
- && typeof errorBody.code === "string" ? errorBody.code : undefined;
- const retryAfter = response.headers.get("retry-after");
- const parsedRetry = retryAfter === null ? NaN : /^\d+$/u.test(retryAfter.trim())
- ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();
- throw new HypiHubHTTPError(response.status, `HypiHub returned HTTP ${response.status}: ${this.safeReason(text)}`,
- Number.isFinite(parsedRetry) ? Math.max(0, parsedRetry) : undefined, code);
+ throw new HypiHubHttpError(response.status, response, text, {
+ method: init.method ?? "GET", url: `${this.baseUrl}${path}`,
+ });
}
return object(body, "HypiHub response");
} finally {
@@ -365,12 +355,12 @@ export class HypiHubUploader {
this.log(`multipart upload failed upload=${uploadId} reason=${this.safeReason(error)}`);
try { await this.json(`/files/uploads/${encodeURIComponent(uploadId)}`, auth, { method: "DELETE" }); }
catch (cancelError) {
- if (!(cancelError instanceof HypiHubHTTPError && (cancelError.status === 404
+ if (!(cancelError instanceof HypiHubHttpError && (cancelError.status === 404
|| (cancelError.status === 409 && cancelError.code === "upload_completed")))) {
this.log(`upload cancellation still pending upload=${uploadId} reason=${this.safeReason(cancelError)}`);
}
}
- throw new Error(this.safeReason(error));
+ throw error instanceof HypiHubServiceError ? error : new Error(this.safeReason(error));
}
}
diff --git a/packages/provider-hypihub/test/oauth.test.ts b/packages/provider-hypihub/test/oauth.test.ts
index 67c4ba8d..ae88a528 100644
--- a/packages/provider-hypihub/test/oauth.test.ts
+++ b/packages/provider-hypihub/test/oauth.test.ts
@@ -52,3 +52,20 @@ test("a static HypiHub API key remains an ordinary non-refreshing credential", a
assert.equal(await auth.token(), "static-api-key");
assert.equal(auth.canRefresh(), false);
});
+
+test("rejected refresh retains its public reason and request id without storing response credentials", async () => {
+ const auth = createHypiHubAuth({
+ credential: {
+ secret: encodeOAuth2Credential({ accessToken: "old", refreshToken: "secret-refresh", expiresAt: 1 }),
+ replace: async () => { throw new Error("Rejected refresh must not replace a credential"); },
+ }, baseUrl: "https://hypit.ai", requestTimeoutMs: 1_000,
+ fetch: async () => Response.json({ error: "invalid_grant", error_description: "Refresh grant expired",
+ access_token: "unexpected-secret", refresh_token: "unexpected-refresh" },
+ { status: 400, headers: { "x-request-id": "req-refresh" } }),
+ });
+ await assert.rejects(auth.token(), (error: Error) => {
+ assert.match(error.message, /HTTP 400; invalid_grant; POST https:\/\/hypit.ai\/oauth\/token; request=req-refresh: Refresh grant expired/u);
+ assert.doesNotMatch(error.message, /unexpected|secret-refresh/u);
+ return true;
+ });
+});
diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.ts
index 9aeca6b8..a15f2095 100644
--- a/packages/provider-hypihub/test/provider.test.ts
+++ b/packages/provider-hypihub/test/provider.test.ts
@@ -10,6 +10,7 @@ import { mimoSpeechEndpoints, sealMimoSpeechRequest } from "@hypit/mimo-speech";
import { fishAudioSpeechEndpoints, sealFishAudioSpeechRequest } from "@hypit/fishaudio-speech";
import { elevenLabsSpeechEndpoints, sealElevenLabsSpeechRequest } from "@hypit/elevenlabs-speech";
import { generationTypes } from "@hypit/generation";
+import { gptImageEndpoints, sealGptImage2Request } from "@hypit/gpt-image";
import { sealSeedanceRequest, seedanceEndpoints } from "@hypit/seedance";
import { sealSpeechEvidenceAudio } from "@hypit/speech";
import { speechEvidenceTypes } from "@hypit/speech-evidence";
@@ -588,6 +589,9 @@ test("HypiHub stops before paid submission when a reference upload fails", async
requestTimeoutMs: 1_000,
fetch: async (input, init) => {
const url = String(input);
+ if (url.endsWith("/v1/models/bytedance%2Fseedance-2-mini")) {
+ return Response.json({ endpoints: ["videos"] });
+ }
if (url.endsWith("/v1/files/uploads")) {
return Response.json({
upload_mode: "s3_multipart",
@@ -641,6 +645,7 @@ test("HypiHub stops before paid submission when a reference upload fails", async
assert.equal(uploadAttempts, 2);
assert.equal(cancelled, true);
assert.equal(paidSubmissions, 0);
+ assert.match(outcome.status === "failed" ? outcome.failure.message : "", /request preparation failed.*generation not submitted/u);
assert.doesNotMatch(outcome.status === "failed" ? outcome.failure.message : "", /must-not-leak/u);
});
@@ -811,6 +816,117 @@ test("reference URL reuse includes its authored classification and forwards it t
assert.deepEqual(seen, [{ personReference: true }, { personReference: false }, {}]);
});
+test("generation and voice cloning check their exact catalogue operation before resolving references", async () => {
+ const resources = new MemoryResourceStore();
+ const image = await resources.put(new Uint8Array([1, 2, 3]), "image/png");
+ const voice = await resources.put(wav(100), "audio/wav");
+ const cases = [
+ {
+ endpoint: seedanceEndpoints.mini!, model: "bytedance/seedance-2-mini", operation: "videos", path: "/videos",
+ constraints: sealSeedanceRequest("seedance-2-mini", {
+ prompt: ["A presenter speaks."], referenceImage: [{ role: "image", artifact: image }],
+ resolution: ["720p"], aspectRatio: ["9:16"], duration: [5], generateAudio: [true], webSearch: [false],
+ }),
+ references: true,
+ },
+ {
+ endpoint: gptImageEndpoints.image!, model: "gpt-image-2-image-to-image", operation: "image_edits", path: "/images/edits",
+ constraints: sealGptImage2Request({ prompt: ["Edit this portrait."], aspectRatio: ["1:1"], resolution: ["1K"],
+ images: [{ role: "image", artifact: image }],
+ }),
+ references: true,
+ },
+ {
+ endpoint: gptImageEndpoints.image!, model: "gpt-image-2-text-to-image", operation: "images", path: "/images/generations",
+ constraints: sealGptImage2Request({ prompt: ["A portrait."], aspectRatio: ["1:1"], resolution: ["1K"] }),
+ references: false,
+ },
+ {
+ endpoint: mimoSpeechEndpoints.voiceClone, model: "mimo-v2.5-tts-voiceclone", operation: "audio_speech", path: "/audio/speech",
+ constraints: sealMimoSpeechRequest("mimo-v2.5-tts-voiceclone", {
+ text: ["Continue speaking."], voiceReference: [{ role: "audio", artifact: voice }],
+ }),
+ references: true,
+ },
+ ];
+ for (const item of cases) for (const availability of ["missing", "different-operation", "undeclared", "unknown", "available"] as const) {
+ const events: string[] = [];
+ const progress: string[] = [];
+ const registry = new EndpointRegistry();
+ await createHypiHubProvider({
+ publicAssetUrl: async (artifact) => {
+ events.push("reference");
+ return `https://media.test/${artifact.resource}`;
+ },
+ fetch: async (input, init) => {
+ const url = new URL(String(input));
+ if (url.pathname === `/v1/models/${encodeURIComponent(item.model)}`) {
+ events.push("catalogue");
+ if (availability === "missing") return Response.json({ error: { code: "model_not_found", message: "No route for this account." } }, {
+ status: 404, headers: { "x-request-id": "catalogue-request" },
+ });
+ if (availability === "unknown") throw new Error("Connection closed before catalogue response");
+ if (availability === "undeclared") return Response.json({ id: item.model });
+ return Response.json({ endpoints: availability === "different-operation" ? ["transcriptions"] : [item.operation] });
+ }
+ assert.equal(url.pathname, `/v1${item.path}`);
+ events.push("submit");
+ const body = JSON.parse(String(init?.body));
+ assert.equal(body.model, item.model);
+ if (item.operation === "image_edits") assert.equal(body.reference_images.length, 1);
+ if (item.operation === "images") assert.equal(body.reference_images, undefined);
+ if (item.operation === "audio_speech") return new Response(new Uint8Array(wav(100)), { headers: { "content-type": "audio/wav" } });
+ return Response.json({ id: "selected-job", status: "queued" });
+ },
+ }).install(registry);
+ const request: Need = {
+ id: "need:catalogue", capability: item.endpoint.capability, returns: item.endpoint.returns,
+ constraints: item.constraints as unknown as CanonicalValue, result: "result:catalogue",
+ };
+ const selected = registry.resolve(request);
+ assert.equal(selected.status, "resolved");
+ const context = {
+ command: { kind: "fulfill-need" as const, id: "command:catalogue", need: request }, need: request, resources,
+ credentials: { apiKey: { secret: "test-key" } }, operation: "operation:catalogue",
+ reportProgress: async (value: { readonly phase?: string }) => { progress.push(value.phase!); },
+ };
+ let failed: { code?: string; message: string } | undefined;
+ if (selected.registration.kind === "asynchronous") {
+ const outcome = await selected.registration.endpoint.start(context);
+ if (outcome.status === "failed") failed = outcome.failure;
+ else assert.equal(outcome.status, "pending");
+ } else {
+ assert.equal(selected.registration.kind, "immediate");
+ try { await selected.registration.handler(context); }
+ catch (error) { failed = error as Error & { code?: string }; }
+ }
+ if (availability === "available") {
+ assert.equal(failed, undefined);
+ assert.deepEqual(events, item.references ? ["catalogue", "reference", "submit"] : ["catalogue", "submit"]);
+ assert.match(progress.at(-1)!, /Submitting HypiHub request/u);
+ } else {
+ assert.ok(failed);
+ assert.deepEqual(events, ["catalogue"], "neither a reference nor another model is tried");
+ assert.match(failed.message, /model catalogue check failed.*references uploaded=0; generation not submitted/u);
+ assert.ok(failed.message.includes(`model=${item.model}; operation=${item.operation}`));
+ if (availability === "missing") {
+ assert.equal(failed.code, "model_not_found");
+ assert.match(failed.message, /HTTP 404.*request=catalogue-request.*No route for this account/u);
+ } else if (availability === "different-operation") {
+ assert.match(failed.message, /does not list operation.*listed operations: transcriptions/u);
+ } else if (availability === "undeclared") {
+ assert.match(failed.message, /returned no valid operation list.*is unknown/u);
+ assert.doesNotMatch(failed.message, /does not list operation|model_not_found/u);
+ } else {
+ assert.match(failed.message, /Connection closed before catalogue response/u);
+ assert.doesNotMatch(failed.message, /model_not_found/u);
+ }
+ assert.equal(progress.length, 1);
+ assert.match(progress[0]!, /Reading HypiHub model catalogue/u);
+ }
+ }
+});
+
test("an unavailable model reports availability without prescribing another login", async () => {
const request = need(sealSeedanceRequest("seedance-2-mini", {
prompt: ["A presenter speaks."], resolution: ["720p"], aspectRatio: ["9:16"],
@@ -828,6 +944,105 @@ test("an unavailable model reports availability without prescribing another logi
assert.doesNotMatch(outcome.failure.message, /sign in|auth login/iu);
});
+test("HTTP evidence keeps model, request id and the complete public reason without inferring account action", async () => {
+ const request = need(sealSeedanceRequest("seedance-2-mini", {
+ prompt: ["A presenter speaks."], resolution: ["720p"], aspectRatio: ["9:16"],
+ duration: [5], generateAudio: [true], webSearch: [false],
+ }) as unknown as CanonicalValue);
+ for (const [status, code] of [[404, "model_not_found"], [401, "account_disabled"], [402, "insufficient_credits"]] as const) {
+ let calls = 0;
+ const reason = `A detailed public reason. ${"detail ".repeat(70)}End of reason.`;
+ const endpoint = await endpointFor(request, async (url) => {
+ calls++;
+ if (String(url).includes("/models/")) return Response.json({ endpoints: ["videos"] });
+ return Response.json({ error: { code, message: reason }, internal: "not-public-evidence" }, {
+ status, headers: { "x-request-id": "req-evidence" },
+ });
+ });
+ const outcome = await endpoint.start({
+ command: { kind: "fulfill-need", id: "command:evidence", need: request }, need: request,
+ resources: new MemoryResourceStore(), credentials: { apiKey: { secret: "private-key" } }, operation: "evidence",
+ });
+ assert.equal(calls, 2);
+ assert.equal(outcome.status, "failed");
+ if (outcome.status !== "failed") continue;
+ assert.equal(outcome.failure.code, code);
+ assert.match(outcome.failure.message, new RegExp(`HTTP ${status}`));
+ assert.match(outcome.failure.message, /POST https:\/\/hypit.ai\/v1\/videos; model=bytedance\/seedance-2-mini; request=req-evidence/u);
+ assert.ok(outcome.failure.message.endsWith(reason));
+ assert.doesNotMatch(outcome.failure.message, /auth login|Sign in|private-key|not-public-evidence/u);
+ }
+});
+
+test("terminal jobs preserve service error codes and receipts on both submission and polling", async () => {
+ const request = need(sealSeedanceRequest("seedance-2-mini", {
+ prompt: ["A presenter speaks."], resolution: ["720p"], aspectRatio: ["9:16"],
+ duration: [5], generateAudio: [true], webSearch: [false],
+ }) as unknown as CanonicalValue);
+ for (const phase of ["start", "poll"] as const) {
+ const endpoint = await endpointFor(request, async (url) => String(url).includes("/models/")
+ ? Response.json({ endpoints: ["videos"] })
+ : Response.json({ id: "job-rejected", status: "failed", model: "bytedance/seedance-2-mini",
+ error_code: "upstream_rejected", error: "Reference could not be processed" }));
+ const context = {
+ command: { kind: "fulfill-need", id: "command:job", need: request } as const, need: request,
+ resources: new MemoryResourceStore(), credentials: { apiKey: { secret: "test-key" } }, operation: "job",
+ };
+ const outcome = phase === "start" ? await endpoint.start(context) : await endpoint.poll({ ...context,
+ handle: { contract: "hypit.hypihub-operation@1", jobId: "job-rejected", startedAt: Date.now(),
+ route: `${request.capability.module.name}@${request.capability.module.version}#${request.capability.name}` },
+ });
+ assert.equal(outcome.status, "failed");
+ if (outcome.status !== "failed") continue;
+ assert.equal(outcome.failure.code, "upstream_rejected");
+ assert.deepEqual(outcome.receipt, { id: "job-rejected" });
+ assert.match(outcome.failure.message, /job-rejected failed; upstream_rejected; model=bytedance\/seedance-2-mini: Reference could not be processed/u);
+ }
+});
+
+for (const kind of ["pricing", "speech"] as const) {
+ test(`${kind} failures retain service evidence across their throwing boundary`, async () => {
+ const request: Need = kind === "pricing" ? need(sealSeedanceRequest("seedance-2-mini", {
+ prompt: ["A presenter."], resolution: ["720p"], aspectRatio: ["9:16"],
+ duration: [5], generateAudio: [true], webSearch: [false],
+ }) as unknown as CanonicalValue) : {
+ id: "need:voice", ...mimoSpeechEndpoints.voiceDesign,
+ constraints: sealMimoSpeechRequest("mimo-v2.5-tts-voicedesign", {
+ text: ["A short sample."], voiceDescription: ["Warm and confident."],
+ }) as unknown as CanonicalValue, result: "voice",
+ };
+ let calls = 0;
+ const provider = createHypiHubProvider({ fetch: async (url) => {
+ calls++;
+ if (String(url).includes("/models/")) return Response.json({ endpoints: ["audio_speech"] });
+ return Response.json({ error: { code: "no_available_provider", message: "No route is ready" } }, {
+ status: 503, headers: { "x-request-id": `req-${kind}` },
+ });
+ } });
+ const credentials = { apiKey: { secret: "private-credential" } };
+ const invoke = async () => {
+ if (kind === "pricing") return await provider.readPricing!({ request, credentials: async () => credentials });
+ const registry = new EndpointRegistry();
+ await provider.install(registry);
+ const selected = registry.resolve(request);
+ assert.equal(selected.status, "resolved");
+ assert.equal(selected.registration.kind, "immediate");
+ return await selected.registration.handler({ need: request, credentials, resources: new MemoryResourceStore(),
+ command: { kind: "fulfill-need", id: "voice", need: request },
+ });
+ };
+ await assert.rejects(invoke, (error: Error) => {
+ assert.match(error.message, /HTTP 503; no_available_provider/u);
+ assert.ok(error.message.includes(`request=req-${kind}`));
+ assert.ok(error.message.includes(kind === "pricing" ? "model=bytedance/seedance-2-mini" : "model=mimo-v2.5-tts-voicedesign"));
+ assert.ok(error.message.endsWith("No route is ready"));
+ assert.doesNotMatch(error.message, /private-credential|auth login/u);
+ return true;
+ });
+ assert.equal(calls, kind === "pricing" ? 1 : 2);
+ });
+}
+
for (const mode of ['success', 'error', 'body-timeout'] as const) {
test(`hosted transcription keeps its receipt on ${mode} without resubmitting`, async () => {
const resources = new MemoryResourceStore();
diff --git a/packages/provider-hypihub/test/routes.test.ts b/packages/provider-hypihub/test/routes.test.ts
index 511d2f5e..6bba8d1d 100644
--- a/packages/provider-hypihub/test/routes.test.ts
+++ b/packages/provider-hypihub/test/routes.test.ts
@@ -1,9 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";
+import type { GenerationArtifactUrlResolver } from "@hypit/generation";
import type { EndpointSupport } from "@hypit/endpoint-kit";
import type { CanonicalValue } from "@hypit/protocol";
import { hypiHubRoutes } from "../src/routes.js";
+import type { HypiHubRoute } from "../src/routes.js";
+
+async function compile(route: HypiHubRoute, constraints: CanonicalValue, resolve: GenerationArtifactUrlResolver) {
+ return await route.prepare(constraints).compile(resolve);
+}
const image = {
kind: "blob" as const,
@@ -18,7 +24,7 @@ const resolveAudio = async () => "data:audio/wav;base64,AQID";
test("HypiHub GPT image requests use canonical edit references and the authored resolution tier", async () => {
const route = hypiHubRoutes.find((item) => item.capability.name === "gpt-image-2");
assert.ok(route);
- const result = await route.compile({
+ const result = await compile(route, {
ports: {
prompt: ["edit"],
aspectRatio: ["1:1"],
@@ -47,7 +53,7 @@ test("HypiHub GPT image requests use canonical edit references and the authored
status: "unsupported",
reason: "HypiHub GPT Image 2 accepts the background option only at 1K; omit it at 2K",
});
- await assert.rejects(route.compile(unsupported, resolve), /background option only at 1K/u);
+ await assert.rejects(compile(route, unsupported, resolve), /background option only at 1K/u);
for (const constraints of [
{ ports: { prompt: ["portrait"], aspectRatio: ["5:4"], resolution: ["2K"] } },
@@ -77,7 +83,7 @@ test("HypiHub GPT image requests use canonical edit references and the authored
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({
+ const result = await compile(route, {
ports: {
prompt: ["animate"],
duration: [5],
@@ -96,7 +102,7 @@ test("HypiHub image-to-video requests preserve Hypit's first-frame semantics", a
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({
+ const result = await compile(route, {
ports: {
prompt: ["animate"],
duration: [5],
@@ -112,7 +118,7 @@ test("HypiHub sends audio references through the public top-level field", 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({
+ const result = await compile(route, {
ports: {
prompt: ["animate"],
duration: [5],
@@ -141,7 +147,7 @@ test("HypiHub Seedance sends reference images through the public top-level field
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: {
+ const result = await compile(route, { ports: {
prompt: ["animate"], duration: [6], aspectRatio: ["16:9"],
referenceImage: [{ role: "image", artifact: image }],
} }, resolve);
@@ -159,7 +165,7 @@ test("HypiHub preserves reference-video roles for one or several videos", async
const video = { ...image, mediaType: "video/mp4" };
const resolveVideo = async (artifact: typeof video) => `https://hypit.ai/files/${artifact.resource.slice(-1)}.mp4`;
- const single = await route.compile({ ports: {
+ const single = await compile(route, { ports: {
prompt: ["animate"], duration: [6],
referenceVideo: [{ role: "video", artifact: video }],
} }, resolveVideo);
@@ -168,7 +174,7 @@ test("HypiHub preserves reference-video roles for one or several videos", async
reference_videos: ["https://hypit.ai/files/1.mp4"],
});
- const multiple = await route.compile({ ports: {
+ const multiple = await compile(route, { ports: {
prompt: ["animate"], duration: [6],
referenceVideo: [
{ role: "video", artifact: video },
@@ -184,7 +190,7 @@ test("HypiHub preserves reference-video roles for one or several videos", async
test("HypiHub MiMo Speech mappings use the public audio speech fields", async () => {
const voiceDesign = hypiHubRoutes.find((item) => item.capability.name === "mimo-v2.5-tts-voicedesign");
assert.ok(voiceDesign);
- const result = await voiceDesign.compile({
+ const result = await compile(voiceDesign, {
ports: { text: ["hello"], voiceDescription: ["warm and calm"] },
}, resolve);
assert.equal(result.model, "mimo-v2.5-tts-voicedesign");
@@ -192,7 +198,7 @@ test("HypiHub MiMo Speech mappings use the public audio speech fields", async ()
const voiceClone = hypiHubRoutes.find((item) => item.capability.name === "mimo-v2.5-tts-voiceclone");
assert.ok(voiceClone);
- const cloned = await voiceClone.compile({
+ const cloned = await compile(voiceClone, {
ports: {
text: ["hello again"],
instruction: ["quiet and direct"],
@@ -213,7 +219,7 @@ test("Seedance person metadata reaches resource transport without changing video
for (const flag of [true, false, undefined]) {
const fields = flag === undefined ? {} : { personReference: flag };
const seen: unknown[] = [];
- const result = await route.compile({ ports: {
+ const result = await compile(route, { ports: {
prompt: ["animate"], duration: [5],
[port]: [{ role: port === "referenceVideo" ? "video" : "image", artifact: image, fields }],
} }, async (_artifact, metadata) => { seen.push(metadata); return "https://media.test/ref"; });
@@ -230,8 +236,8 @@ test("exact model identity survives reference mode and preview selection", async
const preview = hypiHubRoutes.find((item) => item.capability.name === "grok-imagine-video-1.5-preview")!;
for (const images of [[], [{ role: "image", artifact: image }]]) {
const request = { ports: { prompt: ["A scene"], ...(images.length ? { images } : {}) } };
- assert.equal((await lite.compile(request, resolve)).model,
+ assert.equal((await compile(lite, request, resolve)).model,
images.length ? "seedream/5-lite-image-to-image" : "seedream/5-lite-text-to-image");
- assert.equal((await preview.compile(request, resolve)).model, "grok-imagine-video-1.5-preview");
+ assert.equal((await compile(preview, request, resolve)).model, "grok-imagine-video-1.5-preview");
}
});