@skyphusion/create-prism 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/index.js +4 -2
- package/package.json +1 -1
- package/template/CONTRIBUTING.md +6 -2
- package/template/README.md +227 -48
- package/template/docs/legal/README.md +1 -0
- package/template/migrations/0002_auth_public_mode.sql +32 -0
- package/template/migrations/0003_conversation_compact.sql +24 -0
- package/template/package.json +6 -6
- package/template/public/app.js +128 -19
- package/template/public/index.html +50 -4
- package/template/public/styles.css +16 -2
- package/template/schema.sql +17 -0
- package/template/src/auth-kdf.ts +7 -4
- package/template/src/auth.ts +11 -2
- package/template/src/control-plane.ts +254 -0
- package/template/src/conversation-context.ts +126 -0
- package/template/src/env.ts +15 -0
- package/template/src/gateway-credentials.ts +23 -4
- package/template/src/health-schema.ts +4 -0
- package/template/src/index.ts +73 -3982
- package/template/src/longrun-params.ts +4 -2
- package/template/src/models.ts +65 -19
- package/template/src/output-extract.ts +58 -8
- package/template/src/parsers/openai-sse.ts +43 -14
- package/template/src/providers/anthropic.ts +105 -0
- package/template/src/providers/openai-image.ts +66 -0
- package/template/src/providers/openai.ts +79 -13
- package/template/src/providers/xai.ts +91 -0
- package/template/src/proxied-image-params.ts +29 -16
- package/template/src/routes/artifacts.ts +51 -0
- package/template/src/routes/chat.ts +1682 -0
- package/template/src/routes/conversations.ts +494 -0
- package/template/src/routes/documents.ts +262 -0
- package/template/src/routes/health.ts +105 -0
- package/template/src/routes/history.ts +92 -0
- package/template/src/routes/prefs.ts +95 -0
- package/template/src/routes/projects.ts +574 -0
- package/template/src/routes/rag.ts +657 -0
- package/template/src/routes/shared.ts +226 -0
- package/template/src/routes/workflow.ts +304 -0
- package/template/src/stt-session.ts +1 -1
- package/template/src/user-prefs.ts +10 -0
- package/template/src/zip.ts +7 -0
- package/template/tests/anthropic-binding.test.ts +181 -0
- package/template/tests/control-plane.test.ts +112 -0
- package/template/tests/conversation-compact.test.ts +103 -0
- package/template/tests/gateway-credentials.test.ts +37 -0
- package/template/tests/longrun-params.test.ts +19 -0
- package/template/tests/openai-image.test.ts +47 -0
- package/template/tests/openai-responses.test.ts +78 -0
- package/template/tests/openai-sse.test.ts +28 -0
- package/template/tests/output-extract.test.ts +75 -1
- package/template/tests/proxied-image-params.test.ts +16 -7
- package/template/tests/sprint1-catalog.test.ts +27 -0
- package/template/tests/sprint2-catalog.test.ts +51 -0
- package/template/tests/sprint3-catalog.test.ts +29 -0
- package/template/tests/xai-binding.test.ts +127 -0
- package/template/tests-integration/worker.test.ts +9 -2
- package/template/wrangler.example.toml +19 -7
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// Shared request/response + storage primitives and cross-cutting types used by
|
|
2
|
+
// the route modules under src/routes/. index.ts constructs the fetch route
|
|
3
|
+
// table and delegates to those modules; the helpers and types they all lean on
|
|
4
|
+
// (the JSON envelope, identity resolution, the AI-gateway gate, the R2 storage
|
|
5
|
+
// primitives, and the persisted-row/retrieval type shapes) live here so no
|
|
6
|
+
// route module has to import another just to reach them.
|
|
7
|
+
|
|
8
|
+
import type { Env } from "../env";
|
|
9
|
+
import type { ModelEntry } from "../models";
|
|
10
|
+
import type { InputAttachment } from "../types";
|
|
11
|
+
import { extFromMime, bytesToBase64 } from "../utils";
|
|
12
|
+
import { type AiContext } from "../ai-binding";
|
|
13
|
+
import {
|
|
14
|
+
loadGatewayCredentials,
|
|
15
|
+
GATEWAY_NOT_CONFIGURED_MSG,
|
|
16
|
+
CF_AIG_TOKEN_REQUIRED_MSG,
|
|
17
|
+
} from "../gateway-credentials";
|
|
18
|
+
import {
|
|
19
|
+
resolveControlPlane,
|
|
20
|
+
type ControlPlaneCredentials,
|
|
21
|
+
} from "../control-plane";
|
|
22
|
+
import { loadUserPrefs } from "../user-prefs";
|
|
23
|
+
import { resolveIdentity } from "../auth";
|
|
24
|
+
|
|
25
|
+
// ---------- Types ----------
|
|
26
|
+
|
|
27
|
+
export interface ChatRequest {
|
|
28
|
+
model: string;
|
|
29
|
+
system_prompt?: string;
|
|
30
|
+
user_input: string;
|
|
31
|
+
attachments?: InputAttachment[];
|
|
32
|
+
image_url?: string; // v0.21.5: source image for image-to-video models (hh1-i2v); a fetchable URL
|
|
33
|
+
image_key?: string; // v0.21.6: source image as an R2 key (e.g. a prior nano-banana output) for image-to-video chaining
|
|
34
|
+
use_docs?: boolean; // Pass 2: when true, retrieve top-K chunks from Vectorize and inject as context
|
|
35
|
+
use_web_search?: boolean; // v0.17.0: when true, query SearXNG + Wikipedia and inject snippets as context
|
|
36
|
+
conversation_id?: string; // Multi-turn: when present, continue an existing conversation
|
|
37
|
+
project_id?: number; // v0.20.0: when present, scope RAG retrieval to the project's docs
|
|
38
|
+
// and apply the project's system_prompt as default if system_prompt is empty
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface RetrievedChunk {
|
|
42
|
+
// v0.17.0: discriminator. Omitted on existing rows (pre-v0.17.0) and on new
|
|
43
|
+
// RAG-only rows; readers treat "missing" as "rag" for back-compat.
|
|
44
|
+
source_type?: "rag";
|
|
45
|
+
document_id: number;
|
|
46
|
+
filename: string;
|
|
47
|
+
chunk_index: number;
|
|
48
|
+
text: string;
|
|
49
|
+
score: number;
|
|
50
|
+
page?: number | null; // PDFs only
|
|
51
|
+
sheet?: string | null; // XLSX/XLS only
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// v0.17.0: web-search result, stored alongside RAG chunks in the same
|
|
55
|
+
// retrieved_context column. The frontend renders branches on source_type.
|
|
56
|
+
export interface RetrievedWebResult {
|
|
57
|
+
source_type: "web";
|
|
58
|
+
source: "searxng" | "wikipedia";
|
|
59
|
+
url: string;
|
|
60
|
+
title: string;
|
|
61
|
+
snippet: string; // already HTML-stripped
|
|
62
|
+
score?: number; // kept for back-compat with pre-v0.166.0 rows (Tavily scores); unset now
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type RetrievedItem = RetrievedChunk | RetrievedWebResult;
|
|
66
|
+
|
|
67
|
+
export interface PersistedImageAttachment {
|
|
68
|
+
type: "image";
|
|
69
|
+
key: string;
|
|
70
|
+
mime?: string;
|
|
71
|
+
filename?: string;
|
|
72
|
+
}
|
|
73
|
+
export interface PersistedAudioAttachment {
|
|
74
|
+
type: "audio";
|
|
75
|
+
mime?: string;
|
|
76
|
+
filename?: string;
|
|
77
|
+
transcript: string | null;
|
|
78
|
+
}
|
|
79
|
+
export interface PersistedVideoFramesAttachment {
|
|
80
|
+
type: "video_frames";
|
|
81
|
+
keys: string[];
|
|
82
|
+
frame_count: number;
|
|
83
|
+
duration?: number;
|
|
84
|
+
filename?: string;
|
|
85
|
+
}
|
|
86
|
+
export interface PersistedVideoFullAttachment {
|
|
87
|
+
type: "video_full";
|
|
88
|
+
key: string;
|
|
89
|
+
mime?: string;
|
|
90
|
+
filename?: string;
|
|
91
|
+
}
|
|
92
|
+
// v0.24.0: inline text-file attachment. The contents are folded into the
|
|
93
|
+
// prompt (not stored in R2); we persist only metadata so history can show
|
|
94
|
+
// that a file was attached without bloating D1 with the full text.
|
|
95
|
+
export interface PersistedDocumentAttachment {
|
|
96
|
+
type: "document";
|
|
97
|
+
mime?: string;
|
|
98
|
+
filename?: string;
|
|
99
|
+
chars: number;
|
|
100
|
+
}
|
|
101
|
+
export type PersistedAttachment =
|
|
102
|
+
| PersistedImageAttachment
|
|
103
|
+
| PersistedAudioAttachment
|
|
104
|
+
| PersistedVideoFramesAttachment
|
|
105
|
+
| PersistedVideoFullAttachment
|
|
106
|
+
| PersistedDocumentAttachment;
|
|
107
|
+
|
|
108
|
+
export interface OutputArtifact {
|
|
109
|
+
key: string;
|
|
110
|
+
mime: string;
|
|
111
|
+
type: "image" | "audio" | "video";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---------- Helpers ----------
|
|
115
|
+
|
|
116
|
+
export function json(body: unknown, init: ResponseInit = {}): Response {
|
|
117
|
+
const headers = new Headers(init.headers);
|
|
118
|
+
headers.set("content-type", "application/json; charset=utf-8");
|
|
119
|
+
return new Response(JSON.stringify(body), { ...init, headers });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Identity read site #1 (HTTP). Delegates to resolveIdentity so access-mode and
|
|
123
|
+
// public-mode derivation stay in one place. In access mode this is never null.
|
|
124
|
+
// In public mode the router gate rejects unauthenticated /api/* with 401 before
|
|
125
|
+
// any handler runs, so a null here is an unreachable, fail-closed error rather
|
|
126
|
+
// than a silent anonymous cross-attribution.
|
|
127
|
+
export async function getUserEmail(request: Request, env: Env): Promise<string> {
|
|
128
|
+
const id = await resolveIdentity(request, env);
|
|
129
|
+
if (id === null) throw new Error("unauthenticated request reached an owned handler");
|
|
130
|
+
return id;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function modelNeedsCfAigToken(model: ModelEntry): boolean {
|
|
134
|
+
return !!model.provider && model.provider !== "workers-ai";
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function requireAiContext(
|
|
138
|
+
env: Env,
|
|
139
|
+
userEmail: string,
|
|
140
|
+
opts?: { requireCfToken?: boolean },
|
|
141
|
+
): Promise<AiContext | Response> {
|
|
142
|
+
const gateway = await loadGatewayCredentials(env, userEmail);
|
|
143
|
+
if (!gateway?.gatewayId) {
|
|
144
|
+
return json({ error: GATEWAY_NOT_CONFIGURED_MSG, code: "gateway_not_configured" }, { status: 412 });
|
|
145
|
+
}
|
|
146
|
+
if (opts?.requireCfToken && !gateway.cfAigToken) {
|
|
147
|
+
return json({ error: CF_AIG_TOKEN_REQUIRED_MSG, code: "cf_aig_token_required" }, { status: 412 });
|
|
148
|
+
}
|
|
149
|
+
return { env, gateway };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Inference backend for a user: control plane (pcp_) wins when configured,
|
|
154
|
+
* else AI Gateway BYOK / worker secrets.
|
|
155
|
+
*/
|
|
156
|
+
export type InferenceBackend =
|
|
157
|
+
| { kind: "control_plane"; cp: ControlPlaneCredentials }
|
|
158
|
+
| { kind: "gateway"; ctx: AiContext };
|
|
159
|
+
|
|
160
|
+
export async function requireInferenceBackend(
|
|
161
|
+
env: Env,
|
|
162
|
+
userEmail: string,
|
|
163
|
+
opts?: { requireCfToken?: boolean },
|
|
164
|
+
): Promise<InferenceBackend | Response> {
|
|
165
|
+
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
166
|
+
// Control-plane key intentionally replaces gateway BYOK for chat: the proxy
|
|
167
|
+
// holds host credentials. Gateway token is not required when CP is active.
|
|
168
|
+
const cp = resolveControlPlane(prefs, env);
|
|
169
|
+
if (cp) return { kind: "control_plane", cp };
|
|
170
|
+
|
|
171
|
+
const gatewayOrErr = await requireAiContext(env, userEmail, opts);
|
|
172
|
+
if (gatewayOrErr instanceof Response) return gatewayOrErr;
|
|
173
|
+
return { kind: "gateway", ctx: gatewayOrErr };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function r2Put(env: Env, prefix: "in" | "out", mime: string, bytes: Uint8Array, userEmail: string): Promise<string> {
|
|
177
|
+
const key = `${prefix}/${crypto.randomUUID()}.${extFromMime(mime)}`;
|
|
178
|
+
await env.R2.put(key, bytes, {
|
|
179
|
+
httpMetadata: { contentType: mime },
|
|
180
|
+
customMetadata: { user_email: userEmail },
|
|
181
|
+
});
|
|
182
|
+
return key;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
// Read an R2 object and return it as a base64 `data:` URI. Used to inline a
|
|
187
|
+
// source image for image-to-video (hh1-i2v): the upstream accepts data URIs
|
|
188
|
+
// (verified, it re-uploads them to its own OSS), so we don't need a presigned
|
|
189
|
+
// GET URL. Ownership is enforced the same way /api/artifact does: the object's
|
|
190
|
+
// customMetadata.user_email must match, so a client can't reference another
|
|
191
|
+
// user's R2 key via image_key. Throws on miss or ownership mismatch.
|
|
192
|
+
export async function r2KeyToDataUri(env: Env, key: string, userEmail: string): Promise<string> {
|
|
193
|
+
const obj = await env.R2.get(key);
|
|
194
|
+
if (!obj) throw new Error(`source image not found: ${key}`);
|
|
195
|
+
if (obj.customMetadata?.user_email !== userEmail) {
|
|
196
|
+
throw new Error(`source image not owned by requester: ${key}`);
|
|
197
|
+
}
|
|
198
|
+
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
199
|
+
const mime = obj.httpMetadata?.contentType || "image/png";
|
|
200
|
+
return `data:${mime};base64,${bytesToBase64(bytes)}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Attachment-by-reference (v0.21.7): an image or full-video attachment may
|
|
204
|
+
// carry an R2 `key` (an artifact already produced in this conversation)
|
|
205
|
+
// instead of inline `data`. Hydrate `data` from R2 once, here at the request
|
|
206
|
+
// boundary, so every downstream consumer (vision chat, FLUX.2 reference
|
|
207
|
+
// images, image-to-video) works unchanged. Ownership is enforced by
|
|
208
|
+
// r2KeyToDataUri. This is what lets a model use what a previous model in the
|
|
209
|
+
// same conversation generated, with no download/re-upload.
|
|
210
|
+
export async function resolveAttachmentKeys(env: Env, attachments: InputAttachment[], userEmail: string): Promise<InputAttachment[]> {
|
|
211
|
+
return Promise.all(attachments.map(async (att) => {
|
|
212
|
+
if ((att.type === "image" || att.type === "video_full") && att.key && !att.data) {
|
|
213
|
+
return { ...att, data: await r2KeyToDataUri(env, att.key, userEmail) };
|
|
214
|
+
}
|
|
215
|
+
return att;
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export async function r2DeleteSafe(env: Env, key: string): Promise<void> {
|
|
220
|
+
try { await env.R2.delete(key); } catch { /* ignore */ }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function safeParseJson<T>(s: string): T | null {
|
|
224
|
+
try { return JSON.parse(s) as T; } catch { return null; }
|
|
225
|
+
}
|
|
226
|
+
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// LongRunWorkflow: Cloudflare Workflow for durable Unified Billing video/music
|
|
2
|
+
// generation and bulk .zip RAG import. Re-exported from index.ts (wrangler
|
|
3
|
+
// resolves the workflow class_name against the main entry). The gen path holds
|
|
4
|
+
// the blocking env.AI.run call alive across step boundaries; the zip path
|
|
5
|
+
// ingests one file per step (via ./rag ingestDocument) for a fresh subrequest
|
|
6
|
+
// budget each.
|
|
7
|
+
|
|
8
|
+
import { WorkflowEntrypoint, WorkflowStep } from "cloudflare:workers";
|
|
9
|
+
import type { WorkflowEvent } from "cloudflare:workers";
|
|
10
|
+
import type { Env } from "../env";
|
|
11
|
+
import { aiRun, type AiContext } from "../ai-binding";
|
|
12
|
+
import { loadGatewayCredentials, GATEWAY_NOT_CONFIGURED_MSG } from "../gateway-credentials";
|
|
13
|
+
import { buildGenParams } from "../longrun-params";
|
|
14
|
+
import { unzip } from "../zip";
|
|
15
|
+
import { r2Put, r2KeyToDataUri, r2DeleteSafe } from "./shared";
|
|
16
|
+
import type { OutputArtifact } from "./shared";
|
|
17
|
+
import {
|
|
18
|
+
ingestDocument,
|
|
19
|
+
mimeFromName,
|
|
20
|
+
ZIP_MAX_ENTRIES,
|
|
21
|
+
ZIP_MAX_TOTAL_UNCOMPRESSED_BYTES,
|
|
22
|
+
ZIP_MAX_FILE_BYTES,
|
|
23
|
+
} from "./rag";
|
|
24
|
+
|
|
25
|
+
// ---------- LongRunWorkflow (v0.12.0) ----------
|
|
26
|
+
//
|
|
27
|
+
// Cloudflare Workflow that handles Unified Billing video and music generation.
|
|
28
|
+
// Both surfaces (runVideo Unified path, runMusic) hand off to this class via
|
|
29
|
+
// env.LONGRUN.create({ params }). The workflow is responsible for:
|
|
30
|
+
// 1. Invoking env.AI.run (blocking call, 30s-3min)
|
|
31
|
+
// 2. Downloading the resulting artifact from CF's catalog R2 bucket
|
|
32
|
+
// 3. Uploading the bytes to our own R2 bucket
|
|
33
|
+
// 4. Finalizing the D1 row (status, output_artifact, latency)
|
|
34
|
+
//
|
|
35
|
+
// Why Workflows rather than ctx.waitUntil:
|
|
36
|
+
// - waitUntil has a ~30s budget after the HTTP response is sent. env.AI.run
|
|
37
|
+
// for Veo/Seedance/Hailuo etc. takes 1-3 minutes, so the task gets
|
|
38
|
+
// cancelled mid-call. That cancellation was the failure mode in v0.11.x.
|
|
39
|
+
// - Workflows have unlimited wall-clock time per step (CPU time still
|
|
40
|
+
// capped, but env.AI.run is I/O-bound).
|
|
41
|
+
// - Each step retries independently with built-in backoff, so a transient
|
|
42
|
+
// R2 upload failure doesn't force re-running the (expensive) gen call.
|
|
43
|
+
//
|
|
44
|
+
// Step 2 (download + R2 upload) is one combined step because step.do return
|
|
45
|
+
// values are capped at 1 MiB; video files are 5-15MB, music 3-5MB - we can't
|
|
46
|
+
// pass bytes between steps. So we fold the download and R2 put into a single
|
|
47
|
+
// step and return just the small R2 key. The trade-off: if R2 upload fails
|
|
48
|
+
// after a successful download, the retry re-downloads the same source URL
|
|
49
|
+
// (CF's catalog R2 - cheap and reliable). Acceptable.
|
|
50
|
+
//
|
|
51
|
+
// Response shapes per https://developers.cloudflare.com/ai/models/:
|
|
52
|
+
// Veo: { state:"Completed", result:{ video:"..." }, gatewayMetadata }
|
|
53
|
+
// MiniMax: { audio:"..." } (flat) - some normalized providers may wrap in
|
|
54
|
+
// { state, result:{ audio }, gatewayMetadata } so we accept both.
|
|
55
|
+
// Other UB video providers (bytedance/runway/alibaba/pixverse/vidu) are
|
|
56
|
+
// expected to follow the Veo-style wrapper but have NOT been runtime-
|
|
57
|
+
// verified as of v0.12.0. Per-provider param shapes may also differ from
|
|
58
|
+
// the Veo baseline (prompt/duration/aspect_ratio/resolution/generate_audio);
|
|
59
|
+
// errors surface in job_error for iteration.
|
|
60
|
+
|
|
61
|
+
export type LongRunKind = "video" | "music";
|
|
62
|
+
|
|
63
|
+
export interface LongRunGenParams extends Record<string, unknown> {
|
|
64
|
+
rowId: number;
|
|
65
|
+
userEmail: string;
|
|
66
|
+
modelId: string;
|
|
67
|
+
prompt: string;
|
|
68
|
+
lyrics?: string; // music only
|
|
69
|
+
imageUrl?: string; // image-to-video: a fetchable URL passed through as-is
|
|
70
|
+
imageKey?: string; // image-to-video: an R2 key resolved to a data: URI in the workflow (uploads + chaining)
|
|
71
|
+
kind: LongRunKind;
|
|
72
|
+
startedAtIso: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// v0.26.0: durable bulk ZIP import. The uploaded archive is staged to R2
|
|
76
|
+
// (`zipKey`) so its bytes never ride the workflow event payload; the workflow
|
|
77
|
+
// unzips it and ingests each inner file in its own step. Putting each file in
|
|
78
|
+
// a separate step gives each ingest a fresh Worker subrequest budget, which is
|
|
79
|
+
// what lets a large archive import without hitting the per-invocation limit
|
|
80
|
+
// that the synchronous v0.25.0 path could approach.
|
|
81
|
+
export interface ZipImportParams extends Record<string, unknown> {
|
|
82
|
+
kind: "zip_import";
|
|
83
|
+
userEmail: string;
|
|
84
|
+
zipKey: string;
|
|
85
|
+
startedAtIso: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type LongRunParams =
|
|
89
|
+
| LongRunGenParams
|
|
90
|
+
| ZipImportParams;
|
|
91
|
+
|
|
92
|
+
// Returned by the zip-import workflow run() and surfaced via the instance's
|
|
93
|
+
// status().output to the polling client. userEmail is included so the status
|
|
94
|
+
// endpoint can enforce per-user ownership (a guessed instance id can't read
|
|
95
|
+
// another user's import result).
|
|
96
|
+
export interface ZipImportSummary {
|
|
97
|
+
userEmail: string;
|
|
98
|
+
imported_count: number;
|
|
99
|
+
total_chunks: number;
|
|
100
|
+
imported: Array<{ name: string; id: number; chunk_count: number }>;
|
|
101
|
+
skipped: Array<{ name: string; reason: string }>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Shape we expect back from env.AI.run for video and music. Both share the
|
|
105
|
+
// same envelope; only the inner field differs (video vs audio).
|
|
106
|
+
export interface LongRunResult {
|
|
107
|
+
state?: string;
|
|
108
|
+
result?: { video?: string; audio?: string };
|
|
109
|
+
audio?: string; // flat shape for minimax/music-2.6
|
|
110
|
+
gatewayMetadata?: { keySource?: string };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export class LongRunWorkflow extends WorkflowEntrypoint<Env, LongRunParams> {
|
|
114
|
+
async run(event: WorkflowEvent<LongRunParams>, step: WorkflowStep): Promise<unknown> {
|
|
115
|
+
if (event.payload.kind === "zip_import") {
|
|
116
|
+
return this.runZipImport(event.payload, step);
|
|
117
|
+
}
|
|
118
|
+
return this.runGen(event.payload, step);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// v0.26.0: bulk ZIP import. Step 1 unzips the staged archive and stages each
|
|
122
|
+
// inner file to a temp R2 object (returning only the small name+key list, so
|
|
123
|
+
// we stay under the 1 MiB step-return cap and never pass bytes between
|
|
124
|
+
// steps). Each subsequent step ingests one file with a fresh subrequest
|
|
125
|
+
// budget. A failed ingest becomes a skip, not a workflow failure. A final
|
|
126
|
+
// step deletes the temp objects and the staged zip.
|
|
127
|
+
async runZipImport(p: ZipImportParams, step: WorkflowStep): Promise<ZipImportSummary> {
|
|
128
|
+
const { userEmail, zipKey } = p;
|
|
129
|
+
|
|
130
|
+
const { staged, skipped: unzipSkipped } = await step.do(
|
|
131
|
+
"unzip-and-stage",
|
|
132
|
+
{ retries: { limit: 2, delay: "5 seconds", backoff: "exponential" } },
|
|
133
|
+
async (): Promise<{ staged: Array<{ name: string; key: string }>; skipped: Array<{ name: string; reason: string }> }> => {
|
|
134
|
+
const obj = await this.env.R2.get(zipKey);
|
|
135
|
+
if (!obj) throw new Error("staged zip not found in R2");
|
|
136
|
+
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
137
|
+
const { entries, skipped } = await unzip(bytes, {
|
|
138
|
+
maxEntries: ZIP_MAX_ENTRIES,
|
|
139
|
+
maxTotalBytes: ZIP_MAX_TOTAL_UNCOMPRESSED_BYTES,
|
|
140
|
+
maxFileBytes: ZIP_MAX_FILE_BYTES,
|
|
141
|
+
});
|
|
142
|
+
const out: Array<{ name: string; key: string }> = [];
|
|
143
|
+
for (const e of entries) {
|
|
144
|
+
const key = `tmp/${crypto.randomUUID()}`;
|
|
145
|
+
await this.env.R2.put(key, e.bytes, { customMetadata: { user_email: userEmail } });
|
|
146
|
+
out.push({ name: e.name, key });
|
|
147
|
+
}
|
|
148
|
+
return { staged: out, skipped };
|
|
149
|
+
}
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
const imported: ZipImportSummary["imported"] = [];
|
|
153
|
+
const skipped: ZipImportSummary["skipped"] = [...unzipSkipped];
|
|
154
|
+
|
|
155
|
+
// One step per file: each gets its own subrequest budget. ingestDocument
|
|
156
|
+
// swallows its own errors into an ok:false result (after rolling back its
|
|
157
|
+
// partial writes), so an unreadable file does not abort the import.
|
|
158
|
+
for (let i = 0; i < staged.length; i++) {
|
|
159
|
+
const item = staged[i];
|
|
160
|
+
const res = await step.do(
|
|
161
|
+
`ingest-${i}`,
|
|
162
|
+
{ retries: { limit: 2, delay: "5 seconds", backoff: "exponential" } },
|
|
163
|
+
async (): Promise<{ ok: true; name: string; id: number; chunk_count: number } | { ok: false; name: string; reason: string }> => {
|
|
164
|
+
const obj = await this.env.R2.get(item.key);
|
|
165
|
+
if (!obj) return { ok: false, name: item.name, reason: "staged file missing" };
|
|
166
|
+
const bytes = new Uint8Array(await obj.arrayBuffer());
|
|
167
|
+
const r = await ingestDocument(this.env, userEmail, item.name, mimeFromName(item.name), bytes);
|
|
168
|
+
return r.ok
|
|
169
|
+
? { ok: true, name: item.name, id: r.id, chunk_count: r.chunk_count }
|
|
170
|
+
: { ok: false, name: item.name, reason: r.error };
|
|
171
|
+
}
|
|
172
|
+
);
|
|
173
|
+
if (res.ok) imported.push({ name: res.name, id: res.id, chunk_count: res.chunk_count });
|
|
174
|
+
else skipped.push({ name: res.name, reason: res.reason });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Cleanup: drop the temp staged files and the staged zip. Best-effort; a
|
|
178
|
+
// leaked temp object under tmp/ is harmless and can be swept by an R2
|
|
179
|
+
// lifecycle rule. Done after all ingests so a per-file step retry can still
|
|
180
|
+
// re-read its staged object.
|
|
181
|
+
await step.do(
|
|
182
|
+
"cleanup",
|
|
183
|
+
{ retries: { limit: 1, delay: "5 seconds", backoff: "linear" } },
|
|
184
|
+
async (): Promise<void> => {
|
|
185
|
+
for (const item of staged) await r2DeleteSafe(this.env, item.key);
|
|
186
|
+
await r2DeleteSafe(this.env, zipKey);
|
|
187
|
+
}
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
userEmail,
|
|
192
|
+
imported_count: imported.length,
|
|
193
|
+
total_chunks: imported.reduce((s, d) => s + d.chunk_count, 0),
|
|
194
|
+
imported,
|
|
195
|
+
skipped,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async runGen(payload: LongRunGenParams, step: WorkflowStep): Promise<void> {
|
|
200
|
+
const { rowId, userEmail, modelId, prompt, lyrics, imageUrl, imageKey, kind, startedAtIso } = payload;
|
|
201
|
+
|
|
202
|
+
// Best-effort row-fail helper. Used in the outer catch to surface
|
|
203
|
+
// workflow-level failures to the polling client. Failures inside this
|
|
204
|
+
// helper are intentionally swallowed - if D1 is down, there's nothing
|
|
205
|
+
// we can do from a background workflow anyway.
|
|
206
|
+
const failRow = async (msg: string): Promise<void> => {
|
|
207
|
+
try {
|
|
208
|
+
await this.env.DB.prepare(`UPDATE chats SET status = 'failed', job_error = ? WHERE id = ?`)
|
|
209
|
+
.bind(msg.slice(0, 1000), rowId)
|
|
210
|
+
.run();
|
|
211
|
+
} catch { /* swallow */ }
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
// Step 1: invoke the model. Long-running blocking call.
|
|
216
|
+
//
|
|
217
|
+
// Retry policy: ONE retry only. Each attempt costs Unified Billing
|
|
218
|
+
// credits; if it fails twice with a 30s spacing, the third attempt is
|
|
219
|
+
// unlikely to help and we'd rather surface the error to the user.
|
|
220
|
+
const artifactUrl = await step.do(
|
|
221
|
+
"invoke-model",
|
|
222
|
+
{ retries: { limit: 1, delay: "30 seconds", backoff: "linear" } },
|
|
223
|
+
async (): Promise<string> => {
|
|
224
|
+
// Resolve the source image for image-to-video: an R2 key (upload or
|
|
225
|
+
// chained nano-banana output) becomes a data: URI here, inside the
|
|
226
|
+
// step, so the big base64 never rides the Workflow event payload.
|
|
227
|
+
// A plain URL passes straight through. Resolution happens in-step so
|
|
228
|
+
// a transient R2 read is covered by the step's retry.
|
|
229
|
+
const resolvedImage = imageKey
|
|
230
|
+
? await r2KeyToDataUri(this.env, imageKey, userEmail)
|
|
231
|
+
: imageUrl;
|
|
232
|
+
const params = buildGenParams(kind, { modelId, prompt, lyrics, imageUrl: resolvedImage });
|
|
233
|
+
|
|
234
|
+
const gateway = await loadGatewayCredentials(this.env, userEmail);
|
|
235
|
+
if (!gateway?.gatewayId) {
|
|
236
|
+
throw new Error(GATEWAY_NOT_CONFIGURED_MSG);
|
|
237
|
+
}
|
|
238
|
+
const aiCtx: AiContext = { env: this.env, gateway };
|
|
239
|
+
const result = await aiRun(aiCtx, modelId, params) as LongRunResult;
|
|
240
|
+
|
|
241
|
+
if (result.state && result.state !== "Completed") {
|
|
242
|
+
throw new Error(`Unexpected gen state: ${result.state}`);
|
|
243
|
+
}
|
|
244
|
+
const url = kind === "video"
|
|
245
|
+
? result.result?.video
|
|
246
|
+
: (result.audio ?? result.result?.audio);
|
|
247
|
+
if (!url) {
|
|
248
|
+
throw new Error(`Gen completed but no ${kind} URL. Raw: ${JSON.stringify(result).slice(0, 500)}`);
|
|
249
|
+
}
|
|
250
|
+
return url;
|
|
251
|
+
}
|
|
252
|
+
);
|
|
253
|
+
|
|
254
|
+
// Step 2: download artifact and upload to R2 (combined; can't pass
|
|
255
|
+
// bytes between steps due to the 1 MiB step return cap).
|
|
256
|
+
const { r2Key, mime } = await step.do(
|
|
257
|
+
"download-and-store",
|
|
258
|
+
{ retries: { limit: 3, delay: "5 seconds", backoff: "exponential" } },
|
|
259
|
+
async (): Promise<{ r2Key: string; mime: string }> => {
|
|
260
|
+
const aresp = await fetch(artifactUrl);
|
|
261
|
+
if (!aresp.ok) throw new Error(`Fetch ${aresp.status} from ${artifactUrl.slice(0, 100)}`);
|
|
262
|
+
// For video, force video/mp4. CF's catalog R2 and many CDNs serve
|
|
263
|
+
// MP4 as application/octet-stream, which would cause R2 keys to
|
|
264
|
+
// end in .bin when upstream serves application/octet-stream.
|
|
265
|
+
const upstreamMime = aresp.headers.get("content-type") || "";
|
|
266
|
+
const finalMime = kind === "video"
|
|
267
|
+
? "video/mp4"
|
|
268
|
+
: (upstreamMime || "audio/mpeg");
|
|
269
|
+
const bytes = new Uint8Array(await aresp.arrayBuffer());
|
|
270
|
+
const key = await r2Put(this.env, "out", finalMime, bytes, userEmail);
|
|
271
|
+
return { r2Key: key, mime: finalMime };
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
// Step 3: finalize the D1 row.
|
|
276
|
+
await step.do(
|
|
277
|
+
"finalize-d1",
|
|
278
|
+
{ retries: { limit: 3, delay: "5 seconds", backoff: "exponential" } },
|
|
279
|
+
async (): Promise<void> => {
|
|
280
|
+
const outputArtifact: OutputArtifact = {
|
|
281
|
+
key: r2Key,
|
|
282
|
+
mime,
|
|
283
|
+
type: kind === "video" ? "video" : "audio",
|
|
284
|
+
};
|
|
285
|
+
const latency = Date.now() - Date.parse(startedAtIso);
|
|
286
|
+
await this.env.DB.prepare(
|
|
287
|
+
`UPDATE chats SET status = 'done', output_artifact = ?, latency_ms = ? WHERE id = ?`
|
|
288
|
+
)
|
|
289
|
+
.bind(JSON.stringify(outputArtifact), latency, rowId)
|
|
290
|
+
.run();
|
|
291
|
+
}
|
|
292
|
+
);
|
|
293
|
+
} catch (err) {
|
|
294
|
+
// A step exhausted its retries (or some non-step code threw). Mark the
|
|
295
|
+
// D1 row failed so the polling client gets a clear error, then re-throw
|
|
296
|
+
// so the workflow instance itself is reported as errored in the
|
|
297
|
+
// dashboard (preserves observability).
|
|
298
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
299
|
+
await failRow(m);
|
|
300
|
+
throw err;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
@@ -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
|
|
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
|
|
@@ -7,6 +7,11 @@
|
|
|
7
7
|
export interface UserPrefsJson {
|
|
8
8
|
gateway_id?: string;
|
|
9
9
|
cf_aig_token?: string;
|
|
10
|
+
/**
|
|
11
|
+
* When set, chat bills through prism-control-plane (allowlisted origin from
|
|
12
|
+
* worker config, never a user-supplied URL -- SSRF). Client key `pcp_…`.
|
|
13
|
+
*/
|
|
14
|
+
control_plane_key?: string;
|
|
10
15
|
}
|
|
11
16
|
|
|
12
17
|
function parsePrefsJson(raw: string | null | undefined): UserPrefsJson {
|
|
@@ -48,6 +53,11 @@ export async function saveUserPrefs(
|
|
|
48
53
|
if (trimmed) merged.cf_aig_token = trimmed;
|
|
49
54
|
else delete merged.cf_aig_token;
|
|
50
55
|
}
|
|
56
|
+
if (patch.control_plane_key !== undefined) {
|
|
57
|
+
const trimmed = patch.control_plane_key.trim();
|
|
58
|
+
if (trimmed) merged.control_plane_key = trimmed;
|
|
59
|
+
else delete merged.control_plane_key;
|
|
60
|
+
}
|
|
51
61
|
|
|
52
62
|
await db.prepare(
|
|
53
63
|
`INSERT INTO user_prefs (user_email, prefs_json, updated_at)
|
package/template/src/zip.ts
CHANGED
|
@@ -129,6 +129,13 @@ export async function unzip(bytes: Uint8Array, limits: UnzipLimits): Promise<Unz
|
|
|
129
129
|
continue;
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
if (out.length > limits.maxFileBytes) {
|
|
133
|
+
skipped.push({ name, reason: `inflated size ${out.length} over per-file limit` }); continue;
|
|
134
|
+
}
|
|
135
|
+
if (total + out.length > limits.maxTotalBytes) {
|
|
136
|
+
skipped.push({ name, reason: "cumulative inflated size limit reached" }); continue;
|
|
137
|
+
}
|
|
138
|
+
|
|
132
139
|
total += out.length;
|
|
133
140
|
entries.push({ name, bytes: out });
|
|
134
141
|
}
|