@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.
- package/LICENSE +235 -0
- package/NOTICE +3 -0
- package/README.md +114 -0
- package/index.js +195 -0
- package/package.json +44 -0
- package/template/CONTRIBUTING.md +80 -0
- package/template/LICENSE +235 -0
- package/template/MIGRATIONS.md +197 -0
- package/template/NOTICE +3 -0
- package/template/README.md +875 -0
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
- package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
- package/template/docs/legal/README.md +11 -0
- package/template/docs/screenshot-desktop.jpg +0 -0
- package/template/docs/screenshot-mobile.jpg +0 -0
- package/template/gitignore +23 -0
- package/template/migrate-v0.164.0.sql +6 -0
- package/template/migrate-v0.167.0.sql +44 -0
- package/template/migrate-v0.20.0.sql +40 -0
- package/template/migrate-v0.20.2.sql +19 -0
- package/template/migrate-v0.20.3.sql +36 -0
- package/template/migrations/0001_init.sql +134 -0
- package/template/package.json +32 -0
- package/template/public/app.js +2778 -0
- package/template/public/apple-touch-icon.png +0 -0
- package/template/public/favicon-16.png +0 -0
- package/template/public/favicon-32.png +0 -0
- package/template/public/favicon.svg +5 -0
- package/template/public/icon-192.png +0 -0
- package/template/public/icon-512.png +0 -0
- package/template/public/index.html +329 -0
- package/template/public/manifest.webmanifest +14 -0
- package/template/public/streaming-client.js +207 -0
- package/template/public/stt.html +68 -0
- package/template/public/stt.js +16 -0
- package/template/public/styles.css +2068 -0
- package/template/public/voice-widget.js +195 -0
- package/template/schema.sql +283 -0
- package/template/src/ai-binding.ts +33 -0
- package/template/src/auth-kdf.ts +106 -0
- package/template/src/auth.ts +315 -0
- package/template/src/chunking.ts +161 -0
- package/template/src/discord.ts +353 -0
- package/template/src/env.ts +55 -0
- package/template/src/gateway-credentials.ts +97 -0
- package/template/src/health-schema.ts +25 -0
- package/template/src/index.ts +4180 -0
- package/template/src/longrun-params.ts +135 -0
- package/template/src/models.ts +214 -0
- package/template/src/output-extract.ts +128 -0
- package/template/src/parsers/anthropic-sse.ts +56 -0
- package/template/src/parsers/gemini-sse.ts +62 -0
- package/template/src/parsers/openai-sse.ts +60 -0
- package/template/src/parsers/sse-framer.ts +39 -0
- package/template/src/parsers/types.ts +16 -0
- package/template/src/parsers/workers-ai-sse.ts +43 -0
- package/template/src/parsers/xai-sse.ts +40 -0
- package/template/src/providers/anthropic.ts +208 -0
- package/template/src/providers/google.ts +150 -0
- package/template/src/providers/openai.ts +69 -0
- package/template/src/providers/workers-ai.ts +83 -0
- package/template/src/providers/xai.ts +159 -0
- package/template/src/proxied-image-params.ts +43 -0
- package/template/src/rate-limit.ts +77 -0
- package/template/src/searxng.ts +75 -0
- package/template/src/session.ts +114 -0
- package/template/src/stt-session.ts +206 -0
- package/template/src/stt-util.ts +19 -0
- package/template/src/types.ts +56 -0
- package/template/src/user-prefs.ts +63 -0
- package/template/src/utils.ts +73 -0
- package/template/src/zip.ts +137 -0
- package/template/tests/anthropic-sse.test.ts +149 -0
- package/template/tests/auth-kdf.test.ts +59 -0
- package/template/tests/auth-unit.test.ts +97 -0
- package/template/tests/chunking.test.ts +217 -0
- package/template/tests/discord.test.ts +184 -0
- package/template/tests/gateway-credentials.test.ts +65 -0
- package/template/tests/gemini-sse.test.ts +75 -0
- package/template/tests/google-gemini.test.ts +65 -0
- package/template/tests/health-schema.test.ts +35 -0
- package/template/tests/longrun-params.test.ts +128 -0
- package/template/tests/openai-sse.test.ts +71 -0
- package/template/tests/output-extract.test.ts +171 -0
- package/template/tests/proxied-image-params.test.ts +51 -0
- package/template/tests/rate-limit.test.ts +45 -0
- package/template/tests/searxng.test.ts +51 -0
- package/template/tests/sse-framer.test.ts +113 -0
- package/template/tests/stt-session.test.ts +35 -0
- package/template/tests/utils.test.ts +39 -0
- package/template/tests/workers-ai-sse.test.ts +67 -0
- package/template/tests/xai-sse.test.ts +60 -0
- package/template/tests/zip.test.ts +145 -0
- package/template/tests-integration/auth.test.ts +371 -0
- package/template/tests-integration/worker.test.ts +322 -0
- package/template/tsconfig.json +18 -0
- package/template/vitest.config.ts +18 -0
- package/template/vitest.node.config.ts +19 -0
- package/template/vitest.workers.config.ts +47 -0
- package/template/wrangler.example.toml +151 -0
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
// DiscordChatExporter (DCE) JSON parsing + conversation-aware chunking (v0.20.3).
|
|
2
|
+
//
|
|
3
|
+
// DCE's JSON export is a single top-level object:
|
|
4
|
+
// {
|
|
5
|
+
// guild: { id, name, iconUrl },
|
|
6
|
+
// channel: { id, type, categoryId, category, name, topic },
|
|
7
|
+
// dateRange: { after, before },
|
|
8
|
+
// exportedAt: "ISO8601",
|
|
9
|
+
// messages: [ { ...per message... } ],
|
|
10
|
+
// messageCount: N
|
|
11
|
+
// }
|
|
12
|
+
//
|
|
13
|
+
// Per message (fields this module relies on):
|
|
14
|
+
// id Discord snowflake (string)
|
|
15
|
+
// type "Default" | "Reply" | system kinds ("ThreadCreated",
|
|
16
|
+
// "ChannelPinnedMessage", "GuildMemberJoin", "Call", ...)
|
|
17
|
+
// timestamp ISO8601 string
|
|
18
|
+
// content message text (markdown-processed when exported WITHOUT
|
|
19
|
+
// --markdown false, which is what we want for RAG: mentions
|
|
20
|
+
// render as @name, custom emoji as :name:)
|
|
21
|
+
// author { id, name, discriminator, nickname, isBot, ... }
|
|
22
|
+
// attachments [ { id, url, fileName, fileSizeBytes } ]
|
|
23
|
+
//
|
|
24
|
+
// Schema verified against the JsonMessageWriter source and the documented
|
|
25
|
+
// CSV column set (AuthorID, Author=FullName, Date, Content, ...) as of the
|
|
26
|
+
// Feb 2026 DCE index. The parser is defensive: it validates the top-level
|
|
27
|
+
// shape on entry and throws a clear error naming the problem rather than
|
|
28
|
+
// producing garbage. Real exports may carry version-specific quirks
|
|
29
|
+
// (migrated usernames with discriminator "0", thread/forum channels as
|
|
30
|
+
// separate channel objects); those are handled below.
|
|
31
|
+
|
|
32
|
+
// ---------- Public types ----------
|
|
33
|
+
|
|
34
|
+
export interface DiscordMessage {
|
|
35
|
+
messageId: string;
|
|
36
|
+
channel: string; // hierarchical channel name (category / name when both present)
|
|
37
|
+
author: string; // display name: nickname when set, else name
|
|
38
|
+
authorId: string | null;
|
|
39
|
+
isBot: boolean;
|
|
40
|
+
sentAt: string; // ISO8601 (raw from the export)
|
|
41
|
+
content: string; // trimmed text content
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface DiscordChunk {
|
|
45
|
+
text: string; // formatted transcript with a channel header
|
|
46
|
+
channel: string;
|
|
47
|
+
authors: string[]; // distinct authors in first-seen order
|
|
48
|
+
sentAtStart: string; // ISO8601 of earliest message in the chunk
|
|
49
|
+
sentAtEnd: string; // ISO8601 of latest message in the chunk
|
|
50
|
+
messageIds: string[]; // source message ids, for traceability
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ParsedDiscordExport {
|
|
54
|
+
guild: string;
|
|
55
|
+
channel: string;
|
|
56
|
+
messages: DiscordMessage[];
|
|
57
|
+
// Counts for the ingestion summary. parsedCount is messages kept after
|
|
58
|
+
// filtering system/empty messages; rawCount is the export's message total.
|
|
59
|
+
rawCount: number;
|
|
60
|
+
parsedCount: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface ChunkOptions {
|
|
64
|
+
gapMinutes?: number; // gap that starts a new conversation unit (default 15)
|
|
65
|
+
targetChars?: number; // soft cap per chunk (default 1000; larger than the
|
|
66
|
+
// 500-char document default since conversation units
|
|
67
|
+
// benefit from more surrounding context)
|
|
68
|
+
includeBots?: boolean; // keep bot messages (default true)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// DCE message `type` values we treat as real conversation content. Everything
|
|
72
|
+
// else (joins, pins, thread-created, calls, recipient add/remove, channel
|
|
73
|
+
// name/icon changes, etc.) is a system notification and is skipped.
|
|
74
|
+
const CONTENT_MESSAGE_TYPES = new Set(["Default", "Reply"]);
|
|
75
|
+
|
|
76
|
+
const DEFAULT_GAP_MINUTES = 15;
|
|
77
|
+
const DEFAULT_TARGET_CHARS = 1000;
|
|
78
|
+
|
|
79
|
+
// ---------- Parser ----------
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Parse a DCE JSON export (already JSON.parse'd into an object) into
|
|
83
|
+
* normalized messages. Throws on a shape that doesn't look like a DCE
|
|
84
|
+
* export, with an error message naming the missing/wrong field so a real
|
|
85
|
+
* export that differs is diagnosable rather than silently mangled.
|
|
86
|
+
*
|
|
87
|
+
* Filtering:
|
|
88
|
+
* - System messages (type not in CONTENT_MESSAGE_TYPES) are dropped.
|
|
89
|
+
* - Messages whose content is empty after trim are dropped (attachment-only
|
|
90
|
+
* or embed-only messages carry no text for retrieval). This is a
|
|
91
|
+
* deliberate v0.20.3 simplification; representing attachments as
|
|
92
|
+
* "[attachment: name]" is a possible future refinement.
|
|
93
|
+
*/
|
|
94
|
+
export function parseDiscordExport(raw: unknown): ParsedDiscordExport {
|
|
95
|
+
if (typeof raw !== "object" || raw === null) {
|
|
96
|
+
throw new Error("Discord export is not a JSON object");
|
|
97
|
+
}
|
|
98
|
+
const obj = raw as Record<string, unknown>;
|
|
99
|
+
|
|
100
|
+
if (!Array.isArray(obj.messages)) {
|
|
101
|
+
throw new Error("Discord export missing 'messages' array (is this a DiscordChatExporter JSON export?)");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const channelName = resolveChannelName(obj.channel);
|
|
105
|
+
const guildName = resolveGuildName(obj.guild);
|
|
106
|
+
|
|
107
|
+
const messages: DiscordMessage[] = [];
|
|
108
|
+
for (const m of obj.messages as unknown[]) {
|
|
109
|
+
if (typeof m !== "object" || m === null) continue;
|
|
110
|
+
const msg = m as Record<string, unknown>;
|
|
111
|
+
|
|
112
|
+
const type = typeof msg.type === "string" ? msg.type : "Default";
|
|
113
|
+
if (!CONTENT_MESSAGE_TYPES.has(type)) continue;
|
|
114
|
+
|
|
115
|
+
const content = typeof msg.content === "string" ? msg.content.trim() : "";
|
|
116
|
+
if (!content) continue;
|
|
117
|
+
|
|
118
|
+
const messageId = typeof msg.id === "string" ? msg.id : String(msg.id ?? "");
|
|
119
|
+
const sentAt = typeof msg.timestamp === "string" ? msg.timestamp : "";
|
|
120
|
+
if (!sentAt) continue; // a message with no timestamp can't be ordered or filtered
|
|
121
|
+
|
|
122
|
+
const author = msg.author;
|
|
123
|
+
let authorName = "Unknown";
|
|
124
|
+
let authorId: string | null = null;
|
|
125
|
+
let isBot = false;
|
|
126
|
+
if (typeof author === "object" && author !== null) {
|
|
127
|
+
const a = author as Record<string, unknown>;
|
|
128
|
+
// Display name: nickname when present and non-empty, else name. The
|
|
129
|
+
// discriminator ("1234", or "0" for migrated usernames) isn't used
|
|
130
|
+
// for display.
|
|
131
|
+
const nickname = typeof a.nickname === "string" ? a.nickname.trim() : "";
|
|
132
|
+
const name = typeof a.name === "string" ? a.name.trim() : "";
|
|
133
|
+
authorName = nickname || name || "Unknown";
|
|
134
|
+
authorId = typeof a.id === "string" ? a.id : (a.id != null ? String(a.id) : null);
|
|
135
|
+
isBot = a.isBot === true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
messages.push({
|
|
139
|
+
messageId,
|
|
140
|
+
channel: channelName,
|
|
141
|
+
author: authorName,
|
|
142
|
+
authorId,
|
|
143
|
+
isBot,
|
|
144
|
+
sentAt,
|
|
145
|
+
content,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
guild: guildName,
|
|
151
|
+
channel: channelName,
|
|
152
|
+
messages,
|
|
153
|
+
rawCount: (obj.messages as unknown[]).length,
|
|
154
|
+
parsedCount: messages.length,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function resolveChannelName(channel: unknown): string {
|
|
159
|
+
if (typeof channel !== "object" || channel === null) return "unknown-channel";
|
|
160
|
+
const c = channel as Record<string, unknown>;
|
|
161
|
+
const name = typeof c.name === "string" ? c.name.trim() : "";
|
|
162
|
+
const category = typeof c.category === "string" ? c.category.trim() : "";
|
|
163
|
+
if (name && category) return `${category} / ${name}`;
|
|
164
|
+
return name || "unknown-channel";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function resolveGuildName(guild: unknown): string {
|
|
168
|
+
if (typeof guild !== "object" || guild === null) return "unknown-guild";
|
|
169
|
+
const g = guild as Record<string, unknown>;
|
|
170
|
+
return typeof g.name === "string" && g.name.trim() ? g.name.trim() : "unknown-guild";
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ---------- Chunker ----------
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Group normalized messages into conversation-aware chunks. A new chunk
|
|
177
|
+
* starts when the channel changes or when the gap since the previous
|
|
178
|
+
* message exceeds gapMinutes. Within a unit, messages are formatted as a
|
|
179
|
+
* readable transcript with a channel header:
|
|
180
|
+
*
|
|
181
|
+
* [#general]
|
|
182
|
+
* Alice (2024-01-15 12:00): what's at the bottom of the shaft?
|
|
183
|
+
* Bob (2024-01-15 12:01): an old transit hub, mostly flooded
|
|
184
|
+
*
|
|
185
|
+
* Units larger than targetChars are split on message boundaries, repeating
|
|
186
|
+
* the channel header on each piece. A single message longer than targetChars
|
|
187
|
+
* is hard-split (its author prefix stays on the first piece only).
|
|
188
|
+
*/
|
|
189
|
+
export function chunkDiscordMessages(
|
|
190
|
+
messages: DiscordMessage[],
|
|
191
|
+
opts: ChunkOptions = {},
|
|
192
|
+
): DiscordChunk[] {
|
|
193
|
+
const gapMinutes = opts.gapMinutes ?? DEFAULT_GAP_MINUTES;
|
|
194
|
+
const targetChars = opts.targetChars ?? DEFAULT_TARGET_CHARS;
|
|
195
|
+
const includeBots = opts.includeBots ?? true;
|
|
196
|
+
|
|
197
|
+
const filtered = includeBots ? messages : messages.filter((m) => !m.isBot);
|
|
198
|
+
if (filtered.length === 0) return [];
|
|
199
|
+
|
|
200
|
+
// Sort by timestamp ascending. DCE exports are already chronological, but
|
|
201
|
+
// be defensive (a hand-merged file might not be). Stable sort on ISO
|
|
202
|
+
// strings is a lexical sort, which is correct for ISO8601.
|
|
203
|
+
const sorted = [...filtered].sort((a, b) => (a.sentAt < b.sentAt ? -1 : a.sentAt > b.sentAt ? 1 : 0));
|
|
204
|
+
|
|
205
|
+
// Partition into conversation units by channel boundary + time gap.
|
|
206
|
+
const units: DiscordMessage[][] = [];
|
|
207
|
+
let current: DiscordMessage[] = [];
|
|
208
|
+
for (const msg of sorted) {
|
|
209
|
+
if (current.length === 0) {
|
|
210
|
+
current.push(msg);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const prev = current[current.length - 1];
|
|
214
|
+
const sameChannel = prev.channel === msg.channel;
|
|
215
|
+
const withinGap = minutesBetween(prev.sentAt, msg.sentAt) <= gapMinutes;
|
|
216
|
+
if (sameChannel && withinGap) {
|
|
217
|
+
current.push(msg);
|
|
218
|
+
} else {
|
|
219
|
+
units.push(current);
|
|
220
|
+
current = [msg];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (current.length) units.push(current);
|
|
224
|
+
|
|
225
|
+
// Format each unit into one or more chunks, splitting on message
|
|
226
|
+
// boundaries when the formatted transcript exceeds targetChars.
|
|
227
|
+
const chunks: DiscordChunk[] = [];
|
|
228
|
+
for (const unit of units) {
|
|
229
|
+
chunks.push(...formatUnit(unit, targetChars));
|
|
230
|
+
}
|
|
231
|
+
return chunks;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function minutesBetween(isoA: string, isoB: string): number {
|
|
235
|
+
const a = Date.parse(isoA);
|
|
236
|
+
const b = Date.parse(isoB);
|
|
237
|
+
if (Number.isNaN(a) || Number.isNaN(b)) return Number.POSITIVE_INFINITY;
|
|
238
|
+
return Math.abs(b - a) / 60000;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Compact, human-readable timestamp for the transcript body: "YYYY-MM-DD HH:MM".
|
|
242
|
+
// The raw ISO timestamp is preserved in chunk metadata; this is display only.
|
|
243
|
+
function formatTimestamp(iso: string): string {
|
|
244
|
+
const t = Date.parse(iso);
|
|
245
|
+
if (Number.isNaN(t)) return iso;
|
|
246
|
+
const d = new Date(t);
|
|
247
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
248
|
+
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function channelHeader(channel: string): string {
|
|
252
|
+
return `[#${channel}]`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Format one conversation unit (all same channel, within-gap messages) into
|
|
257
|
+
* chunks. Lines are "Author (timestamp): content". The channel header leads
|
|
258
|
+
* each chunk. Splits on message boundaries to stay near targetChars; a
|
|
259
|
+
* single oversized message is hard-split.
|
|
260
|
+
*/
|
|
261
|
+
function formatUnit(unit: DiscordMessage[], targetChars: number): DiscordChunk[] {
|
|
262
|
+
const channel = unit[0].channel;
|
|
263
|
+
const header = channelHeader(channel);
|
|
264
|
+
const out: DiscordChunk[] = [];
|
|
265
|
+
|
|
266
|
+
let lines: string[] = [];
|
|
267
|
+
let bufMessages: DiscordMessage[] = [];
|
|
268
|
+
let bufLen = header.length;
|
|
269
|
+
|
|
270
|
+
const flush = () => {
|
|
271
|
+
if (bufMessages.length === 0) return;
|
|
272
|
+
const text = `${header}\n${lines.join("\n")}`;
|
|
273
|
+
out.push(buildChunk(channel, bufMessages, text));
|
|
274
|
+
lines = [];
|
|
275
|
+
bufMessages = [];
|
|
276
|
+
bufLen = header.length;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
for (const msg of unit) {
|
|
280
|
+
const prefix = `${msg.author} (${formatTimestamp(msg.sentAt)}): `;
|
|
281
|
+
const line = prefix + msg.content;
|
|
282
|
+
|
|
283
|
+
// A single message whose line alone exceeds targetChars: flush whatever
|
|
284
|
+
// is buffered, then hard-split this message across its own chunks.
|
|
285
|
+
if (prefix.length + msg.content.length > targetChars) {
|
|
286
|
+
flush();
|
|
287
|
+
const pieces = hardSplit(msg.content, targetChars - prefix.length);
|
|
288
|
+
for (let i = 0; i < pieces.length; i++) {
|
|
289
|
+
const pieceLine = (i === 0 ? prefix : `${msg.author} (cont.): `) + pieces[i];
|
|
290
|
+
const text = `${header}\n${pieceLine}`;
|
|
291
|
+
out.push(buildChunk(channel, [msg], text));
|
|
292
|
+
}
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Starting a new line would overflow the target: flush first.
|
|
297
|
+
if (bufMessages.length > 0 && bufLen + 1 + line.length > targetChars) {
|
|
298
|
+
flush();
|
|
299
|
+
}
|
|
300
|
+
lines.push(line);
|
|
301
|
+
bufMessages.push(msg);
|
|
302
|
+
bufLen += 1 + line.length;
|
|
303
|
+
}
|
|
304
|
+
flush();
|
|
305
|
+
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function buildChunk(channel: string, msgs: DiscordMessage[], text: string): DiscordChunk {
|
|
310
|
+
// Distinct authors in first-seen order.
|
|
311
|
+
const seen = new Set<string>();
|
|
312
|
+
const authors: string[] = [];
|
|
313
|
+
for (const m of msgs) {
|
|
314
|
+
if (!seen.has(m.author)) {
|
|
315
|
+
seen.add(m.author);
|
|
316
|
+
authors.push(m.author);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// Time range across the messages in this chunk (min/max by ISO lexical order).
|
|
320
|
+
let start = msgs[0].sentAt;
|
|
321
|
+
let end = msgs[0].sentAt;
|
|
322
|
+
for (const m of msgs) {
|
|
323
|
+
if (m.sentAt < start) start = m.sentAt;
|
|
324
|
+
if (m.sentAt > end) end = m.sentAt;
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
text,
|
|
328
|
+
channel,
|
|
329
|
+
authors,
|
|
330
|
+
sentAtStart: start,
|
|
331
|
+
sentAtEnd: end,
|
|
332
|
+
messageIds: msgs.map((m) => m.messageId),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Hard-split a long single message's content into <= size pieces, preferring
|
|
337
|
+
// to break on whitespace near the boundary so words aren't sliced.
|
|
338
|
+
function hardSplit(text: string, size: number): string[] {
|
|
339
|
+
if (size <= 0) return [text];
|
|
340
|
+
const out: string[] = [];
|
|
341
|
+
let remaining = text;
|
|
342
|
+
while (remaining.length > size) {
|
|
343
|
+
let cut = size;
|
|
344
|
+
// Look back up to 80 chars for a space to break on.
|
|
345
|
+
const window = remaining.slice(0, size);
|
|
346
|
+
const lastSpace = window.lastIndexOf(" ");
|
|
347
|
+
if (lastSpace > size - 80 && lastSpace > 0) cut = lastSpace;
|
|
348
|
+
out.push(remaining.slice(0, cut).trim());
|
|
349
|
+
remaining = remaining.slice(cut).trim();
|
|
350
|
+
}
|
|
351
|
+
if (remaining) out.push(remaining);
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Worker Env binding (v0.19.0).
|
|
2
|
+
//
|
|
3
|
+
// Extracted from src/index.ts so provider modules (anthropic, xai, google,
|
|
4
|
+
// workers-ai) and future feature modules can import it without circular
|
|
5
|
+
// reference to the worker entry. The runtime binding shape is identical
|
|
6
|
+
// to what wrangler types regenerate from wrangler.toml; this file is the
|
|
7
|
+
// hand-authored interface the worker code references for type checking.
|
|
8
|
+
//
|
|
9
|
+
// Adding a binding: update wrangler.example.toml, regenerate types
|
|
10
|
+
// (`npx wrangler types`), then mirror the new field here. Optional secrets
|
|
11
|
+
// (BYOK keys, gateway tokens) stay optional in this interface so missing-
|
|
12
|
+
// secret runtime paths surface meaningful errors instead of TypeScript
|
|
13
|
+
// telling deployers they need fields they may legitimately not have set.
|
|
14
|
+
|
|
15
|
+
export interface Env {
|
|
16
|
+
AI: Ai;
|
|
17
|
+
DB: D1Database;
|
|
18
|
+
R2: R2Bucket;
|
|
19
|
+
VEC: VectorizeIndex;
|
|
20
|
+
ASSETS: Fetcher;
|
|
21
|
+
// v0.167.0 (issue #80): deployment auth plane. "public" = first-party
|
|
22
|
+
// username/password accounts, session cookie identity, and fail-closed
|
|
23
|
+
// per-user gateway credentials (visitor inference never bills the host).
|
|
24
|
+
// Unset or "access" = trust Cloudflare Access (Cf-Access-Authenticated-User-
|
|
25
|
+
// Email) and keep worker-secret gateway fallback for private self-host.
|
|
26
|
+
// A var, not a secret; set it in wrangler.toml [vars].
|
|
27
|
+
AUTH_MODE?: string;
|
|
28
|
+
GATEWAY_ID?: string;
|
|
29
|
+
// v0.164.0: optional on the worker when running in public demo mode; each
|
|
30
|
+
// user may store their own gateway slug in D1 user_prefs instead.
|
|
31
|
+
// v0.12.0: Workflow binding for Unified Billing video + music gen. The
|
|
32
|
+
// class is LongRunWorkflow, defined at the bottom of src/index.ts. Each
|
|
33
|
+
// instance invokes env.AI.run (long-running), downloads the artifact,
|
|
34
|
+
// uploads to R2, and finalizes the D1 row across retryable steps.
|
|
35
|
+
LONGRUN: Workflow;
|
|
36
|
+
// v0.108.0: per-session Durable Object that wraps a @cf/deepgram/flux
|
|
37
|
+
// conversational STT WebSocket so the final transcript persists to /history
|
|
38
|
+
// on close (a plain Worker has no reliable post-101 hook to write D1). Class
|
|
39
|
+
// SttSession in src/stt-session.ts. One DO instance per session (newUniqueId).
|
|
40
|
+
STT_SESSION: DurableObjectNamespace;
|
|
41
|
+
// Unified Billing auth for Anthropic, xAI, and proxied partners. Bearer token
|
|
42
|
+
// sent as cf-aig-authorization. Also used when Authenticated Gateway is on.
|
|
43
|
+
// v0.164.0: optional on the worker in public demo mode (per-user token in D1).
|
|
44
|
+
CF_AIG_TOKEN?: string;
|
|
45
|
+
// v0.166.0: base URL of the self-hosted SearXNG instance for the optional
|
|
46
|
+
// web-search retrieval source (our deploy: https://search.skyphusion.org).
|
|
47
|
+
// Optional: when unset, the SearXNG source is silently skipped (Wikipedia,
|
|
48
|
+
// which needs no config, still runs). May be a plain [vars] entry or a secret.
|
|
49
|
+
SEARXNG_URL?: string;
|
|
50
|
+
// v0.166.0: Cloudflare Access service-token halves for a gated SearXNG
|
|
51
|
+
// instance. Sent as CF-Access-Client-Id / CF-Access-Client-Secret ONLY when
|
|
52
|
+
// both are set; a self-hoster running an un-gated instance leaves them unset.
|
|
53
|
+
SEARXNG_ACCESS_CLIENT_ID?: string;
|
|
54
|
+
SEARXNG_ACCESS_CLIENT_SECRET?: string;
|
|
55
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Per-user AI Gateway credentials (v0.164.0).
|
|
2
|
+
//
|
|
3
|
+
// Supports two deployment modes:
|
|
4
|
+
// - Deployer secrets: GATEWAY_ID + CF_AIG_TOKEN on the worker (private install)
|
|
5
|
+
// - Public demo: no worker secrets; each user stores their own gateway slug
|
|
6
|
+
// and Cloudflare API token in D1 user_prefs (Unified Billing on their dime)
|
|
7
|
+
//
|
|
8
|
+
// Resolution merges user prefs over worker secrets field-by-field so a partial
|
|
9
|
+
// override still falls back to deployer defaults where unset.
|
|
10
|
+
//
|
|
11
|
+
// v0.167.0 (issue #80): when AUTH_MODE=public the worker secrets are ignored
|
|
12
|
+
// entirely (fail closed). A public deploy must never bill the host for visitor
|
|
13
|
+
// inference, so even a mistakenly-present GATEWAY_ID / CF_AIG_TOKEN is treated
|
|
14
|
+
// as absent: source is only ever "user" or "none", never "worker"/"mixed".
|
|
15
|
+
|
|
16
|
+
import type { Env } from "./env";
|
|
17
|
+
import { loadUserPrefs, type UserPrefsJson } from "./user-prefs";
|
|
18
|
+
|
|
19
|
+
export interface GatewayCredentials {
|
|
20
|
+
gatewayId: string;
|
|
21
|
+
cfAigToken: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type GatewaySource = "user" | "worker" | "mixed" | "none";
|
|
25
|
+
|
|
26
|
+
export interface GatewayStatus {
|
|
27
|
+
configured: boolean;
|
|
28
|
+
source: GatewaySource;
|
|
29
|
+
gateway_id: string | null;
|
|
30
|
+
cf_aig_token_set: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const GATEWAY_NOT_CONFIGURED_MSG =
|
|
34
|
+
"AI Gateway not configured. Open Account > AI Gateway and enter your gateway slug plus a Cloudflare API token with AI Gateway Run permission. Unified Billing charges your Cloudflare account.";
|
|
35
|
+
|
|
36
|
+
export const CF_AIG_TOKEN_REQUIRED_MSG =
|
|
37
|
+
"This model requires a Cloudflare API token with AI Gateway Run permission. Add it under Account > AI Gateway.";
|
|
38
|
+
|
|
39
|
+
// True when this deployment is the public product; worker gateway secrets are
|
|
40
|
+
// then off-limits for billing resolution.
|
|
41
|
+
function isPublic(env: Env): boolean {
|
|
42
|
+
return env.AUTH_MODE === "public";
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function resolveGatewayFromParts(
|
|
46
|
+
prefs: UserPrefsJson | null,
|
|
47
|
+
env: Env,
|
|
48
|
+
): GatewayCredentials | null {
|
|
49
|
+
// Public mode: user prefs only, no worker-secret fallback (fail closed).
|
|
50
|
+
const workerGateway = isPublic(env) ? "" : (env.GATEWAY_ID?.trim() || "");
|
|
51
|
+
const workerToken = isPublic(env) ? "" : (env.CF_AIG_TOKEN?.trim() || "");
|
|
52
|
+
const gatewayId = (prefs?.gateway_id?.trim() || workerGateway);
|
|
53
|
+
const cfAigToken = (prefs?.cf_aig_token?.trim() || workerToken);
|
|
54
|
+
if (!gatewayId) return null;
|
|
55
|
+
return { gatewayId, cfAigToken };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function gatewaySource(prefs: UserPrefsJson | null, env: Env): GatewaySource {
|
|
59
|
+
const hasUserGateway = !!prefs?.gateway_id?.trim();
|
|
60
|
+
const hasUserToken = !!prefs?.cf_aig_token?.trim();
|
|
61
|
+
// Public mode never counts worker secrets: a public deploy resolves to
|
|
62
|
+
// "user" or "none" only, so a stray worker secret cannot read as "worker".
|
|
63
|
+
const hasWorkerGateway = !isPublic(env) && !!env.GATEWAY_ID?.trim();
|
|
64
|
+
const hasWorkerToken = !isPublic(env) && !!env.CF_AIG_TOKEN?.trim();
|
|
65
|
+
|
|
66
|
+
if (hasUserGateway && hasUserToken && !hasWorkerGateway && !hasWorkerToken) return "user";
|
|
67
|
+
if (!hasUserGateway && !hasUserToken && hasWorkerGateway) return "worker";
|
|
68
|
+
if ((hasUserGateway || hasUserToken) && (hasWorkerGateway || hasWorkerToken)) return "mixed";
|
|
69
|
+
if (hasUserGateway || hasUserToken || hasWorkerGateway) return "mixed";
|
|
70
|
+
return "none";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function loadGatewayCredentials(
|
|
74
|
+
env: Env,
|
|
75
|
+
userEmail: string,
|
|
76
|
+
): Promise<GatewayCredentials | null> {
|
|
77
|
+
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
78
|
+
return resolveGatewayFromParts(prefs, env);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function loadGatewayStatus(env: Env, userEmail: string): Promise<GatewayStatus> {
|
|
82
|
+
const prefs = await loadUserPrefs(env.DB, userEmail);
|
|
83
|
+
const resolved = resolveGatewayFromParts(prefs, env);
|
|
84
|
+
return {
|
|
85
|
+
configured: !!resolved?.gatewayId,
|
|
86
|
+
source: gatewaySource(prefs, env),
|
|
87
|
+
gateway_id: resolved?.gatewayId ?? null,
|
|
88
|
+
cf_aig_token_set: !!(resolved?.cfAigToken),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function maskSecret(value: string | undefined): string | null {
|
|
93
|
+
if (!value?.trim()) return null;
|
|
94
|
+
const v = value.trim();
|
|
95
|
+
if (v.length <= 8) return "••••";
|
|
96
|
+
return `${"•".repeat(Math.min(12, v.length - 4))}${v.slice(-4)}`;
|
|
97
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Required D1 tables for a healthy skyphusion-llm deployment (v0.164.3).
|
|
2
|
+
// /health/deep probes these so schema drift (code deployed, migration missed)
|
|
3
|
+
// surfaces in monitoring instead of as opaque HTTP 500s on /api/models.
|
|
4
|
+
|
|
5
|
+
export const REQUIRED_D1_TABLES = [
|
|
6
|
+
"chats",
|
|
7
|
+
"documents",
|
|
8
|
+
"chunks",
|
|
9
|
+
"projects",
|
|
10
|
+
"project_documents",
|
|
11
|
+
"project_messages",
|
|
12
|
+
"user_prefs",
|
|
13
|
+
] as const;
|
|
14
|
+
|
|
15
|
+
export async function probeD1Schema(db: D1Database): Promise<{ ok: boolean; missing: string[] }> {
|
|
16
|
+
const placeholders = REQUIRED_D1_TABLES.map(() => "?").join(", ");
|
|
17
|
+
const rows = await db.prepare(
|
|
18
|
+
`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${placeholders})`,
|
|
19
|
+
)
|
|
20
|
+
.bind(...REQUIRED_D1_TABLES)
|
|
21
|
+
.all<{ name: string }>();
|
|
22
|
+
const present = new Set((rows.results ?? []).map((r) => r.name));
|
|
23
|
+
const missing = REQUIRED_D1_TABLES.filter((t) => !present.has(t));
|
|
24
|
+
return { ok: missing.length === 0, missing: [...missing] };
|
|
25
|
+
}
|