@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
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Conversation routes: list conversations (grouped by conversation_id), fetch a
|
|
2
|
+
// full transcript, delete a conversation (cascading R2 artifacts across all its
|
|
3
|
+
// turns), and move a conversation to/from a project. Scoped to the caller.
|
|
4
|
+
|
|
5
|
+
import type { Env } from "../env";
|
|
6
|
+
import { json, getUserEmail, r2DeleteSafe, safeParseJson } from "./shared";
|
|
7
|
+
import type { PersistedAttachment, OutputArtifact, RetrievedItem } from "./shared";
|
|
8
|
+
|
|
9
|
+
// ---------- Multi-turn conversations ----------
|
|
10
|
+
//
|
|
11
|
+
// A conversation is a set of chat rows sharing the same conversation_id,
|
|
12
|
+
// ordered by turn_index. Old single-turn chats with NULL conversation_id
|
|
13
|
+
// were backfilled in the migration to 'legacy-<id>' so they still appear
|
|
14
|
+
// in the list. Non-chat rows (image/tts/etc) get 'single-<id>' assigned
|
|
15
|
+
// at persistChat time and show as single-turn entries.
|
|
16
|
+
//
|
|
17
|
+
// handleConversationList returns one row per distinct conversation_id with
|
|
18
|
+
// a summary: turn count, first prompt, latest model, last activity. Used
|
|
19
|
+
// by the sidebar as the replacement for the per-row history list.
|
|
20
|
+
//
|
|
21
|
+
// handleConversationGet returns all rows of a conversation in turn order.
|
|
22
|
+
// Used when the user clicks a conversation to view the full transcript.
|
|
23
|
+
|
|
24
|
+
export async function handleConversationList(request: Request, env: Env): Promise<Response> {
|
|
25
|
+
const userEmail = await getUserEmail(request, env);
|
|
26
|
+
|
|
27
|
+
// Group by conversation_id. For each, give:
|
|
28
|
+
// - turn_count, first/last timestamps
|
|
29
|
+
// - the first user_input as a preview
|
|
30
|
+
// - the model used in the latest turn
|
|
31
|
+
// - whether any turn has a non-null output_artifact (for the icon)
|
|
32
|
+
// - the model_type of the first turn (chat/image/tts/video/music/stt)
|
|
33
|
+
// - v0.20.2: project_id from the conversation's first turn (the sidebar
|
|
34
|
+
// shows a project chip when this is set). project_id is a per-row
|
|
35
|
+
// column but conversations are expected to have a uniform value
|
|
36
|
+
// across turns (handleConversationMoveToProject updates all turns
|
|
37
|
+
// atomically). Subqueries match the existing pattern for first_input.
|
|
38
|
+
const rows = await env.DB.prepare(
|
|
39
|
+
`SELECT
|
|
40
|
+
c.conversation_id,
|
|
41
|
+
COUNT(*) AS turn_count,
|
|
42
|
+
MIN(c.created_at) AS first_created_at,
|
|
43
|
+
MAX(c.created_at) AS last_created_at,
|
|
44
|
+
(SELECT user_input FROM chats c2
|
|
45
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
46
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS first_input,
|
|
47
|
+
(SELECT model FROM chats c2
|
|
48
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
49
|
+
ORDER BY c2.turn_index DESC LIMIT 1) AS latest_model,
|
|
50
|
+
(SELECT model_type FROM chats c2
|
|
51
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
52
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS first_model_type,
|
|
53
|
+
(SELECT project_id FROM chats c2
|
|
54
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
55
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS project_id,
|
|
56
|
+
SUM(CASE WHEN output_artifact IS NOT NULL THEN 1 ELSE 0 END) AS artifact_count
|
|
57
|
+
FROM chats c
|
|
58
|
+
WHERE c.user_email = ?
|
|
59
|
+
GROUP BY c.conversation_id
|
|
60
|
+
ORDER BY last_created_at DESC
|
|
61
|
+
LIMIT 200`
|
|
62
|
+
)
|
|
63
|
+
.bind(userEmail)
|
|
64
|
+
.all<{
|
|
65
|
+
conversation_id: string;
|
|
66
|
+
turn_count: number;
|
|
67
|
+
first_created_at: string;
|
|
68
|
+
last_created_at: string;
|
|
69
|
+
first_input: string;
|
|
70
|
+
latest_model: string;
|
|
71
|
+
first_model_type: string;
|
|
72
|
+
project_id: number | null;
|
|
73
|
+
artifact_count: number;
|
|
74
|
+
}>();
|
|
75
|
+
return json({ user: userEmail, conversations: rows.results ?? [] });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function handleConversationGet(request: Request, env: Env, id: string): Promise<Response> {
|
|
79
|
+
const userEmail = await getUserEmail(request, env);
|
|
80
|
+
const rows = await env.DB.prepare(
|
|
81
|
+
`SELECT * FROM chats
|
|
82
|
+
WHERE conversation_id = ? AND user_email = ?
|
|
83
|
+
ORDER BY turn_index ASC, created_at ASC`
|
|
84
|
+
)
|
|
85
|
+
.bind(id, userEmail)
|
|
86
|
+
.all<{
|
|
87
|
+
attachments: string | null;
|
|
88
|
+
output_artifact: string | null;
|
|
89
|
+
retrieved_context: string | null;
|
|
90
|
+
}>();
|
|
91
|
+
|
|
92
|
+
if ((rows.results ?? []).length === 0) {
|
|
93
|
+
return json({ error: "Not found" }, { status: 404 });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Parse the JSON columns on each turn so the frontend doesn't have to.
|
|
97
|
+
const turns = (rows.results ?? []).map((row) => ({
|
|
98
|
+
...row,
|
|
99
|
+
attachments: row.attachments ? safeParseJson<PersistedAttachment[]>(row.attachments) : null,
|
|
100
|
+
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
101
|
+
retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
|
|
102
|
+
}));
|
|
103
|
+
|
|
104
|
+
return json({ conversation_id: id, turns });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function handleConversationDelete(request: Request, env: Env, id: string): Promise<Response> {
|
|
108
|
+
const userEmail = await getUserEmail(request, env);
|
|
109
|
+
|
|
110
|
+
// Pull all R2 keys across all turns before deleting D1 rows.
|
|
111
|
+
const rows = await env.DB.prepare(
|
|
112
|
+
`SELECT attachments, output_artifact FROM chats
|
|
113
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
114
|
+
)
|
|
115
|
+
.bind(id, userEmail)
|
|
116
|
+
.all<{ attachments: string | null; output_artifact: string | null }>();
|
|
117
|
+
|
|
118
|
+
const results = rows.results ?? [];
|
|
119
|
+
if (results.length === 0) {
|
|
120
|
+
return json({ error: "Not found" }, { status: 404 });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const keysToDelete: string[] = [];
|
|
124
|
+
for (const row of results) {
|
|
125
|
+
if (row.attachments) {
|
|
126
|
+
const atts = safeParseJson<PersistedAttachment[]>(row.attachments) ?? [];
|
|
127
|
+
for (const a of atts) {
|
|
128
|
+
if (a.type === "image") keysToDelete.push(a.key);
|
|
129
|
+
else if (a.type === "video_frames") keysToDelete.push(...(a.keys ?? []));
|
|
130
|
+
else if (a.type === "video_full") keysToDelete.push(a.key);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (row.output_artifact) {
|
|
134
|
+
const oa = safeParseJson<OutputArtifact>(row.output_artifact);
|
|
135
|
+
if (oa?.key) keysToDelete.push(oa.key);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
await env.DB.prepare(
|
|
140
|
+
`DELETE FROM chats WHERE conversation_id = ? AND user_email = ?`
|
|
141
|
+
)
|
|
142
|
+
.bind(id, userEmail)
|
|
143
|
+
.run();
|
|
144
|
+
|
|
145
|
+
for (const k of keysToDelete) {
|
|
146
|
+
await r2DeleteSafe(env, k);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return json({ deleted: id, turns_removed: results.length, artifacts_removed: keysToDelete.length });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// v0.20.2: move a conversation to a project (or clear its project assignment).
|
|
153
|
+
// Body: { project_id: number | null }. When project_id is a number, the
|
|
154
|
+
// project must exist and belong to the same user. When null, the assignment
|
|
155
|
+
// is cleared on all turns.
|
|
156
|
+
//
|
|
157
|
+
// All turns in the conversation are updated atomically. The conversation_id
|
|
158
|
+
// is the existing key for ownership (chats.user_email + conversation_id).
|
|
159
|
+
export async function handleConversationMoveToProject(
|
|
160
|
+
request: Request,
|
|
161
|
+
env: Env,
|
|
162
|
+
conversationId: string,
|
|
163
|
+
): Promise<Response> {
|
|
164
|
+
const userEmail = await getUserEmail(request, env);
|
|
165
|
+
|
|
166
|
+
let body: { project_id?: number | null };
|
|
167
|
+
try {
|
|
168
|
+
body = await request.json();
|
|
169
|
+
} catch {
|
|
170
|
+
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const newProjectId = body.project_id ?? null;
|
|
174
|
+
if (newProjectId !== null) {
|
|
175
|
+
if (!Number.isInteger(newProjectId) || newProjectId <= 0) {
|
|
176
|
+
return json({ error: "project_id must be a positive integer or null" }, { status: 400 });
|
|
177
|
+
}
|
|
178
|
+
// Confirm the target project exists and belongs to this user.
|
|
179
|
+
const proj = await env.DB.prepare(
|
|
180
|
+
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
181
|
+
)
|
|
182
|
+
.bind(newProjectId, userEmail)
|
|
183
|
+
.first();
|
|
184
|
+
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Confirm the conversation exists and belongs to this user before
|
|
188
|
+
// updating, otherwise we silently no-op on stale ids.
|
|
189
|
+
const existing = await env.DB.prepare(
|
|
190
|
+
`SELECT COUNT(*) AS n FROM chats
|
|
191
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
192
|
+
)
|
|
193
|
+
.bind(conversationId, userEmail)
|
|
194
|
+
.first<{ n: number }>();
|
|
195
|
+
if (!existing || existing.n === 0) {
|
|
196
|
+
return json({ error: "Conversation not found" }, { status: 404 });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const result = await env.DB.prepare(
|
|
200
|
+
`UPDATE chats SET project_id = ?
|
|
201
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
202
|
+
)
|
|
203
|
+
.bind(newProjectId, conversationId, userEmail)
|
|
204
|
+
.run();
|
|
205
|
+
|
|
206
|
+
return json({
|
|
207
|
+
conversation_id: conversationId,
|
|
208
|
+
project_id: newProjectId,
|
|
209
|
+
rows_updated: result.meta?.changes ?? 0,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
@@ -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
|
+
|