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: refresh HypiHub OAuth credentials automatically

rpone359ef7408a81
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 9b17ac25..98a91b3b 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -207,9 +207,24 @@ async function hypiHubOAuthLogin(io: CliIo): Promise<string> {
});
const body = await tokenResponse.text();
if (!tokenResponse.ok) throw new Error(`HypiHub OAuth token exchange failed (${tokenResponse.status}): ${body.slice(0, 200)}`);
- const parsed = JSON.parse(body) as { access_token?: unknown };
+ const parsed = JSON.parse(body) as {
+ access_token?: unknown;
+ refresh_token?: unknown;
+ expires_in?: unknown;
+ expires_at?: unknown;
+ };
if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) throw new Error("HypiHub OAuth returned no access token");
- return parsed.access_token;
+ const expiresAt = typeof parsed.expires_at === "number" && Number.isFinite(parsed.expires_at)
+ ? (parsed.expires_at > 10_000_000_000 ? parsed.expires_at : parsed.expires_at * 1_000)
+ : typeof parsed.expires_in === "number" && Number.isFinite(parsed.expires_in) && parsed.expires_in > 0
+ ? Date.now() + parsed.expires_in * 1_000
+ : undefined;
+ return JSON.stringify({
+ format: "hypit.hypihub-oauth@1",
+ accessToken: parsed.access_token,
+ ...(typeof parsed.refresh_token === "string" && parsed.refresh_token.length > 0 ? { refreshToken: parsed.refresh_token } : {}),
+ ...(expiresAt === undefined ? {} : { expiresAt }),
+ });
}
/**
diff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.ts
index 1d090bde..5c6d5e24 100644
--- a/packages/driver-node/src/driver.ts
+++ b/packages/driver-node/src/driver.ts
@@ -324,6 +324,7 @@ export class NodeDriver {
need: structuredClone(executable.command.need),
artifacts: this.artifacts,
credentials: await this.#endpointCredentials(executable.registration),
+ ...(this.credentials === undefined ? {} : { credentialStore: this.credentials }),
operation: identity.id,
};
let outcome: EndpointOutcome;
@@ -438,6 +439,7 @@ export class NodeDriver {
need: structuredClone(executable.command.need),
artifacts: this.artifacts,
credentials: await this.#endpointCredentials(executable.registration),
+ ...(this.credentials === undefined ? {} : { credentialStore: this.credentials }),
});
return { status: "completed", event: await this.#endpointEvent(state, executable, result) };
} catch (error) {
@@ -511,6 +513,7 @@ export class NodeDriver {
need: structuredClone(executable.command.need),
artifacts: this.artifacts,
credentials: await this.#endpointCredentials(executable.registration),
+ ...(this.credentials === undefined ? {} : { credentialStore: this.credentials }),
operation: current.id,
handle: structuredClone(current.handle as NonNullable<typeof current.handle>),
};
diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.ts
index 25547505..ffa6916b 100644
--- a/packages/endpoint-kit/src/index.ts
+++ b/packages/endpoint-kit/src/index.ts
@@ -10,6 +10,7 @@ import type {
import type {
ArtifactStore,
CredentialRef,
+ CredentialStore,
CredentialValue,
OperationFailure,
OperationProgress,
@@ -28,6 +29,8 @@ export type EndpointInvocationContext = {
readonly artifacts: ArtifactStore;
/** Only slots explicitly declared by this configured Endpoint instance are present. */
readonly credentials: Readonly<Record<string, CredentialValue>>;
+ /** Selected CredentialStore, when the Host can persist refreshed credentials. */
+ readonly credentialStore?: CredentialStore;
};
export type ImmediateEndpointHandler = (
diff --git a/packages/provider-hypihub/src/gemini.ts b/packages/provider-hypihub/src/gemini.ts
index 98c629e0..b06afc33 100644
--- a/packages/provider-hypihub/src/gemini.ts
+++ b/packages/provider-hypihub/src/gemini.ts
@@ -1,11 +1,13 @@
import type { GeminiInlinePart } from "@hypit/gemini";
import { HypiHubUploader } from "./upload.js";
+import type { HypiHubAuth } from "./oauth.js";
export type HypiHubGeminiPart = GeminiInlinePart
| { readonly fileData: { readonly mimeType?: string; readonly fileUri: string } };
export type HypiHubGeminiGeneratorOptions = {
readonly apiKey: string;
+ readonly auth?: HypiHubAuth;
readonly model?: string;
readonly baseUrl?: string;
readonly requestTimeoutMs?: number;
@@ -105,7 +107,7 @@ export function createHypiHubGeminiGenerator(options: HypiHubGeminiGeneratorOpti
const startedAt = Date.now();
logger(`media upload started bytes=${bytes.byteLength} mime=${mimeType}`);
try {
- const url = await uploader.upload({ bytes, mediaType: mimeType, purpose: "reference" }, apiKey);
+ const url = await uploader.upload({ bytes, mediaType: mimeType, purpose: "reference" }, options.auth ?? apiKey);
logger(`media upload finished bytes=${bytes.byteLength} mime=${mimeType} elapsed=${Date.now() - startedAt}ms`);
return url;
} catch (error) {
@@ -124,12 +126,13 @@ export function createHypiHubGeminiGenerator(options: HypiHubGeminiGeneratorOpti
let response: Response | undefined;
let text = "";
let attempts = 0;
+ let refreshedAuth = false;
for (let attempt = 0; attempt <= maxRateLimitRetries; attempt += 1) {
attempts += 1;
response = await fetcher(`${baseUrl}/v1beta/models/${encodeURIComponent(model)}:generateContent`, {
method: "POST",
signal: controller.signal,
- headers: { "x-goog-api-key": apiKey, "content-type": "application/json" },
+ headers: { "x-goog-api-key": options.auth === undefined ? apiKey : await options.auth.token(), "content-type": "application/json" },
body: JSON.stringify({
systemInstruction: { parts: [{ text: input.instruction }] },
contents: [{ role: "user", parts }],
@@ -137,6 +140,12 @@ export function createHypiHubGeminiGenerator(options: HypiHubGeminiGeneratorOpti
}),
});
text = await response.text();
+ if (response.status === 401 && !refreshedAuth && options.auth?.canRefresh()) {
+ refreshedAuth = true;
+ await options.auth.refresh();
+ attempt -= 1;
+ continue;
+ }
if (response.status !== 429 || attempt === maxRateLimitRetries) break;
await new Promise((resolve) => setTimeout(resolve, retryDelay(response!, rateLimitRetryDelayMs, attempt)));
}
@@ -144,7 +153,7 @@ export function createHypiHubGeminiGenerator(options: HypiHubGeminiGeneratorOpti
logger(`generateContent response status=${response.status} elapsed=${Date.now() - requestStartedAt}ms attempts=${attempts}`);
if (!response.ok) {
const message = `HypiHub Gemini returned HTTP ${response.status}: ${text.slice(0, 300)}`;
- if (response.status === 401 || response.status === 403 || response.status === 404) {
+ if (response.status === 401) {
throw new Error(`${message}. Sign in to HypiHub at https://hypit.ai with hypit auth login`);
}
throw new Error(message);
diff --git a/packages/provider-hypihub/src/oauth.ts b/packages/provider-hypihub/src/oauth.ts
new file mode 100644
index 00000000..173ccd59
--- /dev/null
+++ b/packages/provider-hypihub/src/oauth.ts
@@ -0,0 +1,143 @@
+import type { CredentialRef, CredentialStore } from "@hypit/runtime";
+import { writableCredentialStore } from "@hypit/runtime";
+
+const OAUTH_CLIENT_ID = "hyc_d5d5e8e7131b0c877756e66c";
+const REFRESH_SKEW_MS = 60_000;
+
+type OAuthTokenResponse = {
+ readonly access_token?: unknown;
+ readonly refresh_token?: unknown;
+ readonly expires_in?: unknown;
+ readonly expires_at?: unknown;
+};
+
+type StoredOAuthCredential = {
+ readonly format: "hypit.hypihub-oauth@1";
+ readonly accessToken: string;
+ readonly refreshToken?: string;
+ readonly expiresAt?: number;
+};
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function object(value: unknown): Record<string, unknown> {
+ assert(value !== null && typeof value === "object" && !Array.isArray(value), "HypiHub OAuth response is invalid");
+ return value as Record<string, unknown>;
+}
+
+function positiveNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
+}
+
+function tokenExpiry(value: OAuthTokenResponse): number | undefined {
+ const absolute = positiveNumber(value.expires_at);
+ if (absolute !== undefined) return absolute > 10_000_000_000 ? absolute : absolute * 1_000;
+ const seconds = positiveNumber(value.expires_in);
+ return seconds === undefined ? undefined : Date.now() + seconds * 1_000;
+}
+
+export function encodeHypiHubOAuthCredential(value: {
+ readonly accessToken: string;
+ readonly refreshToken?: string;
+ readonly expiresAt?: number;
+}): string {
+ assert(value.accessToken.length > 0, "HypiHub OAuth access token is empty");
+ return JSON.stringify({
+ format: "hypit.hypihub-oauth@1",
+ accessToken: value.accessToken,
+ ...(value.refreshToken === undefined ? {} : { refreshToken: value.refreshToken }),
+ ...(value.expiresAt === undefined ? {} : { expiresAt: value.expiresAt }),
+ } satisfies StoredOAuthCredential);
+}
+
+export function decodeHypiHubOAuthCredential(secret: string): StoredOAuthCredential {
+ try {
+ const parsed = object(JSON.parse(secret)) as Partial<StoredOAuthCredential>;
+ if (parsed.format === "hypit.hypihub-oauth@1"
+ && typeof parsed.accessToken === "string" && parsed.accessToken.length > 0
+ && (parsed.refreshToken === undefined || typeof parsed.refreshToken === "string")
+ && (parsed.expiresAt === undefined || typeof parsed.expiresAt === "number")) {
+ return parsed as StoredOAuthCredential;
+ }
+ } catch {
+ // A raw secret is a supported static API key and remains backward compatible.
+ }
+ return { format: "hypit.hypihub-oauth@1", accessToken: secret };
+}
+
+export type HypiHubAuth = {
+ token(): Promise<string>;
+ canRefresh(): boolean;
+ refresh(): Promise<string>;
+};
+
+export function createHypiHubAuth(options: {
+ readonly secret: string;
+ readonly baseUrl: string;
+ readonly fetch: typeof globalThis.fetch;
+ readonly credentialStore?: CredentialStore;
+ readonly credentialRef?: CredentialRef;
+}): HypiHubAuth {
+ let stored = decodeHypiHubOAuthCredential(options.secret);
+ let refreshInFlight: Promise<string> | undefined;
+ const origin = new URL(options.baseUrl).origin;
+
+ const save = async (): Promise<void> => {
+ if (options.credentialStore === undefined || options.credentialRef === undefined) return;
+ const store = await writableCredentialStore(options.credentialStore, options.credentialRef);
+ if (store === undefined) return;
+ await store.put(options.credentialRef, {
+ secret: encodeHypiHubOAuthCredential(stored),
+ ...(stored.expiresAt === undefined ? {} : { expiresAt: stored.expiresAt }),
+ });
+ };
+
+ const refresh = async (): Promise<string> => {
+ if (refreshInFlight !== undefined) return await refreshInFlight;
+ if (stored.refreshToken === undefined) {
+ throw new Error("HypiHub OAuth access token expired and no refresh token is available; run hypit auth login");
+ }
+ refreshInFlight = (async () => {
+ const response = await options.fetch(`${origin}/oauth/token`, {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "refresh_token",
+ refresh_token: stored.refreshToken!,
+ client_id: OAUTH_CLIENT_ID,
+ }),
+ });
+ const text = await response.text();
+ let body: OAuthTokenResponse;
+ try { body = object(text.length === 0 ? {} : 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");
+ const expiresAt = tokenExpiry(body);
+ stored = {
+ format: "hypit.hypihub-oauth@1",
+ accessToken: body.access_token,
+ ...(typeof body.refresh_token === "string" && body.refresh_token.length > 0
+ ? { refreshToken: body.refresh_token } : stored.refreshToken === undefined ? {} : { refreshToken: stored.refreshToken }),
+ ...(expiresAt === undefined ? {} : { expiresAt }),
+ };
+ await save();
+ return stored.accessToken;
+ })();
+ try { return await refreshInFlight; }
+ finally { refreshInFlight = undefined; }
+ };
+
+ return {
+ async token() {
+ if (stored.refreshToken !== undefined && stored.expiresAt !== undefined
+ && stored.expiresAt <= Date.now() + REFRESH_SKEW_MS) return await refresh();
+ return stored.accessToken;
+ },
+ canRefresh() { return stored.refreshToken !== undefined; },
+ refresh,
+ };
+}
diff --git a/packages/provider-hypihub/src/pricing.ts b/packages/provider-hypihub/src/pricing.ts
index 3f2dad48..ec20b89b 100644
--- a/packages/provider-hypihub/src/pricing.ts
+++ b/packages/provider-hypihub/src/pricing.ts
@@ -1,5 +1,6 @@
import type { Need } from "@hypit/protocol";
import type { CredentialRef, CredentialStore } from "@hypit/runtime";
+import type { HypiHubAuth } from "./oauth.js";
import { hypiHubRouteForCapability } from "./routes.js";
@@ -19,7 +20,7 @@ export type HypiHubBuildQuote = {
};
type HypiHubPricingTransport = {
- json(path: string, apiKey: string, init?: RequestInit): Promise<Record<string, unknown>>;
+ json(path: string, auth: HypiHubAuth, init?: RequestInit): Promise<Record<string, unknown>>;
};
function assert(condition: unknown, message: string): asserts condition {
@@ -42,7 +43,7 @@ function capabilityKey(need: Need): string {
async function quoteNeed(
transport: HypiHubPricingTransport,
- apiKey: string,
+ auth: HypiHubAuth,
need: Need,
): Promise<HypiHubQuoteItem> {
const route = hypiHubRouteForCapability(need.capability);
@@ -57,7 +58,7 @@ async function quoteNeed(
if (typeof input.resolution === "string") dimensions.resolution = input.resolution;
const hasReferenceVideo = typeof input.ref_video_url === "string"
|| (Array.isArray(input.reference_videos) && input.reference_videos.length > 0);
- const response = await transport.json("/pricing/quote", apiKey, {
+ const response = await transport.json("/pricing/quote", auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
@@ -80,6 +81,7 @@ async function quoteNeed(
export function createHypiHubPricingClient(options: {
readonly client: HypiHubPricingTransport;
readonly apiKey: CredentialRef;
+ readonly auth: (secret: string, credentials: CredentialStore) => HypiHubAuth;
}): {
quoteMany(needs: readonly Need[], credentials: CredentialStore): Promise<HypiHubBuildQuote>;
} {
@@ -97,7 +99,8 @@ export function createHypiHubPricingClient(options: {
const credential = await credentials.resolve(options.apiKey);
assert(credential !== undefined && credential.secret.length > 0,
"HypiHub login is unavailable; run hypit auth login for HypiHub");
- const items = await Promise.all(needs.map((need) => quoteNeed(options.client, credential.secret, need)));
+ const auth = options.auth(credential.secret, credentials);
+ const items = await Promise.all(needs.map((need) => quoteNeed(options.client, auth, need)));
return {
format: "hypit.build-quote@1",
status: "complete",
diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.ts
index 560c3e4c..0a07b06f 100644
--- a/packages/provider-hypihub/src/provider.ts
+++ b/packages/provider-hypihub/src/provider.ts
@@ -15,6 +15,8 @@ import { hypiHubRouteForCapability, hypiHubRoutes } from "./routes.js";
import { HypiHubUploader } from "./upload.js";
import { transcribeWithHypiHub, whisperXAlignmentRequest } from "./whisperx.js";
import { createHypiHubPricingClient } from "./pricing.js";
+import { createHypiHubAuth } from "./oauth.js";
+import type { HypiHubAuth } from "./oauth.js";
export const hypiHubProviderModuleRef = { name: "@hypit/provider-hypihub", version: "1" } as const;
@@ -60,7 +62,7 @@ function credential(context: EndpointInvocationContext): string {
}
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|403|404)\b|not enabled for|model_not_found|no_capable_provider/iu.test(message)
+ return /API key is unavailable|HypiHub login is unavailable|HTTP 401\b|invalid_token/iu.test(message)
? `${message}. Sign in to HypiHub at https://hypit.ai with hypit auth login`
: message;
}
@@ -80,8 +82,8 @@ function jobId(value: Record<string, unknown>): string {
return id;
}
-async function verifyModelRoute(client: HypiHubClient, apiKey: string, model: string, operation: "images" | "image_edits" | "videos" | "audio_speech" | "transcriptions"): Promise<void> {
- const card = await client.json(`/models/${encodeURIComponent(model)}`, apiKey);
+async function verifyModelRoute(client: HypiHubClient, auth: HypiHubAuth, model: string, operation: "images" | "image_edits" | "videos" | "audio_speech" | "transcriptions"): 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`);
@@ -113,10 +115,14 @@ class HypiHubClient {
fetch: this.fetcher,
});
}
- async json(path: string, apiKey: string, init: RequestInit = {}): Promise<Record<string, unknown>> {
+ async json(path: string, auth: HypiHubAuth, init: RequestInit = {}, retryAuth = true): Promise<Record<string, unknown>> {
const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout);
try {
- const response = await this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: controller.signal, headers: { authorization: `Bearer ${apiKey}`, ...(init.headers ?? {}) } });
+ const response = await this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: controller.signal, headers: { authorization: `Bearer ${await auth.token()}`, ...(init.headers ?? {}) } });
+ if (response.status === 401 && retryAuth && auth.canRefresh()) {
+ await auth.refresh();
+ return await this.json(path, auth, init, false);
+ }
const text = await response.text(); let body: unknown = {};
try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`HypiHub returned invalid JSON (${response.status})`); }
if (!response.ok) throw new Error(`HypiHub returned HTTP ${response.status}: ${text.slice(0, 300)}`);
@@ -137,7 +143,7 @@ class HypiHubClient {
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
- async upload(artifact: BlobRef, artifacts: ArtifactStore, apiKey: string): Promise<string> {
+ async upload(artifact: BlobRef, artifacts: ArtifactStore, auth: HypiHubAuth): Promise<string> {
const bytes = await artifacts.get(artifact.digest);
assert(bytes !== undefined, `HypiHub reference artifact ${artifact.digest} is unavailable`);
assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.digest} size differs`);
@@ -146,53 +152,68 @@ class HypiHubClient {
mediaType: artifact.mediaType,
purpose: "reference",
sha256: artifact.digest,
- }, apiKey);
+ }, auth);
}
- async transcribe(body: Record<string, unknown>, apiKey: string): Promise<Record<string, unknown>> {
- return this.json("/audio/transcriptions", apiKey, {
+ async transcribe(body: Record<string, unknown>, auth: HypiHubAuth): Promise<Record<string, unknown>> {
+ return this.json("/audio/transcriptions", auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
- async binary(path: string, apiKey: string, body: Record<string, unknown>): Promise<{ readonly bytes: Uint8Array; readonly mediaType: string }> {
- const response = await this.fetcher(`${this.baseUrl}${path}`, { method: "POST", headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, body: JSON.stringify(body) });
+ async binary(path: string, auth: HypiHubAuth, body: Record<string, unknown>, retryAuth = true): Promise<{ readonly bytes: Uint8Array; readonly mediaType: string }> {
+ const response = await this.fetcher(`${this.baseUrl}${path}`, { method: "POST", headers: { authorization: `Bearer ${await auth.token()}`, "content-type": "application/json" }, body: JSON.stringify(body) });
+ if (response.status === 401 && retryAuth && auth.canRefresh()) {
+ await auth.refresh();
+ return await this.binary(path, auth, body, false);
+ }
if (!response.ok) throw new Error(`HypiHub returned HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
return { bytes: new Uint8Array(await response.arrayBuffer()), mediaType: response.headers.get("content-type")?.split(";", 1)[0] ?? "audio/wav" };
}
}
-async function complete(client: HypiHubClient, apiKey: string, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ArtifactStore): Promise<EndpointOutcome> {
- const response = await client.json(`/jobs/${encodeURIComponent(id)}/assets`, apiKey); const items = response.items;
+function authFor(context: EndpointInvocationContext, client: HypiHubClient, apiKey: CredentialRef): HypiHubAuth {
+ return createHypiHubAuth({
+ secret: credential(context),
+ baseUrl: client.baseUrl,
+ fetch: client.fetcher,
+ ...(context.credentialStore === undefined ? {} : { credentialStore: context.credentialStore }),
+ credentialRef: apiKey,
+ });
+}
+
+async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ArtifactStore): 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[] = [];
for (const item of items) { const asset = object(item, "HypiHub asset"); assert(typeof asset.url === "string", "HypiHub asset has no URL"); const downloaded = await client.download(asset.url); blobs.push(await artifacts.put(downloaded.bytes, downloaded.mediaType)); }
return { status: "completed", result: { value: route.packageResult(blobs) } };
}
-async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {
+async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, apiKey: CredentialRef, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {
const route = hypiHubRouteForCapability(context.need.capability);
assert(route !== undefined && route.media === "audio", "HypiHub does not implement this exact capability");
+ const auth = authFor(context, client, apiKey);
const compiled = await route.compile(context.need.constraints, async (artifact) => publicAssetUrl === undefined
? await resolveArtifactInline(context.artifacts, artifact)
: await publicAssetUrl(artifact, context.artifacts));
- await verifyModelRoute(client, credential(context), compiled.model, "audio_speech");
- const audio = await client.binary("/audio/speech", credential(context), { model: compiled.model, ...(compiled.input as Record<string, unknown>) });
+ await verifyModelRoute(client, auth, compiled.model, "audio_speech");
+ const audio = await client.binary("/audio/speech", auth, { model: compiled.model, ...(compiled.input as Record<string, unknown>) });
const artifact = await context.artifacts.put(audio.bytes, audio.mediaType);
return { value: route.packageResult([artifact]) };
}
-function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs: number, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): AsyncEndpoint {
+function endpoint(client: HypiHubClient, apiKey: CredentialRef, pollIntervalMs: number, maxOperationMs: number, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): AsyncEndpoint {
return {
async start(context: EndpointStartContext) {
try {
const route = hypiHubRouteForCapability(context.need.capability);
- assert(route !== undefined, "HypiHub does not implement this exact capability"); const apiKey = credential(context);
+ assert(route !== undefined, "HypiHub does not implement this exact capability"); const auth = authFor(context, client, apiKey);
const uploaded = new Map<string, Promise<string>>();
const resolve = (artifact: BlobRef): Promise<string> => {
const existing = uploaded.get(artifact.digest);
if (existing !== undefined) return existing;
const promise = publicAssetUrl === undefined
- ? client.upload(artifact, context.artifacts, apiKey)
+ ? client.upload(artifact, context.artifacts, auth)
: publicAssetUrl(artifact, context.artifacts);
uploaded.set(artifact.digest, promise);
return promise;
@@ -207,10 +228,10 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
const path = route.media === "image"
? (hasReferences ? "/images/edits" : "/images/generations")
: "/videos";
- await verifyModelRoute(client, apiKey, compiled.model,
+ await verifyModelRoute(client, auth, compiled.model,
path === "/images/edits" ? "image_edits" : path === "/images/generations" ? "images" : "videos");
- const response = await client.json(path, apiKey, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": context.operation }, body: JSON.stringify({ model: compiled.model, ...input }) });
- const status = response.status; if (status === "succeeded" || status === "completed") return await complete(client, apiKey, route, jobId(response), context.artifacts);
+ 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; if (status === "succeeded" || status === "completed") return await complete(client, auth, route, jobId(response), context.artifacts);
const handle: Handle = { contract: "hypit.hypihub-operation@1", jobId: jobId(response), route: capabilityKey(route.capability), startedAt: Date.now() };
return wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: "submitted" });
} catch (error) { return failure(error); }
@@ -220,7 +241,8 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
const handle = object(context.handle, "HypiHub handle") as unknown as Handle; const route = hypiHubRouteForCapability(context.need.capability);
assert(route !== undefined && handle.contract === "hypit.hypihub-operation@1" && handle.route === capabilityKey(route.capability), "HypiHub handle is invalid");
if (Date.now() - handle.startedAt > maxOperationMs) throw new Error("HypiHub operation timed out");
- const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, credential(context)); const status = job.status;
+ const auth = authFor(context, client, apiKey);
+ const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, auth); 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") {
const detail = [job.error, job.message, job.reason, job.detail]
@@ -228,7 +250,7 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
throw new Error(`HypiHub job ${status}${typeof detail === "string" ? `: ${detail}` : ""}`);
}
if (status !== "succeeded" && status !== "completed") throw new Error(`HypiHub returned unknown job status ${String(status)}`);
- return await complete(client, credential(context), route, handle.jobId, context.artifacts);
+ return await complete(client, auth, route, handle.jobId, context.artifacts);
} catch (error) { return failure(error); }
},
};
@@ -246,18 +268,21 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
uploadPartTimeout, uploadPartAttempts,
fetcher: options.fetch ?? globalThis.fetch,
});
- const asyncEndpoint = endpoint(client, options.pollIntervalMs ?? 10_000, 20 * 60_000, options.publicAssetUrl);
+ const apiKey = options.apiKey ?? credentialRef("os", "hypihub.oauth");
+ const asyncEndpoint = endpoint(client, apiKey, options.pollIntervalMs ?? 10_000, 20 * 60_000, options.publicAssetUrl);
const audioEndpoint: ImmediateEndpointHandler = async (context) => {
try {
- return await synthesizeAudio(client, context, options.publicAssetUrl);
+ return await synthesizeAudio(client, context, apiKey, options.publicAssetUrl);
} catch (error) {
throw new Error(guidedMessage(error), { cause: error });
}
};
const geminiEndpoint: ImmediateEndpointHandler = async (context) => {
const request = inlineGeminiRequest(context);
+ const auth = authFor(context, client, apiKey);
const generate = createHypiHubGeminiGenerator({
- apiKey: credential(context),
+ apiKey: await auth.token(),
+ auth,
model: context.need.capability.name,
...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),
...(options.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: options.requestTimeoutMs }),
@@ -279,14 +304,14 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
const whisperxEndpoint: ImmediateEndpointHandler = async (context) => {
try {
const request = whisperXAlignmentRequest(context.need.constraints);
- const apiKey = credential(context);
+ const auth = authFor(context, client, apiKey);
const model = options.whisperxModel ?? "victor-upmeet/whisperx";
- await verifyModelRoute(client, apiKey, model, "transcriptions");
+ await verifyModelRoute(client, auth, model, "transcriptions");
const evidence = await transcribeWithHypiHub(
client,
request,
context.artifacts,
- apiKey,
+ auth,
model,
);
return { value: { kind: "inline", value: canonicalize(evidence) } };
@@ -294,7 +319,6 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
throw new Error(guidedMessage(error), { cause: error });
}
};
- const apiKey = options.apiKey ?? credentialRef("os", "hypihub.oauth");
const endpointPackage = defineEndpointPackage({
module: hypiHubProviderModuleRef, facet: "gateway", instance: options.instance ?? "hypihub.default", pool: options.pool ?? options.instance ?? "hypihub.default",
credentials: { apiKey }, credentialInputs: { apiKey: { label: "HypiHub login" } }, defaultConcurrency: options.defaultConcurrency ?? 3,
@@ -320,5 +344,15 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
},
],
});
- return Object.assign(endpointPackage, createHypiHubPricingClient({ client, apiKey }));
+ return Object.assign(endpointPackage, createHypiHubPricingClient({
+ client,
+ apiKey,
+ auth: (secret, credentials) => createHypiHubAuth({
+ secret,
+ baseUrl: client.baseUrl,
+ fetch: client.fetcher,
+ credentialStore: credentials,
+ credentialRef: apiKey,
+ }),
+ }));
}
diff --git a/packages/provider-hypihub/src/upload.ts b/packages/provider-hypihub/src/upload.ts
index a5c7bef4..0db70fcc 100644
--- a/packages/provider-hypihub/src/upload.ts
+++ b/packages/provider-hypihub/src/upload.ts
@@ -1,5 +1,17 @@
import { createHash } from "node:crypto";
+import type { HypiHubAuth } from "./oauth.js";
+
+type UploadAuth = HypiHubAuth | string;
+
+async function uploadToken(auth: UploadAuth): Promise<string> {
+ return typeof auth === "string" ? auth : await auth.token();
+}
+
+function uploadCanRefresh(auth: UploadAuth): boolean {
+ return typeof auth !== "string" && auth.canRefresh();
+}
+
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
@@ -107,15 +119,19 @@ export class HypiHubUploader {
return message.replace(/https?:\/\/\S+/giu, "[redacted-url]").slice(0, 300);
}
- private async json(path: string, apiKey: string, init: RequestInit = {}): Promise<Record<string, unknown>> {
+ private async json(path: string, auth: UploadAuth, init: RequestInit = {}, retryAuth = true): Promise<Record<string, unknown>> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.requestTimeout);
try {
const response = await this.fetcher(`${this.baseUrl}${path}`, {
...init,
signal: controller.signal,
- headers: { authorization: `Bearer ${apiKey}`, ...(init.headers ?? {}) },
+ headers: { authorization: `Bearer ${await uploadToken(auth)}`, ...(init.headers ?? {}) },
});
+ if (response.status === 401 && retryAuth && uploadCanRefresh(auth)) {
+ await (auth as HypiHubAuth).refresh();
+ return await this.json(path, auth, init, false);
+ }
const text = await response.text();
let body: unknown = {};
try { body = text.length === 0 ? {} : JSON.parse(text); }
@@ -129,10 +145,10 @@ export class HypiHubUploader {
}
}
- private async signParts(uploadId: string, declarations: readonly PartDeclaration[], apiKey: string): Promise<Map<number, Record<string, unknown>>> {
+ private async signParts(uploadId: string, declarations: readonly PartDeclaration[], auth: UploadAuth): Promise<Map<number, Record<string, unknown>>> {
const startedAt = Date.now();
this.log(`part signing started upload=${uploadId} parts=${declarations.length}`);
- const response = await this.json(`/files/uploads/${encodeURIComponent(uploadId)}/parts`, apiKey, {
+ const response = await this.json(`/files/uploads/${encodeURIComponent(uploadId)}/parts`, auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ parts: declarations }),
@@ -165,11 +181,11 @@ export class HypiHubUploader {
return { "content-length": contentLength, "x-amz-checksum-sha256": checksum };
}
- private async putPart(uploadId: string, declaration: PartDeclaration, initial: Record<string, unknown>, body: Uint8Array, apiKey: string): Promise<CompletedPart> {
+ private async putPart(uploadId: string, declaration: PartDeclaration, initial: Record<string, unknown>, body: Uint8Array, auth: UploadAuth): Promise<CompletedPart> {
let capability = initial;
for (let attempt = 0; attempt < this.uploadPartAttempts; attempt += 1) {
if (attempt > 0) {
- const refreshed = await this.signParts(uploadId, [declaration], apiKey);
+ const refreshed = await this.signParts(uploadId, [declaration], auth);
capability = refreshed.get(declaration.part_number) ?? {};
}
const controller = new AbortController();
@@ -213,7 +229,7 @@ export class HypiHubUploader {
throw new Error(`S3 upload part ${declaration.part_number} failed after ${this.uploadPartAttempts} attempts`);
}
- private async uploadDirect(bytes: Uint8Array, apiKey: string, policy: Record<string, unknown>): Promise<string> {
+ private async uploadDirect(bytes: Uint8Array, auth: UploadAuth, policy: Record<string, unknown>): Promise<string> {
const uploadId = requiredString(policy.upload_id, "HypiHub upload id");
const partSize = requiredInteger(policy.part_size, "HypiHub upload part size");
const partCount = requiredInteger(policy.part_count, "HypiHub upload part count");
@@ -232,7 +248,7 @@ export class HypiHubUploader {
});
this.log(`multipart upload negotiated upload=${uploadId} bytes=${bytes.byteLength} part_size=${partSize} parts=${partCount} concurrency=${requestedConcurrency}`);
try {
- const signed = await this.signParts(uploadId, declarations, apiKey);
+ const signed = await this.signParts(uploadId, declarations, auth);
const completed = new Array<CompletedPart>(partCount);
let cursor = 0;
const worker = async (): Promise<void> => {
@@ -245,13 +261,13 @@ export class HypiHubUploader {
const body = bytes.subarray(start, Math.min(start + partSize, bytes.byteLength));
const capability = signed.get(declaration.part_number);
assert(capability !== undefined, `HypiHub upload part ${declaration.part_number} was not signed`);
- completed[index] = await this.putPart(uploadId, declaration, capability, body, apiKey);
+ completed[index] = await this.putPart(uploadId, declaration, capability, body, auth);
}
};
await Promise.all(Array.from({ length: Math.min(requestedConcurrency, partCount) }, worker));
const completeStartedAt = Date.now();
this.log(`multipart complete started upload=${uploadId} parts=${partCount}`);
- const response = await this.json(`/files/uploads/${encodeURIComponent(uploadId)}/complete`, apiKey, {
+ const response = await this.json(`/files/uploads/${encodeURIComponent(uploadId)}/complete`, auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ parts: completed }),
@@ -262,13 +278,13 @@ export class HypiHubUploader {
return url;
} catch (error) {
this.log(`multipart upload failed upload=${uploadId} reason=${this.safeReason(error)}`);
- try { await this.json(`/files/uploads/${encodeURIComponent(uploadId)}`, apiKey, { method: "DELETE" }); }
+ try { await this.json(`/files/uploads/${encodeURIComponent(uploadId)}`, auth, { method: "DELETE" }); }
catch { /* S3 Lifecycle is the final abort fallback. */ }
throw error;
}
}
- async upload(input: HypiHubUploadInput, apiKey: string): Promise<string> {
+ async upload(input: HypiHubUploadInput, auth: UploadAuth): Promise<string> {
assert(input.bytes.byteLength > 0, "HypiHub reference artifact is empty");
const startedAt = Date.now();
const digest = createHash("sha256").update(input.bytes).digest("hex");
@@ -281,7 +297,7 @@ export class HypiHubUploader {
const policyStartedAt = Date.now();
this.log(`upload session request started bytes=${input.bytes.byteLength} mime=${input.mediaType}`);
try {
- policy = await this.json("/files/uploads", apiKey, {
+ policy = await this.json("/files/uploads", auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
@@ -299,7 +315,7 @@ export class HypiHubUploader {
throw error;
}
assert(policy.upload_mode === "s3_multipart", "HypiHub returned an unknown upload mode");
- const result = await this.uploadDirect(input.bytes, apiKey, policy);
+ const result = await this.uploadDirect(input.bytes, auth, policy);
this.log(`upload finished bytes=${input.bytes.byteLength} mime=${input.mediaType} elapsed=${this.elapsed(startedAt)}`);
return result;
}
diff --git a/packages/provider-hypihub/src/whisperx.ts b/packages/provider-hypihub/src/whisperx.ts
index 5d195215..f518f0e8 100644
--- a/packages/provider-hypihub/src/whisperx.ts
+++ b/packages/provider-hypihub/src/whisperx.ts
@@ -3,6 +3,7 @@ import type { AlignedTranscriptEvidence, SpeechTranscriptPassage } from "@hypit/
import type { ArtifactStore } from "@hypit/runtime";
import { whisperXCapabilities } from "@hypit/whisperx";
import type { WhisperXAlignmentRequest } from "@hypit/whisperx";
+import type { HypiHubAuth } from "./oauth.js";
type RawWord = { readonly word?: unknown; readonly text?: unknown; readonly start?: unknown; readonly end?: unknown; readonly score?: unknown };
type RawSegment = { readonly start?: unknown; readonly end?: unknown; readonly words?: unknown };
@@ -87,25 +88,25 @@ export function whisperXAlignmentRequest(value: unknown): WhisperXAlignmentReque
export async function transcribeWithHypiHub(
client: {
- upload(artifact: WhisperXAlignmentRequest["audio"], artifacts: ArtifactStore, apiKey: string): Promise<string>;
- transcribe(body: Record<string, unknown>, apiKey: string): Promise<HypiHubWhisperXResponse>;
+ upload(artifact: WhisperXAlignmentRequest["audio"], artifacts: ArtifactStore, auth: HypiHubAuth): Promise<string>;
+ transcribe(body: Record<string, unknown>, auth: HypiHubAuth): Promise<HypiHubWhisperXResponse>;
},
request: WhisperXAlignmentRequest,
artifacts: ArtifactStore,
- apiKey: string,
+ auth: HypiHubAuth,
model: string,
): Promise<AlignedTranscriptEvidence> {
const bytes = await artifacts.get(request.audio.digest);
assert(bytes !== undefined && bytes.byteLength === request.audio.size,
`HypiHub WhisperX evidence Artifact ${request.audio.digest} is unavailable or has changed`);
- const url = await client.upload(request.audio, artifacts, apiKey);
+ const url = await client.upload(request.audio, artifacts, auth);
return interpretHypiHubWhisperXResponse(await client.transcribe({
model,
url,
language: request.language,
response_format: "verbose_json",
timestamp_granularities: ["word", "segment"],
- }, apiKey), request.sampleFrames);
+ }, auth), request.sampleFrames);
}
export { speechEvidenceTypes, whisperXCapabilities };
diff --git a/packages/provider-hypihub/test/gemini.test.ts b/packages/provider-hypihub/test/gemini.test.ts
index 012f4324..68eece43 100644
--- a/packages/provider-hypihub/test/gemini.test.ts
+++ b/packages/provider-hypihub/test/gemini.test.ts
@@ -44,13 +44,16 @@ test("HypiHub Gemini uses native wire format for text, image and video parts", a
] }]);
});
-test("HypiHub Gemini points unavailable models to HypiHub", async () => {
+test("HypiHub Gemini reports unavailable models without misdiagnosing authentication", async () => {
const generate = createHypiHubGeminiGenerator({
apiKey: "test-key",
fetch: async () => new Response("missing", { status: 404 }),
});
- await assert.rejects(() => generate({ instruction: "x", parts: [{ text: "x" }] }),
- /sign in to HypiHub at https:\/\/hypit\.ai with hypit auth login/iu);
+ await assert.rejects(() => generate({ instruction: "x", parts: [{ text: "x" }] }), (error) => {
+ assert.match(String(error), /HTTP 404/iu);
+ assert.doesNotMatch(String(error), /auth login/iu);
+ return true;
+ });
});
test("HypiHub Gemini retries upstream rate limits without reuploading files", async () => {
diff --git a/packages/provider-hypihub/test/oauth.test.ts b/packages/provider-hypihub/test/oauth.test.ts
new file mode 100644
index 00000000..649c69a0
--- /dev/null
+++ b/packages/provider-hypihub/test/oauth.test.ts
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { CredentialValue, WritableCredentialStore } from "@hypit/runtime";
+import { credentialRef } from "@hypit/runtime";
+
+import {
+ createHypiHubAuth,
+ decodeHypiHubOAuthCredential,
+ encodeHypiHubOAuthCredential,
+} from "../src/oauth.js";
+
+test("HypiHub OAuth refreshes an expired token and persists rotated credentials", async () => {
+ const ref = credentialRef("memory", "hypihub.oauth");
+ const values = new Map<string, CredentialValue>();
+ const store: WritableCredentialStore = {
+ owns(candidate) { return candidate.store === "memory"; },
+ async resolve(candidate) { return values.get(candidate.key); },
+ async put(candidate, value) { values.set(candidate.key, value); },
+ async delete(candidate) { return values.delete(candidate.key); },
+ };
+ const requests: URLSearchParams[] = [];
+ const auth = createHypiHubAuth({
+ secret: encodeHypiHubOAuthCredential({
+ accessToken: "expired-access",
+ refreshToken: "refresh-one",
+ expiresAt: Date.now() - 1,
+ }),
+ baseUrl: "https://hypit.ai/v1",
+ credentialStore: store,
+ credentialRef: ref,
+ fetch: async (_input, init) => {
+ requests.push(new URLSearchParams(String(init?.body)));
+ return Response.json({
+ access_token: "fresh-access",
+ refresh_token: "refresh-two",
+ expires_in: 3600,
+ });
+ },
+ });
+
+ assert.equal(await auth.token(), "fresh-access");
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0]?.get("grant_type"), "refresh_token");
+ assert.equal(requests[0]?.get("refresh_token"), "refresh-one");
+ const saved = values.get(ref.key);
+ assert(saved !== undefined);
+ assert.deepEqual(decodeHypiHubOAuthCredential(saved.secret), {
+ format: "hypit.hypihub-oauth@1",
+ accessToken: "fresh-access",
+ refreshToken: "refresh-two",
+ expiresAt: saved.expiresAt,
+ });
+ assert(saved.expiresAt !== undefined && saved.expiresAt > Date.now());
+});
+
+test("raw HypiHub API keys remain backward compatible and are never refreshed", async () => {
+ const auth = createHypiHubAuth({
+ secret: "static-api-key",
+ baseUrl: "https://hypit.ai",
+ fetch: async () => { throw new Error("static keys must not refresh"); },
+ });
+ assert.equal(await auth.token(), "static-api-key");
+ assert.equal(auth.canRefresh(), false);
+});
diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.ts
index 71cae0bd..9ac5da71 100644
--- a/packages/provider-hypihub/test/provider.test.ts
+++ b/packages/provider-hypihub/test/provider.test.ts
@@ -6,10 +6,13 @@ import type { AsyncEndpoint } from "@hypit/endpoint-kit";
import { geminiCapabilities, sealGeminiRequest } from "@hypit/gemini";
import type { CanonicalValue, Need } from "@hypit/protocol";
import { mimoTtsEndpoints } from "@hypit/mimo-tts";
+import type { CredentialValue, WritableCredentialStore } from "@hypit/runtime";
+import { credentialRef } from "@hypit/runtime";
import { textTypes } from "@hypit/text";
import { sealSeedanceRequest, seedanceEndpoints } from "@hypit/seedance";
import { createHypiHubProvider } from "../src/provider.js";
+import { decodeHypiHubOAuthCredential, encodeHypiHubOAuthCredential } from "../src/oauth.js";
function need(constraints: CanonicalValue): Need {
return {
@@ -124,6 +127,71 @@ test("HypiHub uploads referenced Artifacts once, submits their HTTPS URLs, and p
assert.equal(calls.length, 9);
});
+test("HypiHub refreshes after a provider 401, retries with the new token, and persists rotation", async () => {
+ const request = need(sealSeedanceRequest("seedance-2-mini", {
+ prompt: ["A presenter turns toward camera."],
+ resolution: ["720p"], aspectRatio: ["16:9"], duration: [5],
+ generateAudio: [false], webSearch: [false],
+ }) as unknown as CanonicalValue);
+ const ref = credentialRef("os", "hypihub.oauth");
+ const initialSecret = encodeHypiHubOAuthCredential({ accessToken: "old-access", refreshToken: "refresh-one" });
+ let saved: CredentialValue | undefined;
+ const credentialStore: WritableCredentialStore = {
+ owns() { return true; },
+ async resolve() { return saved; },
+ async put(_candidate, value) { saved = value; },
+ async delete() { return true; },
+ };
+ const requests: Array<{ readonly url: string; readonly authorization: string | undefined }> = [];
+ const fakeFetch: typeof globalThis.fetch = async (input, init) => {
+ const url = String(input);
+ const headers = init?.headers as Record<string, string> | undefined;
+ requests.push({ url, authorization: headers?.authorization });
+ if (url === "https://hypit.ai/oauth/token") {
+ assert.equal(init?.method, "POST");
+ assert.match(String(init?.body), /grant_type=refresh_token/iu);
+ return Response.json({ access_token: "fresh-access", refresh_token: "refresh-two", expires_in: 3600 });
+ }
+ if (url.endsWith("/v1/models/bytedance%2Fseedance-2-mini")) {
+ if (headers?.authorization === "Bearer old-access") return new Response("expired", { status: 401 });
+ assert.equal(headers?.authorization, "Bearer fresh-access");
+ return Response.json({ endpoints: ["videos"] });
+ }
+ if (url.endsWith("/v1/videos")) {
+ assert.equal(headers?.authorization, "Bearer fresh-access");
+ return Response.json({ id: "job_refresh_test", status: "queued" });
+ }
+ throw new Error(`Unexpected URL ${url}`);
+ };
+ const registry = new EndpointRegistry();
+ await createHypiHubProvider({ fetch: fakeFetch, pollIntervalMs: 0, requestTimeoutMs: 1_000 }).install(registry);
+ const resolution = registry.resolve(request);
+ assert.equal(resolution.status, "resolved");
+ assert.equal(resolution.registration.kind, "asynchronous");
+ const started = await resolution.registration.endpoint.start({
+ command: { kind: "fulfill-need", id: "command:refresh-test", need: request },
+ need: request,
+ artifacts: new MemoryArtifactStore(),
+ credentials: { apiKey: { secret: initialSecret } },
+ credentialStore,
+ operation: "operation:refresh-test",
+ });
+ assert.equal(started.status, "pending");
+ assert.deepEqual(requests.map((item) => [item.url, item.authorization]), [
+ ["https://hypit.ai/v1/models/bytedance%2Fseedance-2-mini", "Bearer old-access"],
+ ["https://hypit.ai/oauth/token", undefined],
+ ["https://hypit.ai/v1/models/bytedance%2Fseedance-2-mini", "Bearer fresh-access"],
+ ["https://hypit.ai/v1/videos", "Bearer fresh-access"],
+ ]);
+ assert(saved !== undefined);
+ const decoded = decodeHypiHubOAuthCredential(saved.secret);
+ assert.equal(decoded.format, "hypit.hypihub-oauth@1");
+ assert.equal(decoded.accessToken, "fresh-access");
+ assert.equal(decoded.refreshToken, "refresh-two");
+ assert(typeof decoded.expiresAt === "number");
+ assert(decoded.expiresAt > Date.now());
+});
+
test("HypiHub fulfills Gemini through the Runtime endpoint and uploads every media Artifact", async () => {
const artifacts = new MemoryArtifactStore();
const image = await artifacts.put(new Uint8Array([1, 2, 3]), "image/png");
diff --git a/skills/hypit/references/credentials.md b/skills/hypit/references/credentials.md
index 96c1b9a8..f0942c02 100644
--- a/skills/hypit/references/credentials.md
+++ b/skills/hypit/references/credentials.md
@@ -30,6 +30,13 @@ the OS credential store, and opening login does not itself submit a paid generat
`hypit auth login <endpoint> --runtime <profile>` itself. This opens the browser login and waits for
the callback; do not ask the author to run the command or paste a key. Resume only after it succeeds.
+After a successful HypiHub OAuth login, the client stores the access token together with the refresh token
+and expiry metadata in the selected writable CredentialStore. The HypiHub Provider refreshes the access
+token before expiry, retries one request after an upstream `401`, and persists a rotated refresh token when
+the server returns one. A raw API key or legacy token has no refresh token and remains static; after it
+expires, ask the author to sign in again. Do not interpret `403`, `404`, or model-routing errors as an
+authentication failure unless the response is explicitly an unauthorized-token error.
+
HypiHub is the default for supported paid capabilities and Gemini VLM. It can be replaced only when the
author explicitly selects another Provider.
For ordinary `@hypit/gemini` Author Source, the Runtime Profile selects