@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,494 @@
|
|
|
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), move a conversation to/from a project, and compact (summarize older
|
|
4
|
+
// turns for model context). Scoped to the caller.
|
|
5
|
+
|
|
6
|
+
import type { Env } from "../env";
|
|
7
|
+
import { MODELS } from "../models";
|
|
8
|
+
import type { ModelEntry } from "../models";
|
|
9
|
+
import { aiRun, aiLogId, type AiContext } from "../ai-binding";
|
|
10
|
+
import { extractOutput, detectProviderFailure } from "../output-extract";
|
|
11
|
+
import { callAnthropic } from "../providers/anthropic";
|
|
12
|
+
import { callXai } from "../providers/xai";
|
|
13
|
+
import { callGemini } from "../providers/google";
|
|
14
|
+
import { callOpenAI } from "../providers/openai";
|
|
15
|
+
import {
|
|
16
|
+
json,
|
|
17
|
+
getUserEmail,
|
|
18
|
+
r2DeleteSafe,
|
|
19
|
+
safeParseJson,
|
|
20
|
+
requireInferenceBackend,
|
|
21
|
+
modelNeedsCfAigToken,
|
|
22
|
+
} from "./shared";
|
|
23
|
+
import type { PersistedAttachment, OutputArtifact, RetrievedItem } from "./shared";
|
|
24
|
+
import { controlPlaneChat } from "../control-plane";
|
|
25
|
+
import {
|
|
26
|
+
DEFAULT_KEEP_RECENT,
|
|
27
|
+
COMPACT_SYSTEM_PROMPT,
|
|
28
|
+
type ChatTurnRow,
|
|
29
|
+
type ConversationCompactState,
|
|
30
|
+
splitTurnsForCompact,
|
|
31
|
+
formatTurnsForSummary,
|
|
32
|
+
normalizeSummary,
|
|
33
|
+
} from "../conversation-context";
|
|
34
|
+
|
|
35
|
+
/** Default cheap Workers AI chat model for compact when the client omits model. */
|
|
36
|
+
export const DEFAULT_COMPACT_MODEL = "@cf/meta/llama-3.2-3b-instruct";
|
|
37
|
+
|
|
38
|
+
export async function loadCompactState(
|
|
39
|
+
env: Env,
|
|
40
|
+
conversationId: string,
|
|
41
|
+
userEmail: string,
|
|
42
|
+
): Promise<ConversationCompactState | null> {
|
|
43
|
+
const row = await env.DB.prepare(
|
|
44
|
+
`SELECT summary, through_turn_index, keep_recent, model, updated_at
|
|
45
|
+
FROM conversation_compact
|
|
46
|
+
WHERE conversation_id = ? AND user_email = ?`,
|
|
47
|
+
)
|
|
48
|
+
.bind(conversationId, userEmail)
|
|
49
|
+
.first<{
|
|
50
|
+
summary: string;
|
|
51
|
+
through_turn_index: number;
|
|
52
|
+
keep_recent: number;
|
|
53
|
+
model: string;
|
|
54
|
+
updated_at: string;
|
|
55
|
+
}>();
|
|
56
|
+
if (!row?.summary) return null;
|
|
57
|
+
return {
|
|
58
|
+
summary: row.summary,
|
|
59
|
+
through_turn_index: row.through_turn_index,
|
|
60
|
+
keep_recent: row.keep_recent,
|
|
61
|
+
model: row.model,
|
|
62
|
+
updated_at: row.updated_at,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function loadChatTurns(
|
|
67
|
+
env: Env,
|
|
68
|
+
conversationId: string,
|
|
69
|
+
userEmail: string,
|
|
70
|
+
): Promise<ChatTurnRow[]> {
|
|
71
|
+
const r = await env.DB.prepare(
|
|
72
|
+
`SELECT user_input, output, turn_index
|
|
73
|
+
FROM chats
|
|
74
|
+
WHERE conversation_id = ?
|
|
75
|
+
AND user_email = ?
|
|
76
|
+
AND status = 'done'
|
|
77
|
+
AND model_type = 'chat'
|
|
78
|
+
ORDER BY turn_index ASC`,
|
|
79
|
+
)
|
|
80
|
+
.bind(conversationId, userEmail)
|
|
81
|
+
.all<ChatTurnRow>();
|
|
82
|
+
return r.results ?? [];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------- Multi-turn conversations ----------
|
|
86
|
+
//
|
|
87
|
+
// A conversation is a set of chat rows sharing the same conversation_id,
|
|
88
|
+
// ordered by turn_index. Old single-turn chats with NULL conversation_id
|
|
89
|
+
// were backfilled in the migration to 'legacy-<id>' so they still appear
|
|
90
|
+
// in the list. Non-chat rows (image/tts/etc) get 'single-<id>' assigned
|
|
91
|
+
// at persistChat time and show as single-turn entries.
|
|
92
|
+
//
|
|
93
|
+
// handleConversationList returns one row per distinct conversation_id with
|
|
94
|
+
// a summary: turn count, first prompt, latest model, last activity. Used
|
|
95
|
+
// by the sidebar as the replacement for the per-row history list.
|
|
96
|
+
//
|
|
97
|
+
// handleConversationGet returns all rows of a conversation in turn order.
|
|
98
|
+
// Used when the user clicks a conversation to view the full transcript.
|
|
99
|
+
|
|
100
|
+
export async function handleConversationList(request: Request, env: Env): Promise<Response> {
|
|
101
|
+
const userEmail = await getUserEmail(request, env);
|
|
102
|
+
|
|
103
|
+
// Group by conversation_id. For each, give:
|
|
104
|
+
// - turn_count, first/last timestamps
|
|
105
|
+
// - the first user_input as a preview
|
|
106
|
+
// - the model used in the latest turn
|
|
107
|
+
// - whether any turn has a non-null output_artifact (for the icon)
|
|
108
|
+
// - the model_type of the first turn (chat/image/tts/video/music/stt)
|
|
109
|
+
// - v0.20.2: project_id from the conversation's first turn (the sidebar
|
|
110
|
+
// shows a project chip when this is set). project_id is a per-row
|
|
111
|
+
// column but conversations are expected to have a uniform value
|
|
112
|
+
// across turns (handleConversationMoveToProject updates all turns
|
|
113
|
+
// atomically). Subqueries match the existing pattern for first_input.
|
|
114
|
+
const rows = await env.DB.prepare(
|
|
115
|
+
`SELECT
|
|
116
|
+
c.conversation_id,
|
|
117
|
+
COUNT(*) AS turn_count,
|
|
118
|
+
MIN(c.created_at) AS first_created_at,
|
|
119
|
+
MAX(c.created_at) AS last_created_at,
|
|
120
|
+
(SELECT user_input FROM chats c2
|
|
121
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
122
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS first_input,
|
|
123
|
+
(SELECT model FROM chats c2
|
|
124
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
125
|
+
ORDER BY c2.turn_index DESC LIMIT 1) AS latest_model,
|
|
126
|
+
(SELECT model_type FROM chats c2
|
|
127
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
128
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS first_model_type,
|
|
129
|
+
(SELECT project_id FROM chats c2
|
|
130
|
+
WHERE c2.conversation_id = c.conversation_id AND c2.user_email = c.user_email
|
|
131
|
+
ORDER BY c2.turn_index ASC LIMIT 1) AS project_id,
|
|
132
|
+
SUM(CASE WHEN output_artifact IS NOT NULL THEN 1 ELSE 0 END) AS artifact_count
|
|
133
|
+
FROM chats c
|
|
134
|
+
WHERE c.user_email = ?
|
|
135
|
+
GROUP BY c.conversation_id
|
|
136
|
+
ORDER BY last_created_at DESC
|
|
137
|
+
LIMIT 200`
|
|
138
|
+
)
|
|
139
|
+
.bind(userEmail)
|
|
140
|
+
.all<{
|
|
141
|
+
conversation_id: string;
|
|
142
|
+
turn_count: number;
|
|
143
|
+
first_created_at: string;
|
|
144
|
+
last_created_at: string;
|
|
145
|
+
first_input: string;
|
|
146
|
+
latest_model: string;
|
|
147
|
+
first_model_type: string;
|
|
148
|
+
project_id: number | null;
|
|
149
|
+
artifact_count: number;
|
|
150
|
+
}>();
|
|
151
|
+
return json({ user: userEmail, conversations: rows.results ?? [] });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function handleConversationGet(request: Request, env: Env, id: string): Promise<Response> {
|
|
155
|
+
const userEmail = await getUserEmail(request, env);
|
|
156
|
+
const rows = await env.DB.prepare(
|
|
157
|
+
`SELECT * FROM chats
|
|
158
|
+
WHERE conversation_id = ? AND user_email = ?
|
|
159
|
+
ORDER BY turn_index ASC, created_at ASC`
|
|
160
|
+
)
|
|
161
|
+
.bind(id, userEmail)
|
|
162
|
+
.all<{
|
|
163
|
+
attachments: string | null;
|
|
164
|
+
output_artifact: string | null;
|
|
165
|
+
retrieved_context: string | null;
|
|
166
|
+
}>();
|
|
167
|
+
|
|
168
|
+
if ((rows.results ?? []).length === 0) {
|
|
169
|
+
return json({ error: "Not found" }, { status: 404 });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Parse the JSON columns on each turn so the frontend doesn't have to.
|
|
173
|
+
const turns = (rows.results ?? []).map((row) => ({
|
|
174
|
+
...row,
|
|
175
|
+
attachments: row.attachments ? safeParseJson<PersistedAttachment[]>(row.attachments) : null,
|
|
176
|
+
output_artifact: row.output_artifact ? safeParseJson<OutputArtifact>(row.output_artifact) : null,
|
|
177
|
+
retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
|
|
178
|
+
}));
|
|
179
|
+
|
|
180
|
+
const compact = await loadCompactState(env, id, userEmail);
|
|
181
|
+
return json({ conversation_id: id, turns, compact });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function handleConversationDelete(request: Request, env: Env, id: string): Promise<Response> {
|
|
185
|
+
const userEmail = await getUserEmail(request, env);
|
|
186
|
+
|
|
187
|
+
// Pull all R2 keys across all turns before deleting D1 rows.
|
|
188
|
+
const rows = await env.DB.prepare(
|
|
189
|
+
`SELECT attachments, output_artifact FROM chats
|
|
190
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
191
|
+
)
|
|
192
|
+
.bind(id, userEmail)
|
|
193
|
+
.all<{ attachments: string | null; output_artifact: string | null }>();
|
|
194
|
+
|
|
195
|
+
const results = rows.results ?? [];
|
|
196
|
+
if (results.length === 0) {
|
|
197
|
+
return json({ error: "Not found" }, { status: 404 });
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const keysToDelete: string[] = [];
|
|
201
|
+
for (const row of results) {
|
|
202
|
+
if (row.attachments) {
|
|
203
|
+
const atts = safeParseJson<PersistedAttachment[]>(row.attachments) ?? [];
|
|
204
|
+
for (const a of atts) {
|
|
205
|
+
if (a.type === "image") keysToDelete.push(a.key);
|
|
206
|
+
else if (a.type === "video_frames") keysToDelete.push(...(a.keys ?? []));
|
|
207
|
+
else if (a.type === "video_full") keysToDelete.push(a.key);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (row.output_artifact) {
|
|
211
|
+
const oa = safeParseJson<OutputArtifact>(row.output_artifact);
|
|
212
|
+
if (oa?.key) keysToDelete.push(oa.key);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
await env.DB.prepare(
|
|
217
|
+
`DELETE FROM chats WHERE conversation_id = ? AND user_email = ?`
|
|
218
|
+
)
|
|
219
|
+
.bind(id, userEmail)
|
|
220
|
+
.run();
|
|
221
|
+
|
|
222
|
+
// Drop compact state with the conversation (no orphan summaries).
|
|
223
|
+
await env.DB.prepare(
|
|
224
|
+
`DELETE FROM conversation_compact WHERE conversation_id = ? AND user_email = ?`,
|
|
225
|
+
)
|
|
226
|
+
.bind(id, userEmail)
|
|
227
|
+
.run();
|
|
228
|
+
|
|
229
|
+
for (const k of keysToDelete) {
|
|
230
|
+
await r2DeleteSafe(env, k);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return json({ deleted: id, turns_removed: results.length, artifacts_removed: keysToDelete.length });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------- Compact (v0.175.7) ----------
|
|
237
|
+
//
|
|
238
|
+
// POST /api/conversations/:id/compact
|
|
239
|
+
// Body: { keep_recent?: number, model?: string }
|
|
240
|
+
// Summarizes older turns with a chat model; stores the summary so subsequent
|
|
241
|
+
// chat turns inject it instead of re-sending those turns. UI transcript is
|
|
242
|
+
// unchanged.
|
|
243
|
+
//
|
|
244
|
+
// DELETE /api/conversations/:id/compact
|
|
245
|
+
// Clears compact state; next chat turn resends the full raw history again.
|
|
246
|
+
|
|
247
|
+
async function summarizeTranscript(
|
|
248
|
+
env: Env,
|
|
249
|
+
userEmail: string,
|
|
250
|
+
model: ModelEntry,
|
|
251
|
+
transcript: string,
|
|
252
|
+
): Promise<{ text: string; logId: string | null } | Response> {
|
|
253
|
+
const backendOrErr = await requireInferenceBackend(env, userEmail, {
|
|
254
|
+
requireCfToken: modelNeedsCfAigToken(model),
|
|
255
|
+
});
|
|
256
|
+
if (backendOrErr instanceof Response) return backendOrErr;
|
|
257
|
+
|
|
258
|
+
const userContent =
|
|
259
|
+
"Compress the following conversation into a continuity brief.\n\n" + transcript;
|
|
260
|
+
const wantsSystemInMessages = model.provider !== "anthropic" && model.provider !== "google";
|
|
261
|
+
const messages: Array<{ role: string; content: string }> = [];
|
|
262
|
+
if (wantsSystemInMessages) {
|
|
263
|
+
messages.push({ role: "system", content: COMPACT_SYSTEM_PROMPT });
|
|
264
|
+
}
|
|
265
|
+
messages.push({ role: "user", content: userContent });
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
if (backendOrErr.kind === "control_plane") {
|
|
269
|
+
const cpResult = await controlPlaneChat(backendOrErr.cp, {
|
|
270
|
+
model: model.id,
|
|
271
|
+
messages: [
|
|
272
|
+
{ role: "system", content: COMPACT_SYSTEM_PROMPT },
|
|
273
|
+
{ role: "user", content: userContent },
|
|
274
|
+
],
|
|
275
|
+
});
|
|
276
|
+
return { text: cpResult.text, logId: cpResult.requestId };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const aiCtx: AiContext = backendOrErr.ctx;
|
|
280
|
+
let result: unknown;
|
|
281
|
+
let logId: string | null = null;
|
|
282
|
+
if (model.provider === "anthropic") {
|
|
283
|
+
const r = await callAnthropic(aiCtx, model, COMPACT_SYSTEM_PROMPT, messages);
|
|
284
|
+
result = r.raw;
|
|
285
|
+
logId = r.logId;
|
|
286
|
+
} else if (model.provider === "xai") {
|
|
287
|
+
const r = await callXai(aiCtx, model, messages);
|
|
288
|
+
result = r.raw;
|
|
289
|
+
logId = r.logId;
|
|
290
|
+
} else if (model.provider === "google") {
|
|
291
|
+
const r = await callGemini(aiCtx, model, COMPACT_SYSTEM_PROMPT, messages);
|
|
292
|
+
result = r.raw;
|
|
293
|
+
logId = r.logId;
|
|
294
|
+
} else if (model.provider === "openai") {
|
|
295
|
+
const r = await callOpenAI(aiCtx, model, messages);
|
|
296
|
+
result = r.raw;
|
|
297
|
+
logId = r.logId;
|
|
298
|
+
} else {
|
|
299
|
+
result = await aiRun(aiCtx, model.id, { messages });
|
|
300
|
+
logId = aiLogId(aiCtx);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const fail = detectProviderFailure(result);
|
|
304
|
+
if (fail) {
|
|
305
|
+
return json({ error: `Compact model failed: ${fail}` }, { status: 502 });
|
|
306
|
+
}
|
|
307
|
+
const text = extractOutput(result);
|
|
308
|
+
if (!text.trim()) {
|
|
309
|
+
return json({ error: "Compact model returned empty summary" }, { status: 502 });
|
|
310
|
+
}
|
|
311
|
+
return { text, logId };
|
|
312
|
+
} catch (err) {
|
|
313
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
314
|
+
const status = (err as { status?: number })?.status;
|
|
315
|
+
if (status === 401 || status === 402 || status === 403 || status === 429) {
|
|
316
|
+
return json({ error: `Compact AI call failed: ${m}`, code: (err as { code?: string })?.code }, { status });
|
|
317
|
+
}
|
|
318
|
+
return json({ error: `Compact AI call failed: ${m}` }, { status: 502 });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export async function handleConversationCompact(
|
|
323
|
+
request: Request,
|
|
324
|
+
env: Env,
|
|
325
|
+
conversationId: string,
|
|
326
|
+
): Promise<Response> {
|
|
327
|
+
const userEmail = await getUserEmail(request, env);
|
|
328
|
+
|
|
329
|
+
let body: { keep_recent?: number; model?: string } = {};
|
|
330
|
+
try {
|
|
331
|
+
const raw = await request.text();
|
|
332
|
+
if (raw.trim()) body = JSON.parse(raw) as { keep_recent?: number; model?: string };
|
|
333
|
+
} catch {
|
|
334
|
+
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const keepRecent =
|
|
338
|
+
typeof body.keep_recent === "number" && Number.isFinite(body.keep_recent)
|
|
339
|
+
? Math.max(0, Math.min(20, Math.floor(body.keep_recent)))
|
|
340
|
+
: DEFAULT_KEEP_RECENT;
|
|
341
|
+
|
|
342
|
+
const modelId = (body.model?.trim() || DEFAULT_COMPACT_MODEL);
|
|
343
|
+
const model = MODELS.find((m) => m.id === modelId);
|
|
344
|
+
if (!model || model.type !== "chat") {
|
|
345
|
+
return json({ error: `Unknown or non-chat model for compact: ${modelId}` }, { status: 400 });
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const turns = await loadChatTurns(env, conversationId, userEmail);
|
|
349
|
+
if (turns.length === 0) {
|
|
350
|
+
return json({ error: "Conversation not found or has no completed chat turns" }, { status: 404 });
|
|
351
|
+
}
|
|
352
|
+
if (turns.length < keepRecent + 1) {
|
|
353
|
+
return json(
|
|
354
|
+
{
|
|
355
|
+
error: `Need at least ${keepRecent + 1} completed chat turns to compact (have ${turns.length})`,
|
|
356
|
+
code: "not_enough_turns",
|
|
357
|
+
turn_count: turns.length,
|
|
358
|
+
keep_recent: keepRecent,
|
|
359
|
+
},
|
|
360
|
+
{ status: 400 },
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const { summarize, keep } = splitTurnsForCompact(turns, keepRecent);
|
|
365
|
+
if (summarize.length === 0) {
|
|
366
|
+
return json({ error: "Nothing to summarize with this keep_recent", code: "not_enough_turns" }, { status: 400 });
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const transcript = formatTurnsForSummary(summarize);
|
|
370
|
+
const summarized = await summarizeTranscript(env, userEmail, model, transcript);
|
|
371
|
+
if (summarized instanceof Response) return summarized;
|
|
372
|
+
|
|
373
|
+
const summary = normalizeSummary(summarized.text);
|
|
374
|
+
const throughTurnIndex = summarize[summarize.length - 1].turn_index;
|
|
375
|
+
const updatedAt = new Date().toISOString();
|
|
376
|
+
|
|
377
|
+
await env.DB.prepare(
|
|
378
|
+
`INSERT INTO conversation_compact
|
|
379
|
+
(conversation_id, user_email, summary, through_turn_index, keep_recent, model, updated_at)
|
|
380
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
381
|
+
ON CONFLICT(conversation_id, user_email) DO UPDATE SET
|
|
382
|
+
summary = excluded.summary,
|
|
383
|
+
through_turn_index = excluded.through_turn_index,
|
|
384
|
+
keep_recent = excluded.keep_recent,
|
|
385
|
+
model = excluded.model,
|
|
386
|
+
updated_at = excluded.updated_at`,
|
|
387
|
+
)
|
|
388
|
+
.bind(conversationId, userEmail, summary, throughTurnIndex, keepRecent, model.id, updatedAt)
|
|
389
|
+
.run();
|
|
390
|
+
|
|
391
|
+
return json({
|
|
392
|
+
conversation_id: conversationId,
|
|
393
|
+
compact: {
|
|
394
|
+
summary,
|
|
395
|
+
through_turn_index: throughTurnIndex,
|
|
396
|
+
keep_recent: keepRecent,
|
|
397
|
+
model: model.id,
|
|
398
|
+
updated_at: updatedAt,
|
|
399
|
+
},
|
|
400
|
+
turns_summarized: summarize.length,
|
|
401
|
+
turns_kept_raw: keep.length,
|
|
402
|
+
ai_gateway_log_id: summarized.logId,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export async function handleConversationCompactClear(
|
|
407
|
+
request: Request,
|
|
408
|
+
env: Env,
|
|
409
|
+
conversationId: string,
|
|
410
|
+
): Promise<Response> {
|
|
411
|
+
const userEmail = await getUserEmail(request, env);
|
|
412
|
+
const existing = await env.DB.prepare(
|
|
413
|
+
`SELECT COUNT(*) AS n FROM chats WHERE conversation_id = ? AND user_email = ?`,
|
|
414
|
+
)
|
|
415
|
+
.bind(conversationId, userEmail)
|
|
416
|
+
.first<{ n: number }>();
|
|
417
|
+
if (!existing || existing.n === 0) {
|
|
418
|
+
return json({ error: "Conversation not found" }, { status: 404 });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const result = await env.DB.prepare(
|
|
422
|
+
`DELETE FROM conversation_compact WHERE conversation_id = ? AND user_email = ?`,
|
|
423
|
+
)
|
|
424
|
+
.bind(conversationId, userEmail)
|
|
425
|
+
.run();
|
|
426
|
+
|
|
427
|
+
return json({
|
|
428
|
+
conversation_id: conversationId,
|
|
429
|
+
compact: null,
|
|
430
|
+
cleared: (result.meta?.changes ?? 0) > 0,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// v0.20.2: move a conversation to a project (or clear its project assignment).
|
|
435
|
+
// Body: { project_id: number | null }. When project_id is a number, the
|
|
436
|
+
// project must exist and belong to the same user. When null, the assignment
|
|
437
|
+
// is cleared on all turns.
|
|
438
|
+
//
|
|
439
|
+
// All turns in the conversation are updated atomically. The conversation_id
|
|
440
|
+
// is the existing key for ownership (chats.user_email + conversation_id).
|
|
441
|
+
export async function handleConversationMoveToProject(
|
|
442
|
+
request: Request,
|
|
443
|
+
env: Env,
|
|
444
|
+
conversationId: string,
|
|
445
|
+
): Promise<Response> {
|
|
446
|
+
const userEmail = await getUserEmail(request, env);
|
|
447
|
+
|
|
448
|
+
let body: { project_id?: number | null };
|
|
449
|
+
try {
|
|
450
|
+
body = await request.json();
|
|
451
|
+
} catch {
|
|
452
|
+
return json({ error: "Invalid JSON body" }, { status: 400 });
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const newProjectId = body.project_id ?? null;
|
|
456
|
+
if (newProjectId !== null) {
|
|
457
|
+
if (!Number.isInteger(newProjectId) || newProjectId <= 0) {
|
|
458
|
+
return json({ error: "project_id must be a positive integer or null" }, { status: 400 });
|
|
459
|
+
}
|
|
460
|
+
// Confirm the target project exists and belongs to this user.
|
|
461
|
+
const proj = await env.DB.prepare(
|
|
462
|
+
`SELECT id FROM projects WHERE id = ? AND user_email = ?`
|
|
463
|
+
)
|
|
464
|
+
.bind(newProjectId, userEmail)
|
|
465
|
+
.first();
|
|
466
|
+
if (!proj) return json({ error: "Project not found" }, { status: 404 });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Confirm the conversation exists and belongs to this user before
|
|
470
|
+
// updating, otherwise we silently no-op on stale ids.
|
|
471
|
+
const existing = await env.DB.prepare(
|
|
472
|
+
`SELECT COUNT(*) AS n FROM chats
|
|
473
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
474
|
+
)
|
|
475
|
+
.bind(conversationId, userEmail)
|
|
476
|
+
.first<{ n: number }>();
|
|
477
|
+
if (!existing || existing.n === 0) {
|
|
478
|
+
return json({ error: "Conversation not found" }, { status: 404 });
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const result = await env.DB.prepare(
|
|
482
|
+
`UPDATE chats SET project_id = ?
|
|
483
|
+
WHERE conversation_id = ? AND user_email = ?`
|
|
484
|
+
)
|
|
485
|
+
.bind(newProjectId, conversationId, userEmail)
|
|
486
|
+
.run();
|
|
487
|
+
|
|
488
|
+
return json({
|
|
489
|
+
conversation_id: conversationId,
|
|
490
|
+
project_id: newProjectId,
|
|
491
|
+
rows_updated: result.meta?.changes ?? 0,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|