Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

feat: add HypiHub Build pricing quotes (#179)

rponeawaa9a2a8eb7ec6
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index fe5f839c..9b17ac25 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -611,6 +611,7 @@ function assertCommandOptions(args: ParsedArgs): void {
break;
case "check":
case "plan":
+ case "quote":
add("--runtime", "--package-root", "--workspace", "--asset-root");
break;
case "build":
@@ -643,6 +644,7 @@ function usage(): string {
" hypit queue [--runtime profile.json] [--watch]",
" hypit check <self-described-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory]",
" hypit plan <run-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory]",
+ " hypit quote <run-source> --runtime profile.json",
" hypit build <run-source> [--runtime profile.json] [--workspace workspace] [--asset-root directory] [--follow]",
" hypit status <build-id> [--runtime profile.json] [--watch]",
" hypit builds [--runtime profile.json]",
@@ -952,7 +954,7 @@ export async function runCli(
let selectedRuntimeProjectRoot: string | undefined;
const commandProjectRoot = (): string => args.workspaceRoot
?? selectedRuntimeProjectRoot
- ?? ((args.command === "check" || args.command === "plan" || args.command === "build")
+ ?? ((args.command === "check" || args.command === "plan" || args.command === "build" || args.command === "quote")
&& args.file !== undefined
? dirname(resolve(args.file))
: process.cwd());
@@ -1052,7 +1054,7 @@ export async function runCli(
const runtimeWasExplicit = args.runtime !== undefined || positionalRuntime;
let runtimeNeedsHint = runtimeWasExplicit;
if (args.runtime === undefined && !positionalRuntime) {
- const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build";
+ const sourceScoped = args.command === "check" || args.command === "plan" || args.command === "build" || args.command === "quote";
const start = sourceScoped && args.file !== undefined ? dirname(resolve(args.file)) : process.cwd();
const selected = await findRuntimeProfile(start);
if (selected !== undefined) {
@@ -1064,7 +1066,7 @@ export async function runCli(
}
}
const known = args.command === "check" || args.command === "plan"
- || args.command === "build" || args.command === "status" || args.command === "builds"
+ || args.command === "build" || args.command === "quote" || args.command === "status" || args.command === "builds"
|| args.command === "history"
|| args.command === "inspect" || args.command === "get" || args.command === "cancel"
|| args.command === "doctor" || args.command === "programs"
@@ -1862,7 +1864,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 === "build" || args.command === "quote") && !runMode) {
throw new Error(`${args.command} requires a self-described Run Source; check Author Sources independently`);
}
if (args.command === "check") {
@@ -1918,6 +1920,47 @@ export async function runCli(
return;
}
}
+ if (args.command === "quote") {
+ if (args.runtime === undefined) {
+ throw new Error("quote requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");
+ }
+ const archive = lazyRuntimeArchive(await runtimeHost(args.runtime));
+ let loadedRun;
+ try {
+ loadedRun = await loadRunFile({
+ workspace,
+ authorCompiler: compiler,
+ frontends: runFrontends,
+ packageContributions,
+ runtime: archive,
+ });
+ } finally {
+ await archive.close();
+ }
+ const result = loadedRun.compiler.planCompilation(loadedRun);
+ const preflight = await preflightPlan(await runtimeHost(args.runtime), result.state);
+ assertPreflight(preflight);
+ const runtime = await loadRuntime(await runtimeHost(args.runtime));
+ try {
+ const quote = await runtime.quoteBuild({
+ definition: result.definition,
+ ...(loadedPackageSet === undefined ? {} : {
+ componentPackages: loadedPackageSet
+ .filter((item) => (item.contribution.components?.length ?? 0) > 0)
+ .map((item) => item.specifier),
+ }),
+ });
+ writeOperational(quote, "Build quote", "success", [
+ ["Credits", String(quote.totalCredits)],
+ ["USD", `$${quote.totalUsd}`],
+ ["Requests", String(quote.items.length)],
+ ], quote.items.map((item) =>
+ `${item.request} ${item.model} ${item.estimatedCredits} credits $${item.estimatedUsd}`));
+ } finally {
+ await runtime.close();
+ }
+ return;
+ }
if (args.command === "build") {
if (args.runtime === undefined) {
throw new Error("build requires a Runtime; run hypit runtime use <profile> or pass --runtime <profile>");
diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts
index f32025ef..c2dca121 100644
--- a/packages/cli/src/output.ts
+++ b/packages/cli/src/output.ts
@@ -586,6 +586,7 @@ export function writeCliHelp(io: CliIo, topic?: string): void {
colors.strong("Typical flow"),
row("runtime use <profile>", "select this project's execution environment", 40),
row("plan <run-source>", "see exactly what this Run will demand", 40),
+ row("quote <run-source>", "estimate the credits for this Build", 40),
row("build <run-source>", "submit durable work; add --follow to watch", 40),
row("get <build-id>", "read or copy an archived result", 40),
row("doctor [profile]", "diagnose deployment setup when needed", 40),
@@ -593,6 +594,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>", "freeze and inspect a Build plan"),
+ row("quote <run-source>", "estimate the credits for a Build"),
row("build <run-source>", "submit a durable Build; --follow only observes"),
row("image --prompt … --to <path>", "generate one picture file for a package asset"),
"",
diff --git a/packages/provider-hypihub/src/index.ts b/packages/provider-hypihub/src/index.ts
index b016ead7..c2be9d67 100644
--- a/packages/provider-hypihub/src/index.ts
+++ b/packages/provider-hypihub/src/index.ts
@@ -1,5 +1,7 @@
export { createHypiHubProvider, hypiHubProviderModuleRef } from "./provider.js";
export type { CreateHypiHubProviderOptions } from "./provider.js";
+export { createHypiHubPricingClient } from "./pricing.js";
+export type { HypiHubBuildQuote, HypiHubQuoteItem } from "./pricing.js";
export { createHypiHubGeminiGenerator } from "./gemini.js";
export type { HypiHubGeminiGenerateInput, HypiHubGeminiGeneratorOptions, HypiHubGeminiPart } from "./gemini.js";
export { interpretHypiHubWhisperXResponse } from "./whisperx.js";
diff --git a/packages/provider-hypihub/src/pricing.ts b/packages/provider-hypihub/src/pricing.ts
new file mode 100644
index 00000000..3f2dad48
--- /dev/null
+++ b/packages/provider-hypihub/src/pricing.ts
@@ -0,0 +1,110 @@
+import type { Need } from "@hypit/protocol";
+import type { CredentialRef, CredentialStore } from "@hypit/runtime";
+
+import { hypiHubRouteForCapability } from "./routes.js";
+
+export type HypiHubQuoteItem = {
+ readonly request: string;
+ readonly model: string;
+ readonly estimatedCredits: number;
+ readonly estimatedUsd: number;
+};
+
+export type HypiHubBuildQuote = {
+ readonly format: "hypit.build-quote@1";
+ readonly status: "complete";
+ readonly totalCredits: number;
+ readonly totalUsd: number;
+ readonly items: readonly HypiHubQuoteItem[];
+};
+
+type HypiHubPricingTransport = {
+ json(path: string, apiKey: string, init?: RequestInit): Promise<Record<string, unknown>>;
+};
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function object(value: unknown, subject: string): Record<string, unknown> {
+ assert(value !== null && typeof value === "object" && !Array.isArray(value), `${subject} must be an object`);
+ return value as Record<string, unknown>;
+}
+
+function finiteNumber(value: unknown, subject: string): number {
+ assert(typeof value === "number" && Number.isFinite(value), `${subject} is invalid`);
+ return value;
+}
+
+function capabilityKey(need: Need): string {
+ return `${need.capability.module.name}@${need.capability.module.version}#${need.capability.name}`;
+}
+
+async function quoteNeed(
+ transport: HypiHubPricingTransport,
+ apiKey: string,
+ need: Need,
+): Promise<HypiHubQuoteItem> {
+ const route = hypiHubRouteForCapability(need.capability);
+ assert(route !== undefined, `HypiHub cannot price capability ${capabilityKey(need)}`);
+ assert(route.media === "video", `HypiHub pricing does not support ${route.media} capability ${capabilityKey(need)}`);
+ const compiled = await route.compile(need.constraints, async () => "pricing-reference");
+ const input = object(compiled.input, `${need.id} pricing input`);
+ const seconds = input.seconds;
+ assert(typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0,
+ `HypiHub pricing requires a non-negative duration for ${need.id}`);
+ const dimensions: Record<string, unknown> = {};
+ if (typeof input.resolution === "string") dimensions.resolution = input.resolution;
+ const hasReferenceVideo = typeof input.ref_video_url === "string"
+ || (Array.isArray(input.reference_videos) && input.reference_videos.length > 0);
+ const response = await transport.json("/pricing/quote", apiKey, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ model: compiled.model,
+ units: { seconds },
+ dimensions: {
+ ...dimensions,
+ ...(hasReferenceVideo ? { flags: ["reference_video"] } : {}),
+ },
+ }),
+ });
+ return {
+ request: need.id,
+ model: compiled.model,
+ estimatedCredits: finiteNumber(response.estimated_credits, `${need.id}.estimated_credits`),
+ estimatedUsd: finiteNumber(response.estimated_usd, `${need.id}.estimated_usd`),
+ };
+}
+
+export function createHypiHubPricingClient(options: {
+ readonly client: HypiHubPricingTransport;
+ readonly apiKey: CredentialRef;
+}): {
+ quoteMany(needs: readonly Need[], credentials: CredentialStore): Promise<HypiHubBuildQuote>;
+} {
+ return {
+ async quoteMany(needs, credentials) {
+ if (needs.length === 0) {
+ return {
+ format: "hypit.build-quote@1",
+ status: "complete",
+ totalCredits: 0,
+ totalUsd: 0,
+ items: [],
+ };
+ }
+ const credential = await credentials.resolve(options.apiKey);
+ assert(credential !== undefined && credential.secret.length > 0,
+ "HypiHub login is unavailable; run hypit auth login for HypiHub");
+ const items = await Promise.all(needs.map((need) => quoteNeed(options.client, credential.secret, need)));
+ return {
+ format: "hypit.build-quote@1",
+ status: "complete",
+ totalCredits: items.reduce((total, item) => total + item.estimatedCredits, 0),
+ totalUsd: items.reduce((total, item) => total + item.estimatedUsd, 0),
+ items,
+ };
+ },
+ };
+}
diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.ts
index 3c1e97ad..560c3e4c 100644
--- a/packages/provider-hypihub/src/provider.ts
+++ b/packages/provider-hypihub/src/provider.ts
@@ -14,6 +14,7 @@ import { createHypiHubGeminiGenerator } from "./gemini.js";
import { hypiHubRouteForCapability, hypiHubRoutes } from "./routes.js";
import { HypiHubUploader } from "./upload.js";
import { transcribeWithHypiHub, whisperXAlignmentRequest } from "./whisperx.js";
+import { createHypiHubPricingClient } from "./pricing.js";
export const hypiHubProviderModuleRef = { name: "@hypit/provider-hypihub", version: "1" } as const;
@@ -293,9 +294,10 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
throw new Error(guidedMessage(error), { cause: error });
}
};
- return defineEndpointPackage({
+ const apiKey = options.apiKey ?? credentialRef("os", "hypihub.oauth");
+ const endpointPackage = defineEndpointPackage({
module: hypiHubProviderModuleRef, facet: "gateway", instance: options.instance ?? "hypihub.default", pool: options.pool ?? options.instance ?? "hypihub.default",
- credentials: { apiKey: options.apiKey ?? credentialRef("os", "hypihub.oauth") }, credentialInputs: { apiKey: { label: "HypiHub login" } }, defaultConcurrency: options.defaultConcurrency ?? 3,
+ credentials: { apiKey }, credentialInputs: { apiKey: { label: "HypiHub login" } }, defaultConcurrency: options.defaultConcurrency ?? 3,
capabilities: [
...hypiHubRoutes
.filter((route) => options.audio !== false || route.media !== "audio")
@@ -318,4 +320,5 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
},
],
});
+ return Object.assign(endpointPackage, createHypiHubPricingClient({ client, apiKey }));
}
diff --git a/packages/runtime-host-node/src/index.ts b/packages/runtime-host-node/src/index.ts
index 6ee93057..262fb4b4 100644
--- a/packages/runtime-host-node/src/index.ts
+++ b/packages/runtime-host-node/src/index.ts
@@ -23,6 +23,19 @@ export type RuntimeHostBuildSubmission = {
readonly dispatch: BuildDispatchSnapshot;
};
+export type RuntimeBuildQuote = {
+ readonly format: "hypit.build-quote@1";
+ readonly status: "complete";
+ readonly totalCredits: number;
+ readonly totalUsd: number;
+ readonly items: readonly {
+ readonly request: string;
+ readonly model: string;
+ readonly estimatedCredits: number;
+ readonly estimatedUsd: number;
+ }[];
+};
+
export type RuntimeHostStatus = {
readonly build: BuildSnapshot | undefined;
readonly catalog: BuildCatalogEntry | undefined;
@@ -73,6 +86,10 @@ export type RuntimeHostCredentialControl = {
};
export type RuntimeHostExecution = RuntimeHostArchive & RuntimeHostArtifactAccess & RuntimeHostCredentialControl & {
+ quoteBuild(request: {
+ readonly definition: BuildDefinition;
+ readonly componentPackages?: readonly string[];
+ }): Promise<RuntimeBuildQuote>;
build(request: {
readonly id: string;
readonly definition: BuildDefinition;
diff --git a/packages/runtime-local/package.json b/packages/runtime-local/package.json
index 71fece7b..8643dd00 100644
--- a/packages/runtime-local/package.json
+++ b/packages/runtime-local/package.json
@@ -11,6 +11,7 @@
"./worker-process": "./src/worker-process.ts"
},
"dependencies": {
+ "@hypit/core": "workspace:*",
"@hypit/component-kit": "workspace:*",
"@hypit/driver-node": "workspace:*",
"@hypit/endpoint-kit": "workspace:*",
@@ -24,7 +25,6 @@
},
"devDependencies": {
"@hypit/artifact-store-fs": "workspace:*",
- "@hypit/credential-store-env": "workspace:*",
- "@hypit/core": "workspace:*"
+ "@hypit/credential-store-env": "workspace:*"
}
}
diff --git a/packages/runtime-local/src/runtime.ts b/packages/runtime-local/src/runtime.ts
index 0fd25c30..46709f89 100644
--- a/packages/runtime-local/src/runtime.ts
+++ b/packages/runtime-local/src/runtime.ts
@@ -10,6 +10,9 @@ import {
import {
isStreamingArtifactStore,
} from "@hypit/runtime";
+import { materializeBuild } from "@hypit/core";
+import { reduce } from "@hypit/core";
+import type { Need } from "@hypit/protocol";
import { TypeValidatorRegistry } from "@hypit/validation";
import { createLocalRuntimeArchiveControl, createLocalRuntimeArtifactAccess } from "./control.js";
@@ -18,11 +21,16 @@ import { createDurableLocalWorker } from "./worker.js";
import type {
CreateLocalRuntimeOptions,
LocalBuildOptions,
+ LocalBuildQuote,
LocalBuildRequest,
LocalBuildSubmission,
LocalRuntime,
} from "./types.js";
+type PricingEndpoint = import("@hypit/endpoint-kit").EndpointPackage & {
+ quoteMany?: (needs: readonly Need[], credentials: import("@hypit/runtime").CredentialStore) => Promise<LocalBuildQuote>;
+};
+
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
@@ -111,6 +119,58 @@ export async function createLocalRuntime(
const artifacts = createLocalRuntimeArtifactAccess({
artifactStore: options.artifactStore,
});
+ const quoteBuild = async (request: LocalBuildRequest): Promise<LocalBuildQuote> => {
+ await installComponentPackages(request.componentPackages ?? []);
+ const dryDriver = new NodeDriver({
+ producers,
+ endpoints: new EndpointRegistry(),
+ artifacts: options.artifactStore,
+ credentials: options.credentialStore,
+ validators,
+ });
+ let state = materializeBuild(request.definition, []);
+ while (true) {
+ if (state.outstanding.length > 0) state = { ...state, outstanding: [] };
+ const prepared = dryDriver.prepare(state);
+ const producer = prepared.runnable.find((item) => item.command.kind === "invoke-producer");
+ if (producer === undefined) {
+ state = prepared.state;
+ break;
+ }
+ const execution = await dryDriver.executeCommand(prepared.state, producer, { build: "quote" });
+ if (execution.status !== "completed") throw new Error("Build quote expansion reached a non-local operation");
+ state = reduce(prepared.state, execution.event);
+ }
+ if (state.status === "failed") {
+ throw new Error(state.diagnostics.at(-1)?.message ?? "Build quote expansion failed");
+ }
+ if (state.steps.some((step) => step.status === "pending")) {
+ throw new Error("Build quote is not fully determined before a paid result");
+ }
+ const grouped = new Map<PricingEndpoint, Need[]>();
+ for (const need of state.needs) {
+ const endpoint = (options.endpoints ?? []).find((item) => item.offers.some((offer) =>
+ offer.capability.module.name === need.capability.module.name
+ && offer.capability.module.version === need.capability.module.version
+ && offer.capability.name === need.capability.name
+ && offer.returns.module.name === need.returns.module.name
+ && offer.returns.module.version === need.returns.module.version
+ && offer.returns.name === need.returns.name)) as PricingEndpoint | undefined;
+ if (endpoint === undefined || endpoint.quoteMany === undefined) {
+ throw new Error(`No pricing service is available for ${need.capability.name}`);
+ }
+ grouped.set(endpoint, [...grouped.get(endpoint) ?? [], need]);
+ }
+ const quotes = await Promise.all([...grouped.entries()].map(([endpoint, needs]) =>
+ endpoint.quoteMany!(needs, options.credentialStore)));
+ return {
+ format: "hypit.build-quote@1",
+ status: "complete",
+ totalCredits: quotes.reduce((total, quote) => total + quote.totalCredits, 0),
+ totalUsd: quotes.reduce((total, quote) => total + quote.totalUsd, 0),
+ items: quotes.flatMap((quote) => quote.items),
+ };
+ };
const stageAttachments = async (request: LocalBuildRequest): Promise<void> => {
for (const item of request.attachments ?? []) {
if (await options.artifactStore.has(item.artifact.digest)) continue;
@@ -190,6 +250,7 @@ export async function createLocalRuntime(
...archive,
...artifacts,
...credentialControl,
+ quoteBuild,
build: runBuild,
async workOnce() {
return await worker.runOnce();
diff --git a/packages/runtime-local/src/types.ts b/packages/runtime-local/src/types.ts
index 27be64a6..7b560648 100644
--- a/packages/runtime-local/src/types.ts
+++ b/packages/runtime-local/src/types.ts
@@ -14,6 +14,7 @@ import type {
RuntimeHostArchive,
RuntimeHostArtifactAccess,
RuntimeHostBuildSubmission,
+ RuntimeBuildQuote,
RuntimeHostCredentialControl,
RuntimeHostExecution,
} from "@hypit/runtime-host-node";
@@ -57,6 +58,7 @@ export type CreateLocalCredentialControlOptions = {
export type LocalBuildRequest = Parameters<RuntimeHostExecution["build"]>[0];
export type LocalBuildOptions = Parameters<RuntimeHostExecution["build"]>[1];
export type LocalBuildSubmission = RuntimeHostBuildSubmission;
+export type LocalBuildQuote = RuntimeBuildQuote;
export type LocalRuntime = RuntimeHostExecution & {
workOnce(): Promise<BuildDispatchSnapshot | undefined>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c2e63cbc..b8dcd665 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2629,6 +2629,9 @@ importers:
'@hypit/component-kit':
specifier: workspace:*
version: link:../component-kit
+ '@hypit/core':
+ specifier: workspace:*
+ version: link:../core
'@hypit/driver-node':
specifier: workspace:*
version: link:../driver-node
@@ -2660,9 +2663,6 @@ importers:
'@hypit/artifact-store-fs':
specifier: workspace:*
version: link:../artifact-store-fs
- '@hypit/core':
- specifier: workspace:*
- version: link:../core
'@hypit/credential-store-env':
specifier: workspace:*
version: link:../credential-store-env
diff --git a/skills/hypit/references/studio-confirmation.md b/skills/hypit/references/studio-confirmation.md
index 666e563c..b0afec95 100644
--- a/skills/hypit/references/studio-confirmation.md
+++ b/skills/hypit/references/studio-confirmation.md
@@ -31,6 +31,27 @@ After the route-specific final check passes, but before submitting any paid Buil
intended result are acceptable for paid generation.
5. Do not submit `hypit build` until the author explicitly accepts and confirms the cost.
+Before asking for that confirmation, when the author asks how many credits or how much money the Build
+will use, obtain one complete quote for the exact Run and Runtime Profile:
+
+```bash
+hypit quote <run-source> --runtime <profile>
+```
+
+The Agent calls this one high-level command. It must not call HypiHub `/v1/pricing/quote` itself for
+each request, ask the author to calculate individual requests, or estimate from a prompt. The Runtime
+compiles the Run, expands deterministic local Producers in memory, collects every resulting paid Need,
+and the selected HypiHub Provider submits the corresponding pricing requests and aggregates the total
+credits, USD amount and per-request details. Seedance reference-video requests are quoted with the
+`reference_video` pricing flag automatically.
+
+`hypit quote` is read-only with respect to Build execution: it does not submit a Build, create durable
+Build/Dispatch/Operation state, start a Worker, or consume generated media. Use its returned total as
+the amount presented to the author, together with the selected Provider and credential source, then ask
+for confirmation before running `hypit build`. If the quote cannot be completed because a required
+pricing service or credential is unavailable, report that the cost is unknown and do not submit the
+paid Build.
+
If the author does not accept, do not Build. Capture the requested change and enter `revision/route.md`.
Revision edits Source/Recipe/Run and reruns deterministic gates; it does not ask an agent or VLM to
judge the picture.