@skyphusion/create-prism 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +227 -48
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/package.json +6 -6
- package/template/public/app.js +128 -19
- package/template/public/index.html +50 -4
- package/template/public/styles.css +16 -2
- package/template/schema.sql +17 -0
- 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/conversation-context.ts +126 -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 +73 -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 +1682 -0
- package/template/src/routes/conversations.ts +494 -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/stt-session.ts +1 -1
- 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/conversation-compact.test.ts +103 -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
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// RAG document routes: list/get documents, upload (single file or a .zip that
|
|
2
|
+
// fans out to a durable import workflow), poll a zip import, and delete a
|
|
3
|
+
// document (cascading chunks, vectors, project memberships, and R2). The
|
|
4
|
+
// extract/embed/ingest engine lives in ./rag.
|
|
5
|
+
|
|
6
|
+
import type { Env } from "../env";
|
|
7
|
+
import { parseDataUrl, base64ToBytes } from "../utils";
|
|
8
|
+
import { isZip } from "../zip";
|
|
9
|
+
import { json, getUserEmail, r2DeleteSafe } from "./shared";
|
|
10
|
+
import { ingestDocument, DOC_MAX_BYTES } from "./rag";
|
|
11
|
+
import type { LongRunParams, ZipImportSummary } from "./workflow";
|
|
12
|
+
|
|
13
|
+
export async function handleDocumentList(request: Request, env: Env): Promise<Response> {
|
|
14
|
+
const userEmail = await getUserEmail(request, env);
|
|
15
|
+
const url = new URL(request.url);
|
|
16
|
+
const projectIdParam = url.searchParams.get("project_id");
|
|
17
|
+
|
|
18
|
+
// v0.20.0: optional ?project_id=N filter. When set, return only documents
|
|
19
|
+
// attached to that project via project_documents. The project ownership
|
|
20
|
+
// check is done by joining on projects.user_email implicitly via WHERE
|
|
21
|
+
// p.user_email = ?, so attempting to filter by another user's project
|
|
22
|
+
// returns an empty list rather than leaking that the project exists.
|
|
23
|
+
if (projectIdParam !== null) {
|
|
24
|
+
const projectId = Number(projectIdParam);
|
|
25
|
+
if (!Number.isInteger(projectId) || projectId <= 0) {
|
|
26
|
+
return json({ error: "project_id must be a positive integer" }, { status: 400 });
|
|
27
|
+
}
|
|
28
|
+
const rows = await env.DB.prepare(
|
|
29
|
+
`SELECT d.id, d.created_at, d.filename, d.mime, d.size_bytes,
|
|
30
|
+
d.total_chars, d.chunk_count
|
|
31
|
+
FROM documents d
|
|
32
|
+
JOIN project_documents pd ON pd.document_id = d.id
|
|
33
|
+
JOIN projects p ON p.id = pd.project_id
|
|
34
|
+
WHERE d.user_email = ?
|
|
35
|
+
AND p.user_email = ?
|
|
36
|
+
AND pd.project_id = ?
|
|
37
|
+
ORDER BY pd.added_at DESC`
|
|
38
|
+
)
|
|
39
|
+
.bind(userEmail, userEmail, projectId)
|
|
40
|
+
.all<{
|
|
41
|
+
id: number;
|
|
42
|
+
created_at: string;
|
|
43
|
+
filename: string;
|
|
44
|
+
mime: string;
|
|
45
|
+
size_bytes: number;
|
|
46
|
+
total_chars: number;
|
|
47
|
+
chunk_count: number;
|
|
48
|
+
}>();
|
|
49
|
+
return json({
|
|
50
|
+
user: userEmail,
|
|
51
|
+
project_id: projectId,
|
|
52
|
+
documents: rows.results ?? [],
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const rows = await env.DB.prepare(
|
|
57
|
+
`SELECT id, created_at, filename, mime, size_bytes, total_chars, chunk_count
|
|
58
|
+
FROM documents
|
|
59
|
+
WHERE user_email = ?
|
|
60
|
+
ORDER BY created_at DESC`
|
|
61
|
+
)
|
|
62
|
+
.bind(userEmail)
|
|
63
|
+
.all<{
|
|
64
|
+
id: number;
|
|
65
|
+
created_at: string;
|
|
66
|
+
filename: string;
|
|
67
|
+
mime: string;
|
|
68
|
+
size_bytes: number;
|
|
69
|
+
total_chars: number;
|
|
70
|
+
chunk_count: number;
|
|
71
|
+
}>();
|
|
72
|
+
return json({ user: userEmail, documents: rows.results ?? [] });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function handleDocumentGet(request: Request, env: Env, id: number): Promise<Response> {
|
|
76
|
+
const userEmail = await getUserEmail(request, env);
|
|
77
|
+
const doc = await env.DB.prepare(
|
|
78
|
+
`SELECT id, created_at, filename, mime, size_bytes, total_chars, chunk_count
|
|
79
|
+
FROM documents
|
|
80
|
+
WHERE id = ? AND user_email = ?`
|
|
81
|
+
)
|
|
82
|
+
.bind(id, userEmail)
|
|
83
|
+
.first();
|
|
84
|
+
if (!doc) return json({ error: "Not found" }, { status: 404 });
|
|
85
|
+
|
|
86
|
+
// Include first ~10 chunks for inspection without dumping the whole doc.
|
|
87
|
+
const chunks = await env.DB.prepare(
|
|
88
|
+
`SELECT chunk_index, text FROM chunks
|
|
89
|
+
WHERE document_id = ? AND user_email = ?
|
|
90
|
+
ORDER BY chunk_index ASC
|
|
91
|
+
LIMIT 10`
|
|
92
|
+
)
|
|
93
|
+
.bind(id, userEmail)
|
|
94
|
+
.all();
|
|
95
|
+
|
|
96
|
+
return json({ document: doc, chunk_preview: chunks.results ?? [] });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// v0.26.0: a .zip upload is imported durably via the LongRunWorkflow rather
|
|
100
|
+
// than synchronously. We stage the archive to R2 (the workflow reads it from
|
|
101
|
+
// there, since 10MB can't ride the workflow event payload), kick off the
|
|
102
|
+
// workflow, and return its instance id as job_id. The client polls
|
|
103
|
+
// GET /api/import/:id for the result. Expansion + per-file ingest happen in
|
|
104
|
+
// separate workflow steps, each with a fresh subrequest budget, so large
|
|
105
|
+
// archives import without hitting the per-invocation subrequest limit that the
|
|
106
|
+
// old synchronous path (v0.25.0) could approach.
|
|
107
|
+
export async function handleZipImport(env: Env, userEmail: string, zipBytes: Uint8Array): Promise<Response> {
|
|
108
|
+
// Stage the archive so the workflow can read it back. customMetadata.user_email
|
|
109
|
+
// matches the convention used for every other R2 object.
|
|
110
|
+
const zipKey = `tmp/${crypto.randomUUID()}.zip`;
|
|
111
|
+
try {
|
|
112
|
+
await env.R2.put(zipKey, zipBytes, {
|
|
113
|
+
httpMetadata: { contentType: "application/zip" },
|
|
114
|
+
customMetadata: { user_email: userEmail },
|
|
115
|
+
});
|
|
116
|
+
} catch (err) {
|
|
117
|
+
return json({ error: `Failed to stage zip: ${err instanceof Error ? err.message : String(err)}` }, { status: 500 });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const startedAt = new Date().toISOString();
|
|
121
|
+
let instanceId: string;
|
|
122
|
+
try {
|
|
123
|
+
const instance = await env.LONGRUN.create({
|
|
124
|
+
params: { kind: "zip_import", userEmail, zipKey, startedAtIso: startedAt } satisfies LongRunParams,
|
|
125
|
+
});
|
|
126
|
+
instanceId = instance.id;
|
|
127
|
+
} catch (err) {
|
|
128
|
+
await r2DeleteSafe(env, zipKey);
|
|
129
|
+
return json({ error: `Failed to start import: ${err instanceof Error ? err.message : String(err)}` }, { status: 502 });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// async:true tells the client to poll /api/import/:id rather than expecting
|
|
133
|
+
// an inline result.
|
|
134
|
+
return json({ zip: true, async: true, job_id: instanceId });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// v0.26.0: poll a zip-import workflow. Translates the workflow instance status
|
|
138
|
+
// into the same pending/done/failed vocabulary the rest of the UI uses. The
|
|
139
|
+
// import summary is only returned to the user who started it (the workflow
|
|
140
|
+
// records userEmail in its output), so a guessed instance id can't read another
|
|
141
|
+
// user's result.
|
|
142
|
+
export async function handleImportStatus(request: Request, env: Env, id: string): Promise<Response> {
|
|
143
|
+
const userEmail = await getUserEmail(request, env);
|
|
144
|
+
let status: { status: string; output?: unknown; error?: unknown };
|
|
145
|
+
try {
|
|
146
|
+
const instance = await env.LONGRUN.get(id);
|
|
147
|
+
status = await instance.status();
|
|
148
|
+
} catch {
|
|
149
|
+
return json({ error: "Unknown import job" }, { status: 404 });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (status.status === "complete") {
|
|
153
|
+
const summary = (status.output ?? {}) as Partial<ZipImportSummary>;
|
|
154
|
+
if (summary.userEmail !== userEmail) {
|
|
155
|
+
return json({ error: "Unknown import job" }, { status: 404 });
|
|
156
|
+
}
|
|
157
|
+
return json({
|
|
158
|
+
status: "done",
|
|
159
|
+
imported_count: summary.imported_count ?? 0,
|
|
160
|
+
total_chunks: summary.total_chunks ?? 0,
|
|
161
|
+
imported: summary.imported ?? [],
|
|
162
|
+
skipped: summary.skipped ?? [],
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (status.status === "errored" || status.status === "terminated") {
|
|
167
|
+
const msg = typeof status.error === "string" ? status.error : JSON.stringify(status.error ?? "import failed");
|
|
168
|
+
return json({ status: "failed", error: msg });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// queued / running / waiting / paused / unknown -> still in progress.
|
|
172
|
+
return json({ status: "pending" });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export async function handleDocumentUpload(request: Request, env: Env): Promise<Response> {
|
|
176
|
+
const userEmail = await getUserEmail(request, env);
|
|
177
|
+
|
|
178
|
+
// Accept JSON { filename, mime, data: base64 } - matches the existing
|
|
179
|
+
// attachment-upload convention used by the chat path.
|
|
180
|
+
let body: { filename?: string; mime?: string; data?: string };
|
|
181
|
+
try {
|
|
182
|
+
body = await request.json();
|
|
183
|
+
} catch {
|
|
184
|
+
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const filename = body.filename || "untitled.txt";
|
|
188
|
+
const mime = body.mime || "text/plain";
|
|
189
|
+
// No file-type allowlist: any file is accepted. extractChunks routes by
|
|
190
|
+
// format and falls back to UTF-8 text for unknown types, rejecting only
|
|
191
|
+
// bytes that don't decode to usable text. A .zip is expanded (v0.25.0).
|
|
192
|
+
if (!body.data) {
|
|
193
|
+
return json({ error: "Missing file data" }, { status: 400 });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Decode base64 data URL or raw base64.
|
|
197
|
+
let bytes: Uint8Array;
|
|
198
|
+
try {
|
|
199
|
+
const parsed = body.data.startsWith("data:") ? parseDataUrl(body.data) : null;
|
|
200
|
+
bytes = parsed ? base64ToBytes(parsed.base64) : base64ToBytes(body.data);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
return json({ error: `Bad file data: ${err instanceof Error ? err.message : err}` }, { status: 400 });
|
|
203
|
+
}
|
|
204
|
+
if (bytes.length > DOC_MAX_BYTES) {
|
|
205
|
+
return json({ error: `File too large (${bytes.length} bytes, max ${DOC_MAX_BYTES})` }, { status: 413 });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// v0.25.0: a zip is expanded and each inner file ingested separately.
|
|
209
|
+
if (isZip(bytes)) {
|
|
210
|
+
return handleZipImport(env, userEmail, bytes);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const r = await ingestDocument(env, userEmail, filename, mime, bytes);
|
|
214
|
+
if (!r.ok) return json({ error: r.error }, { status: r.status });
|
|
215
|
+
return json({
|
|
216
|
+
id: r.id,
|
|
217
|
+
created_at: r.created_at,
|
|
218
|
+
filename: r.filename,
|
|
219
|
+
mime: r.mime,
|
|
220
|
+
size_bytes: r.size_bytes,
|
|
221
|
+
total_chars: r.total_chars,
|
|
222
|
+
chunk_count: r.chunk_count,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function handleDocumentDelete(request: Request, env: Env, id: number): Promise<Response> {
|
|
227
|
+
const userEmail = await getUserEmail(request, env);
|
|
228
|
+
|
|
229
|
+
const doc = await env.DB.prepare(
|
|
230
|
+
`SELECT r2_key FROM documents WHERE id = ? AND user_email = ?`
|
|
231
|
+
)
|
|
232
|
+
.bind(id, userEmail)
|
|
233
|
+
.first<{ r2_key: string }>();
|
|
234
|
+
if (!doc) return json({ error: "Not found" }, { status: 404 });
|
|
235
|
+
|
|
236
|
+
// Collect vector IDs first so we can clean them out of Vectorize.
|
|
237
|
+
const chunkRows = await env.DB.prepare(
|
|
238
|
+
`SELECT vector_id FROM chunks WHERE document_id = ? AND user_email = ?`
|
|
239
|
+
)
|
|
240
|
+
.bind(id, userEmail)
|
|
241
|
+
.all<{ vector_id: string }>();
|
|
242
|
+
|
|
243
|
+
const vectorIds = (chunkRows.results ?? []).map((r) => r.vector_id);
|
|
244
|
+
if (vectorIds.length) {
|
|
245
|
+
try { await env.VEC.deleteByIds(vectorIds); } catch { /* best effort */ }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Cascade delete in D1 (no real FK enforcement, so explicit) and R2.
|
|
249
|
+
// v0.20.1: also clean up project_documents memberships so deleting a doc
|
|
250
|
+
// that's attached to projects doesn't leave orphan membership rows.
|
|
251
|
+
// v0.20.3: also clean up project_messages (raw Discord rows) for the doc.
|
|
252
|
+
await env.DB.batch([
|
|
253
|
+
env.DB.prepare(`DELETE FROM chunks WHERE document_id = ? AND user_email = ?`).bind(id, userEmail),
|
|
254
|
+
env.DB.prepare(`DELETE FROM project_documents WHERE document_id = ?`).bind(id),
|
|
255
|
+
env.DB.prepare(`DELETE FROM project_messages WHERE document_id = ?`).bind(id),
|
|
256
|
+
env.DB.prepare(`DELETE FROM documents WHERE id = ? AND user_email = ?`).bind(id, userEmail),
|
|
257
|
+
]);
|
|
258
|
+
await r2DeleteSafe(env, doc.r2_key);
|
|
259
|
+
|
|
260
|
+
return json({ deleted: id, vectors_removed: vectorIds.length });
|
|
261
|
+
}
|
|
262
|
+
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Deep health check (/health/deep): exercises D1, the D1 schema, R2, Vectorize,
|
|
2
|
+
// and confirms AI gateway configuration, returning 503 if any check fails. The
|
|
3
|
+
// cheap liveness /health probe stays inline in index.ts.
|
|
4
|
+
|
|
5
|
+
import type { Env } from "../env";
|
|
6
|
+
import { probeD1Schema } from "../health-schema";
|
|
7
|
+
import { json } from "./shared";
|
|
8
|
+
|
|
9
|
+
// ---------- Health checks ----------
|
|
10
|
+
//
|
|
11
|
+
// /health is a liveness probe: no binding access, always 200. Use for
|
|
12
|
+
// frequent (60s) uptime polling.
|
|
13
|
+
//
|
|
14
|
+
// /health/deep exercises each external dependency once. Each check is timed
|
|
15
|
+
// independently; the response body includes per-check ok/latency/error so
|
|
16
|
+
// a partial outage is visible even though the overall HTTP status is 503.
|
|
17
|
+
// Use for slower (5min) polling.
|
|
18
|
+
//
|
|
19
|
+
// Both endpoints sit behind Cloudflare Access. For Kuma to reach them you
|
|
20
|
+
// need either an Access service token (recommended) or a bypass policy on
|
|
21
|
+
// /health* in the Access app config.
|
|
22
|
+
|
|
23
|
+
export interface HealthCheckResult {
|
|
24
|
+
ok: boolean;
|
|
25
|
+
latency_ms: number;
|
|
26
|
+
error?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function handleHealthDeep(env: Env): Promise<Response> {
|
|
30
|
+
const checks: Record<string, HealthCheckResult> = {};
|
|
31
|
+
|
|
32
|
+
// D1: SELECT 1 round-trip. Verifies the binding works and the database
|
|
33
|
+
// is reachable. Doesn't touch any user data.
|
|
34
|
+
{
|
|
35
|
+
const t0 = Date.now();
|
|
36
|
+
try {
|
|
37
|
+
await env.DB.prepare(`SELECT 1 AS ok`).first();
|
|
38
|
+
checks.d1 = { ok: true, latency_ms: Date.now() - t0 };
|
|
39
|
+
} catch (err) {
|
|
40
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
41
|
+
checks.d1 = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// D1 schema: required tables for the deployed worker (v0.164.3). Catches
|
|
46
|
+
// schema drift when code ships before a migration runs (e.g. missing user_prefs).
|
|
47
|
+
{
|
|
48
|
+
const t0 = Date.now();
|
|
49
|
+
try {
|
|
50
|
+
const schema = await probeD1Schema(env.DB);
|
|
51
|
+
checks.d1_schema = schema.ok
|
|
52
|
+
? { ok: true, latency_ms: Date.now() - t0 }
|
|
53
|
+
: { ok: false, latency_ms: Date.now() - t0, error: `missing tables: ${schema.missing.join(", ")}` };
|
|
54
|
+
} catch (err) {
|
|
55
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
56
|
+
checks.d1_schema = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// R2: HEAD on a key that doesn't exist. Returns null on a working binding
|
|
61
|
+
// (no error). Validates auth and bucket reachability without creating or
|
|
62
|
+
// reading user data.
|
|
63
|
+
{
|
|
64
|
+
const t0 = Date.now();
|
|
65
|
+
try {
|
|
66
|
+
await env.R2.head("__healthcheck_nonexistent_key__");
|
|
67
|
+
checks.r2 = { ok: true, latency_ms: Date.now() - t0 };
|
|
68
|
+
} catch (err) {
|
|
69
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
70
|
+
checks.r2 = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Vectorize: describe() returns index metadata. Cheap, no vector ops.
|
|
75
|
+
{
|
|
76
|
+
const t0 = Date.now();
|
|
77
|
+
try {
|
|
78
|
+
await env.VEC.describe();
|
|
79
|
+
checks.vectorize = { ok: true, latency_ms: Date.now() - t0 };
|
|
80
|
+
} catch (err) {
|
|
81
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
82
|
+
checks.vectorize = { ok: false, latency_ms: Date.now() - t0, error: m };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// AI binding: confirm worker-level gateway config, or note per-user mode.
|
|
87
|
+
// We deliberately do NOT run an actual model here; even the cheapest model
|
|
88
|
+
// call burns neurons and a per-minute health probe would add up.
|
|
89
|
+
{
|
|
90
|
+
const t0 = Date.now();
|
|
91
|
+
if (env.GATEWAY_ID?.trim()) {
|
|
92
|
+
checks.ai_config = { ok: true, latency_ms: Date.now() - t0 };
|
|
93
|
+
} else {
|
|
94
|
+
// Public demo: users supply gateway slug + token via /api/prefs.
|
|
95
|
+
checks.ai_config = { ok: true, latency_ms: Date.now() - t0 };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const allOk = Object.values(checks).every((c) => c.ok);
|
|
100
|
+
return json(
|
|
101
|
+
{ ok: allOk, ts: Date.now(), checks },
|
|
102
|
+
{ status: allOk ? 200 : 503 }
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// History routes: list the caller chat rows, fetch one, delete one (cascading
|
|
2
|
+
// its R2 artifacts). Rows are scoped to the caller user_email.
|
|
3
|
+
|
|
4
|
+
import type { Env } from "../env";
|
|
5
|
+
import { json, getUserEmail, r2DeleteSafe, safeParseJson } from "./shared";
|
|
6
|
+
import type { PersistedAttachment, OutputArtifact, RetrievedItem } from "./shared";
|
|
7
|
+
|
|
8
|
+
// ---------- History ----------
|
|
9
|
+
|
|
10
|
+
export async function handleHistoryList(request: Request, env: Env): Promise<Response> {
|
|
11
|
+
const userEmail = await getUserEmail(request, env);
|
|
12
|
+
const url = new URL(request.url);
|
|
13
|
+
const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 200);
|
|
14
|
+
|
|
15
|
+
const rows = await env.DB.prepare(
|
|
16
|
+
`SELECT id, created_at, model, model_type, system_prompt, user_input, output,
|
|
17
|
+
tokens_in, tokens_out, latency_ms, status,
|
|
18
|
+
CASE WHEN attachments IS NOT NULL THEN 1 ELSE 0 END AS has_attachments,
|
|
19
|
+
CASE WHEN output_artifact IS NOT NULL THEN 1 ELSE 0 END AS has_output_artifact
|
|
20
|
+
FROM chats
|
|
21
|
+
WHERE user_email = ?
|
|
22
|
+
ORDER BY created_at DESC
|
|
23
|
+
LIMIT ?`
|
|
24
|
+
)
|
|
25
|
+
.bind(userEmail, limit)
|
|
26
|
+
.all();
|
|
27
|
+
|
|
28
|
+
return json({ user: userEmail, chats: rows.results ?? [] });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function handleHistoryGet(request: Request, env: Env, id: number): Promise<Response> {
|
|
32
|
+
const userEmail = await getUserEmail(request, env);
|
|
33
|
+
const row = await env.DB.prepare(
|
|
34
|
+
`SELECT * FROM chats WHERE id = ? AND user_email = ?`
|
|
35
|
+
)
|
|
36
|
+
.bind(id, userEmail)
|
|
37
|
+
.first<{ attachments: string | null; output_artifact: string | null; retrieved_context: string | null }>();
|
|
38
|
+
|
|
39
|
+
if (!row) return json({ error: "Not found" }, { status: 404 });
|
|
40
|
+
|
|
41
|
+
return json({
|
|
42
|
+
...row,
|
|
43
|
+
attachments: row.attachments ? safeParseJson<PersistedAttachment[]>(row.attachments) : null,
|
|
44
|
+
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
45
|
+
retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function handleHistoryDelete(request: Request, env: Env, id: number): Promise<Response> {
|
|
50
|
+
const userEmail = await getUserEmail(request, env);
|
|
51
|
+
|
|
52
|
+
// Pull keys first so we can clean up R2.
|
|
53
|
+
const row = await env.DB.prepare(
|
|
54
|
+
`SELECT attachments, output_artifact FROM chats WHERE id = ? AND user_email = ?`
|
|
55
|
+
)
|
|
56
|
+
.bind(id, userEmail)
|
|
57
|
+
.first<{ attachments: string | null; output_artifact: string | null }>();
|
|
58
|
+
|
|
59
|
+
if (!row) return json({ error: "Not found" }, { status: 404 });
|
|
60
|
+
|
|
61
|
+
const keysToDelete: string[] = [];
|
|
62
|
+
if (row.attachments) {
|
|
63
|
+
const atts = safeParseJson<PersistedAttachment[]>(row.attachments) ?? [];
|
|
64
|
+
for (const a of atts) {
|
|
65
|
+
if (a.type === "image") keysToDelete.push(a.key);
|
|
66
|
+
else if (a.type === "video_frames") keysToDelete.push(...(a.keys ?? []));
|
|
67
|
+
else if (a.type === "video_full") keysToDelete.push(a.key);
|
|
68
|
+
// audio has no R2 reference
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (row.output_artifact) {
|
|
72
|
+
const oa = safeParseJson<OutputArtifact>(row.output_artifact);
|
|
73
|
+
if (oa?.key) keysToDelete.push(oa.key);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Delete from D1 first; if it succeeds, clean R2. (If R2 cleanup fails the
|
|
77
|
+
// row is already gone, so worst case we have orphaned objects, which is
|
|
78
|
+
// fine for occasional manual cleanup.)
|
|
79
|
+
const result = await env.DB.prepare(
|
|
80
|
+
`DELETE FROM chats WHERE id = ? AND user_email = ?`
|
|
81
|
+
)
|
|
82
|
+
.bind(id, userEmail)
|
|
83
|
+
.run();
|
|
84
|
+
if (!result.success || (result.meta?.changes ?? 0) === 0) {
|
|
85
|
+
return json({ error: "Not found" }, { status: 404 });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (const k of keysToDelete) await r2DeleteSafe(env, k);
|
|
89
|
+
|
|
90
|
+
return json({ deleted: id, r2_keys_deleted: keysToDelete.length });
|
|
91
|
+
}
|
|
92
|
+
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Per-user AI Gateway preference routes (GET/PATCH /api/prefs). Stores the
|
|
2
|
+
// user gateway slug + Unified Billing token in D1 user_prefs; the token is
|
|
3
|
+
// never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
|
|
4
|
+
// metered chat via allowlisted play-proxy (URL is never user-set).
|
|
5
|
+
|
|
6
|
+
import type { Env } from "../env";
|
|
7
|
+
import { loadUserPrefs, saveUserPrefs, type UserPrefsJson } from "../user-prefs";
|
|
8
|
+
import { loadGatewayStatus, maskSecret } from "../gateway-credentials";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_CONTROL_PLANE_URL,
|
|
11
|
+
looksLikeClientKey,
|
|
12
|
+
resolveControlPlane,
|
|
13
|
+
} from "../control-plane";
|
|
14
|
+
import { json, getUserEmail } from "./shared";
|
|
15
|
+
|
|
16
|
+
function controlPlaneStatus(prefs: UserPrefsJson | null, env: Env) {
|
|
17
|
+
const cp = resolveControlPlane(prefs, env);
|
|
18
|
+
return {
|
|
19
|
+
control_plane_configured: !!cp,
|
|
20
|
+
// Display-only origin (from worker config / default); not editable by the user.
|
|
21
|
+
control_plane_url: cp?.baseUrl ?? DEFAULT_CONTROL_PLANE_URL,
|
|
22
|
+
control_plane_key_set: !!prefs?.control_plane_key?.trim(),
|
|
23
|
+
control_plane_key_preview: maskSecret(prefs?.control_plane_key),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function handlePrefsGet(request: Request, env: Env): Promise<Response> {
|
|
28
|
+
const userEmail = await getUserEmail(request, env);
|
|
29
|
+
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
30
|
+
const status = await loadGatewayStatus(env, userEmail);
|
|
31
|
+
return json({
|
|
32
|
+
gateway_id: status.gateway_id,
|
|
33
|
+
cf_aig_token_set: status.cf_aig_token_set,
|
|
34
|
+
cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
|
|
35
|
+
configured: status.configured || !!resolveControlPlane(prefs, env),
|
|
36
|
+
source: status.source,
|
|
37
|
+
...controlPlaneStatus(prefs, env),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
|
|
42
|
+
const userEmail = await getUserEmail(request, env);
|
|
43
|
+
let body: {
|
|
44
|
+
gateway_id?: string;
|
|
45
|
+
cf_aig_token?: string;
|
|
46
|
+
clear_cf_aig_token?: boolean;
|
|
47
|
+
control_plane_key?: string;
|
|
48
|
+
clear_control_plane_key?: boolean;
|
|
49
|
+
};
|
|
50
|
+
try {
|
|
51
|
+
body = await request.json();
|
|
52
|
+
} catch {
|
|
53
|
+
return json({ error: "Invalid JSON" }, { status: 400 });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const patch: UserPrefsJson = {};
|
|
57
|
+
if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
|
|
58
|
+
if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
|
|
59
|
+
if (body.clear_cf_aig_token) patch.cf_aig_token = "";
|
|
60
|
+
if (body.control_plane_key !== undefined) {
|
|
61
|
+
const k = body.control_plane_key.trim();
|
|
62
|
+
if (k && !looksLikeClientKey(k)) {
|
|
63
|
+
return json(
|
|
64
|
+
{
|
|
65
|
+
error:
|
|
66
|
+
"control_plane_key must be a prism-control-plane client key (pcp_<16 hex>_<43 base64url>).",
|
|
67
|
+
code: "invalid_control_plane_key",
|
|
68
|
+
},
|
|
69
|
+
{ status: 400 },
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
patch.control_plane_key = k;
|
|
73
|
+
}
|
|
74
|
+
if (body.clear_control_plane_key) patch.control_plane_key = "";
|
|
75
|
+
|
|
76
|
+
if (Object.keys(patch).length === 0) {
|
|
77
|
+
return json(
|
|
78
|
+
{
|
|
79
|
+
error: "Provide gateway_id, cf_aig_token, and/or control_plane_key to update",
|
|
80
|
+
},
|
|
81
|
+
{ status: 400 },
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const merged = await saveUserPrefs(env.DB, userEmail, patch);
|
|
86
|
+
const status = await loadGatewayStatus(env, userEmail);
|
|
87
|
+
return json({
|
|
88
|
+
gateway_id: status.gateway_id,
|
|
89
|
+
cf_aig_token_set: status.cf_aig_token_set,
|
|
90
|
+
cf_aig_token_preview: maskSecret(merged.cf_aig_token),
|
|
91
|
+
configured: status.configured || !!resolveControlPlane(merged, env),
|
|
92
|
+
source: status.source,
|
|
93
|
+
...controlPlaneStatus(merged, env),
|
|
94
|
+
});
|
|
95
|
+
}
|