@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
@@ -0,0 +1,1709 @@
1
+ // Generation routes: chat (text, multimodal in, streaming), image, TTS, STT,
2
+ // music, and video, plus the shared persistence (persistChat) and the job-poll
3
+ // endpoint. handleChat dispatches by model.type; runChat/runChatStream own the
4
+ // RAG + web-search + multi-turn prelude (retrieval lives in ./rag). Long jobs
5
+ // (video/music) hand off to LongRunWorkflow (./workflow).
6
+
7
+ import type { Env } from "../env";
8
+ import type { ModelType, ModelEntry } from "../models";
9
+ import { MODELS } from "../models";
10
+ import type { InputAttachment } from "../types";
11
+ import type { ProviderStreamEvent } from "../parsers/types";
12
+ import { parseDataUrl, base64ToBytes } from "../utils";
13
+ import { aiRun, aiLogId, type AiContext } from "../ai-binding";
14
+ import { extractOutput, extractUsage, detectProviderFailure, extractProxiedImageAsset } from "../output-extract";
15
+ import { callAnthropic, callAnthropicStream } from "../providers/anthropic";
16
+ import { callXai, callXaiStream } from "../providers/xai";
17
+ import { callWorkersAIStream } from "../providers/workers-ai";
18
+ import { callOpenAI, callOpenAIStream } from "../providers/openai";
19
+ import { callGemini, callGeminiStream } from "../providers/google";
20
+ import { generateOpenAIImage } from "../providers/openai-image";
21
+ import { buildProxiedImageParams } from "../proxied-image-params";
22
+ import {
23
+ json,
24
+ getUserEmail,
25
+ requireAiContext,
26
+ requireInferenceBackend,
27
+ modelNeedsCfAigToken,
28
+ r2Put,
29
+ resolveAttachmentKeys,
30
+ safeParseJson,
31
+ } from "./shared";
32
+ import { controlPlaneChat, type ControlPlaneChatMessage } from "../control-plane";
33
+ import type {
34
+ ChatRequest,
35
+ RetrievedChunk,
36
+ RetrievedWebResult,
37
+ RetrievedItem,
38
+ PersistedAttachment,
39
+ PersistedDocumentAttachment,
40
+ OutputArtifact,
41
+ } from "./shared";
42
+ import {
43
+ retrieveContext,
44
+ RETRIEVE_TOP_K,
45
+ searchWeb,
46
+ formatRetrievalForSystemPrompt,
47
+ formatWebForSystemPrompt,
48
+ looksBinary,
49
+ } from "./rag";
50
+ import { resolveProjectForChat } from "./projects";
51
+ import type { LongRunParams } from "./workflow";
52
+
53
+ //
54
+ // Multimodal model types:
55
+ // - chat: text-generation models. Accepts vision attachments if the model
56
+ // declares 'vision' in capabilities. Audio attachments are transcribed
57
+ // via Whisper before the chat call. Video attachments are 8 client-
58
+ // extracted keyframes plus the original file's audio track (also
59
+ // transcribed). Output: text in chats.output.
60
+ // - image: image-generation models (FLUX-1 schnell, Lucid Origin, Phoenix).
61
+ // Input: user_input as prompt, system_prompt as negative_prompt.
62
+ // Output: PNG written to R2, referenced via chats.output_artifact.
63
+ // - tts: text-to-speech models (Aura-2, MeloTTS).
64
+ // Input: user_input as text.
65
+ // Output: audio written to R2, referenced via chats.output_artifact.
66
+ //
67
+ // Storage:
68
+ // - All input + output artifacts go to R2.
69
+ // - D1 stores R2 keys plus structured metadata.
70
+ // - On DELETE /api/history/:id, R2 objects are removed too.
71
+ // - Artifact ownership is enforced via customMetadata.user_email on the
72
+ // R2 object plus a check in GET /api/artifact/*.
73
+
74
+
75
+ export const WHISPER_MODEL = "@cf/openai/whisper-large-v3-turbo";
76
+
77
+ // v0.24.0: cap on inline text-file (document) attachments folded into a chat
78
+ // prompt. Large files past this are truncated with a marker so a single
79
+ // attachment can't blow the model's context window.
80
+ export const MAX_DOC_ATTACHMENT_CHARS = 200_000;
81
+
82
+ // v0.24.0: shared handling for an inline document (text-file) attachment on a
83
+ // chat turn. The contents are folded into the prompt as a fenced block, the
84
+ // same mechanism as audio transcription. Binary input is rejected via the
85
+ // same looksBinary heuristic the RAG uploader uses. Returns either an error
86
+ // string for the 400 path or the prompt block + persisted metadata record.
87
+ export function buildDocumentAttachment(att: { text?: string; mime?: string; filename?: string }):
88
+ | { error: string }
89
+ | { extra: string; persisted: PersistedDocumentAttachment } {
90
+ const raw = att.text ?? "";
91
+ if (looksBinary(raw)) {
92
+ return { error: `${att.filename || "Attached file"} looks like binary data that can't be read as text. Attach a text-based file (txt, md, yaml, json, csv, source code, etc.).` };
93
+ }
94
+ const truncated = raw.length > MAX_DOC_ATTACHMENT_CHARS;
95
+ const text = truncated ? raw.slice(0, MAX_DOC_ATTACHMENT_CHARS) : raw;
96
+ const fn = att.filename ? ` ${att.filename}` : "";
97
+ const extra = `[Attached file${fn}]\n\`\`\`\n${text}\n\`\`\`${truncated ? "\n[file truncated to fit context]" : ""}`;
98
+ return { extra, persisted: { type: "document", mime: att.mime, filename: att.filename, chars: text.length } };
99
+ }
100
+
101
+ // ---------- /api/chat ----------
102
+
103
+ export async function handleChat(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
104
+ let body: ChatRequest;
105
+ try {
106
+ body = await request.json<ChatRequest>();
107
+ } catch {
108
+ return json({ error: "Invalid JSON" }, { status: 400 });
109
+ }
110
+
111
+ if (!body.model || !body.user_input) {
112
+ return json({ error: "model and user_input are required" }, { status: 400 });
113
+ }
114
+ const model = MODELS.find((x) => x.id === body.model);
115
+ if (!model) {
116
+ return json({ error: `Unknown model: ${body.model}` }, { status: 400 });
117
+ }
118
+
119
+ // Hydrate attachment-by-reference (image/video attachments carrying an R2
120
+ // key instead of inline data) before routing, so every handler sees ready
121
+ // attachments. v0.21.7: cross-model artifact reuse within a conversation.
122
+ if (body.attachments?.length) {
123
+ body.attachments = await resolveAttachmentKeys(env, body.attachments, await getUserEmail(request, env));
124
+ }
125
+
126
+ if (model.type === "chat") return runChat(request, env, model, body);
127
+ if (model.type === "image") return runImage(request, env, model, body);
128
+ if (model.type === "tts") return runTts(request, env, model, body);
129
+ if (model.type === "video") return runVideo(request, env, ctx, model, body);
130
+ if (model.type === "stt") return runStt(request, env, model, body);
131
+ if (model.type === "music") return runMusic(request, env, ctx, model, body);
132
+ // "voice" is a live streaming session, not a request/response turn. The UI
133
+ // opens the mic streamer (WS /api/stt/stream) instead of POSTing here; reject
134
+ // with a clear pointer in case a client tries the chat path anyway.
135
+ if (model.type === "voice") {
136
+ return json(
137
+ { error: "This is a live voice model; connect to the WebSocket at /api/stt/stream (mic streaming), not /api/chat." },
138
+ { status: 400 },
139
+ );
140
+ }
141
+ return json({ error: `Unsupported model type: ${model.type}` }, { status: 500 });
142
+ }
143
+
144
+ // ---------- /api/chat/stream (v0.13.0) ----------
145
+ //
146
+ // Thin entry point. Validates input + model, gates by model.streaming +
147
+ // model.provider (Pass 1 supports Anthropic only), then dispatches to
148
+ // runChatStream. Non-chat types and non-streaming chat models bounce with
149
+ // 400 here so the streaming runtime stays narrow.
150
+
151
+ export async function handleChatStream(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
152
+ void ctx; // the response body is a live stream; the worker stays alive while it's open.
153
+
154
+ let body: ChatRequest;
155
+ try {
156
+ body = await request.json<ChatRequest>();
157
+ } catch {
158
+ return json({ error: "Invalid JSON" }, { status: 400 });
159
+ }
160
+ if (!body.model || !body.user_input) {
161
+ return json({ error: "model and user_input are required" }, { status: 400 });
162
+ }
163
+ const model = MODELS.find((x) => x.id === body.model);
164
+ if (!model) {
165
+ return json({ error: `Unknown model: ${body.model}` }, { status: 400 });
166
+ }
167
+ if (model.type !== "chat") {
168
+ return json({ error: `Streaming is only supported for chat models. Use /api/chat for ${model.type} models.` }, { status: 400 });
169
+ }
170
+ if (!model.streaming) {
171
+ return json({ error: `Model ${model.id} does not support streaming. Use /api/chat (non-streaming) or pick a streaming-capable model.` }, { status: 400 });
172
+ }
173
+ // Anthropic + Workers AI + xAI + OpenAI + Google + Moonshot. Workers AI
174
+ // catalog entries omit `provider` (default "workers-ai"); Unified Billing
175
+ // providers set it explicitly. Keep this allowlist in lockstep with the
176
+ // stream dispatch switch in runChatStream (v0.171.0: moonshotai).
177
+ const isWorkersAI = !model.provider;
178
+ if (
179
+ model.provider !== "anthropic" &&
180
+ model.provider !== "xai" &&
181
+ model.provider !== "openai" &&
182
+ model.provider !== "google" &&
183
+ model.provider !== "moonshotai" &&
184
+ !isWorkersAI
185
+ ) {
186
+ return json({ error: `Streaming for provider '${model.provider}' is not yet implemented.` }, { status: 501 });
187
+ }
188
+
189
+ return runChatStream(request, env, model, body);
190
+ }
191
+
192
+ // ---------- Chat (text generation, multimodal in) ----------
193
+
194
+ export async function runChat(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
195
+ const userEmail = await getUserEmail(request, env);
196
+ const backendOrErr = await requireInferenceBackend(env, userEmail, {
197
+ requireCfToken: modelNeedsCfAigToken(model),
198
+ });
199
+ if (backendOrErr instanceof Response) return backendOrErr;
200
+ const backend = backendOrErr;
201
+ // Gateway AI context when not using control plane (Whisper + provider dispatch).
202
+ const aiCtx: AiContext | null = backend.kind === "gateway" ? backend.ctx : null;
203
+ const inputs: InputAttachment[] = body.attachments ?? [];
204
+
205
+ // v0.20.0: resolve project_id to row, apply per-project system_prompt
206
+ // fallback when the per-turn prompt is empty/undefined. The effective
207
+ // prompt is mutated back onto `body` so downstream provider calls and
208
+ // persistence see exactly what was used. scopedProjectId is passed to
209
+ // retrieveContext so RAG retrieval is filtered to that project's docs.
210
+ const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
211
+ body.system_prompt = resolvedSystemPrompt;
212
+
213
+ // Hot-path parallelization (v0.12.1): kick off the prior-turns SELECT and
214
+ // the RAG retrieve in the background while the attachment walk runs. None
215
+ // of the three depend on each other (the SELECT only needs the inbound
216
+ // conversation_id + user_email; retrieveContext only needs user_email +
217
+ // the raw user_input), so serializing them costs ~600-1500ms on
218
+ // multimodal+RAG turns. We await each promise at its existing use site
219
+ // below so the error surface is unchanged.
220
+ const conversationIdIn = body.conversation_id?.trim() || "";
221
+ const priorTurnsPromise: Promise<{
222
+ rows: Array<{ user_input: string; output: string; turn_index: number }>;
223
+ }> = conversationIdIn
224
+ ? env.DB.prepare(
225
+ `SELECT user_input, output, turn_index
226
+ FROM chats
227
+ WHERE conversation_id = ?
228
+ AND user_email = ?
229
+ AND status = 'done'
230
+ AND model_type = 'chat'
231
+ ORDER BY turn_index ASC`
232
+ )
233
+ .bind(conversationIdIn, userEmail)
234
+ .all<{ user_input: string; output: string; turn_index: number }>()
235
+ .then((r) => ({ rows: r.results ?? [] }))
236
+ : Promise.resolve({ rows: [] });
237
+
238
+ const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
239
+ body.use_docs
240
+ ? retrieveContext(env, userEmail, body.user_input, RETRIEVE_TOP_K, scopedProjectId)
241
+ : Promise.resolve({ chunks: [], error: null });
242
+
243
+ // v0.17.0: web search runs in parallel with RAG retrieval and the
244
+ // attachment walk. Per-source timeouts + catches inside searchWeb bound
245
+ // the worst-case latency to WEB_SEARCH_TIMEOUT_MS.
246
+ const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
247
+ body.use_web_search
248
+ ? searchWeb(env, body.user_input)
249
+ : Promise.resolve({ results: [], error: null });
250
+
251
+ // Walk inputs: write images / video frames to R2, transcribe audio via
252
+ // Whisper. Build three parallel structures used after the loop:
253
+ // - extraText: prompt snippets the LLM sees
254
+ // - imageDataUrls: data URLs the LLM sees as image_url blocks
255
+ // - persistedAtt: per-attachment storage records
256
+ const extraText: string[] = [];
257
+ const imageDataUrls: string[] = [];
258
+ const persistedAtt: PersistedAttachment[] = [];
259
+
260
+ for (const att of inputs) {
261
+ if (att.type === "image") {
262
+ if (!model.capabilities.includes("vision")) {
263
+ return json({ error: `Model ${model.id} does not support vision. Pick a vision-capable chat model or remove the image.` }, { status: 400 });
264
+ }
265
+ const parsed = att.data ? parseDataUrl(att.data) : null;
266
+ if (!parsed) return json({ error: "Invalid image data URL" }, { status: 400 });
267
+ const bytes = base64ToBytes(parsed.base64);
268
+ const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
269
+ imageDataUrls.push(att.data!); // guaranteed by the parsed guard above (data may be hydrated from a key)
270
+ persistedAtt.push({ type: "image", key, mime: parsed.mime, filename: att.filename });
271
+ } else if (att.type === "audio") {
272
+ if (!aiCtx) {
273
+ return json(
274
+ {
275
+ error:
276
+ "Audio attachments need on-worker Whisper, which is unavailable when control-plane mode is on. Clear the control-plane key or remove the audio attachment.",
277
+ code: "control_plane_no_audio",
278
+ },
279
+ { status: 400 },
280
+ );
281
+ }
282
+ const parsed = att.data ? parseDataUrl(att.data) : null;
283
+ if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
284
+ try {
285
+ const wr = await aiRun(aiCtx, WHISPER_MODEL, { audio: parsed.base64 });
286
+ const text = (wr as { text?: string })?.text?.trim() ?? "";
287
+ const label = att.filename ? ` from ${att.filename}` : "";
288
+ extraText.push(text
289
+ ? `[Transcribed audio${label}]\n${text}`
290
+ : `[Audio attachment${label} transcribed to empty text]`);
291
+ persistedAtt.push({ type: "audio", mime: parsed.mime, filename: att.filename, transcript: text || null });
292
+ } catch (err) {
293
+ const m = err instanceof Error ? err.message : String(err);
294
+ return json({ error: `Audio transcription failed: ${m}` }, { status: 502 });
295
+ }
296
+ } else if (att.type === "video_frames") {
297
+ if (!model.capabilities.includes("vision")) {
298
+ return json({ error: `Model ${model.id} does not support vision. Video frames require a vision-capable chat model.` }, { status: 400 });
299
+ }
300
+ const frames = att.frames ?? [];
301
+ // Parse first (cheap, synchronous), then fan out R2 puts in parallel.
302
+ // Frames are independent: there's no ordering constraint between R2
303
+ // writes, only between the resulting `imageDataUrls` entries (which
304
+ // we preserve by iterating the same parsedFrames array twice).
305
+ const parsedFrames = frames
306
+ .map((fdataUrl) => ({ fdataUrl, parsed: parseDataUrl(fdataUrl) }))
307
+ .filter((p): p is { fdataUrl: string; parsed: { mime: string; base64: string } } => p.parsed !== null);
308
+ const keys = await Promise.all(
309
+ parsedFrames.map(({ parsed }) =>
310
+ r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail)
311
+ )
312
+ );
313
+ for (const { fdataUrl } of parsedFrames) {
314
+ imageDataUrls.push(fdataUrl);
315
+ }
316
+ const dur = att.duration ? ` ${att.duration.toFixed(1)}s` : "";
317
+ const fn = att.filename ? ` "${att.filename}"` : "";
318
+ extraText.push(`[Video${fn}${dur}, ${frames.length} evenly-sampled frames attached below]`);
319
+ persistedAtt.push({ type: "video_frames", keys, frame_count: keys.length, duration: att.duration, filename: att.filename });
320
+ } else if (att.type === "video_full") {
321
+ // Full video file upload. No chat model currently consumes the raw video
322
+ // (the keyframe path covers vision models); the upload is still stored in
323
+ // R2 so it appears in history and the plumbing stays ready for a future
324
+ // video-aware model. Dormant since Bedrock Pegasus was removed in v0.95.0.
325
+ const parsed = att.data ? parseDataUrl(att.data) : null;
326
+ if (!parsed) return json({ error: "Invalid video data URL" }, { status: 400 });
327
+ const bytes = base64ToBytes(parsed.base64);
328
+ const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
329
+ const fn = att.filename ? ` "${att.filename}"` : "";
330
+ extraText.push(`[Full video${fn} attached for video-aware model]`);
331
+ persistedAtt.push({ type: "video_full", key, mime: parsed.mime, filename: att.filename });
332
+ } else if (att.type === "document") {
333
+ const r = buildDocumentAttachment(att);
334
+ if ("error" in r) return json({ error: r.error }, { status: 400 });
335
+ extraText.push(r.extra);
336
+ persistedAtt.push(r.persisted);
337
+ }
338
+ }
339
+
340
+ const userText = [body.user_input, ...extraText].filter(Boolean).join("\n\n");
341
+ const userContent: unknown = imageDataUrls.length
342
+ ? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
343
+ : userText;
344
+
345
+ // ---- Multi-turn conversation continuation (v0.10.0) ----
346
+ // If body.conversation_id is present, fetch prior turns of that conversation
347
+ // (filtered to this user, completed chat turns only) and assemble a history
348
+ // of user/assistant message pairs. The current turn appends to that history.
349
+ // If no conversation_id, generate a new one for the first turn.
350
+ // The SELECT itself runs in parallel with the attachment walk (hoisted
351
+ // above as priorTurnsPromise); here we just consume the result.
352
+ let conversationId = conversationIdIn;
353
+ let turnIndex = 0;
354
+ const priorTurns: Array<{ user_input: string; output: string }> = [];
355
+
356
+ if (conversationId) {
357
+ const { rows } = await priorTurnsPromise;
358
+ for (const r of rows) {
359
+ // Skip empty/failed prior turns defensively.
360
+ if (r.user_input && r.output) {
361
+ priorTurns.push({ user_input: r.user_input, output: r.output });
362
+ }
363
+ }
364
+ turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
365
+ } else {
366
+ // crypto.randomUUID() is available in Workers runtime.
367
+ conversationId = crypto.randomUUID();
368
+ }
369
+
370
+ // RAG retrieval (Pass 2) - per-turn, applies only to THIS turn's system prompt.
371
+ // The retrieve itself runs in parallel with the attachment walk + prior-turns
372
+ // fetch (hoisted above as retrievePromise); here we just consume the result.
373
+ const { chunks: retrievedChunks, error: retrievalError } = await retrievePromise;
374
+
375
+ // v0.17.0: web-search retrieval, same parallelism pattern as RAG.
376
+ const { results: webResults, error: webSearchError } = await webSearchPromise;
377
+ const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
378
+
379
+ // Build the effective system prompt: user-supplied prompt followed by
380
+ // the retrieval block(s). Order: user prompt, then RAG (more specific
381
+ // to this user's corpus), then web (more general). Either or both
382
+ // retrieval blocks may be empty.
383
+ const userSystemPrompt = body.system_prompt?.trim() ?? "";
384
+ const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
385
+ const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
386
+ const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
387
+ .filter(Boolean)
388
+ .join("\n\n");
389
+
390
+ // Build the message array. For Anthropic, system goes as a top-level field
391
+ // on the upstream request (handled inside callAnthropic), not in messages.
392
+ // For Workers AI, xAI, and OpenAI, we push a role:"system" message.
393
+ //
394
+ // Prior turns of this conversation go in as alternating user/assistant
395
+ // text messages. Multimodal content (images) from prior turns is NOT
396
+ // re-included; if the user wants to reference earlier images they can
397
+ // re-attach. Current turn's attachments are still threaded into userContent.
398
+ const wantsSystemInMessages = model.provider !== "anthropic" && model.provider !== "google";
399
+ const messages: Array<unknown> = [];
400
+ if (effectiveSystemPrompt && wantsSystemInMessages) {
401
+ messages.push({ role: "system", content: effectiveSystemPrompt });
402
+ }
403
+ for (const t of priorTurns) {
404
+ messages.push({ role: "user", content: t.user_input });
405
+ messages.push({ role: "assistant", content: t.output });
406
+ }
407
+ messages.push({ role: "user", content: userContent });
408
+
409
+ const start = Date.now();
410
+ let result: unknown;
411
+ let logId: string | null = null;
412
+ try {
413
+ if (backend.kind === "control_plane") {
414
+ // Control plane: OpenAI-compatible messages (string content only for v1).
415
+ // Multimodal image parts stay on the gateway path until CP accepts them.
416
+ if (imageDataUrls.length > 0) {
417
+ return json(
418
+ {
419
+ error:
420
+ "Vision attachments are not forwarded on the control-plane path yet. Clear the control-plane key or use a text-only turn.",
421
+ code: "control_plane_no_vision",
422
+ },
423
+ { status: 400 },
424
+ );
425
+ }
426
+ const cpMessages: ControlPlaneChatMessage[] = [];
427
+ if (effectiveSystemPrompt) {
428
+ cpMessages.push({ role: "system", content: effectiveSystemPrompt });
429
+ }
430
+ for (const t of priorTurns) {
431
+ cpMessages.push({ role: "user", content: t.user_input });
432
+ cpMessages.push({ role: "assistant", content: t.output });
433
+ }
434
+ // userContent may be string or multimodal array; flatten to text for CP.
435
+ const userText =
436
+ typeof userContent === "string"
437
+ ? userContent
438
+ : body.user_input + (extraText.length ? `\n\n${extraText.join("\n\n")}` : "");
439
+ cpMessages.push({ role: "user", content: userText });
440
+ const cpResult = await controlPlaneChat(backend.cp, {
441
+ model: model.id,
442
+ messages: cpMessages,
443
+ });
444
+ result = {
445
+ choices: [{ message: { role: "assistant", content: cpResult.text } }],
446
+ usage: {
447
+ prompt_tokens: cpResult.usage.prompt_tokens,
448
+ completion_tokens: cpResult.usage.completion_tokens,
449
+ },
450
+ };
451
+ logId = cpResult.requestId;
452
+ } else if (!aiCtx) {
453
+ return json({ error: "AI gateway context missing" }, { status: 500 });
454
+ } else if (model.provider === "anthropic") {
455
+ const r = await callAnthropic(aiCtx, model, effectiveSystemPrompt || undefined, messages);
456
+ result = r.raw;
457
+ logId = r.logId;
458
+ } else if (model.provider === "xai") {
459
+ const r = await callXai(aiCtx, model, messages);
460
+ result = r.raw;
461
+ logId = r.logId;
462
+ } else if (model.provider === "google") {
463
+ const r = await callGemini(aiCtx, model, effectiveSystemPrompt || undefined, messages);
464
+ result = r.raw;
465
+ logId = r.logId;
466
+ } else if (model.provider === "openai") {
467
+ // Chat Completions or Responses API depending on model.api (v0.173.0).
468
+ const r = await callOpenAI(aiCtx, model, messages);
469
+ result = r.raw;
470
+ logId = r.logId;
471
+ } else {
472
+ // Workers AI hosted chat (and moonshotai Chat Completions via env.AI.run).
473
+ result = await aiRun(aiCtx, model.id, { messages });
474
+ logId = aiLogId(aiCtx);
475
+ }
476
+ } catch (err) {
477
+ const m = err instanceof Error ? err.message : String(err);
478
+ const status = (err as { status?: number })?.status;
479
+ if (status === 401 || status === 402 || status === 403 || status === 429) {
480
+ return json({ error: `AI call failed: ${m}`, code: (err as { code?: string })?.code }, { status });
481
+ }
482
+ return json({ error: `AI call failed: ${m}` }, { status: 502 });
483
+ }
484
+
485
+ // Some providers (notably OpenAI/Gemini proxied via unified billing) return
486
+ // a failure envelope { state: "Failed", error: "..." } as a resolved value
487
+ // instead of throwing. Surface it as a 502 here; otherwise extractOutput
488
+ // would stringify the envelope into chats.output and persist the failed
489
+ // turn as a success.
490
+ const providerFailure = detectProviderFailure(result);
491
+ if (providerFailure) {
492
+ return json({ error: `Model execution failed: ${providerFailure}` }, { status: 502 });
493
+ }
494
+
495
+ const latency = Date.now() - start;
496
+ const output = extractOutput(result);
497
+ const usage = extractUsage(result);
498
+
499
+ const row = await persistChat(env, {
500
+ userEmail,
501
+ model: model.id,
502
+ model_type: "chat",
503
+ system_prompt: body.system_prompt ?? null,
504
+ user_input: body.user_input,
505
+ output,
506
+ output_artifact: null,
507
+ attachments: persistedAtt,
508
+ tokens_in: usage.in_,
509
+ tokens_out: usage.out_,
510
+ latency_ms: latency,
511
+ ai_gateway_log_id: logId,
512
+ retrieved_context: allRetrieved.length ? allRetrieved : null,
513
+ conversation_id: conversationId,
514
+ turn_index: turnIndex,
515
+ project_id: scopedProjectId ?? null,
516
+ });
517
+
518
+ return json({
519
+ id: row.id,
520
+ created_at: row.created_at,
521
+ model: model.id,
522
+ model_type: "chat",
523
+ output,
524
+ tokens_in: usage.in_,
525
+ tokens_out: usage.out_,
526
+ latency_ms: latency,
527
+ ai_gateway_log_id: logId,
528
+ transcripts: extraText,
529
+ retrieved_chunks: retrievedChunks,
530
+ web_results: webResults,
531
+ conversation_id: conversationId,
532
+ turn_index: turnIndex,
533
+ // Diagnostic: when either retrieval source was on, include the exact text
534
+ // that went into the model as the system prompt, plus per-source errors.
535
+ // Inspect via browser DevTools to verify the retrieval block reached
536
+ // the model.
537
+ effective_system_prompt: (body.use_docs || body.use_web_search) ? effectiveSystemPrompt : undefined,
538
+ retrieval_error: body.use_docs ? retrievalError : undefined,
539
+ web_search_error: body.use_web_search ? webSearchError : undefined,
540
+ });
541
+ }
542
+
543
+ // ---------- Image generation ----------
544
+
545
+ export async function runImage(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
546
+ const userEmail = await getUserEmail(request, env);
547
+ let aiCtx: AiContext | null = null;
548
+ const needsProxiedGateway = !!model.provider;
549
+ if (needsProxiedGateway) {
550
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: true });
551
+ if (ctxOrErr instanceof Response) return ctxOrErr;
552
+ aiCtx = ctxOrErr;
553
+ }
554
+
555
+ // Image gen splits two ways. Proxied models (those with a `provider`:
556
+ // nano-banana/google, gpt-image-1.5/openai, recraftv4/recraft) go through the
557
+ // gateway binding, return a URL, and share one code path. The @cf models
558
+ // (no `provider`) return base64 or a ReadableStream and need the bypass +
559
+ // shape-detection handling below. Both converge on the (bytes, mime) tuple
560
+ // and the shared R2-put + persist + respond tail.
561
+ let bytes: Uint8Array;
562
+ let mime: string;
563
+ let latency: number;
564
+ let logId: string | null = null;
565
+
566
+ const start = Date.now();
567
+ try {
568
+ if (model.provider) {
569
+ // Proxied image models ride Unified Billing via the gateway, except the
570
+ // sole OpenAI transparent-PNG carve-out: when OPENAI_API_KEY is set on
571
+ // openai/* image models, call api.openai.com directly (proxy rejects
572
+ // background/output_format). No other provider uses a deployer key.
573
+ //
574
+ // Unified Billing response shapes:
575
+ // URL: { state, result: { image: "https://..." } } or images[]
576
+ // inline: { state, result: { image: "<b64|data-uri>" } } // xAI Grok Imagine
577
+ // xAI requires response_format:b64_json (ZDR-managed credentials reject
578
+ // URL output). extractProxiedImageAsset normalizes both.
579
+ if (model.provider === "openai" && env.OPENAI_API_KEY) {
580
+ const gen = await generateOpenAIImage(env.OPENAI_API_KEY, model.id, body.user_input);
581
+ bytes = gen.bytes;
582
+ mime = gen.mime;
583
+ logId = null; // direct OpenAI; no AI Gateway log
584
+ } else {
585
+ const result = await aiRun(aiCtx!, model.id, buildProxiedImageParams(model.provider, body.user_input));
586
+ logId = aiLogId(aiCtx!);
587
+
588
+ const failure = detectProviderFailure(result);
589
+ if (failure) {
590
+ return json({ error: `Image generation failed: ${failure}` }, { status: 502 });
591
+ }
592
+ const asset = extractProxiedImageAsset(result);
593
+ if (!asset) {
594
+ return json({ error: "Image generation returned no image payload", raw: result }, { status: 502 });
595
+ }
596
+ if (asset.kind === "url") {
597
+ const aresp = await fetch(asset.url);
598
+ if (!aresp.ok) {
599
+ return json({ error: `Failed to fetch generated image: ${aresp.status}` }, { status: 502 });
600
+ }
601
+ bytes = new Uint8Array(await aresp.arrayBuffer());
602
+ mime = aresp.headers.get("content-type") || "image/png";
603
+ } else {
604
+ bytes = base64ToBytes(asset.base64);
605
+ mime = asset.mime || "image/png";
606
+ }
607
+ }
608
+ } else {
609
+ // Two Cloudflare-side complications for Workers AI image gen as of
610
+ // 2026-Q1, both manifesting as either:
611
+ // - AiError 5006 "required properties at '/' are 'multipart'", or
612
+ // - "AI Gateway does not support ReadableStreams yet"
613
+ //
614
+ // The matrix:
615
+ // FLUX-1 schnell, Lucid Origin - JSON in, JSON out (base64). Gateway path works.
616
+ // FLUX-2 (Klein 9b/4b, Dev) - multipart in, JSON out (base64). Gateway can't proxy stream input.
617
+ // Phoenix 1.0, Dreamshaper 8 LCM - JSON in, ReadableStream out. Gateway can't proxy stream output.
618
+ //
619
+ // Solution: bypass the AI Gateway for the five problematic models by
620
+ // calling env.AI.run directly without the gateway option, and detect
621
+ // the response shape at runtime so we can drain a ReadableStream into
622
+ // bytes or extract base64 from JSON as appropriate. Cost: no AI Gateway
623
+ // observability/caching for these specific models (ai_gateway_log_id
624
+ // stays null on the persisted row).
625
+ const isFlux2 = model.id.startsWith("@cf/black-forest-labs/flux-2-");
626
+ const isSdxl = model.id === "@cf/stabilityai/stable-diffusion-xl-base-1.0";
627
+ const bypassGateway = isFlux2
628
+ || model.id === "@cf/leonardo/phoenix-1.0"
629
+ || model.id === "@cf/lykon/dreamshaper-8-lcm"
630
+ || isSdxl; // SDXL returns a ReadableStream image; gateway can't proxy it
631
+
632
+ let runParams: unknown;
633
+
634
+ if (isFlux2) {
635
+ // FLUX.2 requires multipart form data input. FormData doesn't expose
636
+ // its serialized body or boundary directly; wrap in a Response
637
+ // constructor to get the stream + the Content-Type header value
638
+ // with the boundary string.
639
+ const form = new FormData();
640
+ form.append("prompt", body.user_input);
641
+ form.append("width", "1024");
642
+ form.append("height", "1024");
643
+ if (body.system_prompt && body.system_prompt.trim()) {
644
+ // FLUX.2's public schema doesn't list negative_prompt, but the
645
+ // binding ignores unknown form fields rather than erroring.
646
+ form.append("negative_prompt", body.system_prompt);
647
+ }
648
+
649
+ // Reference images (v0.16.0): FLUX.2 accepts up to 4 input images
650
+ // via input_image_0..input_image_3 form fields. Each must be at most
651
+ // 512x512 (the frontend downscales before upload). We silently cap
652
+ // beyond 4 rather than erroring, so a user who picks 5 just doesn't
653
+ // see the 5th show up; the picker UI also caps at 4 client-side.
654
+ const inputs: InputAttachment[] = body.attachments ?? [];
655
+ let refIdx = 0;
656
+ for (const att of inputs) {
657
+ if (refIdx >= 4) break;
658
+ if (att.type !== "image" || !att.data) continue;
659
+ const parsed = parseDataUrl(att.data);
660
+ if (!parsed) continue;
661
+ const blob = new Blob([base64ToBytes(parsed.base64)], { type: parsed.mime });
662
+ form.append(`input_image_${refIdx}`, blob, att.filename || `ref-${refIdx}.png`);
663
+ refIdx++;
664
+ }
665
+
666
+ const formResponse = new Response(form);
667
+ runParams = {
668
+ multipart: {
669
+ body: formResponse.body!,
670
+ contentType: formResponse.headers.get("content-type")!,
671
+ },
672
+ };
673
+ } else {
674
+ const params: Record<string, unknown> = {
675
+ prompt: body.user_input,
676
+ width: 1024,
677
+ height: 1024,
678
+ steps: 25,
679
+ };
680
+ if (body.system_prompt && body.system_prompt.trim()) {
681
+ params.negative_prompt = body.system_prompt;
682
+ }
683
+ // FLUX-1 schnell uses fewer steps and has no negative_prompt.
684
+ if (model.id === "@cf/black-forest-labs/flux-1-schnell") {
685
+ params.steps = 4;
686
+ delete params.negative_prompt;
687
+ }
688
+ // SDXL's step field is `num_steps` (max 20), not `steps`; swap to avoid
689
+ // sending an unknown/over-max field.
690
+ if (isSdxl) {
691
+ delete params.steps;
692
+ params.num_steps = 20;
693
+ }
694
+ runParams = params;
695
+ }
696
+
697
+ // Run via the binding. Bypass the gateway for stream-incompatible
698
+ // models; everything else stays on the aiRun helper path (which
699
+ // populates ai_gateway_log_id for observability).
700
+ let result: unknown;
701
+ if (bypassGateway) {
702
+ type BypassRunFn = (model: string, params: unknown) => Promise<unknown>;
703
+ result = await (env.AI as unknown as { run: BypassRunFn }).run(model.id, runParams);
704
+ } else {
705
+ if (!aiCtx) {
706
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
707
+ if (ctxOrErr instanceof Response) return ctxOrErr;
708
+ aiCtx = ctxOrErr;
709
+ }
710
+ result = await aiRun(aiCtx, model.id, runParams);
711
+ logId = aiLogId(aiCtx);
712
+ }
713
+
714
+ // Two response shapes are possible:
715
+ // 1. JSON { image: "base64..." } - FLUX-1, FLUX-2, Lucid Origin
716
+ // 2. ReadableStream of raw PNG bytes - Phoenix, Dreamshaper
717
+ // Detect at runtime rather than mapping per-model; safer if Cloudflare
718
+ // shifts a model from one shape to the other.
719
+ if (result instanceof ReadableStream) {
720
+ const reader = result.getReader();
721
+ const chunks: Uint8Array[] = [];
722
+ let total = 0;
723
+ while (true) {
724
+ const { done, value } = await reader.read();
725
+ if (done) break;
726
+ if (value) {
727
+ chunks.push(value);
728
+ total += value.length;
729
+ }
730
+ }
731
+ bytes = new Uint8Array(total);
732
+ let offset = 0;
733
+ for (const c of chunks) {
734
+ bytes.set(c, offset);
735
+ offset += c.length;
736
+ }
737
+ // All stream-output image models here emit PNG bytes. (The SDXL docs
738
+ // claim image/jpg, but the binding's actual output is PNG, confirmed
739
+ // live, so we don't special-case it.)
740
+ mime = "image/png";
741
+ } else {
742
+ const b64 = (result as { image?: string })?.image;
743
+ if (!b64 || typeof b64 !== "string") {
744
+ return json({ error: "Image generation returned no image", raw: result }, { status: 502 });
745
+ }
746
+ bytes = base64ToBytes(b64);
747
+ // FLUX.2 outputs PNG; the older JSON path returned JPEG historically.
748
+ mime = isFlux2 ? "image/png" : "image/jpeg";
749
+ }
750
+ }
751
+ } catch (err) {
752
+ const m = err instanceof Error ? err.message : String(err);
753
+ return json({ error: `Image generation failed: ${m}` }, { status: 502 });
754
+ }
755
+ latency = Date.now() - start;
756
+
757
+ const key = await r2Put(env, "out", mime, bytes, userEmail);
758
+ const outputArtifact: OutputArtifact = { key, mime, type: "image" };
759
+
760
+ const row = await persistChat(env, {
761
+ userEmail,
762
+ model: model.id,
763
+ model_type: "image",
764
+ system_prompt: body.system_prompt ?? null,
765
+ user_input: body.user_input,
766
+ output: "",
767
+ output_artifact: outputArtifact,
768
+ attachments: [],
769
+ tokens_in: null,
770
+ tokens_out: null,
771
+ latency_ms: latency,
772
+ ai_gateway_log_id: logId,
773
+ });
774
+
775
+ return json({
776
+ id: row.id,
777
+ created_at: row.created_at,
778
+ model: model.id,
779
+ model_type: "image",
780
+ output: "",
781
+ output_artifact: outputArtifact,
782
+ latency_ms: latency,
783
+ ai_gateway_log_id: logId,
784
+ conversation_id: row.conversation_id,
785
+ turn_index: 0,
786
+ });
787
+ }
788
+
789
+ // ---------- TTS ----------
790
+
791
+ // v0.118.0: speak arbitrary text via Aura-2 and stream the audio back. No D1
792
+ // row (the voice-chat loop calls this for every assistant reply; persisting
793
+ // each one would flood history). Caps length and restricts the voice to the
794
+ // two Aura-2 catalog entries.
795
+ export const TTS_VOICES = new Set(["@cf/deepgram/aura-2-en", "@cf/deepgram/aura-2-es"]);
796
+ export async function handleTtsSpeak(request: Request, env: Env): Promise<Response> {
797
+ const userEmail = await getUserEmail(request, env);
798
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
799
+ if (ctxOrErr instanceof Response) return ctxOrErr;
800
+ const aiCtx = ctxOrErr;
801
+
802
+ let body: { text?: string; voice?: string };
803
+ try {
804
+ body = await request.json<{ text?: string; voice?: string }>();
805
+ } catch {
806
+ return json({ error: "Invalid JSON" }, { status: 400 });
807
+ }
808
+ const text = typeof body.text === "string" ? body.text.trim().slice(0, 4000) : "";
809
+ if (!text) return json({ error: "text required" }, { status: 400 });
810
+ const voice = body.voice && TTS_VOICES.has(body.voice) ? body.voice : "@cf/deepgram/aura-2-en";
811
+ try {
812
+ const resp = await aiRun(aiCtx, voice, { text, prompt: text }, true /* returnRawResponse */);
813
+ if (!(resp instanceof Response)) {
814
+ return json({ error: "TTS returned non-Response shape" }, { status: 502 });
815
+ }
816
+ const mime = resp.headers.get("content-type") || "audio/mpeg";
817
+ const bytes = new Uint8Array(await resp.arrayBuffer());
818
+ return new Response(bytes, { headers: { "content-type": mime, "cache-control": "no-store" } });
819
+ } catch (err) {
820
+ return json({ error: `TTS failed: ${err instanceof Error ? err.message : String(err)}` }, { status: 502 });
821
+ }
822
+ }
823
+
824
+ export async function runTts(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
825
+ const userEmail = await getUserEmail(request, env);
826
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
827
+ if (ctxOrErr instanceof Response) return ctxOrErr;
828
+ const aiCtx = ctxOrErr;
829
+
830
+ let mime: string;
831
+ let bytes: Uint8Array;
832
+ let logId: string | null = null;
833
+
834
+ const start = Date.now();
835
+ try {
836
+ // Aura: { text }; MeloTTS: { prompt, lang? }. Send both keys defensively.
837
+ const params: Record<string, unknown> = { text: body.user_input, prompt: body.user_input };
838
+ const resp = await aiRun(aiCtx, model.id, params, true /* returnRawResponse */);
839
+ logId = aiLogId(aiCtx);
840
+ if (!(resp instanceof Response)) {
841
+ return json({ error: "TTS returned non-Response shape", raw: resp }, { status: 502 });
842
+ }
843
+ mime = resp.headers.get("content-type") || "audio/mpeg";
844
+ bytes = new Uint8Array(await resp.arrayBuffer());
845
+ } catch (err) {
846
+ const m = err instanceof Error ? err.message : String(err);
847
+ return json({ error: `TTS failed: ${m}` }, { status: 502 });
848
+ }
849
+ const latency = Date.now() - start;
850
+
851
+ const key = await r2Put(env, "out", mime, bytes, userEmail);
852
+ const outputArtifact: OutputArtifact = { key, mime, type: "audio" };
853
+
854
+ const row = await persistChat(env, {
855
+ userEmail,
856
+ model: model.id,
857
+ model_type: "tts",
858
+ system_prompt: null,
859
+ user_input: body.user_input,
860
+ output: "",
861
+ output_artifact: outputArtifact,
862
+ attachments: [],
863
+ tokens_in: null,
864
+ tokens_out: null,
865
+ latency_ms: latency,
866
+ ai_gateway_log_id: logId,
867
+ });
868
+
869
+ return json({
870
+ id: row.id,
871
+ created_at: row.created_at,
872
+ model: model.id,
873
+ model_type: "tts",
874
+ output: "",
875
+ output_artifact: outputArtifact,
876
+ latency_ms: latency,
877
+ ai_gateway_log_id: logId,
878
+ conversation_id: row.conversation_id,
879
+ turn_index: 0,
880
+ });
881
+ }
882
+
883
+ // ---------- Speech-to-text (Whisper) ----------
884
+ //
885
+ // Synchronous: user attaches an audio file and picks a Whisper model, worker
886
+ // calls Whisper directly and returns the transcript as the row's `output`
887
+ // text. No D1 status='pending' or polling - Whisper completes in seconds.
888
+ // Reuses the existing audio attachment shape from the chat path.
889
+
890
+ // Deepgram ASR on Workers AI returns the native Deepgram results object, not
891
+ // the top-level { text } that Whisper returns. Standard path is
892
+ // results.channels[0].alternatives[0].transcript; we also tolerate a couple of
893
+ // alternate shapes and a normalized top-level text/transcript, defensively.
894
+ export function extractDeepgramTranscript(result: unknown): string {
895
+ const r = result as {
896
+ results?: {
897
+ channels?: Array<{ alternatives?: Array<{ transcript?: string }> }>;
898
+ alternatives?: Array<{ transcript?: string }>;
899
+ };
900
+ text?: string;
901
+ transcript?: string;
902
+ };
903
+ const viaChannels = r?.results?.channels?.[0]?.alternatives?.[0]?.transcript;
904
+ if (typeof viaChannels === "string") return viaChannels.trim();
905
+ const viaAlternatives = r?.results?.alternatives?.[0]?.transcript;
906
+ if (typeof viaAlternatives === "string") return viaAlternatives.trim();
907
+ if (typeof r?.transcript === "string") return r.transcript.trim();
908
+ if (typeof r?.text === "string") return r.text.trim();
909
+ return "";
910
+ }
911
+
912
+ export async function runStt(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
913
+ const userEmail = await getUserEmail(request, env);
914
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
915
+ if (ctxOrErr instanceof Response) return ctxOrErr;
916
+ const aiCtx = ctxOrErr;
917
+ const t0 = Date.now();
918
+
919
+ const audioAtt = (body.attachments ?? []).find((a) => a.type === "audio");
920
+ if (!audioAtt?.data) {
921
+ return json({ error: "Please attach an audio file to transcribe" }, { status: 400 });
922
+ }
923
+ const parsed = parseDataUrl(audioAtt.data);
924
+ if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
925
+
926
+ const viaDeepgram = model.id.startsWith("@cf/deepgram/");
927
+ let transcript: string;
928
+ try {
929
+ if (viaDeepgram) {
930
+ // Deepgram wants { audio: { body, contentType } } where body is a
931
+ // ReadableStream of the audio bytes (a bare base64 string or Uint8Array
932
+ // fails schema validation). AI Gateway does not support ReadableStream
933
+ // inputs ("error 5006/ReadableStreams not supported"), so this is the
934
+ // one call that bypasses the gateway and hits the binding directly;
935
+ // there's no cf-aig-log-id for it (logId stays null below). Output is
936
+ // the native Deepgram results object, parsed by extractDeepgramTranscript.
937
+ const dr = await (env.AI as unknown as { run: (m: string, p: unknown) => Promise<unknown> })
938
+ .run(model.id, { audio: { body: new Response(base64ToBytes(parsed.base64)).body, contentType: parsed.mime } });
939
+ transcript = extractDeepgramTranscript(dr);
940
+ } else {
941
+ const wr = await aiRun(aiCtx, model.id, { audio: parsed.base64 });
942
+ transcript = (wr as { text?: string })?.text?.trim() ?? "";
943
+ }
944
+ } catch (err) {
945
+ const m = err instanceof Error ? err.message : String(err);
946
+ return json({ error: `Transcription failed: ${m}` }, { status: 502 });
947
+ }
948
+
949
+ const latency = Date.now() - t0;
950
+ // Persist the audio's transcript on the attachment record but not the
951
+ // raw audio bytes (same convention as the chat path).
952
+ const persistedAtt: PersistedAttachment[] = [{
953
+ type: "audio",
954
+ mime: parsed.mime,
955
+ filename: audioAtt.filename,
956
+ transcript: transcript || null,
957
+ }];
958
+
959
+ const row = await persistChat(env, {
960
+ userEmail,
961
+ model: model.id,
962
+ model_type: "stt",
963
+ system_prompt: body.system_prompt ?? null,
964
+ user_input: body.user_input || "(audio attachment)",
965
+ output: transcript || "(empty transcript)",
966
+ output_artifact: null,
967
+ attachments: persistedAtt,
968
+ tokens_in: null,
969
+ tokens_out: null,
970
+ latency_ms: latency,
971
+ ai_gateway_log_id: viaDeepgram ? null : aiLogId(aiCtx),
972
+ });
973
+
974
+ return json({
975
+ id: row.id,
976
+ created_at: row.created_at,
977
+ model: model.id,
978
+ model_type: "stt",
979
+ output: transcript,
980
+ output_artifact: null,
981
+ latency_ms: latency,
982
+ conversation_id: row.conversation_id,
983
+ turn_index: 0,
984
+ });
985
+ }
986
+
987
+ // Conversational STT (@cf/deepgram/flux) is handled by the SttSession Durable
988
+ // Object (src/stt-session.ts), which the /api/stt/stream route forwards the WS
989
+ // upgrade to. It bridges to flux and persists the final transcript to /history.
990
+
991
+ // ---------- Music generation (MiniMax via Unified Billing) ----------
992
+ //
993
+ // As of v0.12.0, music gen uses Cloudflare Workflows for durable execution.
994
+ // The runMusic handler creates a LongRunWorkflow instance, persists its ID
995
+ // on the chats row as job_id, and returns immediately. The workflow handles
996
+ // the actual env.AI.run call (which blocks for ~30-90 seconds), downloads
997
+ // the audio, uploads to R2, and finalizes the D1 row.
998
+ //
999
+ // User input maps to fields:
1000
+ // body.user_input -> "prompt" (style/mood description, ~10-300 chars)
1001
+ // body.system_prompt -> "lyrics" (optional, supports [Verse]/[Chorus] tags)
1002
+
1003
+ export async function runMusic(
1004
+ request: Request,
1005
+ env: Env,
1006
+ ctx: ExecutionContext,
1007
+ model: ModelEntry,
1008
+ body: ChatRequest
1009
+ ): Promise<Response> {
1010
+ // ctx unused now that we no longer schedule a waitUntil task; the workflow
1011
+ // owns the long-running work. Kept in signature for router compatibility.
1012
+ void ctx;
1013
+ const userEmail = await getUserEmail(request, env);
1014
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
1015
+ if (ctxOrErr instanceof Response) return ctxOrErr;
1016
+ void ctxOrErr; // credentials validated; workflow loads them from D1 by userEmail
1017
+ const startedAt = new Date().toISOString();
1018
+
1019
+ const row = await persistChat(env, {
1020
+ userEmail,
1021
+ model: model.id,
1022
+ model_type: "music",
1023
+ system_prompt: body.system_prompt ?? null,
1024
+ user_input: body.user_input,
1025
+ output: "",
1026
+ output_artifact: null,
1027
+ attachments: [],
1028
+ tokens_in: null,
1029
+ tokens_out: null,
1030
+ latency_ms: 0,
1031
+ ai_gateway_log_id: null,
1032
+ status: "pending",
1033
+ job_id: null,
1034
+ job_provider: model.provider ?? null,
1035
+ job_error: null,
1036
+ job_started_at: startedAt,
1037
+ });
1038
+
1039
+ // Kick off the workflow. The instance ID is stored on the row so we can
1040
+ // look it up later for status/observability. If create() itself fails
1041
+ // (e.g., quota exceeded), fail the row synchronously so the client sees
1042
+ // an error rather than an indefinite pending state.
1043
+ // v0.62.0: MiniMax music-2.6 returns gateway error 7003 ("User Input
1044
+ // Error") when lyrics is empty or missing, even for instrumental
1045
+ // requests. Default to "[Instrumental]" - the model's own marker
1046
+ // syntax - so a caller that wants an instrumental track can omit the
1047
+ // system_prompt without their job failing seconds after submit. A
1048
+ // non-empty system_prompt (real lyrics) wins.
1049
+ const rawLyrics = (body.system_prompt ?? "").trim();
1050
+ const lyrics = rawLyrics.length > 0 ? body.system_prompt! : "[Instrumental]";
1051
+
1052
+ let instanceId: string;
1053
+ try {
1054
+ const instance = await env.LONGRUN.create({
1055
+ params: {
1056
+ rowId: row.id,
1057
+ userEmail,
1058
+ modelId: model.id,
1059
+ prompt: body.user_input,
1060
+ lyrics,
1061
+ kind: "music",
1062
+ startedAtIso: startedAt,
1063
+ } satisfies LongRunParams,
1064
+ });
1065
+ instanceId = instance.id;
1066
+ } catch (err) {
1067
+ const m = err instanceof Error ? err.message : String(err);
1068
+ await env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
1069
+ .bind(`Workflow create failed: ${m}`.slice(0, 1000), row.id)
1070
+ .run();
1071
+ return json({ error: `Failed to start music generation: ${m}` }, { status: 502 });
1072
+ }
1073
+
1074
+ // Persist the workflow instance ID on the row for traceability.
1075
+ await env.DB.prepare(`UPDATE chats SET job_id = ? WHERE id = ?`)
1076
+ .bind(instanceId, row.id)
1077
+ .run();
1078
+
1079
+ return json({
1080
+ id: row.id,
1081
+ created_at: row.created_at,
1082
+ model: model.id,
1083
+ model_type: "music",
1084
+ output: "",
1085
+ output_artifact: null,
1086
+ status: "pending",
1087
+ job_started_at: startedAt,
1088
+ job_id: instanceId,
1089
+ conversation_id: row.conversation_id,
1090
+ turn_index: 0,
1091
+ });
1092
+ }
1093
+
1094
+ // ---------- Persistence ----------
1095
+
1096
+ export interface PersistArgs {
1097
+ userEmail: string;
1098
+ model: string;
1099
+ model_type: ModelType;
1100
+ system_prompt: string | null;
1101
+ user_input: string;
1102
+ output: string;
1103
+ output_artifact: OutputArtifact | null;
1104
+ attachments: PersistedAttachment[];
1105
+ tokens_in: number | null;
1106
+ tokens_out: number | null;
1107
+ latency_ms: number;
1108
+ ai_gateway_log_id: string | null;
1109
+ status?: "pending" | "done" | "failed";
1110
+ job_id?: string | null;
1111
+ job_provider?: string | null;
1112
+ job_error?: string | null;
1113
+ job_started_at?: string | null;
1114
+ retrieved_context?: RetrievedItem[] | null;
1115
+ conversation_id?: string | null;
1116
+ turn_index?: number | null;
1117
+ project_id?: number | null; // v0.20.2: project this chat turn was sent within
1118
+ }
1119
+
1120
+ export async function persistChat(env: Env, a: PersistArgs): Promise<{ id: number; created_at: string; conversation_id: string }> {
1121
+ // For non-chat model types (image/tts/video/etc), conversation_id is
1122
+ // auto-assigned as a synthetic per-row key so the rows still group in the
1123
+ // sidebar as single-turn entries.
1124
+ const convId = a.conversation_id ?? null;
1125
+ const turnIdx = a.turn_index ?? null;
1126
+
1127
+ const row = await env.DB.prepare(
1128
+ `INSERT INTO chats
1129
+ (user_email, model, model_type, system_prompt, user_input, output,
1130
+ output_artifact, attachments,
1131
+ tokens_in, tokens_out, latency_ms, ai_gateway_log_id,
1132
+ status, job_id, job_provider, job_error, job_started_at,
1133
+ retrieved_context, conversation_id, turn_index, project_id)
1134
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1135
+ RETURNING id, created_at`
1136
+ )
1137
+ .bind(
1138
+ a.userEmail, a.model, a.model_type, a.system_prompt, a.user_input, a.output,
1139
+ a.output_artifact ? JSON.stringify(a.output_artifact) : null,
1140
+ a.attachments.length ? JSON.stringify(a.attachments) : null,
1141
+ a.tokens_in, a.tokens_out, a.latency_ms, a.ai_gateway_log_id,
1142
+ a.status ?? "done",
1143
+ a.job_id ?? null,
1144
+ a.job_provider ?? null,
1145
+ a.job_error ?? null,
1146
+ a.job_started_at ?? null,
1147
+ a.retrieved_context && a.retrieved_context.length ? JSON.stringify(a.retrieved_context) : null,
1148
+ convId,
1149
+ turnIdx,
1150
+ a.project_id ?? null
1151
+ )
1152
+ .first<{ id: number; created_at: string }>();
1153
+
1154
+ if (!row) {
1155
+ return { id: 0, created_at: new Date().toISOString(), conversation_id: "" };
1156
+ }
1157
+
1158
+ // For non-chat rows that didn't get an explicit conversation_id, backfill
1159
+ // a synthetic one so they appear in the conversation list.
1160
+ let finalConvId = convId;
1161
+ if (!finalConvId) {
1162
+ finalConvId = `single-${row.id}`;
1163
+ await env.DB.prepare(
1164
+ `UPDATE chats SET conversation_id = ?, turn_index = 0 WHERE id = ?`
1165
+ )
1166
+ .bind(finalConvId, row.id)
1167
+ .run();
1168
+ }
1169
+
1170
+ return { id: row.id, created_at: row.created_at, conversation_id: finalConvId };
1171
+ }
1172
+
1173
+ // ---------- runChatStream (v0.13.0) ----------
1174
+ //
1175
+ // Streaming counterpart of runChat. Shares the prelude contract (parallel
1176
+ // hoisting of priorTurnsPromise + retrievePromise overlapping the attachment
1177
+ // walk; multi-turn continuation; RAG system-prompt assembly) and diverges
1178
+ // at the model call: each provider's stream adapter (callAnthropicStream
1179
+ // in src/providers/anthropic.ts, etc.) is an async generator that yields
1180
+ // normalized text deltas and usage events.
1181
+ //
1182
+ // Wire format on the response body (text/event-stream):
1183
+ // data: {"type":"delta","text":"..."}
1184
+ // data: {"type":"done","row_id":N,"latency_ms":N,"tokens_in":N|null,
1185
+ // "tokens_out":N|null,"conversation_id":"...","turn_index":N}
1186
+ // data: {"type":"error","message":"..."}
1187
+ //
1188
+ // Anthropic's native SSE event types (message_start, content_block_delta,
1189
+ // content_block_stop, message_delta, message_stop, ping, etc.) are stripped
1190
+ // inside callAnthropicStream and normalized to the envelope above.
1191
+ //
1192
+ // On client disconnect, the next writer.write() throws; we abort the
1193
+ // upstream Anthropic fetch via AbortController and exit without persisting
1194
+ // the partial response. Design decision B (Pass 1): drop partials.
1195
+ //
1196
+ // NOTE: the prelude here intentionally duplicates the prelude in runChat.
1197
+ // Both functions own the same shape but persist + respond differently. A
1198
+ // later pass may extract a shared helper; for Pass 1 the duplication is
1199
+ // bounded and easier to read than a parameterized abstraction.
1200
+
1201
+ export async function runChatStream(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
1202
+ const userEmail = await getUserEmail(request, env);
1203
+ const backendOrErr = await requireInferenceBackend(env, userEmail, {
1204
+ requireCfToken: modelNeedsCfAigToken(model),
1205
+ });
1206
+ if (backendOrErr instanceof Response) return backendOrErr;
1207
+ const backend = backendOrErr;
1208
+ // Streaming over control plane: run non-stream CP chat then emit one SSE chunk
1209
+ // (full SSE client on the proxy is a follow-up).
1210
+ if (backend.kind === "control_plane") {
1211
+ const nonStream = await runChat(request, env, model, body);
1212
+ if (!nonStream.ok) return nonStream;
1213
+ const payload = (await nonStream.json()) as {
1214
+ output?: string;
1215
+ id?: number;
1216
+ conversation_id?: string;
1217
+ turn_index?: number;
1218
+ tokens_in?: number;
1219
+ tokens_out?: number;
1220
+ latency_ms?: number;
1221
+ };
1222
+ const text = payload.output || "";
1223
+ const encoder = new TextEncoder();
1224
+ const stream = new ReadableStream<Uint8Array>({
1225
+ start(controller) {
1226
+ controller.enqueue(
1227
+ encoder.encode(`data: ${JSON.stringify({ type: "delta", text })}\n\n`),
1228
+ );
1229
+ controller.enqueue(
1230
+ encoder.encode(
1231
+ `data: ${JSON.stringify({
1232
+ type: "done",
1233
+ id: payload.id,
1234
+ conversation_id: payload.conversation_id,
1235
+ turn_index: payload.turn_index,
1236
+ tokens_in: payload.tokens_in,
1237
+ tokens_out: payload.tokens_out,
1238
+ latency_ms: payload.latency_ms,
1239
+ output: text,
1240
+ })}\n\n`,
1241
+ ),
1242
+ );
1243
+ controller.close();
1244
+ },
1245
+ });
1246
+ return new Response(stream, {
1247
+ headers: {
1248
+ "content-type": "text/event-stream; charset=utf-8",
1249
+ "cache-control": "no-store",
1250
+ },
1251
+ });
1252
+ }
1253
+ const aiCtx = backend.ctx;
1254
+ const inputs: InputAttachment[] = body.attachments ?? [];
1255
+
1256
+ // v0.20.0: same project resolution as runChat. See resolveProjectForChat
1257
+ // for semantics. Mutating body.system_prompt here means downstream code
1258
+ // (provider call, persistence) sees the effective prompt with no further
1259
+ // awareness of projects.
1260
+ const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
1261
+ body.system_prompt = resolvedSystemPrompt;
1262
+
1263
+ // Hot-path parallelization (mirrors runChat v0.12.1). Kick off SELECT +
1264
+ // RAG retrieve before the attachment walk; await at the existing use sites.
1265
+ const conversationIdIn = body.conversation_id?.trim() || "";
1266
+ const priorTurnsPromise: Promise<{
1267
+ rows: Array<{ user_input: string; output: string; turn_index: number }>;
1268
+ }> = conversationIdIn
1269
+ ? env.DB.prepare(
1270
+ `SELECT user_input, output, turn_index
1271
+ FROM chats
1272
+ WHERE conversation_id = ?
1273
+ AND user_email = ?
1274
+ AND status = 'done'
1275
+ AND model_type = 'chat'
1276
+ ORDER BY turn_index ASC`
1277
+ )
1278
+ .bind(conversationIdIn, userEmail)
1279
+ .all<{ user_input: string; output: string; turn_index: number }>()
1280
+ .then((r) => ({ rows: r.results ?? [] }))
1281
+ : Promise.resolve({ rows: [] });
1282
+
1283
+ const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
1284
+ body.use_docs
1285
+ ? retrieveContext(env, userEmail, body.user_input, RETRIEVE_TOP_K, scopedProjectId)
1286
+ : Promise.resolve({ chunks: [], error: null });
1287
+
1288
+ // v0.17.0: web search runs in parallel with RAG retrieval, same as runChat.
1289
+ const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
1290
+ body.use_web_search
1291
+ ? searchWeb(env, body.user_input)
1292
+ : Promise.resolve({ results: [], error: null });
1293
+
1294
+ // Attachment walk. Reach completion before any bytes flow back; streaming
1295
+ // helps with time-to-last-token, not time-to-first-token on multimodal turns.
1296
+ const extraText: string[] = [];
1297
+ const imageDataUrls: string[] = [];
1298
+ const persistedAtt: PersistedAttachment[] = [];
1299
+
1300
+ for (const att of inputs) {
1301
+ if (att.type === "image") {
1302
+ if (!model.capabilities.includes("vision")) {
1303
+ return json({ error: `Model ${model.id} does not support vision.` }, { status: 400 });
1304
+ }
1305
+ const parsed = att.data ? parseDataUrl(att.data) : null;
1306
+ if (!parsed) return json({ error: "Invalid image data URL" }, { status: 400 });
1307
+ const bytes = base64ToBytes(parsed.base64);
1308
+ const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
1309
+ imageDataUrls.push(att.data!); // guaranteed by the parsed guard above (data may be hydrated from a key)
1310
+ persistedAtt.push({ type: "image", key, mime: parsed.mime, filename: att.filename });
1311
+ } else if (att.type === "audio") {
1312
+ if (!aiCtx) {
1313
+ return json(
1314
+ {
1315
+ error:
1316
+ "Audio attachments need on-worker Whisper, which is unavailable when control-plane mode is on. Clear the control-plane key or remove the audio attachment.",
1317
+ code: "control_plane_no_audio",
1318
+ },
1319
+ { status: 400 },
1320
+ );
1321
+ }
1322
+ const parsed = att.data ? parseDataUrl(att.data) : null;
1323
+ if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
1324
+ try {
1325
+ const wr = await aiRun(aiCtx, WHISPER_MODEL, { audio: parsed.base64 });
1326
+ const text = (wr as { text?: string })?.text?.trim() ?? "";
1327
+ const label = att.filename ? ` from ${att.filename}` : "";
1328
+ extraText.push(text
1329
+ ? `[Transcribed audio${label}]\n${text}`
1330
+ : `[Audio attachment${label} transcribed to empty text]`);
1331
+ persistedAtt.push({ type: "audio", mime: parsed.mime, filename: att.filename, transcript: text || null });
1332
+ } catch (err) {
1333
+ const m = err instanceof Error ? err.message : String(err);
1334
+ return json({ error: `Audio transcription failed: ${m}` }, { status: 502 });
1335
+ }
1336
+ } else if (att.type === "video_frames") {
1337
+ if (!model.capabilities.includes("vision")) {
1338
+ return json({ error: `Model ${model.id} does not support vision.` }, { status: 400 });
1339
+ }
1340
+ const frames = att.frames ?? [];
1341
+ const parsedFrames = frames
1342
+ .map((fdataUrl) => ({ fdataUrl, parsed: parseDataUrl(fdataUrl) }))
1343
+ .filter((p): p is { fdataUrl: string; parsed: { mime: string; base64: string } } => p.parsed !== null);
1344
+ const keys = await Promise.all(
1345
+ parsedFrames.map(({ parsed }) =>
1346
+ r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail)
1347
+ )
1348
+ );
1349
+ for (const { fdataUrl } of parsedFrames) {
1350
+ imageDataUrls.push(fdataUrl);
1351
+ }
1352
+ const dur = att.duration ? ` ${att.duration.toFixed(1)}s` : "";
1353
+ const fn = att.filename ? ` "${att.filename}"` : "";
1354
+ extraText.push(`[Video${fn}${dur}, ${frames.length} evenly-sampled frames attached below]`);
1355
+ persistedAtt.push({ type: "video_frames", keys, frame_count: keys.length, duration: att.duration, filename: att.filename });
1356
+ } else if (att.type === "video_full") {
1357
+ // No streaming model accepts raw video; reject explicitly so the user
1358
+ // attaches extracted frames instead of getting silent truncation.
1359
+ return json({ error: "Raw video attachments are not accepted on the streaming path. Attach extracted frames instead." }, { status: 400 });
1360
+ } else if (att.type === "document") {
1361
+ const r = buildDocumentAttachment(att);
1362
+ if ("error" in r) return json({ error: r.error }, { status: 400 });
1363
+ extraText.push(r.extra);
1364
+ persistedAtt.push(r.persisted);
1365
+ }
1366
+ }
1367
+
1368
+ const userText = [body.user_input, ...extraText].filter(Boolean).join("\n\n");
1369
+ const userContent: unknown = imageDataUrls.length
1370
+ ? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
1371
+ : userText;
1372
+
1373
+ // Consume the parallel-hoisted promises.
1374
+ let conversationId = conversationIdIn;
1375
+ let turnIndex = 0;
1376
+ const priorTurns: Array<{ user_input: string; output: string }> = [];
1377
+
1378
+ if (conversationId) {
1379
+ const { rows } = await priorTurnsPromise;
1380
+ for (const r of rows) {
1381
+ if (r.user_input && r.output) {
1382
+ priorTurns.push({ user_input: r.user_input, output: r.output });
1383
+ }
1384
+ }
1385
+ turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
1386
+ } else {
1387
+ conversationId = crypto.randomUUID();
1388
+ }
1389
+
1390
+ const { chunks: retrievedChunks } = await retrievePromise;
1391
+ const { results: webResults } = await webSearchPromise;
1392
+ const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
1393
+
1394
+ const userSystemPrompt = body.system_prompt?.trim() ?? "";
1395
+ const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
1396
+ const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
1397
+ const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
1398
+ .filter(Boolean)
1399
+ .join("\n\n");
1400
+
1401
+ // Build the message array. For providers that take system as a separate
1402
+ // top-level param (Anthropic), we DON'T include a system role here;
1403
+ // callAnthropicStream pulls effectiveSystemPrompt to a top-level field.
1404
+ // For Workers AI (and any future provider that accepts role:"system" in
1405
+ // messages, like xAI's OpenAI-compatible API), we DO push it.
1406
+ const wantsSystemInMessages = !(model.provider === "anthropic");
1407
+ const messages: Array<unknown> = [];
1408
+ if (effectiveSystemPrompt && wantsSystemInMessages) {
1409
+ messages.push({ role: "system", content: effectiveSystemPrompt });
1410
+ }
1411
+ for (const t of priorTurns) {
1412
+ messages.push({ role: "user", content: t.user_input });
1413
+ messages.push({ role: "assistant", content: t.output });
1414
+ }
1415
+ messages.push({ role: "user", content: userContent });
1416
+
1417
+ // TransformStream pattern: return `readable` as the response body, write
1418
+ // SSE events to `writer`. The worker stays alive while writer is open, so
1419
+ // the background IIFE doesn't need ctx.waitUntil.
1420
+ const { readable, writable } = new TransformStream();
1421
+ const writer = writable.getWriter();
1422
+ const encoder = new TextEncoder();
1423
+
1424
+ // Emit one SSE event. Returns false if the writer is closed (client
1425
+ // disconnected); caller uses this to short-circuit + abort upstream.
1426
+ const emit = async (event: Record<string, unknown>): Promise<boolean> => {
1427
+ try {
1428
+ await writer.write(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
1429
+ return true;
1430
+ } catch {
1431
+ return false;
1432
+ }
1433
+ };
1434
+
1435
+ const upstreamAbort = new AbortController();
1436
+ const start = Date.now();
1437
+
1438
+ // Background IIFE drives the stream. Does NOT await; this function returns
1439
+ // the Response immediately while the IIFE writes events to the body.
1440
+ (async () => {
1441
+ let accumulated = "";
1442
+ let usageIn: number | null = null;
1443
+ let usageOut: number | null = null;
1444
+
1445
+ try {
1446
+ // Dispatch per provider. All generators yield the same ProviderStreamEvent
1447
+ // shape so the consumer loop is provider-agnostic.
1448
+ let streamGenerator: AsyncGenerator<ProviderStreamEvent>;
1449
+ if (model.provider === "anthropic") {
1450
+ streamGenerator = callAnthropicStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
1451
+ } else if (model.provider === "xai") {
1452
+ streamGenerator = callXaiStream(aiCtx, model, messages, upstreamAbort.signal);
1453
+ } else if (model.provider === "openai" || model.provider === "moonshotai") {
1454
+ // OpenAI + Moonshot K3 (v0.171.0): both are Chat Completions over
1455
+ // env.AI.run with OpenAI-compatible SSE.
1456
+ streamGenerator = callOpenAIStream(aiCtx, model, messages, upstreamAbort.signal);
1457
+ } else if (model.provider === "google") {
1458
+ streamGenerator = callGeminiStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
1459
+ } else {
1460
+ streamGenerator = callWorkersAIStream(aiCtx, model, messages, upstreamAbort.signal);
1461
+ }
1462
+
1463
+ for await (const ev of streamGenerator) {
1464
+ if (ev.type === "text") {
1465
+ accumulated += ev.text;
1466
+ const ok = await emit({ type: "delta", text: ev.text });
1467
+ if (!ok) {
1468
+ // Client gone. Abort upstream so we stop paying for tokens
1469
+ // and exit without persisting (Pass 1: drop partials).
1470
+ upstreamAbort.abort();
1471
+ return;
1472
+ }
1473
+ } else if (ev.type === "usage") {
1474
+ if (ev.in_ !== null) usageIn = ev.in_;
1475
+ if (ev.out_ !== null) usageOut = ev.out_;
1476
+ }
1477
+ }
1478
+
1479
+ const latency = Date.now() - start;
1480
+
1481
+ // Persist as a single row. retrieved_context is saved on the row so
1482
+ // the History/Conversation views render citations the same way runChat
1483
+ // does. v0.17.0: web-search results are stored in the same column with
1484
+ // a source_type discriminator. ai_gateway_log_id is null: streaming
1485
+ // responses from AI Gateway don't surface cf-aig-log-id on the proxied
1486
+ // SSE response.
1487
+ const row = await persistChat(env, {
1488
+ userEmail,
1489
+ model: model.id,
1490
+ model_type: "chat",
1491
+ system_prompt: body.system_prompt ?? null,
1492
+ user_input: body.user_input,
1493
+ output: accumulated,
1494
+ output_artifact: null,
1495
+ attachments: persistedAtt,
1496
+ tokens_in: usageIn,
1497
+ tokens_out: usageOut,
1498
+ latency_ms: latency,
1499
+ ai_gateway_log_id: null,
1500
+ retrieved_context: allRetrieved.length ? allRetrieved : null,
1501
+ conversation_id: conversationId,
1502
+ turn_index: turnIndex,
1503
+ project_id: scopedProjectId ?? null,
1504
+ });
1505
+
1506
+ await emit({
1507
+ type: "done",
1508
+ row_id: row.id,
1509
+ latency_ms: latency,
1510
+ tokens_in: usageIn,
1511
+ tokens_out: usageOut,
1512
+ conversation_id: conversationId,
1513
+ turn_index: turnIndex,
1514
+ });
1515
+ } catch (err) {
1516
+ // Self-triggered AbortError (we aborted because client disconnected)
1517
+ // is expected; suppress it. Anything else is surfaced to the client
1518
+ // as a terminal error event.
1519
+ if (err instanceof Error && err.name === "AbortError") return;
1520
+ const m = err instanceof Error ? err.message : String(err);
1521
+ await emit({ type: "error", message: m });
1522
+ } finally {
1523
+ try { await writer.close(); } catch { /* writer may already be closed */ }
1524
+ }
1525
+ })();
1526
+
1527
+ return new Response(readable, {
1528
+ headers: {
1529
+ "content-type": "text/event-stream; charset=utf-8",
1530
+ "cache-control": "no-cache, no-transform",
1531
+ // Disable any in-path buffering. Cloudflare doesn't buffer streaming
1532
+ // responses but downstream proxies (Nginx etc.) might; this is the
1533
+ // standard hint to flush per-event.
1534
+ "x-accel-buffering": "no",
1535
+ },
1536
+ });
1537
+ }
1538
+
1539
+ // ---------- Video generation (Unified Billing via env.AI.run) ----------
1540
+ //
1541
+ // As of Cloudflare Agents Week 2026 (April 2026), the AI Gateway and Workers
1542
+ // AI are unified. Third-party video models are callable via env.AI.run with
1543
+ // model strings like "google/veo-3.1-fast" or "xai/grok-imagine-video".
1544
+ // Cloudflare bills your account directly under Unified Billing. See:
1545
+ // https://developers.cloudflare.com/ai-gateway/features/unified-billing/
1546
+ // https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/
1547
+ //
1548
+ // Video gen takes 30s-3min. env.AI.run for these models blocks until
1549
+ // completion, which exceeds the ~30s waitUntil budget after an HTTP response.
1550
+ // Cloudflare Workflows (v0.12.0+): the runVideo handler creates a
1551
+ // LongRunWorkflow instance, persists its ID on the row, and returns
1552
+ // immediately. The workflow class holds the long blocking env.AI.run call
1553
+ // alive across step boundaries, then downloads and finalizes D1.
1554
+ //
1555
+ // The frontend polls /api/job/:id for status (reads D1 only; the workflow
1556
+ // updates the row when done).
1557
+
1558
+ export async function runVideo(
1559
+ request: Request,
1560
+ env: Env,
1561
+ ctx: ExecutionContext,
1562
+ model: ModelEntry,
1563
+ body: ChatRequest
1564
+ ): Promise<Response> {
1565
+ void ctx;
1566
+ const userEmail = await getUserEmail(request, env);
1567
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
1568
+ if (ctxOrErr instanceof Response) return ctxOrErr;
1569
+ void ctxOrErr; // credentials validated; workflow loads them from D1 by userEmail
1570
+ const startedAt = new Date().toISOString();
1571
+
1572
+ // Image-to-video models (e.g. alibaba/hh1-i2v, flagged "image-input") need a
1573
+ // source image (v0.21.6). Three sources, resolved into one of two workflow
1574
+ // params: an uploaded attachment or an R2 key (image_key, e.g. a prior
1575
+ // nano-banana output for chaining) -> `imageKey`, resolved to a data: URI in
1576
+ // the workflow; a fetchable external URL (image_url) -> `imageUrl`, passed
1577
+ // through. Uploads are stored to R2 here so the (potentially multi-MB) image
1578
+ // doesn't ride the Workflow event payload (~1 MiB cap); the small key does.
1579
+ const needsImage = model.capabilities.includes("image-input");
1580
+ let srcImageKey: string | undefined;
1581
+ let srcImageUrl: string | undefined;
1582
+ if (needsImage) {
1583
+ const imgAtt = (body.attachments ?? []).find((a) => a.type === "image" && a.data);
1584
+ if (imgAtt && imgAtt.type === "image" && imgAtt.data) {
1585
+ const parsed = parseDataUrl(imgAtt.data);
1586
+ if (!parsed) {
1587
+ return json({ error: "Attached image is not a base64 data URL." }, { status: 400 });
1588
+ }
1589
+ srcImageKey = await r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail);
1590
+ } else if (body.image_key && body.image_key.trim()) {
1591
+ srcImageKey = body.image_key.trim();
1592
+ } else if (body.image_url && body.image_url.trim()) {
1593
+ srcImageUrl = body.image_url.trim();
1594
+ } else {
1595
+ return json({ error: "This image-to-video model requires a source image: attach one, or pass 'image_key' (an R2 key) or 'image_url' (a fetchable URL)." }, { status: 400 });
1596
+ }
1597
+ }
1598
+
1599
+ const row = await persistChat(env, {
1600
+ userEmail,
1601
+ model: model.id,
1602
+ model_type: "video",
1603
+ system_prompt: body.system_prompt ?? null,
1604
+ user_input: body.user_input,
1605
+ output: "",
1606
+ output_artifact: null,
1607
+ attachments: [],
1608
+ tokens_in: null,
1609
+ tokens_out: null,
1610
+ latency_ms: 0,
1611
+ ai_gateway_log_id: null,
1612
+ status: "pending",
1613
+ job_id: null,
1614
+ job_provider: model.provider ?? null,
1615
+ job_error: null,
1616
+ job_started_at: startedAt,
1617
+ });
1618
+
1619
+ let instanceId: string;
1620
+ try {
1621
+ const instance = await env.LONGRUN.create({
1622
+ params: {
1623
+ rowId: row.id,
1624
+ userEmail,
1625
+ modelId: model.id,
1626
+ prompt: body.user_input,
1627
+ imageUrl: srcImageUrl,
1628
+ imageKey: srcImageKey,
1629
+ kind: "video",
1630
+ startedAtIso: startedAt,
1631
+ } satisfies LongRunParams,
1632
+ });
1633
+ instanceId = instance.id;
1634
+ } catch (err) {
1635
+ const m = err instanceof Error ? err.message : String(err);
1636
+ await env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
1637
+ .bind(`Workflow create failed: ${m}`.slice(0, 1000), row.id)
1638
+ .run();
1639
+ return json({ error: `Failed to start video generation: ${m}` }, { status: 502 });
1640
+ }
1641
+
1642
+ // Persist the workflow instance ID on the row for traceability.
1643
+ await env.DB.prepare(`UPDATE chats SET job_id = ? WHERE id = ?`)
1644
+ .bind(instanceId, row.id)
1645
+ .run();
1646
+
1647
+ return json({
1648
+ id: row.id,
1649
+ created_at: row.created_at,
1650
+ model: model.id,
1651
+ model_type: "video",
1652
+ output: "",
1653
+ output_artifact: null,
1654
+ status: "pending",
1655
+ job_started_at: startedAt,
1656
+ job_id: instanceId,
1657
+ conversation_id: row.conversation_id,
1658
+ turn_index: 0,
1659
+ });
1660
+ }
1661
+
1662
+ // ---------- Job polling endpoint ----------
1663
+ //
1664
+ // Reflects the current D1 row state. Long-running video/music jobs are owned
1665
+ // by LongRunWorkflow instances, which update the row when they finish.
1666
+
1667
+ export async function handleJobPoll(request: Request, env: Env, id: number): Promise<Response> {
1668
+ const userEmail = await getUserEmail(request, env);
1669
+
1670
+ const row = await env.DB.prepare(
1671
+ `SELECT id, status, job_error, job_started_at, output_artifact, latency_ms,
1672
+ job_id, job_provider, model_type
1673
+ FROM chats
1674
+ WHERE id = ? AND user_email = ?`
1675
+ )
1676
+ .bind(id, userEmail)
1677
+ .first<{
1678
+ id: number;
1679
+ status: string;
1680
+ job_error: string | null;
1681
+ job_started_at: string | null;
1682
+ output_artifact: string | null;
1683
+ latency_ms: number | null;
1684
+ job_id: string | null;
1685
+ job_provider: string | null;
1686
+ model_type: string;
1687
+ }>();
1688
+
1689
+ if (!row) return json({ error: "Not found" }, { status: 404 });
1690
+
1691
+ // Terminal states return immediately.
1692
+ if (row.status === "done") {
1693
+ return json({
1694
+ id: row.id,
1695
+ status: "done",
1696
+ output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
1697
+ latency_ms: row.latency_ms,
1698
+ });
1699
+ }
1700
+ if (row.status === "failed") {
1701
+ return json({ id: row.id, status: "failed", job_error: row.job_error });
1702
+ }
1703
+
1704
+ // Pending (Unified Billing video/music via LongRunWorkflow). The workflow
1705
+ // updates D1 when its work completes; this endpoint just reflects current
1706
+ // row state.
1707
+ return json({ id: row.id, status: "pending" });
1708
+ }
1709
+