@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.
- package/README.md +5 -3
- package/index.js +4 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +6 -2
- package/template/README.md +45 -33
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/package.json +6 -6
- package/template/public/app.js +44 -16
- package/template/public/index.html +47 -4
- package/template/src/auth-kdf.ts +7 -4
- package/template/src/auth.ts +11 -2
- package/template/src/control-plane.ts +254 -0
- package/template/src/env.ts +15 -0
- package/template/src/gateway-credentials.ts +23 -4
- package/template/src/health-schema.ts +4 -0
- package/template/src/index.ts +65 -3982
- package/template/src/longrun-params.ts +4 -2
- package/template/src/models.ts +65 -19
- package/template/src/output-extract.ts +58 -8
- package/template/src/parsers/openai-sse.ts +43 -14
- package/template/src/providers/anthropic.ts +105 -0
- package/template/src/providers/openai-image.ts +66 -0
- package/template/src/providers/openai.ts +79 -13
- package/template/src/providers/xai.ts +91 -0
- package/template/src/proxied-image-params.ts +29 -16
- package/template/src/routes/artifacts.ts +51 -0
- package/template/src/routes/chat.ts +1709 -0
- package/template/src/routes/conversations.ts +212 -0
- package/template/src/routes/documents.ts +262 -0
- package/template/src/routes/health.ts +105 -0
- package/template/src/routes/history.ts +92 -0
- package/template/src/routes/prefs.ts +95 -0
- package/template/src/routes/projects.ts +574 -0
- package/template/src/routes/rag.ts +657 -0
- package/template/src/routes/shared.ts +226 -0
- package/template/src/routes/workflow.ts +304 -0
- package/template/src/user-prefs.ts +10 -0
- package/template/src/zip.ts +7 -0
- package/template/tests/anthropic-binding.test.ts +181 -0
- package/template/tests/control-plane.test.ts +112 -0
- package/template/tests/gateway-credentials.test.ts +37 -0
- package/template/tests/longrun-params.test.ts +19 -0
- package/template/tests/openai-image.test.ts +47 -0
- package/template/tests/openai-responses.test.ts +78 -0
- package/template/tests/openai-sse.test.ts +28 -0
- package/template/tests/output-extract.test.ts +75 -1
- package/template/tests/proxied-image-params.test.ts +16 -7
- package/template/tests/sprint1-catalog.test.ts +27 -0
- package/template/tests/sprint2-catalog.test.ts +51 -0
- package/template/tests/sprint3-catalog.test.ts +29 -0
- package/template/tests/xai-binding.test.ts +127 -0
- package/template/tests-integration/worker.test.ts +9 -2
- package/template/wrangler.example.toml +19 -7
package/template/src/index.ts
CHANGED
|
@@ -1,29 +1,19 @@
|
|
|
1
|
-
// prism worker (play.skyphusion.org).
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
1
|
+
// prism worker (play.skyphusion.org). This file is the router + orchestrator:
|
|
2
|
+
// the fetch handler below IS the route table (matched top-to-bottom; anything
|
|
3
|
+
// unmatched falls through to the ASSETS static frontend). Per-concern handlers
|
|
4
|
+
// live in src/routes/* (chat, history, conversations, documents, projects,
|
|
5
|
+
// artifacts, prefs, health, workflow) over the shared primitives in
|
|
6
|
+
// src/routes/shared.ts and the RAG engine in src/routes/rag.ts. See CLAUDE.md
|
|
7
|
+
// "Routes reference" for the full table.
|
|
8
|
+
//
|
|
9
|
+
// Auth is resolved in src/auth.ts: public mode gates every /api/* route (except
|
|
10
|
+
// the GET /api/models boot probe and the /api/auth/* endpoints) behind a
|
|
11
|
+
// session; access mode trusts the upstream Cloudflare Access identity. Local
|
|
12
|
+
// dev has neither in front; identity falls back per src/auth.ts.
|
|
7
13
|
|
|
8
|
-
import { getDocumentProxy } from "unpdf";
|
|
9
|
-
import * as XLSX from "xlsx";
|
|
10
|
-
import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers";
|
|
11
|
-
import type { WorkflowEvent } from "cloudflare:workers";
|
|
12
|
-
export { SttSession } from "./stt-session";
|
|
13
|
-
import type { ProviderStreamEvent } from "./parsers/types";
|
|
14
|
-
import type { ModelType, Provider, ModelEntry } from "./models";
|
|
15
14
|
import { MODELS } from "./models";
|
|
16
15
|
import type { Env } from "./env";
|
|
17
|
-
import {
|
|
18
|
-
import { aiRun, aiLogId, type AiContext } from "./ai-binding";
|
|
19
|
-
import {
|
|
20
|
-
loadGatewayCredentials,
|
|
21
|
-
loadGatewayStatus,
|
|
22
|
-
GATEWAY_NOT_CONFIGURED_MSG,
|
|
23
|
-
CF_AIG_TOKEN_REQUIRED_MSG,
|
|
24
|
-
maskSecret,
|
|
25
|
-
} from "./gateway-credentials";
|
|
26
|
-
import { loadUserPrefs, saveUserPrefs } from "./user-prefs";
|
|
16
|
+
import { loadGatewayStatus } from "./gateway-credentials";
|
|
27
17
|
import {
|
|
28
18
|
resolveIdentity,
|
|
29
19
|
authMode,
|
|
@@ -32,293 +22,49 @@ import {
|
|
|
32
22
|
handleLogout,
|
|
33
23
|
handleAccountDelete,
|
|
34
24
|
} from "./auth";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
import {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
} from "./
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const WHISPER_MODEL = "@cf/openai/whisper-large-v3-turbo";
|
|
79
|
-
|
|
80
|
-
// v0.24.0: cap on inline text-file (document) attachments folded into a chat
|
|
81
|
-
// prompt. Large files past this are truncated with a marker so a single
|
|
82
|
-
// attachment can't blow the model's context window.
|
|
83
|
-
const MAX_DOC_ATTACHMENT_CHARS = 200_000;
|
|
84
|
-
|
|
85
|
-
// v0.24.0: shared handling for an inline document (text-file) attachment on a
|
|
86
|
-
// chat turn. The contents are folded into the prompt as a fenced block, the
|
|
87
|
-
// same mechanism as audio transcription. Binary input is rejected via the
|
|
88
|
-
// same looksBinary heuristic the RAG uploader uses. Returns either an error
|
|
89
|
-
// string for the 400 path or the prompt block + persisted metadata record.
|
|
90
|
-
function buildDocumentAttachment(att: { text?: string; mime?: string; filename?: string }):
|
|
91
|
-
| { error: string }
|
|
92
|
-
| { extra: string; persisted: PersistedDocumentAttachment } {
|
|
93
|
-
const raw = att.text ?? "";
|
|
94
|
-
if (looksBinary(raw)) {
|
|
95
|
-
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.).` };
|
|
96
|
-
}
|
|
97
|
-
const truncated = raw.length > MAX_DOC_ATTACHMENT_CHARS;
|
|
98
|
-
const text = truncated ? raw.slice(0, MAX_DOC_ATTACHMENT_CHARS) : raw;
|
|
99
|
-
const fn = att.filename ? ` ${att.filename}` : "";
|
|
100
|
-
const extra = `[Attached file${fn}]\n\`\`\`\n${text}\n\`\`\`${truncated ? "\n[file truncated to fit context]" : ""}`;
|
|
101
|
-
return { extra, persisted: { type: "document", mime: att.mime, filename: att.filename, chars: text.length } };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// ---------- Types ----------
|
|
105
|
-
|
|
106
|
-
interface ChatRequest {
|
|
107
|
-
model: string;
|
|
108
|
-
system_prompt?: string;
|
|
109
|
-
user_input: string;
|
|
110
|
-
attachments?: InputAttachment[];
|
|
111
|
-
image_url?: string; // v0.21.5: source image for image-to-video models (hh1-i2v); a fetchable URL
|
|
112
|
-
image_key?: string; // v0.21.6: source image as an R2 key (e.g. a prior nano-banana output) for image-to-video chaining
|
|
113
|
-
use_docs?: boolean; // Pass 2: when true, retrieve top-K chunks from Vectorize and inject as context
|
|
114
|
-
use_web_search?: boolean; // v0.17.0: when true, query SearXNG + Wikipedia and inject snippets as context
|
|
115
|
-
conversation_id?: string; // Multi-turn: when present, continue an existing conversation
|
|
116
|
-
project_id?: number; // v0.20.0: when present, scope RAG retrieval to the project's docs
|
|
117
|
-
// and apply the project's system_prompt as default if system_prompt is empty
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
interface RetrievedChunk {
|
|
121
|
-
// v0.17.0: discriminator. Omitted on existing rows (pre-v0.17.0) and on new
|
|
122
|
-
// RAG-only rows; readers treat "missing" as "rag" for back-compat.
|
|
123
|
-
source_type?: "rag";
|
|
124
|
-
document_id: number;
|
|
125
|
-
filename: string;
|
|
126
|
-
chunk_index: number;
|
|
127
|
-
text: string;
|
|
128
|
-
score: number;
|
|
129
|
-
page?: number | null; // PDFs only
|
|
130
|
-
sheet?: string | null; // XLSX/XLS only
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// v0.17.0: web-search result, stored alongside RAG chunks in the same
|
|
134
|
-
// retrieved_context column. The frontend renders branches on source_type.
|
|
135
|
-
interface RetrievedWebResult {
|
|
136
|
-
source_type: "web";
|
|
137
|
-
source: "searxng" | "wikipedia";
|
|
138
|
-
url: string;
|
|
139
|
-
title: string;
|
|
140
|
-
snippet: string; // already HTML-stripped
|
|
141
|
-
score?: number; // kept for back-compat with pre-v0.166.0 rows (Tavily scores); unset now
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
type RetrievedItem = RetrievedChunk | RetrievedWebResult;
|
|
145
|
-
|
|
146
|
-
interface PersistedImageAttachment {
|
|
147
|
-
type: "image";
|
|
148
|
-
key: string;
|
|
149
|
-
mime?: string;
|
|
150
|
-
filename?: string;
|
|
151
|
-
}
|
|
152
|
-
interface PersistedAudioAttachment {
|
|
153
|
-
type: "audio";
|
|
154
|
-
mime?: string;
|
|
155
|
-
filename?: string;
|
|
156
|
-
transcript: string | null;
|
|
157
|
-
}
|
|
158
|
-
interface PersistedVideoFramesAttachment {
|
|
159
|
-
type: "video_frames";
|
|
160
|
-
keys: string[];
|
|
161
|
-
frame_count: number;
|
|
162
|
-
duration?: number;
|
|
163
|
-
filename?: string;
|
|
164
|
-
}
|
|
165
|
-
interface PersistedVideoFullAttachment {
|
|
166
|
-
type: "video_full";
|
|
167
|
-
key: string;
|
|
168
|
-
mime?: string;
|
|
169
|
-
filename?: string;
|
|
170
|
-
}
|
|
171
|
-
// v0.24.0: inline text-file attachment. The contents are folded into the
|
|
172
|
-
// prompt (not stored in R2); we persist only metadata so history can show
|
|
173
|
-
// that a file was attached without bloating D1 with the full text.
|
|
174
|
-
interface PersistedDocumentAttachment {
|
|
175
|
-
type: "document";
|
|
176
|
-
mime?: string;
|
|
177
|
-
filename?: string;
|
|
178
|
-
chars: number;
|
|
179
|
-
}
|
|
180
|
-
type PersistedAttachment =
|
|
181
|
-
| PersistedImageAttachment
|
|
182
|
-
| PersistedAudioAttachment
|
|
183
|
-
| PersistedVideoFramesAttachment
|
|
184
|
-
| PersistedVideoFullAttachment
|
|
185
|
-
| PersistedDocumentAttachment;
|
|
186
|
-
|
|
187
|
-
interface OutputArtifact {
|
|
188
|
-
key: string;
|
|
189
|
-
mime: string;
|
|
190
|
-
type: "image" | "audio" | "video";
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
// ---------- Helpers ----------
|
|
194
|
-
|
|
195
|
-
function json(body: unknown, init: ResponseInit = {}): Response {
|
|
196
|
-
const headers = new Headers(init.headers);
|
|
197
|
-
headers.set("content-type", "application/json; charset=utf-8");
|
|
198
|
-
return new Response(JSON.stringify(body), { ...init, headers });
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// Identity read site #1 (HTTP). Delegates to resolveIdentity so access-mode and
|
|
202
|
-
// public-mode derivation stay in one place. In access mode this is never null.
|
|
203
|
-
// In public mode the router gate rejects unauthenticated /api/* with 401 before
|
|
204
|
-
// any handler runs, so a null here is an unreachable, fail-closed error rather
|
|
205
|
-
// than a silent anonymous cross-attribution.
|
|
206
|
-
async function getUserEmail(request: Request, env: Env): Promise<string> {
|
|
207
|
-
const id = await resolveIdentity(request, env);
|
|
208
|
-
if (id === null) throw new Error("unauthenticated request reached an owned handler");
|
|
209
|
-
return id;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function modelNeedsCfAigToken(model: ModelEntry): boolean {
|
|
213
|
-
return !!model.provider && model.provider !== "workers-ai";
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async function requireAiContext(
|
|
217
|
-
env: Env,
|
|
218
|
-
userEmail: string,
|
|
219
|
-
opts?: { requireCfToken?: boolean },
|
|
220
|
-
): Promise<AiContext | Response> {
|
|
221
|
-
const gateway = await loadGatewayCredentials(env, userEmail);
|
|
222
|
-
if (!gateway?.gatewayId) {
|
|
223
|
-
return json({ error: GATEWAY_NOT_CONFIGURED_MSG, code: "gateway_not_configured" }, { status: 412 });
|
|
224
|
-
}
|
|
225
|
-
if (opts?.requireCfToken && !gateway.cfAigToken) {
|
|
226
|
-
return json({ error: CF_AIG_TOKEN_REQUIRED_MSG, code: "cf_aig_token_required" }, { status: 412 });
|
|
227
|
-
}
|
|
228
|
-
return { env, gateway };
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
async function handlePrefsGet(request: Request, env: Env): Promise<Response> {
|
|
232
|
-
const userEmail = await getUserEmail(request, env);
|
|
233
|
-
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
234
|
-
const status = await loadGatewayStatus(env, userEmail);
|
|
235
|
-
return json({
|
|
236
|
-
gateway_id: status.gateway_id,
|
|
237
|
-
cf_aig_token_set: status.cf_aig_token_set,
|
|
238
|
-
cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
|
|
239
|
-
configured: status.configured,
|
|
240
|
-
source: status.source,
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
|
|
245
|
-
const userEmail = await getUserEmail(request, env);
|
|
246
|
-
let body: { gateway_id?: string; cf_aig_token?: string; clear_cf_aig_token?: boolean };
|
|
247
|
-
try {
|
|
248
|
-
body = await request.json();
|
|
249
|
-
} catch {
|
|
250
|
-
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
const patch: { gateway_id?: string; cf_aig_token?: string } = {};
|
|
254
|
-
if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
|
|
255
|
-
if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
|
|
256
|
-
if (body.clear_cf_aig_token) patch.cf_aig_token = "";
|
|
257
|
-
|
|
258
|
-
if (Object.keys(patch).length === 0) {
|
|
259
|
-
return json({ error: "Provide gateway_id and/or cf_aig_token to update" }, { status: 400 });
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
const merged = await saveUserPrefs(env.DB, userEmail, patch);
|
|
263
|
-
const status = await loadGatewayStatus(env, userEmail);
|
|
264
|
-
return json({
|
|
265
|
-
gateway_id: status.gateway_id,
|
|
266
|
-
cf_aig_token_set: status.cf_aig_token_set,
|
|
267
|
-
cf_aig_token_preview: maskSecret(merged.cf_aig_token),
|
|
268
|
-
configured: status.configured,
|
|
269
|
-
source: status.source,
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
async function r2Put(env: Env, prefix: "in" | "out", mime: string, bytes: Uint8Array, userEmail: string): Promise<string> {
|
|
275
|
-
const key = `${prefix}/${crypto.randomUUID()}.${extFromMime(mime)}`;
|
|
276
|
-
await env.R2.put(key, bytes, {
|
|
277
|
-
httpMetadata: { contentType: mime },
|
|
278
|
-
customMetadata: { user_email: userEmail },
|
|
279
|
-
});
|
|
280
|
-
return key;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
// Read an R2 object and return it as a base64 `data:` URI. Used to inline a
|
|
285
|
-
// source image for image-to-video (hh1-i2v): the upstream accepts data URIs
|
|
286
|
-
// (verified, it re-uploads them to its own OSS), so we don't need a presigned
|
|
287
|
-
// GET URL. Ownership is enforced the same way /api/artifact does: the object's
|
|
288
|
-
// customMetadata.user_email must match, so a client can't reference another
|
|
289
|
-
// user's R2 key via image_key. Throws on miss or ownership mismatch.
|
|
290
|
-
async function r2KeyToDataUri(env: Env, key: string, userEmail: string): Promise<string> {
|
|
291
|
-
const obj = await env.R2.get(key);
|
|
292
|
-
if (!obj) throw new Error(`source image not found: ${key}`);
|
|
293
|
-
if (obj.customMetadata?.user_email !== userEmail) {
|
|
294
|
-
throw new Error(`source image not owned by requester: ${key}`);
|
|
295
|
-
}
|
|
296
|
-
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
297
|
-
const mime = obj.httpMetadata?.contentType || "image/png";
|
|
298
|
-
return `data:${mime};base64,${bytesToBase64(bytes)}`;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Attachment-by-reference (v0.21.7): an image or full-video attachment may
|
|
302
|
-
// carry an R2 `key` (an artifact already produced in this conversation)
|
|
303
|
-
// instead of inline `data`. Hydrate `data` from R2 once, here at the request
|
|
304
|
-
// boundary, so every downstream consumer (vision chat, FLUX.2 reference
|
|
305
|
-
// images, image-to-video) works unchanged. Ownership is enforced by
|
|
306
|
-
// r2KeyToDataUri. This is what lets a model use what a previous model in the
|
|
307
|
-
// same conversation generated, with no download/re-upload.
|
|
308
|
-
async function resolveAttachmentKeys(env: Env, attachments: InputAttachment[], userEmail: string): Promise<InputAttachment[]> {
|
|
309
|
-
return Promise.all(attachments.map(async (att) => {
|
|
310
|
-
if ((att.type === "image" || att.type === "video_full") && att.key && !att.data) {
|
|
311
|
-
return { ...att, data: await r2KeyToDataUri(env, att.key, userEmail) };
|
|
312
|
-
}
|
|
313
|
-
return att;
|
|
314
|
-
}));
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
async function r2DeleteSafe(env: Env, key: string): Promise<void> {
|
|
318
|
-
try { await env.R2.delete(key); } catch { /* ignore */ }
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
// ---------- Router ----------
|
|
25
|
+
import { json } from "./routes/shared";
|
|
26
|
+
import { handleHealthDeep } from "./routes/health";
|
|
27
|
+
import { handlePrefsGet, handlePrefsPatch } from "./routes/prefs";
|
|
28
|
+
import {
|
|
29
|
+
handleChat,
|
|
30
|
+
handleChatStream,
|
|
31
|
+
handleTtsSpeak,
|
|
32
|
+
handleJobPoll,
|
|
33
|
+
} from "./routes/chat";
|
|
34
|
+
import {
|
|
35
|
+
handleHistoryList,
|
|
36
|
+
handleHistoryGet,
|
|
37
|
+
handleHistoryDelete,
|
|
38
|
+
} from "./routes/history";
|
|
39
|
+
import {
|
|
40
|
+
handleConversationList,
|
|
41
|
+
handleConversationGet,
|
|
42
|
+
handleConversationDelete,
|
|
43
|
+
handleConversationMoveToProject,
|
|
44
|
+
} from "./routes/conversations";
|
|
45
|
+
import {
|
|
46
|
+
handleDocumentList,
|
|
47
|
+
handleDocumentGet,
|
|
48
|
+
handleDocumentUpload,
|
|
49
|
+
handleDocumentDelete,
|
|
50
|
+
handleImportStatus,
|
|
51
|
+
} from "./routes/documents";
|
|
52
|
+
import {
|
|
53
|
+
handleProjectList,
|
|
54
|
+
handleProjectGet,
|
|
55
|
+
handleProjectCreate,
|
|
56
|
+
handleProjectUpdate,
|
|
57
|
+
handleProjectDelete,
|
|
58
|
+
handleProjectDocAdd,
|
|
59
|
+
handleProjectDocRemove,
|
|
60
|
+
handleDiscordImport,
|
|
61
|
+
} from "./routes/projects";
|
|
62
|
+
import { handleArtifact } from "./routes/artifacts";
|
|
63
|
+
|
|
64
|
+
// Durable Object + Workflow classes must stay exported from the main entry so
|
|
65
|
+
// wrangler resolves each class_name against this module.
|
|
66
|
+
export { SttSession } from "./stt-session";
|
|
67
|
+
export { LongRunWorkflow } from "./routes/workflow";
|
|
322
68
|
|
|
323
69
|
export default {
|
|
324
70
|
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
@@ -375,8 +121,7 @@ export default {
|
|
|
375
121
|
if (url.pathname === "/api/models" && request.method === "GET") {
|
|
376
122
|
// Boot probe: reachable without a session. Carries mode + authenticated so
|
|
377
123
|
// the SPA gates itself in one call (no separate /api/session endpoint).
|
|
378
|
-
//
|
|
379
|
-
// always true and the signup screen never shows on a private deploy.
|
|
124
|
+
// Access mode fails closed unless ACCESS_ALLOW_ANONYMOUS=1 (local dev only).
|
|
380
125
|
const mode = authMode(env);
|
|
381
126
|
const id = await resolveIdentity(request, env);
|
|
382
127
|
const authenticated = id !== null;
|
|
@@ -393,7 +138,14 @@ export default {
|
|
|
393
138
|
username = row?.username ?? null;
|
|
394
139
|
}
|
|
395
140
|
} else {
|
|
396
|
-
gateway = {
|
|
141
|
+
gateway = {
|
|
142
|
+
configured: false,
|
|
143
|
+
source: "none" as const,
|
|
144
|
+
gateway_id: null,
|
|
145
|
+
cf_aig_token_set: false,
|
|
146
|
+
control_plane_configured: false,
|
|
147
|
+
control_plane_key_set: false,
|
|
148
|
+
};
|
|
397
149
|
}
|
|
398
150
|
return json({ models: MODELS, mode, authenticated, user: id, username, gateway });
|
|
399
151
|
}
|
|
@@ -509,3672 +261,3 @@ export default {
|
|
|
509
261
|
},
|
|
510
262
|
|
|
511
263
|
};
|
|
512
|
-
|
|
513
|
-
// ---------- /api/chat ----------
|
|
514
|
-
|
|
515
|
-
async function handleChat(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
516
|
-
let body: ChatRequest;
|
|
517
|
-
try {
|
|
518
|
-
body = await request.json<ChatRequest>();
|
|
519
|
-
} catch {
|
|
520
|
-
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
if (!body.model || !body.user_input) {
|
|
524
|
-
return json({ error: "model and user_input are required" }, { status: 400 });
|
|
525
|
-
}
|
|
526
|
-
const model = MODELS.find((x) => x.id === body.model);
|
|
527
|
-
if (!model) {
|
|
528
|
-
return json({ error: `Unknown model: ${body.model}` }, { status: 400 });
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
// Hydrate attachment-by-reference (image/video attachments carrying an R2
|
|
532
|
-
// key instead of inline data) before routing, so every handler sees ready
|
|
533
|
-
// attachments. v0.21.7: cross-model artifact reuse within a conversation.
|
|
534
|
-
if (body.attachments?.length) {
|
|
535
|
-
body.attachments = await resolveAttachmentKeys(env, body.attachments, await getUserEmail(request, env));
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
if (model.type === "chat") return runChat(request, env, model, body);
|
|
539
|
-
if (model.type === "image") return runImage(request, env, model, body);
|
|
540
|
-
if (model.type === "tts") return runTts(request, env, model, body);
|
|
541
|
-
if (model.type === "video") return runVideo(request, env, ctx, model, body);
|
|
542
|
-
if (model.type === "stt") return runStt(request, env, model, body);
|
|
543
|
-
if (model.type === "music") return runMusic(request, env, ctx, model, body);
|
|
544
|
-
// "voice" is a live streaming session, not a request/response turn. The UI
|
|
545
|
-
// opens the mic streamer (WS /api/stt/stream) instead of POSTing here; reject
|
|
546
|
-
// with a clear pointer in case a client tries the chat path anyway.
|
|
547
|
-
if (model.type === "voice") {
|
|
548
|
-
return json(
|
|
549
|
-
{ error: "This is a live voice model; connect to the WebSocket at /api/stt/stream (mic streaming), not /api/chat." },
|
|
550
|
-
{ status: 400 },
|
|
551
|
-
);
|
|
552
|
-
}
|
|
553
|
-
return json({ error: `Unsupported model type: ${model.type}` }, { status: 500 });
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// ---------- /api/chat/stream (v0.13.0) ----------
|
|
557
|
-
//
|
|
558
|
-
// Thin entry point. Validates input + model, gates by model.streaming +
|
|
559
|
-
// model.provider (Pass 1 supports Anthropic only), then dispatches to
|
|
560
|
-
// runChatStream. Non-chat types and non-streaming chat models bounce with
|
|
561
|
-
// 400 here so the streaming runtime stays narrow.
|
|
562
|
-
|
|
563
|
-
async function handleChatStream(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
|
564
|
-
void ctx; // the response body is a live stream; the worker stays alive while it's open.
|
|
565
|
-
|
|
566
|
-
let body: ChatRequest;
|
|
567
|
-
try {
|
|
568
|
-
body = await request.json<ChatRequest>();
|
|
569
|
-
} catch {
|
|
570
|
-
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
571
|
-
}
|
|
572
|
-
if (!body.model || !body.user_input) {
|
|
573
|
-
return json({ error: "model and user_input are required" }, { status: 400 });
|
|
574
|
-
}
|
|
575
|
-
const model = MODELS.find((x) => x.id === body.model);
|
|
576
|
-
if (!model) {
|
|
577
|
-
return json({ error: `Unknown model: ${body.model}` }, { status: 400 });
|
|
578
|
-
}
|
|
579
|
-
if (model.type !== "chat") {
|
|
580
|
-
return json({ error: `Streaming is only supported for chat models. Use /api/chat for ${model.type} models.` }, { status: 400 });
|
|
581
|
-
}
|
|
582
|
-
if (!model.streaming) {
|
|
583
|
-
return json({ error: `Model ${model.id} does not support streaming. Use /api/chat (non-streaming) or pick a streaming-capable model.` }, { status: 400 });
|
|
584
|
-
}
|
|
585
|
-
// Anthropic + Workers AI + xAI + OpenAI + Google. Workers AI catalog
|
|
586
|
-
// entries omit `provider` (the type allows this and the ModelEntry default
|
|
587
|
-
// per the type comment is "workers-ai"); Unified Billing providers set it
|
|
588
|
-
// explicitly.
|
|
589
|
-
const isWorkersAI = !model.provider;
|
|
590
|
-
if (
|
|
591
|
-
model.provider !== "anthropic" &&
|
|
592
|
-
model.provider !== "xai" &&
|
|
593
|
-
model.provider !== "openai" &&
|
|
594
|
-
model.provider !== "google" &&
|
|
595
|
-
!isWorkersAI
|
|
596
|
-
) {
|
|
597
|
-
return json({ error: `Streaming for provider '${model.provider}' is not yet implemented.` }, { status: 501 });
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
return runChatStream(request, env, model, body);
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
// ---------- Chat (text generation, multimodal in) ----------
|
|
604
|
-
|
|
605
|
-
async function runChat(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
|
|
606
|
-
const userEmail = await getUserEmail(request, env);
|
|
607
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
|
|
608
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
609
|
-
const aiCtx = ctxOrErr;
|
|
610
|
-
const inputs: InputAttachment[] = body.attachments ?? [];
|
|
611
|
-
|
|
612
|
-
// v0.20.0: resolve project_id to row, apply per-project system_prompt
|
|
613
|
-
// fallback when the per-turn prompt is empty/undefined. The effective
|
|
614
|
-
// prompt is mutated back onto `body` so downstream provider calls and
|
|
615
|
-
// persistence see exactly what was used. scopedProjectId is passed to
|
|
616
|
-
// retrieveContext so RAG retrieval is filtered to that project's docs.
|
|
617
|
-
const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
|
|
618
|
-
body.system_prompt = resolvedSystemPrompt;
|
|
619
|
-
|
|
620
|
-
// Hot-path parallelization (v0.12.1): kick off the prior-turns SELECT and
|
|
621
|
-
// the RAG retrieve in the background while the attachment walk runs. None
|
|
622
|
-
// of the three depend on each other (the SELECT only needs the inbound
|
|
623
|
-
// conversation_id + user_email; retrieveContext only needs user_email +
|
|
624
|
-
// the raw user_input), so serializing them costs ~600-1500ms on
|
|
625
|
-
// multimodal+RAG turns. We await each promise at its existing use site
|
|
626
|
-
// below so the error surface is unchanged.
|
|
627
|
-
const conversationIdIn = body.conversation_id?.trim() || "";
|
|
628
|
-
const priorTurnsPromise: Promise<{
|
|
629
|
-
rows: Array<{ user_input: string; output: string; turn_index: number }>;
|
|
630
|
-
}> = conversationIdIn
|
|
631
|
-
? env.DB.prepare(
|
|
632
|
-
`SELECT user_input, output, turn_index
|
|
633
|
-
FROM chats
|
|
634
|
-
WHERE conversation_id = ?
|
|
635
|
-
AND user_email = ?
|
|
636
|
-
AND status = 'done'
|
|
637
|
-
AND model_type = 'chat'
|
|
638
|
-
ORDER BY turn_index ASC`
|
|
639
|
-
)
|
|
640
|
-
.bind(conversationIdIn, userEmail)
|
|
641
|
-
.all<{ user_input: string; output: string; turn_index: number }>()
|
|
642
|
-
.then((r) => ({ rows: r.results ?? [] }))
|
|
643
|
-
: Promise.resolve({ rows: [] });
|
|
644
|
-
|
|
645
|
-
const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
|
|
646
|
-
body.use_docs
|
|
647
|
-
? retrieveContext(env, userEmail, body.user_input, RETRIEVE_TOP_K, scopedProjectId)
|
|
648
|
-
: Promise.resolve({ chunks: [], error: null });
|
|
649
|
-
|
|
650
|
-
// v0.17.0: web search runs in parallel with RAG retrieval and the
|
|
651
|
-
// attachment walk. Per-source timeouts + catches inside searchWeb bound
|
|
652
|
-
// the worst-case latency to WEB_SEARCH_TIMEOUT_MS.
|
|
653
|
-
const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
|
|
654
|
-
body.use_web_search
|
|
655
|
-
? searchWeb(env, body.user_input)
|
|
656
|
-
: Promise.resolve({ results: [], error: null });
|
|
657
|
-
|
|
658
|
-
// Walk inputs: write images / video frames to R2, transcribe audio via
|
|
659
|
-
// Whisper. Build three parallel structures used after the loop:
|
|
660
|
-
// - extraText: prompt snippets the LLM sees
|
|
661
|
-
// - imageDataUrls: data URLs the LLM sees as image_url blocks
|
|
662
|
-
// - persistedAtt: per-attachment storage records
|
|
663
|
-
const extraText: string[] = [];
|
|
664
|
-
const imageDataUrls: string[] = [];
|
|
665
|
-
const persistedAtt: PersistedAttachment[] = [];
|
|
666
|
-
|
|
667
|
-
for (const att of inputs) {
|
|
668
|
-
if (att.type === "image") {
|
|
669
|
-
if (!model.capabilities.includes("vision")) {
|
|
670
|
-
return json({ error: `Model ${model.id} does not support vision. Pick a vision-capable chat model or remove the image.` }, { status: 400 });
|
|
671
|
-
}
|
|
672
|
-
const parsed = att.data ? parseDataUrl(att.data) : null;
|
|
673
|
-
if (!parsed) return json({ error: "Invalid image data URL" }, { status: 400 });
|
|
674
|
-
const bytes = base64ToBytes(parsed.base64);
|
|
675
|
-
const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
|
|
676
|
-
imageDataUrls.push(att.data!); // guaranteed by the parsed guard above (data may be hydrated from a key)
|
|
677
|
-
persistedAtt.push({ type: "image", key, mime: parsed.mime, filename: att.filename });
|
|
678
|
-
} else if (att.type === "audio") {
|
|
679
|
-
const parsed = att.data ? parseDataUrl(att.data) : null;
|
|
680
|
-
if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
|
|
681
|
-
try {
|
|
682
|
-
const wr = await aiRun(aiCtx, WHISPER_MODEL, { audio: parsed.base64 });
|
|
683
|
-
const text = (wr as { text?: string })?.text?.trim() ?? "";
|
|
684
|
-
const label = att.filename ? ` from ${att.filename}` : "";
|
|
685
|
-
extraText.push(text
|
|
686
|
-
? `[Transcribed audio${label}]\n${text}`
|
|
687
|
-
: `[Audio attachment${label} transcribed to empty text]`);
|
|
688
|
-
persistedAtt.push({ type: "audio", mime: parsed.mime, filename: att.filename, transcript: text || null });
|
|
689
|
-
} catch (err) {
|
|
690
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
691
|
-
return json({ error: `Audio transcription failed: ${m}` }, { status: 502 });
|
|
692
|
-
}
|
|
693
|
-
} else if (att.type === "video_frames") {
|
|
694
|
-
if (!model.capabilities.includes("vision")) {
|
|
695
|
-
return json({ error: `Model ${model.id} does not support vision. Video frames require a vision-capable chat model.` }, { status: 400 });
|
|
696
|
-
}
|
|
697
|
-
const frames = att.frames ?? [];
|
|
698
|
-
// Parse first (cheap, synchronous), then fan out R2 puts in parallel.
|
|
699
|
-
// Frames are independent: there's no ordering constraint between R2
|
|
700
|
-
// writes, only between the resulting `imageDataUrls` entries (which
|
|
701
|
-
// we preserve by iterating the same parsedFrames array twice).
|
|
702
|
-
const parsedFrames = frames
|
|
703
|
-
.map((fdataUrl) => ({ fdataUrl, parsed: parseDataUrl(fdataUrl) }))
|
|
704
|
-
.filter((p): p is { fdataUrl: string; parsed: { mime: string; base64: string } } => p.parsed !== null);
|
|
705
|
-
const keys = await Promise.all(
|
|
706
|
-
parsedFrames.map(({ parsed }) =>
|
|
707
|
-
r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail)
|
|
708
|
-
)
|
|
709
|
-
);
|
|
710
|
-
for (const { fdataUrl } of parsedFrames) {
|
|
711
|
-
imageDataUrls.push(fdataUrl);
|
|
712
|
-
}
|
|
713
|
-
const dur = att.duration ? ` ${att.duration.toFixed(1)}s` : "";
|
|
714
|
-
const fn = att.filename ? ` "${att.filename}"` : "";
|
|
715
|
-
extraText.push(`[Video${fn}${dur}, ${frames.length} evenly-sampled frames attached below]`);
|
|
716
|
-
persistedAtt.push({ type: "video_frames", keys, frame_count: keys.length, duration: att.duration, filename: att.filename });
|
|
717
|
-
} else if (att.type === "video_full") {
|
|
718
|
-
// Full video file upload. No chat model currently consumes the raw video
|
|
719
|
-
// (the keyframe path covers vision models); the upload is still stored in
|
|
720
|
-
// R2 so it appears in history and the plumbing stays ready for a future
|
|
721
|
-
// video-aware model. Dormant since Bedrock Pegasus was removed in v0.95.0.
|
|
722
|
-
const parsed = att.data ? parseDataUrl(att.data) : null;
|
|
723
|
-
if (!parsed) return json({ error: "Invalid video data URL" }, { status: 400 });
|
|
724
|
-
const bytes = base64ToBytes(parsed.base64);
|
|
725
|
-
const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
|
|
726
|
-
const fn = att.filename ? ` "${att.filename}"` : "";
|
|
727
|
-
extraText.push(`[Full video${fn} attached for video-aware model]`);
|
|
728
|
-
persistedAtt.push({ type: "video_full", key, mime: parsed.mime, filename: att.filename });
|
|
729
|
-
} else if (att.type === "document") {
|
|
730
|
-
const r = buildDocumentAttachment(att);
|
|
731
|
-
if ("error" in r) return json({ error: r.error }, { status: 400 });
|
|
732
|
-
extraText.push(r.extra);
|
|
733
|
-
persistedAtt.push(r.persisted);
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
const userText = [body.user_input, ...extraText].filter(Boolean).join("\n\n");
|
|
738
|
-
const userContent: unknown = imageDataUrls.length
|
|
739
|
-
? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
|
|
740
|
-
: userText;
|
|
741
|
-
|
|
742
|
-
// ---- Multi-turn conversation continuation (v0.10.0) ----
|
|
743
|
-
// If body.conversation_id is present, fetch prior turns of that conversation
|
|
744
|
-
// (filtered to this user, completed chat turns only) and assemble a history
|
|
745
|
-
// of user/assistant message pairs. The current turn appends to that history.
|
|
746
|
-
// If no conversation_id, generate a new one for the first turn.
|
|
747
|
-
// The SELECT itself runs in parallel with the attachment walk (hoisted
|
|
748
|
-
// above as priorTurnsPromise); here we just consume the result.
|
|
749
|
-
let conversationId = conversationIdIn;
|
|
750
|
-
let turnIndex = 0;
|
|
751
|
-
const priorTurns: Array<{ user_input: string; output: string }> = [];
|
|
752
|
-
|
|
753
|
-
if (conversationId) {
|
|
754
|
-
const { rows } = await priorTurnsPromise;
|
|
755
|
-
for (const r of rows) {
|
|
756
|
-
// Skip empty/failed prior turns defensively.
|
|
757
|
-
if (r.user_input && r.output) {
|
|
758
|
-
priorTurns.push({ user_input: r.user_input, output: r.output });
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
|
|
762
|
-
} else {
|
|
763
|
-
// crypto.randomUUID() is available in Workers runtime.
|
|
764
|
-
conversationId = crypto.randomUUID();
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// RAG retrieval (Pass 2) - per-turn, applies only to THIS turn's system prompt.
|
|
768
|
-
// The retrieve itself runs in parallel with the attachment walk + prior-turns
|
|
769
|
-
// fetch (hoisted above as retrievePromise); here we just consume the result.
|
|
770
|
-
const { chunks: retrievedChunks, error: retrievalError } = await retrievePromise;
|
|
771
|
-
|
|
772
|
-
// v0.17.0: web-search retrieval, same parallelism pattern as RAG.
|
|
773
|
-
const { results: webResults, error: webSearchError } = await webSearchPromise;
|
|
774
|
-
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
775
|
-
|
|
776
|
-
// Build the effective system prompt: user-supplied prompt followed by
|
|
777
|
-
// the retrieval block(s). Order: user prompt, then RAG (more specific
|
|
778
|
-
// to this user's corpus), then web (more general). Either or both
|
|
779
|
-
// retrieval blocks may be empty.
|
|
780
|
-
const userSystemPrompt = body.system_prompt?.trim() ?? "";
|
|
781
|
-
const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
|
|
782
|
-
const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
|
|
783
|
-
const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
|
|
784
|
-
.filter(Boolean)
|
|
785
|
-
.join("\n\n");
|
|
786
|
-
|
|
787
|
-
// Build the message array. For Anthropic, system goes as a top-level field
|
|
788
|
-
// on the upstream request (handled inside callAnthropic), not in messages.
|
|
789
|
-
// For Workers AI, xAI, and OpenAI, we push a role:"system" message.
|
|
790
|
-
//
|
|
791
|
-
// Prior turns of this conversation go in as alternating user/assistant
|
|
792
|
-
// text messages. Multimodal content (images) from prior turns is NOT
|
|
793
|
-
// re-included; if the user wants to reference earlier images they can
|
|
794
|
-
// re-attach. Current turn's attachments are still threaded into userContent.
|
|
795
|
-
const wantsSystemInMessages = model.provider !== "anthropic" && model.provider !== "google";
|
|
796
|
-
const messages: Array<unknown> = [];
|
|
797
|
-
if (effectiveSystemPrompt && wantsSystemInMessages) {
|
|
798
|
-
messages.push({ role: "system", content: effectiveSystemPrompt });
|
|
799
|
-
}
|
|
800
|
-
for (const t of priorTurns) {
|
|
801
|
-
messages.push({ role: "user", content: t.user_input });
|
|
802
|
-
messages.push({ role: "assistant", content: t.output });
|
|
803
|
-
}
|
|
804
|
-
messages.push({ role: "user", content: userContent });
|
|
805
|
-
|
|
806
|
-
const start = Date.now();
|
|
807
|
-
let result: unknown;
|
|
808
|
-
let logId: string | null = null;
|
|
809
|
-
try {
|
|
810
|
-
if (model.id === "@cf/llava-hf/llava-1.5-7b-hf") {
|
|
811
|
-
// LLaVA 1.5 is image-to-text: input is { image: number[] (raw bytes),
|
|
812
|
-
// prompt, max_tokens }, not the chat { messages } shape, and it's
|
|
813
|
-
// single-shot (one image + one prompt; prior turns and system prompt are
|
|
814
|
-
// not threaded). We surface it as a vision chat model so the existing
|
|
815
|
-
// attach UI works, but route it here for the different wire format.
|
|
816
|
-
const imgAtt = inputs.find((a) => a.type === "image");
|
|
817
|
-
if (!imgAtt?.data) {
|
|
818
|
-
return json({ error: "LLaVA needs an image attachment. Attach one, then ask about it." }, { status: 400 });
|
|
819
|
-
}
|
|
820
|
-
const parsedImg = parseDataUrl(imgAtt.data);
|
|
821
|
-
if (!parsedImg) {
|
|
822
|
-
return json({ error: "Invalid image data URL" }, { status: 400 });
|
|
823
|
-
}
|
|
824
|
-
result = await aiRun(aiCtx, model.id, {
|
|
825
|
-
image: [...base64ToBytes(parsedImg.base64)],
|
|
826
|
-
prompt: body.user_input || "Describe this image in detail.",
|
|
827
|
-
max_tokens: 512,
|
|
828
|
-
});
|
|
829
|
-
logId = aiLogId(aiCtx);
|
|
830
|
-
} else if (model.provider === "anthropic") {
|
|
831
|
-
const r = await callAnthropic(aiCtx, model, effectiveSystemPrompt || undefined, messages);
|
|
832
|
-
result = r.raw;
|
|
833
|
-
logId = r.logId;
|
|
834
|
-
} else if (model.provider === "xai") {
|
|
835
|
-
const r = await callXai(aiCtx, model, messages);
|
|
836
|
-
result = r.raw;
|
|
837
|
-
logId = r.logId;
|
|
838
|
-
} else if (model.provider === "google") {
|
|
839
|
-
const r = await callGemini(aiCtx, model, effectiveSystemPrompt || undefined, messages);
|
|
840
|
-
result = r.raw;
|
|
841
|
-
logId = r.logId;
|
|
842
|
-
} else {
|
|
843
|
-
result = await aiRun(aiCtx, model.id, { messages });
|
|
844
|
-
logId = aiLogId(aiCtx);
|
|
845
|
-
}
|
|
846
|
-
} catch (err) {
|
|
847
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
848
|
-
return json({ error: `AI call failed: ${m}` }, { status: 502 });
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
// Some providers (notably OpenAI/Gemini proxied via unified billing) return
|
|
852
|
-
// a failure envelope { state: "Failed", error: "..." } as a resolved value
|
|
853
|
-
// instead of throwing. Surface it as a 502 here; otherwise extractOutput
|
|
854
|
-
// would stringify the envelope into chats.output and persist the failed
|
|
855
|
-
// turn as a success.
|
|
856
|
-
const providerFailure = detectProviderFailure(result);
|
|
857
|
-
if (providerFailure) {
|
|
858
|
-
return json({ error: `Model execution failed: ${providerFailure}` }, { status: 502 });
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
const latency = Date.now() - start;
|
|
862
|
-
const output = extractOutput(result);
|
|
863
|
-
const usage = extractUsage(result);
|
|
864
|
-
|
|
865
|
-
const row = await persistChat(env, {
|
|
866
|
-
userEmail,
|
|
867
|
-
model: model.id,
|
|
868
|
-
model_type: "chat",
|
|
869
|
-
system_prompt: body.system_prompt ?? null,
|
|
870
|
-
user_input: body.user_input,
|
|
871
|
-
output,
|
|
872
|
-
output_artifact: null,
|
|
873
|
-
attachments: persistedAtt,
|
|
874
|
-
tokens_in: usage.in_,
|
|
875
|
-
tokens_out: usage.out_,
|
|
876
|
-
latency_ms: latency,
|
|
877
|
-
ai_gateway_log_id: logId,
|
|
878
|
-
retrieved_context: allRetrieved.length ? allRetrieved : null,
|
|
879
|
-
conversation_id: conversationId,
|
|
880
|
-
turn_index: turnIndex,
|
|
881
|
-
project_id: scopedProjectId ?? null,
|
|
882
|
-
});
|
|
883
|
-
|
|
884
|
-
return json({
|
|
885
|
-
id: row.id,
|
|
886
|
-
created_at: row.created_at,
|
|
887
|
-
model: model.id,
|
|
888
|
-
model_type: "chat",
|
|
889
|
-
output,
|
|
890
|
-
tokens_in: usage.in_,
|
|
891
|
-
tokens_out: usage.out_,
|
|
892
|
-
latency_ms: latency,
|
|
893
|
-
ai_gateway_log_id: logId,
|
|
894
|
-
transcripts: extraText,
|
|
895
|
-
retrieved_chunks: retrievedChunks,
|
|
896
|
-
web_results: webResults,
|
|
897
|
-
conversation_id: conversationId,
|
|
898
|
-
turn_index: turnIndex,
|
|
899
|
-
// Diagnostic: when either retrieval source was on, include the exact text
|
|
900
|
-
// that went into the model as the system prompt, plus per-source errors.
|
|
901
|
-
// Inspect via browser DevTools to verify the retrieval block reached
|
|
902
|
-
// the model.
|
|
903
|
-
effective_system_prompt: (body.use_docs || body.use_web_search) ? effectiveSystemPrompt : undefined,
|
|
904
|
-
retrieval_error: body.use_docs ? retrievalError : undefined,
|
|
905
|
-
web_search_error: body.use_web_search ? webSearchError : undefined,
|
|
906
|
-
});
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
// ---------- Image generation ----------
|
|
910
|
-
|
|
911
|
-
async function runImage(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
|
|
912
|
-
const userEmail = await getUserEmail(request, env);
|
|
913
|
-
let aiCtx: AiContext | null = null;
|
|
914
|
-
const needsProxiedGateway = !!model.provider;
|
|
915
|
-
if (needsProxiedGateway) {
|
|
916
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: true });
|
|
917
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
918
|
-
aiCtx = ctxOrErr;
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
// Image gen splits two ways. Proxied models (those with a `provider`:
|
|
922
|
-
// nano-banana/google, gpt-image-1.5/openai, recraftv4/recraft) go through the
|
|
923
|
-
// gateway binding, return a URL, and share one code path. The @cf models
|
|
924
|
-
// (no `provider`) return base64 or a ReadableStream and need the bypass +
|
|
925
|
-
// shape-detection handling below. Both converge on the (bytes, mime) tuple
|
|
926
|
-
// and the shared R2-put + persist + respond tail.
|
|
927
|
-
let bytes: Uint8Array;
|
|
928
|
-
let mime: string;
|
|
929
|
-
let latency: number;
|
|
930
|
-
let logId: string | null = null;
|
|
931
|
-
|
|
932
|
-
const start = Date.now();
|
|
933
|
-
try {
|
|
934
|
-
if (model.provider) {
|
|
935
|
-
// Proxied image (Unified Billing via the gateway): nano-banana (google),
|
|
936
|
-
// recraftv4 (recraft), and gpt-image-1.5 / gpt-image-2 (openai). All are
|
|
937
|
-
// opaque; v0.166.0 retired the OPENAI_API_KEY BYOK transparent-PNG path
|
|
938
|
-
// (prism#93), so gpt-image-* now ride the proxy like the others.
|
|
939
|
-
// The @cf models carry no `provider`, so this branch is exactly the
|
|
940
|
-
// proxied set. Per-provider request shape comes from buildProxiedImageParams
|
|
941
|
-
// because each upstream schema is additionalProperties:false and rejects
|
|
942
|
-
// the @cf { width, height, steps, negative_prompt } shape; system_prompt
|
|
943
|
-
// has no negative_prompt slot on any of them and is ignored.
|
|
944
|
-
//
|
|
945
|
-
// They return a URL (not base64) in the { state, result } envelope:
|
|
946
|
-
// { state: "Completed", result: { image: "<url>" } }
|
|
947
|
-
// so we fetch the URL and store the bytes, like the video path does. mime
|
|
948
|
-
// comes from the response content-type (recraftv4 returns webp, the
|
|
949
|
-
// openai/google paths return png), so no format is hardcoded on the store.
|
|
950
|
-
// (First pass is text-to-image only; gpt-image-1.5's images[] editing and
|
|
951
|
-
// reference inputs are a later add, mirroring the FLUX.2 ref-image work.)
|
|
952
|
-
const result = await aiRun(aiCtx!, model.id, buildProxiedImageParams(model.provider, body.user_input));
|
|
953
|
-
logId = aiLogId(aiCtx!);
|
|
954
|
-
|
|
955
|
-
const failure = detectProviderFailure(result);
|
|
956
|
-
if (failure) {
|
|
957
|
-
return json({ error: `Image generation failed: ${failure}` }, { status: 502 });
|
|
958
|
-
}
|
|
959
|
-
const imageUrl = extractProxiedImageUrl(result);
|
|
960
|
-
if (!imageUrl) {
|
|
961
|
-
return json({ error: "Image generation returned no image URL", raw: result }, { status: 502 });
|
|
962
|
-
}
|
|
963
|
-
const aresp = await fetch(imageUrl);
|
|
964
|
-
if (!aresp.ok) {
|
|
965
|
-
return json({ error: `Failed to fetch generated image: ${aresp.status}` }, { status: 502 });
|
|
966
|
-
}
|
|
967
|
-
bytes = new Uint8Array(await aresp.arrayBuffer());
|
|
968
|
-
mime = aresp.headers.get("content-type") || "image/png";
|
|
969
|
-
} else {
|
|
970
|
-
// Two Cloudflare-side complications for Workers AI image gen as of
|
|
971
|
-
// 2026-Q1, both manifesting as either:
|
|
972
|
-
// - AiError 5006 "required properties at '/' are 'multipart'", or
|
|
973
|
-
// - "AI Gateway does not support ReadableStreams yet"
|
|
974
|
-
//
|
|
975
|
-
// The matrix:
|
|
976
|
-
// FLUX-1 schnell, Lucid Origin - JSON in, JSON out (base64). Gateway path works.
|
|
977
|
-
// FLUX-2 (Klein 9b/4b, Dev) - multipart in, JSON out (base64). Gateway can't proxy stream input.
|
|
978
|
-
// Phoenix 1.0, Dreamshaper 8 LCM - JSON in, ReadableStream out. Gateway can't proxy stream output.
|
|
979
|
-
//
|
|
980
|
-
// Solution: bypass the AI Gateway for the five problematic models by
|
|
981
|
-
// calling env.AI.run directly without the gateway option, and detect
|
|
982
|
-
// the response shape at runtime so we can drain a ReadableStream into
|
|
983
|
-
// bytes or extract base64 from JSON as appropriate. Cost: no AI Gateway
|
|
984
|
-
// observability/caching for these specific models (ai_gateway_log_id
|
|
985
|
-
// stays null on the persisted row).
|
|
986
|
-
const isFlux2 = model.id.startsWith("@cf/black-forest-labs/flux-2-");
|
|
987
|
-
const isSdxl = model.id === "@cf/stabilityai/stable-diffusion-xl-base-1.0";
|
|
988
|
-
const bypassGateway = isFlux2
|
|
989
|
-
|| model.id === "@cf/leonardo/phoenix-1.0"
|
|
990
|
-
|| model.id === "@cf/lykon/dreamshaper-8-lcm"
|
|
991
|
-
|| isSdxl; // SDXL returns a ReadableStream image; gateway can't proxy it
|
|
992
|
-
|
|
993
|
-
let runParams: unknown;
|
|
994
|
-
|
|
995
|
-
if (isFlux2) {
|
|
996
|
-
// FLUX.2 requires multipart form data input. FormData doesn't expose
|
|
997
|
-
// its serialized body or boundary directly; wrap in a Response
|
|
998
|
-
// constructor to get the stream + the Content-Type header value
|
|
999
|
-
// with the boundary string.
|
|
1000
|
-
const form = new FormData();
|
|
1001
|
-
form.append("prompt", body.user_input);
|
|
1002
|
-
form.append("width", "1024");
|
|
1003
|
-
form.append("height", "1024");
|
|
1004
|
-
if (body.system_prompt && body.system_prompt.trim()) {
|
|
1005
|
-
// FLUX.2's public schema doesn't list negative_prompt, but the
|
|
1006
|
-
// binding ignores unknown form fields rather than erroring.
|
|
1007
|
-
form.append("negative_prompt", body.system_prompt);
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
// Reference images (v0.16.0): FLUX.2 accepts up to 4 input images
|
|
1011
|
-
// via input_image_0..input_image_3 form fields. Each must be at most
|
|
1012
|
-
// 512x512 (the frontend downscales before upload). We silently cap
|
|
1013
|
-
// beyond 4 rather than erroring, so a user who picks 5 just doesn't
|
|
1014
|
-
// see the 5th show up; the picker UI also caps at 4 client-side.
|
|
1015
|
-
const inputs: InputAttachment[] = body.attachments ?? [];
|
|
1016
|
-
let refIdx = 0;
|
|
1017
|
-
for (const att of inputs) {
|
|
1018
|
-
if (refIdx >= 4) break;
|
|
1019
|
-
if (att.type !== "image" || !att.data) continue;
|
|
1020
|
-
const parsed = parseDataUrl(att.data);
|
|
1021
|
-
if (!parsed) continue;
|
|
1022
|
-
const blob = new Blob([base64ToBytes(parsed.base64)], { type: parsed.mime });
|
|
1023
|
-
form.append(`input_image_${refIdx}`, blob, att.filename || `ref-${refIdx}.png`);
|
|
1024
|
-
refIdx++;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
const formResponse = new Response(form);
|
|
1028
|
-
runParams = {
|
|
1029
|
-
multipart: {
|
|
1030
|
-
body: formResponse.body!,
|
|
1031
|
-
contentType: formResponse.headers.get("content-type")!,
|
|
1032
|
-
},
|
|
1033
|
-
};
|
|
1034
|
-
} else {
|
|
1035
|
-
const params: Record<string, unknown> = {
|
|
1036
|
-
prompt: body.user_input,
|
|
1037
|
-
width: 1024,
|
|
1038
|
-
height: 1024,
|
|
1039
|
-
steps: 25,
|
|
1040
|
-
};
|
|
1041
|
-
if (body.system_prompt && body.system_prompt.trim()) {
|
|
1042
|
-
params.negative_prompt = body.system_prompt;
|
|
1043
|
-
}
|
|
1044
|
-
// FLUX-1 schnell uses fewer steps and has no negative_prompt.
|
|
1045
|
-
if (model.id === "@cf/black-forest-labs/flux-1-schnell") {
|
|
1046
|
-
params.steps = 4;
|
|
1047
|
-
delete params.negative_prompt;
|
|
1048
|
-
}
|
|
1049
|
-
// SDXL's step field is `num_steps` (max 20), not `steps`; swap to avoid
|
|
1050
|
-
// sending an unknown/over-max field.
|
|
1051
|
-
if (isSdxl) {
|
|
1052
|
-
delete params.steps;
|
|
1053
|
-
params.num_steps = 20;
|
|
1054
|
-
}
|
|
1055
|
-
runParams = params;
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
// Run via the binding. Bypass the gateway for stream-incompatible
|
|
1059
|
-
// models; everything else stays on the aiRun helper path (which
|
|
1060
|
-
// populates ai_gateway_log_id for observability).
|
|
1061
|
-
let result: unknown;
|
|
1062
|
-
if (bypassGateway) {
|
|
1063
|
-
type BypassRunFn = (model: string, params: unknown) => Promise<unknown>;
|
|
1064
|
-
result = await (env.AI as unknown as { run: BypassRunFn }).run(model.id, runParams);
|
|
1065
|
-
} else {
|
|
1066
|
-
if (!aiCtx) {
|
|
1067
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
|
|
1068
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1069
|
-
aiCtx = ctxOrErr;
|
|
1070
|
-
}
|
|
1071
|
-
result = await aiRun(aiCtx, model.id, runParams);
|
|
1072
|
-
logId = aiLogId(aiCtx);
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
// Two response shapes are possible:
|
|
1076
|
-
// 1. JSON { image: "base64..." } - FLUX-1, FLUX-2, Lucid Origin
|
|
1077
|
-
// 2. ReadableStream of raw PNG bytes - Phoenix, Dreamshaper
|
|
1078
|
-
// Detect at runtime rather than mapping per-model; safer if Cloudflare
|
|
1079
|
-
// shifts a model from one shape to the other.
|
|
1080
|
-
if (result instanceof ReadableStream) {
|
|
1081
|
-
const reader = result.getReader();
|
|
1082
|
-
const chunks: Uint8Array[] = [];
|
|
1083
|
-
let total = 0;
|
|
1084
|
-
while (true) {
|
|
1085
|
-
const { done, value } = await reader.read();
|
|
1086
|
-
if (done) break;
|
|
1087
|
-
if (value) {
|
|
1088
|
-
chunks.push(value);
|
|
1089
|
-
total += value.length;
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
bytes = new Uint8Array(total);
|
|
1093
|
-
let offset = 0;
|
|
1094
|
-
for (const c of chunks) {
|
|
1095
|
-
bytes.set(c, offset);
|
|
1096
|
-
offset += c.length;
|
|
1097
|
-
}
|
|
1098
|
-
// All stream-output image models here emit PNG bytes. (The SDXL docs
|
|
1099
|
-
// claim image/jpg, but the binding's actual output is PNG, confirmed
|
|
1100
|
-
// live, so we don't special-case it.)
|
|
1101
|
-
mime = "image/png";
|
|
1102
|
-
} else {
|
|
1103
|
-
const b64 = (result as { image?: string })?.image;
|
|
1104
|
-
if (!b64 || typeof b64 !== "string") {
|
|
1105
|
-
return json({ error: "Image generation returned no image", raw: result }, { status: 502 });
|
|
1106
|
-
}
|
|
1107
|
-
bytes = base64ToBytes(b64);
|
|
1108
|
-
// FLUX.2 outputs PNG; the older JSON path returned JPEG historically.
|
|
1109
|
-
mime = isFlux2 ? "image/png" : "image/jpeg";
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
} catch (err) {
|
|
1113
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1114
|
-
return json({ error: `Image generation failed: ${m}` }, { status: 502 });
|
|
1115
|
-
}
|
|
1116
|
-
latency = Date.now() - start;
|
|
1117
|
-
|
|
1118
|
-
const key = await r2Put(env, "out", mime, bytes, userEmail);
|
|
1119
|
-
const outputArtifact: OutputArtifact = { key, mime, type: "image" };
|
|
1120
|
-
|
|
1121
|
-
const row = await persistChat(env, {
|
|
1122
|
-
userEmail,
|
|
1123
|
-
model: model.id,
|
|
1124
|
-
model_type: "image",
|
|
1125
|
-
system_prompt: body.system_prompt ?? null,
|
|
1126
|
-
user_input: body.user_input,
|
|
1127
|
-
output: "",
|
|
1128
|
-
output_artifact: outputArtifact,
|
|
1129
|
-
attachments: [],
|
|
1130
|
-
tokens_in: null,
|
|
1131
|
-
tokens_out: null,
|
|
1132
|
-
latency_ms: latency,
|
|
1133
|
-
ai_gateway_log_id: logId,
|
|
1134
|
-
});
|
|
1135
|
-
|
|
1136
|
-
return json({
|
|
1137
|
-
id: row.id,
|
|
1138
|
-
created_at: row.created_at,
|
|
1139
|
-
model: model.id,
|
|
1140
|
-
model_type: "image",
|
|
1141
|
-
output: "",
|
|
1142
|
-
output_artifact: outputArtifact,
|
|
1143
|
-
latency_ms: latency,
|
|
1144
|
-
ai_gateway_log_id: logId,
|
|
1145
|
-
conversation_id: row.conversation_id,
|
|
1146
|
-
turn_index: 0,
|
|
1147
|
-
});
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
// ---------- TTS ----------
|
|
1151
|
-
|
|
1152
|
-
// v0.118.0: speak arbitrary text via Aura-2 and stream the audio back. No D1
|
|
1153
|
-
// row (the voice-chat loop calls this for every assistant reply; persisting
|
|
1154
|
-
// each one would flood history). Caps length and restricts the voice to the
|
|
1155
|
-
// two Aura-2 catalog entries.
|
|
1156
|
-
const TTS_VOICES = new Set(["@cf/deepgram/aura-2-en", "@cf/deepgram/aura-2-es"]);
|
|
1157
|
-
async function handleTtsSpeak(request: Request, env: Env): Promise<Response> {
|
|
1158
|
-
const userEmail = await getUserEmail(request, env);
|
|
1159
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
|
|
1160
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1161
|
-
const aiCtx = ctxOrErr;
|
|
1162
|
-
|
|
1163
|
-
let body: { text?: string; voice?: string };
|
|
1164
|
-
try {
|
|
1165
|
-
body = await request.json<{ text?: string; voice?: string }>();
|
|
1166
|
-
} catch {
|
|
1167
|
-
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
1168
|
-
}
|
|
1169
|
-
const text = typeof body.text === "string" ? body.text.trim().slice(0, 4000) : "";
|
|
1170
|
-
if (!text) return json({ error: "text required" }, { status: 400 });
|
|
1171
|
-
const voice = body.voice && TTS_VOICES.has(body.voice) ? body.voice : "@cf/deepgram/aura-2-en";
|
|
1172
|
-
try {
|
|
1173
|
-
const resp = await aiRun(aiCtx, voice, { text, prompt: text }, true /* returnRawResponse */);
|
|
1174
|
-
if (!(resp instanceof Response)) {
|
|
1175
|
-
return json({ error: "TTS returned non-Response shape" }, { status: 502 });
|
|
1176
|
-
}
|
|
1177
|
-
const mime = resp.headers.get("content-type") || "audio/mpeg";
|
|
1178
|
-
const bytes = new Uint8Array(await resp.arrayBuffer());
|
|
1179
|
-
return new Response(bytes, { headers: { "content-type": mime, "cache-control": "no-store" } });
|
|
1180
|
-
} catch (err) {
|
|
1181
|
-
return json({ error: `TTS failed: ${err instanceof Error ? err.message : String(err)}` }, { status: 502 });
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
async function runTts(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
|
|
1186
|
-
const userEmail = await getUserEmail(request, env);
|
|
1187
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
|
|
1188
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1189
|
-
const aiCtx = ctxOrErr;
|
|
1190
|
-
|
|
1191
|
-
let mime: string;
|
|
1192
|
-
let bytes: Uint8Array;
|
|
1193
|
-
let logId: string | null = null;
|
|
1194
|
-
|
|
1195
|
-
const start = Date.now();
|
|
1196
|
-
try {
|
|
1197
|
-
// Aura: { text }; MeloTTS: { prompt, lang? }. Send both keys defensively.
|
|
1198
|
-
const params: Record<string, unknown> = { text: body.user_input, prompt: body.user_input };
|
|
1199
|
-
const resp = await aiRun(aiCtx, model.id, params, true /* returnRawResponse */);
|
|
1200
|
-
logId = aiLogId(aiCtx);
|
|
1201
|
-
if (!(resp instanceof Response)) {
|
|
1202
|
-
return json({ error: "TTS returned non-Response shape", raw: resp }, { status: 502 });
|
|
1203
|
-
}
|
|
1204
|
-
mime = resp.headers.get("content-type") || "audio/mpeg";
|
|
1205
|
-
bytes = new Uint8Array(await resp.arrayBuffer());
|
|
1206
|
-
} catch (err) {
|
|
1207
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1208
|
-
return json({ error: `TTS failed: ${m}` }, { status: 502 });
|
|
1209
|
-
}
|
|
1210
|
-
const latency = Date.now() - start;
|
|
1211
|
-
|
|
1212
|
-
const key = await r2Put(env, "out", mime, bytes, userEmail);
|
|
1213
|
-
const outputArtifact: OutputArtifact = { key, mime, type: "audio" };
|
|
1214
|
-
|
|
1215
|
-
const row = await persistChat(env, {
|
|
1216
|
-
userEmail,
|
|
1217
|
-
model: model.id,
|
|
1218
|
-
model_type: "tts",
|
|
1219
|
-
system_prompt: null,
|
|
1220
|
-
user_input: body.user_input,
|
|
1221
|
-
output: "",
|
|
1222
|
-
output_artifact: outputArtifact,
|
|
1223
|
-
attachments: [],
|
|
1224
|
-
tokens_in: null,
|
|
1225
|
-
tokens_out: null,
|
|
1226
|
-
latency_ms: latency,
|
|
1227
|
-
ai_gateway_log_id: logId,
|
|
1228
|
-
});
|
|
1229
|
-
|
|
1230
|
-
return json({
|
|
1231
|
-
id: row.id,
|
|
1232
|
-
created_at: row.created_at,
|
|
1233
|
-
model: model.id,
|
|
1234
|
-
model_type: "tts",
|
|
1235
|
-
output: "",
|
|
1236
|
-
output_artifact: outputArtifact,
|
|
1237
|
-
latency_ms: latency,
|
|
1238
|
-
ai_gateway_log_id: logId,
|
|
1239
|
-
conversation_id: row.conversation_id,
|
|
1240
|
-
turn_index: 0,
|
|
1241
|
-
});
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
// ---------- Speech-to-text (Whisper) ----------
|
|
1245
|
-
//
|
|
1246
|
-
// Synchronous: user attaches an audio file and picks a Whisper model, worker
|
|
1247
|
-
// calls Whisper directly and returns the transcript as the row's `output`
|
|
1248
|
-
// text. No D1 status='pending' or polling - Whisper completes in seconds.
|
|
1249
|
-
// Reuses the existing audio attachment shape from the chat path.
|
|
1250
|
-
|
|
1251
|
-
// Deepgram ASR on Workers AI returns the native Deepgram results object, not
|
|
1252
|
-
// the top-level { text } that Whisper returns. Standard path is
|
|
1253
|
-
// results.channels[0].alternatives[0].transcript; we also tolerate a couple of
|
|
1254
|
-
// alternate shapes and a normalized top-level text/transcript, defensively.
|
|
1255
|
-
function extractDeepgramTranscript(result: unknown): string {
|
|
1256
|
-
const r = result as {
|
|
1257
|
-
results?: {
|
|
1258
|
-
channels?: Array<{ alternatives?: Array<{ transcript?: string }> }>;
|
|
1259
|
-
alternatives?: Array<{ transcript?: string }>;
|
|
1260
|
-
};
|
|
1261
|
-
text?: string;
|
|
1262
|
-
transcript?: string;
|
|
1263
|
-
};
|
|
1264
|
-
const viaChannels = r?.results?.channels?.[0]?.alternatives?.[0]?.transcript;
|
|
1265
|
-
if (typeof viaChannels === "string") return viaChannels.trim();
|
|
1266
|
-
const viaAlternatives = r?.results?.alternatives?.[0]?.transcript;
|
|
1267
|
-
if (typeof viaAlternatives === "string") return viaAlternatives.trim();
|
|
1268
|
-
if (typeof r?.transcript === "string") return r.transcript.trim();
|
|
1269
|
-
if (typeof r?.text === "string") return r.text.trim();
|
|
1270
|
-
return "";
|
|
1271
|
-
}
|
|
1272
|
-
|
|
1273
|
-
async function runStt(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
|
|
1274
|
-
const userEmail = await getUserEmail(request, env);
|
|
1275
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
|
|
1276
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1277
|
-
const aiCtx = ctxOrErr;
|
|
1278
|
-
const t0 = Date.now();
|
|
1279
|
-
|
|
1280
|
-
const audioAtt = (body.attachments ?? []).find((a) => a.type === "audio");
|
|
1281
|
-
if (!audioAtt?.data) {
|
|
1282
|
-
return json({ error: "Please attach an audio file to transcribe" }, { status: 400 });
|
|
1283
|
-
}
|
|
1284
|
-
const parsed = parseDataUrl(audioAtt.data);
|
|
1285
|
-
if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
|
|
1286
|
-
|
|
1287
|
-
const viaDeepgram = model.id.startsWith("@cf/deepgram/");
|
|
1288
|
-
let transcript: string;
|
|
1289
|
-
try {
|
|
1290
|
-
if (viaDeepgram) {
|
|
1291
|
-
// Deepgram wants { audio: { body, contentType } } where body is a
|
|
1292
|
-
// ReadableStream of the audio bytes (a bare base64 string or Uint8Array
|
|
1293
|
-
// fails schema validation). AI Gateway does not support ReadableStream
|
|
1294
|
-
// inputs ("error 5006/ReadableStreams not supported"), so this is the
|
|
1295
|
-
// one call that bypasses the gateway and hits the binding directly;
|
|
1296
|
-
// there's no cf-aig-log-id for it (logId stays null below). Output is
|
|
1297
|
-
// the native Deepgram results object, parsed by extractDeepgramTranscript.
|
|
1298
|
-
const dr = await (env.AI as unknown as { run: (m: string, p: unknown) => Promise<unknown> })
|
|
1299
|
-
.run(model.id, { audio: { body: new Response(base64ToBytes(parsed.base64)).body, contentType: parsed.mime } });
|
|
1300
|
-
transcript = extractDeepgramTranscript(dr);
|
|
1301
|
-
} else {
|
|
1302
|
-
const wr = await aiRun(aiCtx, model.id, { audio: parsed.base64 });
|
|
1303
|
-
transcript = (wr as { text?: string })?.text?.trim() ?? "";
|
|
1304
|
-
}
|
|
1305
|
-
} catch (err) {
|
|
1306
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1307
|
-
return json({ error: `Transcription failed: ${m}` }, { status: 502 });
|
|
1308
|
-
}
|
|
1309
|
-
|
|
1310
|
-
const latency = Date.now() - t0;
|
|
1311
|
-
// Persist the audio's transcript on the attachment record but not the
|
|
1312
|
-
// raw audio bytes (same convention as the chat path).
|
|
1313
|
-
const persistedAtt: PersistedAttachment[] = [{
|
|
1314
|
-
type: "audio",
|
|
1315
|
-
mime: parsed.mime,
|
|
1316
|
-
filename: audioAtt.filename,
|
|
1317
|
-
transcript: transcript || null,
|
|
1318
|
-
}];
|
|
1319
|
-
|
|
1320
|
-
const row = await persistChat(env, {
|
|
1321
|
-
userEmail,
|
|
1322
|
-
model: model.id,
|
|
1323
|
-
model_type: "stt",
|
|
1324
|
-
system_prompt: body.system_prompt ?? null,
|
|
1325
|
-
user_input: body.user_input || "(audio attachment)",
|
|
1326
|
-
output: transcript || "(empty transcript)",
|
|
1327
|
-
output_artifact: null,
|
|
1328
|
-
attachments: persistedAtt,
|
|
1329
|
-
tokens_in: null,
|
|
1330
|
-
tokens_out: null,
|
|
1331
|
-
latency_ms: latency,
|
|
1332
|
-
ai_gateway_log_id: viaDeepgram ? null : aiLogId(aiCtx),
|
|
1333
|
-
});
|
|
1334
|
-
|
|
1335
|
-
return json({
|
|
1336
|
-
id: row.id,
|
|
1337
|
-
created_at: row.created_at,
|
|
1338
|
-
model: model.id,
|
|
1339
|
-
model_type: "stt",
|
|
1340
|
-
output: transcript,
|
|
1341
|
-
output_artifact: null,
|
|
1342
|
-
latency_ms: latency,
|
|
1343
|
-
conversation_id: row.conversation_id,
|
|
1344
|
-
turn_index: 0,
|
|
1345
|
-
});
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
// Conversational STT (@cf/deepgram/flux) is handled by the SttSession Durable
|
|
1349
|
-
// Object (src/stt-session.ts), which the /api/stt/stream route forwards the WS
|
|
1350
|
-
// upgrade to. It bridges to flux and persists the final transcript to /history.
|
|
1351
|
-
|
|
1352
|
-
// ---------- Music generation (MiniMax via Unified Billing) ----------
|
|
1353
|
-
//
|
|
1354
|
-
// As of v0.12.0, music gen uses Cloudflare Workflows for durable execution.
|
|
1355
|
-
// The runMusic handler creates a LongRunWorkflow instance, persists its ID
|
|
1356
|
-
// on the chats row as job_id, and returns immediately. The workflow handles
|
|
1357
|
-
// the actual env.AI.run call (which blocks for ~30-90 seconds), downloads
|
|
1358
|
-
// the audio, uploads to R2, and finalizes the D1 row.
|
|
1359
|
-
//
|
|
1360
|
-
// User input maps to fields:
|
|
1361
|
-
// body.user_input -> "prompt" (style/mood description, ~10-300 chars)
|
|
1362
|
-
// body.system_prompt -> "lyrics" (optional, supports [Verse]/[Chorus] tags)
|
|
1363
|
-
|
|
1364
|
-
async function runMusic(
|
|
1365
|
-
request: Request,
|
|
1366
|
-
env: Env,
|
|
1367
|
-
ctx: ExecutionContext,
|
|
1368
|
-
model: ModelEntry,
|
|
1369
|
-
body: ChatRequest
|
|
1370
|
-
): Promise<Response> {
|
|
1371
|
-
// ctx unused now that we no longer schedule a waitUntil task; the workflow
|
|
1372
|
-
// owns the long-running work. Kept in signature for router compatibility.
|
|
1373
|
-
void ctx;
|
|
1374
|
-
const userEmail = await getUserEmail(request, env);
|
|
1375
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
|
|
1376
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1377
|
-
void ctxOrErr; // credentials validated; workflow loads them from D1 by userEmail
|
|
1378
|
-
const startedAt = new Date().toISOString();
|
|
1379
|
-
|
|
1380
|
-
const row = await persistChat(env, {
|
|
1381
|
-
userEmail,
|
|
1382
|
-
model: model.id,
|
|
1383
|
-
model_type: "music",
|
|
1384
|
-
system_prompt: body.system_prompt ?? null,
|
|
1385
|
-
user_input: body.user_input,
|
|
1386
|
-
output: "",
|
|
1387
|
-
output_artifact: null,
|
|
1388
|
-
attachments: [],
|
|
1389
|
-
tokens_in: null,
|
|
1390
|
-
tokens_out: null,
|
|
1391
|
-
latency_ms: 0,
|
|
1392
|
-
ai_gateway_log_id: null,
|
|
1393
|
-
status: "pending",
|
|
1394
|
-
job_id: null,
|
|
1395
|
-
job_provider: model.provider ?? null,
|
|
1396
|
-
job_error: null,
|
|
1397
|
-
job_started_at: startedAt,
|
|
1398
|
-
});
|
|
1399
|
-
|
|
1400
|
-
// Kick off the workflow. The instance ID is stored on the row so we can
|
|
1401
|
-
// look it up later for status/observability. If create() itself fails
|
|
1402
|
-
// (e.g., quota exceeded), fail the row synchronously so the client sees
|
|
1403
|
-
// an error rather than an indefinite pending state.
|
|
1404
|
-
// v0.62.0: MiniMax music-2.6 returns gateway error 7003 ("User Input
|
|
1405
|
-
// Error") when lyrics is empty or missing, even for instrumental
|
|
1406
|
-
// requests. Default to "[Instrumental]" - the model's own marker
|
|
1407
|
-
// syntax - so a caller that wants an instrumental track can omit the
|
|
1408
|
-
// system_prompt without their job failing seconds after submit. A
|
|
1409
|
-
// non-empty system_prompt (real lyrics) wins.
|
|
1410
|
-
const rawLyrics = (body.system_prompt ?? "").trim();
|
|
1411
|
-
const lyrics = rawLyrics.length > 0 ? body.system_prompt! : "[Instrumental]";
|
|
1412
|
-
|
|
1413
|
-
let instanceId: string;
|
|
1414
|
-
try {
|
|
1415
|
-
const instance = await env.LONGRUN.create({
|
|
1416
|
-
params: {
|
|
1417
|
-
rowId: row.id,
|
|
1418
|
-
userEmail,
|
|
1419
|
-
modelId: model.id,
|
|
1420
|
-
prompt: body.user_input,
|
|
1421
|
-
lyrics,
|
|
1422
|
-
kind: "music",
|
|
1423
|
-
startedAtIso: startedAt,
|
|
1424
|
-
} satisfies LongRunParams,
|
|
1425
|
-
});
|
|
1426
|
-
instanceId = instance.id;
|
|
1427
|
-
} catch (err) {
|
|
1428
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1429
|
-
await env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
|
|
1430
|
-
.bind(`Workflow create failed: ${m}`.slice(0, 1000), row.id)
|
|
1431
|
-
.run();
|
|
1432
|
-
return json({ error: `Failed to start music generation: ${m}` }, { status: 502 });
|
|
1433
|
-
}
|
|
1434
|
-
|
|
1435
|
-
// Persist the workflow instance ID on the row for traceability.
|
|
1436
|
-
await env.DB.prepare(`UPDATE chats SET job_id = ? WHERE id = ?`)
|
|
1437
|
-
.bind(instanceId, row.id)
|
|
1438
|
-
.run();
|
|
1439
|
-
|
|
1440
|
-
return json({
|
|
1441
|
-
id: row.id,
|
|
1442
|
-
created_at: row.created_at,
|
|
1443
|
-
model: model.id,
|
|
1444
|
-
model_type: "music",
|
|
1445
|
-
output: "",
|
|
1446
|
-
output_artifact: null,
|
|
1447
|
-
status: "pending",
|
|
1448
|
-
job_started_at: startedAt,
|
|
1449
|
-
job_id: instanceId,
|
|
1450
|
-
conversation_id: row.conversation_id,
|
|
1451
|
-
turn_index: 0,
|
|
1452
|
-
});
|
|
1453
|
-
}
|
|
1454
|
-
|
|
1455
|
-
// ---------- Persistence ----------
|
|
1456
|
-
|
|
1457
|
-
interface PersistArgs {
|
|
1458
|
-
userEmail: string;
|
|
1459
|
-
model: string;
|
|
1460
|
-
model_type: ModelType;
|
|
1461
|
-
system_prompt: string | null;
|
|
1462
|
-
user_input: string;
|
|
1463
|
-
output: string;
|
|
1464
|
-
output_artifact: OutputArtifact | null;
|
|
1465
|
-
attachments: PersistedAttachment[];
|
|
1466
|
-
tokens_in: number | null;
|
|
1467
|
-
tokens_out: number | null;
|
|
1468
|
-
latency_ms: number;
|
|
1469
|
-
ai_gateway_log_id: string | null;
|
|
1470
|
-
status?: "pending" | "done" | "failed";
|
|
1471
|
-
job_id?: string | null;
|
|
1472
|
-
job_provider?: string | null;
|
|
1473
|
-
job_error?: string | null;
|
|
1474
|
-
job_started_at?: string | null;
|
|
1475
|
-
retrieved_context?: RetrievedItem[] | null;
|
|
1476
|
-
conversation_id?: string | null;
|
|
1477
|
-
turn_index?: number | null;
|
|
1478
|
-
project_id?: number | null; // v0.20.2: project this chat turn was sent within
|
|
1479
|
-
}
|
|
1480
|
-
|
|
1481
|
-
async function persistChat(env: Env, a: PersistArgs): Promise<{ id: number; created_at: string; conversation_id: string }> {
|
|
1482
|
-
// For non-chat model types (image/tts/video/etc), conversation_id is
|
|
1483
|
-
// auto-assigned as a synthetic per-row key so the rows still group in the
|
|
1484
|
-
// sidebar as single-turn entries.
|
|
1485
|
-
const convId = a.conversation_id ?? null;
|
|
1486
|
-
const turnIdx = a.turn_index ?? null;
|
|
1487
|
-
|
|
1488
|
-
const row = await env.DB.prepare(
|
|
1489
|
-
`INSERT INTO chats
|
|
1490
|
-
(user_email, model, model_type, system_prompt, user_input, output,
|
|
1491
|
-
output_artifact, attachments,
|
|
1492
|
-
tokens_in, tokens_out, latency_ms, ai_gateway_log_id,
|
|
1493
|
-
status, job_id, job_provider, job_error, job_started_at,
|
|
1494
|
-
retrieved_context, conversation_id, turn_index, project_id)
|
|
1495
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1496
|
-
RETURNING id, created_at`
|
|
1497
|
-
)
|
|
1498
|
-
.bind(
|
|
1499
|
-
a.userEmail, a.model, a.model_type, a.system_prompt, a.user_input, a.output,
|
|
1500
|
-
a.output_artifact ? JSON.stringify(a.output_artifact) : null,
|
|
1501
|
-
a.attachments.length ? JSON.stringify(a.attachments) : null,
|
|
1502
|
-
a.tokens_in, a.tokens_out, a.latency_ms, a.ai_gateway_log_id,
|
|
1503
|
-
a.status ?? "done",
|
|
1504
|
-
a.job_id ?? null,
|
|
1505
|
-
a.job_provider ?? null,
|
|
1506
|
-
a.job_error ?? null,
|
|
1507
|
-
a.job_started_at ?? null,
|
|
1508
|
-
a.retrieved_context && a.retrieved_context.length ? JSON.stringify(a.retrieved_context) : null,
|
|
1509
|
-
convId,
|
|
1510
|
-
turnIdx,
|
|
1511
|
-
a.project_id ?? null
|
|
1512
|
-
)
|
|
1513
|
-
.first<{ id: number; created_at: string }>();
|
|
1514
|
-
|
|
1515
|
-
if (!row) {
|
|
1516
|
-
return { id: 0, created_at: new Date().toISOString(), conversation_id: "" };
|
|
1517
|
-
}
|
|
1518
|
-
|
|
1519
|
-
// For non-chat rows that didn't get an explicit conversation_id, backfill
|
|
1520
|
-
// a synthetic one so they appear in the conversation list.
|
|
1521
|
-
let finalConvId = convId;
|
|
1522
|
-
if (!finalConvId) {
|
|
1523
|
-
finalConvId = `single-${row.id}`;
|
|
1524
|
-
await env.DB.prepare(
|
|
1525
|
-
`UPDATE chats SET conversation_id = ?, turn_index = 0 WHERE id = ?`
|
|
1526
|
-
)
|
|
1527
|
-
.bind(finalConvId, row.id)
|
|
1528
|
-
.run();
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
return { id: row.id, created_at: row.created_at, conversation_id: finalConvId };
|
|
1532
|
-
}
|
|
1533
|
-
|
|
1534
|
-
// ---------- runChatStream (v0.13.0) ----------
|
|
1535
|
-
//
|
|
1536
|
-
// Streaming counterpart of runChat. Shares the prelude contract (parallel
|
|
1537
|
-
// hoisting of priorTurnsPromise + retrievePromise overlapping the attachment
|
|
1538
|
-
// walk; multi-turn continuation; RAG system-prompt assembly) and diverges
|
|
1539
|
-
// at the model call: each provider's stream adapter (callAnthropicStream
|
|
1540
|
-
// in src/providers/anthropic.ts, etc.) is an async generator that yields
|
|
1541
|
-
// normalized text deltas and usage events.
|
|
1542
|
-
//
|
|
1543
|
-
// Wire format on the response body (text/event-stream):
|
|
1544
|
-
// data: {"type":"delta","text":"..."}
|
|
1545
|
-
// data: {"type":"done","row_id":N,"latency_ms":N,"tokens_in":N|null,
|
|
1546
|
-
// "tokens_out":N|null,"conversation_id":"...","turn_index":N}
|
|
1547
|
-
// data: {"type":"error","message":"..."}
|
|
1548
|
-
//
|
|
1549
|
-
// Anthropic's native SSE event types (message_start, content_block_delta,
|
|
1550
|
-
// content_block_stop, message_delta, message_stop, ping, etc.) are stripped
|
|
1551
|
-
// inside callAnthropicStream and normalized to the envelope above.
|
|
1552
|
-
//
|
|
1553
|
-
// On client disconnect, the next writer.write() throws; we abort the
|
|
1554
|
-
// upstream Anthropic fetch via AbortController and exit without persisting
|
|
1555
|
-
// the partial response. Design decision B (Pass 1): drop partials.
|
|
1556
|
-
//
|
|
1557
|
-
// NOTE: the prelude here intentionally duplicates the prelude in runChat.
|
|
1558
|
-
// Both functions own the same shape but persist + respond differently. A
|
|
1559
|
-
// later pass may extract a shared helper; for Pass 1 the duplication is
|
|
1560
|
-
// bounded and easier to read than a parameterized abstraction.
|
|
1561
|
-
|
|
1562
|
-
async function runChatStream(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
|
|
1563
|
-
const userEmail = await getUserEmail(request, env);
|
|
1564
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
|
|
1565
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1566
|
-
const aiCtx = ctxOrErr;
|
|
1567
|
-
const inputs: InputAttachment[] = body.attachments ?? [];
|
|
1568
|
-
|
|
1569
|
-
// v0.20.0: same project resolution as runChat. See resolveProjectForChat
|
|
1570
|
-
// for semantics. Mutating body.system_prompt here means downstream code
|
|
1571
|
-
// (provider call, persistence) sees the effective prompt with no further
|
|
1572
|
-
// awareness of projects.
|
|
1573
|
-
const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
|
|
1574
|
-
body.system_prompt = resolvedSystemPrompt;
|
|
1575
|
-
|
|
1576
|
-
// Hot-path parallelization (mirrors runChat v0.12.1). Kick off SELECT +
|
|
1577
|
-
// RAG retrieve before the attachment walk; await at the existing use sites.
|
|
1578
|
-
const conversationIdIn = body.conversation_id?.trim() || "";
|
|
1579
|
-
const priorTurnsPromise: Promise<{
|
|
1580
|
-
rows: Array<{ user_input: string; output: string; turn_index: number }>;
|
|
1581
|
-
}> = conversationIdIn
|
|
1582
|
-
? env.DB.prepare(
|
|
1583
|
-
`SELECT user_input, output, turn_index
|
|
1584
|
-
FROM chats
|
|
1585
|
-
WHERE conversation_id = ?
|
|
1586
|
-
AND user_email = ?
|
|
1587
|
-
AND status = 'done'
|
|
1588
|
-
AND model_type = 'chat'
|
|
1589
|
-
ORDER BY turn_index ASC`
|
|
1590
|
-
)
|
|
1591
|
-
.bind(conversationIdIn, userEmail)
|
|
1592
|
-
.all<{ user_input: string; output: string; turn_index: number }>()
|
|
1593
|
-
.then((r) => ({ rows: r.results ?? [] }))
|
|
1594
|
-
: Promise.resolve({ rows: [] });
|
|
1595
|
-
|
|
1596
|
-
const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
|
|
1597
|
-
body.use_docs
|
|
1598
|
-
? retrieveContext(env, userEmail, body.user_input, RETRIEVE_TOP_K, scopedProjectId)
|
|
1599
|
-
: Promise.resolve({ chunks: [], error: null });
|
|
1600
|
-
|
|
1601
|
-
// v0.17.0: web search runs in parallel with RAG retrieval, same as runChat.
|
|
1602
|
-
const webSearchPromise: Promise<{ results: RetrievedWebResult[]; error: string | null }> =
|
|
1603
|
-
body.use_web_search
|
|
1604
|
-
? searchWeb(env, body.user_input)
|
|
1605
|
-
: Promise.resolve({ results: [], error: null });
|
|
1606
|
-
|
|
1607
|
-
// Attachment walk. Reach completion before any bytes flow back; streaming
|
|
1608
|
-
// helps with time-to-last-token, not time-to-first-token on multimodal turns.
|
|
1609
|
-
const extraText: string[] = [];
|
|
1610
|
-
const imageDataUrls: string[] = [];
|
|
1611
|
-
const persistedAtt: PersistedAttachment[] = [];
|
|
1612
|
-
|
|
1613
|
-
for (const att of inputs) {
|
|
1614
|
-
if (att.type === "image") {
|
|
1615
|
-
if (!model.capabilities.includes("vision")) {
|
|
1616
|
-
return json({ error: `Model ${model.id} does not support vision.` }, { status: 400 });
|
|
1617
|
-
}
|
|
1618
|
-
const parsed = att.data ? parseDataUrl(att.data) : null;
|
|
1619
|
-
if (!parsed) return json({ error: "Invalid image data URL" }, { status: 400 });
|
|
1620
|
-
const bytes = base64ToBytes(parsed.base64);
|
|
1621
|
-
const key = await r2Put(env, "in", parsed.mime, bytes, userEmail);
|
|
1622
|
-
imageDataUrls.push(att.data!); // guaranteed by the parsed guard above (data may be hydrated from a key)
|
|
1623
|
-
persistedAtt.push({ type: "image", key, mime: parsed.mime, filename: att.filename });
|
|
1624
|
-
} else if (att.type === "audio") {
|
|
1625
|
-
const parsed = att.data ? parseDataUrl(att.data) : null;
|
|
1626
|
-
if (!parsed) return json({ error: "Invalid audio data URL" }, { status: 400 });
|
|
1627
|
-
try {
|
|
1628
|
-
const wr = await aiRun(aiCtx, WHISPER_MODEL, { audio: parsed.base64 });
|
|
1629
|
-
const text = (wr as { text?: string })?.text?.trim() ?? "";
|
|
1630
|
-
const label = att.filename ? ` from ${att.filename}` : "";
|
|
1631
|
-
extraText.push(text
|
|
1632
|
-
? `[Transcribed audio${label}]\n${text}`
|
|
1633
|
-
: `[Audio attachment${label} transcribed to empty text]`);
|
|
1634
|
-
persistedAtt.push({ type: "audio", mime: parsed.mime, filename: att.filename, transcript: text || null });
|
|
1635
|
-
} catch (err) {
|
|
1636
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1637
|
-
return json({ error: `Audio transcription failed: ${m}` }, { status: 502 });
|
|
1638
|
-
}
|
|
1639
|
-
} else if (att.type === "video_frames") {
|
|
1640
|
-
if (!model.capabilities.includes("vision")) {
|
|
1641
|
-
return json({ error: `Model ${model.id} does not support vision.` }, { status: 400 });
|
|
1642
|
-
}
|
|
1643
|
-
const frames = att.frames ?? [];
|
|
1644
|
-
const parsedFrames = frames
|
|
1645
|
-
.map((fdataUrl) => ({ fdataUrl, parsed: parseDataUrl(fdataUrl) }))
|
|
1646
|
-
.filter((p): p is { fdataUrl: string; parsed: { mime: string; base64: string } } => p.parsed !== null);
|
|
1647
|
-
const keys = await Promise.all(
|
|
1648
|
-
parsedFrames.map(({ parsed }) =>
|
|
1649
|
-
r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail)
|
|
1650
|
-
)
|
|
1651
|
-
);
|
|
1652
|
-
for (const { fdataUrl } of parsedFrames) {
|
|
1653
|
-
imageDataUrls.push(fdataUrl);
|
|
1654
|
-
}
|
|
1655
|
-
const dur = att.duration ? ` ${att.duration.toFixed(1)}s` : "";
|
|
1656
|
-
const fn = att.filename ? ` "${att.filename}"` : "";
|
|
1657
|
-
extraText.push(`[Video${fn}${dur}, ${frames.length} evenly-sampled frames attached below]`);
|
|
1658
|
-
persistedAtt.push({ type: "video_frames", keys, frame_count: keys.length, duration: att.duration, filename: att.filename });
|
|
1659
|
-
} else if (att.type === "video_full") {
|
|
1660
|
-
// No streaming model accepts raw video; reject explicitly so the user
|
|
1661
|
-
// attaches extracted frames instead of getting silent truncation.
|
|
1662
|
-
return json({ error: "Raw video attachments are not accepted on the streaming path. Attach extracted frames instead." }, { status: 400 });
|
|
1663
|
-
} else if (att.type === "document") {
|
|
1664
|
-
const r = buildDocumentAttachment(att);
|
|
1665
|
-
if ("error" in r) return json({ error: r.error }, { status: 400 });
|
|
1666
|
-
extraText.push(r.extra);
|
|
1667
|
-
persistedAtt.push(r.persisted);
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
|
|
1671
|
-
const userText = [body.user_input, ...extraText].filter(Boolean).join("\n\n");
|
|
1672
|
-
const userContent: unknown = imageDataUrls.length
|
|
1673
|
-
? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
|
|
1674
|
-
: userText;
|
|
1675
|
-
|
|
1676
|
-
// Consume the parallel-hoisted promises.
|
|
1677
|
-
let conversationId = conversationIdIn;
|
|
1678
|
-
let turnIndex = 0;
|
|
1679
|
-
const priorTurns: Array<{ user_input: string; output: string }> = [];
|
|
1680
|
-
|
|
1681
|
-
if (conversationId) {
|
|
1682
|
-
const { rows } = await priorTurnsPromise;
|
|
1683
|
-
for (const r of rows) {
|
|
1684
|
-
if (r.user_input && r.output) {
|
|
1685
|
-
priorTurns.push({ user_input: r.user_input, output: r.output });
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
|
|
1689
|
-
} else {
|
|
1690
|
-
conversationId = crypto.randomUUID();
|
|
1691
|
-
}
|
|
1692
|
-
|
|
1693
|
-
const { chunks: retrievedChunks } = await retrievePromise;
|
|
1694
|
-
const { results: webResults } = await webSearchPromise;
|
|
1695
|
-
const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
|
|
1696
|
-
|
|
1697
|
-
const userSystemPrompt = body.system_prompt?.trim() ?? "";
|
|
1698
|
-
const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
|
|
1699
|
-
const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
|
|
1700
|
-
const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
|
|
1701
|
-
.filter(Boolean)
|
|
1702
|
-
.join("\n\n");
|
|
1703
|
-
|
|
1704
|
-
// Build the message array. For providers that take system as a separate
|
|
1705
|
-
// top-level param (Anthropic), we DON'T include a system role here;
|
|
1706
|
-
// callAnthropicStream pulls effectiveSystemPrompt to a top-level field.
|
|
1707
|
-
// For Workers AI (and any future provider that accepts role:"system" in
|
|
1708
|
-
// messages, like xAI's OpenAI-compatible API), we DO push it.
|
|
1709
|
-
const wantsSystemInMessages = !(model.provider === "anthropic");
|
|
1710
|
-
const messages: Array<unknown> = [];
|
|
1711
|
-
if (effectiveSystemPrompt && wantsSystemInMessages) {
|
|
1712
|
-
messages.push({ role: "system", content: effectiveSystemPrompt });
|
|
1713
|
-
}
|
|
1714
|
-
for (const t of priorTurns) {
|
|
1715
|
-
messages.push({ role: "user", content: t.user_input });
|
|
1716
|
-
messages.push({ role: "assistant", content: t.output });
|
|
1717
|
-
}
|
|
1718
|
-
messages.push({ role: "user", content: userContent });
|
|
1719
|
-
|
|
1720
|
-
// TransformStream pattern: return `readable` as the response body, write
|
|
1721
|
-
// SSE events to `writer`. The worker stays alive while writer is open, so
|
|
1722
|
-
// the background IIFE doesn't need ctx.waitUntil.
|
|
1723
|
-
const { readable, writable } = new TransformStream();
|
|
1724
|
-
const writer = writable.getWriter();
|
|
1725
|
-
const encoder = new TextEncoder();
|
|
1726
|
-
|
|
1727
|
-
// Emit one SSE event. Returns false if the writer is closed (client
|
|
1728
|
-
// disconnected); caller uses this to short-circuit + abort upstream.
|
|
1729
|
-
const emit = async (event: Record<string, unknown>): Promise<boolean> => {
|
|
1730
|
-
try {
|
|
1731
|
-
await writer.write(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
|
1732
|
-
return true;
|
|
1733
|
-
} catch {
|
|
1734
|
-
return false;
|
|
1735
|
-
}
|
|
1736
|
-
};
|
|
1737
|
-
|
|
1738
|
-
const upstreamAbort = new AbortController();
|
|
1739
|
-
const start = Date.now();
|
|
1740
|
-
|
|
1741
|
-
// Background IIFE drives the stream. Does NOT await; this function returns
|
|
1742
|
-
// the Response immediately while the IIFE writes events to the body.
|
|
1743
|
-
(async () => {
|
|
1744
|
-
let accumulated = "";
|
|
1745
|
-
let usageIn: number | null = null;
|
|
1746
|
-
let usageOut: number | null = null;
|
|
1747
|
-
|
|
1748
|
-
try {
|
|
1749
|
-
// Dispatch per provider. All generators yield the same ProviderStreamEvent
|
|
1750
|
-
// shape so the consumer loop is provider-agnostic.
|
|
1751
|
-
let streamGenerator: AsyncGenerator<ProviderStreamEvent>;
|
|
1752
|
-
if (model.provider === "anthropic") {
|
|
1753
|
-
streamGenerator = callAnthropicStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
|
|
1754
|
-
} else if (model.provider === "xai") {
|
|
1755
|
-
streamGenerator = callXaiStream(aiCtx, model, messages, upstreamAbort.signal);
|
|
1756
|
-
} else if (model.provider === "openai") {
|
|
1757
|
-
streamGenerator = callOpenAIStream(aiCtx, model, messages, upstreamAbort.signal);
|
|
1758
|
-
} else if (model.provider === "google") {
|
|
1759
|
-
streamGenerator = callGeminiStream(aiCtx, model, effectiveSystemPrompt || undefined, messages, upstreamAbort.signal);
|
|
1760
|
-
} else {
|
|
1761
|
-
streamGenerator = callWorkersAIStream(aiCtx, model, messages, upstreamAbort.signal);
|
|
1762
|
-
}
|
|
1763
|
-
|
|
1764
|
-
for await (const ev of streamGenerator) {
|
|
1765
|
-
if (ev.type === "text") {
|
|
1766
|
-
accumulated += ev.text;
|
|
1767
|
-
const ok = await emit({ type: "delta", text: ev.text });
|
|
1768
|
-
if (!ok) {
|
|
1769
|
-
// Client gone. Abort upstream so we stop paying for tokens
|
|
1770
|
-
// and exit without persisting (Pass 1: drop partials).
|
|
1771
|
-
upstreamAbort.abort();
|
|
1772
|
-
return;
|
|
1773
|
-
}
|
|
1774
|
-
} else if (ev.type === "usage") {
|
|
1775
|
-
if (ev.in_ !== null) usageIn = ev.in_;
|
|
1776
|
-
if (ev.out_ !== null) usageOut = ev.out_;
|
|
1777
|
-
}
|
|
1778
|
-
}
|
|
1779
|
-
|
|
1780
|
-
const latency = Date.now() - start;
|
|
1781
|
-
|
|
1782
|
-
// Persist as a single row. retrieved_context is saved on the row so
|
|
1783
|
-
// the History/Conversation views render citations the same way runChat
|
|
1784
|
-
// does. v0.17.0: web-search results are stored in the same column with
|
|
1785
|
-
// a source_type discriminator. ai_gateway_log_id is null: streaming
|
|
1786
|
-
// responses from AI Gateway don't surface cf-aig-log-id on the proxied
|
|
1787
|
-
// SSE response.
|
|
1788
|
-
const row = await persistChat(env, {
|
|
1789
|
-
userEmail,
|
|
1790
|
-
model: model.id,
|
|
1791
|
-
model_type: "chat",
|
|
1792
|
-
system_prompt: body.system_prompt ?? null,
|
|
1793
|
-
user_input: body.user_input,
|
|
1794
|
-
output: accumulated,
|
|
1795
|
-
output_artifact: null,
|
|
1796
|
-
attachments: persistedAtt,
|
|
1797
|
-
tokens_in: usageIn,
|
|
1798
|
-
tokens_out: usageOut,
|
|
1799
|
-
latency_ms: latency,
|
|
1800
|
-
ai_gateway_log_id: null,
|
|
1801
|
-
retrieved_context: allRetrieved.length ? allRetrieved : null,
|
|
1802
|
-
conversation_id: conversationId,
|
|
1803
|
-
turn_index: turnIndex,
|
|
1804
|
-
project_id: scopedProjectId ?? null,
|
|
1805
|
-
});
|
|
1806
|
-
|
|
1807
|
-
await emit({
|
|
1808
|
-
type: "done",
|
|
1809
|
-
row_id: row.id,
|
|
1810
|
-
latency_ms: latency,
|
|
1811
|
-
tokens_in: usageIn,
|
|
1812
|
-
tokens_out: usageOut,
|
|
1813
|
-
conversation_id: conversationId,
|
|
1814
|
-
turn_index: turnIndex,
|
|
1815
|
-
});
|
|
1816
|
-
} catch (err) {
|
|
1817
|
-
// Self-triggered AbortError (we aborted because client disconnected)
|
|
1818
|
-
// is expected; suppress it. Anything else is surfaced to the client
|
|
1819
|
-
// as a terminal error event.
|
|
1820
|
-
if (err instanceof Error && err.name === "AbortError") return;
|
|
1821
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1822
|
-
await emit({ type: "error", message: m });
|
|
1823
|
-
} finally {
|
|
1824
|
-
try { await writer.close(); } catch { /* writer may already be closed */ }
|
|
1825
|
-
}
|
|
1826
|
-
})();
|
|
1827
|
-
|
|
1828
|
-
return new Response(readable, {
|
|
1829
|
-
headers: {
|
|
1830
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
1831
|
-
"cache-control": "no-cache, no-transform",
|
|
1832
|
-
// Disable any in-path buffering. Cloudflare doesn't buffer streaming
|
|
1833
|
-
// responses but downstream proxies (Nginx etc.) might; this is the
|
|
1834
|
-
// standard hint to flush per-event.
|
|
1835
|
-
"x-accel-buffering": "no",
|
|
1836
|
-
},
|
|
1837
|
-
});
|
|
1838
|
-
}
|
|
1839
|
-
|
|
1840
|
-
// ---------- Video generation (Unified Billing via env.AI.run) ----------
|
|
1841
|
-
//
|
|
1842
|
-
// As of Cloudflare Agents Week 2026 (April 2026), the AI Gateway and Workers
|
|
1843
|
-
// AI are unified. Third-party video models are callable via env.AI.run with
|
|
1844
|
-
// model strings like "google/veo-3.1-fast" or "xai/grok-imagine-video".
|
|
1845
|
-
// Cloudflare bills your account directly under Unified Billing. See:
|
|
1846
|
-
// https://developers.cloudflare.com/ai-gateway/features/unified-billing/
|
|
1847
|
-
// https://developers.cloudflare.com/ai/models/google/veo-3.1-fast/
|
|
1848
|
-
//
|
|
1849
|
-
// Video gen takes 30s-3min. env.AI.run for these models blocks until
|
|
1850
|
-
// completion, which exceeds the ~30s waitUntil budget after an HTTP response.
|
|
1851
|
-
// Cloudflare Workflows (v0.12.0+): the runVideo handler creates a
|
|
1852
|
-
// LongRunWorkflow instance, persists its ID on the row, and returns
|
|
1853
|
-
// immediately. The workflow class holds the long blocking env.AI.run call
|
|
1854
|
-
// alive across step boundaries, then downloads and finalizes D1.
|
|
1855
|
-
//
|
|
1856
|
-
// The frontend polls /api/job/:id for status (reads D1 only; the workflow
|
|
1857
|
-
// updates the row when done).
|
|
1858
|
-
|
|
1859
|
-
async function runVideo(
|
|
1860
|
-
request: Request,
|
|
1861
|
-
env: Env,
|
|
1862
|
-
ctx: ExecutionContext,
|
|
1863
|
-
model: ModelEntry,
|
|
1864
|
-
body: ChatRequest
|
|
1865
|
-
): Promise<Response> {
|
|
1866
|
-
void ctx;
|
|
1867
|
-
const userEmail = await getUserEmail(request, env);
|
|
1868
|
-
const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: modelNeedsCfAigToken(model) });
|
|
1869
|
-
if (ctxOrErr instanceof Response) return ctxOrErr;
|
|
1870
|
-
void ctxOrErr; // credentials validated; workflow loads them from D1 by userEmail
|
|
1871
|
-
const startedAt = new Date().toISOString();
|
|
1872
|
-
|
|
1873
|
-
// Image-to-video models (e.g. alibaba/hh1-i2v, flagged "image-input") need a
|
|
1874
|
-
// source image (v0.21.6). Three sources, resolved into one of two workflow
|
|
1875
|
-
// params: an uploaded attachment or an R2 key (image_key, e.g. a prior
|
|
1876
|
-
// nano-banana output for chaining) -> `imageKey`, resolved to a data: URI in
|
|
1877
|
-
// the workflow; a fetchable external URL (image_url) -> `imageUrl`, passed
|
|
1878
|
-
// through. Uploads are stored to R2 here so the (potentially multi-MB) image
|
|
1879
|
-
// doesn't ride the Workflow event payload (~1 MiB cap); the small key does.
|
|
1880
|
-
const needsImage = model.capabilities.includes("image-input");
|
|
1881
|
-
let srcImageKey: string | undefined;
|
|
1882
|
-
let srcImageUrl: string | undefined;
|
|
1883
|
-
if (needsImage) {
|
|
1884
|
-
const imgAtt = (body.attachments ?? []).find((a) => a.type === "image" && a.data);
|
|
1885
|
-
if (imgAtt && imgAtt.type === "image" && imgAtt.data) {
|
|
1886
|
-
const parsed = parseDataUrl(imgAtt.data);
|
|
1887
|
-
if (!parsed) {
|
|
1888
|
-
return json({ error: "Attached image is not a base64 data URL." }, { status: 400 });
|
|
1889
|
-
}
|
|
1890
|
-
srcImageKey = await r2Put(env, "in", parsed.mime, base64ToBytes(parsed.base64), userEmail);
|
|
1891
|
-
} else if (body.image_key && body.image_key.trim()) {
|
|
1892
|
-
srcImageKey = body.image_key.trim();
|
|
1893
|
-
} else if (body.image_url && body.image_url.trim()) {
|
|
1894
|
-
srcImageUrl = body.image_url.trim();
|
|
1895
|
-
} else {
|
|
1896
|
-
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 });
|
|
1897
|
-
}
|
|
1898
|
-
}
|
|
1899
|
-
|
|
1900
|
-
const row = await persistChat(env, {
|
|
1901
|
-
userEmail,
|
|
1902
|
-
model: model.id,
|
|
1903
|
-
model_type: "video",
|
|
1904
|
-
system_prompt: body.system_prompt ?? null,
|
|
1905
|
-
user_input: body.user_input,
|
|
1906
|
-
output: "",
|
|
1907
|
-
output_artifact: null,
|
|
1908
|
-
attachments: [],
|
|
1909
|
-
tokens_in: null,
|
|
1910
|
-
tokens_out: null,
|
|
1911
|
-
latency_ms: 0,
|
|
1912
|
-
ai_gateway_log_id: null,
|
|
1913
|
-
status: "pending",
|
|
1914
|
-
job_id: null,
|
|
1915
|
-
job_provider: model.provider ?? null,
|
|
1916
|
-
job_error: null,
|
|
1917
|
-
job_started_at: startedAt,
|
|
1918
|
-
});
|
|
1919
|
-
|
|
1920
|
-
let instanceId: string;
|
|
1921
|
-
try {
|
|
1922
|
-
const instance = await env.LONGRUN.create({
|
|
1923
|
-
params: {
|
|
1924
|
-
rowId: row.id,
|
|
1925
|
-
userEmail,
|
|
1926
|
-
modelId: model.id,
|
|
1927
|
-
prompt: body.user_input,
|
|
1928
|
-
imageUrl: srcImageUrl,
|
|
1929
|
-
imageKey: srcImageKey,
|
|
1930
|
-
kind: "video",
|
|
1931
|
-
startedAtIso: startedAt,
|
|
1932
|
-
} satisfies LongRunParams,
|
|
1933
|
-
});
|
|
1934
|
-
instanceId = instance.id;
|
|
1935
|
-
} catch (err) {
|
|
1936
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
1937
|
-
await env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
|
|
1938
|
-
.bind(`Workflow create failed: ${m}`.slice(0, 1000), row.id)
|
|
1939
|
-
.run();
|
|
1940
|
-
return json({ error: `Failed to start video generation: ${m}` }, { status: 502 });
|
|
1941
|
-
}
|
|
1942
|
-
|
|
1943
|
-
// Persist the workflow instance ID on the row for traceability.
|
|
1944
|
-
await env.DB.prepare(`UPDATE chats SET job_id = ? WHERE id = ?`)
|
|
1945
|
-
.bind(instanceId, row.id)
|
|
1946
|
-
.run();
|
|
1947
|
-
|
|
1948
|
-
return json({
|
|
1949
|
-
id: row.id,
|
|
1950
|
-
created_at: row.created_at,
|
|
1951
|
-
model: model.id,
|
|
1952
|
-
model_type: "video",
|
|
1953
|
-
output: "",
|
|
1954
|
-
output_artifact: null,
|
|
1955
|
-
status: "pending",
|
|
1956
|
-
job_started_at: startedAt,
|
|
1957
|
-
job_id: instanceId,
|
|
1958
|
-
conversation_id: row.conversation_id,
|
|
1959
|
-
turn_index: 0,
|
|
1960
|
-
});
|
|
1961
|
-
}
|
|
1962
|
-
|
|
1963
|
-
// ---------- Job polling endpoint ----------
|
|
1964
|
-
//
|
|
1965
|
-
// Reflects the current D1 row state. Long-running video/music jobs are owned
|
|
1966
|
-
// by LongRunWorkflow instances, which update the row when they finish.
|
|
1967
|
-
|
|
1968
|
-
async function handleJobPoll(request: Request, env: Env, id: number): Promise<Response> {
|
|
1969
|
-
const userEmail = await getUserEmail(request, env);
|
|
1970
|
-
|
|
1971
|
-
const row = await env.DB.prepare(
|
|
1972
|
-
`SELECT id, status, job_error, job_started_at, output_artifact, latency_ms,
|
|
1973
|
-
job_id, job_provider, model_type
|
|
1974
|
-
FROM chats
|
|
1975
|
-
WHERE id = ? AND user_email = ?`
|
|
1976
|
-
)
|
|
1977
|
-
.bind(id, userEmail)
|
|
1978
|
-
.first<{
|
|
1979
|
-
id: number;
|
|
1980
|
-
status: string;
|
|
1981
|
-
job_error: string | null;
|
|
1982
|
-
job_started_at: string | null;
|
|
1983
|
-
output_artifact: string | null;
|
|
1984
|
-
latency_ms: number | null;
|
|
1985
|
-
job_id: string | null;
|
|
1986
|
-
job_provider: string | null;
|
|
1987
|
-
model_type: string;
|
|
1988
|
-
}>();
|
|
1989
|
-
|
|
1990
|
-
if (!row) return json({ error: "Not found" }, { status: 404 });
|
|
1991
|
-
|
|
1992
|
-
// Terminal states return immediately.
|
|
1993
|
-
if (row.status === "done") {
|
|
1994
|
-
return json({
|
|
1995
|
-
id: row.id,
|
|
1996
|
-
status: "done",
|
|
1997
|
-
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
1998
|
-
latency_ms: row.latency_ms,
|
|
1999
|
-
});
|
|
2000
|
-
}
|
|
2001
|
-
if (row.status === "failed") {
|
|
2002
|
-
return json({ id: row.id, status: "failed", job_error: row.job_error });
|
|
2003
|
-
}
|
|
2004
|
-
|
|
2005
|
-
// Pending (Unified Billing video/music via LongRunWorkflow). The workflow
|
|
2006
|
-
// updates D1 when its work completes; this endpoint just reflects current
|
|
2007
|
-
// row state.
|
|
2008
|
-
return json({ id: row.id, status: "pending" });
|
|
2009
|
-
}
|
|
2010
|
-
|
|
2011
|
-
// ---------- Output extraction (text models) ----------
|
|
2012
|
-
// extractOutput / extractUsage moved to src/output-extract.ts (v0.21.0) so
|
|
2013
|
-
// they can be unit-tested without importing index.ts. Imported at the top.
|
|
2014
|
-
|
|
2015
|
-
// ---------- History ----------
|
|
2016
|
-
|
|
2017
|
-
async function handleHistoryList(request: Request, env: Env): Promise<Response> {
|
|
2018
|
-
const userEmail = await getUserEmail(request, env);
|
|
2019
|
-
const url = new URL(request.url);
|
|
2020
|
-
const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 200);
|
|
2021
|
-
|
|
2022
|
-
const rows = await env.DB.prepare(
|
|
2023
|
-
`SELECT id, created_at, model, model_type, system_prompt, user_input, output,
|
|
2024
|
-
tokens_in, tokens_out, latency_ms, status,
|
|
2025
|
-
CASE WHEN attachments IS NOT NULL THEN 1 ELSE 0 END AS has_attachments,
|
|
2026
|
-
CASE WHEN output_artifact IS NOT NULL THEN 1 ELSE 0 END AS has_output_artifact
|
|
2027
|
-
FROM chats
|
|
2028
|
-
WHERE user_email = ?
|
|
2029
|
-
ORDER BY created_at DESC
|
|
2030
|
-
LIMIT ?`
|
|
2031
|
-
)
|
|
2032
|
-
.bind(userEmail, limit)
|
|
2033
|
-
.all();
|
|
2034
|
-
|
|
2035
|
-
return json({ user: userEmail, chats: rows.results ?? [] });
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
|
-
async function handleHistoryGet(request: Request, env: Env, id: number): Promise<Response> {
|
|
2039
|
-
const userEmail = await getUserEmail(request, env);
|
|
2040
|
-
const row = await env.DB.prepare(
|
|
2041
|
-
`SELECT * FROM chats WHERE id = ? AND user_email = ?`
|
|
2042
|
-
)
|
|
2043
|
-
.bind(id, userEmail)
|
|
2044
|
-
.first<{ attachments: string | null; output_artifact: string | null; retrieved_context: string | null }>();
|
|
2045
|
-
|
|
2046
|
-
if (!row) return json({ error: "Not found" }, { status: 404 });
|
|
2047
|
-
|
|
2048
|
-
return json({
|
|
2049
|
-
...row,
|
|
2050
|
-
attachments: row.attachments ? safeParseJson<PersistedAttachment[]>(row.attachments) : null,
|
|
2051
|
-
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
2052
|
-
retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
|
|
2053
|
-
});
|
|
2054
|
-
}
|
|
2055
|
-
|
|
2056
|
-
function safeParseJson<T>(s: string): T | null {
|
|
2057
|
-
try { return JSON.parse(s) as T; } catch { return null; }
|
|
2058
|
-
}
|
|
2059
|
-
|
|
2060
|
-
// ---------- Multi-turn conversations ----------
|
|
2061
|
-
//
|
|
2062
|
-
// A conversation is a set of chat rows sharing the same conversation_id,
|
|
2063
|
-
// ordered by turn_index. Old single-turn chats with NULL conversation_id
|
|
2064
|
-
// were backfilled in the migration to 'legacy-<id>' so they still appear
|
|
2065
|
-
// in the list. Non-chat rows (image/tts/etc) get 'single-<id>' assigned
|
|
2066
|
-
// at persistChat time and show as single-turn entries.
|
|
2067
|
-
//
|
|
2068
|
-
// handleConversationList returns one row per distinct conversation_id with
|
|
2069
|
-
// a summary: turn count, first prompt, latest model, last activity. Used
|
|
2070
|
-
// by the sidebar as the replacement for the per-row history list.
|
|
2071
|
-
//
|
|
2072
|
-
// handleConversationGet returns all rows of a conversation in turn order.
|
|
2073
|
-
// Used when the user clicks a conversation to view the full transcript.
|
|
2074
|
-
|
|
2075
|
-
async function handleConversationList(request: Request, env: Env): Promise<Response> {
|
|
2076
|
-
const userEmail = await getUserEmail(request, env);
|
|
2077
|
-
|
|
2078
|
-
// Group by conversation_id. For each, give:
|
|
2079
|
-
// - turn_count, first/last timestamps
|
|
2080
|
-
// - the first user_input as a preview
|
|
2081
|
-
// - the model used in the latest turn
|
|
2082
|
-
// - whether any turn has a non-null output_artifact (for the icon)
|
|
2083
|
-
// - the model_type of the first turn (chat/image/tts/video/music/stt)
|
|
2084
|
-
// - v0.20.2: project_id from the conversation's first turn (the sidebar
|
|
2085
|
-
// shows a project chip when this is set). project_id is a per-row
|
|
2086
|
-
// column but conversations are expected to have a uniform value
|
|
2087
|
-
// across turns (handleConversationMoveToProject updates all turns
|
|
2088
|
-
// atomically). Subqueries match the existing pattern for first_input.
|
|
2089
|
-
const rows = await env.DB.prepare(
|
|
2090
|
-
`SELECT
|
|
2091
|
-
c.conversation_id,
|
|
2092
|
-
COUNT(*) AS turn_count,
|
|
2093
|
-
MIN(c.created_at) AS first_created_at,
|
|
2094
|
-
MAX(c.created_at) AS last_created_at,
|
|
2095
|
-
(SELECT user_input FROM chats c2
|
|
2096
|
-
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
2097
|
-
ORDER BY c2.turn_index ASC LIMIT 1) AS first_input,
|
|
2098
|
-
(SELECT model FROM chats c2
|
|
2099
|
-
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
2100
|
-
ORDER BY c2.turn_index DESC LIMIT 1) AS latest_model,
|
|
2101
|
-
(SELECT model_type FROM chats c2
|
|
2102
|
-
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
2103
|
-
ORDER BY c2.turn_index ASC LIMIT 1) AS first_model_type,
|
|
2104
|
-
(SELECT project_id FROM chats c2
|
|
2105
|
-
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
2106
|
-
ORDER BY c2.turn_index ASC LIMIT 1) AS project_id,
|
|
2107
|
-
SUM(CASE WHEN output_artifact IS NOT NULL THEN 1 ELSE 0 END) AS artifact_count
|
|
2108
|
-
FROM chats c
|
|
2109
|
-
WHERE c.user_email = ?
|
|
2110
|
-
GROUP BY c.conversation_id
|
|
2111
|
-
ORDER BY last_created_at DESC
|
|
2112
|
-
LIMIT 200`
|
|
2113
|
-
)
|
|
2114
|
-
.bind(userEmail)
|
|
2115
|
-
.all<{
|
|
2116
|
-
conversation_id: string;
|
|
2117
|
-
turn_count: number;
|
|
2118
|
-
first_created_at: string;
|
|
2119
|
-
last_created_at: string;
|
|
2120
|
-
first_input: string;
|
|
2121
|
-
latest_model: string;
|
|
2122
|
-
first_model_type: string;
|
|
2123
|
-
project_id: number | null;
|
|
2124
|
-
artifact_count: number;
|
|
2125
|
-
}>();
|
|
2126
|
-
return json({ user: userEmail, conversations: rows.results ?? [] });
|
|
2127
|
-
}
|
|
2128
|
-
|
|
2129
|
-
async function handleConversationGet(request: Request, env: Env, id: string): Promise<Response> {
|
|
2130
|
-
const userEmail = await getUserEmail(request, env);
|
|
2131
|
-
const rows = await env.DB.prepare(
|
|
2132
|
-
`SELECT * FROM chats
|
|
2133
|
-
WHERE conversation_id = ? AND user_email = ?
|
|
2134
|
-
ORDER BY turn_index ASC, created_at ASC`
|
|
2135
|
-
)
|
|
2136
|
-
.bind(id, userEmail)
|
|
2137
|
-
.all<{
|
|
2138
|
-
attachments: string | null;
|
|
2139
|
-
output_artifact: string | null;
|
|
2140
|
-
retrieved_context: string | null;
|
|
2141
|
-
}>();
|
|
2142
|
-
|
|
2143
|
-
if ((rows.results ?? []).length === 0) {
|
|
2144
|
-
return json({ error: "Not found" }, { status: 404 });
|
|
2145
|
-
}
|
|
2146
|
-
|
|
2147
|
-
// Parse the JSON columns on each turn so the frontend doesn't have to.
|
|
2148
|
-
const turns = (rows.results ?? []).map((row) => ({
|
|
2149
|
-
...row,
|
|
2150
|
-
attachments: row.attachments ? safeParseJson<PersistedAttachment[]>(row.attachments) : null,
|
|
2151
|
-
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
2152
|
-
retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
|
|
2153
|
-
}));
|
|
2154
|
-
|
|
2155
|
-
return json({ conversation_id: id, turns });
|
|
2156
|
-
}
|
|
2157
|
-
|
|
2158
|
-
async function handleConversationDelete(request: Request, env: Env, id: string): Promise<Response> {
|
|
2159
|
-
const userEmail = await getUserEmail(request, env);
|
|
2160
|
-
|
|
2161
|
-
// Pull all R2 keys across all turns before deleting D1 rows.
|
|
2162
|
-
const rows = await env.DB.prepare(
|
|
2163
|
-
`SELECT attachments, output_artifact FROM chats
|
|
2164
|
-
WHERE conversation_id = ? AND user_email = ?`
|
|
2165
|
-
)
|
|
2166
|
-
.bind(id, userEmail)
|
|
2167
|
-
.all<{ attachments: string | null; output_artifact: string | null }>();
|
|
2168
|
-
|
|
2169
|
-
const results = rows.results ?? [];
|
|
2170
|
-
if (results.length === 0) {
|
|
2171
|
-
return json({ error: "Not found" }, { status: 404 });
|
|
2172
|
-
}
|
|
2173
|
-
|
|
2174
|
-
const keysToDelete: string[] = [];
|
|
2175
|
-
for (const row of results) {
|
|
2176
|
-
if (row.attachments) {
|
|
2177
|
-
const atts = safeParseJson<PersistedAttachment[]>(row.attachments) ?? [];
|
|
2178
|
-
for (const a of atts) {
|
|
2179
|
-
if (a.type === "image") keysToDelete.push(a.key);
|
|
2180
|
-
else if (a.type === "video_frames") keysToDelete.push(...(a.keys ?? []));
|
|
2181
|
-
else if (a.type === "video_full") keysToDelete.push(a.key);
|
|
2182
|
-
}
|
|
2183
|
-
}
|
|
2184
|
-
if (row.output_artifact) {
|
|
2185
|
-
const oa = safeParseJson<OutputArtifact>(row.output_artifact);
|
|
2186
|
-
if (oa?.key) keysToDelete.push(oa.key);
|
|
2187
|
-
}
|
|
2188
|
-
}
|
|
2189
|
-
|
|
2190
|
-
await env.DB.prepare(
|
|
2191
|
-
`DELETE FROM chats WHERE conversation_id = ? AND user_email = ?`
|
|
2192
|
-
)
|
|
2193
|
-
.bind(id, userEmail)
|
|
2194
|
-
.run();
|
|
2195
|
-
|
|
2196
|
-
for (const k of keysToDelete) {
|
|
2197
|
-
await r2DeleteSafe(env, k);
|
|
2198
|
-
}
|
|
2199
|
-
|
|
2200
|
-
return json({ deleted: id, turns_removed: results.length, artifacts_removed: keysToDelete.length });
|
|
2201
|
-
}
|
|
2202
|
-
|
|
2203
|
-
async function handleHistoryDelete(request: Request, env: Env, id: number): Promise<Response> {
|
|
2204
|
-
const userEmail = await getUserEmail(request, env);
|
|
2205
|
-
|
|
2206
|
-
// Pull keys first so we can clean up R2.
|
|
2207
|
-
const row = await env.DB.prepare(
|
|
2208
|
-
`SELECT attachments, output_artifact FROM chats WHERE id = ? AND user_email = ?`
|
|
2209
|
-
)
|
|
2210
|
-
.bind(id, userEmail)
|
|
2211
|
-
.first<{ attachments: string | null; output_artifact: string | null }>();
|
|
2212
|
-
|
|
2213
|
-
if (!row) return json({ error: "Not found" }, { status: 404 });
|
|
2214
|
-
|
|
2215
|
-
const keysToDelete: string[] = [];
|
|
2216
|
-
if (row.attachments) {
|
|
2217
|
-
const atts = safeParseJson<PersistedAttachment[]>(row.attachments) ?? [];
|
|
2218
|
-
for (const a of atts) {
|
|
2219
|
-
if (a.type === "image") keysToDelete.push(a.key);
|
|
2220
|
-
else if (a.type === "video_frames") keysToDelete.push(...(a.keys ?? []));
|
|
2221
|
-
else if (a.type === "video_full") keysToDelete.push(a.key);
|
|
2222
|
-
// audio has no R2 reference
|
|
2223
|
-
}
|
|
2224
|
-
}
|
|
2225
|
-
if (row.output_artifact) {
|
|
2226
|
-
const oa = safeParseJson<OutputArtifact>(row.output_artifact);
|
|
2227
|
-
if (oa?.key) keysToDelete.push(oa.key);
|
|
2228
|
-
}
|
|
2229
|
-
|
|
2230
|
-
// Delete from D1 first; if it succeeds, clean R2. (If R2 cleanup fails the
|
|
2231
|
-
// row is already gone, so worst case we have orphaned objects, which is
|
|
2232
|
-
// fine for occasional manual cleanup.)
|
|
2233
|
-
const result = await env.DB.prepare(
|
|
2234
|
-
`DELETE FROM chats WHERE id = ? AND user_email = ?`
|
|
2235
|
-
)
|
|
2236
|
-
.bind(id, userEmail)
|
|
2237
|
-
.run();
|
|
2238
|
-
if (!result.success || (result.meta?.changes ?? 0) === 0) {
|
|
2239
|
-
return json({ error: "Not found" }, { status: 404 });
|
|
2240
|
-
}
|
|
2241
|
-
|
|
2242
|
-
for (const k of keysToDelete) await r2DeleteSafe(env, k);
|
|
2243
|
-
|
|
2244
|
-
return json({ deleted: id, r2_keys_deleted: keysToDelete.length });
|
|
2245
|
-
}
|
|
2246
|
-
|
|
2247
|
-
// v0.20.2: move a conversation to a project (or clear its project assignment).
|
|
2248
|
-
// Body: { project_id: number | null }. When project_id is a number, the
|
|
2249
|
-
// project must exist and belong to the same user. When null, the assignment
|
|
2250
|
-
// is cleared on all turns.
|
|
2251
|
-
//
|
|
2252
|
-
// All turns in the conversation are updated atomically. The conversation_id
|
|
2253
|
-
// is the existing key for ownership (chats.user_email + conversation_id).
|
|
2254
|
-
async function handleConversationMoveToProject(
|
|
2255
|
-
request: Request,
|
|
2256
|
-
env: Env,
|
|
2257
|
-
conversationId: string,
|
|
2258
|
-
): Promise<Response> {
|
|
2259
|
-
const userEmail = await getUserEmail(request, env);
|
|
2260
|
-
|
|
2261
|
-
let body: { project_id?: number | null };
|
|
2262
|
-
try {
|
|
2263
|
-
body = await request.json();
|
|
2264
|
-
} catch {
|
|
2265
|
-
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
2266
|
-
}
|
|
2267
|
-
|
|
2268
|
-
const newProjectId = body.project_id ?? null;
|
|
2269
|
-
if (newProjectId !== null) {
|
|
2270
|
-
if (!Number.isInteger(newProjectId) || newProjectId <= 0) {
|
|
2271
|
-
return json({ error: "project_id must be a positive integer or null" }, { status: 400 });
|
|
2272
|
-
}
|
|
2273
|
-
// Confirm the target project exists and belongs to this user.
|
|
2274
|
-
const proj = await env.DB.prepare(
|
|
2275
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
2276
|
-
)
|
|
2277
|
-
.bind(newProjectId, userEmail)
|
|
2278
|
-
.first();
|
|
2279
|
-
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
2280
|
-
}
|
|
2281
|
-
|
|
2282
|
-
// Confirm the conversation exists and belongs to this user before
|
|
2283
|
-
// updating, otherwise we silently no-op on stale ids.
|
|
2284
|
-
const existing = await env.DB.prepare(
|
|
2285
|
-
`SELECT COUNT(*) AS n FROM chats
|
|
2286
|
-
WHERE conversation_id = ? AND user_email = ?`
|
|
2287
|
-
)
|
|
2288
|
-
.bind(conversationId, userEmail)
|
|
2289
|
-
.first<{ n: number }>();
|
|
2290
|
-
if (!existing || existing.n === 0) {
|
|
2291
|
-
return json({ error: "Conversation not found" }, { status: 404 });
|
|
2292
|
-
}
|
|
2293
|
-
|
|
2294
|
-
const result = await env.DB.prepare(
|
|
2295
|
-
`UPDATE chats SET project_id = ?
|
|
2296
|
-
WHERE conversation_id = ? AND user_email = ?`
|
|
2297
|
-
)
|
|
2298
|
-
.bind(newProjectId, conversationId, userEmail)
|
|
2299
|
-
.run();
|
|
2300
|
-
|
|
2301
|
-
return json({
|
|
2302
|
-
conversation_id: conversationId,
|
|
2303
|
-
project_id: newProjectId,
|
|
2304
|
-
rows_updated: result.meta?.changes ?? 0,
|
|
2305
|
-
});
|
|
2306
|
-
}
|
|
2307
|
-
|
|
2308
|
-
// ---------- RAG: document ingestion (Pass 1) ----------
|
|
2309
|
-
//
|
|
2310
|
-
// Pass 1 supports text/markdown only. Uploaded files are stored in R2,
|
|
2311
|
-
// chunked, embedded with @cf/baai/bge-base-en-v1.5 (768-dim), and the
|
|
2312
|
-
// resulting vectors are upserted into the Vectorize index. Chunks remain
|
|
2313
|
-
// in D1 keyed by their Vectorize vector_id so retrieval can look up the
|
|
2314
|
-
// original text from a vector hit.
|
|
2315
|
-
//
|
|
2316
|
-
// Chunking is character-based with ~50 char overlap. We try to break on
|
|
2317
|
-
// natural boundaries (paragraph breaks, then newlines, then sentences)
|
|
2318
|
-
// before falling back to a hard cut. Target 500 chars per chunk - small
|
|
2319
|
-
// enough that BGE-base does well, large enough that each chunk carries
|
|
2320
|
-
// usable context.
|
|
2321
|
-
//
|
|
2322
|
-
// Pass 2 will add the retrieval injection path into /api/chat. Pass 1
|
|
2323
|
-
// only builds the ingestion pipeline so we can validate Vectorize +
|
|
2324
|
-
// chunking + embedding end-to-end before touching chat.
|
|
2325
|
-
|
|
2326
|
-
const EMBED_MODEL = "@cf/baai/bge-base-en-v1.5";
|
|
2327
|
-
const EMBED_DIMENSIONS = 768;
|
|
2328
|
-
const EMBED_BATCH_SIZE = 16; // BGE accepts batches; 16 keeps requests small
|
|
2329
|
-
const DOC_MAX_BYTES = 10 * 1024 * 1024; // 10MB upload cap
|
|
2330
|
-
|
|
2331
|
-
// v0.25.0: ZIP import (RAG). A .zip upload is expanded and each inner file is
|
|
2332
|
-
// ingested as its own document. The compressed archive still rides the 10MB
|
|
2333
|
-
// DOC_MAX_BYTES cap above; these bound the decompressed expansion (zip-bomb
|
|
2334
|
-
// guard) and the inner-file count.
|
|
2335
|
-
const ZIP_MAX_ENTRIES = 200;
|
|
2336
|
-
const ZIP_MAX_TOTAL_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
|
|
2337
|
-
const ZIP_MAX_FILE_BYTES = DOC_MAX_BYTES;
|
|
2338
|
-
|
|
2339
|
-
// Best-effort content type for a file pulled out of a zip (we only get a name,
|
|
2340
|
-
// not a mime). extractChunks routes PDFs/spreadsheets by extension regardless,
|
|
2341
|
-
// so this only affects the contentType stored on the R2 object.
|
|
2342
|
-
function mimeFromName(name: string): string {
|
|
2343
|
-
const ext = (name.match(/\.([^.]+)$/)?.[1] ?? "").toLowerCase();
|
|
2344
|
-
switch (ext) {
|
|
2345
|
-
case "pdf": return "application/pdf";
|
|
2346
|
-
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
|
2347
|
-
case "xls": return "application/vnd.ms-excel";
|
|
2348
|
-
case "md": case "markdown": return "text/markdown";
|
|
2349
|
-
case "csv": return "text/csv";
|
|
2350
|
-
case "json": return "application/json";
|
|
2351
|
-
case "html": case "htm": return "text/html";
|
|
2352
|
-
case "xml": return "application/xml";
|
|
2353
|
-
case "txt": case "log": case "yaml": case "yml": return "text/plain";
|
|
2354
|
-
default: return "application/octet-stream";
|
|
2355
|
-
}
|
|
2356
|
-
}
|
|
2357
|
-
|
|
2358
|
-
// v0.17.0: web-search retrieval limits and timeouts. Each upstream is
|
|
2359
|
-
// time-bounded per source so a slow SearXNG doesn't block Wikipedia.
|
|
2360
|
-
// Counts kept small to bound context-token spend when the toggle is on.
|
|
2361
|
-
// v0.166.0: SearXNG replaced the retired Tavily + Brave SaaS sources.
|
|
2362
|
-
const SEARXNG_MAX_RESULTS = 5;
|
|
2363
|
-
const WIKIPEDIA_MAX_RESULTS = 3;
|
|
2364
|
-
const WEB_SEARCH_TIMEOUT_MS = 8000;
|
|
2365
|
-
|
|
2366
|
-
// v0.23.0: RAG document upload accepts any file type (no allowlist). PDF and
|
|
2367
|
-
// XLSX/XLS get native per-page / per-sheet extraction; everything else is
|
|
2368
|
-
// decoded as UTF-8 text (covers txt, md, csv, json, html, source code, logs,
|
|
2369
|
-
// etc. regardless of extension or mime). extractChunks rejects only files
|
|
2370
|
-
// whose bytes don't decode to usable text (binary formats like .docx/.png/.zip).
|
|
2371
|
-
|
|
2372
|
-
interface DocumentRow {
|
|
2373
|
-
id: number;
|
|
2374
|
-
user_email: string;
|
|
2375
|
-
created_at: string;
|
|
2376
|
-
filename: string;
|
|
2377
|
-
mime: string;
|
|
2378
|
-
r2_key: string;
|
|
2379
|
-
size_bytes: number;
|
|
2380
|
-
total_chars: number;
|
|
2381
|
-
chunk_count: number;
|
|
2382
|
-
}
|
|
2383
|
-
|
|
2384
|
-
interface ChunkRow {
|
|
2385
|
-
id: number;
|
|
2386
|
-
document_id: number;
|
|
2387
|
-
user_email: string;
|
|
2388
|
-
chunk_index: number;
|
|
2389
|
-
text: string;
|
|
2390
|
-
vector_id: string;
|
|
2391
|
-
page: number | null;
|
|
2392
|
-
sheet: string | null;
|
|
2393
|
-
}
|
|
2394
|
-
|
|
2395
|
-
// v0.20.0: project + project_documents join. A project groups documents
|
|
2396
|
-
// (and in v0.20.1, conversations) under a shared system_prompt and
|
|
2397
|
-
// retrieval scope. Many-to-many membership via project_documents.
|
|
2398
|
-
interface ProjectRow {
|
|
2399
|
-
id: number;
|
|
2400
|
-
user_email: string;
|
|
2401
|
-
name: string;
|
|
2402
|
-
slug: string;
|
|
2403
|
-
description: string | null;
|
|
2404
|
-
system_prompt: string | null;
|
|
2405
|
-
created_at: string;
|
|
2406
|
-
updated_at: string;
|
|
2407
|
-
}
|
|
2408
|
-
|
|
2409
|
-
// Output of the per-format extractors. Each ExtractedChunk has text plus
|
|
2410
|
-
// optional source-location metadata that gets persisted on the chunk row.
|
|
2411
|
-
interface ExtractedChunk {
|
|
2412
|
-
text: string;
|
|
2413
|
-
page?: number; // PDF: 1-indexed page number
|
|
2414
|
-
sheet?: string; // XLSX/XLS: source sheet name
|
|
2415
|
-
}
|
|
2416
|
-
|
|
2417
|
-
// ---------- RAG Phase 3A: per-format text extraction ----------
|
|
2418
|
-
//
|
|
2419
|
-
// For PDFs we extract per-page using unpdf (a serverless-friendly PDF.js
|
|
2420
|
-
// wrapper) and tag each resulting chunk with its source page. Chunks never
|
|
2421
|
-
// cross page boundaries so the source-page metadata stays meaningful.
|
|
2422
|
-
//
|
|
2423
|
-
// For XLSX/XLS we use SheetJS's CSV exporter per sheet and tag each chunk
|
|
2424
|
-
// with its source sheet name. Same boundary rule: chunks never cross sheets.
|
|
2425
|
-
//
|
|
2426
|
-
// Scanned/image-only PDFs are not handled here; pdfjs extracts the empty
|
|
2427
|
-
// text layer they have, which gives few or zero chunks. A future Phase 3B
|
|
2428
|
-
// would render pages to PNG and run them through a vision model for OCR.
|
|
2429
|
-
|
|
2430
|
-
async function extractPdfChunks(bytes: Uint8Array): Promise<ExtractedChunk[]> {
|
|
2431
|
-
const pdf = await getDocumentProxy(bytes);
|
|
2432
|
-
const out: ExtractedChunk[] = [];
|
|
2433
|
-
for (let i = 1; i <= pdf.numPages; i++) {
|
|
2434
|
-
const page = await pdf.getPage(i);
|
|
2435
|
-
const content = await page.getTextContent();
|
|
2436
|
-
// pdfjs's text items have a .str field; join with spaces and collapse
|
|
2437
|
-
// runs of whitespace that come from rendering positioning.
|
|
2438
|
-
const raw = (content.items as Array<{ str?: string }>)
|
|
2439
|
-
.map((it) => (it.str ?? "").trim())
|
|
2440
|
-
.filter(Boolean)
|
|
2441
|
-
.join(" ")
|
|
2442
|
-
.replace(/[ \t]+/g, " ")
|
|
2443
|
-
.replace(/\s+\n/g, "\n")
|
|
2444
|
-
.trim();
|
|
2445
|
-
if (!raw) continue;
|
|
2446
|
-
for (const piece of chunkText(raw)) {
|
|
2447
|
-
out.push({ text: piece, page: i });
|
|
2448
|
-
}
|
|
2449
|
-
}
|
|
2450
|
-
return out;
|
|
2451
|
-
}
|
|
2452
|
-
|
|
2453
|
-
function extractXlsxChunks(bytes: Uint8Array): ExtractedChunk[] {
|
|
2454
|
-
// SheetJS read accepts ArrayBuffer-ish inputs; dense=true uses a
|
|
2455
|
-
// 2D-array internal layout which is faster on sparse sheets.
|
|
2456
|
-
const wb = XLSX.read(bytes, { type: "array", dense: true });
|
|
2457
|
-
const out: ExtractedChunk[] = [];
|
|
2458
|
-
for (const sheetName of wb.SheetNames) {
|
|
2459
|
-
const ws = wb.Sheets[sheetName];
|
|
2460
|
-
if (!ws) continue;
|
|
2461
|
-
const csv = XLSX.utils.sheet_to_csv(ws, { blankrows: false, strip: true });
|
|
2462
|
-
const text = csv.trim();
|
|
2463
|
-
if (!text) continue;
|
|
2464
|
-
// For a small sheet, the whole CSV may be one chunk. For a large sheet,
|
|
2465
|
-
// chunkText breaks on newlines (the row boundaries in CSV).
|
|
2466
|
-
for (const piece of chunkText(text)) {
|
|
2467
|
-
out.push({ text: piece, sheet: sheetName });
|
|
2468
|
-
}
|
|
2469
|
-
}
|
|
2470
|
-
return out;
|
|
2471
|
-
}
|
|
2472
|
-
|
|
2473
|
-
// v0.23.0: heuristic: is a decoded string actually binary data we failed to
|
|
2474
|
-
// read as text? A meaningful fraction of U+FFFD (UTF-8 replacement) or C0 control
|
|
2475
|
-
// codes other than the usual whitespace (tab, LF, CR) means the source was
|
|
2476
|
-
// binary (zipped office docs, images, archives). Text-based formats stay far
|
|
2477
|
-
// below the threshold. Sample the head to keep this O(1)-ish on big files.
|
|
2478
|
-
function looksBinary(text: string): boolean {
|
|
2479
|
-
if (!text) return true;
|
|
2480
|
-
const sample = text.length > 4096 ? text.slice(0, 4096) : text;
|
|
2481
|
-
let bad = 0;
|
|
2482
|
-
for (let i = 0; i < sample.length; i++) {
|
|
2483
|
-
const c = sample.charCodeAt(i);
|
|
2484
|
-
if (c === 0xfffd) { bad++; continue; }
|
|
2485
|
-
if (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) bad++;
|
|
2486
|
-
}
|
|
2487
|
-
return bad / sample.length > 0.1;
|
|
2488
|
-
}
|
|
2489
|
-
|
|
2490
|
-
// Per-mime dispatcher. Returns ExtractedChunk[] regardless of input format.
|
|
2491
|
-
// The caller is responsible for storing the raw bytes in R2 and persisting
|
|
2492
|
-
// each chunk row with its page/sheet metadata.
|
|
2493
|
-
async function extractChunks(bytes: Uint8Array, mime: string, filename: string): Promise<ExtractedChunk[]> {
|
|
2494
|
-
const ext = (filename.match(/\.([^.]+)$/)?.[1] ?? "").toLowerCase();
|
|
2495
|
-
|
|
2496
|
-
// PDF
|
|
2497
|
-
if (mime === "application/pdf" || ext === "pdf") {
|
|
2498
|
-
return await extractPdfChunks(bytes);
|
|
2499
|
-
}
|
|
2500
|
-
|
|
2501
|
-
// XLSX or XLS
|
|
2502
|
-
if (
|
|
2503
|
-
mime === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
|
|
2504
|
-
mime === "application/vnd.ms-excel" ||
|
|
2505
|
-
ext === "xlsx" || ext === "xls"
|
|
2506
|
-
) {
|
|
2507
|
-
return extractXlsxChunks(bytes);
|
|
2508
|
-
}
|
|
2509
|
-
|
|
2510
|
-
// Everything else: treat as UTF-8 text. Covers txt/md plus any code, CSV,
|
|
2511
|
-
// JSON, HTML, log, or other text-based format, whatever the extension.
|
|
2512
|
-
// Decode with replacement on invalid bytes rather than throwing; if the
|
|
2513
|
-
// result is mostly replacement/control bytes the file is binary in a format
|
|
2514
|
-
// we can't extract, so reject it instead of embedding garbage.
|
|
2515
|
-
const text = new TextDecoder("utf-8").decode(bytes);
|
|
2516
|
-
if (looksBinary(text)) {
|
|
2517
|
-
throw new Error(
|
|
2518
|
-
`${filename} looks like binary data that can't be read as text. PDF and ` +
|
|
2519
|
-
`XLSX/XLS are extracted natively; otherwise upload a text-based file ` +
|
|
2520
|
-
`(txt, md, csv, json, html, source code, etc.).`
|
|
2521
|
-
);
|
|
2522
|
-
}
|
|
2523
|
-
return chunkText(text).map((t) => ({ text: t }));
|
|
2524
|
-
}
|
|
2525
|
-
|
|
2526
|
-
async function embedBatch(env: Env, userEmail: string, texts: string[]): Promise<number[][]> {
|
|
2527
|
-
if (texts.length === 0) return [];
|
|
2528
|
-
const gateway = await loadGatewayCredentials(env, userEmail);
|
|
2529
|
-
if (!gateway?.gatewayId) {
|
|
2530
|
-
throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
|
|
2531
|
-
}
|
|
2532
|
-
const aiCtx: AiContext = { env, gateway };
|
|
2533
|
-
const result = await aiRun(aiCtx, EMBED_MODEL, { text: texts }) as {
|
|
2534
|
-
shape?: [number, number];
|
|
2535
|
-
data?: number[][];
|
|
2536
|
-
};
|
|
2537
|
-
if (!result.data || !Array.isArray(result.data)) {
|
|
2538
|
-
throw new Error("Embedding model returned no data array");
|
|
2539
|
-
}
|
|
2540
|
-
return result.data;
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
// ---------- RAG: retrieval (Pass 2) ----------
|
|
2544
|
-
//
|
|
2545
|
-
// Embeds the user prompt, queries Vectorize for the top-K nearest chunks,
|
|
2546
|
-
// then looks up source text in D1. We filter by user_email in the D1 JOIN
|
|
2547
|
-
// (not in the Vectorize filter param) so this works without a metadata
|
|
2548
|
-
// index on the Vectorize side - simpler for single-user deployments.
|
|
2549
|
-
// Vectorize score ordering is preserved.
|
|
2550
|
-
|
|
2551
|
-
const RETRIEVE_TOP_K = 5;
|
|
2552
|
-
|
|
2553
|
-
async function retrieveContext(
|
|
2554
|
-
env: Env,
|
|
2555
|
-
userEmail: string,
|
|
2556
|
-
queryText: string,
|
|
2557
|
-
topK: number = RETRIEVE_TOP_K,
|
|
2558
|
-
projectId?: number,
|
|
2559
|
-
): Promise<{ chunks: RetrievedChunk[]; error: string | null }> {
|
|
2560
|
-
if (!queryText || !queryText.trim()) {
|
|
2561
|
-
return { chunks: [], error: "Empty query text" };
|
|
2562
|
-
}
|
|
2563
|
-
|
|
2564
|
-
// 1) Embed the query. Log + surface errors instead of silently swallowing.
|
|
2565
|
-
let queryVec: number[];
|
|
2566
|
-
try {
|
|
2567
|
-
const vectors = await embedBatch(env, userEmail, [queryText]);
|
|
2568
|
-
if (vectors.length === 0) {
|
|
2569
|
-
const msg = "Embed returned no vectors";
|
|
2570
|
-
console.error("retrieveContext:", msg);
|
|
2571
|
-
return { chunks: [], error: msg };
|
|
2572
|
-
}
|
|
2573
|
-
queryVec = vectors[0];
|
|
2574
|
-
} catch (err) {
|
|
2575
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
2576
|
-
console.error("retrieveContext: embed failed:", m);
|
|
2577
|
-
return { chunks: [], error: `embed failed: ${m}` };
|
|
2578
|
-
}
|
|
2579
|
-
|
|
2580
|
-
// 2) Query Vectorize. No metadata filter - we scope by user in D1 below.
|
|
2581
|
-
// When projectId is set, we overfetch (3x topK) at the Vectorize stage
|
|
2582
|
-
// and filter by project membership in D1, since Vectorize doesn't know
|
|
2583
|
-
// about project membership. Without overfetch, a small topK that all
|
|
2584
|
-
// misses the project would return zero results even when the project
|
|
2585
|
-
// has relevant chunks.
|
|
2586
|
-
const vectorizeTopK = projectId !== undefined ? topK * 3 : topK;
|
|
2587
|
-
let matches: { id: string; score: number }[];
|
|
2588
|
-
try {
|
|
2589
|
-
const q = await env.VEC.query(queryVec, { topK: vectorizeTopK });
|
|
2590
|
-
matches = (q?.matches ?? []).map((m) => ({ id: m.id, score: m.score }));
|
|
2591
|
-
} catch (err) {
|
|
2592
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
2593
|
-
console.error("retrieveContext: vectorize query failed:", m);
|
|
2594
|
-
return { chunks: [], error: `vectorize query failed: ${m}` };
|
|
2595
|
-
}
|
|
2596
|
-
if (matches.length === 0) {
|
|
2597
|
-
console.warn("retrieveContext: vectorize returned 0 matches for query");
|
|
2598
|
-
return { chunks: [], error: "vectorize returned 0 matches" };
|
|
2599
|
-
}
|
|
2600
|
-
|
|
2601
|
-
// 3) D1 lookup: join chunks to documents, scope by user_email so we
|
|
2602
|
-
// never return another user's chunk even if their vector IDs would
|
|
2603
|
-
// somehow collide. When projectId is set, additionally INNER JOIN
|
|
2604
|
-
// project_documents so only chunks whose document is in that project's
|
|
2605
|
-
// membership set come through.
|
|
2606
|
-
const ids = matches.map((m) => m.id);
|
|
2607
|
-
const placeholders = ids.map(() => "?").join(",");
|
|
2608
|
-
let rows;
|
|
2609
|
-
try {
|
|
2610
|
-
if (projectId !== undefined) {
|
|
2611
|
-
rows = await env.DB.prepare(
|
|
2612
|
-
`SELECT c.document_id, c.chunk_index, c.text, c.vector_id, c.page, c.sheet, d.filename
|
|
2613
|
-
FROM chunks c
|
|
2614
|
-
JOIN documents d ON c.document_id = d.id
|
|
2615
|
-
JOIN project_documents pd ON pd.document_id = d.id
|
|
2616
|
-
JOIN projects p ON p.id = pd.project_id
|
|
2617
|
-
WHERE c.user_email = ?
|
|
2618
|
-
AND p.user_email = ?
|
|
2619
|
-
AND pd.project_id = ?
|
|
2620
|
-
AND c.vector_id IN (${placeholders})`
|
|
2621
|
-
)
|
|
2622
|
-
.bind(userEmail, userEmail, projectId, ...ids)
|
|
2623
|
-
.all<{ document_id: number; chunk_index: number; text: string; vector_id: string; filename: string; page: number | null; sheet: string | null }>();
|
|
2624
|
-
} else {
|
|
2625
|
-
rows = await env.DB.prepare(
|
|
2626
|
-
`SELECT c.document_id, c.chunk_index, c.text, c.vector_id, c.page, c.sheet, d.filename
|
|
2627
|
-
FROM chunks c
|
|
2628
|
-
JOIN documents d ON c.document_id = d.id
|
|
2629
|
-
WHERE c.user_email = ?
|
|
2630
|
-
AND c.vector_id IN (${placeholders})`
|
|
2631
|
-
)
|
|
2632
|
-
.bind(userEmail, ...ids)
|
|
2633
|
-
.all<{ document_id: number; chunk_index: number; text: string; vector_id: string; filename: string; page: number | null; sheet: string | null }>();
|
|
2634
|
-
}
|
|
2635
|
-
} catch (err) {
|
|
2636
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
2637
|
-
console.error("retrieveContext: D1 lookup failed:", m);
|
|
2638
|
-
return { chunks: [], error: `D1 lookup failed: ${m}` };
|
|
2639
|
-
}
|
|
2640
|
-
|
|
2641
|
-
const results = rows.results ?? [];
|
|
2642
|
-
if (results.length === 0) {
|
|
2643
|
-
// Vectorize had matches but D1 join returned nothing. Two causes:
|
|
2644
|
-
// 1. user_email mismatch (vectors written under a different identity).
|
|
2645
|
-
// 2. With projectId set: matches were real but none of the matched
|
|
2646
|
-
// documents are members of the requested project.
|
|
2647
|
-
const idSample = ids.slice(0, 3).join(", ");
|
|
2648
|
-
const scope = projectId !== undefined ? ` project_id=${projectId},` : "";
|
|
2649
|
-
const msg = `Vectorize returned ${matches.length} matches but D1 join returned 0. user_email='${userEmail}',${scope} sample vector_ids=[${idSample}]. Check whether vectors were upserted under a different user identity, or whether the project has any document members.`;
|
|
2650
|
-
console.warn("retrieveContext:", msg);
|
|
2651
|
-
return { chunks: [], error: msg };
|
|
2652
|
-
}
|
|
2653
|
-
|
|
2654
|
-
// 4) Merge scores back in, preserve Vectorize ordering. When projectId
|
|
2655
|
-
// is set we overfetched from Vectorize (3x topK), so cap output here to
|
|
2656
|
-
// hold the chat prompt size to the caller's intended top-K.
|
|
2657
|
-
const byId = new Map(results.map((r) => [r.vector_id, r]));
|
|
2658
|
-
const scoreById = new Map(matches.map((m) => [m.id, m.score]));
|
|
2659
|
-
const out: RetrievedChunk[] = [];
|
|
2660
|
-
for (const id of ids) {
|
|
2661
|
-
if (out.length >= topK) break;
|
|
2662
|
-
const r = byId.get(id);
|
|
2663
|
-
if (!r) continue;
|
|
2664
|
-
out.push({
|
|
2665
|
-
document_id: r.document_id,
|
|
2666
|
-
filename: r.filename,
|
|
2667
|
-
chunk_index: r.chunk_index,
|
|
2668
|
-
text: r.text,
|
|
2669
|
-
score: scoreById.get(id) ?? 0,
|
|
2670
|
-
page: r.page,
|
|
2671
|
-
sheet: r.sheet,
|
|
2672
|
-
});
|
|
2673
|
-
}
|
|
2674
|
-
return { chunks: out, error: null };
|
|
2675
|
-
}
|
|
2676
|
-
|
|
2677
|
-
function formatRetrievalForSystemPrompt(chunks: RetrievedChunk[]): string {
|
|
2678
|
-
if (chunks.length === 0) return "";
|
|
2679
|
-
const body = chunks
|
|
2680
|
-
.map((c, i) => {
|
|
2681
|
-
const loc =
|
|
2682
|
-
c.page !== undefined && c.page !== null ? `, page ${c.page}` :
|
|
2683
|
-
c.sheet ? `, sheet "${c.sheet}"` :
|
|
2684
|
-
"";
|
|
2685
|
-
return `[Excerpt ${i + 1}, from ${c.filename}${loc} (chunk ${c.chunk_index})]\n${c.text}`;
|
|
2686
|
-
})
|
|
2687
|
-
.join("\n\n---\n\n");
|
|
2688
|
-
return [
|
|
2689
|
-
"You have access to the following excerpts from the user's uploaded documents.",
|
|
2690
|
-
"Use them when they are relevant to the user's query. If they don't answer the question,",
|
|
2691
|
-
"say so plainly rather than guessing or hallucinating.",
|
|
2692
|
-
"",
|
|
2693
|
-
body,
|
|
2694
|
-
].join("\n");
|
|
2695
|
-
}
|
|
2696
|
-
|
|
2697
|
-
// ---------- Web search (v0.17.0) ----------
|
|
2698
|
-
//
|
|
2699
|
-
// Optional retrieval source: SearXNG (self-hosted metasearch) for general web,
|
|
2700
|
-
// Wikipedia for lore / reference. Both run in parallel; failure of one doesn't
|
|
2701
|
-
// kill the other. Per-source timeouts (WEB_SEARCH_TIMEOUT_MS) prevent a slow
|
|
2702
|
-
// upstream from blocking the whole turn.
|
|
2703
|
-
//
|
|
2704
|
-
// SearXNG requires SEARXNG_URL; when unset, that source is silently skipped.
|
|
2705
|
-
// Wikipedia needs no config. (v0.166.0: SearXNG replaced the retired Tavily +
|
|
2706
|
-
// Brave SaaS sources; see prism#93.)
|
|
2707
|
-
//
|
|
2708
|
-
// Results are persisted to the existing retrieved_context column alongside
|
|
2709
|
-
// RAG chunks, with source_type discriminator. The frontend renders branches
|
|
2710
|
-
// on source_type to show the source URL for web results.
|
|
2711
|
-
|
|
2712
|
-
async function searchWeb(
|
|
2713
|
-
env: Env,
|
|
2714
|
-
query: string
|
|
2715
|
-
): Promise<{ results: RetrievedWebResult[]; error: string | null }> {
|
|
2716
|
-
const q = query.trim();
|
|
2717
|
-
if (!q) return { results: [], error: null };
|
|
2718
|
-
|
|
2719
|
-
// Each upstream is wrapped in its own timeout + catch so a single failure
|
|
2720
|
-
// doesn't abort the other. Partial results are better than nothing.
|
|
2721
|
-
const searxngPromise: Promise<RetrievedWebResult[]> = env.SEARXNG_URL
|
|
2722
|
-
? searchSearxng(env, q).catch(() => [])
|
|
2723
|
-
: Promise.resolve([]);
|
|
2724
|
-
const wikipediaPromise: Promise<RetrievedWebResult[]> = searchWikipedia(q).catch(() => []);
|
|
2725
|
-
|
|
2726
|
-
const [searxng, wikipedia] = await Promise.all([searxngPromise, wikipediaPromise]);
|
|
2727
|
-
const results = [...searxng, ...wikipedia];
|
|
2728
|
-
|
|
2729
|
-
// Empty results is fine; it just means the query didn't match anything in
|
|
2730
|
-
// any source. Real per-source failures are swallowed by the .catch above
|
|
2731
|
-
// so the other source can still return its hits.
|
|
2732
|
-
return { results, error: null };
|
|
2733
|
-
}
|
|
2734
|
-
|
|
2735
|
-
async function searchSearxng(env: Env, query: string): Promise<RetrievedWebResult[]> {
|
|
2736
|
-
// Access service-token headers are sent only when both halves are set, so an
|
|
2737
|
-
// un-gated self-hosted instance is reached with no headers.
|
|
2738
|
-
const hits = await searchSearxngWeb(env.SEARXNG_URL!, query, {
|
|
2739
|
-
maxResults: SEARXNG_MAX_RESULTS,
|
|
2740
|
-
timeoutMs: WEB_SEARCH_TIMEOUT_MS,
|
|
2741
|
-
accessClientId: env.SEARXNG_ACCESS_CLIENT_ID,
|
|
2742
|
-
accessClientSecret: env.SEARXNG_ACCESS_CLIENT_SECRET,
|
|
2743
|
-
});
|
|
2744
|
-
return hits.map((r): RetrievedWebResult => ({
|
|
2745
|
-
source_type: "web",
|
|
2746
|
-
source: "searxng",
|
|
2747
|
-
url: r.url,
|
|
2748
|
-
title: r.title,
|
|
2749
|
-
snippet: r.snippet,
|
|
2750
|
-
}));
|
|
2751
|
-
}
|
|
2752
|
-
|
|
2753
|
-
async function searchWikipedia(query: string): Promise<RetrievedWebResult[]> {
|
|
2754
|
-
// Wikipedia's search endpoint returns titles + HTML snippets in one call.
|
|
2755
|
-
// origin=* is required for CORS, but harmless server-side too. We don't
|
|
2756
|
-
// hit /page/summary per result (would be N+1 round-trips); the search
|
|
2757
|
-
// snippet is enough for most creative-work queries.
|
|
2758
|
-
const url = new URL("https://en.wikipedia.org/w/api.php");
|
|
2759
|
-
url.searchParams.set("action", "query");
|
|
2760
|
-
url.searchParams.set("list", "search");
|
|
2761
|
-
url.searchParams.set("srsearch", query);
|
|
2762
|
-
url.searchParams.set("srlimit", String(WIKIPEDIA_MAX_RESULTS));
|
|
2763
|
-
url.searchParams.set("srprop", "snippet");
|
|
2764
|
-
url.searchParams.set("format", "json");
|
|
2765
|
-
url.searchParams.set("origin", "*");
|
|
2766
|
-
|
|
2767
|
-
const resp = await fetch(url.toString(), {
|
|
2768
|
-
headers: {
|
|
2769
|
-
// Wikimedia asks for a descriptive User-Agent identifying the tool.
|
|
2770
|
-
// See https://meta.wikimedia.org/wiki/User-Agent_policy
|
|
2771
|
-
"user-agent": "skyphusion-llm-public/0.17.0 (https://github.com/SkyPhusion/skyphusion-llm-public)",
|
|
2772
|
-
},
|
|
2773
|
-
signal: AbortSignal.timeout(WEB_SEARCH_TIMEOUT_MS),
|
|
2774
|
-
});
|
|
2775
|
-
if (!resp.ok) {
|
|
2776
|
-
throw new Error(`Wikipedia ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
|
|
2777
|
-
}
|
|
2778
|
-
const data = await resp.json() as {
|
|
2779
|
-
query?: { search?: Array<{ title?: string; snippet?: string; pageid?: number }> };
|
|
2780
|
-
};
|
|
2781
|
-
const items = data.query?.search ?? [];
|
|
2782
|
-
return items
|
|
2783
|
-
.filter((r) => r.title && r.pageid !== undefined)
|
|
2784
|
-
.map((r): RetrievedWebResult => ({
|
|
2785
|
-
source_type: "web",
|
|
2786
|
-
source: "wikipedia",
|
|
2787
|
-
url: `https://en.wikipedia.org/?curid=${r.pageid}`,
|
|
2788
|
-
title: r.title!,
|
|
2789
|
-
// Snippet comes back as HTML with <span class="searchmatch">...</span>
|
|
2790
|
-
// around matched terms. Strip tags and decode the few entities that
|
|
2791
|
-
// Wikipedia commonly emits. Good enough for an LLM context block.
|
|
2792
|
-
snippet: stripWikipediaSnippet(r.snippet ?? ""),
|
|
2793
|
-
}));
|
|
2794
|
-
}
|
|
2795
|
-
|
|
2796
|
-
function stripWikipediaSnippet(html: string): string {
|
|
2797
|
-
// Strip HTML tags to a fixpoint first, so a reassembled/nested tag (e.g.
|
|
2798
|
-
// "<<script>script>") can't survive a single pass, THEN decode the handful of
|
|
2799
|
-
// entities Wikipedia emits -- decoding & LAST so an encoded entity like
|
|
2800
|
-
// "&lt;" stays literal text instead of being double-unescaped into "<".
|
|
2801
|
-
// Output is plain text for an LLM context block (not an HTML/DOM sink).
|
|
2802
|
-
let prev = "";
|
|
2803
|
-
let s = html;
|
|
2804
|
-
while (s !== prev) {
|
|
2805
|
-
prev = s;
|
|
2806
|
-
s = s.replace(/<[^>]+>/g, "");
|
|
2807
|
-
}
|
|
2808
|
-
return s
|
|
2809
|
-
.replace(/"/g, '"')
|
|
2810
|
-
.replace(/'/g, "'")
|
|
2811
|
-
.replace(/</g, "<")
|
|
2812
|
-
.replace(/>/g, ">")
|
|
2813
|
-
.replace(/ /g, " ")
|
|
2814
|
-
.replace(/&/g, "&")
|
|
2815
|
-
.replace(/\s+/g, " ")
|
|
2816
|
-
.trim();
|
|
2817
|
-
}
|
|
2818
|
-
|
|
2819
|
-
function webSourceSystemLabel(source: RetrievedWebResult["source"]): string {
|
|
2820
|
-
switch (source) {
|
|
2821
|
-
case "searxng": return "Web";
|
|
2822
|
-
case "wikipedia": return "Wikipedia";
|
|
2823
|
-
}
|
|
2824
|
-
}
|
|
2825
|
-
|
|
2826
|
-
function formatWebForSystemPrompt(results: RetrievedWebResult[]): string {
|
|
2827
|
-
if (results.length === 0) return "";
|
|
2828
|
-
const body = results
|
|
2829
|
-
.map((r, i) => {
|
|
2830
|
-
const sourceLabel = webSourceSystemLabel(r.source);
|
|
2831
|
-
return `[${sourceLabel} ${i + 1}, "${r.title}" (${r.url})]\n${r.snippet}`;
|
|
2832
|
-
})
|
|
2833
|
-
.join("\n\n---\n\n");
|
|
2834
|
-
return [
|
|
2835
|
-
"You have access to the following snippets retrieved from web search.",
|
|
2836
|
-
"Treat these as supplementary context, not authoritative fact. Quote URLs",
|
|
2837
|
-
"verbatim if citing a source. If the snippets don't answer the question,",
|
|
2838
|
-
"say so plainly rather than fabricating.",
|
|
2839
|
-
"",
|
|
2840
|
-
body,
|
|
2841
|
-
].join("\n");
|
|
2842
|
-
}
|
|
2843
|
-
|
|
2844
|
-
async function handleDocumentList(request: Request, env: Env): Promise<Response> {
|
|
2845
|
-
const userEmail = await getUserEmail(request, env);
|
|
2846
|
-
const url = new URL(request.url);
|
|
2847
|
-
const projectIdParam = url.searchParams.get("project_id");
|
|
2848
|
-
|
|
2849
|
-
// v0.20.0: optional ?project_id=N filter. When set, return only documents
|
|
2850
|
-
// attached to that project via project_documents. The project ownership
|
|
2851
|
-
// check is done by joining on projects.user_email implicitly via WHERE
|
|
2852
|
-
// p.user_email = ?, so attempting to filter by another user's project
|
|
2853
|
-
// returns an empty list rather than leaking that the project exists.
|
|
2854
|
-
if (projectIdParam !== null) {
|
|
2855
|
-
const projectId = Number(projectIdParam);
|
|
2856
|
-
if (!Number.isInteger(projectId) || projectId <= 0) {
|
|
2857
|
-
return json({ error: "project_id must be a positive integer" }, { status: 400 });
|
|
2858
|
-
}
|
|
2859
|
-
const rows = await env.DB.prepare(
|
|
2860
|
-
`SELECT d.id, d.created_at, d.filename, d.mime, d.size_bytes,
|
|
2861
|
-
d.total_chars, d.chunk_count
|
|
2862
|
-
FROM documents d
|
|
2863
|
-
JOIN project_documents pd ON pd.document_id = d.id
|
|
2864
|
-
JOIN projects p ON p.id = pd.project_id
|
|
2865
|
-
WHERE d.user_email = ?
|
|
2866
|
-
AND p.user_email = ?
|
|
2867
|
-
AND pd.project_id = ?
|
|
2868
|
-
ORDER BY pd.added_at DESC`
|
|
2869
|
-
)
|
|
2870
|
-
.bind(userEmail, userEmail, projectId)
|
|
2871
|
-
.all<{
|
|
2872
|
-
id: number;
|
|
2873
|
-
created_at: string;
|
|
2874
|
-
filename: string;
|
|
2875
|
-
mime: string;
|
|
2876
|
-
size_bytes: number;
|
|
2877
|
-
total_chars: number;
|
|
2878
|
-
chunk_count: number;
|
|
2879
|
-
}>();
|
|
2880
|
-
return json({
|
|
2881
|
-
user: userEmail,
|
|
2882
|
-
project_id: projectId,
|
|
2883
|
-
documents: rows.results ?? [],
|
|
2884
|
-
});
|
|
2885
|
-
}
|
|
2886
|
-
|
|
2887
|
-
const rows = await env.DB.prepare(
|
|
2888
|
-
`SELECT id, created_at, filename, mime, size_bytes, total_chars, chunk_count
|
|
2889
|
-
FROM documents
|
|
2890
|
-
WHERE user_email = ?
|
|
2891
|
-
ORDER BY created_at DESC`
|
|
2892
|
-
)
|
|
2893
|
-
.bind(userEmail)
|
|
2894
|
-
.all<{
|
|
2895
|
-
id: number;
|
|
2896
|
-
created_at: string;
|
|
2897
|
-
filename: string;
|
|
2898
|
-
mime: string;
|
|
2899
|
-
size_bytes: number;
|
|
2900
|
-
total_chars: number;
|
|
2901
|
-
chunk_count: number;
|
|
2902
|
-
}>();
|
|
2903
|
-
return json({ user: userEmail, documents: rows.results ?? [] });
|
|
2904
|
-
}
|
|
2905
|
-
|
|
2906
|
-
async function handleDocumentGet(request: Request, env: Env, id: number): Promise<Response> {
|
|
2907
|
-
const userEmail = await getUserEmail(request, env);
|
|
2908
|
-
const doc = await env.DB.prepare(
|
|
2909
|
-
`SELECT id, created_at, filename, mime, size_bytes, total_chars, chunk_count
|
|
2910
|
-
FROM documents
|
|
2911
|
-
WHERE id = ? AND user_email = ?`
|
|
2912
|
-
)
|
|
2913
|
-
.bind(id, userEmail)
|
|
2914
|
-
.first();
|
|
2915
|
-
if (!doc) return json({ error: "Not found" }, { status: 404 });
|
|
2916
|
-
|
|
2917
|
-
// Include first ~10 chunks for inspection without dumping the whole doc.
|
|
2918
|
-
const chunks = await env.DB.prepare(
|
|
2919
|
-
`SELECT chunk_index, text FROM chunks
|
|
2920
|
-
WHERE document_id = ? AND user_email = ?
|
|
2921
|
-
ORDER BY chunk_index ASC
|
|
2922
|
-
LIMIT 10`
|
|
2923
|
-
)
|
|
2924
|
-
.bind(id, userEmail)
|
|
2925
|
-
.all();
|
|
2926
|
-
|
|
2927
|
-
return json({ document: doc, chunk_preview: chunks.results ?? [] });
|
|
2928
|
-
}
|
|
2929
|
-
|
|
2930
|
-
// Result of ingesting a single file into the RAG store. Returned (not a
|
|
2931
|
-
// Response) so both the single-file upload path and the per-entry zip-import
|
|
2932
|
-
// path can compose it.
|
|
2933
|
-
type IngestResult =
|
|
2934
|
-
| { ok: true; id: number; created_at: string; filename: string; mime: string; size_bytes: number; total_chars: number; chunk_count: number }
|
|
2935
|
-
| { ok: false; status: number; error: string };
|
|
2936
|
-
|
|
2937
|
-
// Core RAG ingest for one file: extract -> store raw bytes in R2 -> insert the
|
|
2938
|
-
// document row -> embed in batches and upsert vectors -> write chunk rows.
|
|
2939
|
-
// Extracted from handleDocumentUpload (v0.25.0) so ZIP import can reuse it
|
|
2940
|
-
// per inner file. Best-effort rollback on embedding failure.
|
|
2941
|
-
async function ingestDocument(env: Env, userEmail: string, filename: string, mime: string, bytes: Uint8Array): Promise<IngestResult> {
|
|
2942
|
-
let extracted: ExtractedChunk[];
|
|
2943
|
-
try {
|
|
2944
|
-
extracted = await extractChunks(bytes, mime, filename);
|
|
2945
|
-
} catch (err) {
|
|
2946
|
-
return { ok: false, status: 400, error: `Extraction failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
2947
|
-
}
|
|
2948
|
-
if (extracted.length === 0) {
|
|
2949
|
-
return { ok: false, status: 400, error: "No chunks produced (empty, image-only/scanned PDF, or unreadable format)." };
|
|
2950
|
-
}
|
|
2951
|
-
|
|
2952
|
-
const totalChars = extracted.reduce((sum, c) => sum + c.text.length, 0);
|
|
2953
|
-
|
|
2954
|
-
// Store raw bytes in R2 for audit / future re-processing.
|
|
2955
|
-
const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
|
|
2956
|
-
|
|
2957
|
-
// Insert document row first so we have its ID for vector_id generation.
|
|
2958
|
-
const docInsert = await env.DB.prepare(
|
|
2959
|
-
`INSERT INTO documents
|
|
2960
|
-
(user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
|
|
2961
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
2962
|
-
RETURNING id, created_at`
|
|
2963
|
-
)
|
|
2964
|
-
.bind(userEmail, filename, mime, r2Key, bytes.length, totalChars, extracted.length)
|
|
2965
|
-
.first<{ id: number; created_at: string }>();
|
|
2966
|
-
if (!docInsert) {
|
|
2967
|
-
await r2DeleteSafe(env, r2Key);
|
|
2968
|
-
return { ok: false, status: 500, error: "Failed to insert document row" };
|
|
2969
|
-
}
|
|
2970
|
-
const docId = docInsert.id;
|
|
2971
|
-
|
|
2972
|
-
// Embed in batches and upsert to Vectorize. We tag every vector with
|
|
2973
|
-
// user_email + document_id so we can filter on retrieval and clean up on delete.
|
|
2974
|
-
// Vector IDs are scoped: `${userEmail}:${docId}:${chunkIndex}`.
|
|
2975
|
-
const vectorIdsWritten: string[] = [];
|
|
2976
|
-
const chunkRowsToInsert: {
|
|
2977
|
-
chunk_index: number;
|
|
2978
|
-
text: string;
|
|
2979
|
-
vector_id: string;
|
|
2980
|
-
page: number | null;
|
|
2981
|
-
sheet: string | null;
|
|
2982
|
-
}[] = [];
|
|
2983
|
-
|
|
2984
|
-
try {
|
|
2985
|
-
for (let b = 0; b < extracted.length; b += EMBED_BATCH_SIZE) {
|
|
2986
|
-
const batch = extracted.slice(b, b + EMBED_BATCH_SIZE);
|
|
2987
|
-
const vectors = await embedBatch(env, userEmail, batch.map((c) => c.text));
|
|
2988
|
-
if (vectors.length !== batch.length) {
|
|
2989
|
-
throw new Error(`Embedding batch returned ${vectors.length} vectors for ${batch.length} texts`);
|
|
2990
|
-
}
|
|
2991
|
-
|
|
2992
|
-
const vectorizePayload = batch.map((c, i) => {
|
|
2993
|
-
const idx = b + i;
|
|
2994
|
-
const vid = `${userEmail}:${docId}:${idx}`;
|
|
2995
|
-
chunkRowsToInsert.push({
|
|
2996
|
-
chunk_index: idx,
|
|
2997
|
-
text: c.text,
|
|
2998
|
-
vector_id: vid,
|
|
2999
|
-
page: c.page ?? null,
|
|
3000
|
-
sheet: c.sheet ?? null,
|
|
3001
|
-
});
|
|
3002
|
-
vectorIdsWritten.push(vid);
|
|
3003
|
-
const metadata: Record<string, string | number> = {
|
|
3004
|
-
user_email: userEmail,
|
|
3005
|
-
document_id: docId,
|
|
3006
|
-
chunk_index: idx,
|
|
3007
|
-
};
|
|
3008
|
-
if (c.page !== undefined) metadata.page = c.page;
|
|
3009
|
-
if (c.sheet !== undefined) metadata.sheet = c.sheet;
|
|
3010
|
-
return { id: vid, values: vectors[i], metadata };
|
|
3011
|
-
});
|
|
3012
|
-
|
|
3013
|
-
await env.VEC.upsert(vectorizePayload);
|
|
3014
|
-
}
|
|
3015
|
-
} catch (err) {
|
|
3016
|
-
// Rollback: best-effort cleanup of partially-written state.
|
|
3017
|
-
if (vectorIdsWritten.length) {
|
|
3018
|
-
try { await env.VEC.deleteByIds(vectorIdsWritten); } catch { /* swallow */ }
|
|
3019
|
-
}
|
|
3020
|
-
await env.DB.prepare(`DELETE FROM documents WHERE id = ?`).bind(docId).run();
|
|
3021
|
-
await r2DeleteSafe(env, r2Key);
|
|
3022
|
-
return { ok: false, status: 502, error: `Embedding failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
3023
|
-
}
|
|
3024
|
-
|
|
3025
|
-
// Now write all chunk rows in a single batched D1 statement.
|
|
3026
|
-
if (chunkRowsToInsert.length) {
|
|
3027
|
-
const stmts = chunkRowsToInsert.map((c) =>
|
|
3028
|
-
env.DB.prepare(
|
|
3029
|
-
`INSERT INTO chunks (document_id, user_email, chunk_index, text, vector_id, page, sheet)
|
|
3030
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
3031
|
-
).bind(docId, userEmail, c.chunk_index, c.text, c.vector_id, c.page, c.sheet)
|
|
3032
|
-
);
|
|
3033
|
-
await env.DB.batch(stmts);
|
|
3034
|
-
}
|
|
3035
|
-
|
|
3036
|
-
return {
|
|
3037
|
-
ok: true,
|
|
3038
|
-
id: docId,
|
|
3039
|
-
created_at: docInsert.created_at,
|
|
3040
|
-
filename,
|
|
3041
|
-
mime,
|
|
3042
|
-
size_bytes: bytes.length,
|
|
3043
|
-
total_chars: totalChars,
|
|
3044
|
-
chunk_count: extracted.length,
|
|
3045
|
-
};
|
|
3046
|
-
}
|
|
3047
|
-
|
|
3048
|
-
// v0.26.0: a .zip upload is imported durably via the LongRunWorkflow rather
|
|
3049
|
-
// than synchronously. We stage the archive to R2 (the workflow reads it from
|
|
3050
|
-
// there, since 10MB can't ride the workflow event payload), kick off the
|
|
3051
|
-
// workflow, and return its instance id as job_id. The client polls
|
|
3052
|
-
// GET /api/import/:id for the result. Expansion + per-file ingest happen in
|
|
3053
|
-
// separate workflow steps, each with a fresh subrequest budget, so large
|
|
3054
|
-
// archives import without hitting the per-invocation subrequest limit that the
|
|
3055
|
-
// old synchronous path (v0.25.0) could approach.
|
|
3056
|
-
async function handleZipImport(env: Env, userEmail: string, zipBytes: Uint8Array): Promise<Response> {
|
|
3057
|
-
// Stage the archive so the workflow can read it back. customMetadata.user_email
|
|
3058
|
-
// matches the convention used for every other R2 object.
|
|
3059
|
-
const zipKey = `tmp/${crypto.randomUUID()}.zip`;
|
|
3060
|
-
try {
|
|
3061
|
-
await env.R2.put(zipKey, zipBytes, {
|
|
3062
|
-
httpMetadata: { contentType: "application/zip" },
|
|
3063
|
-
customMetadata: { user_email: userEmail },
|
|
3064
|
-
});
|
|
3065
|
-
} catch (err) {
|
|
3066
|
-
return json({ error: `Failed to stage zip: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });
|
|
3067
|
-
}
|
|
3068
|
-
|
|
3069
|
-
const startedAt = new Date().toISOString();
|
|
3070
|
-
let instanceId: string;
|
|
3071
|
-
try {
|
|
3072
|
-
const instance = await env.LONGRUN.create({
|
|
3073
|
-
params: { kind: "zip_import", userEmail, zipKey, startedAtIso: startedAt } satisfies LongRunParams,
|
|
3074
|
-
});
|
|
3075
|
-
instanceId = instance.id;
|
|
3076
|
-
} catch (err) {
|
|
3077
|
-
await r2DeleteSafe(env, zipKey);
|
|
3078
|
-
return json({ error: `Failed to start import: ${err instanceof Error ? err.message : String(err)}` }, { status: 502 });
|
|
3079
|
-
}
|
|
3080
|
-
|
|
3081
|
-
// async:true tells the client to poll /api/import/:id rather than expecting
|
|
3082
|
-
// an inline result.
|
|
3083
|
-
return json({ zip: true, async: true, job_id: instanceId });
|
|
3084
|
-
}
|
|
3085
|
-
|
|
3086
|
-
// v0.26.0: poll a zip-import workflow. Translates the workflow instance status
|
|
3087
|
-
// into the same pending/done/failed vocabulary the rest of the UI uses. The
|
|
3088
|
-
// import summary is only returned to the user who started it (the workflow
|
|
3089
|
-
// records userEmail in its output), so a guessed instance id can't read another
|
|
3090
|
-
// user's result.
|
|
3091
|
-
async function handleImportStatus(request: Request, env: Env, id: string): Promise<Response> {
|
|
3092
|
-
const userEmail = await getUserEmail(request, env);
|
|
3093
|
-
let status: { status: string; output?: unknown; error?: unknown };
|
|
3094
|
-
try {
|
|
3095
|
-
const instance = await env.LONGRUN.get(id);
|
|
3096
|
-
status = await instance.status();
|
|
3097
|
-
} catch {
|
|
3098
|
-
return json({ error: "Unknown import job" }, { status: 404 });
|
|
3099
|
-
}
|
|
3100
|
-
|
|
3101
|
-
if (status.status === "complete") {
|
|
3102
|
-
const summary = (status.output ?? {}) as Partial<ZipImportSummary>;
|
|
3103
|
-
if (summary.userEmail !== userEmail) {
|
|
3104
|
-
return json({ error: "Unknown import job" }, { status: 404 });
|
|
3105
|
-
}
|
|
3106
|
-
return json({
|
|
3107
|
-
status: "done",
|
|
3108
|
-
imported_count: summary.imported_count ?? 0,
|
|
3109
|
-
total_chunks: summary.total_chunks ?? 0,
|
|
3110
|
-
imported: summary.imported ?? [],
|
|
3111
|
-
skipped: summary.skipped ?? [],
|
|
3112
|
-
});
|
|
3113
|
-
}
|
|
3114
|
-
|
|
3115
|
-
if (status.status === "errored" || status.status === "terminated") {
|
|
3116
|
-
const msg = typeof status.error === "string" ? status.error : JSON.stringify(status.error ?? "import failed");
|
|
3117
|
-
return json({ status: "failed", error: msg });
|
|
3118
|
-
}
|
|
3119
|
-
|
|
3120
|
-
// queued / running / waiting / paused / unknown -> still in progress.
|
|
3121
|
-
return json({ status: "pending" });
|
|
3122
|
-
}
|
|
3123
|
-
|
|
3124
|
-
async function handleDocumentUpload(request: Request, env: Env): Promise<Response> {
|
|
3125
|
-
const userEmail = await getUserEmail(request, env);
|
|
3126
|
-
|
|
3127
|
-
// Accept JSON { filename, mime, data: base64 } - matches the existing
|
|
3128
|
-
// attachment-upload convention used by the chat path.
|
|
3129
|
-
let body: { filename?: string; mime?: string; data?: string };
|
|
3130
|
-
try {
|
|
3131
|
-
body = await request.json();
|
|
3132
|
-
} catch {
|
|
3133
|
-
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
3134
|
-
}
|
|
3135
|
-
|
|
3136
|
-
const filename = body.filename || "untitled.txt";
|
|
3137
|
-
const mime = body.mime || "text/plain";
|
|
3138
|
-
// No file-type allowlist: any file is accepted. extractChunks routes by
|
|
3139
|
-
// format and falls back to UTF-8 text for unknown types, rejecting only
|
|
3140
|
-
// bytes that don't decode to usable text. A .zip is expanded (v0.25.0).
|
|
3141
|
-
if (!body.data) {
|
|
3142
|
-
return json({ error: "Missing file data" }, { status: 400 });
|
|
3143
|
-
}
|
|
3144
|
-
|
|
3145
|
-
// Decode base64 data URL or raw base64.
|
|
3146
|
-
let bytes: Uint8Array;
|
|
3147
|
-
try {
|
|
3148
|
-
const parsed = body.data.startsWith("data:") ? parseDataUrl(body.data) : null;
|
|
3149
|
-
bytes = parsed ? base64ToBytes(parsed.base64) : base64ToBytes(body.data);
|
|
3150
|
-
} catch (err) {
|
|
3151
|
-
return json({ error: `Bad file data: ${err instanceof Error ? err.message : err}` }, { status: 400 });
|
|
3152
|
-
}
|
|
3153
|
-
if (bytes.length > DOC_MAX_BYTES) {
|
|
3154
|
-
return json({ error: `File too large (${bytes.length} bytes, max ${DOC_MAX_BYTES})` }, { status: 413 });
|
|
3155
|
-
}
|
|
3156
|
-
|
|
3157
|
-
// v0.25.0: a zip is expanded and each inner file ingested separately.
|
|
3158
|
-
if (isZip(bytes)) {
|
|
3159
|
-
return handleZipImport(env, userEmail, bytes);
|
|
3160
|
-
}
|
|
3161
|
-
|
|
3162
|
-
const r = await ingestDocument(env, userEmail, filename, mime, bytes);
|
|
3163
|
-
if (!r.ok) return json({ error: r.error }, { status: r.status });
|
|
3164
|
-
return json({
|
|
3165
|
-
id: r.id,
|
|
3166
|
-
created_at: r.created_at,
|
|
3167
|
-
filename: r.filename,
|
|
3168
|
-
mime: r.mime,
|
|
3169
|
-
size_bytes: r.size_bytes,
|
|
3170
|
-
total_chars: r.total_chars,
|
|
3171
|
-
chunk_count: r.chunk_count,
|
|
3172
|
-
});
|
|
3173
|
-
}
|
|
3174
|
-
|
|
3175
|
-
async function handleDocumentDelete(request: Request, env: Env, id: number): Promise<Response> {
|
|
3176
|
-
const userEmail = await getUserEmail(request, env);
|
|
3177
|
-
|
|
3178
|
-
const doc = await env.DB.prepare(
|
|
3179
|
-
`SELECT r2_key FROM documents WHERE id = ? AND user_email = ?`
|
|
3180
|
-
)
|
|
3181
|
-
.bind(id, userEmail)
|
|
3182
|
-
.first<{ r2_key: string }>();
|
|
3183
|
-
if (!doc) return json({ error: "Not found" }, { status: 404 });
|
|
3184
|
-
|
|
3185
|
-
// Collect vector IDs first so we can clean them out of Vectorize.
|
|
3186
|
-
const chunkRows = await env.DB.prepare(
|
|
3187
|
-
`SELECT vector_id FROM chunks WHERE document_id = ? AND user_email = ?`
|
|
3188
|
-
)
|
|
3189
|
-
.bind(id, userEmail)
|
|
3190
|
-
.all<{ vector_id: string }>();
|
|
3191
|
-
|
|
3192
|
-
const vectorIds = (chunkRows.results ?? []).map((r) => r.vector_id);
|
|
3193
|
-
if (vectorIds.length) {
|
|
3194
|
-
try { await env.VEC.deleteByIds(vectorIds); } catch { /* best effort */ }
|
|
3195
|
-
}
|
|
3196
|
-
|
|
3197
|
-
// Cascade delete in D1 (no real FK enforcement, so explicit) and R2.
|
|
3198
|
-
// v0.20.1: also clean up project_documents memberships so deleting a doc
|
|
3199
|
-
// that's attached to projects doesn't leave orphan membership rows.
|
|
3200
|
-
// v0.20.3: also clean up project_messages (raw Discord rows) for the doc.
|
|
3201
|
-
await env.DB.batch([
|
|
3202
|
-
env.DB.prepare(`DELETE FROM chunks WHERE document_id = ? AND user_email = ?`).bind(id, userEmail),
|
|
3203
|
-
env.DB.prepare(`DELETE FROM project_documents WHERE document_id = ?`).bind(id),
|
|
3204
|
-
env.DB.prepare(`DELETE FROM project_messages WHERE document_id = ?`).bind(id),
|
|
3205
|
-
env.DB.prepare(`DELETE FROM documents WHERE id = ? AND user_email = ?`).bind(id, userEmail),
|
|
3206
|
-
]);
|
|
3207
|
-
await r2DeleteSafe(env, doc.r2_key);
|
|
3208
|
-
|
|
3209
|
-
return json({ deleted: id, vectors_removed: vectorIds.length });
|
|
3210
|
-
}
|
|
3211
|
-
|
|
3212
|
-
// ---------- Projects (v0.20.0) ----------
|
|
3213
|
-
//
|
|
3214
|
-
// Projects group documents (and in v0.20.1 onward, conversations) under a
|
|
3215
|
-
// shared system_prompt and retrieval scope. v0.20.0 endpoints:
|
|
3216
|
-
//
|
|
3217
|
-
// GET /api/projects list user's projects
|
|
3218
|
-
// POST /api/projects create project
|
|
3219
|
-
// GET /api/projects/:id get project + members
|
|
3220
|
-
// PATCH /api/projects/:id rename / update prompt / desc
|
|
3221
|
-
// DELETE /api/projects/:id delete (cascades to memberships)
|
|
3222
|
-
// POST /api/projects/:pid/documents/:did add document to project
|
|
3223
|
-
// DELETE /api/projects/:pid/documents/:did remove document from project
|
|
3224
|
-
// GET /api/documents?project_id=N list docs in project
|
|
3225
|
-
//
|
|
3226
|
-
// All endpoints scope by user_email; cross-user reads return 404,
|
|
3227
|
-
// cross-user writes (e.g. adding another user's doc to your project) are
|
|
3228
|
-
// rejected with 400 before touching the DB.
|
|
3229
|
-
//
|
|
3230
|
-
// Per-project system prompt fallback (handleChat / handleChatStream):
|
|
3231
|
-
// when a chat request includes project_id but no per-turn system_prompt,
|
|
3232
|
-
// the project's system_prompt is used as default. A per-turn system_prompt
|
|
3233
|
-
// always overrides; empty-string system_prompt counts as "set to empty"
|
|
3234
|
-
// and disables the fallback (intentional - lets users explicitly clear).
|
|
3235
|
-
//
|
|
3236
|
-
// Per-project RAG scoping (retrieveContext): when a chat request includes
|
|
3237
|
-
// project_id, retrieval joins project_documents and excludes chunks from
|
|
3238
|
-
// documents not in that project's membership set. No project_id means
|
|
3239
|
-
// "all user's docs" (backward compat).
|
|
3240
|
-
|
|
3241
|
-
// Generate a URL-safe slug from a display name. Strips non-alphanumeric
|
|
3242
|
-
// characters, collapses runs of whitespace and dashes, lowercases, trims.
|
|
3243
|
-
// Empty input or all-punctuation input falls back to "project".
|
|
3244
|
-
function slugify(name: string): string {
|
|
3245
|
-
const s = name
|
|
3246
|
-
.toLowerCase()
|
|
3247
|
-
.normalize("NFKD")
|
|
3248
|
-
.replace(/[^a-z0-9\s-]+/g, "") // drop punctuation/diacritics
|
|
3249
|
-
.trim()
|
|
3250
|
-
.replace(/[\s-]+/g, "-") // collapse whitespace runs to single dash
|
|
3251
|
-
.replace(/^-+|-+$/g, ""); // trim leading/trailing dashes
|
|
3252
|
-
return s || "project";
|
|
3253
|
-
}
|
|
3254
|
-
|
|
3255
|
-
// Find an unused slug for the user. If `base` is unused, returns base.
|
|
3256
|
-
// Otherwise appends -2, -3, ... until free. Bounded at 200 attempts;
|
|
3257
|
-
// beyond that we throw, which would indicate a degenerate slug or a
|
|
3258
|
-
// pathological state.
|
|
3259
|
-
async function findFreeSlug(env: Env, userEmail: string, base: string): Promise<string> {
|
|
3260
|
-
let candidate = base;
|
|
3261
|
-
let suffix = 2;
|
|
3262
|
-
while (suffix < 200) {
|
|
3263
|
-
const existing = await env.DB.prepare(
|
|
3264
|
-
`SELECT id FROM projects WHERE user_email = ? AND slug = ? LIMIT 1`
|
|
3265
|
-
)
|
|
3266
|
-
.bind(userEmail, candidate)
|
|
3267
|
-
.first();
|
|
3268
|
-
if (!existing) return candidate;
|
|
3269
|
-
candidate = `${base}-${suffix}`;
|
|
3270
|
-
suffix++;
|
|
3271
|
-
}
|
|
3272
|
-
throw new Error(`Could not allocate slug after 200 attempts (base='${base}')`);
|
|
3273
|
-
}
|
|
3274
|
-
|
|
3275
|
-
// Shared helper used by runChat + runChatStream. Resolves the chat's
|
|
3276
|
-
// project_id (if any), looks up the project row scoped to the user, and
|
|
3277
|
-
// computes the effective system prompt with project-fallback semantics.
|
|
3278
|
-
//
|
|
3279
|
-
// Semantics:
|
|
3280
|
-
// - body.project_id is undefined or not a positive integer: no project.
|
|
3281
|
-
// - body.project_id points to a project not owned by this user: treated
|
|
3282
|
-
// same as missing (returns project=null, no fallback). Logged.
|
|
3283
|
-
// - body.project_id points to a deleted/unknown project: same as above.
|
|
3284
|
-
//
|
|
3285
|
-
// - Per-turn body.system_prompt non-empty (after trim) wins outright;
|
|
3286
|
-
// the project's system_prompt is ignored.
|
|
3287
|
-
// - Per-turn body.system_prompt is undefined or empty/whitespace AND a
|
|
3288
|
-
// project is resolved AND that project has a non-null system_prompt:
|
|
3289
|
-
// use the project's prompt.
|
|
3290
|
-
// - Otherwise: no effective prompt (undefined).
|
|
3291
|
-
//
|
|
3292
|
-
// The resolved project_id is also returned for retrieveContext scoping.
|
|
3293
|
-
async function resolveProjectForChat(
|
|
3294
|
-
env: Env,
|
|
3295
|
-
userEmail: string,
|
|
3296
|
-
body: ChatRequest,
|
|
3297
|
-
): Promise<{ project: ProjectRow | null; resolvedSystemPrompt: string | undefined; scopedProjectId: number | undefined }> {
|
|
3298
|
-
let project: ProjectRow | null = null;
|
|
3299
|
-
let scopedProjectId: number | undefined;
|
|
3300
|
-
|
|
3301
|
-
if (body.project_id !== undefined && Number.isInteger(body.project_id) && body.project_id > 0) {
|
|
3302
|
-
project = await env.DB.prepare(
|
|
3303
|
-
`SELECT id, user_email, name, slug, description, system_prompt, created_at, updated_at
|
|
3304
|
-
FROM projects WHERE id = ? AND user_email = ?`
|
|
3305
|
-
)
|
|
3306
|
-
.bind(body.project_id, userEmail)
|
|
3307
|
-
.first<ProjectRow>();
|
|
3308
|
-
if (!project) {
|
|
3309
|
-
console.warn(
|
|
3310
|
-
`Chat referenced unknown project_id=${body.project_id} for user_email='${userEmail}'; ` +
|
|
3311
|
-
`falling back to no-project semantics (no system prompt fallback, no retrieval scoping).`
|
|
3312
|
-
);
|
|
3313
|
-
} else {
|
|
3314
|
-
scopedProjectId = project.id;
|
|
3315
|
-
}
|
|
3316
|
-
}
|
|
3317
|
-
|
|
3318
|
-
const reqPrompt = body.system_prompt;
|
|
3319
|
-
const hasReqPrompt = reqPrompt !== undefined && reqPrompt.trim() !== "";
|
|
3320
|
-
const resolvedSystemPrompt = hasReqPrompt
|
|
3321
|
-
? reqPrompt
|
|
3322
|
-
: (project?.system_prompt ?? undefined);
|
|
3323
|
-
|
|
3324
|
-
return { project, resolvedSystemPrompt, scopedProjectId };
|
|
3325
|
-
}
|
|
3326
|
-
|
|
3327
|
-
async function handleProjectList(request: Request, env: Env): Promise<Response> {
|
|
3328
|
-
const userEmail = await getUserEmail(request, env);
|
|
3329
|
-
// LEFT JOIN to count document memberships per project. COUNT(pd.document_id)
|
|
3330
|
-
// returns 0 for projects with no members (because of LEFT JOIN), rather
|
|
3331
|
-
// than 1 which COUNT(*) would return.
|
|
3332
|
-
const rows = await env.DB.prepare(
|
|
3333
|
-
`SELECT p.id, p.name, p.slug, p.description, p.system_prompt,
|
|
3334
|
-
p.created_at, p.updated_at,
|
|
3335
|
-
COUNT(pd.document_id) AS document_count
|
|
3336
|
-
FROM projects p
|
|
3337
|
-
LEFT JOIN project_documents pd ON pd.project_id = p.id
|
|
3338
|
-
WHERE p.user_email = ?
|
|
3339
|
-
GROUP BY p.id
|
|
3340
|
-
ORDER BY p.created_at DESC`
|
|
3341
|
-
)
|
|
3342
|
-
.bind(userEmail)
|
|
3343
|
-
.all<{
|
|
3344
|
-
id: number; name: string; slug: string; description: string | null;
|
|
3345
|
-
system_prompt: string | null; created_at: string; updated_at: string;
|
|
3346
|
-
document_count: number;
|
|
3347
|
-
}>();
|
|
3348
|
-
return json({ user: userEmail, projects: rows.results ?? [] });
|
|
3349
|
-
}
|
|
3350
|
-
|
|
3351
|
-
async function handleProjectGet(request: Request, env: Env, id: number): Promise<Response> {
|
|
3352
|
-
const userEmail = await getUserEmail(request, env);
|
|
3353
|
-
const proj = await env.DB.prepare(
|
|
3354
|
-
`SELECT id, name, slug, description, system_prompt, created_at, updated_at
|
|
3355
|
-
FROM projects WHERE id = ? AND user_email = ?`
|
|
3356
|
-
)
|
|
3357
|
-
.bind(id, userEmail)
|
|
3358
|
-
.first<ProjectRow>();
|
|
3359
|
-
if (!proj) return json({ error: "Not found" }, { status: 404 });
|
|
3360
|
-
|
|
3361
|
-
// Include the project's documents (id, filename, chunk_count) so the
|
|
3362
|
-
// detail view can render them without a second fetch.
|
|
3363
|
-
const docs = await env.DB.prepare(
|
|
3364
|
-
`SELECT d.id, d.filename, d.mime, d.size_bytes, d.chunk_count, d.created_at,
|
|
3365
|
-
pd.added_at
|
|
3366
|
-
FROM project_documents pd
|
|
3367
|
-
JOIN documents d ON d.id = pd.document_id
|
|
3368
|
-
WHERE pd.project_id = ? AND d.user_email = ?
|
|
3369
|
-
ORDER BY pd.added_at DESC`
|
|
3370
|
-
)
|
|
3371
|
-
.bind(id, userEmail)
|
|
3372
|
-
.all<{
|
|
3373
|
-
id: number; filename: string; mime: string; size_bytes: number;
|
|
3374
|
-
chunk_count: number; created_at: string; added_at: string;
|
|
3375
|
-
}>();
|
|
3376
|
-
|
|
3377
|
-
return json({ project: proj, documents: docs.results ?? [] });
|
|
3378
|
-
}
|
|
3379
|
-
|
|
3380
|
-
async function handleProjectCreate(request: Request, env: Env): Promise<Response> {
|
|
3381
|
-
const userEmail = await getUserEmail(request, env);
|
|
3382
|
-
let body: { name?: string; description?: string; system_prompt?: string };
|
|
3383
|
-
try {
|
|
3384
|
-
body = await request.json();
|
|
3385
|
-
} catch {
|
|
3386
|
-
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
3387
|
-
}
|
|
3388
|
-
const name = (body.name ?? "").trim();
|
|
3389
|
-
if (!name) return json({ error: "name is required" }, { status: 400 });
|
|
3390
|
-
if (name.length > 200) return json({ error: "name too long (max 200 chars)" }, { status: 400 });
|
|
3391
|
-
|
|
3392
|
-
const baseSlug = slugify(name);
|
|
3393
|
-
const slug = await findFreeSlug(env, userEmail, baseSlug);
|
|
3394
|
-
|
|
3395
|
-
const description = (body.description ?? "").trim() || null;
|
|
3396
|
-
const systemPrompt = (body.system_prompt ?? "").trim() || null;
|
|
3397
|
-
|
|
3398
|
-
const result = await env.DB.prepare(
|
|
3399
|
-
`INSERT INTO projects (user_email, name, slug, description, system_prompt)
|
|
3400
|
-
VALUES (?, ?, ?, ?, ?)
|
|
3401
|
-
RETURNING id, name, slug, description, system_prompt, created_at, updated_at`
|
|
3402
|
-
)
|
|
3403
|
-
.bind(userEmail, name, slug, description, systemPrompt)
|
|
3404
|
-
.first<ProjectRow>();
|
|
3405
|
-
|
|
3406
|
-
if (!result) return json({ error: "Insert failed" }, { status: 500 });
|
|
3407
|
-
return json({ project: result }, { status: 201 });
|
|
3408
|
-
}
|
|
3409
|
-
|
|
3410
|
-
async function handleProjectUpdate(request: Request, env: Env, id: number): Promise<Response> {
|
|
3411
|
-
const userEmail = await getUserEmail(request, env);
|
|
3412
|
-
// Confirm ownership before any write.
|
|
3413
|
-
const existing = await env.DB.prepare(
|
|
3414
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
3415
|
-
)
|
|
3416
|
-
.bind(id, userEmail)
|
|
3417
|
-
.first();
|
|
3418
|
-
if (!existing) return json({ error: "Not found" }, { status: 404 });
|
|
3419
|
-
|
|
3420
|
-
let body: { name?: string; description?: string | null; system_prompt?: string | null };
|
|
3421
|
-
try {
|
|
3422
|
-
body = await request.json();
|
|
3423
|
-
} catch {
|
|
3424
|
-
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
3425
|
-
}
|
|
3426
|
-
|
|
3427
|
-
// Build dynamic UPDATE based on which fields the caller sent. Undefined =
|
|
3428
|
-
// "don't touch"; null or empty string = "clear to empty/null". Name has
|
|
3429
|
-
// to be a non-empty string if provided.
|
|
3430
|
-
const sets: string[] = [];
|
|
3431
|
-
const params: Array<string | number | null> = [];
|
|
3432
|
-
|
|
3433
|
-
if (body.name !== undefined) {
|
|
3434
|
-
const n = body.name.trim();
|
|
3435
|
-
if (!n) return json({ error: "name cannot be empty" }, { status: 400 });
|
|
3436
|
-
if (n.length > 200) return json({ error: "name too long (max 200 chars)" }, { status: 400 });
|
|
3437
|
-
sets.push("name = ?");
|
|
3438
|
-
params.push(n);
|
|
3439
|
-
}
|
|
3440
|
-
if (body.description !== undefined) {
|
|
3441
|
-
const d = (body.description ?? "").toString().trim() || null;
|
|
3442
|
-
sets.push("description = ?");
|
|
3443
|
-
params.push(d);
|
|
3444
|
-
}
|
|
3445
|
-
if (body.system_prompt !== undefined) {
|
|
3446
|
-
const sp = (body.system_prompt ?? "").toString().trim() || null;
|
|
3447
|
-
sets.push("system_prompt = ?");
|
|
3448
|
-
params.push(sp);
|
|
3449
|
-
}
|
|
3450
|
-
|
|
3451
|
-
if (sets.length === 0) {
|
|
3452
|
-
return json({ error: "No updatable fields in body" }, { status: 400 });
|
|
3453
|
-
}
|
|
3454
|
-
|
|
3455
|
-
// Slug is intentionally NOT updated on rename. Keeps URLs/storage keys
|
|
3456
|
-
// stable. If renames need new slugs, that's a separate explicit op.
|
|
3457
|
-
sets.push("updated_at = datetime('now')");
|
|
3458
|
-
params.push(id, userEmail);
|
|
3459
|
-
|
|
3460
|
-
await env.DB.prepare(
|
|
3461
|
-
`UPDATE projects SET ${sets.join(", ")} WHERE id = ? AND user_email = ?`
|
|
3462
|
-
)
|
|
3463
|
-
.bind(...params)
|
|
3464
|
-
.run();
|
|
3465
|
-
|
|
3466
|
-
const updated = await env.DB.prepare(
|
|
3467
|
-
`SELECT id, name, slug, description, system_prompt, created_at, updated_at
|
|
3468
|
-
FROM projects WHERE id = ? AND user_email = ?`
|
|
3469
|
-
)
|
|
3470
|
-
.bind(id, userEmail)
|
|
3471
|
-
.first<ProjectRow>();
|
|
3472
|
-
return json({ project: updated });
|
|
3473
|
-
}
|
|
3474
|
-
|
|
3475
|
-
async function handleProjectDelete(request: Request, env: Env, id: number): Promise<Response> {
|
|
3476
|
-
const userEmail = await getUserEmail(request, env);
|
|
3477
|
-
const existing = await env.DB.prepare(
|
|
3478
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
3479
|
-
)
|
|
3480
|
-
.bind(id, userEmail)
|
|
3481
|
-
.first();
|
|
3482
|
-
if (!existing) return json({ error: "Not found" }, { status: 404 });
|
|
3483
|
-
|
|
3484
|
-
// Cascade: delete memberships first, then the project itself. Documents
|
|
3485
|
-
// belonging to the project STAY (they may be in other projects, and even
|
|
3486
|
-
// if not, the user uploaded them and may want to keep them outside
|
|
3487
|
-
// project organization). v0.20.3: also clear project_messages scoped to
|
|
3488
|
-
// this project (raw Discord rows; the documents and their chunks stay).
|
|
3489
|
-
await env.DB.batch([
|
|
3490
|
-
env.DB.prepare(`DELETE FROM project_documents WHERE project_id = ?`).bind(id),
|
|
3491
|
-
env.DB.prepare(`DELETE FROM project_messages WHERE project_id = ?`).bind(id),
|
|
3492
|
-
env.DB.prepare(`DELETE FROM projects WHERE id = ? AND user_email = ?`).bind(id, userEmail),
|
|
3493
|
-
]);
|
|
3494
|
-
return json({ deleted: id });
|
|
3495
|
-
}
|
|
3496
|
-
|
|
3497
|
-
async function handleProjectDocAdd(request: Request, env: Env, projectId: number, docId: number): Promise<Response> {
|
|
3498
|
-
const userEmail = await getUserEmail(request, env);
|
|
3499
|
-
// Confirm both project and document belong to the user. Cross-user
|
|
3500
|
-
// attachment is rejected here.
|
|
3501
|
-
const proj = await env.DB.prepare(
|
|
3502
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
3503
|
-
)
|
|
3504
|
-
.bind(projectId, userEmail)
|
|
3505
|
-
.first();
|
|
3506
|
-
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
3507
|
-
|
|
3508
|
-
const doc = await env.DB.prepare(
|
|
3509
|
-
`SELECT id FROM documents WHERE id = ? AND user_email = ?`
|
|
3510
|
-
)
|
|
3511
|
-
.bind(docId, userEmail)
|
|
3512
|
-
.first();
|
|
3513
|
-
if (!doc) return json({ error: "Document not found" }, { status: 404 });
|
|
3514
|
-
|
|
3515
|
-
// INSERT OR IGNORE: idempotent membership. Reattaching a doc that's
|
|
3516
|
-
// already a member returns 200 without an error (added_at stays at the
|
|
3517
|
-
// original value).
|
|
3518
|
-
await env.DB.prepare(
|
|
3519
|
-
`INSERT OR IGNORE INTO project_documents (project_id, document_id) VALUES (?, ?)`
|
|
3520
|
-
)
|
|
3521
|
-
.bind(projectId, docId)
|
|
3522
|
-
.run();
|
|
3523
|
-
return json({ project_id: projectId, document_id: docId, added: true });
|
|
3524
|
-
}
|
|
3525
|
-
|
|
3526
|
-
async function handleProjectDocRemove(request: Request, env: Env, projectId: number, docId: number): Promise<Response> {
|
|
3527
|
-
const userEmail = await getUserEmail(request, env);
|
|
3528
|
-
const proj = await env.DB.prepare(
|
|
3529
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
3530
|
-
)
|
|
3531
|
-
.bind(projectId, userEmail)
|
|
3532
|
-
.first();
|
|
3533
|
-
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
3534
|
-
|
|
3535
|
-
await env.DB.prepare(
|
|
3536
|
-
`DELETE FROM project_documents WHERE project_id = ? AND document_id = ?`
|
|
3537
|
-
)
|
|
3538
|
-
.bind(projectId, docId)
|
|
3539
|
-
.run();
|
|
3540
|
-
return json({ project_id: projectId, document_id: docId, removed: true });
|
|
3541
|
-
}
|
|
3542
|
-
|
|
3543
|
-
// v0.20.3: import a DiscordChatExporter JSON export into a project.
|
|
3544
|
-
//
|
|
3545
|
-
// POST /api/projects/:id/import-discord
|
|
3546
|
-
// Body: { filename?: string, data: base64, options?: { gapMinutes, includeBots } }
|
|
3547
|
-
//
|
|
3548
|
-
// Pipeline (mirrors handleDocumentUpload, but for Discord exports):
|
|
3549
|
-
// 1. validate project ownership
|
|
3550
|
-
// 2. decode + size-check the export bytes
|
|
3551
|
-
// 3. parse DCE JSON -> normalized messages (parseDiscordExport)
|
|
3552
|
-
// 4. conversation-aware chunk (chunkDiscordMessages)
|
|
3553
|
-
// 5. store export bytes in R2
|
|
3554
|
-
// 6. insert a documents row for the export file
|
|
3555
|
-
// 7. attach the document to the project (project_documents)
|
|
3556
|
-
// 8. persist raw messages to project_messages (for future re-chunking)
|
|
3557
|
-
// 9. embed chunks, upsert to Vectorize, insert chunk rows with the
|
|
3558
|
-
// channel/authors/time metadata columns
|
|
3559
|
-
//
|
|
3560
|
-
// The chunk embed/store loop is intentionally a near-duplicate of the one in
|
|
3561
|
-
// handleDocumentUpload rather than a shared helper: the document path is the
|
|
3562
|
-
// higher-traffic code and has no integration tests, so refactoring it to
|
|
3563
|
-
// share code carries regression risk disproportionate to ~30 saved lines.
|
|
3564
|
-
// Consolidation is a candidate for a later cleanup release once integration
|
|
3565
|
-
// tests exist.
|
|
3566
|
-
async function handleDiscordImport(request: Request, env: Env, projectId: number): Promise<Response> {
|
|
3567
|
-
const userEmail = await getUserEmail(request, env);
|
|
3568
|
-
|
|
3569
|
-
const proj = await env.DB.prepare(
|
|
3570
|
-
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
3571
|
-
)
|
|
3572
|
-
.bind(projectId, userEmail)
|
|
3573
|
-
.first();
|
|
3574
|
-
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
3575
|
-
|
|
3576
|
-
let body: { filename?: string; data?: string; options?: { gapMinutes?: number; includeBots?: boolean } };
|
|
3577
|
-
try {
|
|
3578
|
-
body = await request.json();
|
|
3579
|
-
} catch {
|
|
3580
|
-
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
3581
|
-
}
|
|
3582
|
-
if (!body.data) {
|
|
3583
|
-
return json({ error: "Missing export data" }, { status: 400 });
|
|
3584
|
-
}
|
|
3585
|
-
|
|
3586
|
-
const filename = body.filename || "discord-export.json";
|
|
3587
|
-
|
|
3588
|
-
// Decode base64 (data URL or raw).
|
|
3589
|
-
let bytes: Uint8Array;
|
|
3590
|
-
try {
|
|
3591
|
-
const parsed = body.data.startsWith("data:") ? parseDataUrl(body.data) : null;
|
|
3592
|
-
bytes = parsed ? base64ToBytes(parsed.base64) : base64ToBytes(body.data);
|
|
3593
|
-
} catch (err) {
|
|
3594
|
-
return json({ error: `Bad export data: ${err instanceof Error ? err.message : err}` }, { status: 400 });
|
|
3595
|
-
}
|
|
3596
|
-
if (bytes.length > DOC_MAX_BYTES) {
|
|
3597
|
-
return json({
|
|
3598
|
-
error: `Export too large (${bytes.length} bytes, max ${DOC_MAX_BYTES}). Split the export by date range or channel, or wait for presigned upload (v0.20.4).`,
|
|
3599
|
-
}, { status: 413 });
|
|
3600
|
-
}
|
|
3601
|
-
|
|
3602
|
-
// Parse the JSON export.
|
|
3603
|
-
let exportJson: unknown;
|
|
3604
|
-
try {
|
|
3605
|
-
exportJson = JSON.parse(new TextDecoder().decode(bytes));
|
|
3606
|
-
} catch (err) {
|
|
3607
|
-
return json({ error: `Export is not valid JSON: ${err instanceof Error ? err.message : err}` }, { status: 400 });
|
|
3608
|
-
}
|
|
3609
|
-
|
|
3610
|
-
let parsed;
|
|
3611
|
-
try {
|
|
3612
|
-
parsed = parseDiscordExport(exportJson);
|
|
3613
|
-
} catch (err) {
|
|
3614
|
-
return json({ error: `Not a recognized DiscordChatExporter export: ${err instanceof Error ? err.message : err}` }, { status: 400 });
|
|
3615
|
-
}
|
|
3616
|
-
if (parsed.messages.length === 0) {
|
|
3617
|
-
return json({
|
|
3618
|
-
error: "No usable messages in the export (all were system notifications or empty). Nothing to import.",
|
|
3619
|
-
}, { status: 400 });
|
|
3620
|
-
}
|
|
3621
|
-
|
|
3622
|
-
const chunks = chunkDiscordMessages(parsed.messages, {
|
|
3623
|
-
gapMinutes: body.options?.gapMinutes,
|
|
3624
|
-
includeBots: body.options?.includeBots,
|
|
3625
|
-
});
|
|
3626
|
-
if (chunks.length === 0) {
|
|
3627
|
-
return json({ error: "Parsing produced messages but chunking produced none (check includeBots option)." }, { status: 400 });
|
|
3628
|
-
}
|
|
3629
|
-
|
|
3630
|
-
const totalChars = chunks.reduce((sum, c) => sum + c.text.length, 0);
|
|
3631
|
-
const mime = "application/json";
|
|
3632
|
-
const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
|
|
3633
|
-
|
|
3634
|
-
// Insert the documents row for the export file.
|
|
3635
|
-
const docInsert = await env.DB.prepare(
|
|
3636
|
-
`INSERT INTO documents
|
|
3637
|
-
(user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
|
|
3638
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
3639
|
-
RETURNING id, created_at`
|
|
3640
|
-
)
|
|
3641
|
-
.bind(userEmail, filename, mime, r2Key, bytes.length, totalChars, chunks.length)
|
|
3642
|
-
.first<{ id: number; created_at: string }>();
|
|
3643
|
-
if (!docInsert) {
|
|
3644
|
-
await r2DeleteSafe(env, r2Key);
|
|
3645
|
-
return json({ error: "Failed to insert document row" }, { status: 500 });
|
|
3646
|
-
}
|
|
3647
|
-
const docId = docInsert.id;
|
|
3648
|
-
|
|
3649
|
-
// Attach the export document to the project so project-scoped retrieval
|
|
3650
|
-
// includes it immediately.
|
|
3651
|
-
await env.DB.prepare(
|
|
3652
|
-
`INSERT OR IGNORE INTO project_documents (project_id, document_id) VALUES (?, ?)`
|
|
3653
|
-
)
|
|
3654
|
-
.bind(projectId, docId)
|
|
3655
|
-
.run();
|
|
3656
|
-
|
|
3657
|
-
// Persist raw messages for future re-chunking. Batched in groups to stay
|
|
3658
|
-
// within D1 statement limits.
|
|
3659
|
-
const PM_BATCH = 50;
|
|
3660
|
-
for (let i = 0; i < parsed.messages.length; i += PM_BATCH) {
|
|
3661
|
-
const slice = parsed.messages.slice(i, i + PM_BATCH);
|
|
3662
|
-
const stmts = slice.map((m) =>
|
|
3663
|
-
env.DB.prepare(
|
|
3664
|
-
`INSERT INTO project_messages
|
|
3665
|
-
(project_id, document_id, user_email, message_id, channel, author, author_id, is_bot, sent_at, content)
|
|
3666
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
3667
|
-
).bind(projectId, docId, userEmail, m.messageId, m.channel, m.author, m.authorId, m.isBot ? 1 : 0, m.sentAt, m.content)
|
|
3668
|
-
);
|
|
3669
|
-
await env.DB.batch(stmts);
|
|
3670
|
-
}
|
|
3671
|
-
|
|
3672
|
-
// Embed chunks and upsert to Vectorize. vector_id scheme matches documents:
|
|
3673
|
-
// `${userEmail}:${docId}:${chunkIndex}`.
|
|
3674
|
-
const vectorIdsWritten: string[] = [];
|
|
3675
|
-
const chunkRowsToInsert: {
|
|
3676
|
-
chunk_index: number;
|
|
3677
|
-
text: string;
|
|
3678
|
-
vector_id: string;
|
|
3679
|
-
channel: string;
|
|
3680
|
-
authors: string;
|
|
3681
|
-
sent_at_start: string;
|
|
3682
|
-
sent_at_end: string;
|
|
3683
|
-
}[] = [];
|
|
3684
|
-
|
|
3685
|
-
try {
|
|
3686
|
-
for (let b = 0; b < chunks.length; b += EMBED_BATCH_SIZE) {
|
|
3687
|
-
const batch = chunks.slice(b, b + EMBED_BATCH_SIZE);
|
|
3688
|
-
const vectors = await embedBatch(env, userEmail, batch.map((c) => c.text));
|
|
3689
|
-
if (vectors.length !== batch.length) {
|
|
3690
|
-
throw new Error(`Embedding batch returned ${vectors.length} vectors for ${batch.length} texts`);
|
|
3691
|
-
}
|
|
3692
|
-
const payload = batch.map((c, i) => {
|
|
3693
|
-
const idx = b + i;
|
|
3694
|
-
const vid = `${userEmail}:${docId}:${idx}`;
|
|
3695
|
-
chunkRowsToInsert.push({
|
|
3696
|
-
chunk_index: idx,
|
|
3697
|
-
text: c.text,
|
|
3698
|
-
vector_id: vid,
|
|
3699
|
-
channel: c.channel,
|
|
3700
|
-
authors: c.authors.join(", "),
|
|
3701
|
-
sent_at_start: c.sentAtStart,
|
|
3702
|
-
sent_at_end: c.sentAtEnd,
|
|
3703
|
-
});
|
|
3704
|
-
vectorIdsWritten.push(vid);
|
|
3705
|
-
return {
|
|
3706
|
-
id: vid,
|
|
3707
|
-
values: vectors[i],
|
|
3708
|
-
metadata: {
|
|
3709
|
-
user_email: userEmail,
|
|
3710
|
-
document_id: docId,
|
|
3711
|
-
chunk_index: idx,
|
|
3712
|
-
channel: c.channel,
|
|
3713
|
-
},
|
|
3714
|
-
};
|
|
3715
|
-
});
|
|
3716
|
-
await env.VEC.upsert(payload);
|
|
3717
|
-
}
|
|
3718
|
-
} catch (err) {
|
|
3719
|
-
// Rollback partial state.
|
|
3720
|
-
if (vectorIdsWritten.length) {
|
|
3721
|
-
try { await env.VEC.deleteByIds(vectorIdsWritten); } catch { /* swallow */ }
|
|
3722
|
-
}
|
|
3723
|
-
await env.DB.batch([
|
|
3724
|
-
env.DB.prepare(`DELETE FROM project_messages WHERE document_id = ?`).bind(docId),
|
|
3725
|
-
env.DB.prepare(`DELETE FROM project_documents WHERE document_id = ?`).bind(docId),
|
|
3726
|
-
env.DB.prepare(`DELETE FROM documents WHERE id = ?`).bind(docId),
|
|
3727
|
-
]);
|
|
3728
|
-
await r2DeleteSafe(env, r2Key);
|
|
3729
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
3730
|
-
return json({ error: `Embedding failed: ${m}` }, { status: 502 });
|
|
3731
|
-
}
|
|
3732
|
-
|
|
3733
|
-
// Insert chunk rows with the Discord metadata columns. page/sheet stay NULL.
|
|
3734
|
-
if (chunkRowsToInsert.length) {
|
|
3735
|
-
for (let i = 0; i < chunkRowsToInsert.length; i += PM_BATCH) {
|
|
3736
|
-
const slice = chunkRowsToInsert.slice(i, i + PM_BATCH);
|
|
3737
|
-
const stmts = slice.map((c) =>
|
|
3738
|
-
env.DB.prepare(
|
|
3739
|
-
`INSERT INTO chunks
|
|
3740
|
-
(document_id, user_email, chunk_index, text, vector_id, channel, authors, sent_at_start, sent_at_end)
|
|
3741
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
3742
|
-
).bind(docId, userEmail, c.chunk_index, c.text, c.vector_id, c.channel, c.authors, c.sent_at_start, c.sent_at_end)
|
|
3743
|
-
);
|
|
3744
|
-
await env.DB.batch(stmts);
|
|
3745
|
-
}
|
|
3746
|
-
}
|
|
3747
|
-
|
|
3748
|
-
return json({
|
|
3749
|
-
document_id: docId,
|
|
3750
|
-
created_at: docInsert.created_at,
|
|
3751
|
-
project_id: projectId,
|
|
3752
|
-
filename,
|
|
3753
|
-
guild: parsed.guild,
|
|
3754
|
-
channel: parsed.channel,
|
|
3755
|
-
raw_message_count: parsed.rawCount,
|
|
3756
|
-
imported_message_count: parsed.parsedCount,
|
|
3757
|
-
chunk_count: chunks.length,
|
|
3758
|
-
});
|
|
3759
|
-
}
|
|
3760
|
-
|
|
3761
|
-
// ---------- Artifact serving ----------
|
|
3762
|
-
|
|
3763
|
-
async function handleArtifact(request: Request, env: Env, key: string): Promise<Response> {
|
|
3764
|
-
const userEmail = await getUserEmail(request, env);
|
|
3765
|
-
// Artifacts (chat input + output) all live on env.R2.
|
|
3766
|
-
const bucket = env.R2;
|
|
3767
|
-
// v0.142.0: forward the request's conditional headers (If-None-Match) to R2.
|
|
3768
|
-
// With a conditional get, R2 returns the object WITHOUT a body when the
|
|
3769
|
-
// client's ETag still matches, and we reply 304 (a ~0-byte revalidation);
|
|
3770
|
-
// a changed object returns fresh bytes. customMetadata is present on the
|
|
3771
|
-
// body-less R2Object too, so the ownership check is unaffected.
|
|
3772
|
-
const obj = await bucket.get(key, { onlyIf: request.headers });
|
|
3773
|
-
if (!obj) return new Response("Not Found", { status: 404 });
|
|
3774
|
-
|
|
3775
|
-
// Authorization: only the user who created the artifact may fetch it.
|
|
3776
|
-
// We stored user_email in customMetadata at put time. Checked before any
|
|
3777
|
-
// 304 so a non-owner with a guessed ETag still gets 403, never a hit/miss.
|
|
3778
|
-
const owner = obj.customMetadata?.user_email;
|
|
3779
|
-
if (owner !== userEmail) {
|
|
3780
|
-
return new Response("Forbidden", { status: 403 });
|
|
3781
|
-
}
|
|
3782
|
-
|
|
3783
|
-
// Use the last path segment of the R2 key as a download filename hint, so
|
|
3784
|
-
// <a download> on the client saves with the right extension (mp4/png/etc)
|
|
3785
|
-
// rather than defaulting to .bin or no extension.
|
|
3786
|
-
const filename = key.includes("/") ? key.slice(key.lastIndexOf("/") + 1) : key;
|
|
3787
|
-
|
|
3788
|
-
const headers = new Headers();
|
|
3789
|
-
headers.set("content-type", obj.httpMetadata?.contentType || "application/octet-stream");
|
|
3790
|
-
// Revalidate every fetch instead of blind-caching for an hour: no-cache means
|
|
3791
|
-
// the browser keeps its copy but must check ETag first, so an overwritten
|
|
3792
|
-
// artifact shows fresh while an unchanged one costs only a 304. MP4s (which
|
|
3793
|
-
// never overwrite, since a new render is a new job-id key) just 304 cheaply.
|
|
3794
|
-
headers.set("cache-control", "private, no-cache");
|
|
3795
|
-
if (obj.httpEtag) headers.set("etag", obj.httpEtag);
|
|
3796
|
-
headers.set("content-disposition", `inline; filename="${filename}"`);
|
|
3797
|
-
|
|
3798
|
-
// R2 returns a body-less R2Object when the conditional matched (not modified).
|
|
3799
|
-
if (!("body" in obj) || obj.body === null) {
|
|
3800
|
-
return new Response(null, { status: 304, headers });
|
|
3801
|
-
}
|
|
3802
|
-
return new Response(obj.body, { headers });
|
|
3803
|
-
}
|
|
3804
|
-
|
|
3805
|
-
// ---------- Health checks ----------
|
|
3806
|
-
//
|
|
3807
|
-
// /health is a liveness probe: no binding access, always 200. Use for
|
|
3808
|
-
// frequent (60s) uptime polling.
|
|
3809
|
-
//
|
|
3810
|
-
// /health/deep exercises each external dependency once. Each check is timed
|
|
3811
|
-
// independently; the response body includes per-check ok/latency/error so
|
|
3812
|
-
// a partial outage is visible even though the overall HTTP status is 503.
|
|
3813
|
-
// Use for slower (5min) polling.
|
|
3814
|
-
//
|
|
3815
|
-
// Both endpoints sit behind Cloudflare Access. For Kuma to reach them you
|
|
3816
|
-
// need either an Access service token (recommended) or a bypass policy on
|
|
3817
|
-
// /health* in the Access app config.
|
|
3818
|
-
|
|
3819
|
-
interface HealthCheckResult {
|
|
3820
|
-
ok: boolean;
|
|
3821
|
-
latency_ms: number;
|
|
3822
|
-
error?: string;
|
|
3823
|
-
}
|
|
3824
|
-
|
|
3825
|
-
async function handleHealthDeep(env: Env): Promise<Response> {
|
|
3826
|
-
const checks: Record<string, HealthCheckResult> = {};
|
|
3827
|
-
|
|
3828
|
-
// D1: SELECT 1 round-trip. Verifies the binding works and the database
|
|
3829
|
-
// is reachable. Doesn't touch any user data.
|
|
3830
|
-
{
|
|
3831
|
-
const t0 = Date.now();
|
|
3832
|
-
try {
|
|
3833
|
-
await env.DB.prepare(`SELECT 1 AS ok`).first();
|
|
3834
|
-
checks.d1 = { ok: true, latency_ms: Date.now() - t0 };
|
|
3835
|
-
} catch (err) {
|
|
3836
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
3837
|
-
checks.d1 = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
3838
|
-
}
|
|
3839
|
-
}
|
|
3840
|
-
|
|
3841
|
-
// D1 schema: required tables for the deployed worker (v0.164.3). Catches
|
|
3842
|
-
// schema drift when code ships before a migration runs (e.g. missing user_prefs).
|
|
3843
|
-
{
|
|
3844
|
-
const t0 = Date.now();
|
|
3845
|
-
try {
|
|
3846
|
-
const schema = await probeD1Schema(env.DB);
|
|
3847
|
-
checks.d1_schema = schema.ok
|
|
3848
|
-
? { ok: true, latency_ms: Date.now() - t0 }
|
|
3849
|
-
: { ok: false, latency_ms: Date.now() - t0, error: `missing tables: ${schema.missing.join(", ")}` };
|
|
3850
|
-
} catch (err) {
|
|
3851
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
3852
|
-
checks.d1_schema = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
3853
|
-
}
|
|
3854
|
-
}
|
|
3855
|
-
|
|
3856
|
-
// R2: HEAD on a key that doesn't exist. Returns null on a working binding
|
|
3857
|
-
// (no error). Validates auth and bucket reachability without creating or
|
|
3858
|
-
// reading user data.
|
|
3859
|
-
{
|
|
3860
|
-
const t0 = Date.now();
|
|
3861
|
-
try {
|
|
3862
|
-
await env.R2.head("__healthcheck_nonexistent_key__");
|
|
3863
|
-
checks.r2 = { ok: true, latency_ms: Date.now() - t0 };
|
|
3864
|
-
} catch (err) {
|
|
3865
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
3866
|
-
checks.r2 = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
3867
|
-
}
|
|
3868
|
-
}
|
|
3869
|
-
|
|
3870
|
-
// Vectorize: describe() returns index metadata. Cheap, no vector ops.
|
|
3871
|
-
{
|
|
3872
|
-
const t0 = Date.now();
|
|
3873
|
-
try {
|
|
3874
|
-
await env.VEC.describe();
|
|
3875
|
-
checks.vectorize = { ok: true, latency_ms: Date.now() - t0 };
|
|
3876
|
-
} catch (err) {
|
|
3877
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
3878
|
-
checks.vectorize = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
3879
|
-
}
|
|
3880
|
-
}
|
|
3881
|
-
|
|
3882
|
-
// AI binding: confirm worker-level gateway config, or note per-user mode.
|
|
3883
|
-
// We deliberately do NOT run an actual model here; even the cheapest model
|
|
3884
|
-
// call burns neurons and a per-minute health probe would add up.
|
|
3885
|
-
{
|
|
3886
|
-
const t0 = Date.now();
|
|
3887
|
-
if (env.GATEWAY_ID?.trim()) {
|
|
3888
|
-
checks.ai_config = { ok: true, latency_ms: Date.now() - t0 };
|
|
3889
|
-
} else {
|
|
3890
|
-
// Public demo: users supply gateway slug + token via /api/prefs.
|
|
3891
|
-
checks.ai_config = { ok: true, latency_ms: Date.now() - t0 };
|
|
3892
|
-
}
|
|
3893
|
-
}
|
|
3894
|
-
|
|
3895
|
-
const allOk = Object.values(checks).every((c) => c.ok);
|
|
3896
|
-
return json(
|
|
3897
|
-
{ ok: allOk, ts: Date.now(), checks },
|
|
3898
|
-
{ status: allOk ? 200 : 503 }
|
|
3899
|
-
);
|
|
3900
|
-
}
|
|
3901
|
-
|
|
3902
|
-
// ---------- LongRunWorkflow (v0.12.0) ----------
|
|
3903
|
-
//
|
|
3904
|
-
// Cloudflare Workflow that handles Unified Billing video and music generation.
|
|
3905
|
-
// Both surfaces (runVideo Unified path, runMusic) hand off to this class via
|
|
3906
|
-
// env.LONGRUN.create({ params }). The workflow is responsible for:
|
|
3907
|
-
// 1. Invoking env.AI.run (blocking call, 30s-3min)
|
|
3908
|
-
// 2. Downloading the resulting artifact from CF's catalog R2 bucket
|
|
3909
|
-
// 3. Uploading the bytes to our own R2 bucket
|
|
3910
|
-
// 4. Finalizing the D1 row (status, output_artifact, latency)
|
|
3911
|
-
//
|
|
3912
|
-
// Why Workflows rather than ctx.waitUntil:
|
|
3913
|
-
// - waitUntil has a ~30s budget after the HTTP response is sent. env.AI.run
|
|
3914
|
-
// for Veo/Seedance/Hailuo etc. takes 1-3 minutes, so the task gets
|
|
3915
|
-
// cancelled mid-call. That cancellation was the failure mode in v0.11.x.
|
|
3916
|
-
// - Workflows have unlimited wall-clock time per step (CPU time still
|
|
3917
|
-
// capped, but env.AI.run is I/O-bound).
|
|
3918
|
-
// - Each step retries independently with built-in backoff, so a transient
|
|
3919
|
-
// R2 upload failure doesn't force re-running the (expensive) gen call.
|
|
3920
|
-
//
|
|
3921
|
-
// Step 2 (download + R2 upload) is one combined step because step.do return
|
|
3922
|
-
// values are capped at 1 MiB; video files are 5-15MB, music 3-5MB - we can't
|
|
3923
|
-
// pass bytes between steps. So we fold the download and R2 put into a single
|
|
3924
|
-
// step and return just the small R2 key. The trade-off: if R2 upload fails
|
|
3925
|
-
// after a successful download, the retry re-downloads the same source URL
|
|
3926
|
-
// (CF's catalog R2 - cheap and reliable). Acceptable.
|
|
3927
|
-
//
|
|
3928
|
-
// Response shapes per https://developers.cloudflare.com/ai/models/:
|
|
3929
|
-
// Veo: { state:"Completed", result:{ video:"..." }, gatewayMetadata }
|
|
3930
|
-
// MiniMax: { audio:"..." } (flat) - some normalized providers may wrap in
|
|
3931
|
-
// { state, result:{ audio }, gatewayMetadata } so we accept both.
|
|
3932
|
-
// Other UB video providers (bytedance/runway/alibaba/pixverse/vidu) are
|
|
3933
|
-
// expected to follow the Veo-style wrapper but have NOT been runtime-
|
|
3934
|
-
// verified as of v0.12.0. Per-provider param shapes may also differ from
|
|
3935
|
-
// the Veo baseline (prompt/duration/aspect_ratio/resolution/generate_audio);
|
|
3936
|
-
// errors surface in job_error for iteration.
|
|
3937
|
-
|
|
3938
|
-
type LongRunKind = "video" | "music";
|
|
3939
|
-
|
|
3940
|
-
interface LongRunGenParams extends Record<string, unknown> {
|
|
3941
|
-
rowId: number;
|
|
3942
|
-
userEmail: string;
|
|
3943
|
-
modelId: string;
|
|
3944
|
-
prompt: string;
|
|
3945
|
-
lyrics?: string; // music only
|
|
3946
|
-
imageUrl?: string; // image-to-video: a fetchable URL passed through as-is
|
|
3947
|
-
imageKey?: string; // image-to-video: an R2 key resolved to a data: URI in the workflow (uploads + chaining)
|
|
3948
|
-
kind: LongRunKind;
|
|
3949
|
-
startedAtIso: string;
|
|
3950
|
-
}
|
|
3951
|
-
|
|
3952
|
-
// v0.26.0: durable bulk ZIP import. The uploaded archive is staged to R2
|
|
3953
|
-
// (`zipKey`) so its bytes never ride the workflow event payload; the workflow
|
|
3954
|
-
// unzips it and ingests each inner file in its own step. Putting each file in
|
|
3955
|
-
// a separate step gives each ingest a fresh Worker subrequest budget, which is
|
|
3956
|
-
// what lets a large archive import without hitting the per-invocation limit
|
|
3957
|
-
// that the synchronous v0.25.0 path could approach.
|
|
3958
|
-
interface ZipImportParams extends Record<string, unknown> {
|
|
3959
|
-
kind: "zip_import";
|
|
3960
|
-
userEmail: string;
|
|
3961
|
-
zipKey: string;
|
|
3962
|
-
startedAtIso: string;
|
|
3963
|
-
}
|
|
3964
|
-
|
|
3965
|
-
type LongRunParams =
|
|
3966
|
-
| LongRunGenParams
|
|
3967
|
-
| ZipImportParams;
|
|
3968
|
-
|
|
3969
|
-
// Returned by the zip-import workflow run() and surfaced via the instance's
|
|
3970
|
-
// status().output to the polling client. userEmail is included so the status
|
|
3971
|
-
// endpoint can enforce per-user ownership (a guessed instance id can't read
|
|
3972
|
-
// another user's import result).
|
|
3973
|
-
interface ZipImportSummary {
|
|
3974
|
-
userEmail: string;
|
|
3975
|
-
imported_count: number;
|
|
3976
|
-
total_chunks: number;
|
|
3977
|
-
imported: Array<{ name: string; id: number; chunk_count: number }>;
|
|
3978
|
-
skipped: Array<{ name: string; reason: string }>;
|
|
3979
|
-
}
|
|
3980
|
-
|
|
3981
|
-
// Shape we expect back from env.AI.run for video and music. Both share the
|
|
3982
|
-
// same envelope; only the inner field differs (video vs audio).
|
|
3983
|
-
interface LongRunResult {
|
|
3984
|
-
state?: string;
|
|
3985
|
-
result?: { video?: string; audio?: string };
|
|
3986
|
-
audio?: string; // flat shape for minimax/music-2.6
|
|
3987
|
-
gatewayMetadata?: { keySource?: string };
|
|
3988
|
-
}
|
|
3989
|
-
|
|
3990
|
-
export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
|
|
3991
|
-
async run(event: WorkflowEvent<LongRunParams>, step: WorkflowStep): Promise<unknown> {
|
|
3992
|
-
if (event.payload.kind === "zip_import") {
|
|
3993
|
-
return this.runZipImport(event.payload, step);
|
|
3994
|
-
}
|
|
3995
|
-
return this.runGen(event.payload, step);
|
|
3996
|
-
}
|
|
3997
|
-
|
|
3998
|
-
// v0.26.0: bulk ZIP import. Step 1 unzips the staged archive and stages each
|
|
3999
|
-
// inner file to a temp R2 object (returning only the small name+key list, so
|
|
4000
|
-
// we stay under the 1 MiB step-return cap and never pass bytes between
|
|
4001
|
-
// steps). Each subsequent step ingests one file with a fresh subrequest
|
|
4002
|
-
// budget. A failed ingest becomes a skip, not a workflow failure. A final
|
|
4003
|
-
// step deletes the temp objects and the staged zip.
|
|
4004
|
-
async runZipImport(p: ZipImportParams, step: WorkflowStep): Promise<ZipImportSummary> {
|
|
4005
|
-
const { userEmail, zipKey } = p;
|
|
4006
|
-
|
|
4007
|
-
const { staged, skipped: unzipSkipped } = await step.do(
|
|
4008
|
-
"unzip-and-stage",
|
|
4009
|
-
{ retries: { limit: 2, delay: "5 seconds", backoff: "exponential" } },
|
|
4010
|
-
async (): Promise<{ staged: Array<{ name: string; key: string }>; skipped: Array<{ name: string; reason: string }> }> => {
|
|
4011
|
-
const obj = await this.env.R2.get(zipKey);
|
|
4012
|
-
if (!obj) throw new Error("staged zip not found in R2");
|
|
4013
|
-
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
4014
|
-
const { entries, skipped } = await unzip(bytes, {
|
|
4015
|
-
maxEntries: ZIP_MAX_ENTRIES,
|
|
4016
|
-
maxTotalBytes: ZIP_MAX_TOTAL_UNCOMPRESSED_BYTES,
|
|
4017
|
-
maxFileBytes: ZIP_MAX_FILE_BYTES,
|
|
4018
|
-
});
|
|
4019
|
-
const out: Array<{ name: string; key: string }> = [];
|
|
4020
|
-
for (const e of entries) {
|
|
4021
|
-
const key = `tmp/${crypto.randomUUID()}`;
|
|
4022
|
-
await this.env.R2.put(key, e.bytes, { customMetadata: { user_email: userEmail } });
|
|
4023
|
-
out.push({ name: e.name, key });
|
|
4024
|
-
}
|
|
4025
|
-
return { staged: out, skipped };
|
|
4026
|
-
}
|
|
4027
|
-
);
|
|
4028
|
-
|
|
4029
|
-
const imported: ZipImportSummary["imported"] = [];
|
|
4030
|
-
const skipped: ZipImportSummary["skipped"] = [...unzipSkipped];
|
|
4031
|
-
|
|
4032
|
-
// One step per file: each gets its own subrequest budget. ingestDocument
|
|
4033
|
-
// swallows its own errors into an ok:false result (after rolling back its
|
|
4034
|
-
// partial writes), so an unreadable file does not abort the import.
|
|
4035
|
-
for (let i = 0; i < staged.length; i++) {
|
|
4036
|
-
const item = staged[i];
|
|
4037
|
-
const res = await step.do(
|
|
4038
|
-
`ingest-${i}`,
|
|
4039
|
-
{ retries: { limit: 2, delay: "5 seconds", backoff: "exponential" } },
|
|
4040
|
-
async (): Promise<{ ok: true; name: string; id: number; chunk_count: number } | { ok: false; name: string; reason: string }> => {
|
|
4041
|
-
const obj = await this.env.R2.get(item.key);
|
|
4042
|
-
if (!obj) return { ok: false, name: item.name, reason: "staged file missing" };
|
|
4043
|
-
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
4044
|
-
const r = await ingestDocument(this.env, userEmail, item.name, mimeFromName(item.name), bytes);
|
|
4045
|
-
return r.ok
|
|
4046
|
-
? { ok: true, name: item.name, id: r.id, chunk_count: r.chunk_count }
|
|
4047
|
-
: { ok: false, name: item.name, reason: r.error };
|
|
4048
|
-
}
|
|
4049
|
-
);
|
|
4050
|
-
if (res.ok) imported.push({ name: res.name, id: res.id, chunk_count: res.chunk_count });
|
|
4051
|
-
else skipped.push({ name: res.name, reason: res.reason });
|
|
4052
|
-
}
|
|
4053
|
-
|
|
4054
|
-
// Cleanup: drop the temp staged files and the staged zip. Best-effort; a
|
|
4055
|
-
// leaked temp object under tmp/ is harmless and can be swept by an R2
|
|
4056
|
-
// lifecycle rule. Done after all ingests so a per-file step retry can still
|
|
4057
|
-
// re-read its staged object.
|
|
4058
|
-
await step.do(
|
|
4059
|
-
"cleanup",
|
|
4060
|
-
{ retries: { limit: 1, delay: "5 seconds", backoff: "linear" } },
|
|
4061
|
-
async (): Promise<void> => {
|
|
4062
|
-
for (const item of staged) await r2DeleteSafe(this.env, item.key);
|
|
4063
|
-
await r2DeleteSafe(this.env, zipKey);
|
|
4064
|
-
}
|
|
4065
|
-
);
|
|
4066
|
-
|
|
4067
|
-
return {
|
|
4068
|
-
userEmail,
|
|
4069
|
-
imported_count: imported.length,
|
|
4070
|
-
total_chunks: imported.reduce((s, d) => s + d.chunk_count, 0),
|
|
4071
|
-
imported,
|
|
4072
|
-
skipped,
|
|
4073
|
-
};
|
|
4074
|
-
}
|
|
4075
|
-
|
|
4076
|
-
async runGen(payload: LongRunGenParams, step: WorkflowStep): Promise<void> {
|
|
4077
|
-
const { rowId, userEmail, modelId, prompt, lyrics, imageUrl, imageKey, kind, startedAtIso } = payload;
|
|
4078
|
-
|
|
4079
|
-
// Best-effort row-fail helper. Used in the outer catch to surface
|
|
4080
|
-
// workflow-level failures to the polling client. Failures inside this
|
|
4081
|
-
// helper are intentionally swallowed - if D1 is down, there's nothing
|
|
4082
|
-
// we can do from a background workflow anyway.
|
|
4083
|
-
const failRow = async (msg: string): Promise<void> => {
|
|
4084
|
-
try {
|
|
4085
|
-
await this.env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
|
|
4086
|
-
.bind(msg.slice(0, 1000), rowId)
|
|
4087
|
-
.run();
|
|
4088
|
-
} catch { /* swallow */ }
|
|
4089
|
-
};
|
|
4090
|
-
|
|
4091
|
-
try {
|
|
4092
|
-
// Step 1: invoke the model. Long-running blocking call.
|
|
4093
|
-
//
|
|
4094
|
-
// Retry policy: ONE retry only. Each attempt costs Unified Billing
|
|
4095
|
-
// credits; if it fails twice with a 30s spacing, the third attempt is
|
|
4096
|
-
// unlikely to help and we'd rather surface the error to the user.
|
|
4097
|
-
const artifactUrl = await step.do(
|
|
4098
|
-
"invoke-model",
|
|
4099
|
-
{ retries: { limit: 1, delay: "30 seconds", backoff: "linear" } },
|
|
4100
|
-
async (): Promise<string> => {
|
|
4101
|
-
// Resolve the source image for image-to-video: an R2 key (upload or
|
|
4102
|
-
// chained nano-banana output) becomes a data: URI here, inside the
|
|
4103
|
-
// step, so the big base64 never rides the Workflow event payload.
|
|
4104
|
-
// A plain URL passes straight through. Resolution happens in-step so
|
|
4105
|
-
// a transient R2 read is covered by the step's retry.
|
|
4106
|
-
const resolvedImage = imageKey
|
|
4107
|
-
? await r2KeyToDataUri(this.env, imageKey, userEmail)
|
|
4108
|
-
: imageUrl;
|
|
4109
|
-
const params = buildGenParams(kind, { modelId, prompt, lyrics, imageUrl: resolvedImage });
|
|
4110
|
-
|
|
4111
|
-
const gateway = await loadGatewayCredentials(this.env, userEmail);
|
|
4112
|
-
if (!gateway?.gatewayId) {
|
|
4113
|
-
throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
|
|
4114
|
-
}
|
|
4115
|
-
const aiCtx: AiContext = { env: this.env, gateway };
|
|
4116
|
-
const result = await aiRun(aiCtx, modelId, params) as LongRunResult;
|
|
4117
|
-
|
|
4118
|
-
if (result.state && result.state !== "Completed") {
|
|
4119
|
-
throw new Error(`Unexpected gen state: ${result.state}`);
|
|
4120
|
-
}
|
|
4121
|
-
const url = kind === "video"
|
|
4122
|
-
? result.result?.video
|
|
4123
|
-
: (result.audio ?? result.result?.audio);
|
|
4124
|
-
if (!url) {
|
|
4125
|
-
throw new Error(`Gen completed but no ${kind} URL. Raw: ${JSON.stringify(result).slice(0, 500)}`);
|
|
4126
|
-
}
|
|
4127
|
-
return url;
|
|
4128
|
-
}
|
|
4129
|
-
);
|
|
4130
|
-
|
|
4131
|
-
// Step 2: download artifact and upload to R2 (combined; can't pass
|
|
4132
|
-
// bytes between steps due to the 1 MiB step return cap).
|
|
4133
|
-
const { r2Key, mime } = await step.do(
|
|
4134
|
-
"download-and-store",
|
|
4135
|
-
{ retries: { limit: 3, delay: "5 seconds", backoff: "exponential" } },
|
|
4136
|
-
async (): Promise<{ r2Key: string; mime: string }> => {
|
|
4137
|
-
const aresp = await fetch(artifactUrl);
|
|
4138
|
-
if (!aresp.ok) throw new Error(`Fetch ${aresp.status} from ${artifactUrl.slice(0, 100)}`);
|
|
4139
|
-
// For video, force video/mp4. CF's catalog R2 and many CDNs serve
|
|
4140
|
-
// MP4 as application/octet-stream, which would cause R2 keys to
|
|
4141
|
-
// end in .bin when upstream serves application/octet-stream.
|
|
4142
|
-
const upstreamMime = aresp.headers.get("content-type") || "";
|
|
4143
|
-
const finalMime = kind === "video"
|
|
4144
|
-
? "video/mp4"
|
|
4145
|
-
: (upstreamMime || "audio/mpeg");
|
|
4146
|
-
const bytes = new Uint8Array(await aresp.arrayBuffer());
|
|
4147
|
-
const key = await r2Put(this.env, "out", finalMime, bytes, userEmail);
|
|
4148
|
-
return { r2Key: key, mime: finalMime };
|
|
4149
|
-
}
|
|
4150
|
-
);
|
|
4151
|
-
|
|
4152
|
-
// Step 3: finalize the D1 row.
|
|
4153
|
-
await step.do(
|
|
4154
|
-
"finalize-d1",
|
|
4155
|
-
{ retries: { limit: 3, delay: "5 seconds", backoff: "exponential" } },
|
|
4156
|
-
async (): Promise<void> => {
|
|
4157
|
-
const outputArtifact: OutputArtifact = {
|
|
4158
|
-
key: r2Key,
|
|
4159
|
-
mime,
|
|
4160
|
-
type: kind === "video" ? "video" : "audio",
|
|
4161
|
-
};
|
|
4162
|
-
const latency = Date.now() - Date.parse(startedAtIso);
|
|
4163
|
-
await this.env.DB.prepare(
|
|
4164
|
-
`UPDATE chats SET status = 'done', output_artifact = ?, latency_ms = ? WHERE id = ?`
|
|
4165
|
-
)
|
|
4166
|
-
.bind(JSON.stringify(outputArtifact), latency, rowId)
|
|
4167
|
-
.run();
|
|
4168
|
-
}
|
|
4169
|
-
);
|
|
4170
|
-
} catch (err) {
|
|
4171
|
-
// A step exhausted its retries (or some non-step code threw). Mark the
|
|
4172
|
-
// D1 row failed so the polling client gets a clear error, then re-throw
|
|
4173
|
-
// so the workflow instance itself is reported as errored in the
|
|
4174
|
-
// dashboard (preserves observability).
|
|
4175
|
-
const m = err instanceof Error ? err.message : String(err);
|
|
4176
|
-
await failRow(m);
|
|
4177
|
-
throw err;
|
|
4178
|
-
}
|
|
4179
|
-
}
|
|
4180
|
-
}
|