@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.
Files changed (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +8 -2
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
@@ -0,0 +1,136 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { readFile } from "node:fs/promises";
3
+ import * as ts from "typescript";
4
+ import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
5
+ import { validateMediaGenerationSettings } from "../src/index.js";
6
+ import {
7
+ MediaExecutionError,
8
+ MediaSafetyFilterRefusal,
9
+ } from "../src/execution-error.js";
10
+
11
+ // The cheapest catalog video selection. These tests never dispatch to a provider.
12
+ const settings = validateMediaGenerationSettings({
13
+ model: "bytedance/seedance-2.0-mini",
14
+ prompt: "fern fronds unfurling",
15
+ width: 854,
16
+ height: 480,
17
+ durationSeconds: 4,
18
+ });
19
+ const resultUrl = "https://results.example/clip.mp4";
20
+ const completed: MediaAiPort = {
21
+ run: () =>
22
+ Promise.resolve({
23
+ state: "Completed",
24
+ result: { video: resultUrl },
25
+ }),
26
+ };
27
+ const mp4 = Uint8Array.from([
28
+ 0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,
29
+ 0x69, 0x73, 0x6f, 0x6d, 0x6d, 0x70, 0x34, 0x31,
30
+ ]);
31
+
32
+ describe("video provider failure diagnostics", () => {
33
+ it("reaches the real video decoder and output download with offline ports", async () => {
34
+ const downloaded: string[] = [];
35
+ const fetchResult: typeof fetch = (input) => {
36
+ downloaded.push(
37
+ input instanceof Request
38
+ ? input.url
39
+ : input instanceof URL
40
+ ? input.href
41
+ : input,
42
+ );
43
+ return Promise.resolve(new Response(mp4));
44
+ };
45
+ await expect(
46
+ generate(completed, settings, [], undefined, undefined, fetchResult),
47
+ ).resolves.toEqual({ bytes: mp4, format: "mp4" });
48
+ expect(downloaded).toEqual([resultUrl]);
49
+ });
50
+
51
+ it("retains a bounded provider category and code without the upstream message", async () => {
52
+ // Workers AI's ordinary Error representation, not an executable-object fixture.
53
+ const failure = new Error("3031: sanitized upstream failure");
54
+ failure.name = "InferenceUpstreamError";
55
+ const ai: MediaAiPort = { run: () => Promise.reject(failure) };
56
+ await expect(generate(ai, settings, [])).rejects.toMatchObject({
57
+ stage: "provider",
58
+ provider: { category: "InferenceUpstreamError", code: 3031 },
59
+ });
60
+ });
61
+
62
+ it("retains the native HTTP status when downloading a completed video fails", async () => {
63
+ let downloads = 0;
64
+ const fetchResult: typeof fetch = () => {
65
+ downloads++;
66
+ return Promise.resolve(new Response(null, { status: 503 }));
67
+ };
68
+ await expect(
69
+ generate(completed, settings, [], undefined, undefined, fetchResult),
70
+ ).rejects.toMatchObject({
71
+ stage: "normalization",
72
+ provider: { category: "result_download", status: 503 },
73
+ });
74
+ expect(downloads).toBe(1);
75
+ });
76
+
77
+ it("does not expose an arbitrary upstream name, message or cause in diagnostic JSON", async () => {
78
+ const marker = "synthetic-private-prompt-and-result-url";
79
+ const failure = new Error(marker);
80
+ failure.name = marker;
81
+ const ai: MediaAiPort = { run: () => Promise.reject(failure) };
82
+ const error: unknown = await generate(ai, settings, []).catch(
83
+ (cause: unknown) => cause,
84
+ );
85
+ expect(error).toBeInstanceOf(MediaExecutionError);
86
+ expect(error).toMatchObject({
87
+ stage: "provider",
88
+ provider: { category: "Error", code: null },
89
+ });
90
+ expect(JSON.stringify(error)).not.toContain(marker);
91
+ });
92
+
93
+ it("preserves safety-refusal identity without exposing the refusal message", async () => {
94
+ const marker = "synthetic-private-safety-details";
95
+ const failure = new Error(
96
+ `3031: AiError: Input prompt contains NSFW content. ${marker}`,
97
+ );
98
+ failure.name = "InferenceUpstreamError";
99
+ const ai: MediaAiPort = { run: () => Promise.reject(failure) };
100
+ const error: unknown = await generate(ai, settings, []).catch(
101
+ (cause: unknown) => cause,
102
+ );
103
+ expect(error).toBeInstanceOf(MediaSafetyFilterRefusal);
104
+ expect(error).toMatchObject({
105
+ provider: { category: "InferenceUpstreamError", code: 3031 },
106
+ });
107
+ expect(JSON.stringify(error)).not.toContain(marker);
108
+ });
109
+ });
110
+
111
+ describe("safe provider diagnostic contract", () => {
112
+ it("does not add Effect imports to the generated error declaration", async () => {
113
+ const declaration = await readFile(
114
+ new URL("../dist/execution-error.d.ts", import.meta.url),
115
+ "utf8",
116
+ );
117
+ const source = ts.createSourceFile(
118
+ "execution-error.d.ts",
119
+ declaration,
120
+ ts.ScriptTarget.Latest,
121
+ true,
122
+ ts.ScriptKind.TS,
123
+ );
124
+ const effectReferences: string[] = [];
125
+ function visit(node: ts.Node) {
126
+ if (
127
+ ts.isStringLiteral(node) &&
128
+ (node.text === "effect" || node.text.startsWith("effect/"))
129
+ )
130
+ effectReferences.push(node.text);
131
+ ts.forEachChild(node, visit);
132
+ }
133
+ visit(source);
134
+ expect(effectReferences).toEqual([]);
135
+ });
136
+ });
@@ -0,0 +1,251 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import * as Schema from "effect/Schema";
3
+ import { listMediaModels } from "../src/index.js";
4
+ import {
5
+ appMediaGenerationResultSchema,
6
+ destinationSchema,
7
+ mediaModelsSchema,
8
+ appMediaGenerationOutcomeSchema,
9
+ appMediaModelsOutcomeSchema,
10
+ appMediaBrokerFailureSchema,
11
+ } from "../src/app-media-contracts.js";
12
+ import {
13
+ mediaModelSchema,
14
+ mediaVideoSelectionSchema,
15
+ mediaVideoResultSchema,
16
+ parseMediaGenerationInput,
17
+ } from "@fungi.computer/agar/media";
18
+ const decode = <A>(schema: Schema.Codec<A>, raw: unknown) =>
19
+ Schema.decodeUnknownSync(schema, { onExcessProperty: "error" })(raw);
20
+ describe("App broker media contract leaves", () => {
21
+ it("keeps transformed failures and Agar polling separate from HTTP and transport envelopes", () => {
22
+ const failure = {
23
+ error: "HOST_FAILURE",
24
+ message: "Media output could not be retained.",
25
+ stage: "artifact",
26
+ retryable: true,
27
+ };
28
+ expect(appMediaBrokerFailureSchema.parse(failure)).toEqual(failure);
29
+ expect(appMediaGenerationOutcomeSchema.parse(failure)).toEqual(failure);
30
+ const pending = { kind: "pending", retryAfterMs: 5000 };
31
+ expect(appMediaGenerationOutcomeSchema.parse(pending)).toEqual(pending);
32
+ expect(appMediaModelsOutcomeSchema.safeParse(pending).success).toBe(false);
33
+ for (const payload of [
34
+ {
35
+ error: failure.message,
36
+ code: failure.error,
37
+ stage: failure.stage,
38
+ retryable: failure.retryable,
39
+ },
40
+ { kind: "local_refusal", code: "denied" },
41
+ { error: "unknown" },
42
+ {
43
+ error: "attachment_budget_exceeded",
44
+ kind: "exec",
45
+ retryAfterMs: 95_000,
46
+ },
47
+ { error: "attachment_budget_exceeded", kind: "media" },
48
+ { status: "pending", retryAfterSeconds: 5 },
49
+ ]) {
50
+ expect(appMediaGenerationOutcomeSchema.safeParse(payload).success).toBe(
51
+ false,
52
+ );
53
+ }
54
+ expect(
55
+ appMediaGenerationOutcomeSchema.parse({
56
+ error: "library_unavailable",
57
+ message: "",
58
+ }),
59
+ ).toEqual({ error: "library_unavailable", message: "" });
60
+ expect(
61
+ appMediaGenerationOutcomeSchema.safeParse({
62
+ error: "library_unavailable",
63
+ message: "x".repeat(4097),
64
+ }).success,
65
+ ).toBe(false);
66
+ for (const error of ["invalid", "too_large"]) {
67
+ expect(appMediaGenerationOutcomeSchema.parse({ error })).toEqual({
68
+ error,
69
+ });
70
+ }
71
+ });
72
+ it("accepts the whole maintained catalog and bounds repeated entries", () => {
73
+ const models = listMediaModels();
74
+ expect(mediaModelsSchema.parse(models)).toEqual(models);
75
+ expect(mediaModelsSchema.parse([])).toEqual([]);
76
+ expect(mediaModelsSchema.safeParse([...models, ...models]).success).toBe(
77
+ false,
78
+ );
79
+ expect(mediaModelsSchema.safeParse([{ id: "unknown" }]).success).toBe(
80
+ false,
81
+ );
82
+ });
83
+
84
+ it("preserves the admitted Computer and absolute destination bounds", () => {
85
+ expect(
86
+ destinationSchema.parse({ computerId: "computer", path: "/" }),
87
+ ).toEqual({
88
+ computerId: "computer",
89
+ path: "/",
90
+ });
91
+ expect(
92
+ destinationSchema.safeParse({ computerId: "", path: "/print.png" })
93
+ .success,
94
+ ).toBe(false);
95
+ expect(
96
+ destinationSchema.safeParse({ computerId: "c".repeat(257), path: "/" })
97
+ .success,
98
+ ).toBe(false);
99
+ expect(
100
+ destinationSchema.safeParse({ computerId: "computer", path: "print.png" })
101
+ .success,
102
+ ).toBe(false);
103
+ expect(
104
+ destinationSchema.safeParse({
105
+ computerId: "computer",
106
+ path: "/".repeat(1025),
107
+ }).success,
108
+ ).toBe(false);
109
+ });
110
+
111
+ it("decodes completed outputs without treating pending or host failures as results", () => {
112
+ const result = {
113
+ bytes: 1,
114
+ costMilliunits: 0,
115
+ format: "png",
116
+ height: 1,
117
+ model: "model",
118
+ width: 1,
119
+ destination: { computerId: "computer", path: "/print.png" },
120
+ };
121
+ expect(appMediaGenerationResultSchema.parse(result)).toEqual(result);
122
+ expect(
123
+ appMediaGenerationResultSchema.safeParse({
124
+ ...result,
125
+ path: "/print.png",
126
+ }).success,
127
+ ).toBe(false);
128
+ expect(
129
+ appMediaGenerationResultSchema.safeParse({ ...result, bytes: 0 }).success,
130
+ ).toBe(false);
131
+ expect(
132
+ appMediaGenerationResultSchema.safeParse({
133
+ kind: "pending",
134
+ retryAfterMs: 5000,
135
+ }).success,
136
+ ).toBe(false);
137
+ expect(
138
+ appMediaGenerationResultSchema.safeParse({
139
+ error: "HOST_FAILURE",
140
+ message: "unavailable",
141
+ stage: "artifact",
142
+ retryable: true,
143
+ }).success,
144
+ ).toBe(false);
145
+ });
146
+ });
147
+ describe("Agar-owned video wire and Darkroom host catalog", () => {
148
+ it("decodes the actual host catalog, including every video price and role", () => {
149
+ for (const model of listMediaModels())
150
+ expect(decode(mediaModelSchema, model)).toEqual(model);
151
+ });
152
+ it("preserves video selectors and every reference role when normalizing an admitted selection", () => {
153
+ const parsed = parseMediaGenerationInput({
154
+ destination: { path: " prints-id.mp4 " },
155
+ settings: {
156
+ model: "bytedance/seedance-2.0",
157
+ prompt: " fronds ",
158
+ width: 5040,
159
+ height: 2160,
160
+ resolution: "4k",
161
+ aspectRatio: "21:9",
162
+ generateAudio: false,
163
+ durationSeconds: 5,
164
+ references: [
165
+ { path: " first.png ", role: "first-frame" },
166
+ { path: "last.png", role: "last-frame" },
167
+ ],
168
+ },
169
+ });
170
+ expect(
171
+ parsed.settings.references?.map((reference) => reference.role),
172
+ ).toEqual(["first-frame", "last-frame"]);
173
+ expect(parsed.settings).toMatchObject({
174
+ prompt: "fronds",
175
+ resolution: "4k",
176
+ aspectRatio: "21:9",
177
+ generateAudio: false,
178
+ });
179
+ expect(parsed.destination.path).toBe("prints-id.mp4");
180
+ expect(() =>
181
+ parseMediaGenerationInput({
182
+ destination: parsed.destination,
183
+ settings: { ...parsed.settings, width: 5041 },
184
+ }),
185
+ ).toThrow();
186
+ });
187
+ it("refuses frame roles on the destination instead of silently discarding them", () => {
188
+ const input = {
189
+ destination: { path: "prints-id.mp4", role: "first-frame" },
190
+ settings: {
191
+ model: "host-model",
192
+ prompt: "fronds",
193
+ width: 720,
194
+ height: 720,
195
+ },
196
+ };
197
+ expect(() => parseMediaGenerationInput(input)).toThrow();
198
+ });
199
+ it("decodes the neutral path-only selection without accepting host authority", () => {
200
+ const input = {
201
+ model: "google/veo-3.1",
202
+ prompt: "fronds",
203
+ durationSeconds: 6,
204
+ references: [{ path: "first.png", role: "first-frame" }],
205
+ };
206
+ expect(decode(mediaVideoSelectionSchema, input)).toEqual(input);
207
+ expect(() =>
208
+ decode(mediaVideoSelectionSchema, { ...input, computerId: "forged" }),
209
+ ).toThrow();
210
+ });
211
+ it.each([
212
+ { role: "last" },
213
+ { durationSeconds: 3 },
214
+ { durationSeconds: 16 },
215
+ { durationSeconds: 4.5 },
216
+ { references: [{ path: "first.png", role: "video" }] },
217
+ { references: [{ path: "first.png" }] },
218
+ { references: [{ path: "", role: "first-frame" }] },
219
+ {
220
+ references: Array.from({ length: 5 }, () => ({
221
+ path: "ref.png",
222
+ role: "reference",
223
+ })),
224
+ },
225
+ { resolution: "8k" },
226
+ { aspectRatio: "auto" },
227
+ ])("refuses unsupported wire fields or bounds %j", (invalid) => {
228
+ expect(() =>
229
+ decode(mediaVideoSelectionSchema, {
230
+ model: "host-model",
231
+ prompt: "fronds",
232
+ ...invalid,
233
+ }),
234
+ ).toThrow();
235
+ });
236
+ it("decodes a completed MP4 and refuses an image result in the video wire", () => {
237
+ const result = {
238
+ bytes: 12,
239
+ costMilliunits: 60000,
240
+ destination: { computerId: "admitted", path: "prints-id.mp4" },
241
+ format: "mp4",
242
+ height: 720,
243
+ model: "google/veo-3.1-fast",
244
+ width: 1280,
245
+ };
246
+ expect(decode(mediaVideoResultSchema, result)).toEqual(result);
247
+ expect(() =>
248
+ decode(mediaVideoResultSchema, { ...result, format: "png" }),
249
+ ).toThrow();
250
+ });
251
+ });
@@ -0,0 +1,22 @@
1
+ import { cloudflareTest } from "@cloudflare/vitest-plugin";
2
+ import { defineConfig } from "vitest/config";
3
+
4
+ export default defineConfig({
5
+ root: import.meta.dirname,
6
+ plugins: [
7
+ cloudflareTest({
8
+ main: "./test/standalone.worker.mjs",
9
+ remoteBindings: false,
10
+ miniflare: {
11
+ compatibilityDate: "2026-09-02",
12
+ bindings: { MEDIA_TOKEN: "local-media-proof" },
13
+ durableObjects: {
14
+ MEDIA_HOST: { className: "StandaloneMedia", useSQLite: true },
15
+ MEDIA_OPERATION: { className: "MediaOperationDO", useSQLite: true },
16
+ },
17
+ r2Buckets: ["APP_ARTIFACTS", "OUTPUTS", "PROOF"],
18
+ },
19
+ }),
20
+ ],
21
+ test: { include: ["test/standalone.cloudflare.test.mjs"] },
22
+ });
@@ -0,0 +1,14 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ resolve: {
5
+ alias: {
6
+ // Darkroom's own host, so the shipped tests run from the package too.
7
+ "cloudflare:workers": new URL(
8
+ "test/fixtures/cloudflare-workers.fixture.ts",
9
+ import.meta.url,
10
+ ).pathname,
11
+ },
12
+ },
13
+ test: { include: ["test/**/*.test.ts"] },
14
+ });