@skyphusion/create-prism 0.1.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 (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,135 @@
1
+ // Param construction for the long-run video/music workflow (v0.21.5).
2
+ //
3
+ // Extracted as a pure function so the per-model param shapes are unit-testable
4
+ // without importing index.ts (cloudflare:workers). The shapes differ enough
5
+ // that getting them wrong means a rejected upstream call:
6
+ // - text-to-video (Veo/Seedance/etc): { prompt, duration:"8s", aspect_ratio,
7
+ // resolution:"720p", generate_audio } -- duration is a STRING here.
8
+ // - image-to-video: each model has its OWN image field + param shape, and
9
+ // additionalProperties is false on these CF schemas, so a stray field or
10
+ // the wrong image key is rejected. Selected per modelId (see I2V below).
11
+ // - music (minimax/music-2.6): { prompt, lyrics? }
12
+ //
13
+ // i2v is selected by the presence of imageUrl, not a separate kind, so the
14
+ // workflow keeps a single "video" kind.
15
+
16
+ export type GenKind = "video" | "music";
17
+
18
+ export interface GenParamOpts {
19
+ prompt: string;
20
+ lyrics?: string;
21
+ imageUrl?: string; // present => image-to-video
22
+ modelId?: string; // v0.143.0: selects the per-model i2v param shape
23
+ }
24
+
25
+ // v0.143.0: per-model image-to-video param shapes, verified against the
26
+ // Cloudflare model pages (developers.cloudflare.com/ai/models/<id>) on
27
+ // 2026-06-07. `image` accepts a fetchable URL or a base64 data: URI for all of
28
+ // these; the workflow hands us one or the other. Models whose schema makes
29
+ // `prompt` required get a gentle default motion prompt when the caller passed
30
+ // none. Each shape sends only fields the model's schema declares (so it never
31
+ // trips additionalProperties:false) and includes the documented
32
+ // required-with-default fields (so it never misses a required key).
33
+ //
34
+ // Google Veo is intentionally NOT wired here yet: its `image_input` wants raw
35
+ // base64, not a URL/data-URI, which needs an extra conversion step in the
36
+ // workflow. Tracked as a follow-up.
37
+ const DEFAULT_MOTION_PROMPT = "subtle, natural cinematic motion";
38
+
39
+ function imageToVideoParams(
40
+ modelId: string | undefined,
41
+ imageUrl: string,
42
+ prompt: string,
43
+ ): Record<string, unknown> {
44
+ const motion = prompt && prompt.trim() ? prompt : DEFAULT_MOTION_PROMPT;
45
+
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).
49
+ case "bytedance/seedance-2.0":
50
+ case "bytedance/seedance-2.0-fast":
51
+ return {
52
+ image: imageUrl,
53
+ prompt: motion,
54
+ aspect_ratio: "16:9",
55
+ duration: 5,
56
+ resolution: "720p",
57
+ fps: 24,
58
+ camera_fixed: false,
59
+ watermark: false,
60
+ generate_audio: false,
61
+ };
62
+
63
+ // MiniMax Hailuo 2.3: field `first_frame_image`; resolution 768P/1080P.
64
+ case "minimax/hailuo-2.3":
65
+ case "minimax/hailuo-2.3-fast":
66
+ return {
67
+ first_frame_image: imageUrl,
68
+ prompt: motion,
69
+ duration: 6,
70
+ resolution: "768P",
71
+ fast_pretreatment: false,
72
+ prompt_optimizer: true,
73
+ };
74
+
75
+ // RunwayML Gen-4.5: field `image_input`; integer duration 2-10; `ratio`
76
+ // (not resolution).
77
+ case "runwayml/gen-4.5":
78
+ return {
79
+ image_input: imageUrl,
80
+ prompt: motion,
81
+ duration: 5,
82
+ ratio: "1280:720",
83
+ // v0.145.1: loosen Runway's input moderation to its lowest documented
84
+ // setting. The default flags AI-generated photoreal characters as
85
+ // possible real people / public figures and rejects the keyframe (a
86
+ // false positive on our own synthetic renders). This is the only
87
+ // moderation knob any of the wired i2v models exposes; Seedance / Hailuo
88
+ // / hh1 hard-code it provider-side with no override. Operator-gated
89
+ // platform (single key-holder, monitored logs, enforced acceptable use).
90
+ content_moderation: { public_figure_threshold: "low" },
91
+ };
92
+
93
+ // Alibaba hh1-i2v (the original i2v wiring) and the safe default: field
94
+ // `image`; resolution 720P; integer duration 3-15; prompt optional.
95
+ // v0.165.0: alibaba/hh1.1-i2v and alibaba/wan-2.7-i2v share this schema
96
+ // (verified against the CF model pages), so they ride the same case.
97
+ case "alibaba/hh1-i2v":
98
+ case "alibaba/hh1.1-i2v":
99
+ case "alibaba/wan-2.7-i2v":
100
+ default: {
101
+ const params: Record<string, unknown> = {
102
+ image: imageUrl,
103
+ resolution: "720P",
104
+ duration: 5,
105
+ };
106
+ if (prompt && prompt.trim()) params.prompt = prompt;
107
+ return params;
108
+ }
109
+ }
110
+ }
111
+
112
+ export function buildGenParams(kind: GenKind, opts: GenParamOpts): Record<string, unknown> {
113
+ const { prompt, lyrics, imageUrl, modelId } = opts;
114
+
115
+ if (kind === "video" && imageUrl) {
116
+ // image-to-video (per-model shape)
117
+ return imageToVideoParams(modelId, imageUrl, prompt);
118
+ }
119
+
120
+ if (kind === "video") {
121
+ // text-to-video (existing shape)
122
+ return {
123
+ prompt,
124
+ duration: "8s",
125
+ aspect_ratio: "16:9",
126
+ resolution: "720p",
127
+ generate_audio: true,
128
+ };
129
+ }
130
+
131
+ // music
132
+ const params: Record<string, unknown> = { prompt };
133
+ if (lyrics && lyrics.trim()) params.lyrics = lyrics;
134
+ return params;
135
+ }
@@ -0,0 +1,214 @@
1
+ // Model catalog (v0.18.4).
2
+ //
3
+ // Extracted from src/index.ts for navigability. This file is the single
4
+ // authoritative list of models the worker exposes; adding or removing
5
+ // entries here flows automatically to GET /api/models and the frontend
6
+ // model picker.
7
+ //
8
+ // Each entry's `id` is the routing key. The worker's dispatch logic uses
9
+ // the `provider` field (defaulting to "workers-ai") to pick a code path.
10
+ // The `type` field controls which dispatcher runs (chat / image / tts /
11
+ // video / stt / music). The `capabilities` array is mostly UI-driven (vision
12
+ // toggles the attach affordance for vision-capable chat models). The
13
+ // `streaming` flag opts chat models in to POST /api/chat/stream.
14
+ //
15
+ // Catalog conventions for adding a new model:
16
+ // - Use the upstream's canonical ID for the prefix
17
+ // (anthropic/, xai/, openai/, google/, @cf/<vendor>/, etc.)
18
+ // - Keep labels clean: do NOT put billing markers like "BYOK" or "needs CF
19
+ // credits" in the label (they were removed in v0.111.0)
20
+ // - Set streaming: true if the model can stream and your provider's
21
+ // stream parser handles it (Anthropic, xAI, OpenAI, Google, Workers AI
22
+ // are all covered)
23
+
24
+ // "voice" = conversational/streaming STT (a live WebSocket session, not a
25
+ // one-shot request like "stt"); handled out of /api/chat via /api/stt/stream.
26
+ export type ModelType = "chat" | "image" | "tts" | "video" | "stt" | "music" | "voice";
27
+ export type Provider =
28
+ | "workers-ai"
29
+ | "anthropic"
30
+ | "xai"
31
+ | "google"
32
+ | "openai"
33
+ | "bytedance"
34
+ | "minimax"
35
+ | "runwayml"
36
+ | "alibaba"
37
+ | "pixverse"
38
+ | "vidu"
39
+ | "recraft";
40
+
41
+ export interface ModelEntry {
42
+ id: string;
43
+ label: string;
44
+ group: string;
45
+ type: ModelType;
46
+ // "vision" = accepts image input in chat; "image-input" = image-to-video
47
+ // source image required (e.g. alibaba/hh1-i2v, v0.21.5).
48
+ capabilities: Array<"vision" | "image-input">;
49
+ provider?: Provider; // defaults to "workers-ai" when omitted
50
+ // v0.13.0: when true, the model can be invoked via POST /api/chat/stream
51
+ // (server-sent events). Covers Anthropic, Workers AI, xAI, OpenAI, and
52
+ // Google. Chat models only - irrelevant for image/tts/video/stt/music types.
53
+ streaming?: boolean;
54
+ }
55
+
56
+ export const MODELS: ModelEntry[] = [
57
+ // ---- Chat (text generation) ----
58
+ // Anthropic (Unified Billing via cf-aig-authorization, routed through AI Gateway)
59
+ // v0.13.0: streaming: true makes these eligible for POST /api/chat/stream.
60
+ // 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
62
+ { id: "anthropic/claude-sonnet-5", label: "Claude Sonnet 5 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
63
+ { 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
+ { 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
+ { id: "anthropic/claude-opus-4-6", label: "Claude Opus 4.6 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
66
+ { id: "anthropic/claude-sonnet-4-6", label: "Claude Sonnet 4.6 (Anthropic)", group: "Chat \u00b7 Anthropic", type: "chat", capabilities: ["vision"], provider: "anthropic", streaming: true },
67
+ { 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
+
69
+ // 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
71
+ { id: "xai/grok-4.3", label: "Grok 4.3 (xAI)", group: "Chat \u00b7 xAI", type: "chat", capabilities: ["vision"], provider: "xai", streaming: true },
72
+ { 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
+ { 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
75
+
76
+ // Frontier
77
+ { id: "@cf/moonshotai/kimi-k2.6", label: "Kimi K2.6 (1T)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: ["vision"], streaming: true },
78
+ { 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
+ { id: "@cf/openai/gpt-oss-120b", label: "GPT-OSS 120B (reasoning)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: [], streaming: true },
80
+ { id: "@cf/meta/llama-4-scout-17b-16e-instruct", label: "Llama 4 Scout (MoE, vision)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: ["vision"], streaming: true },
81
+ { id: "@cf/google/gemma-4-26b-a4b-it", label: "Gemma 4 26B (vision)", group: "Chat \u00b7 Frontier", type: "chat", capabilities: ["vision"], streaming: true },
82
+ // OpenAI open weights
83
+ { id: "@cf/openai/gpt-oss-20b", label: "GPT-OSS 20B", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], streaming: true },
84
+ // OpenAI proxied via AI Gateway unified billing (v0.21.0; streaming added
85
+ // v0.21.1). Routed through env.AI.run("openai/<model>", { messages }) on the
86
+ // generic chat path; extractOutput handles both the chat-completions
87
+ // ({choices}) and Responses API ({output[].content[]}) shapes. streaming: true
88
+ // uses callOpenAIStream + interpretOpenAISSEFrame (which tolerates both the
89
+ // OpenAI-native delta and CF-normalized flat frame shapes); confirmed live
90
+ // against gpt-5.5 in v0.21.1, including token-usage on the final frame.
91
+ // capabilities is empty: multimodal-in through the proxied binding is
92
+ // unverified, so the attach affordance stays off.
93
+ { id: "openai/gpt-5.5", label: "GPT-5.5 (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
94
+ { id: "openai/gpt-5.4", label: "GPT-5.4 (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
95
+ { id: "openai/gpt-5.4-mini", label: "GPT-5.4 mini (OpenAI)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
96
+ { id: "openai/o4-mini", label: "o4-mini (OpenAI, reasoning)", group: "Chat \u00b7 OpenAI", type: "chat", capabilities: [], provider: "openai", streaming: true },
97
+ // Meta
98
+ { id: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", label: "Llama 3.3 70B (fp8)", group: "Chat \u00b7 Meta", type: "chat", capabilities: [], streaming: true },
99
+ { id: "@cf/meta/llama-3.2-11b-vision-instruct", label: "Llama 3.2 11B (vision)", group: "Chat \u00b7 Meta", type: "chat", capabilities: ["vision"], streaming: true },
100
+ { id: "@cf/meta/llama-3.2-3b-instruct", label: "Llama 3.2 3B", group: "Chat \u00b7 Meta", type: "chat", capabilities: [], streaming: true },
101
+ // Qwen
102
+ { id: "@cf/qwen/qwen3-30b-a3b-fp8", label: "Qwen3 30B MoE", group: "Chat \u00b7 Qwen", type: "chat", capabilities: [], streaming: true },
103
+ { id: "@cf/qwen/qwq-32b", label: "QwQ 32B (reasoning)", group: "Chat \u00b7 Qwen", type: "chat", capabilities: [], streaming: true },
104
+ { id: "@cf/qwen/qwen2.5-coder-32b-instruct", label: "Qwen2.5 Coder 32B", group: "Chat \u00b7 Qwen", type: "chat", capabilities: [], streaming: true },
105
+ // Other
106
+ { id: "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b", label: "DeepSeek R1 32B", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
107
+ { id: "@cf/mistralai/mistral-small-3.1-24b-instruct", label: "Mistral Small 3.1 (vision)", group: "Chat \u00b7 Other", type: "chat", capabilities: ["vision"], streaming: true },
108
+ { id: "@cf/zai-org/glm-4.7-flash", label: "GLM-4.7 Flash (Z.AI, 100+ lang)", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
109
+ { id: "@cf/zai-org/glm-5.2", label: "GLM-5.2 (Z.AI, agentic coding)", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
110
+ { id: "@cf/nvidia/nemotron-3-120b-a12b", label: "Nemotron 3 120B (NVIDIA, agentic)", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
111
+ { id: "@cf/aisingapore/gemma-sea-lion-v4-27b-it", label: "SEA-LION v4 27B (SE Asian langs)", group: "Chat \u00b7 Other", type: "chat", capabilities: [], streaming: true },
112
+ // Gemini proxied via Unified Billing (v0.21.3; streaming v0.21.4). NOT
113
+ // OpenAI-shaped: native contents/candidates format, transformed by
114
+ // src/providers/google.ts. Streaming via callGeminiStream +
115
+ // interpretGeminiSSEFrame, with a dual-mode delta reconciler (handles
116
+ // incremental or cumulative chunks). Text-only (multimodal vision deferred).
117
+ { id: "google/gemini-3.1-pro", label: "Gemini 3.1 Pro (Google)", group: "Chat \u00b7 Google", type: "chat", capabilities: [], provider: "google", streaming: true },
118
+ { id: "google/gemini-3.5-flash", label: "Gemini 3.5 Flash (Google)", group: "Chat \u00b7 Google", type: "chat", capabilities: [], provider: "google", streaming: true },
119
+ // @cf/google/gemma-3-12b-it removed v0.165.0: marked Deprecated on the
120
+ // Workers AI model list; gemma-4-26b-a4b-it (above) is the current Gemma.
121
+ { 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
+ // @hf/nousresearch/hermes-2-pro-mistral-7b removed v0.165.0: marked
123
+ // 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
+ { 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
+
130
+ // ---- Image generation ----
131
+ // Google proxied (Unified Billing): URL-returning, different schema from the
132
+ // @cf models; handled by the provider:"google" branch in runImage (v0.21.2).
133
+ { id: "google/nano-banana-pro", label: "Nano Banana Pro (Google)", group: "Image Gen", type: "image", capabilities: [], provider: "google" },
134
+ // v0.165.0 catalog refresh (#81): newer Google image models, same URL-returning
135
+ // proxied path as nano-banana-pro.
136
+ { id: "google/nano-banana-2", label: "Nano Banana 2 (Google)", group: "Image Gen", type: "image", capabilities: [], provider: "google" },
137
+ { 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.
143
+ { 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.
145
+ { 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.
149
+ { id: "recraft/recraftv4", label: "Recraft V4 (art-directed, opaque)", group: "Image Gen", type: "image", capabilities: [], provider: "recraft" },
150
+ { id: "recraft/recraftv4-1-pro", label: "Recraft V4.1 Pro (art-directed, opaque)", group: "Image Gen", type: "image", capabilities: [], provider: "recraft" },
151
+ { id: "@cf/black-forest-labs/flux-2-klein-9b", label: "FLUX 2 Klein 9B (frontier)", group: "Image Gen", type: "image", capabilities: [] },
152
+ { id: "@cf/black-forest-labs/flux-2-klein-4b", label: "FLUX 2 Klein 4B (faster)", group: "Image Gen", type: "image", capabilities: [] },
153
+ { id: "@cf/black-forest-labs/flux-2-dev", label: "FLUX 2 Dev (multi-reference)", group: "Image Gen", type: "image", capabilities: [] },
154
+ { id: "@cf/black-forest-labs/flux-1-schnell", label: "FLUX-1 schnell (fast)", group: "Image Gen", type: "image", capabilities: [] },
155
+ { id: "@cf/leonardo/lucid-origin", label: "Lucid Origin (Leonardo)", group: "Image Gen", type: "image", capabilities: [] },
156
+ { id: "@cf/leonardo/phoenix-1.0", label: "Phoenix 1.0 (Leonardo)", group: "Image Gen", type: "image", capabilities: [] },
157
+ { id: "@cf/lykon/dreamshaper-8-lcm", label: "Dreamshaper 8 LCM (fast SD)", group: "Image Gen", type: "image", capabilities: [] },
158
+ { id: "@cf/stabilityai/stable-diffusion-xl-base-1.0", label: "Stable Diffusion XL (SDXL)", group: "Image Gen", type: "image", capabilities: [] },
159
+
160
+ // ---- Text-to-speech ----
161
+ { id: "@cf/deepgram/aura-2-en", label: "Aura-2 English (Deepgram)", group: "TTS", type: "tts", capabilities: [] },
162
+ { id: "@cf/deepgram/aura-2-es", label: "Aura-2 Spanish (Deepgram)", group: "TTS", type: "tts", capabilities: [] },
163
+ { id: "@cf/myshell-ai/melotts", label: "MeloTTS (multilingual)", group: "TTS", type: "tts", capabilities: [] },
164
+
165
+ // ---- Speech-to-text ----
166
+ // Attach an audio file, pick a model, get the transcript. Audio file is
167
+ // required; everything else (prompt, system prompt) is ignored. Whisper and
168
+ // Deepgram have different input/output contracts; runStt adapts per model.
169
+ { id: "@cf/openai/whisper-large-v3-turbo", label: "Whisper Large v3 Turbo (best)", group: "Speech-to-text", type: "stt", capabilities: [] },
170
+ { id: "@cf/openai/whisper", label: "Whisper (general purpose)", group: "Speech-to-text", type: "stt", capabilities: [] },
171
+ { id: "@cf/openai/whisper-tiny-en", label: "Whisper Tiny EN (fast, beta)", group: "Speech-to-text", type: "stt", capabilities: [] },
172
+ { id: "@cf/deepgram/nova-3", label: "Deepgram Nova-3 (accurate)", group: "Speech-to-text", type: "stt", capabilities: [] },
173
+ // @cf/deepgram/flux is websocket-only (error 8006 over the request/response
174
+ // binding), so it is NOT a one-shot "stt" model. It is a live "voice" session:
175
+ // selecting it opens the mic streamer (/api/stt/stream), not the /api/chat
176
+ // composer. type "voice" is special-cased on both the routing and UI sides.
177
+ { id: "@cf/deepgram/flux", label: "Deepgram Flux (live mic)", group: "Speech-to-text", type: "voice", capabilities: [], provider: "workers-ai" },
178
+
179
+ // ---- Music generation (Unified Billing only) ----
180
+ { id: "minimax/music-2.6", label: "MiniMax Music 2.6", group: "Music Gen", type: "music", capabilities: [], provider: "minimax" },
181
+
182
+ // ---- Video generation (Cloudflare Unified Billing via env.AI.run) ----
183
+ // All routed through env.AI.run("provider/model", ...) - CF handles auth and
184
+ // billing. Includes xAI Grok Imagine Video (v0.164.0: moved off BYOK).
185
+ { id: "google/veo-3.1", label: "Veo 3.1 (Google)", group: "Video Gen", type: "video", capabilities: [], provider: "google" },
186
+ { 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" },
189
+ { id: "bytedance/seedance-2.0", label: "Seedance 2.0 (ByteDance)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "bytedance" },
190
+ { id: "bytedance/seedance-2.0-fast", label: "Seedance 2.0 Fast (ByteDance)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "bytedance" },
191
+ { id: "minimax/hailuo-2.3", label: "Hailuo 2.3 (MiniMax)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "minimax" },
192
+ { id: "minimax/hailuo-2.3-fast", label: "Hailuo 2.3 Fast (MiniMax)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "minimax" },
193
+ { id: "xai/grok-imagine-video", label: "Grok Imagine Video (xAI)", group: "Video Gen", type: "video", capabilities: [], provider: "xai" },
194
+ // v0.165.0: CF gateway id keeps the -preview suffix (xAI's own docs list it
195
+ // as grok-imagine-video-1.5); we route via the gateway, so use CF's id.
196
+ { id: "xai/grok-imagine-video-1.5-preview", label: "Grok Imagine Video 1.5 (xAI, preview)", group: "Video Gen", type: "video", capabilities: [], provider: "xai" },
197
+ { id: "runwayml/gen-4.5", label: "Gen-4.5 (RunwayML)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "runwayml" },
198
+ { id: "alibaba/hh1-t2v", label: "HappyHorse 1.0 T2V (Alibaba)", group: "Video Gen", type: "video", capabilities: [], provider: "alibaba" },
199
+ // Image-to-video (v0.21.5): requires a source image. Flagged "image-input";
200
+ // runVideo requires body.image_url, and buildGenParams sends the i2v shape.
201
+ { id: "alibaba/hh1-i2v", label: "HappyHorse 1.0 I2V (Alibaba, image-to-video)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "alibaba" },
202
+ // v0.165.0 catalog refresh (#81): HappyHorse 1.1 siblings + Wan 2.7 i2v. The
203
+ // i2v pair uses the same { image, resolution, duration } schema as hh1-i2v
204
+ // (verified against the CF model pages), so buildGenParams' alibaba/default
205
+ // shape covers them. hh1.1-r2v (reference-to-video) is deferred: it needs
206
+ // reference-input plumbing the worker does not have.
207
+ { id: "alibaba/hh1.1-t2v", label: "HappyHorse 1.1 T2V (Alibaba)", group: "Video Gen", type: "video", capabilities: [], provider: "alibaba" },
208
+ { id: "alibaba/hh1.1-i2v", label: "HappyHorse 1.1 I2V (Alibaba, image-to-video)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "alibaba" },
209
+ { id: "alibaba/wan-2.7-i2v", label: "Wan 2.7 I2V (Alibaba, image-to-video)", group: "Video Gen", type: "video", capabilities: ["image-input"], provider: "alibaba" },
210
+ { id: "pixverse/v6", label: "PixVerse v6", group: "Video Gen", type: "video", capabilities: [], provider: "pixverse" },
211
+ { id: "pixverse/v5.6", label: "PixVerse v5.6", group: "Video Gen", type: "video", capabilities: [], provider: "pixverse" },
212
+ { id: "vidu/q3-pro", label: "Vidu Q3 Pro", group: "Video Gen", type: "video", capabilities: [], provider: "vidu" },
213
+ { id: "vidu/q3-turbo", label: "Vidu Q3 Turbo", group: "Video Gen", type: "video", capabilities: [], provider: "vidu" },
214
+ ];
@@ -0,0 +1,128 @@
1
+ // Text-model output + usage extraction (v0.21.0).
2
+ //
3
+ // Extracted from src/index.ts so these pure functions are unit-testable
4
+ // without importing index.ts (which pulls in `cloudflare:workers` and so
5
+ // can't be loaded under the plain-Node vitest pool). Mirrors the same
6
+ // extraction discipline used for parsers, chunking, discord, and ai-binding.
7
+ //
8
+ // Both functions normalize the many response shapes that reach the
9
+ // non-streaming chat path. The shapes come from: Workers AI hosted models
10
+ // (env.AI.run), Anthropic Messages API, Gemini, and OpenAI-style responses
11
+ // (both chat-completions and the Responses API) returned by unified-billing
12
+ // proxied models routed through env.AI.run. New shapes should be added here
13
+ // with a unit test in tests/output-extract.test.ts rather than inlined at a
14
+ // call site.
15
+
16
+ export function extractOutput(result: unknown): string {
17
+ if (typeof result === "string") return result;
18
+ const r = result as Record<string, unknown>;
19
+
20
+ if (typeof r?.response === "string") return r.response;
21
+ if (typeof r?.result === "string") return r.result;
22
+
23
+ // OpenAI chat-completions shape (also what AI Gateway returns for most
24
+ // proxied OpenAI/OpenAI-compatible chat models): { choices: [{ message }] }
25
+ const choices = r?.choices as Array<{ message?: { content?: string } }> | undefined;
26
+ if (Array.isArray(choices) && typeof choices[0]?.message?.content === "string") {
27
+ return choices[0].message.content;
28
+ }
29
+
30
+ // Anthropic Messages API: top-level content array
31
+ const content = r?.content as Array<{ type?: string; text?: string }> | undefined;
32
+ if (Array.isArray(content)) {
33
+ const text = content.filter((b) => b.type === "text").map((b) => b.text ?? "").join("");
34
+ if (text) return text;
35
+ }
36
+
37
+ // OpenAI Responses API shape (used by gpt-5.x-pro and similar): a top-level
38
+ // `output` array of items, each with a `content` array of typed blocks.
39
+ // Output text lives in blocks of type "output_text" (or plain "text").
40
+ const out = r?.output as Array<unknown> | undefined;
41
+ if (Array.isArray(out)) {
42
+ const text = out
43
+ .flatMap((block) => {
44
+ const b = block as { content?: Array<{ type?: string; text?: string }> };
45
+ return (b?.content ?? [])
46
+ .filter((c) => c?.type === "output_text" || c?.type === "text")
47
+ .map((c) => c.text ?? "");
48
+ })
49
+ .join("");
50
+ if (text) return text;
51
+ }
52
+
53
+ // Gemini-native (google/gemini-* via the binding, v0.21.3):
54
+ // { candidates: [{ content: { parts: [{ text }] } }] }
55
+ const candidates = r?.candidates as Array<{ content?: { parts?: Array<{ text?: string }> } }> | undefined;
56
+ if (Array.isArray(candidates)) {
57
+ const text = (candidates[0]?.content?.parts ?? [])
58
+ .map((p) => p.text ?? "")
59
+ .join("");
60
+ if (text) return text;
61
+ }
62
+
63
+ // LLaVA 1.5 image-to-text (@cf/llava-hf/llava-1.5-7b-hf): { description }
64
+ if (typeof r?.description === "string") return r.description;
65
+
66
+ return JSON.stringify(result);
67
+ }
68
+
69
+ export function extractUsage(result: unknown): { in_: number | null; out_: number | null } {
70
+ const r = result as Record<string, unknown>;
71
+ // OpenAI / Anthropic: usage object on result. OpenAI uses
72
+ // prompt_tokens/completion_tokens; Anthropic uses input_tokens/output_tokens.
73
+ const u = r?.usage as Record<string, number> | undefined;
74
+ if (u) {
75
+ return {
76
+ in_: u.prompt_tokens ?? u.input_tokens ?? null,
77
+ out_: u.completion_tokens ?? u.output_tokens ?? null,
78
+ };
79
+ }
80
+ // Gemini-native usage (v0.21.3): usageMetadata.promptTokenCount /
81
+ // candidatesTokenCount (thoughtsTokenCount is reasoning, not counted as out).
82
+ const um = r?.usageMetadata as Record<string, number> | undefined;
83
+ if (um) {
84
+ return {
85
+ in_: um.promptTokenCount ?? null,
86
+ out_: um.candidatesTokenCount ?? null,
87
+ };
88
+ }
89
+ return { in_: null, out_: null };
90
+ }
91
+
92
+ // Detect a provider failure envelope returned as a normal resolved value
93
+ // rather than thrown. Unified-billing proxied models (seen first with the
94
+ // OpenAI chat models in v0.21.0) can return { state: "Failed", error: "..." }
95
+ // from env.AI.run instead of rejecting; the gateway uses the same envelope
96
+ // the LongRunWorkflow already checks for video/music. Without catching it,
97
+ // extractOutput would JSON.stringify the envelope into chats.output and a
98
+ // failed turn would persist as if it succeeded.
99
+ //
100
+ // Sync chat responses (OpenAI {choices}, Anthropic {content}, Workers AI
101
+ // {response}) carry no `state` field, so a present `state` that isn't
102
+ // "Completed" is the signal. Returns the upstream error message (for the
103
+ // caller to surface as a 502) or null when the result looks normal.
104
+ export function detectProviderFailure(result: unknown): string | null {
105
+ if (!result || typeof result !== "object") return null;
106
+ const r = result as Record<string, unknown>;
107
+ if (typeof r.state === "string" && r.state !== "Completed") {
108
+ return typeof r.error === "string" && r.error.trim()
109
+ ? r.error
110
+ : `provider returned state "${r.state}"`;
111
+ }
112
+ return null;
113
+ }
114
+
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 {
122
+ if (!result || typeof result !== "object") return null;
123
+ const r = result as { result?: { image?: unknown }; image?: unknown };
124
+ const wrapped = r.result?.image;
125
+ if (typeof wrapped === "string" && wrapped.length > 0) return wrapped;
126
+ if (typeof r.image === "string" && r.image.length > 0) return r.image;
127
+ return null;
128
+ }
@@ -0,0 +1,56 @@
1
+ // Anthropic SSE interpreter (v0.18.1).
2
+ //
3
+ // Anthropic's streaming format uses named events distinguished by a `type`
4
+ // field inside each `data:` payload (the framer ignores the `event:` header
5
+ // line since the payload's own `type` carries the same information).
6
+ //
7
+ // Event types and our handling:
8
+ // - message_start -> usage event (initial input_tokens + small initial output_tokens)
9
+ // - content_block_start -> ignored
10
+ // - content_block_delta (with delta.type=text_delta) -> text event
11
+ // - content_block_delta (with delta.type=input_json_delta) -> ignored (tool-use)
12
+ // - content_block_stop -> ignored
13
+ // - message_delta -> usage event (final output_tokens count)
14
+ // - message_stop -> ignored
15
+ // - ping -> ignored (keep-alive)
16
+ //
17
+ // Usage appears in TWO places: message_start carries the initial input_tokens
18
+ // plus a low output_tokens estimate, and message_delta later carries the final
19
+ // accurate output_tokens. Consumers typically take the last usage event of
20
+ // each kind. Both are emitted; downstream code decides what to do with them.
21
+
22
+ import type { ProviderStreamEvent } from "./types";
23
+
24
+ export function interpretAnthropicSSEFrame(data: unknown): ProviderStreamEvent[] {
25
+ const events: ProviderStreamEvent[] = [];
26
+ const d = data as Record<string, unknown>;
27
+ const evType = d.type as string | undefined;
28
+
29
+ if (evType === "content_block_delta") {
30
+ const delta = d.delta as { type?: string; text?: string } | undefined;
31
+ if (delta?.type === "text_delta" && typeof delta.text === "string") {
32
+ events.push({ type: "text", text: delta.text });
33
+ }
34
+ } else if (evType === "message_start") {
35
+ const msg = d.message as { usage?: { input_tokens?: number; output_tokens?: number } } | undefined;
36
+ if (msg?.usage) {
37
+ events.push({
38
+ type: "usage",
39
+ in_: msg.usage.input_tokens ?? null,
40
+ out_: msg.usage.output_tokens ?? null,
41
+ });
42
+ }
43
+ } else if (evType === "message_delta") {
44
+ const usage = d.usage as { input_tokens?: number; output_tokens?: number } | undefined;
45
+ if (usage) {
46
+ events.push({
47
+ type: "usage",
48
+ in_: usage.input_tokens ?? null,
49
+ out_: usage.output_tokens ?? null,
50
+ });
51
+ }
52
+ }
53
+ // content_block_start, content_block_stop, message_stop, ping: ignored
54
+
55
+ return events;
56
+ }
@@ -0,0 +1,62 @@
1
+ // Gemini SSE interpreter (v0.21.4).
2
+ //
3
+ // Streamed via env.AI.run("google/gemini-*", { ...contents, stream: true }).
4
+ // Each SSE frame is a Gemini chunk shaped like the non-stream response:
5
+ // { candidates: [{ content: { parts: [{ text }] } }], usageMetadata? }
6
+ //
7
+ // The interpreter is stateless and returns the frame's candidate text as-is
8
+ // (joined parts) plus any usage. The incremental-vs-cumulative question is
9
+ // handled OUTSIDE the interpreter, in the stream caller, via the reconciler
10
+ // below, because it needs cross-frame state. We don't probe which mode the
11
+ // binding uses, so we reconcile defensively (see makeGeminiDeltaReconciler).
12
+
13
+ import type { ProviderStreamEvent } from "./types";
14
+
15
+ export function interpretGeminiSSEFrame(data: unknown): ProviderStreamEvent[] {
16
+ const events: ProviderStreamEvent[] = [];
17
+ if (!data || typeof data !== "object") return events;
18
+ const d = data as {
19
+ candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>;
20
+ usageMetadata?: { promptTokenCount?: number; candidatesTokenCount?: number };
21
+ };
22
+
23
+ const parts = d.candidates?.[0]?.content?.parts;
24
+ if (Array.isArray(parts)) {
25
+ const text = parts.map((p) => p?.text ?? "").join("");
26
+ if (text.length > 0) events.push({ type: "text", text });
27
+ }
28
+
29
+ if (d.usageMetadata) {
30
+ events.push({
31
+ type: "usage",
32
+ in_: d.usageMetadata.promptTokenCount ?? null,
33
+ out_: d.usageMetadata.candidatesTokenCount ?? null,
34
+ });
35
+ }
36
+
37
+ return events;
38
+ }
39
+
40
+ // Gemini stream chunks may be INCREMENTAL (each chunk's text is the new piece)
41
+ // or CUMULATIVE (each chunk's text is the full answer so far), depending on the
42
+ // binding. We don't probe it, so reconcile defensively:
43
+ // - If the new frame text extends what we've already emitted (startsWith),
44
+ // it's cumulative -> emit only the new suffix.
45
+ // - Otherwise it's a fresh incremental piece -> emit it whole.
46
+ // Both modes produce correct, non-repeating deltas for the consumer to append.
47
+ // Edge case: an incremental piece that exactly equals emitted+suffix would be
48
+ // mis-sliced; astronomically unlikely in natural-language token streams. If a
49
+ // live test ever shows repeated or truncated text, the probe (raw frames) tells
50
+ // you the true mode and this can be hard-coded to one branch.
51
+ export function makeGeminiDeltaReconciler(): (frameText: string) => string {
52
+ let emitted = "";
53
+ return (t: string): string => {
54
+ if (t.startsWith(emitted)) {
55
+ const delta = t.slice(emitted.length);
56
+ emitted = t;
57
+ return delta;
58
+ }
59
+ emitted += t;
60
+ return t;
61
+ };
62
+ }