@fungi.computer/darkroom 0.5.12 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -0
- package/dist/app-media-contracts.d.ts +4 -0
- package/dist/browser-failure.d.ts +2 -0
- package/dist/browser-failure.js +2 -0
- package/dist/cloudflare/provider.js +3 -3
- package/dist/cloudflare/reference-images.d.ts +6 -0
- package/dist/cloudflare/reference-images.js +25 -7
- package/dist/cost-estimate.js +2 -2
- package/dist/daily-media-meter.d.ts +55 -0
- package/dist/daily-media-meter.js +81 -0
- package/dist/execution-error.d.ts +1 -1
- package/dist/gateway-models.d.ts +8 -2
- package/dist/gateway-models.js +35 -10
- package/dist/gateway-wire.d.ts +1 -0
- package/dist/gateway-wire.js +2 -0
- package/dist/index.d.ts +50 -12
- package/dist/index.js +33 -23
- package/dist/media-binding.d.ts +3 -0
- package/dist/media-binding.js +3 -3
- package/dist/media-generation.js +9 -5
- package/dist/media-operation-contract.d.ts +3 -1
- package/dist/media-operation-do.d.ts +13 -2
- package/dist/media-operation-do.js +26 -1
- package/dist/media-operation-owner.d.ts +8 -0
- package/dist/media-operation-owner.js +8 -5
- package/dist/media-operation.js +2 -2
- package/dist/media-quote.d.ts +14 -0
- package/dist/media-quote.js +17 -0
- package/dist/model-catalog.d.ts +438 -5
- package/dist/model-catalog.js +232 -30
- package/dist/reference-image-size.d.ts +4 -3
- package/dist/reference-image-size.js +9 -9
- package/dist/server.d.ts +17 -1
- package/dist/server.js +44 -6
- package/docs/api/app-media-contracts.md +4 -0
- package/docs/api/browser.md +4 -2
- package/docs/api/cloudflare.md +53 -0
- package/docs/api/index.md +464 -55
- package/docs/api/server.md +214 -22
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -133,6 +133,135 @@ fact.
|
|
|
133
133
|
Video generation runs through the operation's alarm. A 202 response tells you to
|
|
134
134
|
retry the same request ID after the supplied `Retry-After` delay.
|
|
135
135
|
|
|
136
|
+
## Bring your own provider and models
|
|
137
|
+
|
|
138
|
+
A provider owns its model list. The built-in Fungi gateway provider carries
|
|
139
|
+
today's catalogue; a host that injects its own `MediaProvider` also supplies
|
|
140
|
+
that provider's catalogue, as data decoded with `parseMediaCatalogue`. Darkroom
|
|
141
|
+
validates every request against the active provider's catalogue, so `fal-ai/...`
|
|
142
|
+
ids are accepted by your provider and refused by the gateway's.
|
|
143
|
+
|
|
144
|
+
Each entry carries the per-model bounds the validator enforces: prompt length,
|
|
145
|
+
dimensions or exact sizes, steps, reference counts, and for video the durations,
|
|
146
|
+
resolution/aspect formats and per-second prices. Mark a video model's
|
|
147
|
+
`video.provider` as `"host"`: your provider owns that model's wire grammar.
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import {
|
|
151
|
+
parseMediaCatalogue,
|
|
152
|
+
type MediaProvider,
|
|
153
|
+
} from "@fungi.computer/darkroom";
|
|
154
|
+
import { createMediaService } from "@fungi.computer/darkroom/server";
|
|
155
|
+
import { MediaOperationDO } from "@fungi.computer/darkroom/cloudflare";
|
|
156
|
+
|
|
157
|
+
declare const FAL_KEY: string; // your fal.ai key, from the host environment
|
|
158
|
+
|
|
159
|
+
// Decoded once; throws MediaSettingsError on a malformed or contradictory entry.
|
|
160
|
+
export const falCatalogue = parseMediaCatalogue([
|
|
161
|
+
{
|
|
162
|
+
id: "fal-ai/minimax/hailuo-2.3/standard/image-to-video",
|
|
163
|
+
label: "Hailuo 2.3 Standard",
|
|
164
|
+
kind: "video",
|
|
165
|
+
tier: "draft",
|
|
166
|
+
outputFormats: [],
|
|
167
|
+
maxPromptLength: 2_000,
|
|
168
|
+
sizes: ["1366x768"],
|
|
169
|
+
input: {
|
|
170
|
+
transport: "json",
|
|
171
|
+
dimensions: "own",
|
|
172
|
+
maxDimension: 1366,
|
|
173
|
+
maxDimensionDocumented: false,
|
|
174
|
+
defaultWidth: 1366,
|
|
175
|
+
defaultHeight: 768,
|
|
176
|
+
steps: "fixed",
|
|
177
|
+
maxSteps: null,
|
|
178
|
+
defaultSteps: null,
|
|
179
|
+
referenceField: "image_url",
|
|
180
|
+
maxReferences: 1,
|
|
181
|
+
referenceDimension: null,
|
|
182
|
+
referenceFormat: "png",
|
|
183
|
+
},
|
|
184
|
+
video: {
|
|
185
|
+
minSeconds: 6,
|
|
186
|
+
maxSeconds: 10,
|
|
187
|
+
defaultSeconds: 6,
|
|
188
|
+
durations: [6, 10],
|
|
189
|
+
provider: "host",
|
|
190
|
+
formats: [
|
|
191
|
+
{ resolution: "768p", aspectRatio: "16:9", width: 1366, height: 768 },
|
|
192
|
+
],
|
|
193
|
+
defaultResolution: "768p",
|
|
194
|
+
defaultAspectRatio: "16:9",
|
|
195
|
+
supportsAudio: false,
|
|
196
|
+
defaultGenerateAudio: null,
|
|
197
|
+
referenceRoles: ["first-frame"],
|
|
198
|
+
maxReferenceImages: 0,
|
|
199
|
+
referenceResolutions: [],
|
|
200
|
+
prices: [
|
|
201
|
+
{
|
|
202
|
+
resolution: "768p",
|
|
203
|
+
silentMilliunitsPerSecond: 3_000,
|
|
204
|
+
audioMilliunitsPerSecond: 3_000,
|
|
205
|
+
},
|
|
206
|
+
],
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
]);
|
|
210
|
+
|
|
211
|
+
// Settings arrive already validated against falCatalogue.
|
|
212
|
+
export const falProvider: MediaProvider = async (
|
|
213
|
+
settings,
|
|
214
|
+
references,
|
|
215
|
+
signal,
|
|
216
|
+
) => {
|
|
217
|
+
const first = references[0];
|
|
218
|
+
if (first === undefined)
|
|
219
|
+
throw new Error("image-to-video needs a first frame");
|
|
220
|
+
const queued = await fetch(`https://queue.fal.run/${settings.model}`, {
|
|
221
|
+
method: "POST",
|
|
222
|
+
headers: {
|
|
223
|
+
Authorization: `Key ${FAL_KEY}`,
|
|
224
|
+
"Content-Type": "application/json",
|
|
225
|
+
},
|
|
226
|
+
body: JSON.stringify({
|
|
227
|
+
prompt: settings.prompt,
|
|
228
|
+
duration: String(settings.durationSeconds),
|
|
229
|
+
image_url: `data:image/${first.format};base64,${btoa(String.fromCharCode(...first.bytes))}`,
|
|
230
|
+
}),
|
|
231
|
+
signal: signal ?? null,
|
|
232
|
+
});
|
|
233
|
+
// ...poll the queue, download the MP4 and return it.
|
|
234
|
+
return {
|
|
235
|
+
bytes: new Uint8Array(await (await queued.blob()).arrayBuffer()),
|
|
236
|
+
format: "mp4",
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// The durable job engine runs your provider from its alarm, so it needs the
|
|
241
|
+
// same catalogue.
|
|
242
|
+
export class FalMediaOperationDO extends MediaOperationDO {
|
|
243
|
+
protected override mediaProvider() {
|
|
244
|
+
return falProvider;
|
|
245
|
+
}
|
|
246
|
+
protected override mediaCatalogue() {
|
|
247
|
+
return falCatalogue;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// In the request path, pass the catalogue and your own quote beside the provider.
|
|
252
|
+
const service = createMediaService({
|
|
253
|
+
// scope, operations, metering and destination as in the quick start
|
|
254
|
+
provider: falProvider,
|
|
255
|
+
catalogue: falCatalogue,
|
|
256
|
+
estimate: (settings) => 3_000 * (settings.durationSeconds ?? 6),
|
|
257
|
+
// ...
|
|
258
|
+
});
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
`GET /models` lists `falCatalogue`. A request for a model outside it, or
|
|
262
|
+
settings outside its bounds, is refused before billing or dispatch. The
|
|
263
|
+
gateway's own models are refused by this provider the same way.
|
|
264
|
+
|
|
136
265
|
## API reference
|
|
137
266
|
|
|
138
267
|
| Import | Purpose |
|
|
@@ -464,6 +464,7 @@ export declare const agentAppMediaLibraryFailureSchema: z.ZodLazy<z.ZodObject<{
|
|
|
464
464
|
export declare const appMediaBrokerFailureSchema: z.ZodObject<{
|
|
465
465
|
error: z.ZodEnum<{
|
|
466
466
|
readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
|
|
467
|
+
readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
|
|
467
468
|
readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
|
|
468
469
|
readonly HOST_FAILURE: "HOST_FAILURE";
|
|
469
470
|
readonly INVALID_ARGUMENT: "INVALID_ARGUMENT";
|
|
@@ -514,6 +515,7 @@ export declare const appMediaRefusalSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
514
515
|
}, z.core.$strict>>, z.ZodObject<{
|
|
515
516
|
error: z.ZodEnum<{
|
|
516
517
|
readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
|
|
518
|
+
readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
|
|
517
519
|
readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
|
|
518
520
|
readonly HOST_FAILURE: "HOST_FAILURE";
|
|
519
521
|
readonly INVALID_ARGUMENT: "INVALID_ARGUMENT";
|
|
@@ -729,6 +731,7 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
|
|
|
729
731
|
}, z.core.$strict>>, z.ZodObject<{
|
|
730
732
|
error: z.ZodEnum<{
|
|
731
733
|
readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
|
|
734
|
+
readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
|
|
732
735
|
readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
|
|
733
736
|
readonly HOST_FAILURE: "HOST_FAILURE";
|
|
734
737
|
readonly INVALID_ARGUMENT: "INVALID_ARGUMENT";
|
|
@@ -799,6 +802,7 @@ export declare const appMediaGenerationOutcomeSchema: z.ZodUnion<readonly [z.Zod
|
|
|
799
802
|
}, z.core.$strict>>, z.ZodObject<{
|
|
800
803
|
error: z.ZodEnum<{
|
|
801
804
|
readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
|
|
805
|
+
readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
|
|
802
806
|
readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
|
|
803
807
|
readonly HOST_FAILURE: "HOST_FAILURE";
|
|
804
808
|
readonly INVALID_ARGUMENT: "INVALID_ARGUMENT";
|
|
@@ -23,6 +23,8 @@ export declare const mediaFailureSchema: z.ZodObject<{
|
|
|
23
23
|
code: z.ZodEnum<{
|
|
24
24
|
/** Host admission or Computer access was denied. */
|
|
25
25
|
readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
|
|
26
|
+
/** The host's daily media spending limit is used up until 00:00 UTC. */
|
|
27
|
+
readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
|
|
26
28
|
/** Host billing did not admit this attempt. */
|
|
27
29
|
readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
|
|
28
30
|
/** The host could not complete generation or saving. */
|
package/dist/browser-failure.js
CHANGED
|
@@ -13,6 +13,8 @@ export const mediaFailureSchema = z.strictObject({
|
|
|
13
13
|
code: z.enum({
|
|
14
14
|
/** Host admission or Computer access was denied. */
|
|
15
15
|
CAPABILITY_DENIED: "CAPABILITY_DENIED",
|
|
16
|
+
/** The host's daily media spending limit is used up until 00:00 UTC. */
|
|
17
|
+
DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED",
|
|
16
18
|
/** Host billing did not admit this attempt. */
|
|
17
19
|
INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT",
|
|
18
20
|
/** The host could not complete generation or saving. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import * as Redacted from "effect/Redacted";
|
|
3
|
-
import { buildProviderInput,
|
|
3
|
+
import { buildProviderInput, getGatewayModel, estimateImageMilliunits, normalizeMediaProviderOutput, mediaProviderWireSchema, validateMediaGenerationSettings, } from "../index.js";
|
|
4
4
|
import { MediaExecutionError, MediaSafetyFilterRefusal, } from "../execution-error.js";
|
|
5
5
|
import { decodeMediaProviderErrorCategory, } from "@fungi.computer/agar/errors";
|
|
6
6
|
import { estimateGatewayMilliunits, gatewayInput, isGatewayModel, } from "../gateway-models.js";
|
|
@@ -144,7 +144,7 @@ async function generateThroughGateway(ai, settings, references, signal, options,
|
|
|
144
144
|
catch (cause) {
|
|
145
145
|
throw providerFailure(settings.model, cause);
|
|
146
146
|
}
|
|
147
|
-
const model =
|
|
147
|
+
const model = getGatewayModel(settings.model);
|
|
148
148
|
const video = model?.kind === "video";
|
|
149
149
|
try {
|
|
150
150
|
if (video) {
|
|
@@ -163,7 +163,7 @@ async function generateThroughGateway(ai, settings, references, signal, options,
|
|
|
163
163
|
}
|
|
164
164
|
const parsed = gatewayOutputSchema.parse(providerValue);
|
|
165
165
|
return await normalizeMediaProviderOutput(mediaProviderWireSchema.parse({
|
|
166
|
-
images: [{ url: parsed.result.image }],
|
|
166
|
+
images: [{ url: parsed.result.image ?? parsed.result.images?.[0] }],
|
|
167
167
|
}), { fetchUrl: (url) => fetchResult(url, { signal: signal ?? null }) });
|
|
168
168
|
}
|
|
169
169
|
catch (cause) {
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { type ImageViewFitter, type ReferenceImageFitter } from "../index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Cloudflare answers the Images binding with error 9432 ("not available using
|
|
4
|
+
* legacy billing") when the account has not moved to the current billing
|
|
5
|
+
* model. Say what to do, not the raw binding failure.
|
|
6
|
+
*/
|
|
7
|
+
export declare const imagesLegacyBillingMessage = "Cloudflare Images is not available on this Cloudflare account because it is on legacy billing (Cloudflare error 9432). Reference images need the Images binding. Update the account's billing in the Cloudflare dashboard, or generate without reference images.";
|
|
2
8
|
/** Only image metadata and the bounded resize chain are consumed by Media. */
|
|
3
9
|
export type MediaImagePort = {
|
|
4
10
|
/** Read decoded image metadata through the Images binding. */
|
|
@@ -16,6 +16,19 @@ const formats = {
|
|
|
16
16
|
"image/gif": "gif",
|
|
17
17
|
"image/webp": "webp",
|
|
18
18
|
};
|
|
19
|
+
/**
|
|
20
|
+
* Cloudflare answers the Images binding with error 9432 ("not available using
|
|
21
|
+
* legacy billing") when the account has not moved to the current billing
|
|
22
|
+
* model. Say what to do, not the raw binding failure.
|
|
23
|
+
*/
|
|
24
|
+
export const imagesLegacyBillingMessage = "Cloudflare Images is not available on this Cloudflare account because it is on legacy billing (Cloudflare error 9432). Reference images need the Images binding. Update the account's billing in the Cloudflare dashboard, or generate without reference images.";
|
|
25
|
+
/** The Images binding's `ImagesError` carries Cloudflare's numeric error code. */
|
|
26
|
+
const legacyBillingFailure = z.object({ code: z.literal(9432) });
|
|
27
|
+
function legacyBillingRefusal(cause) {
|
|
28
|
+
return legacyBillingFailure.safeParse(cause).success
|
|
29
|
+
? new MediaSettingsError(imagesLegacyBillingMessage)
|
|
30
|
+
: undefined;
|
|
31
|
+
}
|
|
19
32
|
const stream = (bytes) => new ReadableStream({
|
|
20
33
|
start(controller) {
|
|
21
34
|
controller.enqueue(bytes.slice());
|
|
@@ -34,9 +47,10 @@ export function createImagesReferenceFitter(images) {
|
|
|
34
47
|
try {
|
|
35
48
|
info = metadata.parse(await images.info(stream(bytes)));
|
|
36
49
|
}
|
|
37
|
-
catch {
|
|
38
|
-
//
|
|
39
|
-
throw
|
|
50
|
+
catch (cause) {
|
|
51
|
+
// Other Images failure detail is never surfaced; the caller's bytes are.
|
|
52
|
+
throw (legacyBillingRefusal(cause) ??
|
|
53
|
+
new MediaSettingsError("reference image is not a supported image"));
|
|
40
54
|
}
|
|
41
55
|
const transform = referenceImageTransform(model, info.width, info.height);
|
|
42
56
|
const target = referenceImageFormat(model);
|
|
@@ -48,7 +62,10 @@ export function createImagesReferenceFitter(images) {
|
|
|
48
62
|
.transform(transform)
|
|
49
63
|
.output(target === "image/webp"
|
|
50
64
|
? { format: target, quality: REFERENCE_WEBP_QUALITY }
|
|
51
|
-
: { format: target })
|
|
65
|
+
: { format: target })
|
|
66
|
+
.catch((cause) => {
|
|
67
|
+
throw legacyBillingRefusal(cause) ?? cause;
|
|
68
|
+
});
|
|
52
69
|
bytes = new Uint8Array(await output.response().arrayBuffer());
|
|
53
70
|
if (bytes.byteLength === 0 || bytes.byteLength > MAX_REFERENCE_BYTES)
|
|
54
71
|
throw new MediaSettingsError("reference image exceeds the byte limit");
|
|
@@ -75,9 +92,10 @@ export function createImagesViewFitter(images) {
|
|
|
75
92
|
try {
|
|
76
93
|
metadata.parse(await images.info(stream(input)));
|
|
77
94
|
}
|
|
78
|
-
catch {
|
|
79
|
-
//
|
|
80
|
-
throw
|
|
95
|
+
catch (cause) {
|
|
96
|
+
// Other Images failure detail is never surfaced.
|
|
97
|
+
throw (legacyBillingRefusal(cause) ??
|
|
98
|
+
new MediaSettingsError("image is not a supported image"));
|
|
81
99
|
}
|
|
82
100
|
const output = await images
|
|
83
101
|
.input(stream(input))
|
package/dist/cost-estimate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getGatewayModel, MAX_REFERENCE_COUNT, MediaSettingsError, } from "./model-catalog.js";
|
|
2
2
|
import { neuronsToMilliunits } from "./neurons.js";
|
|
3
3
|
import * as z from "zod";
|
|
4
4
|
const TILE = 512;
|
|
@@ -29,7 +29,7 @@ const checked = (modelId, params) => {
|
|
|
29
29
|
return invalid("dimensions, steps, or references are invalid");
|
|
30
30
|
const candidate = parsed.data;
|
|
31
31
|
const references = candidate.references ?? [];
|
|
32
|
-
const model =
|
|
32
|
+
const model = getGatewayModel(modelId);
|
|
33
33
|
if (model === undefined)
|
|
34
34
|
throw new MediaSettingsError(`Image cost unknown for model "${modelId}"`);
|
|
35
35
|
if (references.length > model.input.maxReferences)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { MediaMetering } from "./media-operation-contract.js";
|
|
2
|
+
/** The Durable Object storage slice the meter owns tables in. */
|
|
3
|
+
export type DailyMediaMeterStorage = Readonly<{
|
|
4
|
+
/** SQLite access owned by the Durable Object. */
|
|
5
|
+
sql: Readonly<{
|
|
6
|
+
/** Run one statement with positional bindings. */
|
|
7
|
+
exec: (query: string, ...bindings: readonly (string | number)[]) => Readonly<{
|
|
8
|
+
/** Read every returned row. */
|
|
9
|
+
toArray: () => readonly unknown[];
|
|
10
|
+
}>;
|
|
11
|
+
}>;
|
|
12
|
+
/** Run the body in one synchronous transaction. */
|
|
13
|
+
transactionSync: <T>(body: () => T) => T;
|
|
14
|
+
}>;
|
|
15
|
+
/** RPC surface of the Durable Object that owns one Oyster's daily media total. */
|
|
16
|
+
export type DailyMediaMeterPort = Readonly<{
|
|
17
|
+
/** Hold one generation's provider cost against today's limit; false when it would exceed it. */
|
|
18
|
+
dailyAdmit: (input: Readonly<{
|
|
19
|
+
operationId: string;
|
|
20
|
+
costMilliunits: number;
|
|
21
|
+
limitMilliunits: number;
|
|
22
|
+
}>) => Promise<boolean> | boolean;
|
|
23
|
+
/** Release the hold when nothing was delivered, or keep it once delivered. */
|
|
24
|
+
dailySettle: (input: Readonly<{
|
|
25
|
+
operationId: string;
|
|
26
|
+
delivered: boolean;
|
|
27
|
+
}>) => Promise<void> | void;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* A UTC-day total of admitted media cost, kept in one Durable Object's SQLite.
|
|
31
|
+
* Every statement runs inside one synchronous transaction, so two concurrent
|
|
32
|
+
* admits near the limit are serialized by the object and cannot both pass.
|
|
33
|
+
* Holds are keyed by the durable operation id, so a retried admit never counts
|
|
34
|
+
* twice. A hold that is never settled stays counted until its day ends.
|
|
35
|
+
*/
|
|
36
|
+
export declare class DailyMediaMeter {
|
|
37
|
+
private readonly storage;
|
|
38
|
+
private readonly now;
|
|
39
|
+
private ready;
|
|
40
|
+
constructor(storage: DailyMediaMeterStorage, now?: () => number);
|
|
41
|
+
private ensureSchema;
|
|
42
|
+
/** Hold `costMilliunits` for this operation unless the day's total would exceed the limit. */
|
|
43
|
+
admit(input: Readonly<{
|
|
44
|
+
operationId: string;
|
|
45
|
+
costMilliunits: number;
|
|
46
|
+
limitMilliunits: number;
|
|
47
|
+
}>): boolean;
|
|
48
|
+
/** Keep the hold when media was delivered; release it when nothing was. */
|
|
49
|
+
settle(input: Readonly<{
|
|
50
|
+
operationId: string;
|
|
51
|
+
delivered: boolean;
|
|
52
|
+
}>): void;
|
|
53
|
+
}
|
|
54
|
+
/** `MediaMetering` that enforces one exact daily limit through the owning object. */
|
|
55
|
+
export declare function createDailyMediaMetering(meter: DailyMediaMeterPort, limitMilliunits: number): MediaMetering;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { MediaBillingRefusal } from "./execution-error.js";
|
|
3
|
+
const totalRowSchema = z.strictObject({ total: z.number() });
|
|
4
|
+
const MS_PER_DAY = 86_400_000;
|
|
5
|
+
/** The UTC day number a timestamp falls in; the total resets when it changes. */
|
|
6
|
+
function utcDay(timestamp) {
|
|
7
|
+
return Math.floor(timestamp / MS_PER_DAY);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A UTC-day total of admitted media cost, kept in one Durable Object's SQLite.
|
|
11
|
+
* Every statement runs inside one synchronous transaction, so two concurrent
|
|
12
|
+
* admits near the limit are serialized by the object and cannot both pass.
|
|
13
|
+
* Holds are keyed by the durable operation id, so a retried admit never counts
|
|
14
|
+
* twice. A hold that is never settled stays counted until its day ends.
|
|
15
|
+
*/
|
|
16
|
+
export class DailyMediaMeter {
|
|
17
|
+
storage;
|
|
18
|
+
now;
|
|
19
|
+
ready = false;
|
|
20
|
+
constructor(storage, now = Date.now) {
|
|
21
|
+
this.storage = storage;
|
|
22
|
+
this.now = now;
|
|
23
|
+
}
|
|
24
|
+
ensureSchema() {
|
|
25
|
+
if (this.ready)
|
|
26
|
+
return;
|
|
27
|
+
this.storage.sql.exec("CREATE TABLE IF NOT EXISTS daily_media_hold (operation_id TEXT PRIMARY KEY, day INTEGER NOT NULL, milliunits INTEGER NOT NULL CHECK(milliunits>=0)) STRICT");
|
|
28
|
+
this.ready = true;
|
|
29
|
+
}
|
|
30
|
+
/** Hold `costMilliunits` for this operation unless the day's total would exceed the limit. */
|
|
31
|
+
admit(input) {
|
|
32
|
+
return this.storage.transactionSync(() => {
|
|
33
|
+
this.ensureSchema();
|
|
34
|
+
const day = utcDay(this.now());
|
|
35
|
+
const { sql } = this.storage;
|
|
36
|
+
sql.exec("DELETE FROM daily_media_hold WHERE day < ?", day);
|
|
37
|
+
const held = sql
|
|
38
|
+
.exec("SELECT day FROM daily_media_hold WHERE operation_id = ?", input.operationId)
|
|
39
|
+
.toArray()[0];
|
|
40
|
+
if (held !== undefined)
|
|
41
|
+
return true;
|
|
42
|
+
const { total } = totalRowSchema.parse(sql
|
|
43
|
+
.exec("SELECT COALESCE(SUM(milliunits),0) AS total FROM daily_media_hold WHERE day = ?", day)
|
|
44
|
+
.toArray()[0]);
|
|
45
|
+
if (total + input.costMilliunits > input.limitMilliunits)
|
|
46
|
+
return false;
|
|
47
|
+
sql.exec("INSERT INTO daily_media_hold (operation_id, day, milliunits) VALUES (?, ?, ?)", input.operationId, day, input.costMilliunits);
|
|
48
|
+
return true;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** Keep the hold when media was delivered; release it when nothing was. */
|
|
52
|
+
settle(input) {
|
|
53
|
+
if (input.delivered)
|
|
54
|
+
return;
|
|
55
|
+
this.storage.transactionSync(() => {
|
|
56
|
+
this.ensureSchema();
|
|
57
|
+
this.storage.sql.exec("DELETE FROM daily_media_hold WHERE operation_id = ?", input.operationId);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** `MediaMetering` that enforces one exact daily limit through the owning object. */
|
|
62
|
+
export function createDailyMediaMetering(meter, limitMilliunits) {
|
|
63
|
+
return {
|
|
64
|
+
admit: async (input) => {
|
|
65
|
+
const admitted = await meter.dailyAdmit({
|
|
66
|
+
operationId: input.operationId,
|
|
67
|
+
costMilliunits: input.providerCostMilliunits,
|
|
68
|
+
limitMilliunits,
|
|
69
|
+
});
|
|
70
|
+
if (!admitted)
|
|
71
|
+
throw new MediaBillingRefusal("daily_limit_reached");
|
|
72
|
+
return { priceMilliunits: input.providerCostMilliunits };
|
|
73
|
+
},
|
|
74
|
+
settle: async (input) => {
|
|
75
|
+
await meter.dailySettle({
|
|
76
|
+
operationId: input.operationId,
|
|
77
|
+
delivered: input.units > 0,
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -51,7 +51,7 @@ export declare class MediaSafetyFilterRefusal extends MediaExecutionError {
|
|
|
51
51
|
constructor(options?: MediaExecutionErrorOptions);
|
|
52
52
|
}
|
|
53
53
|
/** Why the host's billing owner refused to admit a new generation. */
|
|
54
|
-
export type MediaBillingRefusalCode = "insufficient_credits" | "denied";
|
|
54
|
+
export type MediaBillingRefusalCode = "insufficient_credits" | "denied" | "daily_limit_reached";
|
|
55
55
|
/** A definitive billing refusal before dispatch; nothing was generated or charged. */
|
|
56
56
|
export declare class MediaBillingRefusal extends Error {
|
|
57
57
|
/** Bounded refusal or failure reason. */
|
package/dist/gateway-models.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { type MediaCatalogue } from "./model-catalog.js";
|
|
1
2
|
import { type MediaGenerationSettings, type MediaReferenceBytes } from "./index.js";
|
|
2
3
|
import type { MediaVideoModelId } from "./model-catalog.js";
|
|
3
4
|
/** Gateway images and the verified catalog's video families share Unified billing. */
|
|
4
|
-
export type GatewayModelId = "openai/gpt-image-2" | MediaVideoModelId;
|
|
5
|
+
export type GatewayModelId = "openai/gpt-image-2" | "bytedance/seedream-5-pro" | MediaVideoModelId;
|
|
5
6
|
export declare const isGatewayModel: (id: string) => id is GatewayModelId;
|
|
6
7
|
/** What one generation bills: whole images, or seconds of video. */
|
|
7
8
|
export type MediaUnits = Readonly<{
|
|
@@ -11,7 +12,7 @@ export type MediaUnits = Readonly<{
|
|
|
11
12
|
units: number;
|
|
12
13
|
}>;
|
|
13
14
|
/** Billing units for validated settings; video bills its requested length. */
|
|
14
|
-
export declare function mediaUnits(settings: MediaGenerationSettings): MediaUnits;
|
|
15
|
+
export declare function mediaUnits(settings: MediaGenerationSettings, catalogue?: MediaCatalogue): MediaUnits;
|
|
15
16
|
/** Milliunits (1 cent = 1,000) of provider cost, rounded up. */
|
|
16
17
|
export declare function estimateGatewayMilliunits(settings: MediaGenerationSettings, references: readonly Readonly<{
|
|
17
18
|
width: number;
|
|
@@ -29,4 +30,9 @@ export declare function gatewayInput(settings: MediaGenerationSettings, referenc
|
|
|
29
30
|
size: string;
|
|
30
31
|
quality: string;
|
|
31
32
|
output_format: "png" | "jpeg" | "webp";
|
|
33
|
+
watermark?: never;
|
|
34
|
+
} | {
|
|
35
|
+
prompt: string;
|
|
36
|
+
size: string;
|
|
37
|
+
watermark: boolean;
|
|
32
38
|
};
|
package/dist/gateway-models.js
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
|
-
import { getMediaModel, MediaSettingsError } from "./model-catalog.js";
|
|
1
|
+
import { getGatewayModel, getMediaModel, mediaModels, MediaSettingsError, } from "./model-catalog.js";
|
|
2
2
|
import { validateMediaGenerationSettings, estimateVideoMilliunits, } from "./index.js";
|
|
3
3
|
import { imageDataUri } from "./video-providers/reference-encoding.js";
|
|
4
4
|
import { videoProviderAdapters, } from "./video-providers/index.js";
|
|
5
|
-
export const isGatewayModel = (id) => id === "openai/gpt-image-2" ||
|
|
5
|
+
export const isGatewayModel = (id) => id === "openai/gpt-image-2" ||
|
|
6
|
+
id === "bytedance/seedream-5-pro" ||
|
|
7
|
+
getGatewayModel(id)?.kind === "video";
|
|
6
8
|
/** Billing units for validated settings; video bills its requested length. */
|
|
7
|
-
export function mediaUnits(settings) {
|
|
8
|
-
const model = getMediaModel(settings.model);
|
|
9
|
+
export function mediaUnits(settings, catalogue = mediaModels) {
|
|
10
|
+
const model = getMediaModel(settings.model, catalogue);
|
|
9
11
|
if (model === undefined)
|
|
10
12
|
throw new MediaSettingsError("billing units require a known Media model");
|
|
11
13
|
if (model.kind === "video") {
|
|
12
14
|
const checked = validateMediaGenerationSettings({
|
|
13
15
|
...settings,
|
|
14
16
|
references: settings.references?.map((reference) => ({ ...reference })),
|
|
15
|
-
});
|
|
17
|
+
}, catalogue);
|
|
16
18
|
if (checked.durationSeconds === undefined)
|
|
17
19
|
throw new MediaSettingsError("video settings need a duration");
|
|
18
20
|
return { unit: "video_second", units: checked.durationSeconds };
|
|
@@ -23,12 +25,22 @@ export function mediaUnits(settings) {
|
|
|
23
25
|
* GPT Image 2 output tokens per image at `medium` quality. OpenAI publishes
|
|
24
26
|
* this table for its gpt-image models; PRICE DECISION PENDING (Levi): confirm
|
|
25
27
|
* against the first live gateway logs, which carry the real token counts.
|
|
28
|
+
* Any other size is billed in proportion to its pixels at the 1024x1024 rate
|
|
29
|
+
* (1,056 tokens per 1,048,576 pixels, which reproduces the table's 1024x1536
|
|
30
|
+
* row exactly and bounds its 1536x1024 row), rounded up; OpenAI publishes no
|
|
31
|
+
* table for the larger sizes.
|
|
26
32
|
*/
|
|
27
33
|
const gptImageOutputTokens = new Map([
|
|
28
34
|
["1024x1024", 1_056],
|
|
29
35
|
["1024x1536", 1_584],
|
|
30
36
|
["1536x1024", 1_568],
|
|
31
37
|
]);
|
|
38
|
+
const gptImageTokensPerMegapixel = 1_056 / 1_048_576;
|
|
39
|
+
function gptImageOutputTokenCount(settings) {
|
|
40
|
+
const known = gptImageOutputTokens.get(sizeOf(settings));
|
|
41
|
+
return (known ??
|
|
42
|
+
Math.ceil(settings.width * settings.height * gptImageTokensPerMegapixel));
|
|
43
|
+
}
|
|
32
44
|
/**
|
|
33
45
|
* USD per million tokens: text input, image input and image output, as
|
|
34
46
|
* Cloudflare publishes them for this exact model.
|
|
@@ -60,9 +72,7 @@ const sizeOf = (settings) => `${String(settings.width)}x${String(settings.height
|
|
|
60
72
|
/** Milliunits (1 cent = 1,000) of provider cost, rounded up. */
|
|
61
73
|
export function estimateGatewayMilliunits(settings, references) {
|
|
62
74
|
if (settings.model === "openai/gpt-image-2") {
|
|
63
|
-
const output =
|
|
64
|
-
if (output === undefined)
|
|
65
|
-
throw new MediaSettingsError("unsupported GPT Image 2 size");
|
|
75
|
+
const output = gptImageOutputTokenCount(settings);
|
|
66
76
|
if (references.length !== (settings.references?.length ?? 0))
|
|
67
77
|
throw new MediaSettingsError("resolved references must match every admitted reference");
|
|
68
78
|
// A bound on prompt tokens: at most one token per character, plus one
|
|
@@ -75,7 +85,12 @@ export function estimateGatewayMilliunits(settings, references) {
|
|
|
75
85
|
inputImage * gptImageRates.inputImage) /
|
|
76
86
|
10);
|
|
77
87
|
}
|
|
78
|
-
|
|
88
|
+
// Cloudflare prices Seedream 5 Pro at $0.045 per image, and $0.03 per input
|
|
89
|
+
// image (none are sent); it states no price by size.
|
|
90
|
+
// https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/
|
|
91
|
+
if (settings.model === "bytedance/seedream-5-pro")
|
|
92
|
+
return 4_500;
|
|
93
|
+
if (getGatewayModel(settings.model)?.kind === "video")
|
|
79
94
|
return estimateVideoMilliunits(settings);
|
|
80
95
|
throw new MediaSettingsError(`${settings.model} is not a gateway model`);
|
|
81
96
|
}
|
|
@@ -104,11 +119,21 @@ export function gatewayInput(settings, references = [], outputFormat = "png") {
|
|
|
104
119
|
return body;
|
|
105
120
|
return { ...body, images: references.map(gptImageReference) };
|
|
106
121
|
}
|
|
122
|
+
if (settings.model === "bytedance/seedream-5-pro") {
|
|
123
|
+
if (references.length > 0)
|
|
124
|
+
throw new MediaSettingsError("bytedance/seedream-5-pro takes no reference images here");
|
|
125
|
+
// `watermark` is a required field; false adds none.
|
|
126
|
+
return {
|
|
127
|
+
prompt: settings.prompt,
|
|
128
|
+
size: sizeOf(settings),
|
|
129
|
+
watermark: false,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
107
132
|
const checked = validateMediaGenerationSettings({
|
|
108
133
|
...settings,
|
|
109
134
|
references: settings.references?.map((reference) => ({ ...reference })),
|
|
110
135
|
});
|
|
111
|
-
const model =
|
|
136
|
+
const model = getGatewayModel(checked.model);
|
|
112
137
|
if (model?.video == null ||
|
|
113
138
|
checked.resolution === undefined ||
|
|
114
139
|
checked.aspectRatio === undefined ||
|
package/dist/gateway-wire.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export declare const gatewayOutputSchema: z.ZodLazy<z.ZodObject<{
|
|
|
7
7
|
state: z.ZodOptional<z.ZodLiteral<"Completed">>;
|
|
8
8
|
result: z.ZodObject<{
|
|
9
9
|
image: z.ZodOptional<z.ZodLazy<z.ZodURL>>;
|
|
10
|
+
images: z.ZodOptional<z.ZodArray<z.ZodLazy<z.ZodURL>>>;
|
|
10
11
|
video: z.ZodOptional<z.ZodLazy<z.ZodURL>>;
|
|
11
12
|
}, z.core.$loose>;
|
|
12
13
|
}, z.core.$loose>>;
|
package/dist/gateway-wire.js
CHANGED
|
@@ -9,6 +9,8 @@ export const gatewayOutputSchema = z.lazy(() => z.looseObject({
|
|
|
9
9
|
state: z.literal("Completed").optional(),
|
|
10
10
|
result: z.looseObject({
|
|
11
11
|
image: resultUrl.optional(),
|
|
12
|
+
/** Seedream answers with a list of result URLs. */
|
|
13
|
+
images: z.array(resultUrl).min(1).optional(),
|
|
12
14
|
video: resultUrl.optional(),
|
|
13
15
|
}),
|
|
14
16
|
}));
|