@fungi.computer/darkroom 0.6.0 → 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.
Files changed (39) hide show
  1. package/README.md +129 -0
  2. package/dist/app-media-contracts.d.ts +4 -0
  3. package/dist/browser-failure.d.ts +2 -0
  4. package/dist/browser-failure.js +2 -0
  5. package/dist/cloudflare/provider.js +3 -3
  6. package/dist/cloudflare/reference-images.d.ts +6 -0
  7. package/dist/cloudflare/reference-images.js +25 -7
  8. package/dist/cost-estimate.js +2 -2
  9. package/dist/daily-media-meter.d.ts +55 -0
  10. package/dist/daily-media-meter.js +81 -0
  11. package/dist/execution-error.d.ts +1 -1
  12. package/dist/gateway-models.d.ts +8 -2
  13. package/dist/gateway-models.js +24 -7
  14. package/dist/gateway-wire.d.ts +1 -0
  15. package/dist/gateway-wire.js +2 -0
  16. package/dist/index.d.ts +49 -12
  17. package/dist/index.js +31 -21
  18. package/dist/media-binding.js +3 -3
  19. package/dist/media-generation.js +9 -5
  20. package/dist/media-operation-contract.d.ts +3 -1
  21. package/dist/media-operation-do.d.ts +13 -2
  22. package/dist/media-operation-do.js +26 -1
  23. package/dist/media-operation-owner.d.ts +8 -0
  24. package/dist/media-operation-owner.js +8 -5
  25. package/dist/media-operation.js +2 -2
  26. package/dist/media-quote.d.ts +14 -0
  27. package/dist/media-quote.js +17 -0
  28. package/dist/model-catalog.d.ts +435 -4
  29. package/dist/model-catalog.js +130 -6
  30. package/dist/reference-image-size.d.ts +4 -3
  31. package/dist/reference-image-size.js +9 -9
  32. package/dist/server.d.ts +17 -1
  33. package/dist/server.js +44 -6
  34. package/docs/api/app-media-contracts.md +4 -0
  35. package/docs/api/browser.md +4 -2
  36. package/docs/api/cloudflare.md +53 -0
  37. package/docs/api/index.md +461 -54
  38. package/docs/api/server.md +194 -5
  39. package/package.json +2 -2
package/dist/server.d.ts CHANGED
@@ -2,11 +2,13 @@ export { estimateMediaModel } from "./cloudflare/provider.js";
2
2
  export { mediaPendingSchema, mediaBindingCallSchema, mediaBindingGenerationSchema, mediaImageBindingInputSchema, mediaVideoBindingInputSchema, parseMediaBindingCall, mediaBindingRequest, readMediaBindingReply, type MediaBindingCall, type MediaBindingGeneration, type MediaBindingRequest, } from "./media-binding.js";
3
3
  import { Hono } from "hono";
4
4
  import { z } from "zod";
5
- import { validateMediaGenerationSettings, type MediaProvider, type MediaReference, type MediaReferenceBytes } from "./index.js";
5
+ import { validateMediaGenerationSettings, type MediaCatalogue, type MediaProvider, type MediaReference, type MediaReferenceBytes } from "./index.js";
6
6
  import { type MediaExecution, type MediaMetering } from "./media-operation-contract.js";
7
7
  import { MediaExecutionError, type MediaBillingRefusalCode } from "./execution-error.js";
8
+ export { createDailyMediaMetering, DailyMediaMeter, type DailyMediaMeterPort, type DailyMediaMeterStorage, } from "./daily-media-meter.js";
8
9
  export { MediaBillingRefusal, MediaExecutionError, type MediaBillingRefusalCode, type MediaFailureStage, type MediaExecutionErrorOptions, } from "./execution-error.js";
9
10
  export { mediaUnits, type MediaUnits } from "./gateway-models.js";
11
+ export { quoteMediaGeneration, type MediaQuote } from "./media-quote.js";
10
12
  export type { MediaMetering, MediaOperation, } from "./media-operation-contract.js";
11
13
  export { MediaOperationOwner, mediaOperationDestinationSchema, mediaOperationCoordinatesSchema, mediaOperationStateSchema, mediaImageSchema, mediaOperationResultSchema, } from "./media-operation-owner.js";
12
14
  export type { MediaOperationCoordinates, MediaOperationRequest, MediaOperationProjection, MediaOperationDecision, MediaOperationState, MediaOperationResult, MediaOperationEnvironment, MediaOperationHooks, MediaImage, MediaErasurePreflight, MediaErasureReadback, MediaRetentionResult, } from "./media-operation-owner.js";
@@ -97,6 +99,20 @@ export type MediaServiceHost = Readonly<{
97
99
  /** Translate host authority failures; undefined uses the shared Media failure. */
98
100
  onFailure?: (error: MediaExecutionError) => Response | undefined;
99
101
  }> & (Readonly<{
102
+ /** Omitted: the Fungi gateway provider's own catalogue and quote. */
103
+ catalogue?: undefined;
104
+ /** Omitted with the catalogue: the gateway's own quote. */
105
+ estimate?: undefined;
106
+ }> | Readonly<{
107
+ /**
108
+ * The injected `provider`'s own model list, decoded with
109
+ * `parseMediaCatalogue`. Requests are validated against it, never
110
+ * against the Fungi gateway's.
111
+ */
112
+ catalogue: MediaCatalogue;
113
+ /** Provider cost of validated settings in milliunits; owned by the custom provider. */
114
+ estimate: (settings: Parameters<MediaProvider>[0], references: readonly MediaReferenceBytes[]) => number;
115
+ }>) & (Readonly<{
100
116
  /** The host pays its own provider directly. */
101
117
  metering: "unmetered";
102
118
  /** Unmetered hosts do not have billing refusal policy. */
package/dist/server.js CHANGED
@@ -7,11 +7,14 @@ import { AppError, describeAppError } from "@fungi.computer/agar/errors";
7
7
  import * as Effect from "effect/Effect";
8
8
  import * as Result from "effect/Result";
9
9
  import { runMediaGeneration } from "./media-generation.js";
10
- import { validateMediaGenerationSettings, listMediaModels, mediaGenerationSettingsSchema, mediaRequestedImageFormatSchema, MediaSettingsError, } from "./index.js";
10
+ import { quoteMediaGeneration } from "./media-quote.js";
11
+ import { validateMediaGenerationSettings, mediaModels, mediaGenerationSettingsSchema, mediaRequestedImageFormatSchema, MediaSettingsError, } from "./index.js";
11
12
  import { mediaResultSchema, } from "./media-operation-contract.js";
12
13
  import { MediaOutputFormatMismatch, MediaBillingRefusal, MediaExecutionError, MediaSafetyFilterRefusal, } from "./execution-error.js";
14
+ export { createDailyMediaMetering, DailyMediaMeter, } from "./daily-media-meter.js";
13
15
  export { MediaBillingRefusal, MediaExecutionError, } from "./execution-error.js";
14
16
  export { mediaUnits } from "./gateway-models.js";
17
+ export { quoteMediaGeneration } from "./media-quote.js";
15
18
  export { MediaOperationOwner, mediaOperationDestinationSchema, mediaOperationCoordinatesSchema, mediaOperationStateSchema, mediaImageSchema, mediaOperationResultSchema, } from "./media-operation-owner.js";
16
19
  const identifier = z.lazy(() => z.string().min(1).max(256));
17
20
  /** Decode relative service generation input. Identity comes from the host. */
@@ -27,6 +30,10 @@ export const mediaRequestSchema = z.strictObject({
27
30
  /** Optional verified image encoding pin. */
28
31
  outputFormat: mediaRequestedImageFormatSchema.optional(),
29
32
  });
33
+ /** A price request: the exact settings, no destination or request id. */
34
+ const mediaQuoteRequestSchema = z.strictObject({
35
+ settings: mediaGenerationSettingsSchema,
36
+ });
30
37
  export { mediaResultSchema } from "./media-operation-contract.js";
31
38
  async function readJsonBody(request) {
32
39
  try {
@@ -46,6 +53,11 @@ const headers = {
46
53
  "Cache-Control": "private, no-store",
47
54
  "X-Content-Type-Options": "nosniff",
48
55
  };
56
+ const billingRefusalWire = {
57
+ insufficient_credits: { code: "INSUFFICIENT_CREDIT", status: 402 },
58
+ denied: { code: "CAPABILITY_DENIED", status: 403 },
59
+ daily_limit_reached: { code: "DAILY_LIMIT_REACHED", status: 429 },
60
+ };
49
61
  function failure(error, refusalMessages) {
50
62
  if (error instanceof MediaSafetyFilterRefusal)
51
63
  return Response.json({
@@ -76,12 +88,10 @@ function failure(error, refusalMessages) {
76
88
  error: refusalMessages?.[error.cause.code] ??
77
89
  "Media generation was refused by the host.",
78
90
  stage: "billing",
79
- code: error.cause.code === "insufficient_credits"
80
- ? "INSUFFICIENT_CREDIT"
81
- : "CAPABILITY_DENIED",
91
+ code: billingRefusalWire[error.cause.code].code,
82
92
  retryable: false,
83
93
  }, {
84
- status: error.cause.code === "denied" ? 403 : 402,
94
+ status: billingRefusalWire[error.cause.code].status,
85
95
  headers,
86
96
  });
87
97
  if (error instanceof MediaSettingsError ||
@@ -192,7 +202,7 @@ function outcomeResponse(outcome) {
192
202
  /** Relative HTTP routes; the caller admits identity and supplies destination access. */
193
203
  export function createMediaService(host) {
194
204
  const app = new Hono();
195
- app.get("/models", () => Response.json(listMediaModels().map((model) => host.destination.readReference !== undefined ||
205
+ app.get("/models", () => Response.json((host.catalogue ?? mediaModels).map((model) => host.destination.readReference !== undefined ||
196
206
  model.input.maxReferences === 0
197
207
  ? model
198
208
  : {
@@ -224,5 +234,33 @@ export function createMediaService(host) {
224
234
  : undefined) ?? failure(error, host.refusalMessages),
225
235
  })));
226
236
  });
237
+ // The provider cost of one exact request, priced by the same estimator and
238
+ // reference reads as /generate; the host applies any billing policy.
239
+ app.post("/quote", async (context) => {
240
+ const body = await readJsonBody(context.req.raw);
241
+ const input = body.kind === "parsed"
242
+ ? mediaQuoteRequestSchema.safeParse(body.value)
243
+ : undefined;
244
+ if (input?.success !== true)
245
+ return failure(new MediaSettingsError("invalid request"));
246
+ try {
247
+ const quote = await quoteMediaGeneration(input.data.settings, {
248
+ read: (reference, model) => {
249
+ if (host.destination.readReference === undefined)
250
+ throw new MediaSettingsError("reference images are unavailable");
251
+ return host.destination.readReference(reference, model);
252
+ },
253
+ });
254
+ return Response.json(quote, { headers });
255
+ }
256
+ catch (cause) {
257
+ if (cause instanceof MediaSettingsError)
258
+ return failure(cause);
259
+ const error = cause instanceof MediaExecutionError
260
+ ? cause
261
+ : new MediaExecutionError("estimate", { cause });
262
+ return host.onFailure?.(error) ?? failure(error, host.refusalMessages);
263
+ }
264
+ });
227
265
  return app;
228
266
  }
@@ -449,6 +449,7 @@ Missing-library refusal decoded and returned by the App media broker.
449
449
  const appMediaBrokerFailureSchema: ZodObject<{
450
450
  error: ZodEnum<{
451
451
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
452
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
452
453
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
453
454
  HOST_FAILURE: "HOST_FAILURE";
454
455
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -502,6 +503,7 @@ const appMediaRefusalSchema: ZodUnion<readonly [ZodObject<{
502
503
  }, $strict>>, ZodObject<{
503
504
  error: ZodEnum<{
504
505
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
506
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
505
507
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
506
508
  HOST_FAILURE: "HOST_FAILURE";
507
509
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -597,6 +599,7 @@ const appMediaModelsOutcomeSchema: ZodUnion<readonly [ZodLazy<ZodArray<ZodReadon
597
599
  }, $strict>>, ZodObject<{
598
600
  error: ZodEnum<{
599
601
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
602
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
600
603
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
601
604
  HOST_FAILURE: "HOST_FAILURE";
602
605
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -669,6 +672,7 @@ const appMediaGenerationOutcomeSchema: ZodUnion<readonly [ZodObject<{
669
672
  }, $strict>>, ZodObject<{
670
673
  error: ZodEnum<{
671
674
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
675
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
672
676
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
673
677
  HOST_FAILURE: "HOST_FAILURE";
674
678
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -62,6 +62,7 @@ const mediaFailureSchema: ZodObject<{
62
62
  }>;
63
63
  code: ZodEnum<{
64
64
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
65
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
65
66
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
66
67
  HOST_FAILURE: "HOST_FAILURE";
67
68
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -101,6 +102,7 @@ function readMediaFailure(
101
102
  | "destination-write";
102
103
  code:
103
104
  | "CAPABILITY_DENIED"
105
+ | "DAILY_LIMIT_REACHED"
104
106
  | "INSUFFICIENT_CREDIT"
105
107
  | "HOST_FAILURE"
106
108
  | "INVALID_ARGUMENT"
@@ -127,8 +129,8 @@ Read and decode one Media host failure at the browser HTTP boundary.
127
129
  \| `"generation-authorization"` \| `"settings"` \| `"estimate"` \| `"billing"`
128
130
  \| `"operation"` \| `"normalization"` \| `"artifact"` \|
129
131
  `"destination-authorization"` \| `"destination-write"`; `code`: \|
130
- `"CAPABILITY_DENIED"` \| `"INSUFFICIENT_CREDIT"` \| `"HOST_FAILURE"` \|
131
- `"INVALID_ARGUMENT"` \| `"MEDIA_PROVIDER_FAILURE"` \|
132
+ `"CAPABILITY_DENIED"` \| `"DAILY_LIMIT_REACHED"` \| `"INSUFFICIENT_CREDIT"` \|
133
+ `"HOST_FAILURE"` \| `"INVALID_ARGUMENT"` \| `"MEDIA_PROVIDER_FAILURE"` \|
132
134
  `"MEDIA_PROVIDER_FAILURE_UNCHARGED"` \| `"SAFETY_FILTER_REFUSED"`; `retryable`:
133
135
  `boolean`; `provider?`: `MediaProviderDiagnostic`; \} \| `null`\>
134
136
 
@@ -18,6 +18,10 @@ Cloudflare lifecycle and RPC surface around the durable media owner.
18
18
 
19
19
  - `DurableObject`\<[`MediaOperationCloudflareEnvironment`](#mediaoperationcloudflareenvironment)\>
20
20
 
21
+ #### Implements
22
+
23
+ - [`DailyMediaMeterPort`](server.md#dailymediameterport)
24
+
21
25
  #### Constructors
22
26
 
23
27
  ##### Constructor
@@ -45,6 +49,55 @@ DurableObject<MediaOperationCloudflareEnvironment>.constructor
45
49
 
46
50
  #### Methods
47
51
 
52
+ ##### dailyAdmit()
53
+
54
+ ```ts
55
+ dailyAdmit(...input): boolean;
56
+ ```
57
+
58
+ Admit one generation against today's hard stop; false means the daily limit is
59
+ reached.
60
+
61
+ ###### Parameters
62
+
63
+ | Parameter | Type |
64
+ | ---------- | --------------------------------------------------------------------------------------------------------- |
65
+ | ...`input` | \[`Readonly`\<\{ `operationId`: `string`; `costMilliunits`: `number`; `limitMilliunits`: `number`; \}\>\] |
66
+
67
+ ###### Returns
68
+
69
+ `boolean`
70
+
71
+ ###### Implementation of
72
+
73
+ ```ts
74
+ DailyMediaMeterPort.dailyAdmit;
75
+ ```
76
+
77
+ ##### dailySettle()
78
+
79
+ ```ts
80
+ dailySettle(...input): void;
81
+ ```
82
+
83
+ Settle an admitted generation once its outcome is known.
84
+
85
+ ###### Parameters
86
+
87
+ | Parameter | Type |
88
+ | ---------- | ------------------------------------------------------------------------ |
89
+ | ...`input` | \[`Readonly`\<\{ `operationId`: `string`; `delivered`: `boolean`; \}\>\] |
90
+
91
+ ###### Returns
92
+
93
+ `void`
94
+
95
+ ###### Implementation of
96
+
97
+ ```ts
98
+ DailyMediaMeterPort.dailySettle;
99
+ ```
100
+
48
101
  ##### read()
49
102
 
50
103
  ```ts