@fungi.computer/darkroom 0.11.10 → 0.11.12
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 +13 -0
- package/examples/standalone/README.md +52 -0
- package/examples/standalone/worker.ts +87 -0
- package/examples/standalone/wrangler.jsonc +26 -0
- package/package.json +8 -2
- package/src/app-media-contracts.ts +142 -0
- package/src/audio-providers/elevenlabs.ts +108 -0
- package/src/audio-reference-types.ts +47 -0
- package/src/audio-references.ts +107 -0
- package/src/browser-failure.ts +73 -0
- package/src/browser.ts +7 -0
- package/src/cloudflare/provider-reason.ts +89 -0
- package/src/cloudflare/provider.ts +405 -0
- package/src/cloudflare/r2-destination.ts +130 -0
- package/src/cloudflare/reference-images.ts +193 -0
- package/src/cloudflare.ts +38 -0
- package/src/cost-estimate.ts +129 -0
- package/src/daily-media-meter.ts +163 -0
- package/src/effect.ts +2 -0
- package/src/execution-error.ts +98 -0
- package/src/failure.ts +13 -0
- package/src/gateway-models.ts +304 -0
- package/src/gateway-wire.ts +36 -0
- package/src/index.ts +1454 -0
- package/src/media-binding.ts +260 -0
- package/src/media-content-type.ts +60 -0
- package/src/media-generation.ts +171 -0
- package/src/media-operation-contract.ts +173 -0
- package/src/media-operation-do.ts +257 -0
- package/src/media-operation-owner.ts +1786 -0
- package/src/media-operation-storage.ts +110 -0
- package/src/media-operation.ts +454 -0
- package/src/media-path.ts +8 -0
- package/src/media-quote.ts +34 -0
- package/src/media-run-lifetime.ts +5 -0
- package/src/media-written.ts +38 -0
- package/src/model-catalog.ts +1574 -0
- package/src/neurons.ts +6 -0
- package/src/node-webpmux.d.ts +12 -0
- package/src/provenance-bytes.ts +22 -0
- package/src/provenance-export.ts +126 -0
- package/src/provenance-jpeg.ts +83 -0
- package/src/provenance-png.ts +26 -0
- package/src/provenance-signed.ts +7 -0
- package/src/provenance-xmp.ts +57 -0
- package/src/provenance.ts +87 -0
- package/src/reference-image-size.ts +67 -0
- package/src/reference-read.ts +50 -0
- package/src/server.ts +711 -0
- package/src/video-providers/index.ts +18 -0
- package/src/video-providers/minimax.ts +96 -0
- package/src/video-providers/reference-encoding.ts +32 -0
- package/src/video-providers/types.ts +47 -0
- package/src/video-providers/unified.ts +68 -0
- package/test/audio-models.test.ts +428 -0
- package/test/audio-references.test.ts +428 -0
- package/test/custom-catalogue.test.ts +257 -0
- package/test/daily-media-meter.test.ts +287 -0
- package/test/failure.test.ts +190 -0
- package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
- package/test/fixtures/media-operation.fixture.ts +134 -0
- package/test/fixtures/media-team-prompts.ts +7 -0
- package/test/fixtures/native-sqlite.fixture.ts +40 -0
- package/test/gateway-models.test.ts +712 -0
- package/test/media-operation-do.test.ts +1565 -0
- package/test/media-quote.test.ts +81 -0
- package/test/media-retention.test.ts +597 -0
- package/test/media-service.test.ts +549 -0
- package/test/media-team-prompts.test.ts +92 -0
- package/test/model-facts.test.ts +126 -0
- package/test/prompt-limit.test.ts +53 -0
- package/test/provenance-export.test.ts +144 -0
- package/test/provenance-images.fixture.mjs +17 -0
- package/test/provenance.test.ts +179 -0
- package/test/provider-gateway.test.ts +114 -0
- package/test/provider-reasons.test.ts +133 -0
- package/test/r2-destination.test.ts +166 -0
- package/test/reference-image-size.test.ts +73 -0
- package/test/reference-images-billing.test.ts +40 -0
- package/test/reference-images.test.ts +399 -0
- package/test/standalone.cloudflare.test.mjs +298 -0
- package/test/standalone.worker.mjs +70 -0
- package/test/transform-models.test.ts +400 -0
- package/test/video-capabilities.test.ts +160 -0
- package/test/video-contract.test.ts +533 -0
- package/test/video-failure-lifecycle.test.ts +177 -0
- package/test/video-provider.test.ts +136 -0
- package/test/video-wire.test.ts +251 -0
- package/vitest.cloudflare.config.ts +22 -0
- package/vitest.node.config.ts +14 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
3
|
+
import { pending } from "@fungi.computer/agar/backend-definition";
|
|
4
|
+
import { mediaRequestIdSchema } from "@fungi.computer/agar/media-request-id";
|
|
5
|
+
import { mediaLibraryPathSchema } from "@fungi.computer/agar/media-library";
|
|
6
|
+
import {
|
|
7
|
+
getGatewayModel,
|
|
8
|
+
mediaAudioSelectionSchema,
|
|
9
|
+
mediaGenerationSelectionSchema,
|
|
10
|
+
mediaRequestedImageFormatSchema,
|
|
11
|
+
mediaVideoSelectionSchema,
|
|
12
|
+
validateMediaGenerationSelection,
|
|
13
|
+
validateMediaGenerationSettings,
|
|
14
|
+
validateMediaVideoSelection,
|
|
15
|
+
MediaSettingsError,
|
|
16
|
+
readResponseBytes,
|
|
17
|
+
type MediaGenerationSettings,
|
|
18
|
+
} from "./index.js";
|
|
19
|
+
export { mediaResultSchema } from "./media-operation-contract.js";
|
|
20
|
+
import { mediaFailureSchema } from "./browser-failure.js";
|
|
21
|
+
import {
|
|
22
|
+
appMediaBrokerFailureSchema,
|
|
23
|
+
appMediaGenerationResultSchema,
|
|
24
|
+
mediaModelsSchema,
|
|
25
|
+
} from "./app-media-contracts.js";
|
|
26
|
+
|
|
27
|
+
/** The App owns its folder; the host owns Computer identity and the output filename. */
|
|
28
|
+
const mediaBindingLibraryPathSchema = z
|
|
29
|
+
.string()
|
|
30
|
+
.refine(
|
|
31
|
+
Schema.is(mediaLibraryPathSchema),
|
|
32
|
+
"Select an absolute library folder",
|
|
33
|
+
);
|
|
34
|
+
/** Image settings and path references crossing a scoped MEDIA binding. */
|
|
35
|
+
export const mediaImageBindingInputSchema = z.strictObject({
|
|
36
|
+
/** Select image generation rather than video. */
|
|
37
|
+
kind: z.literal("image"),
|
|
38
|
+
/** Attempt identity retained through polling and replay. */
|
|
39
|
+
requestId: mediaRequestIdSchema,
|
|
40
|
+
/** App-owned absolute folder; the host supplies Computer authority. */
|
|
41
|
+
libraryPath: mediaBindingLibraryPathSchema,
|
|
42
|
+
/** Image model selection, references and inference settings. */
|
|
43
|
+
settings: mediaGenerationSelectionSchema
|
|
44
|
+
.omit({ durationSeconds: true, voiceId: true, audioReferences: true })
|
|
45
|
+
.extend({
|
|
46
|
+
/** Output width in pixels; an image always names its size. */
|
|
47
|
+
width: z.number().int().min(1).max(5_040),
|
|
48
|
+
/** Output height in pixels; an image always names its size. */
|
|
49
|
+
height: z.number().int().min(1).max(5_040),
|
|
50
|
+
/** Optional inference-step count for models that support it. */
|
|
51
|
+
steps: z
|
|
52
|
+
.number()
|
|
53
|
+
.int()
|
|
54
|
+
.nonnegative()
|
|
55
|
+
.max(Number.MAX_SAFE_INTEGER)
|
|
56
|
+
.optional(),
|
|
57
|
+
})
|
|
58
|
+
.refine(
|
|
59
|
+
(settings) => getGatewayModel(settings.model)?.kind === "image",
|
|
60
|
+
"Select an image model from listModels",
|
|
61
|
+
),
|
|
62
|
+
/** Requested image encoding, validated against the selected model. */
|
|
63
|
+
outputFormat: mediaRequestedImageFormatSchema.optional(),
|
|
64
|
+
});
|
|
65
|
+
/** Video settings and path references crossing the same scoped binding. */
|
|
66
|
+
export const mediaVideoBindingInputSchema = z.strictObject({
|
|
67
|
+
/** Select video generation rather than an image. */
|
|
68
|
+
kind: z.literal("video"),
|
|
69
|
+
/** Attempt identity retained through polling and replay. */
|
|
70
|
+
requestId: mediaRequestIdSchema,
|
|
71
|
+
/** App-owned absolute folder; the host supplies Computer authority. */
|
|
72
|
+
libraryPath: mediaBindingLibraryPathSchema,
|
|
73
|
+
/** Catalog-backed video model, size, duration and references. */
|
|
74
|
+
settings: mediaVideoSelectionSchema,
|
|
75
|
+
});
|
|
76
|
+
/** Speech or music settings crossing the same scoped binding; audio takes no references. */
|
|
77
|
+
export const mediaAudioBindingInputSchema = z.strictObject({
|
|
78
|
+
/** Select speech or music generation. */
|
|
79
|
+
kind: z.literal("audio"),
|
|
80
|
+
/** Attempt identity retained through polling and replay. */
|
|
81
|
+
requestId: mediaRequestIdSchema,
|
|
82
|
+
/** App-owned absolute folder; the host supplies Computer authority. */
|
|
83
|
+
libraryPath: mediaBindingLibraryPathSchema,
|
|
84
|
+
/** Catalog-backed audio model, prompt, voice and length. */
|
|
85
|
+
settings: mediaAudioSelectionSchema,
|
|
86
|
+
});
|
|
87
|
+
/** One generation identity, including the App-owned folder captured for replay. */
|
|
88
|
+
export const mediaBindingGenerationSchema = z.discriminatedUnion("kind", [
|
|
89
|
+
mediaImageBindingInputSchema,
|
|
90
|
+
mediaVideoBindingInputSchema,
|
|
91
|
+
mediaAudioBindingInputSchema,
|
|
92
|
+
]);
|
|
93
|
+
/** Parsed generation command consumed by either host. */
|
|
94
|
+
export type MediaBindingGeneration = z.output<
|
|
95
|
+
typeof mediaBindingGenerationSchema
|
|
96
|
+
>;
|
|
97
|
+
/** Maintained MEDIA grammar; reference selectors carry no Computer authority. */
|
|
98
|
+
export const mediaBindingCallSchema = z.discriminatedUnion("operation", [
|
|
99
|
+
z.strictObject({
|
|
100
|
+
/** Read the model catalog without dispatching generation. */
|
|
101
|
+
operation: z.literal("models"),
|
|
102
|
+
/** Catalog reads carry no guest authority or generation settings. */
|
|
103
|
+
input: z.strictObject({}),
|
|
104
|
+
}),
|
|
105
|
+
z.strictObject({
|
|
106
|
+
/** Execute or poll one admitted generation identity. */
|
|
107
|
+
operation: z.literal("generate"),
|
|
108
|
+
/** The App's captured generation selection and library folder. */
|
|
109
|
+
input: mediaBindingGenerationSchema,
|
|
110
|
+
}),
|
|
111
|
+
]);
|
|
112
|
+
/** Parsed call consumed by host admission and transport. */
|
|
113
|
+
export type MediaBindingCall = z.output<typeof mediaBindingCallSchema>;
|
|
114
|
+
/** Background-generation reply emitted by the durable service. */
|
|
115
|
+
export const mediaPendingSchema = z.lazy(() =>
|
|
116
|
+
z.strictObject({
|
|
117
|
+
/** Background work has been accepted but is not yet delivered. */
|
|
118
|
+
status: z.literal("pending"),
|
|
119
|
+
/** Host-supplied delay before polling the same attempt again. */
|
|
120
|
+
retryAfterSeconds: z.number().int().positive(),
|
|
121
|
+
}),
|
|
122
|
+
);
|
|
123
|
+
/** Parsing and model refusal stay shared; authorization remains host-owned. */
|
|
124
|
+
export function parseMediaBindingCall(raw: z.core.util.JSONType):
|
|
125
|
+
| Readonly<{
|
|
126
|
+
/** The binding input passed its shared grammar. */
|
|
127
|
+
kind: "parsed";
|
|
128
|
+
/** Validated command for host admission. */
|
|
129
|
+
call: MediaBindingCall;
|
|
130
|
+
}>
|
|
131
|
+
| Readonly<{
|
|
132
|
+
/** Input size, grammar or model selection was refused. */
|
|
133
|
+
kind: "refused";
|
|
134
|
+
/** Safe refusal returned without provider dispatch. */
|
|
135
|
+
result: z.core.util.JSONType;
|
|
136
|
+
}> {
|
|
137
|
+
if (new TextEncoder().encode(JSON.stringify(raw)).byteLength > 64 * 1024)
|
|
138
|
+
return { kind: "refused", result: { error: "too_large" } };
|
|
139
|
+
const parsed = mediaBindingCallSchema.safeParse(raw);
|
|
140
|
+
if (!parsed.success) return { kind: "refused", result: { error: "invalid" } };
|
|
141
|
+
if (parsed.data.operation === "generate") {
|
|
142
|
+
try {
|
|
143
|
+
if (parsed.data.input.kind === "image")
|
|
144
|
+
validateMediaGenerationSelection(parsed.data.input.settings);
|
|
145
|
+
else if (parsed.data.input.kind === "audio")
|
|
146
|
+
validateMediaGenerationSettings(parsed.data.input.settings);
|
|
147
|
+
else validateMediaVideoSelection(parsed.data.input.settings);
|
|
148
|
+
} catch (cause) {
|
|
149
|
+
if (!(cause instanceof MediaSettingsError)) throw cause;
|
|
150
|
+
return {
|
|
151
|
+
kind: "refused",
|
|
152
|
+
result: {
|
|
153
|
+
error: "INVALID_ARGUMENT",
|
|
154
|
+
message: cause.message,
|
|
155
|
+
stage: "settings",
|
|
156
|
+
retryable: false,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { kind: "parsed", call: parsed.data };
|
|
162
|
+
}
|
|
163
|
+
/** Relative service input after the host attaches its trusted Computer to references. */
|
|
164
|
+
export type MediaBindingRequest = Readonly<{
|
|
165
|
+
/** Host-selected output filename within the App's library folder. */
|
|
166
|
+
path: string;
|
|
167
|
+
/** Validated references with explicit Computer identities, authorized by the host. */
|
|
168
|
+
settings: MediaGenerationSettings;
|
|
169
|
+
/** Optional image encoding; video output remains MP4 and audio MP3. */
|
|
170
|
+
outputFormat?: z.output<typeof mediaRequestedImageFormatSchema>;
|
|
171
|
+
}>;
|
|
172
|
+
/** Choose the same fixed filename on both hosts without a recursive App lookup. */
|
|
173
|
+
export function mediaBindingRequest(
|
|
174
|
+
input: MediaBindingGeneration,
|
|
175
|
+
computerId: string,
|
|
176
|
+
): MediaBindingRequest {
|
|
177
|
+
const selected =
|
|
178
|
+
input.kind === "image"
|
|
179
|
+
? validateMediaGenerationSelection(input.settings)
|
|
180
|
+
: input.kind === "audio"
|
|
181
|
+
? validateMediaGenerationSettings(input.settings)
|
|
182
|
+
: validateMediaVideoSelection(input.settings);
|
|
183
|
+
const { references, audioReferences, ...settings } = selected;
|
|
184
|
+
const model = getGatewayModel(input.settings.model);
|
|
185
|
+
const format =
|
|
186
|
+
input.kind === "video"
|
|
187
|
+
? "mp4"
|
|
188
|
+
: input.kind === "audio"
|
|
189
|
+
? "mp3"
|
|
190
|
+
: (input.outputFormat ??
|
|
191
|
+
(model?.outputFormats.includes("png")
|
|
192
|
+
? "png"
|
|
193
|
+
: (model?.outputFormats[0] ?? "png")));
|
|
194
|
+
const attach = <
|
|
195
|
+
Reference extends { path: string; computerId?: string | undefined },
|
|
196
|
+
>(
|
|
197
|
+
selection: readonly Reference[],
|
|
198
|
+
) =>
|
|
199
|
+
selection.map((reference) => ({
|
|
200
|
+
...reference,
|
|
201
|
+
computerId: reference.computerId ?? computerId,
|
|
202
|
+
}));
|
|
203
|
+
let attached: MediaGenerationSettings = settings;
|
|
204
|
+
if (references !== undefined)
|
|
205
|
+
attached = { ...attached, references: attach(references) };
|
|
206
|
+
if (audioReferences !== undefined)
|
|
207
|
+
attached = { ...attached, audioReferences: attach(audioReferences) };
|
|
208
|
+
const request: MediaBindingRequest = {
|
|
209
|
+
path: `${input.libraryPath}/prints-${input.requestId}.${format}`,
|
|
210
|
+
settings: attached,
|
|
211
|
+
};
|
|
212
|
+
if (input.kind === "image" && input.outputFormat !== undefined)
|
|
213
|
+
return { ...request, outputFormat: input.outputFormat };
|
|
214
|
+
return request;
|
|
215
|
+
}
|
|
216
|
+
/** Decode bounded service replies once for both MEDIA host bindings. */
|
|
217
|
+
export async function readMediaBindingReply(
|
|
218
|
+
input: MediaBindingCall,
|
|
219
|
+
computerId: string,
|
|
220
|
+
response: Response,
|
|
221
|
+
): Promise<z.core.util.JSONType> {
|
|
222
|
+
const bytes = await readResponseBytes(
|
|
223
|
+
new Response(response.body, { headers: response.headers }),
|
|
224
|
+
240 * 1024,
|
|
225
|
+
);
|
|
226
|
+
const value: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
const failure = mediaFailureSchema.safeParse(value);
|
|
229
|
+
if (!failure.success) return { error: "unavailable" };
|
|
230
|
+
const projected: z.input<typeof appMediaBrokerFailureSchema> = {
|
|
231
|
+
error: failure.data.code,
|
|
232
|
+
message: failure.data.error,
|
|
233
|
+
stage: failure.data.stage,
|
|
234
|
+
retryable: failure.data.retryable,
|
|
235
|
+
};
|
|
236
|
+
if (failure.data.provider !== undefined)
|
|
237
|
+
projected.provider = failure.data.provider;
|
|
238
|
+
return z.json().parse(appMediaBrokerFailureSchema.parse(projected));
|
|
239
|
+
}
|
|
240
|
+
if (input.operation === "models")
|
|
241
|
+
return z.json().parse(mediaModelsSchema.parse(value));
|
|
242
|
+
if (response.status === 202) {
|
|
243
|
+
if (input.input.kind === "image") return { error: "unavailable" };
|
|
244
|
+
return z
|
|
245
|
+
.json()
|
|
246
|
+
.parse(pending(mediaPendingSchema.parse(value).retryAfterSeconds * 1000));
|
|
247
|
+
}
|
|
248
|
+
const result = appMediaGenerationResultSchema.parse(value);
|
|
249
|
+
if (
|
|
250
|
+
result.destination.computerId !== computerId ||
|
|
251
|
+
(input.input.kind === "video"
|
|
252
|
+
? result.format !== "mp4"
|
|
253
|
+
: input.input.kind === "audio"
|
|
254
|
+
? result.format !== "mp3"
|
|
255
|
+
: input.input.outputFormat !== undefined &&
|
|
256
|
+
result.format !== input.input.outputFormat)
|
|
257
|
+
)
|
|
258
|
+
return { error: "unavailable" };
|
|
259
|
+
return z.json().parse(result);
|
|
260
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { ImageFormat } from "./index.js";
|
|
2
|
+
import { isMp4 } from "./gateway-wire.js";
|
|
3
|
+
|
|
4
|
+
/** The image encoding named by the file's magic bytes, if any. */
|
|
5
|
+
export const sniffImageFormat = (
|
|
6
|
+
bytes: Uint8Array,
|
|
7
|
+
): ImageFormat | undefined => {
|
|
8
|
+
if (
|
|
9
|
+
bytes.length >= 8 &&
|
|
10
|
+
bytes[0] === 0x89 &&
|
|
11
|
+
bytes[1] === 0x50 &&
|
|
12
|
+
bytes[2] === 0x4e &&
|
|
13
|
+
bytes[3] === 0x47 &&
|
|
14
|
+
bytes[4] === 0x0d &&
|
|
15
|
+
bytes[5] === 0x0a &&
|
|
16
|
+
bytes[6] === 0x1a &&
|
|
17
|
+
bytes[7] === 0x0a
|
|
18
|
+
)
|
|
19
|
+
return "png";
|
|
20
|
+
if (
|
|
21
|
+
bytes.length >= 3 &&
|
|
22
|
+
bytes[0] === 0xff &&
|
|
23
|
+
bytes[1] === 0xd8 &&
|
|
24
|
+
bytes[2] === 0xff
|
|
25
|
+
)
|
|
26
|
+
return "jpeg";
|
|
27
|
+
if (
|
|
28
|
+
bytes.length >= 6 &&
|
|
29
|
+
bytes[0] === 0x47 &&
|
|
30
|
+
bytes[1] === 0x49 &&
|
|
31
|
+
bytes[2] === 0x46 &&
|
|
32
|
+
bytes[3] === 0x38 &&
|
|
33
|
+
(bytes[4] === 0x37 || bytes[4] === 0x39) &&
|
|
34
|
+
bytes[5] === 0x61
|
|
35
|
+
)
|
|
36
|
+
return "gif";
|
|
37
|
+
if (
|
|
38
|
+
bytes.length >= 12 &&
|
|
39
|
+
bytes[0] === 0x52 &&
|
|
40
|
+
bytes[1] === 0x49 &&
|
|
41
|
+
bytes[2] === 0x46 &&
|
|
42
|
+
bytes[3] === 0x46 &&
|
|
43
|
+
bytes[8] === 0x57 &&
|
|
44
|
+
bytes[9] === 0x45 &&
|
|
45
|
+
bytes[10] === 0x42 &&
|
|
46
|
+
bytes[11] === 0x50
|
|
47
|
+
)
|
|
48
|
+
return "webp";
|
|
49
|
+
return undefined;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** The MIME type for generated bytes, from their magic numbers. */
|
|
53
|
+
export const mediaContentType = (bytes: Uint8Array): string => {
|
|
54
|
+
const image = sniffImageFormat(bytes);
|
|
55
|
+
if (image !== undefined) return `image/${image}`;
|
|
56
|
+
if (isMp4(bytes)) return "video/mp4";
|
|
57
|
+
const id3 = bytes[0] === 0x49 && bytes[1] === 0x44 && bytes[2] === 0x33;
|
|
58
|
+
const frame = bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0;
|
|
59
|
+
return id3 || frame ? "audio/mpeg" : "application/octet-stream";
|
|
60
|
+
};
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import {
|
|
3
|
+
getMediaModel,
|
|
4
|
+
validateMediaGenerationSettings,
|
|
5
|
+
resolveMediaReferences,
|
|
6
|
+
MediaSettingsError,
|
|
7
|
+
} from "./index.js";
|
|
8
|
+
import { resolveMediaAudioReferences } from "./audio-references.js";
|
|
9
|
+
import { estimate } from "./cloudflare/provider.js";
|
|
10
|
+
import { mediaModels } from "./model-catalog.js";
|
|
11
|
+
import { executeMediaOperation } from "./media-operation.js";
|
|
12
|
+
import type { MediaExecution } from "./media-operation-contract.js";
|
|
13
|
+
import { MediaExecutionError } from "./execution-error.js";
|
|
14
|
+
import { mediaResultSchema } from "./media-operation-contract.js";
|
|
15
|
+
import type {
|
|
16
|
+
MediaServiceHost,
|
|
17
|
+
MediaGenerationRequest,
|
|
18
|
+
MediaGenerationOutcome,
|
|
19
|
+
} from "./server.js";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Validate, admit, dispatch and save one generation against `host`. Shared by
|
|
23
|
+
* the `/generate` Hono route and the Agent image tool so both run the exact
|
|
24
|
+
* same admission, billing and destination-write sequence.
|
|
25
|
+
*/
|
|
26
|
+
export function runMediaGeneration(
|
|
27
|
+
host: MediaServiceHost,
|
|
28
|
+
request: MediaGenerationRequest,
|
|
29
|
+
signal?: AbortSignal,
|
|
30
|
+
): Effect.Effect<
|
|
31
|
+
MediaGenerationOutcome,
|
|
32
|
+
MediaExecutionError | MediaSettingsError
|
|
33
|
+
> {
|
|
34
|
+
const catalogue = host.catalogue ?? mediaModels;
|
|
35
|
+
const estimator = host.estimate ?? estimate;
|
|
36
|
+
return Effect.gen(function* () {
|
|
37
|
+
const settings = yield* Effect.try({
|
|
38
|
+
try: () => validateMediaGenerationSettings(request.settings, catalogue),
|
|
39
|
+
catch: () => new MediaSettingsError("invalid generation settings"),
|
|
40
|
+
});
|
|
41
|
+
if (
|
|
42
|
+
request.outputFormat !== undefined &&
|
|
43
|
+
!getMediaModel(settings.model, catalogue)?.outputFormats.includes(
|
|
44
|
+
request.outputFormat,
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
return yield* Effect.fail(
|
|
48
|
+
new MediaSettingsError(
|
|
49
|
+
"model cannot produce the requested image format",
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
const path = request.path;
|
|
53
|
+
const beforeAdmit = host.beforeAdmit;
|
|
54
|
+
if (beforeAdmit !== undefined)
|
|
55
|
+
yield* Effect.tryPromise({
|
|
56
|
+
try: () => beforeAdmit(request.requestId),
|
|
57
|
+
catch: (cause) =>
|
|
58
|
+
new MediaExecutionError("generation-authorization", { cause }),
|
|
59
|
+
});
|
|
60
|
+
const execution: Omit<MediaExecution, "signal"> & {
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
} = {
|
|
63
|
+
embedPrompt: request.embedPrompt,
|
|
64
|
+
operation: host.operations.getByName(`media:${request.requestId}`),
|
|
65
|
+
actorUserId: host.scope.actorId,
|
|
66
|
+
coordinates: {
|
|
67
|
+
namespace: host.scope.namespace,
|
|
68
|
+
owner: host.scope.owner,
|
|
69
|
+
},
|
|
70
|
+
requestId: request.requestId,
|
|
71
|
+
catalogue,
|
|
72
|
+
request: {
|
|
73
|
+
...settings,
|
|
74
|
+
computerId: host.scope.destinationId,
|
|
75
|
+
path,
|
|
76
|
+
outputFormat: request.outputFormat,
|
|
77
|
+
},
|
|
78
|
+
metering: host.metering,
|
|
79
|
+
destination: {
|
|
80
|
+
authorize: () => host.destination.authorize(path),
|
|
81
|
+
write: (bytes) => host.destination.write(path, bytes),
|
|
82
|
+
remove: (sha256) => host.destination.remove(path, { sha256 }),
|
|
83
|
+
},
|
|
84
|
+
generation: {
|
|
85
|
+
prepare: async () => {
|
|
86
|
+
const references = await resolveMediaReferences(
|
|
87
|
+
settings,
|
|
88
|
+
{
|
|
89
|
+
read: (reference, model) => {
|
|
90
|
+
if (host.destination.readReference === undefined)
|
|
91
|
+
throw new MediaSettingsError(
|
|
92
|
+
"reference images are unavailable",
|
|
93
|
+
);
|
|
94
|
+
return host.destination.readReference(reference, model);
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
catalogue,
|
|
98
|
+
);
|
|
99
|
+
const audioReferences = await resolveMediaAudioReferences(
|
|
100
|
+
settings,
|
|
101
|
+
{
|
|
102
|
+
read: (reference) => {
|
|
103
|
+
if (host.destination.readAudioReference === undefined)
|
|
104
|
+
throw new MediaSettingsError(
|
|
105
|
+
"audio references are unavailable",
|
|
106
|
+
);
|
|
107
|
+
return host.destination.readAudioReference(reference);
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
catalogue,
|
|
111
|
+
);
|
|
112
|
+
const costMilliunits = estimator(settings, references);
|
|
113
|
+
// Reference preparation may suspend. This final authority check is
|
|
114
|
+
// the new-generation admission cutoff, before durable dispatch.
|
|
115
|
+
try {
|
|
116
|
+
await host.authorizeGeneration?.();
|
|
117
|
+
} catch (cause) {
|
|
118
|
+
throw new MediaExecutionError("generation-authorization", {
|
|
119
|
+
cause,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
costMilliunits,
|
|
124
|
+
references,
|
|
125
|
+
audioReferences,
|
|
126
|
+
run: (runSignal?: AbortSignal) =>
|
|
127
|
+
host.provider(
|
|
128
|
+
settings,
|
|
129
|
+
references,
|
|
130
|
+
runSignal,
|
|
131
|
+
request.outputFormat,
|
|
132
|
+
audioReferences,
|
|
133
|
+
),
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
if (signal !== undefined) execution.signal = signal;
|
|
139
|
+
const outcome = yield* executeMediaOperation(execution);
|
|
140
|
+
if (outcome.kind === "conflict") return { kind: "conflict" as const };
|
|
141
|
+
if (
|
|
142
|
+
outcome.kind === "accepted" ||
|
|
143
|
+
(outcome.kind === "pending" &&
|
|
144
|
+
getMediaModel(settings.model, catalogue)?.kind !== "image")
|
|
145
|
+
)
|
|
146
|
+
// A video generation runs in the background; retry this request id.
|
|
147
|
+
return {
|
|
148
|
+
kind: "pending" as const,
|
|
149
|
+
background: true,
|
|
150
|
+
retryAfterSeconds: 5,
|
|
151
|
+
};
|
|
152
|
+
if (outcome.kind === "pending")
|
|
153
|
+
return {
|
|
154
|
+
kind: "pending" as const,
|
|
155
|
+
background: false,
|
|
156
|
+
retryAfterSeconds: 5,
|
|
157
|
+
};
|
|
158
|
+
if (outcome.kind === "interrupted") return { kind: "interrupted" as const };
|
|
159
|
+
if (outcome.kind !== "succeeded") return { kind: "unavailable" as const };
|
|
160
|
+
return {
|
|
161
|
+
kind: "succeeded" as const,
|
|
162
|
+
bytes: outcome.bytes,
|
|
163
|
+
costMilliunits: outcome.costMilliunits,
|
|
164
|
+
path,
|
|
165
|
+
format: mediaResultSchema.shape.format.parse(outcome.format),
|
|
166
|
+
model: settings.model,
|
|
167
|
+
height: settings.height,
|
|
168
|
+
width: settings.width,
|
|
169
|
+
};
|
|
170
|
+
});
|
|
171
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import type {
|
|
3
|
+
MediaOperationOwner,
|
|
4
|
+
MediaOperationCoordinates,
|
|
5
|
+
MediaOperationRequest,
|
|
6
|
+
} from "./media-operation-owner.js";
|
|
7
|
+
import type { MediaRemoval } from "./media-written.js";
|
|
8
|
+
import type { MediaUnits } from "./gateway-models.js";
|
|
9
|
+
import type {
|
|
10
|
+
MediaAudioReferenceBytes,
|
|
11
|
+
MediaCatalogue,
|
|
12
|
+
MediaReferenceBytes,
|
|
13
|
+
} from "./index.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The host's billing owner for Media. Every call is keyed by the durable
|
|
17
|
+
* operation id and must be idempotent: a lost acknowledgement is retried with
|
|
18
|
+
* the same id and must never admit, hold, or charge twice.
|
|
19
|
+
*/
|
|
20
|
+
export type MediaMetering = Readonly<{
|
|
21
|
+
/**
|
|
22
|
+
* Admit one generation and hold its price before any provider dispatch.
|
|
23
|
+
* Throws {@link MediaBillingRefusal} for a definitive refusal. Returns the
|
|
24
|
+
* customer price in milliunits (1 cent = 1,000 milliunits).
|
|
25
|
+
*/
|
|
26
|
+
admit: (
|
|
27
|
+
input: Readonly<{
|
|
28
|
+
/** Durable operation name. */
|
|
29
|
+
operationId: string;
|
|
30
|
+
/** Provider catalog model identifier. */
|
|
31
|
+
model: string;
|
|
32
|
+
/** Billing unit and count: one image, or seconds of video. */
|
|
33
|
+
unit: MediaUnits["unit"];
|
|
34
|
+
/** Number of admitted or delivered units. */
|
|
35
|
+
units: number;
|
|
36
|
+
/** Provider cost of all units together. */
|
|
37
|
+
providerCostMilliunits: number;
|
|
38
|
+
}>,
|
|
39
|
+
) => Promise<
|
|
40
|
+
Readonly<{
|
|
41
|
+
/** Host-admitted customer price. */
|
|
42
|
+
priceMilliunits: number;
|
|
43
|
+
}>
|
|
44
|
+
>;
|
|
45
|
+
/** Settle delivered units: all admitted units once saved, 0 when nothing was delivered. */
|
|
46
|
+
settle: (
|
|
47
|
+
input: Readonly<{
|
|
48
|
+
/** Durable operation name. */
|
|
49
|
+
operationId: string;
|
|
50
|
+
/** Number of admitted or delivered units. */
|
|
51
|
+
units: number;
|
|
52
|
+
}>,
|
|
53
|
+
) => Promise<void>;
|
|
54
|
+
}>;
|
|
55
|
+
|
|
56
|
+
/** Local or RPC methods consumed by a replay-safe generation. */
|
|
57
|
+
export type MediaOperation = {
|
|
58
|
+
[
|
|
59
|
+
Method in
|
|
60
|
+
| "admit"
|
|
61
|
+
| "claim"
|
|
62
|
+
| "dispatchInBackground"
|
|
63
|
+
| "interruptGeneration"
|
|
64
|
+
| "readGenerated"
|
|
65
|
+
| "recordEstimate"
|
|
66
|
+
| "recordGenerated"
|
|
67
|
+
| "recordSucceeded"
|
|
68
|
+
| "recordWritten"
|
|
69
|
+
| "recordWrittenWithoutSettlement"
|
|
70
|
+
| "releaseEstimate"
|
|
71
|
+
| "releaseWrite"
|
|
72
|
+
| "recordWriteIntent"
|
|
73
|
+
| "retained"
|
|
74
|
+
| "readRetained"
|
|
75
|
+
| "erase"
|
|
76
|
+
]: (
|
|
77
|
+
...input: Parameters<MediaOperationOwner[Method]>
|
|
78
|
+
) =>
|
|
79
|
+
| ReturnType<MediaOperationOwner[Method]>
|
|
80
|
+
| Promise<Awaited<ReturnType<MediaOperationOwner[Method]>>>;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Admitted identity, durable operation and host effects for one generation. */
|
|
84
|
+
export type MediaExecution = Readonly<{
|
|
85
|
+
/** Durable owner methods for this generation. */
|
|
86
|
+
operation: MediaOperation;
|
|
87
|
+
/** Host-admitted actor identifier. */
|
|
88
|
+
actorUserId: string;
|
|
89
|
+
/** Host namespace and owner identity. */
|
|
90
|
+
coordinates: MediaOperationCoordinates;
|
|
91
|
+
/** Stable caller request identity reused on retries. */
|
|
92
|
+
requestId: string;
|
|
93
|
+
/** Captured generation and fixed destination. */
|
|
94
|
+
request: MediaOperationRequest;
|
|
95
|
+
/** The active provider's model list; omitted means the Fungi gateway's. */
|
|
96
|
+
catalogue?: MediaCatalogue | undefined;
|
|
97
|
+
/** The billing owner, or `unmetered` when the host pays its own provider. */
|
|
98
|
+
metering: MediaMetering | "unmetered";
|
|
99
|
+
/** Optional cancellation signal. */
|
|
100
|
+
signal?: AbortSignal;
|
|
101
|
+
/**
|
|
102
|
+
* Publish the prompt in the image's XMP as `fungi:prompt`. Omitted or false
|
|
103
|
+
* keeps the prompt out of the file: a host must opt in per generation.
|
|
104
|
+
*/
|
|
105
|
+
embedPrompt?: boolean | undefined;
|
|
106
|
+
/** Host-owned destination authorization and writing. */
|
|
107
|
+
destination: Readonly<{
|
|
108
|
+
/** Check host permission before writing or dispatching generation. */
|
|
109
|
+
authorize: () => Promise<void>;
|
|
110
|
+
/** Save exact generated bytes to the admitted destination. */
|
|
111
|
+
write: (bytes: Uint8Array) => Promise<void>;
|
|
112
|
+
/**
|
|
113
|
+
* Delete the file this generation wrote, only while it still holds the
|
|
114
|
+
* bytes with this SHA-256. Called when the operation was erased while the
|
|
115
|
+
* write was in flight, so the saved file does not outlive it.
|
|
116
|
+
*/
|
|
117
|
+
remove: (sha256: string) => Promise<MediaRemoval>;
|
|
118
|
+
}>;
|
|
119
|
+
/** Reference preparation and provider dispatch effects. */
|
|
120
|
+
generation: Readonly<{
|
|
121
|
+
/** Resolve references and price before provider dispatch. */
|
|
122
|
+
prepare: () => Promise<
|
|
123
|
+
Readonly<{
|
|
124
|
+
/** Estimated provider cost in milliunits, where 1 cent is 1,000 milliunits. */
|
|
125
|
+
costMilliunits: number;
|
|
126
|
+
/** Host-authorized reference images. */
|
|
127
|
+
references: readonly MediaReferenceBytes[];
|
|
128
|
+
/** Host-authorized reference audio clips, parsed and within the model's budget. */
|
|
129
|
+
audioReferences: readonly MediaAudioReferenceBytes[];
|
|
130
|
+
/** Dispatch one provider call with the prepared inputs. */
|
|
131
|
+
run: (signal?: AbortSignal) => Promise<
|
|
132
|
+
Readonly<{
|
|
133
|
+
/** Generated output bytes. */
|
|
134
|
+
bytes: Uint8Array;
|
|
135
|
+
/** Actual output encoding. */
|
|
136
|
+
format: string;
|
|
137
|
+
}>
|
|
138
|
+
>;
|
|
139
|
+
}>
|
|
140
|
+
>;
|
|
141
|
+
}>;
|
|
142
|
+
}>;
|
|
143
|
+
|
|
144
|
+
/** Decode a completed generation, destination path and estimated or settled price. */
|
|
145
|
+
export const mediaResultSchema = z.strictObject({
|
|
146
|
+
/** Output byte length. */
|
|
147
|
+
bytes: z.number().int().positive(),
|
|
148
|
+
/** Admitted price in milliunits, where 1 cent is 1,000 milliunits. */
|
|
149
|
+
costMilliunits: z.number().int().nonnegative(),
|
|
150
|
+
/** Fixed destination or reference file path. */
|
|
151
|
+
path: z.string().min(1).max(1_024),
|
|
152
|
+
/** Actual output encoding. */
|
|
153
|
+
format: z.enum({
|
|
154
|
+
/** PNG image encoding. */
|
|
155
|
+
png: "png",
|
|
156
|
+
/** JPEG image encoding. */
|
|
157
|
+
jpeg: "jpeg",
|
|
158
|
+
/** GIF image encoding. */
|
|
159
|
+
gif: "gif",
|
|
160
|
+
/** WebP image encoding. */
|
|
161
|
+
webp: "webp",
|
|
162
|
+
/** MP4 video encoding. */
|
|
163
|
+
mp4: "mp4",
|
|
164
|
+
/** MP3 audio encoding. */
|
|
165
|
+
mp3: "mp3",
|
|
166
|
+
}),
|
|
167
|
+
/** Requested image height or nominal video selector, not decoded MP4 dimensions; absent for audio. */
|
|
168
|
+
height: z.number().int().positive().optional(),
|
|
169
|
+
/** Provider catalog model identifier. */
|
|
170
|
+
model: z.string().min(1).max(256),
|
|
171
|
+
/** Requested image width or nominal video selector, not decoded MP4 dimensions; absent for audio. */
|
|
172
|
+
width: z.number().int().positive().optional(),
|
|
173
|
+
});
|