@skyphusion/create-prism 0.175.6 → 1.0.4

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.
@@ -24,6 +24,7 @@ import {
24
24
  } from "./auth";
25
25
  import { json } from "./routes/shared";
26
26
  import { handleHealthDeep } from "./routes/health";
27
+ import { VERSION } from "./version";
27
28
  import { handlePrefsGet, handlePrefsPatch } from "./routes/prefs";
28
29
  import {
29
30
  handleChat,
@@ -41,6 +42,8 @@ import {
41
42
  handleConversationGet,
42
43
  handleConversationDelete,
43
44
  handleConversationMoveToProject,
45
+ handleConversationCompact,
46
+ handleConversationCompactClear,
44
47
  } from "./routes/conversations";
45
48
  import {
46
49
  handleDocumentList,
@@ -60,6 +63,8 @@ import {
60
63
  handleDiscordImport,
61
64
  } from "./routes/projects";
62
65
  import { handleArtifact } from "./routes/artifacts";
66
+ import { handleCspReport } from "./routes/csp-report";
67
+ import { CSP_HEADER, buildCspPolicy } from "./csp";
63
68
 
64
69
  // Durable Object + Workflow classes must stay exported from the main entry so
65
70
  // wrangler resolves each class_name against this module.
@@ -72,8 +77,19 @@ export default {
72
77
 
73
78
  // Cheap liveness check. No binding access; sub-millisecond response.
74
79
  // Use for high-frequency uptime polling (Kuma at 60s interval, etc).
80
+ //
81
+ // Carries `version` so "which code is serving?" is answerable from an
82
+ // unauthenticated surface. A green deploy workflow proves the upload
83
+ // succeeded, not that the running Worker is the code you think it is, and
84
+ // until this field existed that question needed an account-scoped
85
+ // Cloudflare token. It is on the LIVENESS probe deliberately: the answer
86
+ // is about the deploy, not about the bindings, so it must not require
87
+ // /health/deep's D1, R2 and Vectorize round-trips, and it has to survive
88
+ // the 503 path. Value comes from src/version.ts, pinned to package.json by
89
+ // a test that DERIVES the expected string rather than transcribing it.
90
+ // See fleet-chezmoi#1641.
75
91
  if (url.pathname === "/health") {
76
- return json({ ok: true, ts: Date.now() });
92
+ return json({ ok: true, ts: Date.now(), version: VERSION });
77
93
  }
78
94
 
79
95
  // Deep check: exercises D1, R2, Vectorize, and confirms the AI gateway
@@ -100,6 +116,16 @@ export default {
100
116
  return handleLogout(request, env);
101
117
  }
102
118
 
119
+ // CSP violation collector (fleet-chezmoi#1646). Sits above the gate
120
+ // deliberately: browsers post violation reports WITHOUT credentials, so a
121
+ // session-gated collector would collect nothing. That makes it an
122
+ // unauthenticated public write endpoint, and the handler is written for
123
+ // that: body cap with refusal past it, fixed bounded projection, per-IP
124
+ // rate limit with visible shedding, prune-on-write retention.
125
+ if (url.pathname === "/api/csp-report" && request.method === "POST") {
126
+ return handleCspReport(request, env);
127
+ }
128
+
103
129
  // Public-mode gate: every other /api/* route requires a valid session.
104
130
  // GET /api/models is exempt (it is the unauthenticated boot probe). Uniform
105
131
  // 401 { code: "unauthenticated" } so the frontend routes the user to the
@@ -233,6 +259,12 @@ export default {
233
259
  if (cp && request.method === "PATCH") {
234
260
  return handleConversationMoveToProject(request, env, cp[1]);
235
261
  }
262
+ // v0.175.7: compact older turns into a summary for model context.
263
+ const cc = url.pathname.match(/^\/api\/conversations\/([A-Za-z0-9_:-]+)\/compact$/);
264
+ if (cc) {
265
+ if (request.method === "POST") return handleConversationCompact(request, env, cc[1]);
266
+ if (request.method === "DELETE") return handleConversationCompactClear(request, env, cc[1]);
267
+ }
236
268
 
237
269
  const h = url.pathname.match(/^\/api\/history\/(\d+)$/);
238
270
  if (h) {
@@ -257,7 +289,58 @@ export default {
257
289
  return handleArtifact(request, env, decodeURIComponent(a[1]));
258
290
  }
259
291
 
260
- return env.ASSETS.fetch(request);
292
+ // ---- Security headers on the static surface (fleet-chezmoi#1646) ----
293
+ //
294
+ // SCOPE, stated so it is not mistaken for more than it is: these are
295
+ // applied to the ASSETS responses, which is where the HTML and every
296
+ // static file come from. API responses returned above do NOT carry them.
297
+ // For CSP that is correct, since a policy only governs the document that
298
+ // carries it. For HSTS it is a known and deliberate gap in phase one: a
299
+ // browser that has loaded the page already holds the header, and widening
300
+ // it to every route is a separate change to every response path.
301
+ //
302
+ // The three headers this deploy already carries (x-frame-options,
303
+ // referrer-policy, x-content-type-options) are NOT set here. They are
304
+ // applied at the edge by a zone Transform Rule for every host on the
305
+ // zone, measured directly in the zone config. Setting them here would be
306
+ // a duplicate CERTAINTY rather than a duplicate risk, and a duplicated
307
+ // x-frame-options is worse than either value alone because agents
308
+ // disagree about which wins. Bringing that rule under declared config is
309
+ // fleet-chezmoi#1626; duplicating a control is not declaring it.
310
+ const assetRes = await env.ASSETS.fetch(request);
311
+ const isHtml = (assetRes.headers.get("content-type") || "").includes("text/html");
312
+ const headers = new Headers(assetRes.headers);
313
+
314
+ // ENFORCING as of the fleet-chezmoi#1646 promotion. Violations are now
315
+ // BLOCKED, and still posted to the collector routed above, which is what
316
+ // keeps this observable: the stored `disposition` reads `enforce` rather
317
+ // than `report`, so a directive this policy gets wrong arrives as a row
318
+ // naming what broke instead of as a user noticing a dead feature.
319
+ //
320
+ // The two exceptions the policy carries (`data:` on img-src, `blob:` on
321
+ // media-src) were each established by an OBSERVED violation during the
322
+ // report-only phase, never by reading the frontend and deciding what
323
+ // looked necessary. See src/csp.ts for the provenance of each.
324
+ //
325
+ // Note the header NAME comes from the same module as the policy. Building
326
+ // an enforcing policy and emitting it under the report-only name is a
327
+ // decorative control that no test reading only one of the two can catch.
328
+ if (isHtml) {
329
+ headers.set(CSP_HEADER, buildCspPolicy());
330
+ }
331
+
332
+ // HSTS. Phase-one max-age is deliberately SHORT (1 day). A long max-age is
333
+ // cached by every client that sees it and cannot be recalled, so shipping
334
+ // six months on first rollout commits the estate to a promise nobody has
335
+ // observed holding yet. Ramping is a one-line change once it has. No
336
+ // preload, which is the genuinely irreversible one.
337
+ headers.set("strict-transport-security", "max-age=86400; includeSubDomains");
338
+
339
+ return new Response(assetRes.body, {
340
+ status: assetRes.status,
341
+ statusText: assetRes.statusText,
342
+ headers,
343
+ });
261
344
  },
262
345
 
263
346
  };
@@ -49,6 +49,8 @@ import {
49
49
  } from "./rag";
50
50
  import { resolveProjectForChat } from "./projects";
51
51
  import type { LongRunParams } from "./workflow";
52
+ import { loadChatTurns, loadCompactState } from "./conversations";
53
+ import { applyCompactToPriorTurns } from "../conversation-context";
52
54
 
53
55
  //
54
56
  // Multimodal model types:
@@ -218,22 +220,14 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
218
220
  // multimodal+RAG turns. We await each promise at its existing use site
219
221
  // below so the error surface is unchanged.
220
222
  const conversationIdIn = body.conversation_id?.trim() || "";
221
- const priorTurnsPromise: Promise<{
222
- rows: Array<{ user_input: string; output: string; turn_index: number }>;
223
- }> = conversationIdIn
224
- ? env.DB.prepare(
225
- `SELECT user_input, output, turn_index
226
- FROM chats
227
- WHERE conversation_id = ?
228
- AND user_email = ?
229
- AND status = 'done'
230
- AND model_type = 'chat'
231
- ORDER BY turn_index ASC`
232
- )
233
- .bind(conversationIdIn, userEmail)
234
- .all<{ user_input: string; output: string; turn_index: number }>()
235
- .then((r) => ({ rows: r.results ?? [] }))
236
- : Promise.resolve({ rows: [] });
223
+ // Prior turns + compact state (v0.175.7): when compacted, only recent raw
224
+ // turns are re-sent; older turns are replaced by a system summary block.
225
+ const priorContextPromise = conversationIdIn
226
+ ? Promise.all([
227
+ loadChatTurns(env, conversationIdIn, userEmail),
228
+ loadCompactState(env, conversationIdIn, userEmail),
229
+ ]).then(([turns, compact]) => applyCompactToPriorTurns(turns, compact))
230
+ : Promise.resolve(applyCompactToPriorTurns([], null));
237
231
 
238
232
  const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
239
233
  body.use_docs
@@ -342,26 +336,19 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
342
336
  ? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
343
337
  : userText;
344
338
 
345
- // ---- Multi-turn conversation continuation (v0.10.0) ----
346
- // If body.conversation_id is present, fetch prior turns of that conversation
347
- // (filtered to this user, completed chat turns only) and assemble a history
348
- // of user/assistant message pairs. The current turn appends to that history.
349
- // If no conversation_id, generate a new one for the first turn.
350
- // The SELECT itself runs in parallel with the attachment walk (hoisted
351
- // above as priorTurnsPromise); here we just consume the result.
339
+ // ---- Multi-turn conversation continuation (v0.10.0) + compact (v0.175.7) ----
340
+ // If body.conversation_id is present, load prior turns (and optional compact
341
+ // summary). The current turn appends. If no conversation_id, mint a new one.
352
342
  let conversationId = conversationIdIn;
353
343
  let turnIndex = 0;
354
- const priorTurns: Array<{ user_input: string; output: string }> = [];
344
+ let priorTurns: Array<{ user_input: string; output: string }> = [];
345
+ let compactBlock: string | null = null;
355
346
 
356
347
  if (conversationId) {
357
- const { rows } = await priorTurnsPromise;
358
- for (const r of rows) {
359
- // Skip empty/failed prior turns defensively.
360
- if (r.user_input && r.output) {
361
- priorTurns.push({ user_input: r.user_input, output: r.output });
362
- }
363
- }
364
- turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
348
+ const prior = await priorContextPromise;
349
+ priorTurns = prior.priorTurns;
350
+ turnIndex = prior.turnIndex;
351
+ compactBlock = prior.compactBlock;
365
352
  } else {
366
353
  // crypto.randomUUID() is available in Workers runtime.
367
354
  conversationId = crypto.randomUUID();
@@ -376,14 +363,12 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
376
363
  const { results: webResults, error: webSearchError } = await webSearchPromise;
377
364
  const allRetrieved: RetrievedItem[] = [...retrievedChunks, ...webResults];
378
365
 
379
- // Build the effective system prompt: user-supplied prompt followed by
380
- // the retrieval block(s). Order: user prompt, then RAG (more specific
381
- // to this user's corpus), then web (more general). Either or both
382
- // retrieval blocks may be empty.
366
+ // Build the effective system prompt: user-supplied prompt, optional compact
367
+ // block for earlier turns, then retrieval. Order: user, compact, RAG, web.
383
368
  const userSystemPrompt = body.system_prompt?.trim() ?? "";
384
369
  const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
385
370
  const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
386
- const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
371
+ const effectiveSystemPrompt = [userSystemPrompt, compactBlock, retrievalBlock, webBlock]
387
372
  .filter(Boolean)
388
373
  .join("\n\n");
389
374
 
@@ -544,13 +529,24 @@ export async function runChat(request: Request, env: Env, model: ModelEntry, bod
544
529
 
545
530
  export async function runImage(request: Request, env: Env, model: ModelEntry, body: ChatRequest): Promise<Response> {
546
531
  const userEmail = await getUserEmail(request, env);
547
- let aiCtx: AiContext | null = null;
532
+
533
+ // Resolve the caller's own gateway credentials before any inference runs.
534
+ //
535
+ // This is deliberately NOT conditional on which transport the model uses.
536
+ // Some @cf image models call the binding directly because the gateway cannot
537
+ // proxy their request or response shapes (see the bypass block further down);
538
+ // that is a TRANSPORT property of the model and must not decide
539
+ // AUTHORIZATION of the caller. Resolving here, unconditionally, makes this
540
+ // the single seam every branch below passes through, so a model that later
541
+ // needs some new transport cannot acquire a new way around the gate along
542
+ // with it.
543
+ //
544
+ // requireCfToken is the one thing that legitimately varies: proxied models
545
+ // additionally need a Cloudflare AI Gateway token, @cf models do not.
548
546
  const needsProxiedGateway = !!model.provider;
549
- if (needsProxiedGateway) {
550
- const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: true });
551
- if (ctxOrErr instanceof Response) return ctxOrErr;
552
- aiCtx = ctxOrErr;
553
- }
547
+ const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: needsProxiedGateway });
548
+ if (ctxOrErr instanceof Response) return ctxOrErr;
549
+ const aiCtx: AiContext = ctxOrErr;
554
550
 
555
551
  // Image gen splits two ways. Proxied models (those with a `provider`:
556
552
  // nano-banana/google, gpt-image-1.5/openai, recraftv4/recraft) go through the
@@ -582,8 +578,8 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
582
578
  mime = gen.mime;
583
579
  logId = null; // direct OpenAI; no AI Gateway log
584
580
  } else {
585
- const result = await aiRun(aiCtx!, model.id, buildProxiedImageParams(model.provider, body.user_input));
586
- logId = aiLogId(aiCtx!);
581
+ const result = await aiRun(aiCtx, model.id, buildProxiedImageParams(model.provider, body.user_input));
582
+ logId = aiLogId(aiCtx);
587
583
 
588
584
  const failure = detectProviderFailure(result);
589
585
  if (failure) {
@@ -699,14 +695,14 @@ export async function runImage(request: Request, env: Env, model: ModelEntry, bo
699
695
  // populates ai_gateway_log_id for observability).
700
696
  let result: unknown;
701
697
  if (bypassGateway) {
698
+ // Transport bypass only. Credentials were resolved at the top of
699
+ // runImage, so this call is authorized on exactly the same terms as
700
+ // every other path here. What it skips is the gateway TRANSPORT, and
701
+ // with it the gateway's observability, which is why ai_gateway_log_id
702
+ // stays null on the persisted row below.
702
703
  type BypassRunFn = (model: string, params: unknown) => Promise<unknown>;
703
704
  result = await (env.AI as unknown as { run: BypassRunFn }).run(model.id, runParams);
704
705
  } else {
705
- if (!aiCtx) {
706
- const ctxOrErr = await requireAiContext(env, userEmail, { requireCfToken: false });
707
- if (ctxOrErr instanceof Response) return ctxOrErr;
708
- aiCtx = ctxOrErr;
709
- }
710
706
  result = await aiRun(aiCtx, model.id, runParams);
711
707
  logId = aiLogId(aiCtx);
712
708
  }
@@ -1260,25 +1256,15 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1260
1256
  const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
1261
1257
  body.system_prompt = resolvedSystemPrompt;
1262
1258
 
1263
- // Hot-path parallelization (mirrors runChat v0.12.1). Kick off SELECT +
1264
- // RAG retrieve before the attachment walk; await at the existing use sites.
1259
+ // Hot-path parallelization (mirrors runChat v0.12.1). Kick off prior
1260
+ // context (turns + compact) + RAG before the attachment walk.
1265
1261
  const conversationIdIn = body.conversation_id?.trim() || "";
1266
- const priorTurnsPromise: Promise<{
1267
- rows: Array<{ user_input: string; output: string; turn_index: number }>;
1268
- }> = conversationIdIn
1269
- ? env.DB.prepare(
1270
- `SELECT user_input, output, turn_index
1271
- FROM chats
1272
- WHERE conversation_id = ?
1273
- AND user_email = ?
1274
- AND status = 'done'
1275
- AND model_type = 'chat'
1276
- ORDER BY turn_index ASC`
1277
- )
1278
- .bind(conversationIdIn, userEmail)
1279
- .all<{ user_input: string; output: string; turn_index: number }>()
1280
- .then((r) => ({ rows: r.results ?? [] }))
1281
- : Promise.resolve({ rows: [] });
1262
+ const priorContextPromise = conversationIdIn
1263
+ ? Promise.all([
1264
+ loadChatTurns(env, conversationIdIn, userEmail),
1265
+ loadCompactState(env, conversationIdIn, userEmail),
1266
+ ]).then(([turns, compact]) => applyCompactToPriorTurns(turns, compact))
1267
+ : Promise.resolve(applyCompactToPriorTurns([], null));
1282
1268
 
1283
1269
  const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
1284
1270
  body.use_docs
@@ -1370,19 +1356,17 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1370
1356
  ? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
1371
1357
  : userText;
1372
1358
 
1373
- // Consume the parallel-hoisted promises.
1359
+ // Consume the parallel-hoisted promises (turns + compact + retrieval).
1374
1360
  let conversationId = conversationIdIn;
1375
1361
  let turnIndex = 0;
1376
- const priorTurns: Array<{ user_input: string; output: string }> = [];
1362
+ let priorTurns: Array<{ user_input: string; output: string }> = [];
1363
+ let compactBlock: string | null = null;
1377
1364
 
1378
1365
  if (conversationId) {
1379
- const { rows } = await priorTurnsPromise;
1380
- for (const r of rows) {
1381
- if (r.user_input && r.output) {
1382
- priorTurns.push({ user_input: r.user_input, output: r.output });
1383
- }
1384
- }
1385
- turnIndex = rows.length ? (rows[rows.length - 1].turn_index + 1) : 0;
1366
+ const prior = await priorContextPromise;
1367
+ priorTurns = prior.priorTurns;
1368
+ turnIndex = prior.turnIndex;
1369
+ compactBlock = prior.compactBlock;
1386
1370
  } else {
1387
1371
  conversationId = crypto.randomUUID();
1388
1372
  }
@@ -1394,7 +1378,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1394
1378
  const userSystemPrompt = body.system_prompt?.trim() ?? "";
1395
1379
  const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
1396
1380
  const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
1397
- const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
1381
+ const effectiveSystemPrompt = [userSystemPrompt, compactBlock, retrievalBlock, webBlock]
1398
1382
  .filter(Boolean)
1399
1383
  .join("\n\n");
1400
1384
 
@@ -1,10 +1,86 @@
1
1
  // Conversation routes: list conversations (grouped by conversation_id), fetch a
2
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.
3
+ // turns), move a conversation to/from a project, and compact (summarize older
4
+ // turns for model context). Scoped to the caller.
4
5
 
5
6
  import type { Env } from "../env";
6
- import { json, getUserEmail, r2DeleteSafe, safeParseJson } from "./shared";
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";
7
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
+ }
8
84
 
9
85
  // ---------- Multi-turn conversations ----------
10
86
  //
@@ -101,7 +177,8 @@ export async function handleConversationGet(request: Request, env: Env, id: stri
101
177
  retrieved_context: row.retrieved_context ? safeParseJson<RetrievedItem[]>(row.retrieved_context) : null,
102
178
  }));
103
179
 
104
- return json({ conversation_id: id, turns });
180
+ const compact = await loadCompactState(env, id, userEmail);
181
+ return json({ conversation_id: id, turns, compact });
105
182
  }
106
183
 
107
184
  export async function handleConversationDelete(request: Request, env: Env, id: string): Promise<Response> {
@@ -142,6 +219,13 @@ export async function handleConversationDelete(request: Request, env: Env, id: s
142
219
  .bind(id, userEmail)
143
220
  .run();
144
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
+
145
229
  for (const k of keysToDelete) {
146
230
  await r2DeleteSafe(env, k);
147
231
  }
@@ -149,6 +233,204 @@ export async function handleConversationDelete(request: Request, env: Env, id: s
149
233
  return json({ deleted: id, turns_removed: results.length, artifacts_removed: keysToDelete.length });
150
234
  }
151
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
+
152
434
  // v0.20.2: move a conversation to a project (or clear its project assignment).
153
435
  // Body: { project_id: number | null }. When project_id is a number, the
154
436
  // project must exist and belong to the same user. When null, the assignment