@skyphusion/create-prism 0.1.0 → 0.175.6

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 (54) hide show
  1. package/README.md +5 -3
  2. package/index.js +4 -2
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +6 -2
  5. package/template/README.md +45 -33
  6. package/template/docs/legal/README.md +1 -0
  7. package/template/migrations/0002_auth_public_mode.sql +32 -0
  8. package/template/package.json +6 -6
  9. package/template/public/app.js +44 -16
  10. package/template/public/index.html +47 -4
  11. package/template/src/auth-kdf.ts +7 -4
  12. package/template/src/auth.ts +11 -2
  13. package/template/src/control-plane.ts +254 -0
  14. package/template/src/env.ts +15 -0
  15. package/template/src/gateway-credentials.ts +23 -4
  16. package/template/src/health-schema.ts +4 -0
  17. package/template/src/index.ts +65 -3982
  18. package/template/src/longrun-params.ts +4 -2
  19. package/template/src/models.ts +65 -19
  20. package/template/src/output-extract.ts +58 -8
  21. package/template/src/parsers/openai-sse.ts +43 -14
  22. package/template/src/providers/anthropic.ts +105 -0
  23. package/template/src/providers/openai-image.ts +66 -0
  24. package/template/src/providers/openai.ts +79 -13
  25. package/template/src/providers/xai.ts +91 -0
  26. package/template/src/proxied-image-params.ts +29 -16
  27. package/template/src/routes/artifacts.ts +51 -0
  28. package/template/src/routes/chat.ts +1709 -0
  29. package/template/src/routes/conversations.ts +212 -0
  30. package/template/src/routes/documents.ts +262 -0
  31. package/template/src/routes/health.ts +105 -0
  32. package/template/src/routes/history.ts +92 -0
  33. package/template/src/routes/prefs.ts +95 -0
  34. package/template/src/routes/projects.ts +574 -0
  35. package/template/src/routes/rag.ts +657 -0
  36. package/template/src/routes/shared.ts +226 -0
  37. package/template/src/routes/workflow.ts +304 -0
  38. package/template/src/user-prefs.ts +10 -0
  39. package/template/src/zip.ts +7 -0
  40. package/template/tests/anthropic-binding.test.ts +181 -0
  41. package/template/tests/control-plane.test.ts +112 -0
  42. package/template/tests/gateway-credentials.test.ts +37 -0
  43. package/template/tests/longrun-params.test.ts +19 -0
  44. package/template/tests/openai-image.test.ts +47 -0
  45. package/template/tests/openai-responses.test.ts +78 -0
  46. package/template/tests/openai-sse.test.ts +28 -0
  47. package/template/tests/output-extract.test.ts +75 -1
  48. package/template/tests/proxied-image-params.test.ts +16 -7
  49. package/template/tests/sprint1-catalog.test.ts +27 -0
  50. package/template/tests/sprint2-catalog.test.ts +51 -0
  51. package/template/tests/sprint3-catalog.test.ts +29 -0
  52. package/template/tests/xai-binding.test.ts +127 -0
  53. package/template/tests-integration/worker.test.ts +9 -2
  54. package/template/wrangler.example.toml +19 -7
@@ -44,10 +44,12 @@ function imageToVideoParams(
44
44
  const motion = prompt && prompt.trim() ? prompt : DEFAULT_MOTION_PROMPT;
45
45
 
46
46
  switch (modelId) {
47
- // ByteDance Seedance 2.0: field `image`; integer duration 4-12; resolution
48
- // 480p/720p/1080p; aspect_ratio. generate_audio off (we score separately).
47
+ // ByteDance Seedance 2.0 family: field `image`; integer duration 4-12;
48
+ // resolution 480p/720p (mini caps at 720p); aspect_ratio. generate_audio
49
+ // off (we score separately). v0.170.0: seedance-2.0-mini shares this shape.
49
50
  case "bytedance/seedance-2.0":
50
51
  case "bytedance/seedance-2.0-fast":
52
+ case "bytedance/seedance-2.0-mini":
51
53
  return {
52
54
  image: imageUrl,
53
55
  prompt: motion,
@@ -36,7 +36,8 @@ export type Provider =
36
36
  | "alibaba"
37
37
  | "pixverse"
38
38
  | "vidu"
39
- | "recraft";
39
+ | "recraft"
40
+ | "moonshotai";
40
41
 
41
42
  export interface ModelEntry {
42
43
  id: string;
@@ -51,6 +52,16 @@ export interface ModelEntry {
51
52
  // (server-sent events). Covers Anthropic, Workers AI, xAI, OpenAI, and
52
53
  // Google. Chat models only - irrelevant for image/tts/video/stt/music types.
53
54
  streaming?: boolean;
55
+ // v0.169.0 / v0.170.0: when true, dispatch through the env.AI.run binding
56
+ // (the new CF Unified Billing catalog surface) instead of the legacy AI
57
+ // Gateway provider-fetch path. Used when the frozen legacy allowlist would
58
+ // forward an unknown id keyless (provider 401). See anthropic.ts / xai.ts.
59
+ binding?: boolean;
60
+ // v0.173.0: OpenAI request surface. Default (omitted) is Chat Completions
61
+ // ({ messages }). "responses" uses the Responses API ({ input, instructions,
62
+ // max_output_tokens }) for models that only ship that format (gpt-5.6-*,
63
+ // gpt-5.5-pro). See src/providers/openai.ts.
64
+ api?: "responses";
54
65
  }
55
66
 
56
67
  export const MODELS: ModelEntry[] = [
@@ -58,8 +69,16 @@ export const MODELS: ModelEntry[] = [
58
69
  // Anthropic (Unified Billing via cf-aig-authorization, routed through AI Gateway)
59
70
  // v0.13.0: streaming: true makes these eligible for POST /api/chat/stream.
60
71
  // v0.165.0 catalog refresh (#81): Claude 5 family added.
61
- // removed v0.167.1: anthropic/claude-fable-5 -- CF Unified Billing does not accept the id yet (502 gateway refusal, 2026-07-18 live smoke); re-add when developers.cloudflare.com lists it
72
+ // v0.169.0 (#169): claude-fable-5 re-added via the env.AI.run binding
73
+ // (binding: true). CF moved new-model onboarding to the Unified Billing
74
+ // catalog surface; the legacy AI Gateway anthropic allowlist is frozen and
75
+ // forwards this id keyless (provider 401, surfaced as a 502). The binding
76
+ // path injects credentials. Dispatch lives in src/providers/anthropic.ts.
77
+ { id: "anthropic/claude-fable-5", label: "Claude Fable 5 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true, binding: true },
62
78
  { id: "anthropic/claude-sonnet-5", label: "Claude Sonnet 5 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
79
+ // v0.170.0: Claude Opus 5 (near-Fable intelligence, lower price). New CF
80
+ // Unified Billing onboarding; binding path required (legacy allowlist frozen).
81
+ { id: "anthropic/claude-opus-5", label: "Claude Opus 5 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true, binding: true },
63
82
  { id: "anthropic/claude-opus-4-8", label: "Claude Opus 4.8 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
64
83
  { id: "anthropic/claude-opus-4-7", label: "Claude Opus 4.7 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
65
84
  { id: "anthropic/claude-opus-4-6", label: "Claude Opus 4.6 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
@@ -67,13 +86,24 @@ export const MODELS: ModelEntry[] = [
67
86
  { id: "anthropic/claude-haiku-4-5", label: "Claude Haiku 4.5 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
68
87
 
69
88
  // xAI / Grok (Unified Billing via cf-aig-authorization, routed through AI Gateway)
70
- // removed v0.167.1: xai/grok-4.5 -- CF Unified Billing does not accept the id yet (502 gateway refusal, 2026-07-18 live smoke); re-add when developers.cloudflare.com lists it
89
+ // v0.170.0: grok-4.5 re-added via env.AI.run binding (binding: true). CF docs
90
+ // now list it on the Unified Billing catalog with working env.AI.run examples;
91
+ // legacy gateway allowlist remains frozen for new ids.
92
+ { id: "xai/grok-4.5", label: "Grok 4.5 (xAI)", group: "Chat \u00b7 xAI", type: "chat", capabilities: ["vision"], provider: "xai", streaming: true, binding: true },
71
93
  { id: "xai/grok-4.3", label: "Grok 4.3 (xAI)", group: "Chat \u00b7 xAI", type: "chat", capabilities: ["vision"], provider: "xai", streaming: true },
72
94
  { id: "xai/grok-4.20-multi-agent-0309", label: "Grok 4.20 Multi-Agent (xAI)", group: "Chat \u00b7 xAI", type: "chat", capabilities: ["vision"], provider: "xai", streaming: true },
73
95
  { id: "xai/grok-4.20-0309-reasoning", label: "Grok 4.20 Reasoning (xAI)", group: "Chat \u00b7 xAI", type: "chat", capabilities: ["vision"], provider: "xai", streaming: true },
74
- // removed v0.167.1: xai/grok-build-0.1 -- CF Unified Billing does not accept the id yet (502 gateway refusal, 2026-07-18 live smoke); re-add when developers.cloudflare.com lists it
96
+ // blocked (v0.169.0): xai/grok-build-0.1 is absent from the new CF Unified
97
+ // Billing catalog, and the legacy AI Gateway allowlist is frozen (forwards
98
+ // unknown ids keyless -> provider 401). Re-add when
99
+ // env.AI.run("xai/grok-build-0.1") resolves, not when a docs page updates.
75
100
 
76
101
  // Frontier
102
+ // v0.171.0: Kimi K3 is third-party Unified Billing (moonshotai/*), not Workers
103
+ // AI (@cf/moonshotai/*). Chat Completions via env.AI.run; stream reuses the
104
+ // OpenAI-compatible SSE path (callOpenAIStream). Vision claimed upstream;
105
+ // multimodal-in through the proxy is unsmoked, so caps stay empty like OpenAI.
106
+ { id: "moonshotai/kimi-k3", label: "Kimi K3 (Moonshot, 1M ctx)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: [], provider: "moonshotai", streaming: true },
77
107
  { id: "@cf/moonshotai/kimi-k2.6", label: "Kimi K2.6 (1T)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: ["vision"], streaming: true },
78
108
  { id: "@cf/moonshotai/kimi-k2.7-code", label: "Kimi K2.7 Code (1T, vision)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: ["vision"], streaming: true },
79
109
  { id: "@cf/openai/gpt-oss-120b", label: "GPT-OSS 120B (reasoning)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: [], streaming: true },
@@ -91,6 +121,11 @@ export const MODELS: ModelEntry[] = [
91
121
  // capabilities is empty: multimodal-in through the proxied binding is
92
122
  // unverified, so the attach affordance stays off.
93
123
  { id: "openai/gpt-5.5", label: "GPT-5.5 (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
124
+ // v0.173.0: Responses API only (not Chat Completions). Flagged api:"responses".
125
+ { id: "openai/gpt-5.5-pro", label: "GPT-5.5 Pro (OpenAI, Responses)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true, api: "responses" },
126
+ { id: "openai/gpt-5.6-sol", label: "GPT-5.6 Sol (OpenAI, Responses)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true, api: "responses" },
127
+ { id: "openai/gpt-5.6-terra", label: "GPT-5.6 Terra (OpenAI, Responses)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true, api: "responses" },
128
+ { id: "openai/gpt-5.6-luna", label: "GPT-5.6 Luna (OpenAI, Responses)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true, api: "responses" },
94
129
  { id: "openai/gpt-5.4", label: "GPT-5.4 (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
95
130
  { id: "openai/gpt-5.4-mini", label: "GPT-5.4 mini (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
96
131
  { id: "openai/o4-mini", label: "o4-mini (OpenAI, reasoning)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
@@ -116,15 +151,13 @@ export const MODELS: ModelEntry[] = [
116
151
  // incremental or cumulative chunks). Text-only (multimodal vision deferred).
117
152
  { id: "google/gemini-3.1-pro", label: "Gemini 3.1 Pro (Google)", group: "Chat \u00b7 Google", type: "chat", capabilities: [], provider: "google", streaming: true },
118
153
  { id: "google/gemini-3.5-flash", label: "Gemini 3.5 Flash (Google)", group: "Chat \u00b7 Google", type: "chat", capabilities: [], provider: "google", streaming: true },
154
+ // v0.170.0: newer Flash tier; same Generate Content / google dispatcher path.
155
+ { id: "google/gemini-3.6-flash", label: "Gemini 3.6 Flash (Google)", group: "Chat \u00b7 Google", type: "chat", capabilities: [], provider: "google", streaming: true },
119
156
  // @cf/google/gemma-3-12b-it removed v0.165.0: marked Deprecated on the
120
157
  // Workers AI model list; gemma-4-26b-a4b-it (above) is the current Gemma.
121
158
  { id: "@cf/ibm-granite/granite-4.0-h-micro", label: "Granite 4.0 Micro (IBM)", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
122
159
  // @hf/nousresearch/hermes-2-pro-mistral-7b removed v0.165.0: marked
123
160
  // Deprecated (and Beta) on the Workers AI model list.
124
- // LLaVA 1.5: image-to-text, single-shot. Surfaced as a vision chat model so
125
- // the attach UI works, but runChat routes it to the { image, prompt } wire
126
- // format. No streaming (omitted): it returns one { description } per call.
127
- { id: "@cf/llava-hf/llava-1.5-7b-hf", label: "LLaVA 1.5 7B (image Q&A, single-shot)", group: "Chat \u00b7 Other", type: "chat", capabilities: ["vision"] },
128
161
  { id: "@cf/meta/llama-3.2-1b-instruct", label: "Llama 3.2 1B (tiny, cheap)", group: "Chat \u00b7 Meta", type: "chat", capabilities: [], streaming: true },
129
162
 
130
163
  // ---- Image generation ----
@@ -134,20 +167,31 @@ export const MODELS: ModelEntry[] = [
134
167
  // v0.165.0 catalog refresh (#81): newer Google image models, same URL-returning
135
168
  // proxied path as nano-banana-pro.
136
169
  { id: "google/nano-banana-2", label: "Nano Banana 2 (Google)", group: "Image Gen", type: "image", capabilities: [], provider: "google" },
170
+ // v0.172.0: fast/cheap Nano Banana sibling; same google proxied image path.
171
+ { id: "google/nano-banana-2-lite", label: "Nano Banana 2 Lite (Google)", group: "Image Gen", type: "image", capabilities: [], provider: "google" },
137
172
  { id: "google/imagen-4", label: "Imagen 4 (Google)", group: "Image Gen", type: "image", capabilities: [], provider: "google" },
138
- // gpt-image-1.5 (v0.22.0). Opaque only: the CF proxy schema is
139
- // { prompt, images, quality, size, style } and 7003-rejects
140
- // background/output_format, so transparency is impossible through it.
141
- // v0.166.0 retired the OPENAI_API_KEY BYOK transparent-PNG path (prism#93),
142
- // so this rides the Unified Billing proxy like the other proxied image models.
173
+ // gpt-image-1.5 (v0.22.0). Opaque on CF proxy by default ({ prompt, quality,
174
+ // size }; proxy 7003-rejects background/output_format). Optional OPENAI_API_KEY
175
+ // BYOK (restored v0.174.0 after prism#93 / v0.166.0) for transparent PNG.
143
176
  { id: "openai/gpt-image-1.5", label: "GPT Image 1.5 (OpenAI)", group: "Image Gen", type: "image", capabilities: [], provider: "openai" },
144
- // gpt-image-2 (v0.165.0): same opaque proxy dispatch as 1.5.
177
+ // gpt-image-2 (v0.165.0): same opaque-proxy / optional transparent BYOK split.
145
178
  { id: "openai/gpt-image-2", label: "GPT Image 2 (OpenAI)", group: "Image Gen", type: "image", capabilities: [], provider: "openai" },
146
- // recraftv4 is opaque and art-directed (the CF proxy exposes no alpha flag,
147
- // only an opaque background_color). Strong text rendering and style controls;
148
- // returns webp. Added for logos/icons-on-bg/styled scenes, NOT transparency.
179
+ // recraftv4 is opaque and art-directed. Strong text rendering; returns webp.
180
+ // buildProxiedImageParams sends bare { prompt } (v0.174.1+); V4/V4.1 reject
181
+ // legacy style enums and V4.1 Pro rejects 1024x1024.
149
182
  { id: "recraft/recraftv4", label: "Recraft V4 (art-directed, opaque)", group: "Image Gen", type: "image", capabilities: [], provider: "recraft" },
183
+ // v0.172.0: standard-res V4.1 (pro is 2048px+); same recraft dispatcher.
184
+ { id: "recraft/recraftv4-1", label: "Recraft V4.1 (art-directed, opaque)", group: "Image Gen", type: "image", capabilities: [], provider: "recraft" },
150
185
  { id: "recraft/recraftv4-1-pro", label: "Recraft V4.1 Pro (art-directed, opaque)", group: "Image Gen", type: "image", capabilities: [], provider: "recraft" },
186
+ // v0.171.0: xAI / ByteDance image via buildProxiedImageParams +
187
+ // extractProxiedImageAsset. Seedream: result.images[]; Grok Imagine:
188
+ // b64_json (ZDR) or URL, normalized by extractProxiedImageAsset.
189
+ { id: "xai/grok-imagine-image", label: "Grok Imagine Image (xAI)", group: "Image Gen", type: "image", capabilities: [], provider: "xai" },
190
+ // v0.172.0: higher-fidelity Grok Imagine sibling; same xai image path.
191
+ { id: "xai/grok-imagine-image-quality", label: "Grok Imagine Image Quality (xAI)", group: "Image Gen", type: "image", capabilities: [], provider: "xai" },
192
+ { id: "bytedance/seedream-5-pro", label: "Seedream 5 Pro (ByteDance)", group: "Image Gen", type: "image", capabilities: [], provider: "bytedance" },
193
+ // v0.172.0: lighter/faster Seedream; same bytedance image path (images[]).
194
+ { id: "bytedance/seedream-5-lite", label: "Seedream 5 Lite (ByteDance)", group: "Image Gen", type: "image", capabilities: [], provider: "bytedance" },
151
195
  { id: "@cf/black-forest-labs/flux-2-klein-9b", label: "FLUX 2 Klein 9B (frontier)", group: "Image Gen", type: "image", capabilities: [] },
152
196
  { id: "@cf/black-forest-labs/flux-2-klein-4b", label: "FLUX 2 Klein 4B (faster)", group: "Image Gen", type: "image", capabilities: [] },
153
197
  { id: "@cf/black-forest-labs/flux-2-dev", label: "FLUX 2 Dev (multi-reference)", group: "Image Gen", type: "image", capabilities: [] },
@@ -184,10 +228,12 @@ export const MODELS: ModelEntry[] = [
184
228
  // billing. Includes xAI Grok Imagine Video (v0.164.0: moved off BYOK).
185
229
  { id: "google/veo-3.1", label: "Veo 3.1 (Google)", group: "Video Gen", type: "video", capabilities: [], provider: "google" },
186
230
  { id: "google/veo-3.1-fast", label: "Veo 3.1 Fast (Google)", group: "Video Gen", type: "video", capabilities: [], provider: "google" },
187
- { id: "google/veo-3", label: "Veo 3 (Google)", group: "Video Gen", type: "video", capabilities: [], provider: "google" },
188
- { id: "google/veo-3-fast", label: "Veo 3 Fast (Google)", group: "Video Gen", type: "video", capabilities: [], provider: "google" },
231
+ // google/veo-3 and google/veo-3-fast: CF returns 7010 deprecated
232
+ // ("use google/veo-3.1-fast instead"); removed from catalog 2026-08-04.
189
233
  { id: "bytedance/seedance-2.0", label: "Seedance 2.0 (ByteDance)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "bytedance" },
190
234
  { id: "bytedance/seedance-2.0-fast", label: "Seedance 2.0 Fast (ByteDance)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "bytedance" },
235
+ // v0.170.0: compact/cost-efficient Seedance sibling; same t2v/i2v param shape.
236
+ { id: "bytedance/seedance-2.0-mini", label: "Seedance 2.0 Mini (ByteDance)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "bytedance" },
191
237
  { id: "minimax/hailuo-2.3", label: "Hailuo 2.3 (MiniMax)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "minimax" },
192
238
  { id: "minimax/hailuo-2.3-fast", label: "Hailuo 2.3 Fast (MiniMax)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "minimax" },
193
239
  { id: "xai/grok-imagine-video", label: "Grok Imagine Video (xAI)", group: "Video Gen", type: "video", capabilities: [], provider: "xai" },
@@ -109,20 +109,70 @@ export function detectProviderFailure(result: unknown): string | null {
109
109
  ? r.error
110
110
  : `provider returned state "${r.state}"`;
111
111
  }
112
+ // OpenAI Responses API: status is "completed" | "failed" | "incomplete" | ...
113
+ // (not the video/image `state` field). Treat failed/incomplete as errors so
114
+ // we do not persist an empty success row.
115
+ if (typeof r.status === "string" && r.status !== "completed" && r.object === "response") {
116
+ const err = r.error as { message?: string } | string | null | undefined;
117
+ const msg = typeof err === "string" ? err
118
+ : err && typeof err === "object" && typeof err.message === "string" ? err.message
119
+ : null;
120
+ return msg && msg.trim()
121
+ ? msg
122
+ : `provider returned status "${r.status}"`;
123
+ }
112
124
  return null;
113
125
  }
114
126
 
115
- // Pull the generated-image URL out of a proxied image-gen response. Proxied
116
- // image models (the Google nano-banana family, added v0.21.2) return a URL,
117
- // not base64, wrapped in the same { state, result } envelope as video/music:
118
- // { state: "Completed", result: { image: "<url>" } }
119
- // The bare { image: "<url>" } form (the documented Output schema, without the
120
- // binding wrapper) is accepted too. Returns the URL string or null.
121
- export function extractProxiedImageUrl(result: unknown): string | null {
127
+ // Pull the first image string out of a proxied image-gen response.
128
+ // Envelope shapes (env.AI.run / Unified Billing):
129
+ // { state: "Completed", result: { image: "<url|b64|data-uri>" } } // google/openai/xai
130
+ // { state: "Completed", result: { images: ["...", ...] } } // Seedream
131
+ // Bare { image } / { images } forms are accepted too. Multi-image: first wins.
132
+ function firstImageString(result: unknown): string | null {
122
133
  if (!result || typeof result !== "object") return null;
123
- const r = result as { result?: { image?: unknown }; image?: unknown };
134
+ const r = result as {
135
+ result?: { image?: unknown; images?: unknown };
136
+ image?: unknown;
137
+ images?: unknown;
138
+ };
124
139
  const wrapped = r.result?.image;
125
140
  if (typeof wrapped === "string" && wrapped.length > 0) return wrapped;
141
+ const wrappedArr = r.result?.images;
142
+ if (Array.isArray(wrappedArr) && typeof wrappedArr[0] === "string" && wrappedArr[0].length > 0) {
143
+ return wrappedArr[0];
144
+ }
126
145
  if (typeof r.image === "string" && r.image.length > 0) return r.image;
146
+ if (Array.isArray(r.images) && typeof r.images[0] === "string" && r.images[0].length > 0) {
147
+ return r.images[0];
148
+ }
149
+ return null;
150
+ }
151
+
152
+ // URL-only helper (kept for call sites / tests that only want a fetchable URL).
153
+ export function extractProxiedImageUrl(result: unknown): string | null {
154
+ const s = firstImageString(result);
155
+ if (!s) return null;
156
+ if (/^https?:\/\//i.test(s) || s.startsWith("data:")) return s;
127
157
  return null;
128
158
  }
159
+
160
+ // v0.174.0: Unified Billing Grok Imagine returns base64 (response_format
161
+ // b64_json) rather than a URL. Normalize either form so runImage can store
162
+ // bytes without a fetch when the payload is already inline.
163
+ export type ProxiedImageAsset =
164
+ | { kind: "url"; url: string }
165
+ | { kind: "b64"; base64: string; mime: string };
166
+
167
+ export function extractProxiedImageAsset(result: unknown): ProxiedImageAsset | null {
168
+ const s = firstImageString(result);
169
+ if (!s) return null;
170
+ if (/^https?:\/\//i.test(s)) return { kind: "url", url: s };
171
+ if (s.startsWith("data:")) {
172
+ const m = s.match(/^data:([^;]+);base64,(.+)$/);
173
+ if (!m) return null;
174
+ return { kind: "b64", mime: m[1], base64: m[2] };
175
+ }
176
+ // Raw base64 (Grok Imagine b64_json default).
177
+ return { kind: "b64", mime: "image/png", base64: s };
178
+ }
@@ -1,25 +1,27 @@
1
- // OpenAI SSE interpreter (v0.21.0).
1
+ // OpenAI SSE interpreter (v0.21.0; Responses API stream events v0.173.0).
2
2
  //
3
- // OpenAI chat models are proxied through Cloudflare Unified Billing via
4
- // env.AI.run("openai/<model>", { messages, stream: true }). Empirically the
5
- // binding can hand back one of two known frame shapes for a streamed proxied
6
- // model, and which one is not contractually documented:
3
+ // OpenAI models are proxied through Cloudflare Unified Billing via
4
+ // env.AI.run("openai/<model>", ...). Empirically the binding can hand back
5
+ // several known frame shapes; which one is not contractually documented:
7
6
  //
8
- // 1. OpenAI-native delta (same wire format as xAI):
7
+ // 1. Chat Completions native delta:
9
8
  // { "choices": [{ "delta": { "content": "..." } }], "usage"?: {...} }
10
9
  // 2. CF-normalized flat (same shape Workers AI hosted models emit):
11
10
  // { "response": "...", "usage"?: {...} }
11
+ // 3. Responses API typed events (v0.173.0):
12
+ // { "type": "response.output_text.delta", "delta": "..." }
13
+ // { "type": "response.completed", "response": { "usage": {...} } }
12
14
  //
13
15
  // Rather than guess which one the proxy uses (and ship a parser that silently
14
- // yields empty output if the guess is wrong), this interpreter handles BOTH.
15
- // The two shapes don't collide: an OpenAI-native frame has no `response` key,
16
- // a flat frame has no `choices`, so checking each independently is safe. If a
17
- // future third shape appears, add a branch here with a fixture test.
16
+ // yields empty output if the guess is wrong), this interpreter handles all of
17
+ // them. The shapes don't collide on the fields we read. If a future fourth
18
+ // shape appears, add a branch here with a fixture test.
18
19
  //
19
20
  // `data: [DONE]` is dropped by the SSE framer before frames reach here. Empty
20
21
  // content/response strings (normal on the trailing usage frame) are dropped.
21
- // Usage naming is accepted in both OpenAI (prompt_tokens/completion_tokens)
22
- // and Anthropic-derived (input_tokens/output_tokens) forms for safety.
22
+ // Usage naming is accepted in both Chat Completions
23
+ // (prompt_tokens/completion_tokens) and Responses
24
+ // (input_tokens/output_tokens) forms.
23
25
 
24
26
  import type { ProviderStreamEvent } from "./types";
25
27
 
@@ -27,6 +29,8 @@ export function interpretOpenAISSEFrame(data: unknown): ProviderStreamEvent[] {
27
29
  const events: ProviderStreamEvent[] = [];
28
30
  if (!data || typeof data !== "object") return events;
29
31
  const d = data as {
32
+ type?: string;
33
+ delta?: unknown;
30
34
  choices?: Array<{ delta?: { content?: string } }>;
31
35
  response?: unknown;
32
36
  usage?: {
@@ -37,13 +41,38 @@ export function interpretOpenAISSEFrame(data: unknown): ProviderStreamEvent[] {
37
41
  };
38
42
  };
39
43
 
40
- // Shape 1: OpenAI-native delta.
44
+ // Shape 3: Responses API typed events.
45
+ if (d.type === "response.output_text.delta") {
46
+ if (typeof d.delta === "string" && d.delta.length > 0) {
47
+ events.push({ type: "text", text: d.delta });
48
+ }
49
+ } else if (d.type === "response.completed") {
50
+ const resp = d.response as {
51
+ usage?: {
52
+ prompt_tokens?: number;
53
+ completion_tokens?: number;
54
+ input_tokens?: number;
55
+ output_tokens?: number;
56
+ };
57
+ } | undefined;
58
+ const u = resp?.usage;
59
+ if (u) {
60
+ events.push({
61
+ type: "usage",
62
+ in_: u.prompt_tokens ?? u.input_tokens ?? null,
63
+ out_: u.completion_tokens ?? u.output_tokens ?? null,
64
+ });
65
+ }
66
+ }
67
+
68
+ // Shape 1: Chat Completions native delta.
41
69
  const delta = d.choices?.[0]?.delta?.content;
42
70
  if (typeof delta === "string" && delta.length > 0) {
43
71
  events.push({ type: "text", text: delta });
44
72
  }
45
73
 
46
- // Shape 2: CF-normalized flat `response`.
74
+ // Shape 2: CF-normalized flat `response` (string only; object form is
75
+ // Responses completed envelope, handled above).
47
76
  if (typeof d.response === "string" && d.response.length > 0) {
48
77
  events.push({ type: "text", text: d.response });
49
78
  }
@@ -18,6 +18,7 @@
18
18
  // blocks with base64 source.
19
19
 
20
20
  import type { AiContext } from "../ai-binding";
21
+ import { aiRun, aiLogId } from "../ai-binding";
21
22
  import type { ModelEntry } from "../models";
22
23
  import type { ProviderStreamEvent } from "../parsers/types";
23
24
  import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
@@ -126,12 +127,110 @@ async function prepareAnthropicRequest(
126
127
  };
127
128
  }
128
129
 
130
+ // v0.169.0 / v0.170.0: binding-dispatch path for models flagged `binding: true`
131
+ // (claude-fable-5, claude-opus-5). Cloudflare moved new-model onboarding to the
132
+ // Unified Billing catalog surface reached through env.AI.run; the legacy AI
133
+ // Gateway anthropic endpoint (prepareAnthropicRequest above) has a frozen
134
+ // credential-injection allowlist that forwards unknown ids keyless, so the
135
+ // provider 401s. The binding injects Unified Billing credentials and returns
136
+ // the SAME native Anthropic wire shapes the legacy path does (message JSON for
137
+ // non-stream; message_start / content_block_delta / message_delta SSE for
138
+ // stream), so the existing message transform, output-extract, and
139
+ // anthropic-sse interpreter are reused unchanged.
140
+ //
141
+ // The binding body is Anthropic-shaped (system top-level, base64 image blocks),
142
+ // exactly what transformToAnthropic already produces. Unlike the legacy path we
143
+ // pass the FULL prefixed id (e.g. "anthropic/claude-fable-5") to env.AI.run;
144
+ // the catalog id carries the vendor prefix, so no "anthropic/" strip here.
145
+ function buildAnthropicBindingBody(
146
+ systemPrompt: string | undefined,
147
+ messages: Array<unknown>,
148
+ stream: boolean,
149
+ ): Record<string, unknown> {
150
+ const { system, messages: aMessages } = transformToAnthropic(messages, systemPrompt);
151
+ const body: Record<string, unknown> = { max_tokens: 4096, messages: aMessages };
152
+ if (system) body.system = system;
153
+ if (stream) body.stream = true;
154
+ return body;
155
+ }
156
+
157
+ async function callAnthropicBinding(
158
+ ctx: AiContext,
159
+ model: ModelEntry,
160
+ systemPrompt: string | undefined,
161
+ messages: Array<unknown>,
162
+ ): Promise<{ raw: unknown; logId: string | null }> {
163
+ const body = buildAnthropicBindingBody(systemPrompt, messages, false);
164
+ const raw = await aiRun(ctx, model.id, body);
165
+ return { raw, logId: aiLogId(ctx) };
166
+ }
167
+
168
+ async function* callAnthropicStreamBinding(
169
+ ctx: AiContext,
170
+ model: ModelEntry,
171
+ systemPrompt: string | undefined,
172
+ messages: Array<unknown>,
173
+ signal: AbortSignal,
174
+ ): AsyncGenerator<ProviderStreamEvent> {
175
+ const body = buildAnthropicBindingBody(systemPrompt, messages, true);
176
+ const result = await aiRun(ctx, model.id, body);
177
+
178
+ if (!(result instanceof ReadableStream)) {
179
+ throw new Error(`Anthropic binding did not return a stream (got ${typeof result}). Ensure stream:true is honored by this model.`);
180
+ }
181
+
182
+ const reader = result.getReader();
183
+ const decoder = new TextDecoder();
184
+ let buffer = "";
185
+
186
+ // env.AI.run takes no AbortSignal, so bridge it to reader.cancel() the same
187
+ // way callWorkersAIStream does. If already aborted, cancel immediately.
188
+ const onAbort = () => { try { reader.cancel(); } catch { /* fine */ } };
189
+ if (signal.aborted) {
190
+ onAbort();
191
+ } else {
192
+ signal.addEventListener("abort", onAbort, { once: true });
193
+ }
194
+
195
+ try {
196
+ while (true) {
197
+ const { done, value } = await reader.read();
198
+ if (done) break;
199
+
200
+ buffer += decoder.decode(value, { stream: true });
201
+
202
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
203
+ buffer = remainder;
204
+
205
+ for (const payload of payloads) {
206
+ let data: unknown;
207
+ try {
208
+ data = JSON.parse(payload);
209
+ } catch {
210
+ // Anthropic emits thinking + signature deltas by default (fable-5)
211
+ // and some data lines carry trailing whitespace; JSON.parse tolerates
212
+ // trailing whitespace, and a genuinely unparseable frame is skipped.
213
+ continue;
214
+ }
215
+ for (const event of interpretAnthropicSSEFrame(data)) yield event;
216
+ }
217
+ }
218
+ } finally {
219
+ signal.removeEventListener("abort", onAbort);
220
+ try { reader.releaseLock(); } catch { /* fine */ }
221
+ }
222
+ }
223
+
129
224
  export async function callAnthropic(
130
225
  ctx: AiContext,
131
226
  model: ModelEntry,
132
227
  systemPrompt: string | undefined,
133
228
  messages: Array<unknown>,
134
229
  ): Promise<{ raw: unknown; logId: string | null }> {
230
+ // v0.169.0: flagged models dispatch through the env.AI.run binding, not the
231
+ // legacy AI Gateway provider fetch below.
232
+ if (model.binding) return callAnthropicBinding(ctx, model, systemPrompt, messages);
233
+
135
234
  const { url, headers, body } = await prepareAnthropicRequest(
136
235
  ctx, model, systemPrompt, messages, { stream: false },
137
236
  );
@@ -156,6 +255,12 @@ export async function* callAnthropicStream(
156
255
  messages: Array<unknown>,
157
256
  signal: AbortSignal,
158
257
  ): AsyncGenerator<ProviderStreamEvent> {
258
+ // v0.169.0: flagged models stream through the env.AI.run binding.
259
+ if (model.binding) {
260
+ yield* callAnthropicStreamBinding(ctx, model, systemPrompt, messages, signal);
261
+ return;
262
+ }
263
+
159
264
  const { url, headers, body } = await prepareAnthropicRequest(
160
265
  ctx, model, systemPrompt, messages, { stream: true },
161
266
  );
@@ -0,0 +1,66 @@
1
+ // OpenAI direct (BYOK) image generation for transparent PNG.
2
+ //
3
+ // Why this exists separately from the proxied image path: the Cloudflare
4
+ // Unified Billing proxy for openai/gpt-image-* exposes a strict schema
5
+ // { prompt, images, quality, size, style } and 7003-rejects `background` and
6
+ // `output_format`. OpenAI's own /v1/images/generations endpoint DOES accept
7
+ // both, so a direct BYOK call is the only way to get a real alpha channel.
8
+ //
9
+ // Per Conrad (2026-08-04): this is the SOLE deployer-key exception. Every
10
+ // other provider stays on Unified Billing only. Gated on OPENAI_API_KEY:
11
+ // when the secret is unset, runImage falls through to the opaque proxy.
12
+ //
13
+ // GPT image models ALWAYS return base64 (data[0].b64_json); the `url` response
14
+ // format is unsupported for them. `background: "transparent"` with
15
+ // `output_format: "png"` yields an RGBA PNG.
16
+ import { base64ToBytes } from "../utils";
17
+
18
+ export interface GeneratedImage {
19
+ bytes: Uint8Array;
20
+ mime: string;
21
+ }
22
+
23
+ // modelId is the catalog id, e.g. "openai/gpt-image-1.5"; OpenAI wants the bare
24
+ // model string, so we strip the "openai/" routing prefix.
25
+ export async function generateOpenAIImage(
26
+ apiKey: string,
27
+ modelId: string,
28
+ prompt: string,
29
+ ): Promise<GeneratedImage> {
30
+ const model = modelId.replace(/^openai\//, "");
31
+
32
+ const resp = await fetch("https://api.openai.com/v1/images/generations", {
33
+ method: "POST",
34
+ headers: {
35
+ Authorization: `Bearer ${apiKey}`,
36
+ "Content-Type": "application/json",
37
+ },
38
+ body: JSON.stringify({
39
+ model,
40
+ prompt,
41
+ size: "1024x1024",
42
+ quality: "high",
43
+ background: "transparent",
44
+ output_format: "png",
45
+ }),
46
+ });
47
+
48
+ if (!resp.ok) {
49
+ let detail = "";
50
+ try {
51
+ const e = (await resp.json()) as { error?: { message?: string } };
52
+ detail = e?.error?.message ? `: ${e.error.message}` : "";
53
+ } catch {
54
+ /* non-JSON error body; status alone is enough */
55
+ }
56
+ throw new Error(`OpenAI image API ${resp.status}${detail}`);
57
+ }
58
+
59
+ const data = (await resp.json()) as { data?: Array<{ b64_json?: string }> };
60
+ const b64 = data?.data?.[0]?.b64_json;
61
+ if (!b64) {
62
+ throw new Error("OpenAI image API returned no b64_json image data");
63
+ }
64
+
65
+ return { bytes: base64ToBytes(b64), mime: "image/png" };
66
+ }