@skyphusion/create-prism 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/index.js +4 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +6 -2
- package/template/README.md +227 -48
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/package.json +6 -6
- package/template/public/app.js +128 -19
- package/template/public/index.html +50 -4
- package/template/public/styles.css +16 -2
- package/template/schema.sql +17 -0
- package/template/src/auth-kdf.ts +7 -4
- package/template/src/auth.ts +11 -2
- package/template/src/control-plane.ts +254 -0
- package/template/src/conversation-context.ts +126 -0
- package/template/src/env.ts +15 -0
- package/template/src/gateway-credentials.ts +23 -4
- package/template/src/health-schema.ts +4 -0
- package/template/src/index.ts +73 -3982
- package/template/src/longrun-params.ts +4 -2
- package/template/src/models.ts +65 -19
- package/template/src/output-extract.ts +58 -8
- package/template/src/parsers/openai-sse.ts +43 -14
- package/template/src/providers/anthropic.ts +105 -0
- package/template/src/providers/openai-image.ts +66 -0
- package/template/src/providers/openai.ts +79 -13
- package/template/src/providers/xai.ts +91 -0
- package/template/src/proxied-image-params.ts +29 -16
- package/template/src/routes/artifacts.ts +51 -0
- package/template/src/routes/chat.ts +1682 -0
- package/template/src/routes/conversations.ts +494 -0
- package/template/src/routes/documents.ts +262 -0
- package/template/src/routes/health.ts +105 -0
- package/template/src/routes/history.ts +92 -0
- package/template/src/routes/prefs.ts +95 -0
- package/template/src/routes/projects.ts +574 -0
- package/template/src/routes/rag.ts +657 -0
- package/template/src/routes/shared.ts +226 -0
- package/template/src/routes/workflow.ts +304 -0
- package/template/src/stt-session.ts +1 -1
- package/template/src/user-prefs.ts +10 -0
- package/template/src/zip.ts +7 -0
- package/template/tests/anthropic-binding.test.ts +181 -0
- package/template/tests/control-plane.test.ts +112 -0
- package/template/tests/conversation-compact.test.ts +103 -0
- package/template/tests/gateway-credentials.test.ts +37 -0
- package/template/tests/longrun-params.test.ts +19 -0
- package/template/tests/openai-image.test.ts +47 -0
- package/template/tests/openai-responses.test.ts +78 -0
- package/template/tests/openai-sse.test.ts +28 -0
- package/template/tests/output-extract.test.ts +75 -1
- package/template/tests/proxied-image-params.test.ts +16 -7
- package/template/tests/sprint1-catalog.test.ts +27 -0
- package/template/tests/sprint2-catalog.test.ts +51 -0
- package/template/tests/sprint3-catalog.test.ts +29 -0
- package/template/tests/xai-binding.test.ts +127 -0
- package/template/tests-integration/worker.test.ts +9 -2
- package/template/wrangler.example.toml +19 -7
|
@@ -1,31 +1,97 @@
|
|
|
1
|
-
// OpenAI proxied chat
|
|
1
|
+
// OpenAI proxied chat via Cloudflare Unified Billing (v0.21.0; Responses API v0.173.0).
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
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.
|
|
3
|
+
// Two request surfaces, selected by ModelEntry.api:
|
|
4
|
+
// - "chat" (default): Chat Completions { messages, stream? }
|
|
5
|
+
// - "responses": Responses API { input, instructions?, max_output_tokens, stream? }
|
|
9
6
|
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
// consumer signal fires.
|
|
7
|
+
// Both go through env.AI.run (not a direct provider fetch). Streaming parses SSE
|
|
8
|
+
// with interpretOpenAISSEFrame, which handles Chat Completions deltas, CF flat
|
|
9
|
+
// `response` frames, and Responses API output_text.delta / completed events.
|
|
14
10
|
|
|
15
11
|
import type { AiContext } from "../ai-binding";
|
|
16
12
|
import type { ModelEntry } from "../models";
|
|
17
13
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
18
|
-
import { aiRun } from "../ai-binding";
|
|
14
|
+
import { aiRun, aiLogId } from "../ai-binding";
|
|
19
15
|
import { extractSSEDataPayloads } from "../parsers/sse-framer";
|
|
20
16
|
import { interpretOpenAISSEFrame } from "../parsers/openai-sse";
|
|
21
17
|
|
|
18
|
+
// Convert OpenAI-style chat messages into a Responses API body.
|
|
19
|
+
// System messages become top-level `instructions`; user/assistant become `input`.
|
|
20
|
+
// Multimodal content arrays are flattened to text (Responses models ship with
|
|
21
|
+
// empty vision caps until multimodal-in is smoked).
|
|
22
|
+
export function buildOpenAIResponsesBody(
|
|
23
|
+
messages: Array<unknown>,
|
|
24
|
+
opts: { stream?: boolean; maxOutputTokens?: number } = {},
|
|
25
|
+
): Record<string, unknown> {
|
|
26
|
+
let instructions: string | undefined;
|
|
27
|
+
const input: Array<{ role: string; content: string }> = [];
|
|
28
|
+
|
|
29
|
+
for (const raw of messages) {
|
|
30
|
+
const msg = raw as { role?: string; content?: unknown };
|
|
31
|
+
if (msg.role === "system") {
|
|
32
|
+
const text = contentToText(msg.content);
|
|
33
|
+
if (text) instructions = instructions ? `${instructions}\n\n${text}` : text;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (msg.role !== "user" && msg.role !== "assistant") continue;
|
|
37
|
+
input.push({ role: msg.role, content: contentToText(msg.content) });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const body: Record<string, unknown> = {
|
|
41
|
+
input,
|
|
42
|
+
max_output_tokens: opts.maxOutputTokens ?? 4096,
|
|
43
|
+
};
|
|
44
|
+
if (instructions) body.instructions = instructions;
|
|
45
|
+
if (opts.stream) body.stream = true;
|
|
46
|
+
return body;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function contentToText(content: unknown): string {
|
|
50
|
+
if (typeof content === "string") return content;
|
|
51
|
+
if (!Array.isArray(content)) return "";
|
|
52
|
+
return content
|
|
53
|
+
.map((block) => {
|
|
54
|
+
const b = block as { type?: string; text?: string };
|
|
55
|
+
if (b?.type === "text" && typeof b.text === "string") return b.text;
|
|
56
|
+
return "";
|
|
57
|
+
})
|
|
58
|
+
.filter(Boolean)
|
|
59
|
+
.join("\n");
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isResponses(model: ModelEntry): boolean {
|
|
63
|
+
return model.api === "responses";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function buildRunParams(
|
|
67
|
+
model: ModelEntry,
|
|
68
|
+
messages: Array<unknown>,
|
|
69
|
+
stream: boolean,
|
|
70
|
+
): Record<string, unknown> {
|
|
71
|
+
if (isResponses(model)) {
|
|
72
|
+
return buildOpenAIResponsesBody(messages, { stream, maxOutputTokens: 4096 });
|
|
73
|
+
}
|
|
74
|
+
const body: Record<string, unknown> = { messages };
|
|
75
|
+
if (stream) body.stream = true;
|
|
76
|
+
return body;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function callOpenAI(
|
|
80
|
+
ctx: AiContext,
|
|
81
|
+
model: ModelEntry,
|
|
82
|
+
messages: Array<unknown>,
|
|
83
|
+
): Promise<{ raw: unknown; logId: string | null }> {
|
|
84
|
+
const raw = await aiRun(ctx, model.id, buildRunParams(model, messages, false));
|
|
85
|
+
return { raw, logId: aiLogId(ctx) };
|
|
86
|
+
}
|
|
87
|
+
|
|
22
88
|
export async function* callOpenAIStream(
|
|
23
89
|
ctx: AiContext,
|
|
24
90
|
model: ModelEntry,
|
|
25
91
|
messages: Array<unknown>,
|
|
26
92
|
signal: AbortSignal,
|
|
27
93
|
): AsyncGenerator<ProviderStreamEvent> {
|
|
28
|
-
const result = await aiRun(ctx, model.id,
|
|
94
|
+
const result = await aiRun(ctx, model.id, buildRunParams(model, messages, true));
|
|
29
95
|
|
|
30
96
|
if (!(result instanceof ReadableStream)) {
|
|
31
97
|
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.`);
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
// rather than the older max_tokens field.
|
|
21
21
|
|
|
22
22
|
import type { AiContext } from "../ai-binding";
|
|
23
|
+
import { aiRun, aiLogId } from "../ai-binding";
|
|
23
24
|
import type { ModelEntry } from "../models";
|
|
24
25
|
import type { ProviderStreamEvent } from "../parsers/types";
|
|
25
26
|
import { CF_AIG_TOKEN_REQUIRED_MSG } from "../gateway-credentials";
|
|
@@ -71,11 +72,95 @@ async function prepareXaiRequest(
|
|
|
71
72
|
};
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
// v0.170.0: binding-dispatch path for models flagged `binding: true`
|
|
76
|
+
// (currently xai/grok-4.5). Same frozen-allowlist story as Anthropic Fable-5:
|
|
77
|
+
// new Unified Billing models land on the env.AI.run catalog surface; the
|
|
78
|
+
// legacy AI Gateway grok endpoint may forward unknown ids keyless and 401.
|
|
79
|
+
// Body is OpenAI Chat Completions shaped (messages + max_completion_tokens);
|
|
80
|
+
// the FULL prefixed catalog id is passed to env.AI.run. Non-stream returns
|
|
81
|
+
// chat.completion JSON (extractOutput); stream returns OpenAI-compatible SSE
|
|
82
|
+
// consumed by interpretXaiSSEFrame.
|
|
83
|
+
function buildXaiBindingBody(
|
|
84
|
+
messages: Array<unknown>,
|
|
85
|
+
stream: boolean,
|
|
86
|
+
): Record<string, unknown> {
|
|
87
|
+
const body: Record<string, unknown> = {
|
|
88
|
+
messages,
|
|
89
|
+
max_completion_tokens: 4096,
|
|
90
|
+
};
|
|
91
|
+
if (stream) {
|
|
92
|
+
body.stream = true;
|
|
93
|
+
body.stream_options = { include_usage: true };
|
|
94
|
+
}
|
|
95
|
+
return body;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function callXaiBinding(
|
|
99
|
+
ctx: AiContext,
|
|
100
|
+
model: ModelEntry,
|
|
101
|
+
messages: Array<unknown>,
|
|
102
|
+
): Promise<{ raw: unknown; logId: string | null }> {
|
|
103
|
+
const raw = await aiRun(ctx, model.id, buildXaiBindingBody(messages, false));
|
|
104
|
+
return { raw, logId: aiLogId(ctx) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function* callXaiStreamBinding(
|
|
108
|
+
ctx: AiContext,
|
|
109
|
+
model: ModelEntry,
|
|
110
|
+
messages: Array<unknown>,
|
|
111
|
+
signal: AbortSignal,
|
|
112
|
+
): AsyncGenerator<ProviderStreamEvent> {
|
|
113
|
+
const result = await aiRun(ctx, model.id, buildXaiBindingBody(messages, true));
|
|
114
|
+
|
|
115
|
+
if (!(result instanceof ReadableStream)) {
|
|
116
|
+
throw new Error(`xAI binding did not return a stream (got ${typeof result}). Ensure stream:true is honored by this model.`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const reader = result.getReader();
|
|
120
|
+
const decoder = new TextDecoder();
|
|
121
|
+
let buffer = "";
|
|
122
|
+
|
|
123
|
+
const onAbort = () => { try { reader.cancel(); } catch { /* fine */ } };
|
|
124
|
+
if (signal.aborted) {
|
|
125
|
+
onAbort();
|
|
126
|
+
} else {
|
|
127
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
while (true) {
|
|
132
|
+
const { done, value } = await reader.read();
|
|
133
|
+
if (done) break;
|
|
134
|
+
|
|
135
|
+
buffer += decoder.decode(value, { stream: true });
|
|
136
|
+
|
|
137
|
+
const { payloads, remainder } = extractSSEDataPayloads(buffer);
|
|
138
|
+
buffer = remainder;
|
|
139
|
+
|
|
140
|
+
for (const payload of payloads) {
|
|
141
|
+
let data: unknown;
|
|
142
|
+
try {
|
|
143
|
+
data = JSON.parse(payload);
|
|
144
|
+
} catch {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
for (const event of interpretXaiSSEFrame(data)) yield event;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} finally {
|
|
151
|
+
signal.removeEventListener("abort", onAbort);
|
|
152
|
+
try { reader.releaseLock(); } catch { /* fine */ }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
74
156
|
export async function callXai(
|
|
75
157
|
ctx: AiContext,
|
|
76
158
|
model: ModelEntry,
|
|
77
159
|
messages: Array<unknown>,
|
|
78
160
|
): Promise<{ raw: unknown; logId: string | null }> {
|
|
161
|
+
// v0.170.0: flagged models dispatch through the env.AI.run binding.
|
|
162
|
+
if (model.binding) return callXaiBinding(ctx, model, messages);
|
|
163
|
+
|
|
79
164
|
const { url, headers, body } = await prepareXaiRequest(ctx, model, messages, { stream: false });
|
|
80
165
|
|
|
81
166
|
const resp = await fetch(url, { method: "POST", headers, body });
|
|
@@ -113,6 +198,12 @@ export async function* callXaiStream(
|
|
|
113
198
|
messages: Array<unknown>,
|
|
114
199
|
signal: AbortSignal,
|
|
115
200
|
): AsyncGenerator<ProviderStreamEvent> {
|
|
201
|
+
// v0.170.0: flagged models stream through the env.AI.run binding.
|
|
202
|
+
if (model.binding) {
|
|
203
|
+
yield* callXaiStreamBinding(ctx, model, messages, signal);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
|
|
116
207
|
const { url, headers, body } = await prepareXaiRequest(ctx, model, messages, { stream: true });
|
|
117
208
|
|
|
118
209
|
const resp = await fetch(url, {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// Per-provider request params for proxied (non-@cf) image models (v0.22.0
|
|
1
|
+
// Per-provider request params for proxied (non-@cf) image models (v0.22.0;
|
|
2
|
+
// xAI b64_json + OpenAI BYOK carve-out notes v0.174.0).
|
|
2
3
|
//
|
|
3
4
|
// Every proxied image schema is additionalProperties:false (verified against
|
|
4
5
|
// the CF model pages), so each provider gets ONLY the keys it accepts; the @cf
|
|
@@ -10,15 +11,18 @@
|
|
|
10
11
|
// testable. This takes the two primitives it needs rather than the ModelEntry/
|
|
11
12
|
// ChatRequest objects, keeping it free of any Workers-runtime import.
|
|
12
13
|
//
|
|
13
|
-
// google
|
|
14
|
-
// openai
|
|
15
|
-
// { prompt,
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
// on
|
|
21
|
-
//
|
|
14
|
+
// google (nano-banana family): { prompt, output_format } -> PNG URL
|
|
15
|
+
// openai (gpt-image-*): opaque via proxy
|
|
16
|
+
// { prompt, quality, size }. Transparent PNG
|
|
17
|
+
// only via OPENAI_API_KEY BYOK (openai-image.ts).
|
|
18
|
+
// recraft (recraftv4*): opaque. Returns webp URL. V4/V4.1 reject
|
|
19
|
+
// legacy style enums; V4.1 Pro rejects
|
|
20
|
+
// 1024x1024. Bare { prompt } live-verified
|
|
21
|
+
// 200 on v4 / v4-1 / v4-1-pro (v0.174.1).
|
|
22
|
+
// xai (grok-imagine-*): { prompt, response_format: "b64_json" }
|
|
23
|
+
// CF Unified Billing xAI path is ZDR-constrained
|
|
24
|
+
// and rejects URL output; base64 is required.
|
|
25
|
+
// bytedance (seedream-*): { prompt } -> result.images[] URLs
|
|
22
26
|
import type { Provider } from "./models";
|
|
23
27
|
|
|
24
28
|
export function buildProxiedImageParams(
|
|
@@ -29,14 +33,23 @@ export function buildProxiedImageParams(
|
|
|
29
33
|
case "google":
|
|
30
34
|
return { prompt, output_format: "png" };
|
|
31
35
|
case "openai":
|
|
32
|
-
// gpt-image
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
// BYOK transparent-PNG path (prism#93), so this is the only image path.
|
|
36
|
+
// gpt-image-* via the CF proxy. The proxy's schema is strictly
|
|
37
|
+
// { prompt, images, quality, size, style } and 7003-rejects
|
|
38
|
+
// background/output_format, so transparency is impossible here.
|
|
39
|
+
// Transparent PNGs use OPENAI_API_KEY + generateOpenAIImage instead.
|
|
37
40
|
return { prompt, quality: "high", size: "1024x1024" };
|
|
38
41
|
case "recraft":
|
|
39
|
-
|
|
42
|
+
// V4/V4.1 7003 on style digital_illustration / realistic_image.
|
|
43
|
+
// V4.1 Pro 7003 on size 1024x1024 (2048x2048 or default OK).
|
|
44
|
+
// Bare prompt is accepted on v4, v4-1, and v4-1-pro.
|
|
45
|
+
return { prompt };
|
|
46
|
+
case "xai":
|
|
47
|
+
// Unified Billing Grok Imagine rejects URL format on CF's managed
|
|
48
|
+
// credentials ("Zero Data Retention teams do not have access to URL
|
|
49
|
+
// format"). b64_json is the path that works keylessly.
|
|
50
|
+
return { prompt, response_format: "b64_json" };
|
|
51
|
+
case "bytedance":
|
|
52
|
+
return { prompt };
|
|
40
53
|
default:
|
|
41
54
|
return { prompt };
|
|
42
55
|
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Artifact serving: stream an R2 object (chat input or generated output) gated
|
|
2
|
+
// by the customMetadata.user_email ownership check, with conditional-GET (ETag)
|
|
3
|
+
// revalidation support.
|
|
4
|
+
|
|
5
|
+
import type { Env } from "../env";
|
|
6
|
+
import { getUserEmail } from "./shared";
|
|
7
|
+
|
|
8
|
+
// ---------- Artifact serving ----------
|
|
9
|
+
|
|
10
|
+
export async function handleArtifact(request: Request, env: Env, key: string): Promise<Response> {
|
|
11
|
+
const userEmail = await getUserEmail(request, env);
|
|
12
|
+
// Artifacts (chat input + output) all live on env.R2.
|
|
13
|
+
const bucket = env.R2;
|
|
14
|
+
// v0.142.0: forward the request's conditional headers (If-None-Match) to R2.
|
|
15
|
+
// With a conditional get, R2 returns the object WITHOUT a body when the
|
|
16
|
+
// client's ETag still matches, and we reply 304 (a ~0-byte revalidation);
|
|
17
|
+
// a changed object returns fresh bytes. customMetadata is present on the
|
|
18
|
+
// body-less R2Object too, so the ownership check is unaffected.
|
|
19
|
+
const obj = await bucket.get(key, { onlyIf: request.headers });
|
|
20
|
+
if (!obj) return new Response("Not Found", { status: 404 });
|
|
21
|
+
|
|
22
|
+
// Authorization: only the user who created the artifact may fetch it.
|
|
23
|
+
// We stored user_email in customMetadata at put time. Checked before any
|
|
24
|
+
// 304 so a non-owner with a guessed ETag still gets 403, never a hit/miss.
|
|
25
|
+
const owner = obj.customMetadata?.user_email;
|
|
26
|
+
if (owner !== userEmail) {
|
|
27
|
+
return new Response("Forbidden", { status: 403 });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Use the last path segment of the R2 key as a download filename hint, so
|
|
31
|
+
// <a download> on the client saves with the right extension (mp4/png/etc)
|
|
32
|
+
// rather than defaulting to .bin or no extension.
|
|
33
|
+
const filename = key.includes("/") ? key.slice(key.lastIndexOf("/") + 1) : key;
|
|
34
|
+
|
|
35
|
+
const headers = new Headers();
|
|
36
|
+
headers.set("content-type", obj.httpMetadata?.contentType || "application/octet-stream");
|
|
37
|
+
// Revalidate every fetch instead of blind-caching for an hour: no-cache means
|
|
38
|
+
// the browser keeps its copy but must check ETag first, so an overwritten
|
|
39
|
+
// artifact shows fresh while an unchanged one costs only a 304. MP4s (which
|
|
40
|
+
// never overwrite, since a new render is a new job-id key) just 304 cheaply.
|
|
41
|
+
headers.set("cache-control", "private, no-cache");
|
|
42
|
+
if (obj.httpEtag) headers.set("etag", obj.httpEtag);
|
|
43
|
+
headers.set("content-disposition", `inline; filename="${filename}"`);
|
|
44
|
+
|
|
45
|
+
// R2 returns a body-less R2Object when the conditional matched (not modified).
|
|
46
|
+
if (!("body" in obj) || obj.body === null) {
|
|
47
|
+
return new Response(null, { status: 304, headers });
|
|
48
|
+
}
|
|
49
|
+
return new Response(obj.body, { headers });
|
|
50
|
+
}
|
|
51
|
+
|