@skyphusion/create-prism 0.1.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.
Files changed (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,60 @@
1
+ // OpenAI SSE interpreter (v0.21.0).
2
+ //
3
+ // OpenAI chat models are proxied through Cloudflare Unified Billing via
4
+ // env.AI.run("openai/<model>", { messages, stream: true }). Empirically the
5
+ // binding can hand back one of two known frame shapes for a streamed proxied
6
+ // model, and which one is not contractually documented:
7
+ //
8
+ // 1. OpenAI-native delta (same wire format as xAI):
9
+ // { "choices": [{ "delta": { "content": "..." } }], "usage"?: {...} }
10
+ // 2. CF-normalized flat (same shape Workers AI hosted models emit):
11
+ // { "response": "...", "usage"?: {...} }
12
+ //
13
+ // Rather than guess which one the proxy uses (and ship a parser that silently
14
+ // yields empty output if the guess is wrong), this interpreter handles BOTH.
15
+ // The two shapes don't collide: an OpenAI-native frame has no `response` key,
16
+ // a flat frame has no `choices`, so checking each independently is safe. If a
17
+ // future third shape appears, add a branch here with a fixture test.
18
+ //
19
+ // `data: [DONE]` is dropped by the SSE framer before frames reach here. Empty
20
+ // content/response strings (normal on the trailing usage frame) are dropped.
21
+ // Usage naming is accepted in both OpenAI (prompt_tokens/completion_tokens)
22
+ // and Anthropic-derived (input_tokens/output_tokens) forms for safety.
23
+
24
+ import type { ProviderStreamEvent } from "./types";
25
+
26
+ export function interpretOpenAISSEFrame(data: unknown): ProviderStreamEvent[] {
27
+ const events: ProviderStreamEvent[] = [];
28
+ if (!data || typeof data !== "object") return events;
29
+ const d = data as {
30
+ choices?: Array<{ delta?: { content?: string } }>;
31
+ response?: unknown;
32
+ usage?: {
33
+ prompt_tokens?: number;
34
+ completion_tokens?: number;
35
+ input_tokens?: number;
36
+ output_tokens?: number;
37
+ };
38
+ };
39
+
40
+ // Shape 1: OpenAI-native delta.
41
+ const delta = d.choices?.[0]?.delta?.content;
42
+ if (typeof delta === "string" && delta.length > 0) {
43
+ events.push({ type: "text", text: delta });
44
+ }
45
+
46
+ // Shape 2: CF-normalized flat `response`.
47
+ if (typeof d.response === "string" && d.response.length > 0) {
48
+ events.push({ type: "text", text: d.response });
49
+ }
50
+
51
+ if (d.usage) {
52
+ events.push({
53
+ type: "usage",
54
+ in_: d.usage.prompt_tokens ?? d.usage.input_tokens ?? null,
55
+ out_: d.usage.completion_tokens ?? d.usage.output_tokens ?? null,
56
+ });
57
+ }
58
+
59
+ return events;
60
+ }
@@ -0,0 +1,39 @@
1
+ // Shared SSE framer (v0.18.1).
2
+ //
3
+ // Extracted from callXaiStream, callWorkersAIStream, and callAnthropicStream
4
+ // in src/index.ts. All three providers emit OpenAI/Anthropic-compatible SSE
5
+ // where event boundaries are blank-line-delimited (`\n\n`) and the payload
6
+ // we care about lives on `data:` lines; per-provider event-type semantics
7
+ // live in their respective interpreters (xai-sse.ts, workers-ai-sse.ts,
8
+ // anthropic-sse.ts).
9
+ //
10
+ // Behavior preserved from the inline implementations:
11
+ // - Multi-line `data:` fields use "last line wins" rather than concat
12
+ // (none of our three providers emit multi-line data fields; spec-correct
13
+ // SSE would concat with newlines, but we match the pre-extraction
14
+ // behavior exactly).
15
+ // - Both `"data: "` (with space) and `"data:"` (compact) prefixes work.
16
+ // - `[DONE]` sentinel is dropped.
17
+ // - Blank or whitespace-only events are dropped.
18
+ // - `event:`, `id:`, `retry:` lines are ignored; the parser only reads `data:`.
19
+
20
+ export function extractSSEDataPayloads(
21
+ buffer: string,
22
+ ): { payloads: string[]; remainder: string } {
23
+ const payloads: string[] = [];
24
+ const parts = buffer.split("\n\n");
25
+ const remainder = parts.pop() ?? "";
26
+
27
+ for (const part of parts) {
28
+ if (!part.trim()) continue;
29
+ let payload = "";
30
+ for (const line of part.split("\n")) {
31
+ if (line.startsWith("data: ")) payload = line.slice(6);
32
+ else if (line.startsWith("data:")) payload = line.slice(5);
33
+ }
34
+ if (!payload || payload === "[DONE]") continue;
35
+ payloads.push(payload);
36
+ }
37
+
38
+ return { payloads, remainder };
39
+ }
@@ -0,0 +1,16 @@
1
+ // Shared types for streaming-response parsers (v0.18.0).
2
+ //
3
+ // ProviderStreamEvent is the normalized envelope every provider's streaming
4
+ // parser yields. The worker layers above (callXaiStream, callAnthropicStream,
5
+ // callGeminiStream, callOpenAIStream, callWorkersAIStream, plus runChatStream
6
+ // that consumes them) are all written against this shape, so each provider's
7
+ // specific wire format (OpenAI-style SSE, Anthropic named-event SSE) gets
8
+ // translated to this common type at the parser boundary.
9
+ //
10
+ // Adding a new field here is a breaking change for the v0.13.0 envelope
11
+ // contract in /api/chat/stream; the worker has to forward whatever lands here
12
+ // and frontends would need to handle it.
13
+
14
+ export type ProviderStreamEvent =
15
+ | { type: "text"; text: string }
16
+ | { type: "usage"; in_: number | null; out_: number | null };
@@ -0,0 +1,43 @@
1
+ // Workers AI SSE interpreter (v0.18.1).
2
+ //
3
+ // Workers AI's streaming format uses a flat `response` field per chunk rather
4
+ // than OpenAI's nested choices/delta/content. Empty-string `response` is
5
+ // normal on the final chunk (which carries usage) and is dropped.
6
+ //
7
+ // Usage naming varies by underlying model wrapper: some Workers AI adapters
8
+ // (especially OpenAI-derived ones like gpt-oss-120b/20b) emit OpenAI naming
9
+ // `prompt_tokens`/`completion_tokens`; others (Anthropic-derived adapters)
10
+ // emit `input_tokens`/`output_tokens`. We accept both and prefer the OpenAI
11
+ // names when both are present.
12
+ //
13
+ // Reasoning models (gpt-oss-120b, qwq-32b, deepseek-r1-distill-qwen-32b)
14
+ // emit `<think>...</think>` blocks inside `response`. The interpreter passes
15
+ // them through unchanged; the UI is responsible for folding them if desired.
16
+
17
+ import type { ProviderStreamEvent } from "./types";
18
+
19
+ export function interpretWorkersAISSEFrame(data: unknown): ProviderStreamEvent[] {
20
+ const events: ProviderStreamEvent[] = [];
21
+ const d = data as Record<string, unknown>;
22
+
23
+ const resp = d.response;
24
+ if (typeof resp === "string" && resp.length > 0) {
25
+ events.push({ type: "text", text: resp });
26
+ }
27
+
28
+ const usage = d.usage as {
29
+ prompt_tokens?: number;
30
+ completion_tokens?: number;
31
+ input_tokens?: number;
32
+ output_tokens?: number;
33
+ } | undefined;
34
+ if (usage) {
35
+ events.push({
36
+ type: "usage",
37
+ in_: usage.prompt_tokens ?? usage.input_tokens ?? null,
38
+ out_: usage.completion_tokens ?? usage.output_tokens ?? null,
39
+ });
40
+ }
41
+
42
+ return events;
43
+ }
@@ -0,0 +1,40 @@
1
+ // xAI SSE interpreter (v0.18.1).
2
+ //
3
+ // xAI's streaming API is OpenAI-compatible: each `data:` frame contains
4
+ // JSON of the shape:
5
+ // {
6
+ // "id": "...", "object": "chat.completion.chunk", "created": N,
7
+ // "model": "grok-X", "choices": [{ "delta": { "content": "..." } }]
8
+ // }
9
+ // followed by a usage frame (when stream_options.include_usage:true):
10
+ // { ..., "usage": { "prompt_tokens": N, "completion_tokens": M, "total_tokens": K } }
11
+ // terminated by `data: [DONE]` (which the SSE framer drops before we see it).
12
+ //
13
+ // We extract text deltas from choices[0].delta.content and usage from the
14
+ // top-level usage object. Empty-string deltas are normal on the usage frame
15
+ // and are dropped.
16
+
17
+ import type { ProviderStreamEvent } from "./types";
18
+
19
+ export function interpretXaiSSEFrame(data: unknown): ProviderStreamEvent[] {
20
+ const events: ProviderStreamEvent[] = [];
21
+ const d = data as {
22
+ choices?: Array<{ delta?: { content?: string } }>;
23
+ usage?: { prompt_tokens?: number; completion_tokens?: number };
24
+ };
25
+
26
+ const text = d.choices?.[0]?.delta?.content;
27
+ if (typeof text === "string" && text.length > 0) {
28
+ events.push({ type: "text", text });
29
+ }
30
+
31
+ if (d.usage) {
32
+ events.push({
33
+ type: "usage",
34
+ in_: d.usage.prompt_tokens ?? null,
35
+ out_: d.usage.completion_tokens ?? null,
36
+ });
37
+ }
38
+
39
+ return events;
40
+ }
@@ -0,0 +1,208 @@
1
+ // Anthropic Unified Billing chat dispatch (v0.93.0).
2
+ //
3
+ // Extracted from src/index.ts. Owns the request builder, message transform,
4
+ // non-streaming caller, and streaming caller for Anthropic Messages API
5
+ // through Cloudflare AI Gateway.
6
+ //
7
+ // Auth strategy: Unified Billing (keyless). We hit the AI Gateway anthropic
8
+ // endpoint with cf-aig-authorization: Bearer <CF_AIG_TOKEN> and send NO
9
+ // provider key. Cloudflare uses its own upstream credentials and rolls the
10
+ // cost into the Cloudflare bill. An x-api-key would flip the gateway back to
11
+ // BYOK / pass-through billing, so we deliberately never set one. CF_AIG_TOKEN
12
+ // is therefore required for this provider (was BYOK via x-api-key before
13
+ // v0.93.0).
14
+ //
15
+ // The message format coming in is OpenAI-style (role + content array with
16
+ // text / image_url blocks). We transform to Anthropic's Messages API shape:
17
+ // system pulled to a top-level field, image_url blocks rewritten as image
18
+ // blocks with base64 source.
19
+
20
+ import type { AiContext } from "../ai-binding";
21
+ import type { ModelEntry } from "../models";
22
+ import type { ProviderStreamEvent } from "../parsers/types";
23
+ import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
24
+ import { parseDataUrl } from "../utils";
25
+ import { extractSSEDataPayloads } from "../parsers/sse-framer";
26
+ import { interpretAnthropicSSEFrame } from "../parsers/anthropic-sse";
27
+
28
+ interface AnthropicMessage {
29
+ role: "user" | "assistant";
30
+ content: Array<unknown>;
31
+ }
32
+
33
+ function transformToAnthropic(
34
+ messages: Array<unknown>,
35
+ systemPromptOverride: string | undefined,
36
+ ): { system: string | undefined; messages: AnthropicMessage[] } {
37
+ let system: string | undefined = systemPromptOverride && systemPromptOverride.trim()
38
+ ? systemPromptOverride
39
+ : undefined;
40
+ const out: AnthropicMessage[] = [];
41
+
42
+ for (const m of messages) {
43
+ const msg = m as { role: string; content: unknown };
44
+ if (msg.role === "system") {
45
+ const text = typeof msg.content === "string" ? msg.content : "";
46
+ system = system ? `${system}\n\n${text}` : text;
47
+ continue;
48
+ }
49
+ if (msg.role !== "user" && msg.role !== "assistant") continue;
50
+
51
+ if (typeof msg.content === "string") {
52
+ out.push({ role: msg.role, content: [{ type: "text", text: msg.content }] });
53
+ continue;
54
+ }
55
+
56
+ if (!Array.isArray(msg.content)) continue;
57
+
58
+ const content: Array<unknown> = [];
59
+ for (const block of msg.content) {
60
+ const b = block as { type?: string; text?: string; image_url?: { url?: string } };
61
+ if (b.type === "text" && typeof b.text === "string") {
62
+ content.push({ type: "text", text: b.text });
63
+ } else if (b.type === "image_url" && b.image_url?.url) {
64
+ const parsed = parseDataUrl(b.image_url.url);
65
+ if (parsed) {
66
+ content.push({
67
+ type: "image",
68
+ source: { type: "base64", media_type: parsed.mime, data: parsed.base64 },
69
+ });
70
+ }
71
+ }
72
+ }
73
+ out.push({ role: msg.role, content });
74
+ }
75
+
76
+ return { system, messages: out };
77
+ }
78
+
79
+ // Shared request builder for both callAnthropic (non-streaming) and
80
+ // callAnthropicStream (eventstream). The transform, URL, auth headers, and
81
+ // body shape are identical between the two; only stream:true on the body
82
+ // and accept:text/event-stream on the headers differ, conditional on
83
+ // opts.stream. Mirrors the v0.17.2 prepareXaiRequest pattern.
84
+
85
+ async function prepareAnthropicRequest(
86
+ ctx: AiContext,
87
+ model: ModelEntry,
88
+ systemPrompt: string | undefined,
89
+ messages: Array<unknown>,
90
+ opts: { stream: boolean },
91
+ ): Promise<{ url: string; headers: Record<string, string>; body: string }> {
92
+ const { system, messages: aMessages } = transformToAnthropic(messages, systemPrompt);
93
+
94
+ const baseUrl = await (ctx.env.AI as unknown as {
95
+ gateway: (id: string) => { getUrl: (provider: string) => Promise<string> };
96
+ }).gateway(ctx.gateway.gatewayId).getUrl("anthropic");
97
+
98
+ // Strip the "anthropic/" prefix we use in our internal IDs; Anthropic's API
99
+ // expects just the model name (e.g. "claude-opus-4-6").
100
+ const modelName = model.id.replace(/^anthropic\//, "");
101
+
102
+ const bodyObj: Record<string, unknown> = {
103
+ model: modelName,
104
+ max_tokens: 4096,
105
+ messages: aMessages,
106
+ };
107
+ if (system) bodyObj.system = system;
108
+ if (opts.stream) bodyObj.stream = true;
109
+
110
+ const headers: Record<string, string> = {
111
+ "anthropic-version": "2023-06-01",
112
+ "content-type": "application/json",
113
+ };
114
+ if (opts.stream) headers["accept"] = "text/event-stream";
115
+ // Unified Billing: keyless. Never send x-api-key (that would make the
116
+ // gateway bill BYOK/pass-through); authorize with the gateway token only.
117
+ if (!ctx.gateway.cfAigToken) {
118
+ throw new Error(CF_AIG_TOKEN_REQUIRED_MSG);
119
+ }
120
+ headers["cf-aig-authorization"] = `Bearer ${ctx.gateway.cfAigToken}`;
121
+
122
+ return {
123
+ url: `${baseUrl}/v1/messages`,
124
+ headers,
125
+ body: JSON.stringify(bodyObj),
126
+ };
127
+ }
128
+
129
+ export async function callAnthropic(
130
+ ctx: AiContext,
131
+ model: ModelEntry,
132
+ systemPrompt: string | undefined,
133
+ messages: Array<unknown>,
134
+ ): Promise<{ raw: unknown; logId: string | null }> {
135
+ const { url, headers, body } = await prepareAnthropicRequest(
136
+ ctx, model, systemPrompt, messages, { stream: false },
137
+ );
138
+
139
+ const resp = await fetch(url, { method: "POST", headers, body });
140
+
141
+ const logId = resp.headers.get("cf-aig-log-id");
142
+
143
+ if (!resp.ok) {
144
+ const errText = await resp.text();
145
+ throw new Error(`Anthropic API ${resp.status}: ${errText.slice(0, 500)}`);
146
+ }
147
+
148
+ const raw = await resp.json();
149
+ return { raw, logId };
150
+ }
151
+
152
+ export async function* callAnthropicStream(
153
+ ctx: AiContext,
154
+ model: ModelEntry,
155
+ systemPrompt: string | undefined,
156
+ messages: Array<unknown>,
157
+ signal: AbortSignal,
158
+ ): AsyncGenerator<ProviderStreamEvent> {
159
+ const { url, headers, body } = await prepareAnthropicRequest(
160
+ ctx, model, systemPrompt, messages, { stream: true },
161
+ );
162
+
163
+ const resp = await fetch(url, {
164
+ method: "POST",
165
+ headers,
166
+ body,
167
+ signal,
168
+ });
169
+
170
+ if (!resp.ok) {
171
+ const errText = await resp.text();
172
+ throw new Error(`Anthropic API ${resp.status}: ${errText.slice(0, 500)}`);
173
+ }
174
+ if (!resp.body) throw new Error("Anthropic returned no stream body");
175
+
176
+ const reader = resp.body.getReader();
177
+ const decoder = new TextDecoder();
178
+ let buffer = "";
179
+
180
+ try {
181
+ while (true) {
182
+ const { done, value } = await reader.read();
183
+ if (done) break;
184
+
185
+ buffer += decoder.decode(value, { stream: true });
186
+
187
+ // SSE event boundaries are \n\n. Within an event, the fields we care
188
+ // about are `data: <json>` lines; everything else (event: name, id:,
189
+ // retry:) we ignore. Anthropic uses `event:` for the type and `data:`
190
+ // for the payload; the payload's own `type` field also carries the
191
+ // event kind, so we can rely on that alone.
192
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
193
+ buffer = remainder;
194
+
195
+ for (const payload of payloads) {
196
+ let data: unknown;
197
+ try {
198
+ data = JSON.parse(payload);
199
+ } catch {
200
+ continue;
201
+ }
202
+ for (const event of interpretAnthropicSSEFrame(data)) yield event;
203
+ }
204
+ }
205
+ } finally {
206
+ try { reader.releaseLock(); } catch { /* fine */ }
207
+ }
208
+ }
@@ -0,0 +1,150 @@
1
+ // Google Gemini chat (Unified Billing, v0.21.3).
2
+ //
3
+ // Gemini is proxied through env.AI.run but, unlike the OpenAI proxied models,
4
+ // it is NOT OpenAI-shaped. Verified against the CF model page, the binding
5
+ // passes Gemini-native format through in both directions:
6
+ //
7
+ // env.AI.run("google/gemini-3.1-pro", {
8
+ // contents: [{ role: "user", parts: [{ text: "..." }] }],
9
+ // systemInstruction: { parts: [{ text: "..." }] }, // optional
10
+ // generationConfig: { temperature: 0.3 }, // optional
11
+ // })
12
+ //
13
+ // and returns { candidates: [{ content: { parts: [{ text }] } }],
14
+ // usageMetadata: { promptTokenCount, candidatesTokenCount, ... } }.
15
+ //
16
+ // So this needs a transform from the worker's internal OpenAI-style message
17
+ // array, the same way Anthropic does. Two differences to get right:
18
+ // - Roles: Gemini uses "user" and "model" (no "assistant", no "system" turn).
19
+ // The system prompt is hoisted to systemInstruction by the caller (runChat
20
+ // keeps it out of `messages` for provider "google"), but we also defensively
21
+ // drop any stray system-role entry here.
22
+ // - Content: the internal turns carry string content on the text path. We
23
+ // coerce defensively (array content -> joined text parts) so a stray
24
+ // multimodal turn degrades to text rather than throwing. (Vision input is
25
+ // a later pass; the catalog entry is text-only for now.)
26
+ //
27
+ // Non-streaming chat via callGemini; streaming via callGeminiStream (v0.21.4),
28
+ // which mirrors callOpenAIStream (binding path + abort bridge) and uses the
29
+ // Gemini SSE interpreter plus a dual-mode delta reconciler.
30
+
31
+ import type { AiContext } from "../ai-binding";
32
+ import { aiRun, aiLogId } from "../ai-binding";
33
+ import type { ModelEntry } from "../models";
34
+ import type { ProviderStreamEvent } from "../parsers/types";
35
+ import { extractSSEDataPayloads } from "../parsers/sse-framer";
36
+ import { interpretGeminiSSEFrame, makeGeminiDeltaReconciler } from "../parsers/gemini-sse";
37
+
38
+ type InternalMessage = { role?: string; content?: unknown };
39
+
40
+ function textFromContent(content: unknown): string {
41
+ if (typeof content === "string") return content;
42
+ if (Array.isArray(content)) {
43
+ return content
44
+ .map((part) => {
45
+ const p = part as { type?: string; text?: string };
46
+ return p?.type === "text" || typeof p?.text === "string" ? p.text ?? "" : "";
47
+ })
48
+ .join("");
49
+ }
50
+ return content == null ? "" : String(content);
51
+ }
52
+
53
+ // Pure transform: internal [{role, content}] -> Gemini `contents`. Exported
54
+ // for unit testing the role mapping (assistant -> model) and system drop.
55
+ export function geminiContentsFromMessages(
56
+ messages: Array<unknown>,
57
+ ): Array<{ role: string; parts: Array<{ text: string }> }> {
58
+ const contents: Array<{ role: string; parts: Array<{ text: string }> }> = [];
59
+ for (const raw of messages) {
60
+ const m = (raw ?? {}) as InternalMessage;
61
+ if (m.role === "system") continue; // hoisted to systemInstruction
62
+ const role = m.role === "assistant" ? "model" : "user";
63
+ contents.push({ role, parts: [{ text: textFromContent(m.content) }] });
64
+ }
65
+ return contents;
66
+ }
67
+
68
+ export function prepareGeminiRequest(
69
+ systemPrompt: string | undefined,
70
+ messages: Array<unknown>,
71
+ ): Record<string, unknown> {
72
+ const body: Record<string, unknown> = {
73
+ contents: geminiContentsFromMessages(messages),
74
+ };
75
+ if (systemPrompt && systemPrompt.trim()) {
76
+ body.systemInstruction = { parts: [{ text: systemPrompt }] };
77
+ }
78
+ return body;
79
+ }
80
+
81
+ export async function callGemini(
82
+ ctx: AiContext,
83
+ model: ModelEntry,
84
+ systemPrompt: string | undefined,
85
+ messages: Array<unknown>,
86
+ ): Promise<{ raw: unknown; logId: string | null }> {
87
+ const raw = await aiRun(ctx, model.id, prepareGeminiRequest(systemPrompt, messages));
88
+ return { raw, logId: aiLogId(ctx) };
89
+ }
90
+
91
+ export async function* callGeminiStream(
92
+ ctx: AiContext,
93
+ model: ModelEntry,
94
+ systemPrompt: string | undefined,
95
+ messages: Array<unknown>,
96
+ signal: AbortSignal,
97
+ ): AsyncGenerator<ProviderStreamEvent> {
98
+ const result = await aiRun(ctx, model.id, {
99
+ ...prepareGeminiRequest(systemPrompt, messages),
100
+ stream: true,
101
+ });
102
+
103
+ if (!(result instanceof ReadableStream)) {
104
+ throw new Error(`Gemini did not return a stream (got ${typeof result}). The binding may not honor stream:true for this model; use POST /api/chat instead.`);
105
+ }
106
+
107
+ const reader = result.getReader();
108
+ const decoder = new TextDecoder();
109
+ let buffer = "";
110
+ const reconcile = makeGeminiDeltaReconciler();
111
+
112
+ const onAbort = () => { try { reader.cancel(); } catch { /* fine */ } };
113
+ if (signal.aborted) {
114
+ onAbort();
115
+ } else {
116
+ signal.addEventListener("abort", onAbort, { once: true });
117
+ }
118
+
119
+ try {
120
+ while (true) {
121
+ const { done, value } = await reader.read();
122
+ if (done) break;
123
+
124
+ buffer += decoder.decode(value, { stream: true });
125
+
126
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
127
+ buffer = remainder;
128
+
129
+ for (const payload of payloads) {
130
+ let data: unknown;
131
+ try {
132
+ data = JSON.parse(payload);
133
+ } catch {
134
+ continue;
135
+ }
136
+ for (const event of interpretGeminiSSEFrame(data)) {
137
+ if (event.type === "text") {
138
+ const delta = reconcile(event.text);
139
+ if (delta) yield { type: "text", text: delta };
140
+ } else {
141
+ yield event;
142
+ }
143
+ }
144
+ }
145
+ }
146
+ } finally {
147
+ signal.removeEventListener("abort", onAbort);
148
+ try { reader.releaseLock(); } catch { /* fine */ }
149
+ }
150
+ }
@@ -0,0 +1,69 @@
1
+ // OpenAI proxied chat streaming (v0.21.0).
2
+ //
3
+ // OpenAI chat models route through Cloudflare Unified Billing, not BYOK, so
4
+ // the streaming path is the env.AI.run binding path (same as Workers AI),
5
+ // NOT a direct provider-endpoint fetch (the way Anthropic and xAI stream).
6
+ // We call aiRun with stream:true, get a ReadableStream of SSE frames, and
7
+ // parse them with interpretOpenAISSEFrame, which tolerates both the
8
+ // OpenAI-native delta shape and the CF-normalized flat `response` shape.
9
+ //
10
+ // Structurally identical to callWorkersAIStream (the other binding-based
11
+ // streaming path); only the frame interpreter differs. Abort is bridged the
12
+ // same way: env.AI.run takes no AbortSignal, so we cancel the reader when the
13
+ // consumer signal fires.
14
+
15
+ import type { AiContext } from "../ai-binding";
16
+ import type { ModelEntry } from "../models";
17
+ import type { ProviderStreamEvent } from "../parsers/types";
18
+ import { aiRun } from "../ai-binding";
19
+ import { extractSSEDataPayloads } from "../parsers/sse-framer";
20
+ import { interpretOpenAISSEFrame } from "../parsers/openai-sse";
21
+
22
+ export async function* callOpenAIStream(
23
+ ctx: AiContext,
24
+ model: ModelEntry,
25
+ messages: Array<unknown>,
26
+ signal: AbortSignal,
27
+ ): AsyncGenerator<ProviderStreamEvent> {
28
+ const result = await aiRun(ctx, model.id, { messages, stream: true });
29
+
30
+ if (!(result instanceof ReadableStream)) {
31
+ throw new Error(`OpenAI proxied model did not return a stream (got ${typeof result}). The binding may not honor stream:true for this model; use POST /api/chat instead.`);
32
+ }
33
+
34
+ const reader = result.getReader();
35
+ const decoder = new TextDecoder();
36
+ let buffer = "";
37
+
38
+ const onAbort = () => { try { reader.cancel(); } catch { /* fine */ } };
39
+ if (signal.aborted) {
40
+ onAbort();
41
+ } else {
42
+ signal.addEventListener("abort", onAbort, { once: true });
43
+ }
44
+
45
+ try {
46
+ while (true) {
47
+ const { done, value } = await reader.read();
48
+ if (done) break;
49
+
50
+ buffer += decoder.decode(value, { stream: true });
51
+
52
+ const { payloads, remainder } = extractSSEDataPayloads(buffer);
53
+ buffer = remainder;
54
+
55
+ for (const payload of payloads) {
56
+ let data: unknown;
57
+ try {
58
+ data = JSON.parse(payload);
59
+ } catch {
60
+ continue;
61
+ }
62
+ for (const event of interpretOpenAISSEFrame(data)) yield event;
63
+ }
64
+ }
65
+ } finally {
66
+ signal.removeEventListener("abort", onAbort);
67
+ try { reader.releaseLock(); } catch { /* fine */ }
68
+ }
69
+ }