Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat(runtime): expose provider pricing and request support
kashorin59b17e777b0d
diff --git a/docs/guide/providers.md b/docs/guide/providers.mdindex d229a9de..a804141a 100644--- a/docs/guide/providers.md+++ b/docs/guide/providers.md@@ -140,14 +140,18 @@ the Runtime has resolved that Endpoint's declared credential slots. It may makerequest to the real service, such as reading the authenticated model catalog. It must not be called byBuild preflight and must never submit generation work.-A Provider that charges declares where it publishes prices, and nothing more: `pricing: { kind: "page",-url }` on `defineEndpointPackage`, pointing at the Provider's own public price page. A Provider that-runs on this machine declares `pricing: { kind: "local" }`. Hypit never copies or interprets prices;-`hypit plan --runtime <profile>` prints the Endpoint behind each request. Local work is marked local;-Provider work carries the Provider's price page so the Agent can read the source before a paid Build.-An undeclared price source is reported as unknown. Planning applies the selected Endpoint's ordinary-`supports` check and does not maintain a second selection table. When an upstream file will only exist-during the Build, the capability package reconstructs the authored+A Provider that charges declares where it publishes prices with `pricing: { kind: "page", url }` on+`defineEndpointPackage`; a Provider that runs on this machine declares `pricing: { kind: "local" }`.+An Endpoint may additionally return current Provider-shaped documents from `readPricing`; a service+with only a web page keeps that page as its interface. `hypit pricing <run> --runtime <profile>` places+the material beside the Run's Needs without creating a Build. The Agent can calculate and explain the+cost from those two facts, while the user's decision remains the spending authority. The shared+interface remains only a source URL and Provider-shaped JSON, so a newly supported relay does not+require a new Hypit pricing category.++`hypit plan --runtime <profile>` remains local and prints the Endpoint behind each request. Planning+applies the selected Endpoint's ordinary `supports` check and does not maintain a second selection+table. When an upstream file will only exist during the Build, the capability package reconstructs the authoredrequest parameters and leaves that file as a symbolic Resource slot. The same `supports` predicate stillruns before the Build is queued. A package that cannot describe the request stops planning instead offalling back to capability-only selection.diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.mdindex 86daae41..db53ff3b 100644--- a/docs/zh/guide/providers.md+++ b/docs/zh/guide/providers.md@@ -133,7 +133,17 @@ Activation 还可以返回 `diagnose(context)`。它只会在用户显式运行Runtime 会先解析该 Endpoint 自己声明的凭据槽。它可以对真实服务做一次有界只读请求,例如读取已认证账户的模型目录;Build 预检不能调用它,它也绝不能提交生成任务。-收费的 Provider 只声明一件事:价格发布在哪里。在 `defineEndpointPackage` 上写 `pricing: { kind: "page", url }`,指向 Provider 自己的公开价格页;在本机运行的 Provider 声明 `pricing: { kind: "local" }`。Hypit 不复制也不解释价格;`hypit plan --runtime <profile>` 会列出每个请求的 Endpoint,本地工作明确标成本地,Provider 工作附带它自己的价格页,Agent 在付费 Build 之前去原始页面读价。未声明价格来源的会被报告为未知。上游文件尚未生成时,能力包仍重建全部作者参数,只把未来文件保留为符号 Resource 槽;同一个 Endpoint 的普通 `supports` 会在 Build 入队前检查这份规格。包无法说明请求时直接停止,不回退成 capability-only 的假验证,也不维护第二张选择表。+收费的 Provider 用 `pricing: { kind: "page", url }` 声明价格发布页面;在本机运行的 Provider+声明 `pricing: { kind: "local" }`。Endpoint 还可以通过 `readPricing` 返回 Provider 当前发布的+原始费率文档;只有网页的服务继续以该网页作为价格入口。`hypit pricing <run> --runtime <profile>`+把这些材料放在 Run 的 Needs 旁边,而且不会创建 Build。Agent 可以据此计算并解释费用,用户的+决定仍然是支出授权。共享接口只有来源 URL 和保持 Provider 原始形状的 JSON,因此接入新的+中转站不需要先给 Hypit 增加一种价格表分类。++`hypit plan --runtime <profile>` 仍然完全在本地执行并列出每个请求的 Endpoint。上游文件尚未+生成时,能力包仍重建全部作者参数,只把未来文件保留为符号 Resource 槽;同一个 Endpoint 的+普通 `supports` 会在 Build 入队前检查这份规格。包无法说明请求时直接停止,不回退成+capability-only 的假验证,也不维护第二张选择表。## 5. 按需声明 Managed Programdiff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.tsindex 53175c1b..6a8e2b92 100644--- a/packages/cli/src/arguments.ts+++ b/packages/cli/src/arguments.ts@@ -62,7 +62,8 @@ export function parseCommand(argv: readonly string[]): CliCommand {...optionalPackageRoot(options),};}- case "plan": {+ case "plan":+ case "pricing": {const [source, rest] = requiredPositional(tail, `${command} requires one Source`);const options = commandOptions(command, rest,"--runtime", "--package-root", "--workspace", "--asset-root", "--limit");diff --git a/packages/cli/src/build-planning.ts b/packages/cli/src/build-planning.tsindex 2eb1b85f..20f72e4f 100644--- a/packages/cli/src/build-planning.ts+++ b/packages/cli/src/build-planning.ts@@ -56,6 +56,15 @@ function sameRef(&& left.name === right.name;}+/** The author-facing component and operation, without the encoded Source identity. */+function plannedStepLabel(step: string): string {+ let decoded = step;+ try { decoded = decodeURIComponent(step); } catch { /* keep the raw id */ }+ const marker = "::component::";+ const at = decoded.lastIndexOf(marker);+ return at === -1 ? decoded : decoded.slice(at + marker.length);+}+function demandedCapabilities(state: BuildState): readonly CapabilityRef[] {const found = new Map(plannedNeeds(state).map((need) => [capabilityName(need.capability), need.capability]));return [...found.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, value]) => value);@@ -64,14 +73,23 @@ function demandedCapabilities(state: BuildState): readonly CapabilityRef[] {export type PlanProviderView = {readonly request: string;readonly capability: string;- readonly status: "resolved" | "unresolved" | "ambiguous";+ readonly status: "resolved" | "unresolved" | "unsupported" | "ambiguous";readonly endpoint?: string;readonly use?: string;readonly pricing?: { readonly kind: "page"; readonly url: string } | { readonly kind: "local" };readonly endpoints?: readonly string[];+ readonly rejections?: readonly { readonly endpoint: string; readonly message: string }[];readonly binding?: string;};+export type PlanPricingView = PlanProviderView & {+ readonly pricingDocuments?: readonly {+ readonly source: string;+ readonly data: CanonicalValue;+ }[];+ readonly pricingError?: string;+};+export type PendingPlanInput = {readonly input: string;readonly record: string;@@ -284,14 +302,13 @@ export async function evaluatePlanNeeds(return { state, needs: result };}-/** Resolve every planned request independently; concrete constraints exercise Endpoint `supports`. */-export async function describePlanProviders(- host: NodeRuntimeHost,+/** The complete pre-Build requests shared by Endpoint selection and Provider pricing reads. */+export function plannedProviderQueries(state: BuildState,evaluated: EvaluatedPlan,-): Promise<readonly PlanProviderView[]> {+): readonly import("@hypit/runtime-host-node").RuntimeHostProviderQuery[] {const planned = plannedNeeds(state);- const requests = planned.flatMap((item) => {+ return planned.flatMap((item) => {const plannedRequest = evaluated.needs.get(item.need);const constraints = plannedRequest?.constraints;if (plannedRequest === undefined || constraints === undefined) return [];@@ -308,6 +325,16 @@ export async function describePlanProviders(}),}];});+}++/** Resolve every planned request independently; concrete constraints exercise Endpoint `supports`. */+export async function describePlanProviders(+ host: NodeRuntimeHost,+ state: BuildState,+ evaluated: EvaluatedPlan,+): Promise<readonly PlanProviderView[]> {+ const planned = plannedNeeds(state);+ const requests = plannedProviderQueries(state, evaluated);const described = (await host.providers(requests)).map((item) => ({request: item.request,capability: capabilityName(item.capability),@@ -316,6 +343,7 @@ export async function describePlanProviders(...(item.use === undefined ? {} : { use: item.use }),...(item.pricing === undefined ? {} : { pricing: item.pricing }),...(item.endpoints === undefined ? {} : { endpoints: item.endpoints }),+ ...(item.rejections === undefined ? {} : { rejections: item.rejections }),...(item.binding === undefined ? {} : { binding: item.binding }),}));return planned.map((item) => described.find((provider) => provider.request === item.need) ?? {@@ -325,6 +353,35 @@ export async function describePlanProviders(}).filter((item, index, all) => all.findIndex((candidate) => candidate.request === item.request) === index);}+/** Read Provider-owned pricing material relevant to each planned request. */+export async function describePlanPricing(+ host: NodeRuntimeHost,+ state: BuildState,+ evaluated: EvaluatedPlan,+): Promise<readonly PlanPricingView[]> {+ const planned = plannedNeeds(state);+ const requests = plannedProviderQueries(state, evaluated);+ const pricing = await host.pricing(requests);+ const described = pricing.map((item): PlanPricingView => ({+ request: item.request,+ capability: capabilityName(item.capability),+ status: item.status,+ ...(item.endpoint === undefined ? {} : { endpoint: item.endpoint }),+ ...(item.use === undefined ? {} : { use: item.use }),+ ...(item.pricing === undefined ? {} : { pricing: item.pricing }),+ ...(item.endpoints === undefined ? {} : { endpoints: item.endpoints }),+ ...(item.rejections === undefined ? {} : { rejections: item.rejections }),+ ...(item.binding === undefined ? {} : { binding: item.binding }),+ ...(item.pricingDocuments === undefined ? {} : { pricingDocuments: item.pricingDocuments }),+ ...(item.pricingError === undefined ? {} : { pricingError: item.pricingError }),+ }));+ return planned.map((item) => described.find((entry) => entry.request === item.need) ?? {+ request: item.need,+ capability: capabilityName(item.capability),+ status: "unresolved" as const,+ }).filter((item, index, all) => all.findIndex((candidate) => candidate.request === item.request) === index);+}+/** Refuse a Build before it is queued when any external request is not fully selectable. */export function assertPlannedRequests(state: BuildState,@@ -333,14 +390,21 @@ export function assertPlannedRequests(): void {const byRequest = new Map(providers.map((item) => [item.request, item]));const problems = plannedNeeds(state).flatMap((planned) => {+ const subject = plannedStepLabel(planned.step);const issue = evaluated.needs.get(planned.need)?.issue;- if (issue !== undefined) return [`${planned.step}.${planned.port}: ${issue}`];+ if (issue !== undefined) return [`${subject}: ${issue}`];const provider = byRequest.get(planned.need);if (provider?.status === "resolved") return [];if (provider?.status === "ambiguous") {- return [`${planned.step}.${planned.port}: several Endpoints accept ${capabilityName(planned.capability)}; bind one in the Runtime Profile`];+ return [`${subject}: several Endpoints accept ${capabilityName(planned.capability)}; bind one in the Runtime Profile`];+ }+ if (provider?.status === "unsupported") {+ const detail = (provider.rejections ?? [])+ .map((rejection) => `${rejection.endpoint}: ${rejection.message}`)+ .join("; ");+ return [`${subject}: ${detail || `no configured Endpoint accepts the complete ${capabilityName(planned.capability)} request`}`];}- return [`${planned.step}.${planned.port}: no selected Endpoint accepts the complete ${capabilityName(planned.capability)} request`];+ return [`${subject}: no selected Endpoint accepts the complete ${capabilityName(planned.capability)} request`];});if (problems.length > 0) {throw new Error([diff --git a/packages/cli/src/command.ts b/packages/cli/src/command.tsindex 8d1096e4..7f3f1c6a 100644--- a/packages/cli/src/command.ts+++ b/packages/cli/src/command.ts@@ -22,6 +22,7 @@ type SourceOptions = ProjectOption & {export type AuthorCommand =| (CommandBase & SourceOptions & { readonly command: "check" })| (CommandBase & SourceOptions & RuntimeOption & { readonly command: "plan" })+ | (CommandBase & SourceOptions & RuntimeOption & { readonly command: "pricing" })| (CommandBase & SourceOptions & RuntimeOption & {readonly command: "build";readonly follow: boolean;diff --git a/packages/cli/src/commands/environment.ts b/packages/cli/src/commands/environment.tsindex 6d02ffb1..49653130 100644--- a/packages/cli/src/commands/environment.ts+++ b/packages/cli/src/commands/environment.ts@@ -52,6 +52,9 @@ export async function runEnvironmentCommand(input: {: (event: { readonly specifier: string; readonly phase: "checking" | "installing" | "ready" }): void => {if (event.phase === "installing") io.write(` · Installing ${event.specifier}\n`);};+ const reportCredentialProgress = args.presentation.json+ ? io.writeProgress+ : io.writeProgress ?? io.write;if (args.command === "paths") {const runtimePaths = runtimeProfile === undefined@@ -344,7 +347,11 @@ export async function runEnvironmentCommand(input: {throw new Error(`${item.label} cannot be written by this command; ${source}`);}const raw = item.acquisition !== undefined && args.credentialFile === undefined- ? await acquireOAuthCredential(io, item.acquisition)+ ? await acquireOAuthCredential(item.acquisition, {+ ...(reportCredentialProgress === undefined ? {} : {+ onProgress: (message) => reportCredentialProgress(` · ${message}\n`),+ }),+ }): args.credentialFile === undefined? await io.readSecret?.(`${item.label}: `): await readFile(args.credentialFile, "utf8");diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.tsindex 6920f00c..b88a5aad 100644--- a/packages/cli/src/main.ts+++ b/packages/cli/src/main.ts@@ -17,7 +17,7 @@ import { writeCliHelp, writeCliOutput } from "./output.js";import type { CliIo, CliMachineView } from "./output.js";import { parseCommand } from "./arguments.js";import type { CliCommand, RuntimeOption } from "./command.js";-import { assertPlannedRequests, assertPreflight, createCatalogDescriptor, describePlanNeeds, describePlanProviders, evaluatePlanNeeds, preflightPlan } from "./build-planning.js";+import { assertPlannedRequests, assertPreflight, createCatalogDescriptor, describePlanNeeds, describePlanPricing, describePlanProviders, evaluatePlanNeeds, preflightPlan } from "./build-planning.js";import { buildProgressLines, observeBuild } from "./observation.js";import { isProjectResultCommand, runProjectResultCommand } from "./commands/results.js";import { isEnvironmentCommand, runEnvironmentCommand } from "./commands/environment.js";@@ -267,7 +267,7 @@ export async function runCli(: `No trusted Author or Run compiler accepts Frontend ${sourceHeader.using}`;throw new Error(message);}- if ((args.command === "plan" || args.command === "build") && !runMode) {+ if ((args.command === "plan" || args.command === "pricing" || args.command === "build") && !runMode) {throw new Error(`${args.command} requires a self-described Run Source; check Author Sources independently`);}if (args.command === "check") {@@ -571,6 +571,27 @@ export async function runCli(const result = loaded.compiler.planCompilation(loaded);const planHost = runtimeProfile === undefined ? undefined : await runtimeHost(runtimeProfile);const evaluated = await evaluatePlanNeeds(result.definition, packageContributions);+ if (args.command === "pricing") {+ if (planHost === undefined) {+ throw new Error("pricing requires a Runtime; run hypit runtime init, select one with runtime use, or pass --runtime <profile>");+ }+ const pricing = await describePlanPricing(planHost, evaluated.state, evaluated);+ const needs = describePlanNeeds(evaluated.state, evaluated, pricing);+ const shown = args.limit;+ writeCliOutput(io, args.presentation, {+ kind: "pricing",+ machine: {+ format: "hypit.cli-pricing@1",+ run: projectPath(loaded.path, effectiveWorkspaceRoot),+ requestCount: pricing.length,+ pricing: pricing.slice(0, shown),+ ...(pricing.length <= shown ? {} : { omittedPricing: pricing.length - shown }),+ needs: needs.slice(0, shown),+ ...(needs.length <= shown ? {} : { omittedNeeds: needs.length - shown }),+ },+ });+ return;+ }const preflight = planHost === undefined ? undefined : await preflightPlan(planHost, evaluated.state);const providers = planHost === undefined ? undefined : await describePlanProviders(planHost, evaluated.state, evaluated);const needs = describePlanNeeds(evaluated.state, evaluated, providers ?? []);@@ -584,15 +605,17 @@ export async function runCli(const allUnreached = unreachedGenerations(result.compilation.author.graph, result.state, outputNames).map((item) => ({ output: item.name, operation: item.producer }));const targets = loaded.run.document.targets.map((item) => item.output);- const unresolvedRequestCount = providers?.filter((item) => item.status !== "resolved").length ?? 0;+ const unsupportedRequestCount = providers?.filter((item) => item.status === "unsupported").length ?? 0;+ const unresolvedRequestCount = providers?.filter((item) => item.status === "unresolved" || item.status === "ambiguous").length ?? 0;const localRequestCount = providers?.filter((item) => item.status === "resolved" && item.pricing?.kind === "local").length ?? 0;- const providerRequestCount = providers === undefined ? undefined : providers.length - localRequestCount - unresolvedRequestCount;+ const providerRequestCount = providers?.filter((item) => item.status === "resolved" && item.pricing?.kind !== "local").length;const requestIssueCount = needs.filter((item) => item.issue !== undefined).length;writeCliOutput(io, args.presentation, {kind: "plan",machine: {format: "hypit.cli-plan@3",- ok: (preflight?.ok ?? true) && unresolvedRequestCount === 0 && requestIssueCount === 0,+ ok: (preflight?.ok ?? true) && unresolvedRequestCount === 0+ && unsupportedRequestCount === 0 && requestIssueCount === 0,run: projectPath(loaded.path, effectiveWorkspaceRoot),targetCount: targets.length,targets: targets.slice(0, args.limit),@@ -600,7 +623,7 @@ export async function runCli(requestCount: needs.length,requestIssueCount,...(providerRequestCount === undefined ? {} : { providerRequestCount }),- ...(providers === undefined ? {} : { localRequestCount, unresolvedRequestCount }),+ ...(providers === undefined ? {} : { localRequestCount, unresolvedRequestCount, unsupportedRequestCount }),choiceCount: allChoices.length,choices: allChoices.slice(0, args.limit),...(allChoices.length <= args.limit ? {} : { omittedChoices: allChoices.length - args.limit }),@@ -629,7 +652,8 @@ export async function runCli(} }),},});- if ((preflight !== undefined && !preflight.ok) || unresolvedRequestCount > 0 || requestIssueCount > 0) io.setExitCode?.(1);+ if ((preflight !== undefined && !preflight.ok) || unresolvedRequestCount > 0+ || unsupportedRequestCount > 0 || requestIssueCount > 0) io.setExitCode?.(1);} finally {await planResults?.close();}diff --git a/packages/cli/src/oauth.ts b/packages/cli/src/oauth.tsindex d9022def..78b199ee 100644--- a/packages/cli/src/oauth.ts+++ b/packages/cli/src/oauth.ts@@ -5,10 +5,14 @@ import { spawn } from "node:child_process";import type { CredentialAcquisition } from "@hypit/runtime";import { encodeOAuth2Credential } from "@hypit/runtime";-import type { CliIo } from "./output.js";-const CALLBACK_MARK_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true"><path d="M7.6 3.8H14.6L12.6 7.2H5.6L7.6 3.8Z" fill="currentColor"/><path d="M4.1 10.4H16.6L18.7 7H30.4L27.9 11.1H16.1L14.1 14.2H1.8L4.1 10.4Z" fill="currentColor"/><path d="M19.1 14.1H23.1L19.3 20.7H15.4L19.1 14.1Z" fill="currentColor"/></svg>`;+type OAuthAcquisitionOptions = {+ readonly onProgress?: (message: string) => void;+ readonly fetch?: typeof globalThis.fetch;+ readonly open?: (url: string) => void;+};+function base64url(bytes: Uint8Array): string {return Buffer.from(bytes).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");}@@ -26,9 +30,12 @@ function tokenExpiry(value: { readonly expires_at?: unknown; readonly expires_in/** Acquire one OAuth credential from the exact data declared by its Endpoint package. */export async function acquireOAuthCredential(- io: CliIo,acquisition: CredentialAcquisition,+ options: OAuthAcquisitionOptions = {},): Promise<string> {+ if (!Number.isSafeInteger(acquisition.requestTimeoutMs) || acquisition.requestTimeoutMs <= 0) {+ throw new Error("OAuth token request timeout must be a positive integer");+ }const verifier = base64url(randomBytes(32));// S256 is part of OAuth PKCE. It authenticates this browser exchange; it is not content identity.const challenge = base64url(createHash("sha256").update(verifier).digest());@@ -36,10 +43,6 @@ export async function acquireOAuthCredential(const server = createServer();const callback = new Promise<string>((resolveCode, reject) => {let settled = false;- // The browser can still hold the callback connection, and commonly opens a second- // one for /favicon.ico, after the code has been read. `server.close()` waits for- // those to end, which keeps the process alive long past the exchange, so drop them- // once the response has actually been written and stop the socket holding the loop open.const closeAllConnections = (): void => {server.closeAllConnections?.();server.unref();@@ -98,23 +101,42 @@ export async function acquireOAuthCredential(authorize.searchParams.set("state", state);authorize.searchParams.set("code_challenge", challenge);authorize.searchParams.set("code_challenge_method", "S256");- io.write(`Opening sign-in: ${authorize}\n`);- const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";- const openerArgs = process.platform === "win32" ? ["/c", "start", "", authorize.toString()] : [authorize.toString()];- spawn(opener, openerArgs, { stdio: "ignore", detached: true, windowsHide: true }).unref();+ options.onProgress?.(`Opening sign-in: ${authorize}`);+ if (options.open === undefined) {+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";+ const openerArgs = process.platform === "win32" ? ["/c", "start", "", authorize.toString()] : [authorize.toString()];+ spawn(opener, openerArgs, { stdio: "ignore", detached: true, windowsHide: true }).unref();+ } else {+ options.open(authorize.toString());+ }const code = await callback;- const tokenResponse = await fetch(acquisition.tokenEndpoint, {- method: "POST",- headers: { "content-type": "application/x-www-form-urlencoded" },- body: new URLSearchParams({- grant_type: "authorization_code",- code,- redirect_uri: redirectUri,- client_id: acquisition.clientId,- code_verifier: verifier,- }),- });- const body = await tokenResponse.text();+ options.onProgress?.("Authorization returned. Exchanging token…");+ const deadline = AbortSignal.timeout(acquisition.requestTimeoutMs);+ let tokenResponse: Response;+ let body: string;+ try {+ tokenResponse = await (options.fetch ?? globalThis.fetch)(acquisition.tokenEndpoint, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ grant_type: "authorization_code",+ code,+ redirect_uri: redirectUri,+ client_id: acquisition.clientId,+ code_verifier: verifier,+ }),+ signal: deadline,+ });+ body = await tokenResponse.text();+ } catch (error) {+ if (deadline.aborted) {+ throw new Error(+ `OAuth authorization returned, but the token exchange timed out after ${acquisition.requestTimeoutMs} ms; no credential was stored`,+ { cause: error },+ );+ }+ throw error;+ }if (!tokenResponse.ok) throw new Error(`OAuth token exchange failed (${tokenResponse.status}): ${body.slice(0, 200)}`);const parsed = JSON.parse(body) as {readonly access_token?: unknown;@@ -125,6 +147,7 @@ export async function acquireOAuthCredential(if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) {throw new Error("OAuth token response contained no access token");}+ options.onProgress?.("Token received. Saving credential…");const expiresAt = tokenExpiry(parsed);return encodeOAuth2Credential({accessToken: parsed.access_token,@@ -136,10 +159,10 @@ export async function acquireOAuthCredential(}function callbackPage(success: boolean): string {- const title = success ? "Signed in to Hypit" : "Hypit sign-in failed";- const heading = success ? "Hypit is signed in" : "Hypit sign-in failed";+ const title = success ? "Authorization received" : "Hypit sign-in failed";+ const heading = success ? "Authorization received" : "Hypit sign-in failed";const message = success- ? "Your credential is ready. You can close this window."+ ? "Return to the terminal while Hypit finishes the token exchange and stores the credential.": "The sign-in could not be completed. You can close this window and try again.";const tone = success ? "success" : "error";const favicon = `data:image/svg+xml,${encodeURIComponent(CALLBACK_MARK_SVG)}`;diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsindex a891c6ce..a0167ff3 100644--- a/packages/cli/src/output.ts+++ b/packages/cli/src/output.ts@@ -1,5 +1,7 @@import { relative, resolve } from "node:path";+import type { CanonicalValue } from "@hypit/protocol";+import type { OperationalMachineView } from "./machine-view.js";export type CliTerminal = {@@ -11,6 +13,8 @@ export type CliTerminal = {export type CliIo = {readonly write: (text: string) => void;+ /** Human progress that may use stderr while `write` remains a stable machine-output channel. */+ readonly writeProgress?: (text: string) => void;/** Concrete command shells expose process status without coupling the engine to Node globals. */readonly setExitCode?: (code: number) => void;/** Interactive secret input supplied by the concrete CLI shell; never echoed or logged. */@@ -98,11 +102,12 @@ export type PlanPreflight = {export type PlanProvider = {readonly request: string;readonly capability: string;- readonly status: "resolved" | "unresolved" | "ambiguous";+ readonly status: "resolved" | "unresolved" | "unsupported" | "ambiguous";readonly endpoint?: string;readonly use?: string;readonly pricing?: { readonly kind: "page"; readonly url: string } | { readonly kind: "local" };readonly endpoints?: readonly string[];+ readonly rejections?: readonly { readonly endpoint: string; readonly message: string }[];readonly binding?: string;};@@ -119,6 +124,7 @@ export type PlanOutput = {readonly providerRequestCount?: number;readonly localRequestCount?: number;readonly unresolvedRequestCount?: number;+ readonly unsupportedRequestCount?: number;readonly choiceCount: number;readonly choices: readonly { readonly output: string; readonly candidate: string }[];readonly omittedChoices?: number;@@ -133,6 +139,26 @@ export type PlanOutput = {readonly preflight?: PlanPreflight;};+export type PricingEntry = PlanProvider & {+ readonly pricingDocuments?: readonly PricingDocument[];+ readonly pricingError?: string;+};++export type PricingDocument = {+ readonly source: string;+ readonly data: CanonicalValue;+};++export type PricingOutput = {+ readonly format: "hypit.cli-pricing@1";+ readonly run: string;+ readonly requestCount: number;+ readonly pricing: readonly PricingEntry[];+ readonly omittedPricing?: number;+ readonly needs: readonly PlanNeed[];+ readonly omittedNeeds?: number;+};+export type PlanNeed = {readonly request: string;readonly step: string;@@ -171,6 +197,10 @@ export type CliPresentation =readonly kind: "plan";readonly machine: PlanOutput;}+ | {+ readonly kind: "pricing";+ readonly machine: PricingOutput;+ }| {readonly kind: "operational";readonly machine: CliMachineView;@@ -416,10 +446,19 @@ function providerGroupKey(provider: PlanProvider): string {use: provider.use,pricing: provider.pricing,endpoints: provider.endpoints,+ rejections: provider.rejections,binding: provider.binding,});}+function providerRejectionText(provider: PlanProvider, verbose: boolean): string {+ const rejections = provider.rejections ?? [];+ if (rejections.length === 0) return "no configured Endpoint accepts this request";+ const shown = verbose ? rejections : rejections.slice(0, 1);+ return shown.map((rejection) => `${rejection.endpoint}: ${rejection.message}`).join("; ")+ + (shown.length === rejections.length ? "" : ` · ${rejections.length - shown.length} more Endpoint rejection${rejections.length - shown.length === 1 ? "" : "s"}`);+}+function renderPlan(view: Extract<CliPresentation, { kind: "plan" }>,io: CliIo,@@ -439,8 +478,9 @@ function renderPlan(["Targets", targetSummary],["Requests", String(view.machine.requestCount)],...(view.machine.requestIssueCount === 0 ? [] : [["Request issues", String(view.machine.requestIssueCount)] as const]),- ...(view.machine.providerRequestCount === undefined ? [] : [["Provider requests", String(view.machine.providerRequestCount)] as const]),- ...(view.machine.localRequestCount === undefined ? [] : [["Local requests", String(view.machine.localRequestCount)] as const]),+ ...((view.machine.providerRequestCount ?? 0) === 0 ? [] : [["Provider requests", String(view.machine.providerRequestCount)] as const]),+ ...((view.machine.localRequestCount ?? 0) === 0 ? [] : [["Local requests", String(view.machine.localRequestCount)] as const]),+ ...((view.machine.unsupportedRequestCount ?? 0) === 0 ? [] : [["Unsupported", String(view.machine.unsupportedRequestCount)] as const]),...((view.machine.unresolvedRequestCount ?? 0) === 0 ? [] : [["Unresolved", String(view.machine.unresolvedRequestCount)] as const]),...(view.machine.preflight === undefined ? [] : [["Preflight", view.machine.preflight.ok ? "ready" : "needs attention",@@ -464,6 +504,8 @@ function renderPlan(? `${item.endpoint ?? ""} ${colors.dim(`(${item.use ?? "?"})${item.binding === undefined ? "" : ", bound in the Profile"}`)}`: item.status === "ambiguous"? colors.warning(`${(item.endpoints ?? []).join(", ")} all offer it; add "bindings": { "${item.capability}": "<instance>" } to the Profile`)+ : item.status === "unsupported"+ ? colors.error(providerRejectionText(item, verbose)): item.binding === undefined? colors.error("no selected Endpoint accepts this request"): colors.error(`bound to ${item.binding}, which does not offer it`);@@ -537,6 +579,82 @@ function renderPlan(return `${lines.join("\n")}\n`;}+function pricingDocumentLines(document: PricingDocument, colors: Palette, verbose: boolean): string[] {+ if (!verbose) {+ return [` ${colors.dim("Pricing data")} ${document.source} ${colors.dim("· use --json or --verbose for the Provider document")}`];+ }+ const rendered = JSON.stringify(document.data, undefined, 2);+ return [+ ` ${colors.dim("Source")} ${document.source}`,+ ...rendered.split("\n").map((line) => ` ${line}`),+ ];+}++function renderPricing(+ view: Extract<CliPresentation, { kind: "pricing" }>,+ io: CliIo,+ colors: Palette,+ verbose: boolean,+): string {+ const machine = view.machine;+ const lines = [heading("info", "Provider pricing information", io, colors), ""];+ lines.push(...facts([+ ["Run", shortPath(machine.run)],+ ["Requests", String(machine.requestCount)],+ ], colors));+ if (machine.pricing.length > 0) lines.push("", colors.strong("Requests and pricing sources"));+ const groups = new Map<string, PricingEntry[]>();+ for (const item of machine.pricing) {+ const key = JSON.stringify({+ capability: item.capability,+ status: item.status,+ endpoint: item.endpoint,+ use: item.use,+ pricing: item.pricing,+ endpoints: item.endpoints,+ rejections: item.rejections,+ binding: item.binding,+ pricingDocuments: item.pricingDocuments,+ pricingError: item.pricingError,+ });+ groups.set(key, [...(groups.get(key) ?? []), item]);+ }+ for (const group of groups.values()) {+ const item = group[0]!;+ const selected = item.status === "resolved"+ ? `${item.endpoint ?? ""} ${colors.dim(`(${item.use ?? "?"})`)}`+ : item.status === "ambiguous"+ ? colors.error(`several Endpoints: ${(item.endpoints ?? []).join(", ")}`)+ : item.status === "unsupported"+ ? colors.error(providerRejectionText(item, verbose))+ : colors.error("no selected Endpoint accepts this request");+ lines.push(` ${colors.accent(verbose ? item.capability : capabilityLabel(item.capability))}`);+ lines.push(` ${selected}${group.length === 1 ? "" : ` each ×${group.length}`}`);+ if (item.pricing?.kind === "local") {+ lines.push(` ${colors.dim("local, no Provider charge")}`);+ }+ for (const document of item.pricingDocuments ?? []) {+ lines.push(...pricingDocumentLines(document, colors, verbose));+ }+ if (item.pricingError !== undefined) {+ lines.push(` ${colors.warning(`Could not read Provider pricing: ${item.pricingError}`)}`);+ }+ if ((item.pricingDocuments?.length ?? 0) === 0 && item.pricing?.kind === "page") {+ lines.push(` ${colors.dim("Pricing page")} ${item.pricing.url}`);+ } else if ((item.pricingDocuments?.length ?? 0) === 0 && item.pricing === undefined+ && item.status === "resolved" && item.pricingError === undefined) {+ lines.push(` ${colors.dim("No pricing source declared by this Provider")}`);+ }+ const requests = new Set(group.map((entry) => entry.request));+ const needs = machine.needs.filter((need) => requests.has(need.request));+ lines.push(...groupedNeedLines(needs, colors, verbose));+ }+ if ((machine.omittedPricing ?? 0) > 0) {+ lines.push(` ${colors.dim(`${machine.omittedPricing} more requests · use --limit <count>`)}`);+ }+ return `${lines.join("\n")}\n`;+}+function renderOperational(view: Extract<CliPresentation, { kind: "operational" }>,io: CliIo,@@ -566,7 +684,9 @@ export function writeCliOutput(? renderRunCheck(presentation, io, colors, options.verbose): presentation.kind === "plan"? renderPlan(presentation, io, colors, options.verbose)- : renderOperational(presentation, io, colors);+ : presentation.kind === "pricing"+ ? renderPricing(presentation, io, colors, options.verbose)+ : renderOperational(presentation, io, colors);io.write(output);}@@ -604,6 +724,16 @@ function commandHelp(topic: string, colors: Palette): readonly string[] | undefi"and price page behind each external request.","Planning never starts external work.",],+ pricing: [+ colors.accent(colors.strong("hypit pricing")),+ colors.dim("Read current pricing material from the selected Providers for the requests in one Run."),+ "",+ " hypit pricing <run-source> [--runtime <profile>] [--workspace <workspace>] [--asset-root <directory>]",+ "",+ "Pricing is an explicit read-only network operation. It starts no Build and submits no generation.",+ "The command shows each Need beside its Provider source; use --json or --verbose for the raw document.",+ "Hypit calculates no total.",+ ],build: [colors.accent(colors.strong("hypit build")),colors.dim("Submit one durable Build and ensure its selected Runtime Worker is available."),@@ -744,6 +874,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {colors.strong("Authoring"),row("check <source>", "verify one self-described Author or Run source"),row("plan <run-source>", "show selected work without executing"),+ row("pricing <run-source>", "read selected Providers' current pricing material"),row("build <run-source>", "submit a Build; --follow observes it"),"",colors.strong("Results"),diff --git a/packages/cli/test/oauth.test.ts b/packages/cli/test/oauth.test.tsnew file mode 100644index 00000000..2675594b--- /dev/null+++ b/packages/cli/test/oauth.test.ts@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { once } from "node:events";+import { createConnection } from "node:net";+import test from "node:test";++import { decodeOAuth2Credential } from "@hypit/runtime";++import { acquireOAuthCredential } from "../src/oauth.js";++const acquisition = {+ kind: "oauth2-pkce" as const,+ authorizationEndpoint: "https://identity.example.test/authorize",+ tokenEndpoint: "https://identity.example.test/token",+ clientId: "client",+ scopes: ["work"],+ requestTimeoutMs: 1_000,+};++function returnAuthorization(url: string, page: (html: string) => void): void {+ const authorization = new URL(url);+ const redirect = new URL(authorization.searchParams.get("redirect_uri")!);+ redirect.searchParams.set("state", authorization.searchParams.get("state")!);+ redirect.searchParams.set("code", "authorization-code");+ void globalThis.fetch(redirect).then(async (response) => {+ assert.equal(response.status, 200);+ page(await response.text());+ });+}++test("OAuth callback reports authorization while the CLI finishes the credential", async () => {+ let resolveCallback!: (html: string) => void;+ const callbackPage = new Promise<string>((resolve) => { resolveCallback = resolve; });+ const progress: string[] = [];+ const raw = await acquireOAuthCredential(acquisition, {+ onProgress: (message) => progress.push(message),+ open: (url) => returnAuthorization(url, resolveCallback),+ fetch: async (input, init) => {+ assert.equal(String(input), acquisition.tokenEndpoint);+ assert.equal(init?.signal?.aborted, false);+ return Response.json({ access_token: "access", refresh_token: "refresh", expires_in: 60 });+ },+ });++ const credential = decodeOAuth2Credential(raw);+ const callbackHtml = await callbackPage;+ assert.equal(credential?.accessToken, "access");+ assert.match(callbackHtml, /Authorization received/u);+ assert.doesNotMatch(callbackHtml, /credential is ready|signed in to Hypit/iu);+ assert.deepEqual(progress.slice(1), [+ "Authorization returned. Exchanging token…",+ "Token received. Saving credential…",+ ]);+});++test("OAuth callback releases another browser connection after sending its page", async () => {+ let browserConnection: ReturnType<typeof createConnection> | undefined;+ const raw = await acquireOAuthCredential(acquisition, {+ open: (url) => {+ const authorization = new URL(url);+ const redirect = new URL(authorization.searchParams.get("redirect_uri")!);+ browserConnection = createConnection({ host: redirect.hostname, port: Number(redirect.port) });+ void once(browserConnection, "connect").then(() => {+ browserConnection!.write(`GET /favicon.ico HTTP/1.1\r\nHost: ${redirect.host}\r\n`);+ returnAuthorization(url, () => {});+ });+ },+ fetch: async () => Response.json({ access_token: "access" }),+ });++ assert.equal(decodeOAuth2Credential(raw)?.accessToken, "access");+ assert.ok(browserConnection);+ if (!browserConnection.destroyed) {+ await once(browserConnection, "close", { signal: AbortSignal.timeout(1_000) });+ }+});++test("OAuth token exchange uses the Endpoint-declared request timeout", async () => {+ await assert.rejects(+ async () => await acquireOAuthCredential({ ...acquisition, requestTimeoutMs: 20 }, {+ open: (url) => returnAuthorization(url, () => {}),+ fetch: async (_input, init) => await new Promise<Response>((_resolve, reject) => {+ const signal = init?.signal;+ if (signal?.aborted === true) {+ reject(signal.reason);+ return;+ }+ signal?.addEventListener("abort", () => reject(signal.reason), { once: true });+ }),+ }),+ /token exchange timed out after 20 ms.*no credential was stored/u,+ );+});diff --git a/packages/cli/test/output.test.ts b/packages/cli/test/output.test.tsindex 5d928a36..e4b1b5aa 100644--- a/packages/cli/test/output.test.ts+++ b/packages/cli/test/output.test.ts@@ -106,7 +106,7 @@ test("plan names the Provider and price page behind each request, and points atassert.match(without, /Pass --runtime <profile>/u);assert.doesNotMatch(without, /Providers and price pages/u);- const output = capture(human, { kind: "plan", machine: { ...base, providerRequestCount: 2, localRequestCount: 1, unresolvedRequestCount: 1, providers: [+ const output = capture(human, { kind: "plan", machine: { ...base, providerRequestCount: 2, localRequestCount: 1, unresolvedRequestCount: 0, unsupportedRequestCount: 1, providers: [{request: "seedance:one",capability: "@hypit/seedance@1#seedance-2-mini",@@ -117,7 +117,17 @@ test("plan names the Provider and price page behind each request, and points at},{ request: "media:one", capability: "@hypit/media@1#inspect", status: "resolved", endpoint: "media.local", use: "@hypit/provider-media-local", pricing: { kind: "local" } },{ request: "whisper:one", capability: "@hypit/whisperx@1#whisperx-alignment", status: "resolved", endpoint: "whisperx.remote", use: "@hypit/provider-example" },- { request: "image:one", capability: "@hypit/gpt-image@1#gpt-image-2", status: "unresolved" },+ {+ request: "image:one",+ capability: "@hypit/gpt-image@1#gpt-image-2",+ status: "unsupported",+ endpoint: "hypihub.default",+ use: "@hypit/provider-hypihub",+ rejections: [{+ endpoint: "hypihub.default",+ message: "transparent background is available only at 1K; requested 2K",+ }],+ },], needs: [{request: "seedance:one",step: "video::component::presenter.generate",@@ -130,7 +140,8 @@ test("plan names the Provider and price page behind each request, and points atassert.match(output, /@hypit\/seedance#seedance-2-mini\n\s+hypihub\.default \(@hypit\/provider-hypihub\)\s+·\s+https:\/\/hypit\.ai\/commercial\/pricing\//u);assert.match(output, /media\.local .*·\s+local, no Provider charge/u);assert.match(output, /whisperx\.remote .*·\s+price source unknown/u);- assert.match(output, /gpt-image#gpt-image-2\n\s+no selected Endpoint accepts this request\n/u);+ assert.match(output, /Unsupported\s+1/u);+ assert.match(output, /gpt-image#gpt-image-2\n\s+hypihub\.default: transparent background is available only at 1K; requested 2K\n/u);assert.match(output, /prompt 42 chars · duration 10 · resolution 720p · 1 image reference · input produced during Build/u);assert.doesNotMatch(output, /Pass --runtime/u);assert.doesNotMatch(output, /seedance@1#/u);@@ -141,6 +152,45 @@ test("plan names the Provider and price page behind each request, and points atassert.match(verbose, /@hypit\/seedance@1#seedance-2-mini\n\s+hypihub\.default, kie\.default all offer it/u);});+test("pricing presents Provider-owned material beside the corresponding Needs", () => {+ const presentation = { kind: "pricing", machine: {+ format: "hypit.cli-pricing@1",+ run: "/project/build.svrun",+ requestCount: 2,+ pricing: [{+ request: "seedance:one", capability: "@hypit/seedance@1#seedance-2", status: "resolved",+ endpoint: "hypihub.default", use: "@hypit/provider-hypihub",+ pricing: { kind: "page", url: "https://hypit.ai/commercial/pricing/" },+ pricingDocuments: [{+ source: "https://hypit.ai/v1/pricing?model=bytedance%2Fseedance-2",+ data: { model: "bytedance/seedance-2", pricing: { mode: "per_second", per_second_usd: 0.1045 } },+ }],+ }, {+ request: "image:one", capability: "@hypit/gpt-image@1#gpt-image-2", status: "resolved",+ endpoint: "kie.default", use: "@hypit/provider-kie",+ pricing: { kind: "page", url: "https://kie.ai/pricing" },+ }],+ needs: [{+ request: "seedance:one", step: "video::component::presenter.generate", port: "generation",+ capability: "@hypit/seedance@1#seedance-2", endpoint: "hypihub.default",+ summary: { fields: { duration: 5, resolution: "720p" }, references: {} }, pending: [],+ }, {+ request: "image:one", step: "video::component::portrait.generate", port: "generation",+ capability: "@hypit/gpt-image@1#gpt-image-2", endpoint: "kie.default", pending: [],+ }],+ } } as const;+ const output = capture(human, presentation);+ assert.match(output, /Provider pricing information/u);+ assert.match(output, /https:\/\/hypit\.ai\/v1\/pricing\?model=bytedance%2Fseedance-2/u);+ assert.match(output, /use --json or --verbose for the Provider document/u);+ assert.doesNotMatch(output, /"per_second_usd": 0\.1045/u);+ assert.match(output, /duration 5 · resolution 720p/u);+ assert.match(output, /Pricing page\s+https:\/\/kie\.ai\/pricing/u);++ const verbose = capture({ ...human, verbose: true }, presentation);+ assert.match(verbose, /"per_second_usd": 0\.1045/u);+});+test("run check treats historical reuse as a normal summary", () => {const output = capture(human, {kind: "check-run",diff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.tsindex c9191f08..08709e8d 100644--- a/packages/driver-node/src/driver.ts+++ b/packages/driver-node/src/driver.ts@@ -203,6 +203,17 @@ export class NodeDriver {},};}+ if (resolution.status === "unsupported") {+ return {+ blocked: {+ command: command.id,+ reason: "unsupported-endpoint-request",+ subject: resolution.rejections+ .map((rejection) => `${rejection.endpointId}: ${rejection.reason}`)+ .join("; "),+ },+ };+ }if (resolution.status === "ambiguous") {return {blocked: {diff --git a/packages/driver-node/src/registry.ts b/packages/driver-node/src/registry.tsindex 038546c4..913261e2 100644--- a/packages/driver-node/src/registry.ts+++ b/packages/driver-node/src/registry.ts@@ -194,24 +194,41 @@ export class EndpointRegistry implements EndpointRegistrar {resolve(need: EndpointRequest): EndpointResolution {const key = endpointCapabilityKey(need.capability);- const registrations = (this.#registrationsByCapability.get(key) ?? []).filter((registration) =>- sameRef(registration.returns, need.returns)- && (registration.supports?.(need) ?? true));+ const registrations = (this.#registrationsByCapability.get(key) ?? [])+ .filter((registration) => sameRef(registration.returns, need.returns));const bound = this.#bindings.get(key);if (bound !== undefined) {const chosen = registrations.find((registration) => registration.id === bound);- // A binding names the Endpoint; an Endpoint that cannot serve this request is a missing one,- // reported with the id so the deployment sees which binding to revisit.- return chosen === undefined ? { status: "missing", endpointId: bound } : { status: "resolved", registration: chosen };+ if (chosen === undefined) return { status: "missing", endpointId: bound };+ const support = chosen.supports?.(need) ?? { status: "supported" };+ if (support.status === "unsupported") {+ if (!support.reason.trim()) throw new Error(`Endpoint ${chosen.id} returned an empty unsupported reason`);+ return { status: "unsupported", rejections: [{ endpointId: chosen.id, reason: support.reason }] };+ }+ return { status: "resolved", registration: chosen };}if (registrations.length === 0) return { status: "missing" };- if (registrations.length > 1) {+ const supported: EndpointRegistration[] = [];+ const rejections: { endpointId: string; reason: string }[] = [];+ for (const registration of registrations) {+ const support = registration.supports?.(need) ?? { status: "supported" };+ if (support.status === "supported") {+ supported.push(registration);+ } else {+ if (!support.reason.trim()) throw new Error(`Endpoint ${registration.id} returned an empty unsupported reason`);+ rejections.push({ endpointId: registration.id, reason: support.reason });+ }+ }+ if (supported.length === 0) {+ return { status: "unsupported", rejections: rejections.sort((left, right) => left.endpointId.localeCompare(right.endpointId)) };+ }+ if (supported.length > 1) {return {status: "ambiguous",- endpointIds: [...new Set(registrations.map((registration) => registration.id))].sort(),+ endpointIds: [...new Set(supported.map((registration) => registration.id))].sort(),};}- return { status: "resolved", registration: registrations[0]! };+ return { status: "resolved", registration: supported[0]! };}}diff --git a/packages/driver-node/src/types.ts b/packages/driver-node/src/types.tsindex 6a40e9e3..afd2dce8 100644--- a/packages/driver-node/src/types.ts+++ b/packages/driver-node/src/types.ts@@ -30,6 +30,7 @@ export type BlockedCommand = {readonly reason:| "missing-producer"| "missing-endpoint"+ | "unsupported-endpoint-request"| "ambiguous-endpoint"| "missing-operation-store";readonly subject: string;@@ -61,4 +62,8 @@ export type EndpointRegistration = EndpointRegistrationBase & (export type EndpointResolution =| { readonly status: "resolved"; readonly registration: EndpointRegistration }| { readonly status: "missing"; readonly endpointId?: string }+ | {+ readonly status: "unsupported";+ readonly rejections: readonly { readonly endpointId: string; readonly reason: string }[];+ }| { readonly status: "ambiguous"; readonly endpointIds: readonly string[] };diff --git a/packages/driver-node/test/driver.test.ts b/packages/driver-node/test/driver.test.tsindex c484b1c0..368da832 100644--- a/packages/driver-node/test/driver.test.ts+++ b/packages/driver-node/test/driver.test.ts@@ -183,13 +183,15 @@ test("Endpoint capabilities may narrow themselves with typed Need constraints",const { producers, endpoints } = configuredRegistry();endpoints.registerImmediateEndpoint("example:wrong-model", capabilities.generation, types.generated, () => {throw new Error("unsupported endpoint must never run");- }, { supports: () => false });+ }, { supports: () => ({ status: "unsupported", reason: "example request is unsupported" }) });endpoints.registerImmediateEndpoint("example:compatible", capabilities.generation, types.generated, () => ({value: { kind: "inline", value: "Compatible" },}), {supports: (need) => {const constraints = need.constraints as Readonly<Record<string, unknown>>;- return constraints.prompt === "Greet Ada";+ return constraints.prompt === "Greet Ada"+ ? { status: "supported" }+ : { status: "unsupported", reason: "prompt must be Greet Ada" };},});diff --git a/packages/endpoint-kit/README.md b/packages/endpoint-kit/README.mdindex f6868088..d7c1e79d 100644--- a/packages/endpoint-kit/README.md+++ b/packages/endpoint-kit/README.md@@ -68,7 +68,27 @@ session; capabilities that require durable quota shared with Builds stay Build-oEndpoint packages are selected by a Runtime Profile, never activated by author imports. This packagedepends on no Node filesystem, scheduler implementation or video domain.+An Endpoint may also expose `readPricing`. It receives the same complete `EndpointRequest` used for+support selection and resolves only that Endpoint's declared credentials when its source requires+them. The Provider returns current pricing documents together with their source URLs. Their data shape+belongs to the Provider: one service may return a model rate card, another a broader mixed catalogue,+and another may expose only its declared pricing page. Hypit preserves the material instead of+inventing a shared rate-table taxonomy, interpreting formulas, calculating totals, or turning pricing+information into spending authority.++Three facts remain separate at this boundary:++- the `EndpointRequest` describes the work selected by the Run;+- an `EndpointPricingDocument` describes prices published by that Provider;+- spending authority belongs to the user's decision about the described work and cost.++The caller can place the first two beside each other for an Agent to calculate and explain. Request+selection continues to follow the Runtime Profile and Endpoint support, while submission continues to+follow the user's authority.+`supports` receives one complete support description. For an executing Need, concrete graph valuesare already in `constraints`. During pre-Build planning, an upstream value that does not exist yet isrepresented by a semantic `pendingInputs` slot instead. A Provider may use the slot's input andmedia role to enforce support limits, but it never receives graph traversal rules or future bytes.+It returns either `supported`, or `unsupported` with the Provider's reason. Selection infrastructure+preserves that reason without interpreting request fields or maintaining a central limitation table.diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.tsindex 79b6fa06..8982414b 100644--- a/packages/endpoint-kit/src/index.ts+++ b/packages/endpoint-kit/src/index.ts@@ -7,6 +7,7 @@ import type {StoredValue,TypeRef,} from "@hypit/protocol";+import { canonicalize } from "@hypit/protocol";import type {ResourceStore,CredentialAcquisition,@@ -60,6 +61,31 @@ export type EndpointCredential = CredentialValue & {readonly replace?: (value: CredentialValue) => Promise<void>;};+/** Provider-owned pricing material read from one exact source. Its shape remains the Provider's. */+export type EndpointPricingDocument = {+ readonly source: string;+ readonly data: CanonicalValue;+};++export type EndpointPricingReaderContext = {+ readonly request: EndpointRequest;+ /** Resolve credentials only when this Provider's pricing source requires them. */+ readonly credentials: () => Promise<Readonly<Record<string, EndpointCredential>>>;+};++/** Read whatever current pricing material this Provider can usefully narrow for one request. */+export type EndpointPricingReader = (+ context: EndpointPricingReaderContext,+) => Awaitable<readonly EndpointPricingDocument[]>;++export function verifyEndpointPricingDocument(value: EndpointPricingDocument): void {+ let source: URL | undefined;+ try { source = new URL(value.source); } catch { source = undefined; }+ assert(source?.protocol === "https:" || source?.hostname === "localhost",+ "Endpoint pricing source must use HTTPS or localhost");+ canonicalize(value.data);+}+export type EndpointInvocationContext = {readonly command: FulfillNeedCommand;readonly need: Need;@@ -161,9 +187,14 @@ export function endpointResourceClaims(scheduling: EndpointScheduling, request:});}+/** A Provider's complete support decision for one concrete request. */+export type EndpointSupport =+ | { readonly status: "supported" }+ | { readonly status: "unsupported"; readonly reason: string };+export type EndpointRegistrationOptions = {readonly pool?: string;- readonly supports?: (request: EndpointRequest) => boolean;+ readonly supports?: (request: EndpointRequest) => EndpointSupport;readonly scheduling?: EndpointScheduling;readonly credentials?: Readonly<Record<string, CredentialRef>>;/**@@ -211,6 +242,8 @@ export type EndpointPackage = {/** Host-facing login material declared by this exact configured Endpoint instance. */readonly credentials: readonly EndpointCredentialDescription[];readonly pricing?: EndpointPricing;+ /** Optional live pricing-material reader owned by this Provider. */+ readonly readPricing?: EndpointPricingReader;install(registry: EndpointRegistrar): Awaitable<void>;};@@ -218,7 +251,7 @@ export type EndpointOffer = {readonly capability: CapabilityRef;readonly returns: TypeRef;readonly endpoint: string;- readonly supports?: (request: EndpointRequest) => boolean;+ readonly supports?: (request: EndpointRequest) => EndpointSupport;readonly transient?: true;};@@ -236,7 +269,7 @@ type EndpointCapabilityBase = {readonly unitsForRequest?: EndpointScheduling["unitsForRequest"];readonly capability: CapabilityRef;readonly returns: TypeRef;- readonly supports?: (request: EndpointRequest) => boolean;+ readonly supports?: (request: EndpointRequest) => EndpointSupport;/*** Also allow this capability in a disposable, non-Build authoring execution.* The Provider is asserting that it needs no durable or cross-Build capacity@@ -279,6 +312,8 @@ export type DefineEndpointPackageOptions = {readonly actionLimits?: EndpointActionLimits;/** The Provider's own price page, or `local` for work that runs on this machine without a charge. */readonly pricing?: EndpointPricing;+ /** Read current Provider-owned pricing material relevant to one request. */+ readonly readPricing?: EndpointPricingReader;readonly capabilities: readonly EndpointCapability[];};@@ -374,6 +409,7 @@ export function defineEndpointPackage(options: DefineEndpointPackageOptions): Enoffers,credentials: credentialDescriptions,...(options.pricing === undefined ? {} : { pricing: structuredClone(options.pricing) }),+ ...(options.readPricing === undefined ? {} : { readPricing: options.readPricing }),install(registry) {for (const capability of options.capabilities) {const capacity = capability.capacity ?? capability.capability.name;diff --git a/packages/generation/README.md b/packages/generation/README.mdindex 9d8b53e3..c689d672 100644--- a/packages/generation/README.md+++ b/packages/generation/README.md@@ -6,6 +6,9 @@ External Model and Provider packages import this public subpath from the `hypit`It gives both sides the same request and result vocabulary without a dependency between theirimplementations. `sealGenerationPortTable` describes a model's inputs; `GenerationWireMapping` and`compileWireRequest` can translate those inputs to one Provider's documented wire fields.+`selectWireModelForRequest` applies the same route selection without resolving media bytes. During+planning, a Provider may add the model-port names already attached as future graph inputs; the+selector does not inspect graph structure or interpret media roles.The package owns `GenerationRequest`, `GeneratedImageSet` and `GeneratedVideoSet` identities,schemas, validators and graph facets. Generated sets are atomic Products: a Provider persists thediff --git a/packages/generation/src/index.ts b/packages/generation/src/index.tsindex 456f3b21..18c59efa 100644--- a/packages/generation/src/index.ts+++ b/packages/generation/src/index.ts@@ -15,6 +15,7 @@ export {compileWireRequest,mappingSupportsRequest,selectWireModel,+ selectWireModelForRequest,} from "./mapping.js";export type {GenerationArtifactUrlResolver,diff --git a/packages/generation/src/mapping.ts b/packages/generation/src/mapping.tsindex c7d98f66..38d28a9d 100644--- a/packages/generation/src/mapping.ts+++ b/packages/generation/src/mapping.ts@@ -72,6 +72,29 @@ export function selectWireModel(mapping: GenerationWireMapping, present: Readonlthrow new Error(`${mapping.capability.name} has no route for ports ${[...present].sort().join(", ")}`);}+/**+ * Select one service model from the authored request shape.+ *+ * During planning, `pendingPorts` names graph inputs the model package has+ * already attached even though their Resource bytes do not exist yet. They are+ * ordinary model port names, not graph traversal instructions.+ */+export function selectWireModelForRequest(+ mapping: GenerationWireMapping,+ request: GenerationRequest,+ pendingPorts: readonly string[] = [],+): string {+ assert(mappingSupportsRequest(mapping, request),+ `${mapping.capability.name} request contains a port this Provider cannot map`);+ const present = new Set(presentPorts(request));+ for (const port of pendingPorts) {+ assert(mapping.fields[port] !== undefined,+ `${mapping.capability.name} request contains future port ${port} this Provider cannot map`);+ present.add(port);+ }+ return selectWireModel(mapping, present);+}+async function urlsOf(values: readonly GenerationMediaValue[],resolve: GenerationArtifactUrlResolver,@@ -88,9 +111,7 @@ export async function compileWireRequest(request: GenerationRequest,resolve: GenerationArtifactUrlResolver,): Promise<GenerationWireRequest> {- assert(mappingSupportsRequest(mapping, request),- `${mapping.capability.name} request contains a port this Provider cannot map`);- const present = presentPorts(request);+ const model = selectWireModelForRequest(mapping, request);const input: Record<string, CanonicalValue> = { ...(mapping.constants ?? {}) };for (const [port, field] of Object.entries(mapping.fields)) {@@ -120,7 +141,7 @@ export async function compileWireRequest(}}- return { model: selectWireModel(mapping, present), input: canonicalize(input) };+ return { model, input: canonicalize(input) };}/** Does this request only use ports this mapping can write? Needs no model package. */diff --git a/packages/generation/test/ports.test.ts b/packages/generation/test/ports.test.tsindex 10aa06e2..fb0f87f4 100644--- a/packages/generation/test/ports.test.ts+++ b/packages/generation/test/ports.test.ts@@ -13,6 +13,7 @@ import {sealGenerationRequestDraft,sealGenerationPortTable,selectWireModel,+ selectWireModelForRequest,verifyRequestAgainstPorts,} from "@hypit/generation";import type { GenerationPortTable, GenerationWireMapping } from "@hypit/generation";@@ -173,6 +174,10 @@ test("one mapping compiles every port shape and routes by port presence", asyncconst textOnly = sealGenerationPortRequest(table, { prompt: ["hi"], duration: [8], resolution: ["720p"] });assert.equal(selectWireModel(mapping, new Set(Object.keys(textOnly.ports))), "demo/text-to-video");+ assert.equal(+ selectWireModelForRequest(mapping, textOnly, ["referenceImage"]),+ "demo/reference-to-video",+ );const framed = sealGenerationPortRequest(table, {prompt: ["hi"],duration: [8],diff --git a/packages/gpt-image/README.md b/packages/gpt-image/README.mdindex a27f42bb..b2e0d7f4 100644--- a/packages/gpt-image/README.md+++ b/packages/gpt-image/README.md@@ -39,6 +39,12 @@ module changes the visible graph expansion rather than the document structure:</gpt:Image>```+Set the optional `background` attribute to `transparent` when the generated image should carry+alpha, `opaque` when every output pixel should be opaque, or `auto` when the model should choose.+Omitting it leaves that choice to the model and selected Provider. Provider-specific combinations,+including which resolution tiers accept an explicit background choice, are reported by that+Provider before generation.+`prompt` is an ordinary `Text` graph edge. Every `Reference` is an ordinary image Artifact edge;the Surface does not copy runtime media into request metadata. The raw module expands to requestassembly, generation and primary-image selection. The clean module then adds the officialdiff --git a/packages/gpt-image/src/index.ts b/packages/gpt-image/src/index.tsindex 69b4048f..0519d28b 100644--- a/packages/gpt-image/src/index.ts+++ b/packages/gpt-image/src/index.ts@@ -21,12 +21,21 @@ export const gptImage2Ports: GenerationPortTable = sealGenerationPortTable({name: "aspectRatio",value: {kind: "enum",- values: ["auto", "1:1", "3:2", "2:3", "4:3", "3:4", "5:4", "4:5", "16:9", "9:16", "21:9"],+ values: [+ "auto", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16",+ "2:1", "1:2", "3:1", "1:3", "21:9", "9:21", "5:4", "4:5",+ ],},minItems: 1,maxItems: 1,},{ name: "resolution", value: { kind: "enum", values: ["1K", "2K", "4K"] }, minItems: 1, maxItems: 1 },+ {+ name: "background",+ value: { kind: "enum", values: ["transparent", "opaque", "auto"] },+ minItems: 0,+ maxItems: 1,+ },{ name: "images", value: { kind: "media", accepts: ["image"] }, minItems: 0, maxItems: 16 },],requires: [],@@ -76,15 +85,25 @@ const gptImageAttributes: readonly SurfaceAttributeVocabulary[] = [kind: "literal",required: true,summary: "The shape of the generated picture.",- values: ["auto", "1:1", "3:2", "2:3", "4:3", "3:4", "5:4", "4:5", "16:9", "9:16", "21:9"],+ values: [+ "auto", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16",+ "2:1", "1:2", "3:1", "1:3", "21:9", "9:21", "5:4", "4:5",+ ],},{name: "resolution",kind: "literal",required: true,- summary: "The size band the model renders at.",+ summary: "The model's output resolution tier.",values: ["1K", "2K", "4K"],},+ {+ name: "background",+ kind: "literal",+ required: false,+ summary: "Requests transparent pixels or a fully opaque generated picture.",+ values: ["transparent", "opaque", "auto"],+ },];const gptImageChildren: readonly SurfaceChildVocabulary[] = [diff --git a/packages/gpt-image/src/surface.ts b/packages/gpt-image/src/surface.tsindex 4c3ae50e..f13fbfe6 100644--- a/packages/gpt-image/src/surface.ts+++ b/packages/gpt-image/src/surface.ts@@ -115,7 +115,7 @@ function references(function decode(clean: boolean): StructuredSurfaceHandler {return ({ element, resolveReference }) => {- exactAttributes(element, ["id", "prompt", "aspect-ratio", "resolution"],+ exactAttributes(element, ["id", "prompt", "aspect-ratio", "resolution", "background"],["id", "prompt", "aspect-ratio", "resolution"]);const id = textAttribute(element, "id");const promptSource = prompt(element, resolveReference);@@ -123,9 +123,13 @@ function decode(clean: boolean): StructuredSurfaceHandler {const endpoint = gptImageEndpoints.image!;const imagePort = generationPort(gptImage2Ports, "images");assert(imagePort.value.kind === "media", "GPT Image images port is not media");+ const background = element.attributes.background === undefined+ ? undefined+ : textAttribute(element, "background");const draft = sealGptImage2Draft({aspectRatio: [textAttribute(element, "aspect-ratio")],resolution: [textAttribute(element, "resolution")],+ ...(background === undefined ? {} : { background: [background] }),});const records: Array<{readonly id: string;diff --git a/packages/gpt-image/test/surface.test.ts b/packages/gpt-image/test/surface.test.tsindex 79db6be4..6015897e 100644--- a/packages/gpt-image/test/surface.test.ts+++ b/packages/gpt-image/test/surface.test.ts@@ -34,7 +34,7 @@ async function decode(source: string, handler: StructuredSurfaceHandler) {});}-const authored = `<gpt:Image id="holding" prompt={prompt} aspect-ratio="21:9" resolution="2K">+const authored = `<gpt:Image id="holding" prompt={prompt} aspect-ratio="9:21" resolution="2K" background="auto"><gpt:Reference image={person.image}/><gpt:Reference image={product.image}/></gpt:Image>`;@@ -52,6 +52,13 @@ test("raw GPT Image Surface keeps Text and every reference image on explicit grakind: "component-output", component: "product", output: "image",});assert.deepEqual(component.outputs, { image: "holding.image" });+ const draft = result.records.find((record) => record.id === "holding.draft");+ assert.equal(draft?.value.kind, "inline");+ assert.deepEqual((draft?.value.value as { ports?: unknown }).ports, {+ aspectRatio: ["9:21"],+ resolution: ["2K"],+ background: ["auto"],+ });assert.equal(result.records.filter((record) => record.id.endsWith(".binding")).length, 2);assert.equal(result.records.some((record) => record.id.endsWith(".cleanup")), false);assert.deepEqual(result.fragments[0]?.operations.map((operation) => operation.id), [diff --git a/packages/provider-hyperframes-aws-lambda/src/provider.ts b/packages/provider-hyperframes-aws-lambda/src/provider.tsindex e6510f38..c5b878ae 100644--- a/packages/provider-hyperframes-aws-lambda/src/provider.ts+++ b/packages/provider-hyperframes-aws-lambda/src/provider.ts@@ -120,17 +120,23 @@ function requestDocument(value: CanonicalValue): HyperframesDocument {return request.document as HyperframesDocument;}-export function supportsAwsLambdaHyperframes(value: CanonicalValue): boolean {+function awsLambdaHyperframesRejection(value: CanonicalValue): string | undefined {try {const document = requestDocument(value);- return document.surfaces.length === 0- && document.frameRate.denominator === 1- && SUPPORTED_FPS.has(document.frameRate.numerator);- } catch {- return false;+ if (document.surfaces.length > 0) return "AWS Lambda HyperFrames does not accept embedded Surfaces";+ if (document.frameRate.denominator !== 1 || !SUPPORTED_FPS.has(document.frameRate.numerator)) {+ return "AWS Lambda HyperFrames accepts integer 24, 30 or 60 fps";+ }+ return undefined;+ } catch (error) {+ return error instanceof Error ? error.message : String(error);}}+export function supportsAwsLambdaHyperframes(value: CanonicalValue): boolean {+ return awsLambdaHyperframesRejection(value) === undefined;+}+function implementationFailure(code: string, error: unknown): EndpointOutcome {return {status: "failed",@@ -506,7 +512,10 @@ export function createAwsLambdaHyperframesProvider(config: CreateAwsLambdaHyperflifecycle: "asynchronous" as const,capability: renderHyperframesCapabilities.renderVisual,returns: mediaTypes.renderedVisual,- supports: (need) => supportsAwsLambdaHyperframes(need.constraints),+ supports: (need) => {+ const reason = awsLambdaHyperframesRejection(need.constraints);+ return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };+ },endpoint,}],});diff --git a/packages/provider-hypihub/README.md b/packages/provider-hypihub/README.mdindex 865ae6d4..649bc259 100644--- a/packages/provider-hypihub/README.md+++ b/packages/provider-hypihub/README.md@@ -12,6 +12,18 @@ admits them into the current Build's working byte area. Image references use Hypfor one video). First/last-frame images use `first_frame` and `last_frame`. It alsoexports a small Gemini-native VLM generator for callers that previously used Vertex.+The current HypiHub GPT Image 2 route exposes the same request surface as its KIE upstream:++| Resolution | Ratios unavailable at this Endpoint | `background` |+| --- | --- | --- |+| `1K` | none | optional |+| `2K` | `5:4`, `4:5`, `3:1`, `1:3`, `9:21` | omit |+| `4K` | `3:1`, `1:3`, `9:21` | omit |++HypiHub owns this support check independently: it neither imports the KIE Provider nor narrows the+GPT Image model package. When the service surface changes, this Provider can change without changing+the model or another Provider.+For moving portraits, [Volcengine Matting](../volcengine-matting/README.md) maps`@hypit/volcengine-matting@1#matte-portrait-video` to `POST /v1/videos` with`model: "matte-portrait-video"`, `ref_video_url` and `format` (`WEBM` by default, or `MOV`).@@ -58,6 +70,9 @@ Resource identity is uploaded once within one Runtime operation. Hypit keeps nocross-Build cache. Embedded callers may replace this transport with `publicAssetUrl`.OAuth login stores the access token, refresh token and expiry as one opaque credential value. The+browser callback only confirms that authorization returned to the CLI; the CLI reports success after+the bounded token exchange and Credential Store write complete. `oauthRequestTimeoutMs` controls that+exchange and defaults to 30 seconds, independently of the longer inference request timeout. TheProvider refreshes that value shortly before expiry or after an unauthorised response when theselected Store is writable. Its Endpoint receives only the credential slot it declared and a narrowoperation for replacing that same slot; it cannot enumerate the Store, choose another key or read@@ -71,9 +86,11 @@ from surfaced upload errors.The default remote alignment model is `victor-upmeet/whisperx`; `transcriptionModel` may select anotherHypiHub model that exposes the `transcriptions` route. `hypit doctor` reads the authenticated modelcatalog to verify configured capabilities; ordinary preflight never makes that request. The package-declares HypiHub's public pricing page, `https://hypit.ai/commercial/pricing/`, as its price source;-`hypit plan --runtime <profile>` prints it beside each request this Endpoint would serve. Per-model-credit costs are never copied into Hypit.+declares HypiHub's public pricing page, `https://hypit.ai/commercial/pricing/`, as its price source.+For each selected Need, `readPricing` resolves the corresponding HypiHub model and returns the service's+authenticated `GET /v1/pricing?model=<model>` response unchanged together with that URL. It covers+generation, visual observation, alignment, Voice Design, and Voice Clone through the same mechanism;+the Provider does not maintain a second list of billing formulas or calculate a request total.HypiHub declares MiMo Voice Design and Voice Clone together with every other capability it serves; itnever hides one. Voice Design produces an accepted voice-reference Resource, and Voice Clone uses@@ -81,11 +98,21 @@ that reference to produce independent speech. Hypit does not expose MiMo presetselected Endpoint offers the same capability (a local WhisperX, a Vertex Gemini, or the official MiMoProvider), the Runtime Profile's `bindings` say which Endpoint serves it.-Execution policy remains local to this Provider. A profile may set `requestTimeoutMs`,-`operationTimeoutMs`, `uploadPartTimeoutMs`, `uploadPartAttempts`, `downloadAttempts`,-`geminiRateLimitAttempts` and `geminiRateLimitRetryDelayMs`; defaults are respectively 300 seconds,-20 minutes, 5 minutes, 3 attempts, 3 attempts, 4 attempts and 2 seconds. `defaultConcurrency`-controls the total shared capacity of this Profile's HypiHub pool. Optional `capabilityConcurrency`+Execution policy remains local to this Provider:++| Profile field | Default | What it controls |+| --- | ---: | --- |+| `requestTimeoutMs` | 300 seconds | ordinary Provider HTTP requests |+| `oauthRequestTimeoutMs` | 30 seconds | OAuth token exchange and refresh |+| `pricingRequestTimeoutMs` | 30 seconds | authenticated pricing requests |+| `operationTimeoutMs` | 20 minutes | one remote asynchronous operation |+| `uploadPartTimeoutMs` | 5 minutes | one upload part |+| `uploadPartAttempts` | 3 | attempts for one upload part |+| `downloadAttempts` | 3 | attempts to collect one result |+| `geminiRateLimitAttempts` | 4 | Gemini attempts after rate limits |+| `geminiRateLimitRetryDelayMs` | 2 seconds | delay between those attempts |++`defaultConcurrency` controls the total shared capacity of this Profile's HypiHub pool. Optional `capabilityConcurrency`sets narrower group limits, for example `{ "seedance-2-mini": 2, "gemini": 3, "transcription": 1 }`.Image/video/speech groups use the exact capability name; all Gemini capabilities share `gemini`, andWhisperX uses `transcription`. These limits coordinate this Runtime's requests; HypiHub remainsdiff --git a/packages/provider-hypihub/src/activation.ts b/packages/provider-hypihub/src/activation.tsindex 9e832921..8a0fdb4e 100644--- a/packages/provider-hypihub/src/activation.ts+++ b/packages/provider-hypihub/src/activation.ts@@ -23,6 +23,8 @@ const adapter = createRuntimeEndpointAdapterFacet({"capabilityConcurrency","pollIntervalMs","requestTimeoutMs",+ "oauthRequestTimeoutMs",+ "pricingRequestTimeoutMs","operationTimeoutMs","uploadPartTimeoutMs","uploadPartAttempts",@@ -44,6 +46,8 @@ const adapter = createRuntimeEndpointAdapterFacet({const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "HypiHub defaultConcurrency");const pollIntervalMs = runtimeConfigPositiveInteger(config.pollIntervalMs, "HypiHub pollIntervalMs");const requestTimeoutMs = runtimeConfigPositiveInteger(config.requestTimeoutMs, "HypiHub requestTimeoutMs");+ const oauthRequestTimeoutMs = runtimeConfigPositiveInteger(config.oauthRequestTimeoutMs, "HypiHub oauthRequestTimeoutMs");+ const pricingRequestTimeoutMs = runtimeConfigPositiveInteger(config.pricingRequestTimeoutMs, "HypiHub pricingRequestTimeoutMs");const operationTimeoutMs = runtimeConfigPositiveInteger(config.operationTimeoutMs, "HypiHub operationTimeoutMs");const uploadPartTimeoutMs = runtimeConfigPositiveInteger(config.uploadPartTimeoutMs, "HypiHub uploadPartTimeoutMs");const uploadPartAttempts = runtimeConfigPositiveInteger(config.uploadPartAttempts, "HypiHub uploadPartAttempts");@@ -65,6 +69,8 @@ const adapter = createRuntimeEndpointAdapterFacet({...(capabilityConcurrency === undefined ? {} : { capabilityConcurrency }),...(pollIntervalMs === undefined ? {} : { pollIntervalMs }),...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),+ ...(oauthRequestTimeoutMs === undefined ? {} : { oauthRequestTimeoutMs }),+ ...(pricingRequestTimeoutMs === undefined ? {} : { pricingRequestTimeoutMs }),...(operationTimeoutMs === undefined ? {} : { operationTimeoutMs }),...(uploadPartTimeoutMs === undefined ? {} : { uploadPartTimeoutMs }),...(uploadPartAttempts === undefined ? {} : { uploadPartAttempts }),diff --git a/packages/provider-hypihub/src/mapping.ts b/packages/provider-hypihub/src/mapping.tsindex 80c414ad..8a5b64e6 100644--- a/packages/provider-hypihub/src/mapping.ts+++ b/packages/provider-hypihub/src/mapping.ts@@ -48,9 +48,8 @@ export const hypiHubMappings: readonly GenerationWireMapping[] = [fields: {prompt: { as: "value", field: "prompt" },aspectRatio: { as: "value", field: "aspect_ratio" },- // `size` carries the 1K/2K/4K tier verbatim; the upstream reads it beside- // `aspect_ratio` to choose the pixel dimensions.- resolution: { as: "value", field: "size", whenAbsent: "1K" },+ resolution: { as: "value", field: "resolution", whenAbsent: "1K" },+ background: { as: "value", field: "background" },images: { as: "itemObject", field: "reference_images", urlKey: "url", fieldKeys: {} },},},@@ -59,7 +58,7 @@ export const hypiHubMappings: readonly GenerationWireMapping[] = [fields: {prompt: { as: "value" as const, field: "prompt" },aspectRatio: { as: "value" as const, field: "aspect_ratio" },- resolution: { as: "value" as const, field: "size", whenAbsent: "1024x1024" },+ resolution: { as: "value" as const, field: "resolution" },images: { as: "itemObject" as const, field: "reference_images", urlKey: "url", fieldKeys: {} },outputFormat: { as: "value" as const, field: "output_format" },},diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.tsindex b61d8449..c4973c32 100644--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@ -1,8 +1,10 @@import { requestDeadline } from "@hypit/runtime-kit";-import type { AsyncEndpoint, EndpointFulfillment, EndpointInvocationContext, EndpointPollContext, EndpointStartContext, EndpointOutcome, ImmediateEndpointHandler } from "@hypit/endpoint-kit";+import type { AsyncEndpoint, EndpointCredential, EndpointFulfillment, EndpointInvocationContext, EndpointPollContext, EndpointPricingReader, EndpointStartContext, EndpointOutcome, ImmediateEndpointHandler } from "@hypit/endpoint-kit";import { defineEndpointPackage, wakeAfter } from "@hypit/endpoint-kit";import { geminiCapabilities, geminiModels, geminiTypes, sealVisualObservation, verifyGeminiRequest } from "@hypit/gemini";import type { GeminiRequest } from "@hypit/gemini";+import { selectWireModelForRequest } from "@hypit/generation";+import type { GenerationRequest } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef } from "@hypit/protocol";import { credentialRef } from "@hypit/runtime";@@ -34,6 +36,8 @@ export type CreateHypiHubProviderOptions = {readonly capabilityConcurrency?: Readonly<Record<string, number>>;readonly pollIntervalMs?: number;readonly requestTimeoutMs?: number;+ readonly oauthRequestTimeoutMs?: number;+ readonly pricingRequestTimeoutMs?: number;readonly operationTimeoutMs?: number;readonly uploadPartTimeoutMs?: number;readonly uploadPartAttempts?: number;@@ -61,10 +65,10 @@ function apiBaseUrl(value: string): string {const origin = trimmed.replace(/\/(?:v1beta|v1)$/iu, "");return `${origin}/v1`;}-function credential(context: EndpointInvocationContext) {- const value = context.credentials.apiKey?.secret;+function credential(credentials: Readonly<Record<string, EndpointCredential>>) {+ const value = credentials.apiKey?.secret;assert(typeof value === "string" && value.length > 0, "HypiHub login is unavailable; run hypit auth login for HypiHub");- return context.credentials.apiKey!;+ return credentials.apiKey!;}function guidedMessage(error: unknown): string {const message = error instanceof Error ? error.message : String(error);@@ -230,13 +234,61 @@ class HypiHubClient {function authFor(context: EndpointInvocationContext, client: HypiHubClient): HypiHubAuth {return createHypiHubAuth({- credential: credential(context),+ credential: credential(context.credentials),baseUrl: client.baseUrl,requestTimeoutMs: client.timeout,fetch: client.fetcher,});}+function pricingAuth(credentials: Readonly<Record<string, EndpointCredential>>, client: HypiHubClient): HypiHubAuth {+ return createHypiHubAuth({+ credential: credential(credentials),+ baseUrl: client.baseUrl,+ requestTimeoutMs: client.timeout,+ fetch: client.fetcher,+ });+}++function pricingModel(request: import("@hypit/endpoint-kit").EndpointRequest, transcriptionModel: string): string | undefined {+ if (capabilityKey(request.capability) === capabilityKey(whisperXCapabilities.alignment)) {+ return transcriptionModel;+ }+ if (request.capability.module.name === geminiCapabilities[geminiModels[0]].module.name+ && request.capability.module.version === geminiCapabilities[geminiModels[0]].module.version+ && geminiModels.some((model) => model === request.capability.name)) {+ return request.capability.name;+ }+ const route = hypiHubRouteForCapability(request.capability);+ if (route === undefined) return undefined;+ const generation = request.constraints as unknown as GenerationRequest;+ return selectWireModelForRequest(+ route,+ generation,+ request.pendingInputs?.map((input) => input.input),+ );+}++/** Read HypiHub's own current model-pricing document without calculating a request total. */+function hypiHubPricingReader(client: HypiHubClient, transcriptionModel: string): EndpointPricingReader {+ const documents = new Map<string, Promise<Record<string, unknown>>>();+ return async ({ request, credentials }) => {+ const model = pricingModel(request, transcriptionModel);+ if (model === undefined) return [];+ const path = `/pricing?model=${encodeURIComponent(model)}`;+ let pending = documents.get(model);+ if (pending === undefined) {+ pending = credentials().then(async (resolved) => await client.json(path, pricingAuth(resolved, client)));+ documents.set(model, pending);+ }+ const response = await pending;+ return [{+ source: `${client.baseUrl}${path}`,+ data: canonicalize(response),+ }];+ };+}+function cardEndpoints(card: Record<string, unknown> | undefined): readonly string[] {return Array.isArray(card?.endpoints)? card.endpoints.filter((item): item is string => typeof item === "string")@@ -426,6 +478,8 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}assert(Number.isSafeInteger(limit) && limit > 0, `HypiHub ${name} capacity must be a positive integer`);}const requestTimeoutMs = options.requestTimeoutMs ?? 300_000;+ const oauthRequestTimeoutMs = options.oauthRequestTimeoutMs ?? 30_000;+ const pricingRequestTimeoutMs = options.pricingRequestTimeoutMs ?? 30_000;const operationTimeoutMs = options.operationTimeoutMs ?? 20 * 60_000;const uploadPartTimeoutMs = options.uploadPartTimeoutMs ?? 5 * 60_000;const uploadPartAttempts = options.uploadPartAttempts ?? 3;@@ -434,6 +488,8 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}const geminiRateLimitRetryDelayMs = options.geminiRateLimitRetryDelayMs ?? 2_000;for (const [name, value] of Object.entries({requestTimeoutMs,+ oauthRequestTimeoutMs,+ pricingRequestTimeoutMs,operationTimeoutMs,uploadPartTimeoutMs,uploadPartAttempts,@@ -452,6 +508,14 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}downloadAttempts,fetcher: options.fetch ?? globalThis.fetch,});+ const pricingClient = new HypiHubClient({+ baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"),+ timeout: pricingRequestTimeoutMs,+ uploadPartTimeout: uploadPartTimeoutMs,+ uploadPartAttempts,+ downloadAttempts,+ fetcher: options.fetch ?? globalThis.fetch,+ });const asyncEndpoint = endpoint(client, options.pollIntervalMs ?? 10_000, operationTimeoutMs, options.publicAssetUrl);const audioEndpoint: ImmediateEndpointHandler = async (context) => {try {@@ -528,6 +592,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}return defineEndpointPackage({module: hypiHubProviderModuleRef, facet: "gateway", instance: options.instance ?? "hypihub.default", pool: options.pool ?? options.instance ?? "hypihub.default",pricing: { kind: "page", url: "https://hypit.ai/commercial/pricing/" },+ readPricing: hypiHubPricingReader(pricingClient, transcriptionModel),credentials: { apiKey: options.apiKey ?? credentialRef("os", "hypihub.oauth") },credentialInputs: { apiKey: {label: "HypiHub login",@@ -537,6 +602,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}tokenEndpoint: new URL("/oauth/token", oauthOrigin).toString(),clientId: "hyc_d5d5e8e7131b0c877756e66c",scopes: ["user:profile", "user:inference"],+ requestTimeoutMs: oauthRequestTimeoutMs,},} },defaultConcurrency: options.defaultConcurrency ?? 4,@@ -544,8 +610,8 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}capabilities: [...hypiHubRoutes.map((route) => route.media === "audio"- ? { capability: route.capability, returns: route.returns, lifecycle: "immediate" as const, handler: audioEndpoint, capacity: route.capability.name, ...(capabilityConcurrency[route.capability.name] === undefined ? {} : { maxConcurrency: capabilityConcurrency[route.capability.name]! }) }- : { capability: route.capability, returns: route.returns, lifecycle: "asynchronous" as const, endpoint: asyncEndpoint, capacity: route.capability.name, ...(capabilityConcurrency[route.capability.name] === undefined ? {} : { maxConcurrency: capabilityConcurrency[route.capability.name]! }) }),+ ? { capability: route.capability, returns: route.returns, lifecycle: "immediate" as const, handler: audioEndpoint, capacity: route.capability.name, ...(route.supports === undefined ? {} : { supports: route.supports }), ...(capabilityConcurrency[route.capability.name] === undefined ? {} : { maxConcurrency: capabilityConcurrency[route.capability.name]! }) }+ : { capability: route.capability, returns: route.returns, lifecycle: "asynchronous" as const, endpoint: asyncEndpoint, capacity: route.capability.name, ...(route.supports === undefined ? {} : { supports: route.supports }), ...(capabilityConcurrency[route.capability.name] === undefined ? {} : { maxConcurrency: capabilityConcurrency[route.capability.name]! }) }),...geminiModels.map((model) => ({capability: geminiCapabilities[model],returns: geminiTypes.visualObservation,diff --git a/packages/provider-hypihub/src/routes.ts b/packages/provider-hypihub/src/routes.tsindex e7f004ec..870ded4b 100644--- a/packages/provider-hypihub/src/routes.ts+++ b/packages/provider-hypihub/src/routes.ts@@ -8,35 +8,74 @@ import {import type { GenerationArtifactUrlResolver, GenerationRequest, GenerationWireMapping } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CapabilityRef, CanonicalValue, StoredValue, TypeRef } from "@hypit/protocol";+import type { EndpointRequest, EndpointSupport } from "@hypit/endpoint-kit";import { hypiHubMappings } from "./mapping.js";export type HypiHubRoute = (typeof hypiHubMappings)[number] & {readonly key: string;readonly returns: TypeRef;readonly media: "image" | "video" | "audio";+ readonly supports?: (request: EndpointRequest) => EndpointSupport;readonly compile: (constraints: CanonicalValue, resolve: GenerationArtifactUrlResolver) => Promise<{ readonly model: string; readonly input: CanonicalValue }>;readonly packageResult: (artifacts: readonly BlobRef[]) => StoredValue;};-export const hypiHubRoutes: readonly HypiHubRoute[] = hypiHubMappings.map((mapping) => ({- ...mapping,- key: capabilityKey(mapping.capability),- returns: mapping.result === "image" ? generationTypes.imageSet- : mapping.result === "video" ? generationTypes.videoSet : generationTypes.audioSet,- media: mapping.result,- compile: async (constraints, resolve) => normalizeHypiHubRequest(- mapping,- await compileWireRequest(mapping, constraints as unknown as GenerationRequest, resolve),- ),- packageResult: (artifacts) => ({- kind: "inline",- value: canonicalize(mapping.result === "image"- ? sealGeneratedImageSet({ images: artifacts })- : mapping.result === "video"- ? sealGeneratedVideoSet({ videos: artifacts })- : sealGeneratedAudioSet({ audios: artifacts })),- }),-}));+function scalar(request: GenerationRequest, port: string): string | number | boolean | undefined {+ const value = request.ports[port]?.[0];+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : undefined;+}++/** Current HypiHub GPT Image combinations, independently declared at this Endpoint boundary. */+function hypiHubGenerationRejection(mapping: GenerationWireMapping, request: GenerationRequest): string | undefined {+ if (mapping.capability.module.name !== "@hypit/gpt-image" || mapping.capability.name !== "gpt-image-2") {+ return undefined;+ }+ const ratio = scalar(request, "aspectRatio");+ const resolution = scalar(request, "resolution");+ const background = scalar(request, "background");+ const unsupportedRatios = resolution === "2K"+ ? ["5:4", "4:5", "3:1", "1:3", "9:21"]+ : resolution === "4K" ? ["3:1", "1:3", "9:21"] : [];+ if (unsupportedRatios.includes(String(ratio))) {+ return `HypiHub GPT Image 2 does not accept ${String(ratio)} at ${String(resolution)}`;+ }+ if (background !== undefined && resolution !== "1K") {+ return `HypiHub GPT Image 2 accepts the background option only at 1K; omit it at ${String(resolution)}`;+ }+ return undefined;+}++export const hypiHubRoutes: readonly HypiHubRoute[] = hypiHubMappings.map((mapping) => {+ const hasRequestLimits = mapping.capability.module.name === "@hypit/gpt-image"+ && mapping.capability.name === "gpt-image-2";+ return {+ ...mapping,+ key: capabilityKey(mapping.capability),+ returns: mapping.result === "image" ? generationTypes.imageSet+ : mapping.result === "video" ? generationTypes.videoSet : generationTypes.audioSet,+ media: mapping.result,+ ...(hasRequestLimits ? {+ supports: (request: EndpointRequest) => {+ const reason = hypiHubGenerationRejection(mapping, request.constraints as unknown as GenerationRequest);+ return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };+ },+ } : {}),+ compile: async (constraints, resolve) => {+ const request = constraints as unknown as GenerationRequest;+ const rejection = hypiHubGenerationRejection(mapping, request);+ if (rejection !== undefined) throw new Error(rejection);+ return normalizeHypiHubRequest(mapping, await compileWireRequest(mapping, request, resolve));+ },+ packageResult: (artifacts) => ({+ kind: "inline",+ value: canonicalize(mapping.result === "image"+ ? sealGeneratedImageSet({ images: artifacts })+ : mapping.result === "video"+ ? sealGeneratedVideoSet({ videos: artifacts })+ : sealGeneratedAudioSet({ audios: artifacts })),+ }),+ };+});/** Convert the provider-neutral generation wire shape to HypiHub's public API shape. */function normalizeHypiHubRequest(diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.tsindex 7f292bfb..d49b9867 100644--- a/packages/provider-hypihub/test/provider.test.ts+++ b/packages/provider-hypihub/test/provider.test.ts@@ -7,6 +7,7 @@ import type { AsyncEndpoint } from "@hypit/endpoint-kit";import { geminiCapabilities, geminiTypes, sealGeminiRequest } from "@hypit/gemini";import type { CanonicalValue, Need } from "@hypit/protocol";import { mimoSpeechEndpoints, sealMimoSpeechRequest } from "@hypit/mimo-speech";+import { generationTypes } from "@hypit/generation";import { sealSeedanceRequest, seedanceEndpoints } from "@hypit/seedance";import { sealSpeechEvidenceAudio } from "@hypit/speech";import { speechEvidenceTypes } from "@hypit/speech-evidence";@@ -112,12 +113,94 @@ test("HypiHub declares its own credential acquisition flow", () => {assert.equal(credential?.acquisition?.kind, "oauth2-pkce");assert.equal(credential?.acquisition?.authorizationEndpoint, "https://hypit.ai/oauth/consent");assert.equal(credential?.acquisition?.tokenEndpoint, "https://hypit.ai/oauth/token");+ assert.equal(credential?.acquisition?.requestTimeoutMs, 30_000);+});++test("HypiHub publishes GPT Image request limits through its Endpoint offer", () => {+ const offer = createHypiHubProvider().offers.find((item) => item.capability.name === "gpt-image-2");+ assert.ok(offer);+ assert.deepEqual(offer.supports?.({+ capability: offer.capability,+ returns: offer.returns,+ constraints: {+ ports: {+ prompt: ["cutout"], aspectRatio: ["1:1"], resolution: ["2K"], background: ["opaque"],+ },+ },+ }), {+ status: "unsupported",+ reason: "HypiHub GPT Image 2 accepts the background option only at 1K; omit it at 2K",+ });});test("HypiHub derives credential acquisition from its configured service origin", () => {- const [credential] = createHypiHubProvider({ baseUrl: "https://gateway.example.test/v1" }).credentials;+ const [credential] = createHypiHubProvider({+ baseUrl: "https://gateway.example.test/v1",+ oauthRequestTimeoutMs: 12_000,+ }).credentials;assert.equal(credential?.acquisition?.authorizationEndpoint, "https://gateway.example.test/oauth/consent");assert.equal(credential?.acquisition?.tokenEndpoint, "https://gateway.example.test/oauth/token");+ assert.equal(credential?.acquisition?.requestTimeoutMs, 12_000);+});++test("HypiHub returns its current model-pricing document", async () => {+ const provider = createHypiHubProvider({+ pricingRequestTimeoutMs: 1_000,+ fetch: async (input, init) => {+ assert.equal(String(input), "https://hypit.ai/v1/pricing?model=bytedance%2Fseedance-2");+ assert.equal((init?.headers as Record<string, string>).authorization, "Bearer test-key");+ return Response.json({+ object: "model_pricing",+ model: "bytedance/seedance-2",+ pricing: { mode: "per_second", per_second_usd: 0.1045 },+ });+ },+ });+ const request = {+ capability: seedanceEndpoints.standard!.capability,+ returns: seedanceEndpoints.standard!.returns,+ constraints: sealSeedanceRequest("seedance-2", {+ prompt: ["A presenter speaks to camera."], resolution: ["720p"], aspectRatio: ["9:16"],+ duration: [5], generateAudio: [true], webSearch: [false],+ }) as unknown as CanonicalValue,+ };+ assert.deepEqual(await provider.readPricing!({+ request,+ credentials: async () => ({ apiKey: { secret: "test-key" } }),+ }), [{+ source: "https://hypit.ai/v1/pricing?model=bytedance%2Fseedance-2",+ data: {+ object: "model_pricing",+ model: "bytedance/seedance-2",+ pricing: { mode: "per_second", per_second_usd: 0.1045 },+ },+ }]);+});++test("HypiHub prices the wire route selected by an authored future input", async () => {+ const provider = createHypiHubProvider({+ pricingRequestTimeoutMs: 1_000,+ fetch: async (input) => {+ assert.equal(String(input), "https://hypit.ai/v1/pricing?model=gpt-image-2-image-to-image");+ return Response.json({ object: "model_pricing", model: "gpt-image-2-image-to-image" });+ },+ });+ const request = {+ capability: { module: { name: "@hypit/gpt-image", version: "1" }, name: "gpt-image-2" },+ returns: generationTypes.imageSet,+ constraints: {+ ports: { prompt: ["A portrait."], aspectRatio: ["9:16"], resolution: ["1K"] },+ },+ pendingInputs: [{ input: "images", role: "image" }],+ } as const;+ const [document] = await provider.readPricing!({+ request,+ credentials: async () => ({ apiKey: { secret: "test-key" } }),+ });+ assert.deepEqual(document?.data, {+ object: "model_pricing",+ model: "gpt-image-2-image-to-image",+ });});test("HypiHub doctor checks the authenticated catalogue only when actively invoked", async () => {diff --git a/packages/provider-hypihub/test/routes.test.ts b/packages/provider-hypihub/test/routes.test.tsindex 38de070d..a9e1ca08 100644--- a/packages/provider-hypihub/test/routes.test.ts+++ b/packages/provider-hypihub/test/routes.test.ts@@ -1,5 +1,7 @@import assert from "node:assert/strict";import test from "node:test";+import type { EndpointSupport } from "@hypit/endpoint-kit";+import type { CanonicalValue } from "@hypit/protocol";import { hypiHubRoutes } from "../src/routes.js";@@ -13,7 +15,7 @@ const image = {const resolve = async () => "data:image/png;base64,AQID";const resolveAudio = async () => "data:audio/wav;base64,AQID";-test("HypiHub GPT image requests use canonical edit references and the resolution tier", async () => {+test("HypiHub GPT image requests use canonical edit references and the authored resolution tier", async () => {const route = hypiHubRoutes.find((item) => item.capability.name === "gpt-image-2");assert.ok(route);const result = await route.compile({@@ -21,6 +23,7 @@ test("HypiHub GPT image requests use canonical edit references and the resolutioprompt: ["edit"],aspectRatio: ["1:1"],resolution: ["1K"],+ background: ["transparent"],images: [{ role: "image", artifact: image }],},}, resolve);@@ -28,9 +31,47 @@ test("HypiHub GPT image requests use canonical edit references and the resolutioassert.deepEqual(result.input, {prompt: "edit",aspect_ratio: "1:1",- size: "1K",+ resolution: "1K",+ background: "transparent",reference_images: [{ url: "data:image/png;base64,AQID" }],});++ const unsupported = { ports: {+ prompt: ["cutout"], aspectRatio: ["1:1"], resolution: ["2K"], background: ["opaque"],+ } } as unknown as CanonicalValue;+ assert.deepEqual(route.supports?.({+ capability: route.capability,+ returns: route.returns,+ constraints: unsupported,+ }), {+ status: "unsupported",+ reason: "HypiHub GPT Image 2 accepts the background option only at 1K; omit it at 2K",+ });+ await assert.rejects(route.compile(unsupported, resolve), /background option only at 1K/u);++ for (const constraints of [+ { ports: { prompt: ["portrait"], aspectRatio: ["5:4"], resolution: ["2K"] } },+ { ports: { prompt: ["portrait"], aspectRatio: ["3:1"], resolution: ["4K"] } },+ ]) {+ const support: EndpointSupport | undefined = route.supports?.({+ capability: route.capability,+ returns: route.returns,+ constraints,+ });+ assert.equal(support?.status, "unsupported");+ assert.match(support?.status === "unsupported" ? support.reason : "", /HypiHub GPT Image 2/u);+ }++ for (const constraints of [+ { ports: { prompt: ["portrait"], aspectRatio: ["auto"], resolution: ["4K"] } },+ { ports: { prompt: ["portrait"], aspectRatio: ["5:4"], resolution: ["4K"] } },+ ]) {+ assert.deepEqual(route.supports?.({+ capability: route.capability,+ returns: route.returns,+ constraints,+ }), { status: "supported" });+ }});test("HypiHub image-to-video requests preserve Hypit's first-frame semantics", async () => {diff --git a/packages/provider-kie/README.md b/packages/provider-kie/README.mdindex 0954d7d9..a82641ca 100644--- a/packages/provider-kie/README.md+++ b/packages/provider-kie/README.md@@ -28,15 +28,31 @@ routes rather than extra Capabilities.| `@hypit/seedream` | `seedream-5-lite` | `seedream/5-lite-{text,image}-to-image` || `@hypit/background-removal` | `remove-background` | `recraft/remove-background` |-KIE accepts the GPT Image 2 `4:3`, `3:4` and `4:5` ratios. Its restrictions are combinations rather-than a blacklist: `auto` is 1K-only, `1:1` is unavailable at 4K, and `4:5` is 1K-only. The KIE-Endpoint checks those exact combinations before upload or paid submission without narrowing the-model package's Provider-neutral vocabulary.+KIE's current GPT Image 2 request surface is:++| Resolution | Ratios unavailable at this Endpoint | `background` |+| --- | --- | --- |+| `1K` | none | optional |+| `2K` | `5:4`, `4:5`, `3:1`, `1:3`, `9:21` | omit |+| `4K` | `3:1`, `1:3`, `9:21` | omit |++These facts were checked against KIE's live `createTask` endpoint on 2026-09-07. The live API accepts+`5:4` and `4:5` at 4K even though KIE's [model page](https://kie.ai/gpt-image-2) currently lists a+broader restriction. At 2K and 4K, any explicit `background` value is rejected, including `opaque`+and `auto`. The KIE Endpoint checks this boundary before upload or paid submission; the GPT Image+model package continues to expose the complete Provider-neutral vocabulary.KIE's Grok Imagine endpoints accept up to seven reference images, but only one at 1080p. This isalso checked by the KIE Endpoint; the Grok model packages retain their model-level seven-imagecapacity.+KIE publishes a public model-pricing catalogue at `POST /client/v1/model-pricing/page`. For each+selected Need, `readPricing` derives the same KIE wire model used for execution, reads the catalogue's+pages with that wire model in KIE's `modelDescription` query, and preserves the returned records. The+Provider contains no Hypit model-price table and does not interpret KIE's descriptions or formulas.+All returned parameter rows remain intact for the Agent to read beside the Need. Reading this public+catalogue does not resolve the generation API credential and submits no work.+There is deliberately no Grok image capability and no MiMo capability in this release. Seedream's`nsfwCheck` is explicit author request content; KIE cannot silently enable or disable it. Acustomer-specific “spicy” treatment belongs in a Recipe that selects and parameterizes exact modeldiff --git a/packages/provider-kie/src/mapping.ts b/packages/provider-kie/src/mapping.tsindex 258a047e..191a1d48 100644--- a/packages/provider-kie/src/mapping.ts+++ b/packages/provider-kie/src/mapping.ts@@ -106,6 +106,7 @@ const gptImageMapping: GenerationWireMapping = {prompt: { as: "value", field: "prompt" },aspectRatio: { as: "value", field: "aspect_ratio" },resolution: { as: "value", field: "resolution" },+ background: { as: "value", field: "background" },images: { as: "urlArray", field: "input_urls" },},};diff --git a/packages/provider-kie/src/provider.ts b/packages/provider-kie/src/provider.tsindex b0745af9..441f7652 100644--- a/packages/provider-kie/src/provider.ts+++ b/packages/provider-kie/src/provider.ts@@ -2,6 +2,7 @@ import { requestDeadline } from "@hypit/runtime-kit";import type {AsyncEndpoint,EndpointPollContext,+ EndpointPricingReader,EndpointStartContext,EndpointOutcome,} from "@hypit/endpoint-kit";@@ -123,6 +124,7 @@ type KieClientOptions = {class KieClient {readonly #options: KieClientOptions;+ readonly #pricingRecords = new Map<string, Promise<readonly Record<string, unknown>[]>>();constructor(options: KieClientOptions) {this.#options = options;@@ -193,6 +195,40 @@ class KieClient {}}+ get pricingSource(): string {+ return `${this.#options.apiBaseUrl}/client/v1/model-pricing/page`;+ }++ async pricingRecords(model: string): Promise<readonly Record<string, unknown>[]> {+ let pending = this.#pricingRecords.get(model);+ if (pending === undefined) {+ pending = (async () => {+ const records: Record<string, unknown>[] = [];+ let page = 1;+ let pages = 1;+ while (page <= pages) {+ const response = await this.#json(this.pricingSource, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ pageNum: page, pageSize: 100, modelDescription: model, interfaceType: "" }),+ });+ assert(response.code === 200, "KIE pricing service rejected the rate-card request");+ const data = object(response.data, "KIE pricing data");+ assert(Array.isArray(data.records), "KIE pricing data contains no records array");+ for (const value of data.records) records.push(object(value, "KIE pricing record"));+ const reportedPages = data.pages;+ assert(typeof reportedPages === "number" && Number.isSafeInteger(reportedPages)+ && reportedPages >= 0 && reportedPages <= 100, "KIE pricing page count is invalid");+ pages = reportedPages;+ page += 1;+ }+ return records;+ })();+ this.#pricingRecords.set(model, pending);+ }+ return await pending;+ }+async upload(artifact: BlobRef, resources: ResourceStore, apiKey: string): Promise<string> {if (artifact.size > this.#options.maxArtifactBytes) {throw new KieError("KIE_ARTIFACT_TOO_LARGE", `Artifact ${artifact.resource} exceeds the configured KIE upload limit`);@@ -390,6 +426,20 @@ class KieClient {}}+function kiePricingReader(client: KieClient): EndpointPricingReader {+ return async ({ request }) => {+ const route = kieRouteForCapability(request.capability);+ if (route === undefined) return [];+ const selectedModel = route.selectModel(request);+ const records = await client.pricingRecords(selectedModel);+ if (records.length === 0) return [];+ return [{+ source: client.pricingSource,+ data: canonicalize({ model: selectedModel, records }),+ }];+ };+}+function resultUrls(data: Record<string, unknown>): string[] {let result: unknown = data.resultJson;if (typeof result === "string") {@@ -577,6 +627,7 @@ export function createKieProvider(config: CreateKieProviderOptions) {instance: config.instance ?? "kie.default",pool: config.pool ?? config.instance ?? "kie.default",pricing: { kind: "page", url: "https://kie.ai/pricing" },+ readPricing: kiePricingReader(client),credentials: { apiKey: config.apiKey ?? credentialRef("env", "KIE_API_KEY") },credentialInputs: { apiKey: { label: "KIE API key" } },defaultConcurrency: config.defaultConcurrency ?? 10,diff --git a/packages/provider-kie/src/routes.ts b/packages/provider-kie/src/routes.tsindex 78e8f65c..fd6d69c1 100644--- a/packages/provider-kie/src/routes.ts+++ b/packages/provider-kie/src/routes.ts@@ -7,13 +7,14 @@ import type { BackgroundRemovalRequest } from "@hypit/background-removal";import {compileWireRequest,generationTypes,+ selectWireModelForRequest,sealGeneratedImageSet,sealGeneratedVideoSet,} from "@hypit/generation";import type { GenerationArtifactUrlResolver, GenerationRequest, GenerationWireMapping } from "@hypit/generation";import { canonicalize } from "@hypit/protocol";import type { BlobRef, CanonicalValue, CapabilityRef, StoredValue, TypeRef } from "@hypit/protocol";-import type { EndpointRequest } from "@hypit/endpoint-kit";+import type { EndpointRequest, EndpointSupport } from "@hypit/endpoint-kit";import { kieModelCatalog, verifyKieModelCatalog } from "./mapping.js";@@ -28,7 +29,9 @@ export type KieRoute = {readonly returns: TypeRef;readonly media: "image" | "video";readonly maxResults: number;- readonly supports?: (request: EndpointRequest) => boolean;+ readonly supports?: (request: EndpointRequest) => EndpointSupport;+ /** Select the same service model before or during execution, without resolving Resource bytes. */+ readonly selectModel: (request: EndpointRequest) => string;readonly compile: (constraints: CanonicalValue,resolve: GenerationArtifactUrlResolver,@@ -50,14 +53,15 @@ function kieGenerationRejection(mapping: GenerationWireMapping, request: Generatif (mapping.capability.module.name === "@hypit/gpt-image" && mapping.capability.name === "gpt-image-2") {const ratio = scalar(request, "aspectRatio");const resolution = scalar(request, "resolution");- if (ratio === "auto" && resolution !== "1K") {- return `KIE GPT Image 2 accepts auto aspect ratio only at 1K, not ${String(resolution)}`;+ const background = scalar(request, "background");+ const unsupportedRatios = resolution === "2K"+ ? ["5:4", "4:5", "3:1", "1:3", "9:21"]+ : resolution === "4K" ? ["3:1", "1:3", "9:21"] : [];+ if (unsupportedRatios.includes(String(ratio))) {+ return `KIE GPT Image 2 does not accept ${String(ratio)} at ${String(resolution)}`;}- if (ratio === "1:1" && resolution === "4K") {- return "KIE GPT Image 2 does not accept 1:1 at 4K";- }- if (ratio === "4:5" && resolution !== "1K") {- return `KIE GPT Image 2 accepts 4:5 only at 1K, not ${String(resolution)}`;+ if (background !== undefined && resolution !== "1K") {+ return `KIE GPT Image 2 accepts the background option only at 1K; omit it at ${String(resolution)}`;}}if (mapping.capability.module.name === "@hypit/grok-imagine"@@ -83,10 +87,15 @@ const generationRoutes: readonly KieRoute[] = kieGenerationMappings.map((mappingreturns: mapping.result === "image" ? generationTypes.imageSet : generationTypes.videoSet,media: mapping.result,maxResults: mapping.result === "image" ? 16 : 8,- supports: (need: EndpointRequest) => kieGenerationRejection(+ supports: (need: EndpointRequest) => {+ const reason = kieGenerationRejection(mapping, need.constraints as unknown as GenerationRequest);+ return reason === undefined ? { status: "supported" } : { status: "unsupported", reason };+ },+ selectModel: (need) => selectWireModelForRequest(mapping,need.constraints as unknown as GenerationRequest,- ) === undefined,+ need.pendingInputs?.map((input) => input.input),+ ),compile: async (constraints, resolve) => {const request = constraints as unknown as GenerationRequest;const rejection = kieGenerationRejection(mapping, request);@@ -107,6 +116,7 @@ const backgroundRemovalRoute: KieRoute = {returns: artifactTypes.blob,media: "image",maxResults: 1,+ selectModel: () => "recraft/remove-background",compile: async (constraints, resolve) => {const request = constraints as unknown as BackgroundRemovalRequest;assertBackgroundRemovalRequest(request);diff --git a/packages/provider-kie/test/models.test.ts b/packages/provider-kie/test/models.test.tsindex 6bc35dee..738d21e0 100644--- a/packages/provider-kie/test/models.test.ts+++ b/packages/provider-kie/test/models.test.ts@@ -1,6 +1,7 @@import assert from "node:assert/strict";import test from "node:test";import { MemoryResourceStore } from "@hypit/driver-node";+import type { EndpointSupport } from "@hypit/endpoint-kit";import {assertMappingCoversPorts,compileWireRequest,@@ -28,7 +29,8 @@ import {seedreamDefinition,sealSeedreamRequest,} from "@hypit/seedream";-import type { CapabilityRef } from "@hypit/protocol";+import type { CanonicalValue, CapabilityRef } from "@hypit/protocol";+import { kieRoutes } from "../src/routes.js";/*** Every exact model this repository ships, paired with the Capability it publishes.@@ -47,16 +49,12 @@ function capabilityKey(ref: CapabilityRef): string {const upload = async (artifact: { readonly resource: string }) => `https://upload.test/${artifact.resource}`;-/**- * The check the old hand-written translators could not perform. Forgetting a- * reference role or an item field used to surface only after paid generation- * returned the wrong result; it now fails here.- */+/** Every declared model port must have an explicit KIE wire mapping. */test("the KIE mapping covers every port every exact model declares", () => {assert.equal(modelCapabilities.length, kieModelCatalog.length);const mappings = new Map(kieModelCatalog.map((item) => [capabilityKey(item.capability), item]));for (const { ports, capability } of modelCapabilities) {- // Matched on the full Capability, version included: a stale mapping cannot pass by name alone.+ // The full Capability includes the model module version.const mapping = mappings.get(capabilityKey(capability));assert.ok(mapping, `KIE declares no mapping for ${capabilityKey(capability)}`);assertMappingCoversPorts(ports, mapping);@@ -182,6 +180,63 @@ test("Seedance 2.5 maps its exact request without leaking KIE envelope controls});});+test("KIE maps GPT Image background and applies its measured request combinations", async () => {+ const route = kieRoutes.find((item) => item.capability.name === "gpt-image-2");+ assert.ok(route);+ const request = sealGptImage2Request({+ prompt: ["A product cutout."],+ aspectRatio: ["1:1"],+ resolution: ["1K"],+ background: ["transparent"],+ });+ const task = await route.compile(request as unknown as CanonicalValue, upload);+ assert.deepEqual(task.input, {+ prompt: "A product cutout.",+ aspect_ratio: "1:1",+ resolution: "1K",+ background: "transparent",+ });++ for (const unsupported of [+ sealGptImage2Request({+ prompt: ["A product cutout."], aspectRatio: ["1:1"], resolution: ["2K"],+ background: ["opaque"],+ }),+ sealGptImage2Request({+ prompt: ["A portrait."], aspectRatio: ["5:4"], resolution: ["2K"],+ }),+ sealGptImage2Request({+ prompt: ["A portrait."], aspectRatio: ["3:1"], resolution: ["4K"],+ }),+ ]) {+ const support: EndpointSupport | undefined = route.supports?.({+ capability: route.capability,+ returns: route.returns,+ constraints: unsupported as unknown as CanonicalValue,+ });+ assert.equal(support?.status, "unsupported");+ assert.match(support?.status === "unsupported" ? support.reason : "", /KIE GPT Image 2/u);+ }++ for (const supported of [+ sealGptImage2Request({+ prompt: ["A portrait."], aspectRatio: ["auto"], resolution: ["4K"],+ }),+ sealGptImage2Request({+ prompt: ["A portrait."], aspectRatio: ["1:1"], resolution: ["4K"],+ }),+ sealGptImage2Request({+ prompt: ["A portrait."], aspectRatio: ["5:4"], resolution: ["4K"],+ }),+ ]) {+ assert.deepEqual(route.supports?.({+ capability: route.capability,+ returns: route.returns,+ constraints: supported as unknown as CanonicalValue,+ }), { status: "supported" });+ }+});+test("one model reaching a service that splits it keeps the reference roles intact", async () => {const store = new MemoryResourceStore();const image = await store.put(new Uint8Array([1]), "image/png");diff --git a/packages/provider-kie/test/provider.test.ts b/packages/provider-kie/test/provider.test.tsindex 5a7c4f4b..315f1bab 100644--- a/packages/provider-kie/test/provider.test.ts+++ b/packages/provider-kie/test/provider.test.ts@@ -11,6 +11,7 @@ import type { AsyncEndpoint } from "@hypit/endpoint-kit";import { artifactTypes } from "@hypit/artifact";import { backgroundRemovalCapabilities, backgroundRemovalRequest } from "@hypit/background-removal";import { seedanceEndpoints, sealSeedanceRequest } from "@hypit/seedance";+import { generationTypes } from "@hypit/generation";import type { CanonicalValue, Need } from "@hypit/protocol";import { createKieProvider } from "@hypit/provider-kie";@@ -85,6 +86,85 @@ test("all KIE capabilities share one asynchronous task engine and use exact-mode});});+test("KIE exposes the rate-card records returned for the request's wire model", async () => {+ const provider = createKieProvider({+ fetch: async (input, init) => {+ assert.equal(String(input), "https://api.kie.ai/client/v1/model-pricing/page");+ assert.deepEqual(JSON.parse(String(init?.body)), {+ pageNum: 1,+ pageSize: 100,+ modelDescription: "bytedance/seedance-2-mini",+ interfaceType: "",+ });+ return Response.json({ code: 200, data: {+ records: [{+ modelDescription: "bytedance/seedance-2-mini, 720P no video",+ creditPrice: "8.2",+ creditUnit: "per second",+ usdPrice: "0.041",+ }],+ pages: 1,+ } });+ },+ });+ const request = {+ capability: seedanceEndpoints.mini!.capability,+ returns: seedanceEndpoints.mini!.returns,+ constraints: sealSeedanceRequest("seedance-2-mini", {+ prompt: ["A presenter speaks to camera."], resolution: ["720p"], aspectRatio: ["9:16"],+ duration: [5], generateAudio: [true], webSearch: [false],+ }) as unknown as CanonicalValue,+ };+ assert.deepEqual(await provider.readPricing!({+ request,+ credentials: async () => { throw new Error("public pricing must not require credentials"); },+ }), [{+ source: "https://api.kie.ai/client/v1/model-pricing/page",+ data: {+ model: "bytedance/seedance-2-mini",+ records: [{+ modelDescription: "bytedance/seedance-2-mini, 720P no video",+ creditPrice: "8.2",+ creditUnit: "per second",+ usdPrice: "0.041",+ }],+ },+ }]);+});++test("KIE prices the wire route selected by an authored future input", async () => {+ const provider = createKieProvider({+ fetch: async () => Response.json({ code: 200, data: {+ records: [{+ modelDescription: "gpt-image-2-image-to-image, 1K",+ creditPrice: "8",+ creditUnit: "per image",+ }],+ pages: 1,+ } }),+ });+ const request = {+ capability: { module: { name: "@hypit/gpt-image", version: "1" }, name: "gpt-image-2" },+ returns: generationTypes.imageSet,+ constraints: {+ ports: { prompt: ["A portrait."], aspectRatio: ["9:16"], resolution: ["1K"] },+ },+ pendingInputs: [{ input: "images", role: "image" }],+ } as const;+ const [document] = await provider.readPricing!({+ request,+ credentials: async () => { throw new Error("public pricing must not require credentials"); },+ });+ assert.deepEqual(document?.data, {+ model: "gpt-image-2-image-to-image",+ records: [{+ modelDescription: "gpt-image-2-image-to-image, 1K",+ creditPrice: "8",+ creditUnit: "per image",+ }],+ });+});+test("KIE uploads referenced resources, polls one task, and persists generated bytes", async () => {const resources = new MemoryResourceStore();const firstFrame = await resources.put(new Uint8Array([1, 2, 3]), "image/png");diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.tsindex c987f8b4..341f84e3 100644--- a/packages/runtime-host-node/src/index.ts+++ b/packages/runtime-host-node/src/index.ts@@ -6,7 +6,7 @@ import type { ArtifactAttachment } from "@hypit/workspace";import type { BuildResultForward } from "@hypit/build-result";import type { BuildResultRepositoryLocation } from "@hypit/build-result-kit";import type { DriverRunResult, NodeDriverOptions, ProducerRegistry } from "@hypit/driver-node";-import type { BuildDefinition, BuildState, CapabilityRef, Need, StoredValue } from "@hypit/protocol";+import type { BuildDefinition, BuildState, CanonicalValue, CapabilityRef, Need, StoredValue } from "@hypit/protocol";import type {BuildCatalogDescriptor,BuildCompletion,@@ -154,8 +154,8 @@ export type RuntimeHostCapabilityProvider = {/** Caller-owned identity for this planned request. */readonly request: string;readonly capability: CapabilityRef;- readonly status: "resolved" | "unresolved" | "ambiguous";- /** Configured Endpoint instance that would serve the capability, when exactly one does. */+ readonly status: "resolved" | "unresolved" | "unsupported" | "ambiguous";+ /** Configured Endpoint instance selected for this request, when exactly one is identifiable. */readonly endpoint?: string;/** Provider package the Runtime Profile selected for that Endpoint. */readonly use?: string;@@ -163,10 +163,22 @@ export type RuntimeHostCapabilityProvider = {readonly pricing?: { readonly kind: "page"; readonly url: string } | { readonly kind: "local" };/** Every matching Endpoint instance when the selection is ambiguous. */readonly endpoints?: readonly string[];+ /** Provider-owned reasons from Endpoints that offer the capability but reject this request. */+ readonly rejections?: readonly { readonly endpoint: string; readonly message: string }[];/** The Endpoint instance the Profile's `bindings` name for this capability, when it names one. */readonly binding?: string;};+export type RuntimeHostCapabilityPricing = RuntimeHostCapabilityProvider & {+ /** Provider-owned current pricing material relevant to this request. */+ readonly pricingDocuments?: readonly {+ readonly source: string;+ readonly data: CanonicalValue;+ }[];+ /** A failed pricing-source read. The Provider's static price page remains available. */+ readonly pricingError?: string;+};+export type RuntimeHostProviderQuery = {readonly request: string;readonly capability: CapabilityRef;@@ -267,6 +279,8 @@ export type NodeRuntimeHost = {* Reads the Profile and Endpoint declarations only; never resolves a credential or contacts a service.*/providers(requests: readonly RuntimeHostProviderQuery[]): Promise<readonly RuntimeHostCapabilityProvider[]>;+ /** Read current Provider-owned pricing material relevant to these requests. */+ pricing(requests: readonly RuntimeHostProviderQuery[]): Promise<readonly RuntimeHostCapabilityPricing[]>;/*** Execute one immediate Need through the selected Endpoint and its credentials, outside any Build.* The creation-time boundary for observation, transcription and other quick capabilities; itdiff --git a/packages/runtime-local/src/config.ts b/packages/runtime-local/src/config.tsindex 1d9dbe98..63b97cda 100644--- a/packages/runtime-local/src/config.ts+++ b/packages/runtime-local/src/config.ts@@ -8,8 +8,8 @@ import {} from "@hypit/package-loader-node";import type { NodePackageSelectionRequest } from "@hypit/package-loader-node";import { EndpointRegistry, NodeDriver } from "@hypit/driver-node";-import type { EndpointCredential, EndpointFulfillment, EndpointRegistrar, EndpointScheduling } from "@hypit/endpoint-kit";-import { endpointResourceClaims } from "@hypit/endpoint-kit";+import type { EndpointCredential, EndpointFulfillment, EndpointPackage, EndpointRegistrar, EndpointScheduling } from "@hypit/endpoint-kit";+import { endpointResourceClaims, verifyEndpointPricingDocument } from "@hypit/endpoint-kit";import { assertBuildId, canonicalize, canonicalStringify } from "@hypit/protocol";import type { CanonicalValue, CapabilityRef, Need } from "@hypit/protocol";import {@@ -52,6 +52,7 @@ import {import type {HostPackageProgress,HostPackageReport,+ RuntimeHostCapabilityPricing,RuntimeHostCapabilityProvider,RuntimeHostProviderQuery,RuntimeHostTransientExecution,@@ -193,10 +194,6 @@ function bindings(value: unknown, endpoints: readonly LocalRuntimeAdapterSelectiexport function parseLocalRuntimeProfile(value: unknown): LocalRuntimeProfile {const item = object(value, "$runtime");- if (item.runtime !== undefined && item.format === "hypit.runtime-profile@1") {- throw new Error("This Runtime Profile uses the retired hypit.runtime-profile@1 shape with a nested runtime object. "- + "Move runtime.config.dataRoot, credentials and endpoints to the top level and set format to hypit.runtime-local@1.");- }exactKeys(item, ["format", "dataRoot", "credentials", "endpoints", "bindings"], "$runtime");if (item.format !== "hypit.runtime-local@1") {throw new Error("$runtime.format must be hypit.runtime-local@1");@@ -650,6 +647,21 @@ export async function describeRuntimeConfigProviders(...(request.pendingInputs === undefined ? {} : { pendingInputs: request.pendingInputs }),});if (resolution.status === "missing") return { ...base, status: "unresolved", ...bound };+ if (resolution.status === "unsupported") {+ const endpoint = resolution.rejections.length === 1 ? resolution.rejections[0]!.endpointId : undefined;+ const match = endpoint === undefined ? undefined+ : activations.find(({ activation }) => activation.endpoint.instance.id === endpoint);+ const pricing = match?.activation.endpoint.pricing;+ return {+ ...base,+ status: "unsupported",+ ...(endpoint === undefined ? {} : { endpoint }),+ ...(match === undefined ? {} : { use: match.entry.use }),+ ...(pricing === undefined ? {} : { pricing: structuredClone(pricing) }),+ rejections: resolution.rejections.map((item) => ({ endpoint: item.endpointId, message: item.reason })),+ ...bound,+ };+ }if (resolution.status === "ambiguous") return { ...base, status: "ambiguous", endpoints: resolution.endpointIds, ...bound };const match = activations.find(({ activation }) => activation.endpoint.instance.id === resolution.registration.id);const pricing = match?.activation.endpoint.pricing;@@ -664,6 +676,138 @@ export async function describeRuntimeConfigProviders(});}+async function resolveEndpointCredentials(+ endpoint: EndpointPackage,+ store: CredentialStore,+ profile: string,+): Promise<Readonly<Record<string, EndpointCredential>>> {+ const credentials: Record<string, EndpointCredential> = {};+ for (const slot of endpoint.credentials) {+ const value = await store.resolve(slot.ref);+ if (value === undefined) {+ throw new Error(`${slot.label} for Endpoint ${slot.endpoint} is not configured. ${+ slot.ref.store === "env"+ ? `Set ${slot.ref.key} in this process environment.`+ : `Configure it with: hypit auth login ${slot.endpoint} --runtime ${profile}`}`);+ }+ const writable = await writableCredentialStore(store, slot.ref);+ credentials[slot.slot] = {+ ...value,+ ...(writable === undefined ? {} : {+ replace: async (replacement: CredentialValue) => await writable.put(slot.ref, replacement),+ }),+ };+ }+ return credentials;+}++/** Read current Provider-owned pricing material; no Build, generation or durable pricing cache is created. */+export async function readRuntimeConfigPricing(+ path: string,+ requests: readonly RuntimeHostProviderQuery[],+ options: LoadRuntimeConfigOptions = {},+): Promise<readonly RuntimeHostCapabilityPricing[]> {+ if (requests.length === 0) return [];+ const { absolute, document, root, packageRoot } = await openRuntimeConfig(path, options.packageRoot);+ const hostStateRoot = resolve(options.hostStateRoot ?? hypitHostStateRoot());+ const registry = options.registry ?? new RuntimeAdapterRegistry();+ await installRuntimeAdapters(registry, packageRoot, runtimePackageSelection(document), options.distributionPackageRoot);+ const activations = await activatedEndpoints(document, root, hostStateRoot, registry);+ const endpoints = await installedEndpointRegistry(document, activations);+ let stores: Awaited<ReturnType<typeof openCredentialStores>> | undefined;+ const openedStores = async () => stores ??= await openCredentialStores(document, root, hostStateRoot, registry);+ const result: RuntimeHostCapabilityPricing[] = [];+ try {+ for (const request of requests) {+ const base = {+ request: request.request,+ capability: structuredClone(request.capability),+ };+ const binding = document.bindings[capabilityKey(request.capability)];+ const bound = binding === undefined ? {} : { binding };+ const endpointRequest = {+ capability: request.capability,+ returns: request.returns,+ constraints: request.constraints,+ ...(request.pendingInputs === undefined ? {} : { pendingInputs: request.pendingInputs }),+ };+ const resolution = endpoints.resolve(endpointRequest);+ if (resolution.status === "missing") {+ result.push({+ ...base,+ status: "unresolved",+ ...bound,+ });+ continue;+ }+ if (resolution.status === "unsupported") {+ const endpoint = resolution.rejections.length === 1 ? resolution.rejections[0]!.endpointId : undefined;+ const match = endpoint === undefined ? undefined+ : activations.find(({ activation }) => activation.endpoint.instance.id === endpoint);+ const pricing = match?.activation.endpoint.pricing;+ result.push({+ ...base,+ status: "unsupported",+ ...(endpoint === undefined ? {} : { endpoint }),+ ...(match === undefined ? {} : { use: match.entry.use }),+ ...(pricing === undefined ? {} : { pricing: structuredClone(pricing) }),+ rejections: resolution.rejections.map((item) => ({ endpoint: item.endpointId, message: item.reason })),+ ...bound,+ });+ continue;+ }+ if (resolution.status === "ambiguous") {+ result.push({+ ...base,+ status: "ambiguous",+ endpoints: resolution.endpointIds,+ ...bound,+ });+ continue;+ }+ const match = activations.find(({ activation }) =>+ activation.endpoint.instance.id === resolution.registration.id);+ const pricing = match?.activation.endpoint.pricing;+ const selected = {+ ...base,+ status: "resolved" as const,+ endpoint: resolution.registration.id,+ ...(match === undefined ? {} : { use: match.entry.use }),+ ...(pricing === undefined ? {} : { pricing: structuredClone(pricing) }),+ ...bound,+ };+ if (pricing?.kind === "local" || match?.activation.endpoint.readPricing === undefined) {+ result.push(selected);+ continue;+ }+ try {+ const pricingDocuments = await match.activation.endpoint.readPricing({+ request: endpointRequest,+ credentials: async () => {+ const opened = await openedStores();+ return await resolveEndpointCredentials(match.activation.endpoint, opened.store, absolute);+ },+ });+ pricingDocuments.forEach(verifyEndpointPricingDocument);+ result.push({+ ...selected,+ ...(pricingDocuments.length === 0 ? {} : {+ pricingDocuments: structuredClone(pricingDocuments),+ }),+ });+ } catch (error) {+ result.push({+ ...selected,+ pricingError: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return result;+ } finally {+ await stores?.close();+ }+}+/*** Execute one immediate Need through the selected Profile, outside any Build.*@@ -691,6 +835,11 @@ export async function invokeRuntimeConfigNeed(? `No Endpoint in ${absolute} serves ${subject}; hypit plan --runtime ${absolute} shows which Endpoint each capability needs`: `${absolute} binds ${subject} to ${resolution.endpointId}, which does not serve this request; change that binding`);}+ if (resolution.status === "unsupported") {+ throw new Error(resolution.rejections+ .map((rejection) => `${rejection.endpointId} rejected ${subject}: ${rejection.reason}`)+ .join("; "));+ }if (resolution.status === "ambiguous") {throw new Error(`Several Endpoints in ${absolute} serve ${subject}: ${resolution.endpointIds.join(", ")}. `+ `Say which one does it: add "bindings": { "${subject}": "<instance>" } to the Profile`);@@ -703,23 +852,7 @@ export async function invokeRuntimeConfigNeed(if (activation === undefined) throw new Error(`Endpoint ${registration.id} is not declared by ${absolute}`);const stores = await openCredentialStores(document, root, hostStateRoot, registry);try {- const credentials: Record<string, EndpointCredential> = {};- for (const slot of activation.endpoint.credentials) {- const value = await stores.store.resolve(slot.ref);- if (value === undefined) {- throw new Error(`${slot.label} for Endpoint ${slot.endpoint} is not configured. ${- slot.ref.store === "env"- ? `Set ${slot.ref.key} in this process environment.`- : `Configure it with: hypit auth login ${slot.endpoint} --runtime ${absolute}`}`);- }- const writable = await writableCredentialStore(stores.store, slot.ref);- credentials[slot.slot] = {- ...value,- ...(writable === undefined ? {} : {- replace: async (replacement: CredentialValue) => await writable.put(slot.ref, replacement),- }),- };- }+ const credentials = await resolveEndpointCredentials(activation.endpoint, stores.store, absolute);return await registration.handler({command: { kind: "fulfill-need", id: `command:${need.id}`, need },need,diff --git a/packages/runtime-local/src/host.ts b/packages/runtime-local/src/host.tsindex 9265456d..1d3b3265 100644--- a/packages/runtime-local/src/host.ts+++ b/packages/runtime-local/src/host.ts@@ -17,6 +17,7 @@ import {openTransientRuntimeConfigExecution,prepareRuntimeConfigPackages,preflightRuntimeConfig,+ readRuntimeConfigPricing,resolveRuntimeConfigPaths,} from "./config.js";import {@@ -135,6 +136,10 @@ export async function openLocalRuntimeHost(packageRoot: basePackageRoot,...distribution,}),+ pricing: async (requests) => await readRuntimeConfigPricing(profile, requests, {+ packageRoot: basePackageRoot,+ ...distribution,+ }),invoke: async (need, resources) => await invokeRuntimeConfigNeed(profile, need, resources, {packageRoot: basePackageRoot,...distribution,diff --git a/packages/runtime-local/src/index.ts b/packages/runtime-local/src/index.tsindex 2b81382f..f2afab90 100644--- a/packages/runtime-local/src/index.ts+++ b/packages/runtime-local/src/index.ts@@ -22,6 +22,7 @@ export {openTransientRuntimeConfigExecution,prepareRuntimeConfigPackages,preflightRuntimeConfig,+ readRuntimeConfigPricing,parseLocalRuntimeProfile,resolveRuntimeConfigPaths,} from "./config.js";diff --git a/packages/runtime-local/test/config.test.ts b/packages/runtime-local/test/config.test.tsindex 9aab1147..9e1b9708 100644--- a/packages/runtime-local/test/config.test.ts+++ b/packages/runtime-local/test/config.test.ts@@ -39,6 +39,7 @@ import {openProjectBuildResultRepository,parseLocalRuntimeProfile,preflightRuntimeConfig,+ readRuntimeConfigPricing,} from "@hypit/runtime-local";function inlineString(value: unknown): string {@@ -381,6 +382,72 @@ test("Runtime providers name the selected Endpoint and its declared price source}});+test("Runtime pricing reads Provider-owned material with only the selected Endpoint's credentials", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-runtime-pricing-"));+ const path = join(root, "hypit.runtime.json");+ await writeFile(path, JSON.stringify(profile({+ dataRoot: ".",+ credentials: { secrets: { use: "example.credentials" } },+ endpoints: { paid: { use: "example.paid" }, local: { use: "example.local" } },+ })));+ const generate = { module: { name: "example.model", version: "1" }, name: "generate" } as const;+ const render = { module: { name: "example.render", version: "1" }, name: "render" } as const;+ const returns = { module: { name: "example.value", version: "1" }, name: "Output" } as const;+ const handler = () => ({ value: { kind: "inline" as const, value: null } });+ const registry = new RuntimeAdapterRegistry();+ registry.registerFacet(createRuntimeCredentialStoreAdapterFacet({+ use: "example.credentials",+ validate() {},+ open: () => ({ value: {+ async resolve(ref) {+ return ref.store === "secrets" && ref.key === "paid.key" ? { secret: "selected-key" } : undefined;+ },+ } }),+ }));+ registry.registerFacet(createRuntimeEndpointAdapterFacet({+ use: "example.paid",+ activate: (context) => ({ endpoint: defineEndpointPackage({+ module: { name: "example.provider", version: "1" }, facet: "paid",+ instance: context.instance, pool: context.pool ?? context.instance,+ credentials: { apiKey: credentialRef("secrets", "paid.key") },+ pricing: { kind: "page", url: "https://prices.example/models" },+ readPricing: async ({ request, credentials }) => {+ const resolved = await credentials();+ assert.equal(resolved.apiKey?.secret, "selected-key");+ assert.deepEqual(request.constraints, { seconds: 5 });+ return [{ source: "https://prices.example/models/generate", data: { usdPerSecond: 0.25 } }];+ },+ capabilities: [{ capability: generate, returns, lifecycle: "immediate", handler }],+ }) }),+ }));+ registry.registerFacet(createRuntimeEndpointAdapterFacet({+ use: "example.local",+ activate: (context) => ({ endpoint: defineEndpointPackage({+ module: { name: "example.local", version: "1" }, facet: "local",+ instance: context.instance, pool: context.pool ?? context.instance, pricing: { kind: "local" },+ capabilities: [{ capability: render, returns, lifecycle: "immediate", handler }],+ }) }),+ }));+ try {+ assert.deepEqual(await readRuntimeConfigPricing(path, [+ providerQuery("generate", generate, returns, { seconds: 5 }),+ providerQuery("render", render, returns, null),+ ], { registry }), [{+ request: "generate", capability: generate, status: "resolved", endpoint: "paid", use: "example.paid",+ pricing: { kind: "page", url: "https://prices.example/models" },+ pricingDocuments: [{+ source: "https://prices.example/models/generate",+ data: { usdPerSecond: 0.25 },+ }],+ }, {+ request: "render", capability: render, status: "resolved", endpoint: "local", use: "example.local",+ pricing: { kind: "local" },+ }]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});+test("transient execution follows capability opt-in rather than pricing and keeps Profile bindings", async () => {const root = await mkdtemp(join(tmpdir(), "hypit-runtime-transient-"));const path = join(root, "hypit.runtime.json");@@ -421,7 +488,9 @@ test("transient execution follows capability opt-in rather than pricing and keepreturns: greetingTypes.generated,lifecycle: "immediate",transient: true,- supports: (need) => (need.constraints as { readonly prompt?: unknown }).prompt === "Greet Ada",+ supports: (need) => (need.constraints as { readonly prompt?: unknown }).prompt === "Greet Ada"+ ? { status: "supported" }+ : { status: "unsupported", reason: "prompt must be Greet Ada" },handler: ({ need, credentials }) => {remoteCalls += 1;assert.deepEqual(need.constraints, { prompt: "Greet Ada" });@@ -535,7 +604,9 @@ test("Runtime provider inspection applies Endpoint supports when the complete rereturns,lifecycle: "immediate",supports: (need) => (need.constraints as { readonly allowed?: unknown } | null)?.allowed === true- && need.pendingInputs?.some((input) => input.role === "image") === true,+ && need.pendingInputs?.some((input) => input.role === "image") === true+ ? { status: "supported" }+ : { status: "unsupported", reason: "request needs allowed=true and a pending image input" },handler: () => ({ value: { kind: "inline", value: null } }),}],}),@@ -550,8 +621,24 @@ test("Runtime provider inspection applies Endpoint supports when the complete rependingInputs: [{ input: "reference", role: "image" }],},], { registry }), [- { request: "pending-file", capability, status: "unresolved" },- { request: "complete", capability, status: "unresolved" },+ {+ request: "pending-file",+ capability,+ status: "unsupported",+ endpoint: "narrow",+ use: "example.narrow",+ pricing: { kind: "local" },+ rejections: [{ endpoint: "narrow", message: "request needs allowed=true and a pending image input" }],+ },+ {+ request: "complete",+ capability,+ status: "unsupported",+ endpoint: "narrow",+ use: "example.narrow",+ pricing: { kind: "local" },+ rejections: [{ endpoint: "narrow", message: "request needs allowed=true and a pending image input" }],+ },{ request: "symbolic-resource", capability, status: "resolved", endpoint: "narrow", use: "example.narrow", pricing: { kind: "local" } },]);} finally {@@ -654,10 +741,6 @@ test("a Profile binds a contested capability to one of its Endpoints, and says s})), /names nowhere, which is not an Endpoint instance of this Profile \(paid\)/u);assert.throws(() => parseLocalRuntimeProfile(profile({ bindings: { "not a key": "paid" } })), /capability key/u);assert.throws(() => parseLocalRuntimeProfile({ ...profile(), stale: 1, older: 2 }), /does not accept stale, older; it accepts/u);- assert.throws(() => parseLocalRuntimeProfile({- format: "hypit.runtime-profile@1",- runtime: { use: "@hypit/runtime-local", config: {} },- }), /retired hypit.runtime-profile@1 shape/u);});test("providers, doctor and invoke share one resolver: a contested capability is ambiguous until the Profile binds it", async () => {diff --git a/packages/runtime/src/credentials.ts b/packages/runtime/src/credentials.tsindex 7877c4c6..81eeff5e 100644--- a/packages/runtime/src/credentials.ts+++ b/packages/runtime/src/credentials.ts@@ -46,6 +46,8 @@ export type CredentialAcquisition = {readonly tokenEndpoint: string;readonly clientId: string;readonly scopes: readonly string[];+ /** Maximum duration of the service-owned token exchange after browser authorization returns. */+ readonly requestTimeoutMs: number;};export type CredentialStore = {diff --git a/packages/video-cli/src/cli.ts b/packages/video-cli/src/cli.tsindex 8bd416fc..e136185e 100644--- a/packages/video-cli/src/cli.ts+++ b/packages/video-cli/src/cli.ts@@ -49,6 +49,7 @@ async function readSecret(prompt: string): Promise<string> {const io: CliIo = {write: (text) => process.stdout.write(text),+ writeProgress: (text) => process.stderr.write(text),setExitCode: (code) => { process.exitCode = code; },readSecret,terminal: {