@skyphusion/create-prism 0.175.6 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyphusion/create-prism",
3
- "version": "0.175.6",
3
+ "version": "1.0.0",
4
4
  "description": "Scaffold a new prism deployment: a multimodal AI playground on Cloudflare Workers.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Conrad Rockenhaus",
@@ -4,7 +4,49 @@
4
4
  [![Typecheck](https://github.com/skyphusion-labs/prism/actions/workflows/typecheck.yml/badge.svg)](https://github.com/skyphusion-labs/prism/actions/workflows/typecheck.yml)
5
5
  [![Voice chat](https://img.shields.io/badge/%F0%9F%8E%99%EF%B8%8F_voice_chat-speak_%26_hear_chat_models-6d8cff)](#voice-chat)
6
6
 
7
- A multimodal AI playground deployed as a single Cloudflare Worker. **Live demo:** https://play.skyphusion.org (free signup, bring your own AI Gateway). **~45 chat models** across Workers AI, Anthropic, xAI, OpenAI, Google, and Moonshot (see `GET /api/models`), **hands-free voice chat** (talk to any chat model and hear it reply), image / TTS / STT / video / music generation, cross-model artifact reuse within a conversation (v0.21.7), RAG over files of any type (v0.23.0), projects that scope a knowledge base and system prompt, Discord chat-log ingestion, opt-in web search via self-hosted SearXNG and Wikipedia, SSE streaming on supported chat models, and multi-turn conversations. One web UI with first-party accounts, per-user history, R2 for all binary artifacts.
7
+ A multimodal AI playground deployed as a single Cloudflare Worker. **Live demo:** https://play.skyphusion.org (free signup, bring your own AI Gateway). Catalog breadth is live at `GET /api/models` (and `src/models.ts`): **93** models (44 chat + 21 image + 19 video + 3 TTS + 4 STT + 1 music + 1 live voice); the tables under [Features](#features) list every id. Native clients hit the commercial plane ([prism-control-plane](https://github.com/skyphusion-labs/prism-control-plane)); this Worker is the playground surface (RAG, projects, compact, web search). **Hands-free voice chat**, cross-model artifact reuse, RAG, projects, Discord ingestion, web search, SSE streaming, and multi-turn conversations (with optional **compact**). One web UI with first-party accounts, per-user history, R2 for all binary artifacts.
8
+
9
+ ```mermaid
10
+ flowchart TB
11
+ subgraph browser["Browser / play.skyphusion.org"]
12
+ UI["public/ app.js<br/>chat · image · video · voice"]
13
+ end
14
+
15
+ subgraph worker["Worker: skyphusion-llm"]
16
+ Auth["AUTH_MODE public or access"]
17
+ Chat["/api/chat · /api/chat/stream"]
18
+ Multi["image · TTS · STT · video · music"]
19
+ RAG["Vectorize + D1 RAG"]
20
+ WF["LongRunWorkflow<br/>video · music"]
21
+ end
22
+
23
+ subgraph store["Bindings"]
24
+ D1["D1 history + chunks"]
25
+ R2["R2 artifacts"]
26
+ VZ["Vectorize embeddings"]
27
+ end
28
+
29
+ subgraph ai["Cloudflare AI"]
30
+ GW["AI Gateway"]
31
+ Run["env.AI.run"]
32
+ end
33
+
34
+ subgraph native["Native apps optional"]
35
+ iOS["prism-ios → play-proxy<br/>control plane not this Worker"]
36
+ end
37
+
38
+ UI --> Auth --> Chat
39
+ Auth --> Multi
40
+ Chat --> Run
41
+ Multi --> Run
42
+ Multi --> WF
43
+ Chat --> RAG
44
+ RAG --> VZ
45
+ Chat --> D1
46
+ Multi --> R2
47
+ Run --> GW
48
+ iOS -.->|"separate host<br/>play-proxy.skyphusion.org"| native
49
+ ```
8
50
 
9
51
  <p align="center">
10
52
  <img src="docs/screenshot-desktop.jpg" alt="Desktop UI: image generation with Nano Banana Pro" width="800"><br><br>
@@ -36,27 +78,150 @@ One Worker, no framework, no build step beyond TypeScript. The interesting parts
36
78
  - **Cloudflare Workflows** owns long-running Unified Billing video and music generation (30s to 3min jobs). The `LongRunWorkflow` class holds the blocking `env.AI.run` call alive across step boundaries that `ctx.waitUntil` cannot.
37
79
  - **Two auth modes, one identity seam.** An `AUTH_MODE` setting picks how the worker learns who you are: **public** mode (the hosted product) runs first-party username/password accounts behind an opaque server-side session cookie, while **access** mode (the default, for private self-host) trusts Cloudflare Access's `Cf-Access-Authenticated-User-Email`. Either way a single stable, opaque account id scopes history and R2 ownership (`customMetadata.user_email`), so cross-user access is impossible even if a UUID is guessed.
38
80
  - **Client-side video keyframe extraction** sends 8 evenly-spaced frames to vision-capable chat models instead of uploading the full video file.
39
- - **Searchable model picker** (v0.111.0) groups the live catalog (~94 entries across 7 modalities as of v0.174.3) with capability badges (vision, stream) inline; type to filter by name.
81
+ - **Searchable model picker** (v0.111.0) groups the live catalog from `GET /api/models` (chat + image + video + speech + music) with capability badges (vision, stream) inline; type to filter by name.
40
82
 
41
83
  ## Features
42
84
 
43
- **Chat (see `GET /api/models` / `src/models.ts` for the live list):**
44
- - Workers AI: Llama 4 Scout, Llama 3.x family, Qwen3 30B / QwQ 32B / Qwen2.5 Coder 32B, DeepSeek R1, Mistral Small 3.1, Gemma 4 26B, Granite 4 Micro, Nemotron 3 120B, GLM-4.7 Flash / GLM-5.2, GPT-OSS 120B / 20B, Kimi K2.6 / K2.7 Code, SEA-LION v4 27B, LLaVA 1.5 7B (single-shot vision; the one non-streaming model)
45
- - Anthropic (Unified Billing): Sonnet 5, Opus 5, Opus 4.8 / 4.7 / 4.6, Sonnet 4.6, Haiku 4.5 (all streaming; Fable needs `binding: true`)
46
- - xAI (Unified Billing): Grok 4.5, Grok 4.3, Grok 4.20 (Multi-Agent and Reasoning)
47
- - OpenAI (Unified Billing): GPT-5.5 / 5.5-pro, GPT-5.6 Sol / Terra / Luna (Responses API), GPT-5.4 / mini, o4-mini
48
- - Google Gemini (Unified Billing): Gemini 3.1 Pro, 3.5 Flash, 3.6 Flash
49
- - Moonshot (Unified Billing): Kimi K3
50
-
51
- **Image generation:** Google Nano Banana Pro / Nano Banana 2 / Lite / Imagen 4 (Unified Billing), GPT Image 1.5 and GPT Image 2 (opaque on the proxy; transparent PNG only when `OPENAI_API_KEY` is set, v0.174.0), Recraft V4 / V4.1 / V4.1 Pro (opaque, art-directed), xAI Grok Imagine Image (+ Quality), ByteDance Seedream 5 Pro / Lite, FLUX 2 Klein 9B/4B, FLUX 2 Dev, FLUX-1 schnell, Lucid Origin, Phoenix 1.0, Dreamshaper 8 LCM, Stable Diffusion XL. FLUX.2 models accept up to 4 reference images (v0.16.0) for image-to-image generation, downscaled client-side to 512px.
52
-
53
- **Video generation:** Google Veo 3.1 / 3.1 Fast, ByteDance Seedance 2.0 / 2.0 Fast / Mini, MiniMax Hailuo 2.3 / 2.3 Fast, RunwayML Gen-4.5, Alibaba HappyHorse 1.0 and 1.1 T2V / I2V plus Wan 2.7 I2V, PixVerse v6 / v5.6, Vidu Q3 Pro / Q3 Turbo, xAI Grok Imagine Video and Video 1.5. All route through Unified Billing and durable Cloudflare Workflows.
54
-
55
- **Music generation:** MiniMax Music 2.6 (Unified Billing, durable via Workflows).
56
-
57
- **Text-to-speech:** Aura-2 EN / ES, MeloTTS.
58
-
59
- **Speech-to-text:** Whisper Large v3 Turbo / Whisper / Whisper Tiny EN and Deepgram Nova-3 (one-shot transcription), plus **Deepgram Flux** conversational/streaming STT with live turn detection over a WebSocket (v0.108.0).
85
+ **Full model catalog (93 entries):** tables below are generated from `src/models.ts`. Live list always wins: `GET /api/models`. The commercial control plane ([prism-control-plane](https://github.com/skyphusion-labs/prism-control-plane)) mirrors the same ids in `src/catalog.ts`.
86
+
87
+ | Modality | Count |
88
+ | --- | ---: |
89
+ | Chat | 44 |
90
+ | Image | 21 |
91
+ | Video | 19 |
92
+ | Text-to-speech (TTS) | 3 |
93
+ | Speech-to-text (STT) | 4 |
94
+ | Music | 1 |
95
+ | Live voice (Flux) | 1 |
96
+ | **Total** | **93** |
97
+
98
+ #### Chat (44)
99
+
100
+ | Model id | Notes |
101
+ | --- | --- |
102
+ | `anthropic/claude-fable-5` | Anthropic; binding |
103
+ | `anthropic/claude-sonnet-5` | Anthropic |
104
+ | `anthropic/claude-opus-5` | Anthropic |
105
+ | `anthropic/claude-opus-4-8` | Anthropic |
106
+ | `anthropic/claude-opus-4-7` | Anthropic |
107
+ | `anthropic/claude-opus-4-6` | Anthropic |
108
+ | `anthropic/claude-sonnet-4-6` | Anthropic |
109
+ | `anthropic/claude-haiku-4-5` | Anthropic |
110
+ | `xai/grok-4.5` | xAI |
111
+ | `xai/grok-4.3` | xAI |
112
+ | `xai/grok-4.20-multi-agent-0309` | xAI multi-agent |
113
+ | `xai/grok-4.20-0309-reasoning` | xAI reasoning |
114
+ | `moonshotai/kimi-k3` | Moonshot UB |
115
+ | `@cf/moonshotai/kimi-k2.6` | Workers AI |
116
+ | `@cf/moonshotai/kimi-k2.7-code` | Workers AI, vision |
117
+ | `@cf/openai/gpt-oss-120b` | Workers AI, reasoning |
118
+ | `@cf/meta/llama-4-scout-17b-16e-instruct` | Workers AI, vision |
119
+ | `@cf/google/gemma-4-26b-a4b-it` | Workers AI, vision |
120
+ | `@cf/openai/gpt-oss-20b` | Workers AI |
121
+ | `openai/gpt-5.5` | OpenAI UB |
122
+ | `openai/gpt-5.5-pro` | OpenAI Responses |
123
+ | `openai/gpt-5.6-sol` | OpenAI Responses |
124
+ | `openai/gpt-5.6-terra` | OpenAI Responses |
125
+ | `openai/gpt-5.6-luna` | OpenAI Responses |
126
+ | `openai/gpt-5.4` | OpenAI UB |
127
+ | `openai/gpt-5.4-mini` | OpenAI UB |
128
+ | `openai/o4-mini` | OpenAI reasoning |
129
+ | `@cf/meta/llama-3.3-70b-instruct-fp8-fast` | Workers AI |
130
+ | `@cf/meta/llama-3.2-11b-vision-instruct` | Workers AI, vision |
131
+ | `@cf/meta/llama-3.2-3b-instruct` | Workers AI |
132
+ | `@cf/qwen/qwen3-30b-a3b-fp8` | Workers AI |
133
+ | `@cf/qwen/qwq-32b` | Workers AI, reasoning |
134
+ | `@cf/qwen/qwen2.5-coder-32b-instruct` | Workers AI |
135
+ | `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` | Workers AI |
136
+ | `@cf/mistralai/mistral-small-3.1-24b-instruct` | Workers AI, vision |
137
+ | `@cf/zai-org/glm-4.7-flash` | Workers AI |
138
+ | `@cf/zai-org/glm-5.2` | Workers AI |
139
+ | `@cf/nvidia/nemotron-3-120b-a12b` | Workers AI |
140
+ | `@cf/aisingapore/gemma-sea-lion-v4-27b-it` | Workers AI |
141
+ | `google/gemini-3.1-pro` | Google Gemini, binding |
142
+ | `google/gemini-3.5-flash` | Google Gemini, binding |
143
+ | `google/gemini-3.6-flash` | Google Gemini, binding |
144
+ | `@cf/ibm-granite/granite-4.0-h-micro` | Workers AI |
145
+ | `@cf/meta/llama-3.2-1b-instruct` | Workers AI |
146
+
147
+ #### Image (21)
148
+
149
+ | Model id | Notes |
150
+ | --- | --- |
151
+ | `google/nano-banana-pro` | Google UB |
152
+ | `google/nano-banana-2` | Google UB |
153
+ | `google/nano-banana-2-lite` | Google UB |
154
+ | `google/imagen-4` | Google UB |
155
+ | `openai/gpt-image-1.5` | OpenAI UB; transparent PNG needs `OPENAI_API_KEY` |
156
+ | `openai/gpt-image-2` | OpenAI UB; transparent PNG needs `OPENAI_API_KEY` |
157
+ | `recraft/recraftv4` | Recraft UB |
158
+ | `recraft/recraftv4-1` | Recraft UB |
159
+ | `recraft/recraftv4-1-pro` | Recraft UB |
160
+ | `xai/grok-imagine-image` | xAI UB |
161
+ | `xai/grok-imagine-image-quality` | xAI UB |
162
+ | `bytedance/seedream-5-pro` | ByteDance UB |
163
+ | `bytedance/seedream-5-lite` | ByteDance UB |
164
+ | `@cf/black-forest-labs/flux-2-klein-9b` | FLUX 2; up to 4 refs |
165
+ | `@cf/black-forest-labs/flux-2-klein-4b` | FLUX 2; up to 4 refs |
166
+ | `@cf/black-forest-labs/flux-2-dev` | FLUX 2 multi-reference |
167
+ | `@cf/black-forest-labs/flux-1-schnell` | FLUX-1 fast |
168
+ | `@cf/leonardo/lucid-origin` | Leonardo |
169
+ | `@cf/leonardo/phoenix-1.0` | Leonardo |
170
+ | `@cf/lykon/dreamshaper-8-lcm` | Fast SD |
171
+ | `@cf/stabilityai/stable-diffusion-xl-base-1.0` | SDXL |
172
+
173
+ #### Video (19)
174
+
175
+ | Model id | Notes |
176
+ | --- | --- |
177
+ | `google/veo-3.1` | Workflow long-run |
178
+ | `google/veo-3.1-fast` | Workflow long-run |
179
+ | `bytedance/seedance-2.0` | Workflow long-run |
180
+ | `bytedance/seedance-2.0-fast` | Workflow long-run |
181
+ | `bytedance/seedance-2.0-mini` | Workflow long-run |
182
+ | `minimax/hailuo-2.3` | i2v-required |
183
+ | `minimax/hailuo-2.3-fast` | i2v-required |
184
+ | `xai/grok-imagine-video` | ZDR upload_url |
185
+ | `xai/grok-imagine-video-1.5-preview` | ZDR upload_url |
186
+ | `runwayml/gen-4.5` | Workflow long-run |
187
+ | `alibaba/hh1-t2v` | HappyHorse 1.0 T2V |
188
+ | `alibaba/hh1-i2v` | HappyHorse 1.0 I2V |
189
+ | `alibaba/hh1.1-t2v` | HappyHorse 1.1 T2V |
190
+ | `alibaba/hh1.1-i2v` | HappyHorse 1.1 I2V |
191
+ | `alibaba/wan-2.7-i2v` | Wan 2.7 I2V |
192
+ | `pixverse/v6` | Workflow long-run |
193
+ | `pixverse/v5.6` | Workflow long-run |
194
+ | `vidu/q3-pro` | Workflow long-run |
195
+ | `vidu/q3-turbo` | Workflow long-run |
196
+
197
+ #### TTS (3)
198
+
199
+ | Model id | Notes |
200
+ | --- | --- |
201
+ | `@cf/deepgram/aura-2-en` | English |
202
+ | `@cf/deepgram/aura-2-es` | Spanish speakers |
203
+ | `@cf/myshell-ai/melotts` | Multilingual |
204
+
205
+ #### STT (4)
206
+
207
+ | Model id | Notes |
208
+ | --- | --- |
209
+ | `@cf/openai/whisper-large-v3-turbo` | Best quality |
210
+ | `@cf/openai/whisper` | General |
211
+ | `@cf/openai/whisper-tiny-en` | Fast English |
212
+ | `@cf/deepgram/nova-3` | Accurate batch |
213
+
214
+ #### Music (1)
215
+
216
+ | Model id | Notes |
217
+ | --- | --- |
218
+ | `minimax/music-2.6` | Workflow long-run |
219
+
220
+ #### Live voice (1)
221
+
222
+ | Model id | Notes |
223
+ | --- | --- |
224
+ | `@cf/deepgram/flux` | Streaming STT over WebSocket |
60
225
 
61
226
  **Voice chat: talk to any model, hear it reply (v0.118.0):** a mic button on any chat model starts a hands-free loop, your speech is transcribed by Flux, each finished turn is sent to the selected model through the normal chat path, and the reply is spoken back via Aura-2 TTS. Works with every chat model in the catalog; the conversation saves to history like any other, and the whole loop runs on Cloudflare (no third-party STT/TTS). See [Voice chat](#voice-chat).
62
227
 
@@ -70,9 +235,11 @@ One Worker, no framework, no build step beyond TypeScript. The interesting parts
70
235
 
71
236
  **Streaming (v0.13.0+):** `POST /api/chat/stream` returns SSE for any chat model flagged `streaming: true` in the catalog. Token deltas surface as `{ type: "delta", text: "..." }` events, terminal completion as `{ type: "done", ... }` with token counts and conversation IDs. Client disconnect aborts the upstream model call immediately.
72
237
 
73
- **Multi-turn conversations:** `conversation_id` plus `turn_index` on chat rows. Continuing a conversation pulls prior turns and assembles a full message history for the next call. Mixed-model conversations allowed (start with Llama, continue with Claude). Text-only on continuation; prior images, audio, and video are not re-sent.
238
+ **Multi-turn conversations:** `conversation_id` plus `turn_index` on chat rows. Continuing a conversation pulls prior completed chat turns and assembles them for the next call. Mixed-model conversations allowed (start with Llama, continue with Claude). Text-only on continuation; prior images, audio, and video are not re-sent.
239
+
240
+ **Conversation compact (v0.175.7):** long threads re-send every prior turn into the model context by default. The UI **compact** control (conversation header) asks a chat model to summarize older turns; the next call injects that summary into the system prompt and only re-sends the recent raw turns (default keep last 2). The full UI transcript is unchanged. **Expand** clears the summary so the next turn uses full history again. API: `POST` / `DELETE /api/conversations/:id/compact`; `GET /api/conversations/:id` returns `compact: null | { summary, through_turn_index, keep_recent, model, updated_at }`.
74
241
 
75
- **UI (focus-mode redesign, v0.110.0+):** a single centered conversation column with a floating composer; the sidebar (searchable history, projects, documents) is a slide-in overlay; a searchable model picker (type to filter, v0.111.0); a ⚙ popover for the system prompt + retrieval toggles and an account menu in the top bar; a paperclip attach button and a voice-chat mic. Capability-aware mode switching (vision-only attachment types; image-mode re-skins to "negative prompt"; TTS / STT / video / music / voice hide irrelevant inputs), FLUX.2 reference-image attach UI (v0.16.0), per-turn web-search toggle (v0.17.0), per-user replay-able history with attachments and generated artifacts, Enter to send / Shift+Enter for newline. Mobile-optimized (safe-area insets, touch targets, no iOS zoom).
242
+ **UI (focus-mode redesign, v0.110.0+):** a single centered conversation column with a floating composer; the sidebar (searchable history, projects, documents) is a slide-in overlay; a searchable model picker (type to filter, v0.111.0); a ⚙ popover for the system prompt + retrieval toggles and an account menu in the top bar; a paperclip attach button and a voice-chat mic; conversation header **compact** / **expand** when a thread has enough turns (v0.175.7). Capability-aware mode switching (vision-only attachment types; image-mode re-skins to "negative prompt"; TTS / STT / video / music / voice hide irrelevant inputs), FLUX.2 reference-image attach UI (v0.16.0), per-turn web-search toggle (v0.17.0), per-user replay-able history with attachments and generated artifacts, Enter to send / Shift+Enter for newline. Mobile-optimized (safe-area insets, touch targets, no iOS zoom).
76
243
 
77
244
  **Auth (two modes via `AUTH_MODE`):** **public** (the hosted product) is first-party username/password signup with an opaque session cookie and mandatory per-user BYOK: each user brings their own AI Gateway, the worker holds no gateway secrets, and inference bills the user, never the host. **access** (the default, for private self-host) puts Cloudflare Access on the worker URL and scopes per-user history and R2 ownership via `Cf-Access-Authenticated-User-Email` (free up to 50 seats on Zero Trust). See [Running the public service](#running-the-public-service).
78
245
 
@@ -362,9 +529,11 @@ The worker is the only public surface. R2 is private; the worker streams objects
362
529
  | GET/WS | `/api/stt/stream` | WebSocket for conversational STT (Deepgram Flux via the `SttSession` DO); persists the transcript to history on close |
363
530
  | POST | `/api/tts` | Synthesize text to speech (Aura-2) and stream the audio back (no history row); used by the voice-chat loop |
364
531
  | GET | `/api/conversations` | List the caller's conversations (grouped by `conversation_id`, includes each conversation's `project_id`) |
365
- | GET | `/api/conversations/:id` | Full transcript for a conversation |
366
- | DELETE | `/api/conversations/:id` | Cascade delete of all turns plus R2 artifacts |
532
+ | GET | `/api/conversations/:id` | Full transcript for a conversation; includes `compact` state when set (v0.175.7) |
533
+ | DELETE | `/api/conversations/:id` | Cascade delete of all turns plus R2 artifacts (and compact state) |
367
534
  | PATCH | `/api/conversations/:id/project` | Move a conversation to a project, or clear it (`{project_id: number \| null}`) |
535
+ | POST | `/api/conversations/:id/compact` | Summarize older turns for model context (`{ keep_recent?, model? }`; v0.175.7) |
536
+ | DELETE | `/api/conversations/:id/compact` | Clear compact summary; next turn uses full raw history (v0.175.7) |
368
537
  | GET | `/api/history/:id` | One chat row with full attachment + output references |
369
538
  | DELETE | `/api/history/:id` | Delete a single chat row and clean up its R2 objects |
370
539
  | GET | `/api/job/:id` | Poll an async video / music generation job's status |
@@ -792,7 +961,6 @@ If your use case is the legal-research pattern (citation accuracy matters, sourc
792
961
 
793
962
  ## Streaming
794
963
 
795
- `POST /api/chat/stream` accepts the same request body as `POST /api/chat` and returns `text/event-stream`. Available for any chat model flagged `streaming: true` in the catalog (almost all chat models; LLaVA 1.5 is the usual single-shot exception). Providers include Workers AI, Anthropic, xAI, OpenAI (Chat Completions and Responses), Google Gemini, and Moonshot.
796
964
 
797
965
  Wire format:
798
966
 
@@ -827,7 +995,6 @@ Note: AI Gateway does not surface `cf-aig-log-id` on proxied SSE responses, so s
827
995
  - `capabilities`: array. Currently only `"vision"` is recognized; applies to chat models only.
828
996
  - `provider` (optional): `"workers-ai"` (default) | `"anthropic"` | `"xai"` | `"openai"` | `"google"` | `"moonshotai"` | `"bytedance"` | `"minimax"` | `"runwayml"` | `"alibaba"` | `"pixverse"` | `"vidu"` | `"recraft"` (Unified Billing). Drives the call dispatch.
829
997
  - `api` (optional, OpenAI chat only): `"responses"` for Responses API models (v0.173.0); omit for Chat Completions.
830
- - `streaming` (optional, chat only): when `true`, the model is eligible for `POST /api/chat/stream`. Nearly all chat models; LLaVA 1.5 is the usual non-stream exception.
831
998
 
832
999
  Full Workers AI catalog: https://developers.cloudflare.com/workers-ai/models/. Skip anything tagged "Planned deprecation."
833
1000
 
@@ -0,0 +1,24 @@
1
+ -- Conversation compact state (v0.175.7 / prism compact ability).
2
+ --
3
+ -- Multi-turn chat currently resends every prior turn text into the model
4
+ -- context. A long thread blows the window. Compact stores a model-written
5
+ -- summary of older turns; the next chat turn injects that summary and only
6
+ -- the recent raw turns. The full transcript in chats stays intact for the UI.
7
+ --
8
+ -- through_turn_index is inclusive: turns with turn_index <= through_turn_index
9
+ -- are covered by summary and are NOT re-sent as raw user/assistant pairs.
10
+ -- keep_recent is recorded for display; the authoritative cut is through_turn_index.
11
+
12
+ CREATE TABLE IF NOT EXISTS conversation_compact (
13
+ conversation_id TEXT NOT NULL,
14
+ user_email TEXT NOT NULL,
15
+ summary TEXT NOT NULL,
16
+ through_turn_index INTEGER NOT NULL,
17
+ keep_recent INTEGER NOT NULL DEFAULT 2,
18
+ model TEXT NOT NULL,
19
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
20
+ PRIMARY KEY (conversation_id, user_email)
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS idx_conversation_compact_user
24
+ ON conversation_compact(user_email);
@@ -21,7 +21,7 @@
21
21
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
22
22
  },
23
23
  "devDependencies": {
24
- "@cloudflare/vitest-pool-workers": "^0.19.1",
24
+ "@cloudflare/vitest-pool-workers": "^0.20.1",
25
25
  "@cloudflare/workers-types": "^5.20260804.1",
26
26
  "@types/node": "^26.1.2",
27
27
  "@vitest/coverage-v8": "^4.1.10",
@@ -192,6 +192,9 @@ const userInput = $("#user-input");
192
192
  const runBtn = $("#run");
193
193
  const transcriptEl = $("#transcript");
194
194
  const convTitleEl = $("#conv-title");
195
+ const convCompactBadge = $("#conv-compact-badge");
196
+ const convCompactBtn = $("#conv-compact-btn");
197
+ const convUncompactBtn = $("#conv-uncompact-btn");
195
198
  const outputMeta = $("#output-meta");
196
199
  const historyList = $("#history-list");
197
200
  const accountEmail = $("#account-email");
@@ -260,6 +263,8 @@ const state = {
260
263
  gateway: null,
261
264
  currentConversationId: null,
262
265
  currentTurns: [],
266
+ /** Compact summary for model context (v0.175.7); null when expanded. */
267
+ currentCompact: null,
263
268
  modelsById: {},
264
269
  pendingAttachments: [],
265
270
  pollTimer: null,
@@ -629,7 +634,7 @@ async function handleFiles(files) {
629
634
  // STT and FLUX-2 despite the affordance UI being shown.
630
635
  const isFlux2 = m.id.startsWith("@cf/black-forest-labs/flux-2-");
631
636
  // v0.21.10: image-input (i2v) models accept a source image too. Without this,
632
- // the early guard dropped the file before the per-file branch ran — which
637
+ // the early guard dropped the file before the per-file branch ran -- which
633
638
  // killed BOTH the picker and drag/drop for i2v (the v0.21.9 fix patched
634
639
  // downstream of this return and never reached).
635
640
  const isImageInput = (m.capabilities || []).includes("image-input");
@@ -1157,9 +1162,10 @@ async function loadConversations() {
1157
1162
 
1158
1163
  async function loadConversation(id) {
1159
1164
  stopPolling();
1160
- const { turns } = await api(`/api/conversations/${encodeURIComponent(id)}`);
1165
+ const data = await api(`/api/conversations/${encodeURIComponent(id)}`);
1161
1166
  state.currentConversationId = id;
1162
- state.currentTurns = turns || [];
1167
+ state.currentTurns = data.turns || [];
1168
+ state.currentCompact = data.compact || null;
1163
1169
 
1164
1170
  // Set the model picker to the most-recent turn's model so the user can
1165
1171
  // continue with the same model by default (they can switch before submitting).
@@ -1175,6 +1181,7 @@ async function loadConversation(id) {
1175
1181
 
1176
1182
  renderTranscript(state.currentTurns);
1177
1183
  updateConvTitle();
1184
+ updateCompactControls();
1178
1185
 
1179
1186
  // If the latest turn is still pending (async video/music job), resume polling.
1180
1187
  const last = state.currentTurns[state.currentTurns.length - 1];
@@ -1193,6 +1200,7 @@ function newChat() {
1193
1200
  stopPolling();
1194
1201
  state.currentConversationId = null;
1195
1202
  state.currentTurns = [];
1203
+ state.currentCompact = null;
1196
1204
  userInput.value = "";
1197
1205
  autoGrowUserInput();
1198
1206
  state.pendingAttachments = [];
@@ -1200,6 +1208,7 @@ function newChat() {
1200
1208
  renderTranscript([]);
1201
1209
  outputMeta.textContent = "";
1202
1210
  updateConvTitle();
1211
+ updateCompactControls();
1203
1212
  userInput.focus();
1204
1213
  }
1205
1214
 
@@ -1214,6 +1223,78 @@ function updateConvTitle() {
1214
1223
  }
1215
1224
  }
1216
1225
 
1226
+ /** Show compact/expand controls when the open conversation has enough chat turns. */
1227
+ function updateCompactControls() {
1228
+ if (!convCompactBtn || !convUncompactBtn || !convCompactBadge) return;
1229
+ const chatTurns = (state.currentTurns || []).filter(
1230
+ (t) => t.model_type === "chat" && t.status === "done" && t.user_input && t.output,
1231
+ );
1232
+ const hasConv = !!state.currentConversationId && chatTurns.length > 0;
1233
+ const compacted = !!state.currentCompact;
1234
+ // Need keep_recent(2) + at least one turn to summarize.
1235
+ const canCompact = hasConv && chatTurns.length >= 3;
1236
+
1237
+ convCompactBadge.hidden = !compacted;
1238
+ convCompactBtn.hidden = !canCompact || compacted;
1239
+ convUncompactBtn.hidden = !compacted;
1240
+ convCompactBtn.disabled = false;
1241
+ convUncompactBtn.disabled = false;
1242
+ }
1243
+
1244
+ async function compactCurrentConversation() {
1245
+ if (!state.currentConversationId) return;
1246
+ convCompactBtn.disabled = true;
1247
+ convCompactBtn.textContent = "compacting…";
1248
+ try {
1249
+ const model = modelSelect.value || undefined;
1250
+ const data = await api(
1251
+ `/api/conversations/${encodeURIComponent(state.currentConversationId)}/compact`,
1252
+ {
1253
+ method: "POST",
1254
+ body: JSON.stringify({ keep_recent: 2, model }),
1255
+ },
1256
+ );
1257
+ state.currentCompact = data.compact || null;
1258
+ updateCompactControls();
1259
+ const n = data.turns_summarized ?? 0;
1260
+ const k = data.turns_kept_raw ?? 0;
1261
+ outputMeta.textContent = `compacted ${n} turn${n === 1 ? "" : "s"}; keeping ${k} recent raw`;
1262
+ } catch (err) {
1263
+ outputMeta.textContent = err?.message || "compact failed";
1264
+ } finally {
1265
+ convCompactBtn.textContent = "compact";
1266
+ updateCompactControls();
1267
+ }
1268
+ }
1269
+
1270
+ async function uncompactCurrentConversation() {
1271
+ if (!state.currentConversationId) return;
1272
+ convUncompactBtn.disabled = true;
1273
+ try {
1274
+ await api(
1275
+ `/api/conversations/${encodeURIComponent(state.currentConversationId)}/compact`,
1276
+ { method: "DELETE" },
1277
+ );
1278
+ state.currentCompact = null;
1279
+ outputMeta.textContent = "expanded — next turn uses full history";
1280
+ updateCompactControls();
1281
+ } catch (err) {
1282
+ outputMeta.textContent = err?.message || "expand failed";
1283
+ updateCompactControls();
1284
+ }
1285
+ }
1286
+
1287
+ if (convCompactBtn) {
1288
+ convCompactBtn.addEventListener("click", () => {
1289
+ compactCurrentConversation();
1290
+ });
1291
+ }
1292
+ if (convUncompactBtn) {
1293
+ convUncompactBtn.addEventListener("click", () => {
1294
+ uncompactCurrentConversation();
1295
+ });
1296
+ }
1297
+
1217
1298
  // ---------- Transcript rendering ----------
1218
1299
 
1219
1300
  function renderTranscript(turns) {
@@ -201,6 +201,9 @@
201
201
  <main class="conversation">
202
202
  <header class="conv-head">
203
203
  <span id="conv-title">new conversation</span>
204
+ <span id="conv-compact-badge" class="conv-compact-badge" hidden title="Older turns are summarized for the model; full transcript still shown below">compacted</span>
205
+ <button id="conv-compact-btn" type="button" class="conv-compact-btn" hidden title="Summarize older turns so the model uses less context">compact</button>
206
+ <button id="conv-uncompact-btn" type="button" class="conv-compact-btn conv-uncompact-btn" hidden title="Clear summary; next turn resends full history">expand</button>
204
207
  <span id="output-meta"></span>
205
208
  </header>
206
209
  <div id="transcript" class="transcript"></div>
@@ -1693,10 +1693,24 @@ body::before {
1693
1693
  .conversation { flex: 1 1 auto; overflow-y: auto; min-height: 0; }
1694
1694
  .conv-head {
1695
1695
  max-width: 820px; margin: 0 auto; padding: 1rem 1.25rem 0;
1696
- display: flex; align-items: baseline; gap: 0.75rem; color: var(--fg-dim);
1696
+ display: flex; align-items: center; flex-wrap: wrap; gap: 0.5rem 0.75rem; color: var(--fg-dim);
1697
1697
  }
1698
1698
  #conv-title { font-size: 0.9rem; font-weight: 600; color: var(--fg); }
1699
- #output-meta { font-size: 0.75rem; }
1699
+ .conv-compact-badge {
1700
+ font-size: 0.65rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;
1701
+ padding: 0.15rem 0.45rem; border-radius: 999px;
1702
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
1703
+ color: var(--accent); border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
1704
+ }
1705
+ .conv-compact-btn {
1706
+ font-size: 0.72rem; font-weight: 500; padding: 0.2rem 0.55rem;
1707
+ border-radius: 999px; border: 1px solid var(--border); background: var(--bg-elev);
1708
+ color: var(--fg-dim); cursor: pointer;
1709
+ }
1710
+ .conv-compact-btn:hover { border-color: var(--accent); color: var(--fg); }
1711
+ .conv-compact-btn:disabled { opacity: 0.5; cursor: wait; }
1712
+ .conv-uncompact-btn { border-style: dashed; }
1713
+ #output-meta { font-size: 0.75rem; margin-left: auto; }
1700
1714
  .transcript { max-width: 820px; margin: 0 auto; padding: 0.75rem 1.25rem 1.5rem; }
1701
1715
 
1702
1716
  /* floating composer */
@@ -50,6 +50,23 @@ CREATE TABLE IF NOT EXISTS chats (
50
50
  CREATE INDEX IF NOT EXISTS idx_chats_conversation
51
51
  ON chats(conversation_id, turn_index);
52
52
 
53
+ -- Compact state for multi-turn context (v0.175.7). Full transcript stays in
54
+ -- chats; this row holds a summary of older turns so the model path does not
55
+ -- re-send them. See src/conversation-context.ts.
56
+ CREATE TABLE IF NOT EXISTS conversation_compact (
57
+ conversation_id TEXT NOT NULL,
58
+ user_email TEXT NOT NULL,
59
+ summary TEXT NOT NULL,
60
+ through_turn_index INTEGER NOT NULL,
61
+ keep_recent INTEGER NOT NULL DEFAULT 2,
62
+ model TEXT NOT NULL,
63
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
64
+ PRIMARY KEY (conversation_id, user_email)
65
+ );
66
+
67
+ CREATE INDEX IF NOT EXISTS idx_conversation_compact_user
68
+ ON conversation_compact(user_email);
69
+
53
70
  CREATE INDEX IF NOT EXISTS idx_chats_user_created
54
71
  ON chats(user_email, created_at DESC);
55
72
 
@@ -0,0 +1,126 @@
1
+ // Conversation context for multi-turn chat: prior turns + optional compact
2
+ // summary (v0.175.7). Pure helpers live here so chat routes and the compact
3
+ // endpoint share one assembly rule, and so unit tests cover it without D1.
4
+
5
+ export const DEFAULT_KEEP_RECENT = 2;
6
+ /** Soft cap on stored / injected summary text (chars). */
7
+ export const COMPACT_SUMMARY_MAX_CHARS = 12_000;
8
+ /** Minimum completed chat turns before compact is useful (keep_recent + 1). */
9
+ export const MIN_TURNS_TO_COMPACT = DEFAULT_KEEP_RECENT + 1;
10
+
11
+ export type ChatTurnRow = {
12
+ user_input: string;
13
+ output: string;
14
+ turn_index: number;
15
+ };
16
+
17
+ export type ConversationCompactState = {
18
+ summary: string;
19
+ through_turn_index: number;
20
+ keep_recent: number;
21
+ model: string;
22
+ updated_at: string;
23
+ };
24
+
25
+ export type PriorContext = {
26
+ /** Raw user/assistant pairs to put on the wire after any compact block. */
27
+ priorTurns: Array<{ user_input: string; output: string }>;
28
+ /** Next turn_index for persistChat. */
29
+ turnIndex: number;
30
+ /** System-prompt block for compacted earlier turns, or null. */
31
+ compactBlock: string | null;
32
+ compact: ConversationCompactState | null;
33
+ };
34
+
35
+ /** Split turns into those summarized vs kept raw. */
36
+ export function splitTurnsForCompact(
37
+ turns: ChatTurnRow[],
38
+ keepRecent: number,
39
+ ): { summarize: ChatTurnRow[]; keep: ChatTurnRow[] } {
40
+ const k = Math.max(0, Math.floor(keepRecent));
41
+ if (turns.length === 0) return { summarize: [], keep: [] };
42
+ if (k === 0) return { summarize: turns.slice(), keep: [] };
43
+ if (turns.length <= k) return { summarize: [], keep: turns.slice() };
44
+ return {
45
+ summarize: turns.slice(0, turns.length - k),
46
+ keep: turns.slice(turns.length - k),
47
+ };
48
+ }
49
+
50
+ /** Flatten turns into a plain transcript the summarizer model can read. */
51
+ export function formatTurnsForSummary(turns: ChatTurnRow[]): string {
52
+ const parts: string[] = [];
53
+ for (const t of turns) {
54
+ const u = (t.user_input ?? "").trim();
55
+ const a = (t.output ?? "").trim();
56
+ if (!u && !a) continue;
57
+ parts.push(`User:\n${u || "(empty)"}\n\nAssistant:\n${a || "(empty)"}`);
58
+ }
59
+ return parts.join("\n\n---\n\n");
60
+ }
61
+
62
+ /** System-prompt block injected when a conversation is compacted. */
63
+ export function buildCompactSystemBlock(summary: string): string {
64
+ const s = summary.trim();
65
+ if (!s) return "";
66
+ return (
67
+ "[Compacted earlier conversation]\n" +
68
+ "The following is a summary of earlier turns in this thread. Treat it as " +
69
+ "authoritative context. Recent turns (if any) follow as normal messages.\n\n" +
70
+ s +
71
+ "\n\n[End compacted context]"
72
+ );
73
+ }
74
+
75
+ /**
76
+ * Apply compact state to a full ordered turn list.
77
+ * - priorTurns: only turns AFTER through_turn_index (raw recent context)
78
+ * - compactBlock: summary system block when state is present
79
+ * - turnIndex: max(turn_index)+1 or 0
80
+ */
81
+ export function applyCompactToPriorTurns(
82
+ allTurns: ChatTurnRow[],
83
+ state: ConversationCompactState | null,
84
+ ): PriorContext {
85
+ const usable = allTurns.filter((t) => t.user_input && t.output);
86
+ // Next index must clear every stored turn_index, including empty/failed rows
87
+ // that were filtered out of the wire history.
88
+ const turnIndex = allTurns.length
89
+ ? Math.max(...allTurns.map((t) => t.turn_index)) + 1
90
+ : 0;
91
+
92
+ if (!state?.summary?.trim()) {
93
+ return {
94
+ priorTurns: usable.map((t) => ({ user_input: t.user_input, output: t.output })),
95
+ turnIndex,
96
+ compactBlock: null,
97
+ compact: null,
98
+ };
99
+ }
100
+
101
+ const through = state.through_turn_index;
102
+ const recent = usable.filter((t) => t.turn_index > through);
103
+ const block = buildCompactSystemBlock(state.summary);
104
+ return {
105
+ priorTurns: recent.map((t) => ({ user_input: t.user_input, output: t.output })),
106
+ turnIndex,
107
+ compactBlock: block || null,
108
+ compact: state,
109
+ };
110
+ }
111
+
112
+ /** Clamp and normalize a model-produced summary for storage / injection. */
113
+ export function normalizeSummary(raw: string): string {
114
+ let s = (raw ?? "").trim();
115
+ if (s.length > COMPACT_SUMMARY_MAX_CHARS) {
116
+ s = s.slice(0, COMPACT_SUMMARY_MAX_CHARS) + "\n[summary truncated]";
117
+ }
118
+ return s;
119
+ }
120
+
121
+ export const COMPACT_SYSTEM_PROMPT =
122
+ "You compress multi-turn chat history into a continuity brief for another " +
123
+ "assistant that will continue the conversation. Preserve: decisions, facts, " +
124
+ "names, constraints, open questions, and anything the user asked to remember. " +
125
+ "Drop chit-chat and repeated boilerplate. Write in neutral third person or " +
126
+ "tight bullet form. No preamble like 'Here is a summary'.";
@@ -41,6 +41,8 @@ import {
41
41
  handleConversationGet,
42
42
  handleConversationDelete,
43
43
  handleConversationMoveToProject,
44
+ handleConversationCompact,
45
+ handleConversationCompactClear,
44
46
  } from "./routes/conversations";
45
47
  import {
46
48
  handleDocumentList,
@@ -233,6 +235,12 @@ export default {
233
235
  if (cp && request.method === "PATCH") {
234
236
  return handleConversationMoveToProject(request, env, cp[1]);
235
237
  }
238
+ // v0.175.7: compact older turns into a summary for model context.
239
+ const cc = url.pathname.match(/^\/api\/conversations\/([A-Za-z0-9_:-]+)\/compact$/);
240
+ if (cc) {
241
+ if (request.method === "POST") return handleConversationCompact(request, env, cc[1]);
242
+ if (request.method === "DELETE") return handleConversationCompactClear(request, env, cc[1]);
243
+ }
236
244
 
237
245
  const h = url.pathname.match(/^\/api\/history\/(\d+)$/);
238
246
  if (h) {
@@ -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
 
@@ -1260,25 +1245,15 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1260
1245
  const { resolvedSystemPrompt, scopedProjectId } = await resolveProjectForChat(env, userEmail, body);
1261
1246
  body.system_prompt = resolvedSystemPrompt;
1262
1247
 
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.
1248
+ // Hot-path parallelization (mirrors runChat v0.12.1). Kick off prior
1249
+ // context (turns + compact) + RAG before the attachment walk.
1265
1250
  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: [] });
1251
+ const priorContextPromise = conversationIdIn
1252
+ ? Promise.all([
1253
+ loadChatTurns(env, conversationIdIn, userEmail),
1254
+ loadCompactState(env, conversationIdIn, userEmail),
1255
+ ]).then(([turns, compact]) => applyCompactToPriorTurns(turns, compact))
1256
+ : Promise.resolve(applyCompactToPriorTurns([], null));
1282
1257
 
1283
1258
  const retrievePromise: Promise<{ chunks: RetrievedChunk[]; error: string | null }> =
1284
1259
  body.use_docs
@@ -1370,19 +1345,17 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1370
1345
  ? [{ type: "text", text: userText }, ...imageDataUrls.map((url) => ({ type: "image_url", image_url: { url } }))]
1371
1346
  : userText;
1372
1347
 
1373
- // Consume the parallel-hoisted promises.
1348
+ // Consume the parallel-hoisted promises (turns + compact + retrieval).
1374
1349
  let conversationId = conversationIdIn;
1375
1350
  let turnIndex = 0;
1376
- const priorTurns: Array<{ user_input: string; output: string }> = [];
1351
+ let priorTurns: Array<{ user_input: string; output: string }> = [];
1352
+ let compactBlock: string | null = null;
1377
1353
 
1378
1354
  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;
1355
+ const prior = await priorContextPromise;
1356
+ priorTurns = prior.priorTurns;
1357
+ turnIndex = prior.turnIndex;
1358
+ compactBlock = prior.compactBlock;
1386
1359
  } else {
1387
1360
  conversationId = crypto.randomUUID();
1388
1361
  }
@@ -1394,7 +1367,7 @@ export async function runChatStream(request: Request, env: Env, model: ModelEntr
1394
1367
  const userSystemPrompt = body.system_prompt?.trim() ?? "";
1395
1368
  const retrievalBlock = retrievedChunks.length ? formatRetrievalForSystemPrompt(retrievedChunks) : "";
1396
1369
  const webBlock = webResults.length ? formatWebForSystemPrompt(webResults) : "";
1397
- const effectiveSystemPrompt = [userSystemPrompt, retrievalBlock, webBlock]
1370
+ const effectiveSystemPrompt = [userSystemPrompt, compactBlock, retrievalBlock, webBlock]
1398
1371
  .filter(Boolean)
1399
1372
  .join("\n\n");
1400
1373
 
@@ -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
@@ -7,7 +7,7 @@
7
7
  // - opens the upstream flux socket (env.AI.run({websocket:true})) and bridges
8
8
  // audio up / Deepgram events down,
9
9
  // - accumulates each committed turn into DO SQLite (hibernation-safe; the
10
- // in-memory upstream socket is NOT — outbound sockets do not hibernate, so
10
+ // in-memory upstream socket is NOT -- outbound sockets do not hibernate, so
11
11
  // we lean on the fact that an active STT session streams audio continuously
12
12
  // and never goes idle long enough to hibernate, with a guard if it does),
13
13
  // - on close, concatenates the turns and writes one chats row (model_type
@@ -0,0 +1,103 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ applyCompactToPriorTurns,
4
+ buildCompactSystemBlock,
5
+ formatTurnsForSummary,
6
+ normalizeSummary,
7
+ splitTurnsForCompact,
8
+ COMPACT_SUMMARY_MAX_CHARS,
9
+ DEFAULT_KEEP_RECENT,
10
+ } from "../src/conversation-context";
11
+
12
+ const turns = [
13
+ { user_input: "hi", output: "hello", turn_index: 0 },
14
+ { user_input: "what is 2+2", output: "4", turn_index: 1 },
15
+ { user_input: "and 3+3", output: "6", turn_index: 2 },
16
+ { user_input: "thanks", output: "anytime", turn_index: 3 },
17
+ ];
18
+
19
+ describe("splitTurnsForCompact", () => {
20
+ it("keeps the last N raw and summarizes the rest", () => {
21
+ const { summarize, keep } = splitTurnsForCompact(turns, 2);
22
+ expect(summarize.map((t) => t.turn_index)).toEqual([0, 1]);
23
+ expect(keep.map((t) => t.turn_index)).toEqual([2, 3]);
24
+ });
25
+
26
+ it("summarizes nothing when keep_recent covers the whole thread", () => {
27
+ const { summarize, keep } = splitTurnsForCompact(turns, 10);
28
+ expect(summarize).toEqual([]);
29
+ expect(keep).toHaveLength(4);
30
+ });
31
+
32
+ it("default keep matches DEFAULT_KEEP_RECENT (2)", () => {
33
+ expect(DEFAULT_KEEP_RECENT).toBe(2);
34
+ const { keep } = splitTurnsForCompact(turns, DEFAULT_KEEP_RECENT);
35
+ expect(keep).toHaveLength(2);
36
+ });
37
+ });
38
+
39
+ describe("formatTurnsForSummary", () => {
40
+ it("labels user and assistant and separates turns", () => {
41
+ const text = formatTurnsForSummary(turns.slice(0, 2));
42
+ expect(text).toContain("User:\nhi");
43
+ expect(text).toContain("Assistant:\nhello");
44
+ expect(text).toContain("---");
45
+ expect(text).toContain("what is 2+2");
46
+ });
47
+ });
48
+
49
+ describe("buildCompactSystemBlock", () => {
50
+ it("wraps the summary with markers the model can anchor on", () => {
51
+ const block = buildCompactSystemBlock("User prefers brief answers.");
52
+ expect(block).toMatch(/\[Compacted earlier conversation\]/);
53
+ expect(block).toContain("User prefers brief answers.");
54
+ expect(block).toMatch(/\[End compacted context\]/);
55
+ });
56
+
57
+ it("returns empty for blank summary", () => {
58
+ expect(buildCompactSystemBlock(" ")).toBe("");
59
+ });
60
+ });
61
+
62
+ describe("applyCompactToPriorTurns", () => {
63
+ it("without compact state returns all usable turns", () => {
64
+ const ctx = applyCompactToPriorTurns(turns, null);
65
+ expect(ctx.priorTurns).toHaveLength(4);
66
+ expect(ctx.compactBlock).toBeNull();
67
+ expect(ctx.turnIndex).toBe(4);
68
+ });
69
+
70
+ it("with compact state drops covered turns and injects the block", () => {
71
+ const ctx = applyCompactToPriorTurns(turns, {
72
+ summary: "Discussed arithmetic; answers were short.",
73
+ through_turn_index: 1,
74
+ keep_recent: 2,
75
+ model: "@cf/meta/llama-3.2-3b-instruct",
76
+ updated_at: "2026-08-06T00:00:00Z",
77
+ });
78
+ expect(ctx.priorTurns.map((t) => t.user_input)).toEqual(["and 3+3", "thanks"]);
79
+ expect(ctx.compactBlock).toContain("Discussed arithmetic");
80
+ expect(ctx.turnIndex).toBe(4);
81
+ });
82
+
83
+ it("skips empty/failed turns when building prior pairs", () => {
84
+ const mixed = [
85
+ ...turns,
86
+ { user_input: "oops", output: "", turn_index: 4 },
87
+ ];
88
+ const ctx = applyCompactToPriorTurns(mixed, null);
89
+ expect(ctx.priorTurns).toHaveLength(4);
90
+ // Next index still advances past the empty row's index.
91
+ expect(ctx.turnIndex).toBe(5);
92
+ });
93
+ });
94
+
95
+ describe("normalizeSummary", () => {
96
+ it("trims and truncates oversized summaries", () => {
97
+ expect(normalizeSummary(" short ")).toBe("short");
98
+ const long = "x".repeat(COMPACT_SUMMARY_MAX_CHARS + 50);
99
+ const out = normalizeSummary(long);
100
+ expect(out.length).toBeLessThanOrEqual(COMPACT_SUMMARY_MAX_CHARS + 30);
101
+ expect(out).toContain("[summary truncated]");
102
+ });
103
+ });