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
fix(endpoint-kit): share the poll error decision across asynchronous Providers (#337)
Sharky Wangec6f2083ef92
diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.tsindex 878dd5ce..22e3df7c 100644--- a/packages/endpoint-kit/src/index.ts+++ b/packages/endpoint-kit/src/index.ts@@ -492,3 +492,50 @@ export function wakeAfter(...(progress === undefined ? {} : { progress }),};}++/** A service reported a failure with a stable code. */+export class EndpointServiceError extends Error {+ constructor(readonly code: string, message: string) { super(message); }+}+/** A non-success HTTP response, with the wait the service asked for when it gave one. */+export class EndpointHttpError extends EndpointServiceError {+ constructor(code: string, message: string, readonly status: number, readonly retryAfterMs?: number) { super(code, message); }+}+/** The request produced no response: connection failure, interrupted read, or request timeout. */+export class EndpointTransportError extends Error {}+/** A success response whose body cannot be used. */+export class EndpointResponseError extends Error {}++/** Report a rejected send or read as a transport error. */+export async function transport<T>(request: Promise<T>): Promise<T> {+ try { return await request; } catch (error) {+ if (error instanceof EndpointTransportError) throw error;+ throw new EndpointTransportError(error instanceof Error ? error.message : String(error), { cause: error });+ }+}++/** The wait a `Retry-After` header asks for, in milliseconds; either delay-seconds or an HTTP-date. */+export function retryAfterMs(headers: Headers, now = Date.now()): number | undefined {+ const value = headers.get("retry-after")?.trim();+ if (value === undefined || value.length === 0) return undefined;+ const delay = /^\d+$/u.test(value) ? Number(value) * 1000 : Date.parse(value) - now;+ return Number.isFinite(delay) ? Math.max(0, Math.round(delay)) : undefined;+}++/**+ * Decide a poll action's outcome from the error it threw. Transport errors and HTTP 429/5xx keep the+ * job pending for the next poll; every other error, including credential and response errors, fails it.+ */+export function pollAgainOrFail(error: unknown, options: {+ readonly handle: CanonicalValue;+ readonly pollIntervalMs: number;+ readonly failure: (error: unknown) => EndpointOutcome;+}): EndpointOutcome {+ if (error instanceof EndpointTransportError) {+ return wakeAfter(options.handle, options.pollIntervalMs, Date.now(), { phase: "retrying" });+ }+ if (error instanceof EndpointHttpError && (error.status === 429 || error.status >= 500)) {+ return wakeAfter(options.handle, error.retryAfterMs ?? options.pollIntervalMs, Date.now(), { phase: "retrying" });+ }+ return options.failure(error);+}diff --git a/packages/provider-beatapi/src/errors.ts b/packages/provider-beatapi/src/errors.tsindex 7ab0cd8a..0fa2ec16 100644--- a/packages/provider-beatapi/src/errors.ts+++ b/packages/provider-beatapi/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError } from "@hypit/endpoint-kit";+/** BeatAPI's `{ error: { code, message, request_id, retry_after_seconds } }` envelope and terminal task errors. */function record(value: unknown): Record<string, unknown> | undefined {return value !== null && typeof value === "object" && !Array.isArray(value)@@ -12,12 +14,10 @@ export function safeBeatApiReason(value: string): string {return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");}-export class BeatApiServiceError extends Error {- constructor(readonly code: string, message: string) { super(message); }-}+export class BeatApiServiceError extends EndpointServiceError {}-export class BeatApiHttpError extends BeatApiServiceError {- constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,+export class BeatApiHttpError extends EndpointHttpError {+ constructor(status: number, response: { readonly headers: Headers }, bodyText: string,request: { readonly method: string; readonly path: 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. */ }@@ -32,7 +32,8 @@ export class BeatApiHttpError extends BeatApiServiceError {...(requestId === undefined ? [] : [`request=${requestId}`]),...(retryAfter === undefined ? [] : [`retry-after=${retryAfter}s`]),];- super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeBeatApiReason(reason)}`}`);+ super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeBeatApiReason(reason)}`}`,+ status, retryAfter === undefined ? undefined : Math.round(retryAfter * 1000));}}diff --git a/packages/provider-beatapi/src/provider.ts b/packages/provider-beatapi/src/provider.tsindex bbb62ba9..8cad98eb 100644--- a/packages/provider-beatapi/src/provider.ts+++ b/packages/provider-beatapi/src/provider.ts@@ -1,6 +1,6 @@import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointInvocationContext, EndpointOutcome } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import type { GenerationArtifactUrlResolver } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";@@ -75,18 +75,18 @@ function failureMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}function failure(error: unknown): EndpointOutcome {- return { status: "failed", failure: { code: error instanceof BeatApiServiceError ? error.code : "BEATAPI_ERROR", message: failureMessage(error) } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "BEATAPI_ERROR", message: failureMessage(error) } };}class BeatApiClient {constructor(readonly baseUrl: string, readonly timeout: number, readonly fetcher: typeof globalThis.fetch) {}async json(path: string, key: string, init: RequestInit = {}): Promise<Record<string, unknown>> {- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("BeatAPI request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {...init, signal: deadline.signal, headers: { authorization: `Bearer ${key}`, ...(init.headers ?? {}) },- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));if (!response.ok) {const input = typeof init.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : undefined;throw new BeatApiHttpError(response.status, response, text, {@@ -94,7 +94,7 @@ class BeatApiClient {});}let body: unknown;- try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`BeatAPI returned invalid JSON (${response.status})`); }+ try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new EndpointResponseError(`BeatAPI returned invalid JSON (${response.status})`); }return object(object(body, "BeatAPI response").data, "BeatAPI response data");} finally { deadline.finish(); }}@@ -154,7 +154,7 @@ function endpoint(client: BeatApiClient, pollIntervalMs: number, maxOperationMs:try {body = await request.compile(resolverFor(client, context, publicAssetUrl));} catch (error) {- throw new BeatApiServiceError(error instanceof BeatApiServiceError ? error.code : "BEATAPI_ERROR",+ throw new BeatApiServiceError(error instanceof EndpointServiceError ? error.code : "BEATAPI_ERROR",`BeatAPI request preparation failed; model=${request.model}; generation not submitted: ${failureMessage(error)}`);}await context.reportProgress?.({ phase: `Submitting BeatAPI request: ${request.model}` });@@ -181,13 +181,7 @@ function endpoint(client: BeatApiClient, pollIntervalMs: number, maxOperationMs:if (Date.now() - handle.startedAt > maxOperationMs) {return { status: "failed", receipt, failure: { code: "BEATAPI_OPERATION_TIMEOUT", message: `BeatAPI task ${handle.taskId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let task: Record<string, unknown>;- try {- task = await client.json(`/v1/tasks/${encodeURIComponent(handle.taskId)}`, apiKey(context.credentials));- } catch (error) {- if (error instanceof BeatApiHttpError && error.status < 500) return { ...failure(error), receipt };- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" }), receipt };- }+ const task = await client.json(`/v1/tasks/${encodeURIComponent(handle.taskId)}`, apiKey(context.credentials));const status = String(task.status);if (pendingStatuses.includes(status)) {return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: status }), receipt };@@ -200,7 +194,7 @@ function endpoint(client: BeatApiClient, pollIntervalMs: number, maxOperationMs:const urls = media.map((item, index) => httpsUrl(object(item, `BeatAPI output ${index + 1}`).url, `BeatAPI output ${index + 1}`));return { status: "ready", handle: canonicalize({ ...handle, urls }), receipt };} catch (error) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {diff --git a/packages/provider-hiapi/src/errors.ts b/packages/provider-hiapi/src/errors.tsindex 0e32e849..b0f6ce1c 100644--- a/packages/provider-hiapi/src/errors.ts+++ b/packages/provider-hiapi/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError } from "@hypit/endpoint-kit";+/** HiAPI's `{ code, message, error_code }` envelope and task `error` object, kept at the service boundary. */function record(value: unknown): Record<string, unknown> | undefined {return value !== null && typeof value === "object" && !Array.isArray(value)@@ -12,12 +14,10 @@ export function safeHiApiReason(value: string): string {return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");}-export class HiApiServiceError extends Error {- constructor(readonly code: string, message: string) { super(message); }-}+export class HiApiServiceError extends EndpointServiceError {}-export class HiApiHttpError extends HiApiServiceError {- constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,+export class HiApiHttpError extends EndpointHttpError {+ constructor(status: number, response: { readonly headers: Headers }, bodyText: string,request: { readonly method: string; readonly path: 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. */ }@@ -29,7 +29,7 @@ export class HiApiHttpError extends HiApiServiceError {...(request.model === undefined ? [] : [`model=${request.model}`]),...(requestId === undefined ? [] : [`request=${requestId}`]),];- super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeHiApiReason(reason)}`}`);+ super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeHiApiReason(reason)}`}`, status);}}diff --git a/packages/provider-hiapi/src/provider.ts b/packages/provider-hiapi/src/provider.tsindex 236564b1..af443c9b 100644--- a/packages/provider-hiapi/src/provider.ts+++ b/packages/provider-hiapi/src/provider.ts@@ -1,6 +1,6 @@import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointInvocationContext, EndpointOutcome } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import type { GenerationArtifactUrlResolver } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";@@ -56,18 +56,18 @@ function failureMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}function failure(error: unknown): EndpointOutcome {- return { status: "failed", failure: { code: error instanceof HiApiServiceError ? error.code : "HIAPI_ERROR", message: failureMessage(error) } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "HIAPI_ERROR", message: failureMessage(error) } };}class HiApiClient {constructor(readonly baseUrl: string, readonly timeout: number, readonly fetcher: typeof globalThis.fetch) {}async json(path: string, key: string, init: RequestInit = {}): Promise<Record<string, unknown>> {- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("HiAPI request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {...init, signal: deadline.signal, headers: { authorization: `Bearer ${key}`, ...(init.headers ?? {}) },- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));if (!response.ok) {const input = typeof init.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : undefined;throw new HiApiHttpError(response.status, response, text, {@@ -75,7 +75,7 @@ class HiApiClient {});}let body: unknown;- try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`HiAPI returned invalid JSON (${response.status})`); }+ try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new EndpointResponseError(`HiAPI returned invalid JSON (${response.status})`); }return object(object(body, "HiAPI response").data, "HiAPI response data");} finally { deadline.finish(); }}@@ -130,7 +130,7 @@ function endpoint(client: HiApiClient, pollIntervalMs: number, maxOperationMs: ntry {body = await request.compile(resolverFor(request.mediaLimits, context, publicAssetUrl));} catch (error) {- throw new HiApiServiceError(error instanceof HiApiServiceError ? error.code : "HIAPI_ERROR",+ throw new HiApiServiceError(error instanceof EndpointServiceError ? error.code : "HIAPI_ERROR",`HiAPI request preparation failed; model=${request.model}; generation not submitted: ${failureMessage(error)}`);}await context.reportProgress?.({ phase: `Submitting HiAPI request: ${request.model}` });@@ -155,13 +155,7 @@ function endpoint(client: HiApiClient, pollIntervalMs: number, maxOperationMs: nif (Date.now() - handle.startedAt > maxOperationMs) {return { status: "failed", receipt, failure: { code: "HIAPI_OPERATION_TIMEOUT", message: `HiAPI task ${handle.taskId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let task: Record<string, unknown>;- try {- task = await client.json(`/v1/tasks/${encodeURIComponent(handle.taskId)}`, apiKey(context.credentials));- } catch (error) {- if (error instanceof HiApiHttpError && error.status < 500) return { ...failure(error), receipt };- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" }), receipt };- }+ const task = await client.json(`/v1/tasks/${encodeURIComponent(handle.taskId)}`, apiKey(context.credentials));const status = String(task.status);if (status === "queued" || status === "handling" || status === "archiving") {return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: status }), receipt };@@ -177,7 +171,7 @@ function endpoint(client: HiApiClient, pollIntervalMs: number, maxOperationMs: n});return { status: "ready", handle: canonicalize({ ...handle, urls }), receipt };} catch (error) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {diff --git a/packages/provider-hypihub/src/errors.ts b/packages/provider-hypihub/src/errors.tsindex 1d5ca876..c380447c 100644--- a/packages/provider-hypihub/src/errors.ts+++ b/packages/provider-hypihub/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError, retryAfterMs } from "@hypit/endpoint-kit";+/** 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)@@ -12,13 +14,10 @@ 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 HypiHubServiceError extends EndpointServiceError {}-export class HypiHubHttpError extends HypiHubServiceError {- readonly retryAfterMs?: number;- constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,+export class HypiHubHttpError extends EndpointHttpError {+ constructor(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. */ }@@ -41,10 +40,8 @@ export class HypiHubHttpError extends HypiHubServiceError {...(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);+ + (body === undefined && bodyText.length > 2000 ? " [response excerpt truncated]" : ""),+ status, retryAfterMs(response.headers));}}diff --git a/packages/provider-hypihub/src/oauth.ts b/packages/provider-hypihub/src/oauth.tsindex e6b8c0b7..96dddf24 100644--- a/packages/provider-hypihub/src/oauth.ts+++ b/packages/provider-hypihub/src/oauth.ts@@ -1,4 +1,5 @@import type { EndpointCredential } from "@hypit/endpoint-kit";+import { EndpointTransportError, transport } from "@hypit/endpoint-kit";import { decodeOAuth2Credential, encodeOAuth2Credential } from "@hypit/runtime";import { requestDeadline } from "@hypit/runtime-kit";import { HypiHubHttpError } from "./errors.js";@@ -66,9 +67,9 @@ export function createHypiHubAuth(options: {throw new Error("HypiHub OAuth credential is read-only; run hypit auth login with a writable Credential Store");}refreshing = (async () => {- const deadline = requestDeadline(options.requestTimeoutMs, () => new Error("HypiHub OAuth refresh timed out"));+ const deadline = requestDeadline(options.requestTimeoutMs, () => new EndpointTransportError("HypiHub OAuth refresh timed out"));try {- const response = await deadline.wait(options.fetch(tokenEndpoint, {+ const response = await transport(deadline.wait(options.fetch(tokenEndpoint, {method: "POST",headers: { "content-type": "application/x-www-form-urlencoded" },body: new URLSearchParams({@@ -77,8 +78,8 @@ export function createHypiHubAuth(options: {client_id: OAUTH_CLIENT_ID,}),signal: deadline.signal,- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));if (!response.ok) throw new HypiHubHttpError(response.status, response, text, {method: "POST", url: tokenEndpoint,});diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.tsindex 8ecbebc3..d151121c 100644--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@ -1,7 +1,7 @@import { readFileSync } from "node:fs";import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointFulfillment, EndpointInvocationContext, EndpointPollContext, EndpointPricingReader, EndpointStartContext, EndpointOutcome, ImmediateEndpointHandler } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import { selectWireModelForRequest } from "@hypit/generation";import type { GenerationRequest } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";@@ -98,7 +98,7 @@ function failureMessage(error: unknown): string {}function failure(error: unknown): EndpointOutcome {const message = failureMessage(error);- return { status: "failed", failure: { code: error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR", message } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "HYPIHUB_ERROR", message } };}function jobId(value: Record<string, unknown>): string {@@ -150,11 +150,11 @@ class HypiHubClient {async json(path: string, auth: HypiHubAuth, init: RequestInit = {}, refreshOnUnauthorized = true,onResponse?: (response: Response) => Promise<void>): Promise<Record<string, unknown>> {const token = await auth.token();- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("HypiHub request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: deadline.signal, headers: { authorization: `Bearer ${token}`, ...(init.headers ?? {}) } }));+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: deadline.signal, headers: { authorization: `Bearer ${token}`, ...(init.headers ?? {}) } })));if (response.status !== 401 && onResponse !== undefined) await deadline.wait(onResponse(response));- const text = await deadline.wait(response.text()); let body: unknown = {};+ const text = await transport(deadline.wait(response.text())); let body: unknown = {};if (response.status === 401 && refreshOnUnauthorized && auth.canRefresh()) {deadline.finish();await auth.refresh();@@ -167,7 +167,7 @@ class HypiHubClient {...(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})`); }+ try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new EndpointResponseError(`HypiHub returned invalid JSON (${response.status})`); }return object(body, "HypiHub response");} finally { deadline.finish(); }}@@ -427,7 +427,7 @@ async function prepareGeneration(client: HypiHubClient, context: EndpointInvocattry {await verifyModelRoute(client, auth, request.model, request.operation);} catch (error) {- throw new HypiHubServiceError(error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR",+ throw new HypiHubServiceError(error instanceof EndpointServiceError ? 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})` });@@ -446,7 +446,7 @@ async function prepareGeneration(client: HypiHubClient, context: EndpointInvocattry {compiled = await request.compile(resolve);} catch (error) {- throw new HypiHubServiceError(error instanceof HypiHubServiceError ? error.code : "HYPIHUB_ERROR",+ throw new HypiHubServiceError(error instanceof EndpointServiceError ? 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 };@@ -494,21 +494,14 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:receipt: { id: handle.jobId },failure: { code: "HYPIHUB_OPERATION_TIMEOUT", message: `HypiHub job ${handle.jobId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let job: Record<string, unknown>;- try {- job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, authFor(context, client));- } catch (error) {- if (error instanceof HypiHubHttpError && error.status < 500) return failure(error);- return wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" });- }- const status = job.status;+ 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) });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) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {diff --git a/packages/provider-hypihub/src/upload.ts b/packages/provider-hypihub/src/upload.tsindex 942eb13e..da117656 100644--- a/packages/provider-hypihub/src/upload.ts+++ b/packages/provider-hypihub/src/upload.ts@@ -1,8 +1,9 @@+import { EndpointServiceError } from "@hypit/endpoint-kit";import { requestDeadline } from "@hypit/runtime-kit";import { createHash } from "node:crypto";import type { HypiHubAuth } from "./oauth.js";-import { HypiHubHttpError, HypiHubServiceError, safeHypiHubReason } from "./errors.js";+import { HypiHubHttpError, safeHypiHubReason } from "./errors.js";type UploadAuth = HypiHubAuth | string;@@ -360,7 +361,7 @@ export class HypiHubUploader {this.log(`upload cancellation still pending upload=${uploadId} reason=${this.safeReason(cancelError)}`);}}- throw error instanceof HypiHubServiceError ? error : new Error(this.safeReason(error));+ throw error instanceof EndpointServiceError ? error : new Error(this.safeReason(error));}}diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.tsindex 0c0f1d9a..0598cafd 100644--- a/packages/provider-hypihub/test/provider.test.ts+++ b/packages/provider-hypihub/test/provider.test.ts@@ -789,11 +789,13 @@ test("HypiHub exposes model groups beneath its own total capacity", async () =>test("HypiHub operation deadlines fail while polling transport errors keep the job pending", async () => {const request = need({});let requests = 0;+ let reply: (() => Response) | undefined;const registry = new EndpointRegistry();await createHypiHubProvider({ pollIntervalMs: 0, operationTimeoutMs: 60_000,fetch: async (url) => {requests++; assert.match(String(url), /\/jobs\/test$/);- throw new Error("offline");+ if (reply === undefined) throw new Error("offline");+ return reply();} }).install(registry);const selected = registry.resolve(request);assert.equal(selected.status, "resolved"); assert.equal(selected.registration.kind, "asynchronous");@@ -806,10 +808,23 @@ test("HypiHub operation deadlines fail while polling transport errors keep the jassert.equal(timedOut.status, "failed");assert.equal(timedOut.status === "failed" && timedOut.failure.code, "HYPIHUB_OPERATION_TIMEOUT");assert.equal(requests, 0);- const offline = await endpoint.poll({ ...common, handle: { ...common.handle, startedAt: Date.now() } });+ const live = { ...common, handle: { ...common.handle, startedAt: Date.now() } };+ const offline = await endpoint.poll(live);assert.equal(offline.status, "pending");assert.equal(offline.status === "pending" && offline.progress?.phase, "retrying");assert.equal(requests, 1);+ reply = () => new Response("", { status: 429, headers: { "retry-after": "3" } });+ const before = Date.now();+ const limited = await endpoint.poll(live);+ assert.equal(limited.status, "pending");+ assert.ok(limited.status === "pending" && limited.wakeAt! >= before + 3_000);+ reply = () => new Response("{}", { status: 404 });+ const missing = await endpoint.poll(live);+ assert.equal(missing.status, "failed");+ assert.equal(requests, 3);+ const unconfigured = await endpoint.poll({ ...live, credentials: {} });+ assert.equal(unconfigured.status, "failed");+ assert.equal(requests, 3);});test("reference URL reuse includes its authored classification and forwards it to custom transport", async () => {diff --git a/packages/provider-monid/src/errors.ts b/packages/provider-monid/src/errors.tsindex c15bd039..f819f28c 100644--- a/packages/provider-monid/src/errors.ts+++ b/packages/provider-monid/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError } from "@hypit/endpoint-kit";+/** Monid's `{ code, message }` error envelope and run outcome fields, kept at the service boundary. */function record(value: unknown): Record<string, unknown> | undefined {return value !== null && typeof value === "object" && !Array.isArray(value)@@ -12,12 +14,10 @@ export function safeMonidReason(value: string): string {return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");}-export class MonidServiceError extends Error {- constructor(readonly code: string, message: string) { super(message); }-}+export class MonidServiceError extends EndpointServiceError {}-export class MonidHttpError extends MonidServiceError {- constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,+export class MonidHttpError extends EndpointHttpError {+ constructor(status: number, response: { readonly headers: Headers }, bodyText: string,request: { readonly method: string; readonly path: string }) {let body: Record<string, unknown> | undefined;try { body = record(JSON.parse(bodyText)); } catch { /* Non-JSON gateway failures still have HTTP evidence. */ }@@ -27,7 +27,7 @@ export class MonidHttpError extends MonidServiceError {`Monid HTTP ${status}`, `${request.method} ${request.path}`,...(requestId === undefined ? [] : [`request=${requestId}`]),];- super("MONID_HTTP_ERROR", `${facts.join("; ")}${reason === undefined ? "" : `: ${safeMonidReason(reason)}`}`);+ super("MONID_HTTP_ERROR", `${facts.join("; ")}${reason === undefined ? "" : `: ${safeMonidReason(reason)}`}`, status);}}diff --git a/packages/provider-monid/src/provider.ts b/packages/provider-monid/src/provider.tsindex c52f046b..ed789933 100644--- a/packages/provider-monid/src/provider.ts+++ b/packages/provider-monid/src/provider.ts@@ -1,6 +1,6 @@import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointInvocationContext, EndpointOutcome } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import type { GenerationArtifactUrlResolver } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";@@ -55,7 +55,7 @@ function failureMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}function failure(error: unknown): EndpointOutcome {- return { status: "failed", failure: { code: error instanceof MonidServiceError ? error.code : "MONID_ERROR", message: failureMessage(error) } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "MONID_ERROR", message: failureMessage(error) } };}function runId(run: Record<string, unknown>): string {assert(typeof run.runId === "string" && run.runId.length > 0, "Monid response has no runId");@@ -90,18 +90,18 @@ const extensions: Readonly<Record<string, string>> = {class MonidClient {constructor(readonly baseUrl: string, readonly timeout: number, readonly pollIntervalMs: number, readonly fetcher: typeof globalThis.fetch) {}async json(path: string, key: string, init: RequestInit = {}): Promise<{ readonly status: number; readonly body: Record<string, unknown> }> {- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("Monid request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {...init, signal: deadline.signal, headers: { authorization: `Bearer ${key}`, ...(init.headers ?? {}) },- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));let body: unknown;try { body = text.length === 0 ? {} : JSON.parse(text); } catch { body = undefined; }// A synchronous run mirrors the provider's HTTP status while still returning the run itself.const run = body !== null && typeof body === "object" && !Array.isArray(body) && typeof (body as Record<string, unknown>).runId === "string";if (!response.ok && !run) throw new MonidHttpError(response.status, response, text, { method: init.method ?? "GET", path });- assert(body !== undefined, `Monid returned invalid JSON (${response.status})`);+ if (body === undefined) throw new EndpointResponseError(`Monid returned invalid JSON (${response.status})`);return { status: response.status, body: object(body, "Monid response") };} finally { deadline.finish(); }}@@ -176,7 +176,7 @@ function endpoint(client: MonidClient, pollIntervalMs: number, maxOperationMs: ntry {input = await request.compile(resolverFor(client, context, publicAssetUrl));} catch (error) {- throw new MonidServiceError(error instanceof MonidServiceError ? error.code : "MONID_ERROR",+ throw new MonidServiceError(error instanceof EndpointServiceError ? error.code : "MONID_ERROR",`Monid request preparation failed; endpoint=${request.endpoint}; generation not submitted: ${failureMessage(error)}`);}await context.reportProgress?.({ phase: `Submitting Monid request: ${request.service} ${request.endpoint}` });@@ -202,13 +202,7 @@ function endpoint(client: MonidClient, pollIntervalMs: number, maxOperationMs: nif (Date.now() - handle.startedAt > maxOperationMs) {return { status: "failed", receipt, failure: { code: "MONID_OPERATION_TIMEOUT", message: `Monid run ${handle.runId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let run: Record<string, unknown>;- try {- run = await client.getRun(handle.runId, apiKey(context.credentials));- } catch (error) {- if (error instanceof MonidHttpError && error.status < 500) return { ...failure(error), receipt };- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" }), receipt };- }+ const run = await client.getRun(handle.runId, apiKey(context.credentials));const status = String(run.status);if (!monidTerminalStatuses.includes(status as typeof monidTerminalStatuses[number])) {return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: status }), receipt };@@ -217,7 +211,7 @@ function endpoint(client: MonidClient, pollIntervalMs: number, maxOperationMs: nif (rejected !== undefined) return { ...failure(rejected), receipt };return { status: "ready", handle: canonicalize({ ...handle, urls: outputUrls(run) }), receipt };} catch (error) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {diff --git a/packages/provider-pollo/src/errors.ts b/packages/provider-pollo/src/errors.tsindex 530ac3e5..d2d69df4 100644--- a/packages/provider-pollo/src/errors.ts+++ b/packages/provider-pollo/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError } from "@hypit/endpoint-kit";+/** Pollo's `{ errorCode, message, code, requestId }` envelope and generation `failMsg`, kept at the service boundary. */function record(value: unknown): Record<string, unknown> | undefined {return value !== null && typeof value === "object" && !Array.isArray(value)@@ -12,12 +14,10 @@ export function safePolloReason(value: string): string {return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");}-export class PolloServiceError extends Error {- constructor(readonly code: string, message: string) { super(message); }-}+export class PolloServiceError extends EndpointServiceError {}-export class PolloHttpError extends PolloServiceError {- constructor(readonly status: number, bodyText: string, request: { readonly method: string; readonly path: string }) {+export class PolloHttpError extends EndpointHttpError {+ constructor(status: number, bodyText: string, request: { readonly method: string; readonly path: string }) {let body: Record<string, unknown> | undefined;try { body = record(JSON.parse(bodyText)); } catch { /* Non-JSON gateway failures still have HTTP evidence. */ }const code = text(body?.errorCode) ?? "POLLO_HTTP_ERROR";@@ -27,7 +27,7 @@ export class PolloHttpError extends PolloServiceError {`Pollo HTTP ${status}`, code, `${request.method} ${request.path}`,...(requestId === undefined ? [] : [`request=${requestId}`]),];- super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safePolloReason(reason)}`}`);+ super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safePolloReason(reason)}`}`, status);}}diff --git a/packages/provider-pollo/src/provider.ts b/packages/provider-pollo/src/provider.tsindex b5035dcb..50f29491 100644--- a/packages/provider-pollo/src/provider.ts+++ b/packages/provider-pollo/src/provider.ts@@ -1,6 +1,6 @@import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointInvocationContext, EndpointOutcome } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import type { GenerationArtifactUrlResolver } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";@@ -55,21 +55,21 @@ function failureMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}function failure(error: unknown): EndpointOutcome {- return { status: "failed", failure: { code: error instanceof PolloServiceError ? error.code : "POLLO_ERROR", message: failureMessage(error) } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "POLLO_ERROR", message: failureMessage(error) } };}class PolloClient {constructor(readonly baseUrl: string, readonly timeout: number, readonly fetcher: typeof globalThis.fetch) {}async json(path: string, key: string, init: RequestInit = {}): Promise<Record<string, unknown>> {- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("Pollo request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {...init, signal: deadline.signal, headers: { "x-api-key": key, ...(init.headers ?? {}) },- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));if (!response.ok) throw new PolloHttpError(response.status, text, { method: init.method ?? "GET", path });let body: unknown;- try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`Pollo returned invalid JSON (${response.status})`); }+ try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new EndpointResponseError(`Pollo returned invalid JSON (${response.status})`); }return object(body, "Pollo response");} finally { deadline.finish(); }}@@ -108,7 +108,7 @@ function endpoint(client: PolloClient, pollIntervalMs: number, maxOperationMs: ntry {body = await request.compile(resolverFor(context, publicAssetUrl));} catch (error) {- throw new PolloServiceError(error instanceof PolloServiceError ? error.code : "POLLO_ERROR",+ throw new PolloServiceError(error instanceof EndpointServiceError ? error.code : "POLLO_ERROR",`Pollo request preparation failed; path=${request.path}; generation not submitted: ${failureMessage(error)}`);}await context.reportProgress?.({ phase: `Submitting Pollo request: ${request.path}` });@@ -133,13 +133,7 @@ function endpoint(client: PolloClient, pollIntervalMs: number, maxOperationMs: nif (Date.now() - handle.startedAt > maxOperationMs) {return { status: "failed", receipt, failure: { code: "POLLO_OPERATION_TIMEOUT", message: `Pollo task ${handle.taskId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let task: Record<string, unknown>;- try {- task = await client.json(`/v1/generation/${encodeURIComponent(handle.taskId)}/status`, apiKey(context.credentials));- } catch (error) {- if (error instanceof PolloHttpError && error.status < 500) return { ...failure(error), receipt };- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" }), receipt };- }+ const task = await client.json(`/v1/generation/${encodeURIComponent(handle.taskId)}/status`, apiKey(context.credentials));assert(Array.isArray(task.generations) && task.generations.length > 0, "Pollo task has no generations");const generations = task.generations.map((item, index) => object(item, `Pollo generation ${index + 1}`));const rejected = polloTaskFailure(generations, handle.taskId);@@ -156,7 +150,7 @@ function endpoint(client: PolloClient, pollIntervalMs: number, maxOperationMs: n});return { status: "ready", handle: canonicalize({ ...handle, urls }), receipt };} catch (error) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {diff --git a/packages/provider-tokendance/src/errors.ts b/packages/provider-tokendance/src/errors.tsindex 078d83ff..1e0af040 100644--- a/packages/provider-tokendance/src/errors.ts+++ b/packages/provider-tokendance/src/errors.ts@@ -1,3 +1,5 @@+import { EndpointHttpError, EndpointServiceError } from "@hypit/endpoint-kit";+/** TokenDance relays each protocol's own error body; keep the code, the message and the HTTP facts. */function record(value: unknown): Record<string, unknown> | undefined {return value !== null && typeof value === "object" && !Array.isArray(value)@@ -12,12 +14,10 @@ export function safeTokenDanceReason(value: string): string {return value.replace(/https?:\/\/\S+/giu, "[redacted-url]");}-export class TokenDanceServiceError extends Error {- constructor(readonly code: string, message: string) { super(message); }-}+export class TokenDanceServiceError extends EndpointServiceError {}-export class TokenDanceHttpError extends TokenDanceServiceError {- constructor(readonly status: number, response: { readonly headers: Headers }, bodyText: string,+export class TokenDanceHttpError extends EndpointHttpError {+ constructor(status: number, response: { readonly headers: Headers }, bodyText: string,request: { readonly method: string; readonly path: 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. */ }@@ -31,7 +31,7 @@ export class TokenDanceHttpError extends TokenDanceServiceError {...(request.model === undefined ? [] : [`model=${request.model}`]),...(requestId === undefined ? [] : [`request=${requestId}`]),];- super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeTokenDanceReason(reason)}`}`);+ super(code, `${facts.join("; ")}${reason === undefined ? "" : `: ${safeTokenDanceReason(reason)}`}`, status);}}diff --git a/packages/provider-tokendance/src/provider.ts b/packages/provider-tokendance/src/provider.tsindex 08be4264..29b5af92 100644--- a/packages/provider-tokendance/src/provider.ts+++ b/packages/provider-tokendance/src/provider.ts@@ -1,6 +1,6 @@import { requestDeadline } from "@hypit/runtime-kit";import type { AsyncEndpoint, EndpointCredential, EndpointInvocationContext, EndpointOutcome, ImmediateEndpointHandler } from "@hypit/endpoint-kit";-import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";+import { EndpointResponseError, EndpointServiceError, EndpointTransportError, defineEndpointPackage, pollAgainOrFail, transport, wakeAfter } from "@hypit/endpoint-kit";import type { GenerationArtifactUrlResolver } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";@@ -56,7 +56,7 @@ function failureMessage(error: unknown): string {return error instanceof Error ? error.message : String(error);}function failure(error: unknown): EndpointOutcome {- return { status: "failed", failure: { code: error instanceof TokenDanceServiceError ? error.code : "TOKENDANCE_ERROR", message: failureMessage(error) } };+ return { status: "failed", failure: { code: error instanceof EndpointServiceError ? error.code : "TOKENDANCE_ERROR", message: failureMessage(error) } };}function httpsUrl(value: unknown, subject: string): string {assert(typeof value === "string" && /^https?:\/\//u.test(value), `${subject} has no download URL`);@@ -66,12 +66,12 @@ function httpsUrl(value: unknown, subject: string): string {class TokenDanceClient {constructor(readonly baseUrl: string, readonly timeout: number, readonly fetcher: typeof globalThis.fetch) {}async json(path: string, key: string, init: RequestInit = {}): Promise<Record<string, unknown>> {- const deadline = requestDeadline(this.timeout);+ const deadline = requestDeadline(this.timeout, () => new EndpointTransportError("TokenDance request timed out"));try {- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {+ const response = await transport(deadline.wait(this.fetcher(`${this.baseUrl}${path}`, {...init, signal: deadline.signal, headers: { authorization: `Bearer ${key}`, ...(init.headers ?? {}) },- }));- const text = await deadline.wait(response.text());+ })));+ const text = await transport(deadline.wait(response.text()));if (!response.ok) {const input = typeof init.body === "string" ? JSON.parse(init.body) as Record<string, unknown> : undefined;throw new TokenDanceHttpError(response.status, response, text, {@@ -79,7 +79,7 @@ class TokenDanceClient {});}let body: unknown;- try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`TokenDance returned invalid JSON (${response.status})`); }+ try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new EndpointResponseError(`TokenDance returned invalid JSON (${response.status})`); }return object(body, "TokenDance response");} finally { deadline.finish(); }}@@ -145,7 +145,7 @@ async function prepare(client: TokenDanceClient, context: EndpointInvocationContassert(cap === undefined || Buffer.byteLength(body) <= cap,`TokenDance ${route.protocol} accepts request bodies up to ${(cap ?? 0) / 1_000_000} MB; inline references make this one ${Buffer.byteLength(body)} bytes`);} catch (error) {- throw new TokenDanceServiceError(error instanceof TokenDanceServiceError ? error.code : "TOKENDANCE_ERROR",+ throw new TokenDanceServiceError(error instanceof EndpointServiceError ? error.code : "TOKENDANCE_ERROR",`TokenDance request preparation failed; model=${request.model}; generation not submitted: ${failureMessage(error)}`);}return { route, model: request.model, body };@@ -208,14 +208,7 @@ function endpoint(client: TokenDanceClient, pollIntervalMs: number, maxOperationif (Date.now() - handle.startedAt > maxOperationMs) {return { status: "failed", receipt, failure: { code: "TOKENDANCE_OPERATION_TIMEOUT", message: `TokenDance task ${handle.taskId} exceeded this Provider's operationTimeoutMs (${maxOperationMs}); remote outcome is unknown` } };}- let response: Record<string, unknown>;- try {- response = await client.json(paths[route.protocol].task(handle.taskId), apiKey(context.credentials));- } catch (error) {- if (error instanceof TokenDanceHttpError && error.status < 500) return { ...failure(error), receipt };- return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "retrying" }), receipt };- }- const task = taskBody(route.protocol, response);+ const task = taskBody(route.protocol, await client.json(paths[route.protocol].task(handle.taskId), apiKey(context.credentials)));const status = String(task.status);if (status === "queued" || status === "running") return { ...wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: status }), receipt };const rejected = tokenDanceTaskFailure(task, handle.taskId);@@ -223,7 +216,7 @@ function endpoint(client: TokenDanceClient, pollIntervalMs: number, maxOperationassert(status === "succeeded", `TokenDance returned unknown task status ${status}`);return { status: "ready", handle: canonicalize({ ...handle, url: taskVideoUrl(route.protocol, task) }), receipt };} catch (error) {- return failure(error);+ return pollAgainOrFail(error, { handle: context.handle, pollIntervalMs, failure });}},async collect(context) {