catalyst-ai 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/README.md +30 -0
- package/android/.gradle/8.9/checksums/checksums.lock +0 -0
- package/android/.gradle/8.9/dependencies-accessors/gc.properties +0 -0
- package/android/.gradle/8.9/fileChanges/last-build.bin +0 -0
- package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/8.9/gc.properties +0 -0
- package/android/.gradle/9.2.0/checksums/checksums.lock +0 -0
- package/android/.gradle/9.2.0/fileChanges/last-build.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/9.2.0/gc.properties +0 -0
- package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
- package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/android/build.gradle.kts +47 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/io/catalyst/nativeai/AIBridge.kt +24 -0
- package/android/src/main/java/io/catalyst/nativeai/CatalystAIBridge.kt +79 -0
- package/android/src/main/java/io/catalyst/nativeai/NativeBridgeAI.kt +293 -0
- package/android/src/main/resources/META-INF/services/io.catalyst.nativeai.AIBridge +1 -0
- package/package.json +27 -0
- package/scripts/check-peer.js +11 -0
- package/src/buildAttachmentSystemPrompt.js +19 -0
- package/src/index.js +4 -0
- package/src/metrics.js +210 -0
- package/src/pricing.js +14 -0
- package/src/route.js +529 -0
- package/src/useCloudAI.js +315 -0
- package/src/useNativeAI.js +308 -0
- package/src/useWebAI.js +385 -0
package/src/route.js
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
const express = require("express")
|
|
2
|
+
|
|
3
|
+
const router = express.Router()
|
|
4
|
+
|
|
5
|
+
// Hard ceiling on how long a single /stream request may run upstream — protects
|
|
6
|
+
// against a hung provider connection holding a request open indefinitely.
|
|
7
|
+
const STREAM_TIMEOUT_MS = 120_000
|
|
8
|
+
|
|
9
|
+
// ─── helpers ────────────────────────────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
function getAIConfig() {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(process.env.AI_CONFIG || "{}")
|
|
14
|
+
} catch {
|
|
15
|
+
return {}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function isAIEnabled() {
|
|
20
|
+
return getAIConfig()?.enabled === true
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function getProviderConfig(provider) {
|
|
24
|
+
const cfg = getAIConfig()?.providers?.[provider]
|
|
25
|
+
if (!cfg || !cfg.apiKey) return null
|
|
26
|
+
return cfg
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Returns an error string if the request body is invalid, otherwise null.
|
|
30
|
+
function validateRequestBody(req, cfg) {
|
|
31
|
+
const { messages, model } = req.body ?? {}
|
|
32
|
+
if (!Array.isArray(messages) || messages.length === 0) return "messages must be a non-empty array"
|
|
33
|
+
const resolvedModel = model || cfg.defaultModel
|
|
34
|
+
if (!resolvedModel) return "no model specified and provider has no defaultModel configured"
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sseHeaders(res) {
|
|
39
|
+
res.setHeader("Content-Type", "text/event-stream")
|
|
40
|
+
res.setHeader("Cache-Control", "no-cache")
|
|
41
|
+
res.setHeader("Connection", "keep-alive")
|
|
42
|
+
res.setHeader("X-Accel-Buffering", "no")
|
|
43
|
+
res.flushHeaders()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ─── usage normalization ──────────────────────────────────────────────────────
|
|
47
|
+
// Each provider/API reports token usage under different field names. Normalize
|
|
48
|
+
// to a common shape so the client doesn't need per-provider parsing logic.
|
|
49
|
+
|
|
50
|
+
// NOTE: completionTokens is normalized to mean "visible output only" across all
|
|
51
|
+
// providers/APIs. OpenAI's completion_tokens/output_tokens *include* reasoning
|
|
52
|
+
// tokens (reasoning_tokens is a subset, not additive) — Gemini's
|
|
53
|
+
// candidatesTokenCount *excludes* thoughts (thoughtsTokenCount is additive).
|
|
54
|
+
// Subtracting reasoning out here keeps totalTokens = prompt + completion +
|
|
55
|
+
// reasoning valid for every provider downstream.
|
|
56
|
+
|
|
57
|
+
function normalizeOpenAIChatUsage(usage, model) {
|
|
58
|
+
if (!usage) return null
|
|
59
|
+
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ?? 0
|
|
60
|
+
return {
|
|
61
|
+
model,
|
|
62
|
+
promptTokens: usage.prompt_tokens ?? 0,
|
|
63
|
+
cachedTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
|
|
64
|
+
completionTokens: (usage.completion_tokens ?? 0) - reasoningTokens,
|
|
65
|
+
reasoningTokens,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function normalizeOpenAIResponsesUsage(usage, model) {
|
|
70
|
+
if (!usage) return null
|
|
71
|
+
const reasoningTokens = usage.output_tokens_details?.reasoning_tokens ?? 0
|
|
72
|
+
return {
|
|
73
|
+
model,
|
|
74
|
+
promptTokens: usage.input_tokens ?? 0,
|
|
75
|
+
cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
|
|
76
|
+
completionTokens: (usage.output_tokens ?? 0) - reasoningTokens,
|
|
77
|
+
reasoningTokens,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// stateless generateContent / streamGenerateContent
|
|
82
|
+
function normalizeGeminiUsage(usageMetadata, model) {
|
|
83
|
+
if (!usageMetadata) return null
|
|
84
|
+
return {
|
|
85
|
+
model,
|
|
86
|
+
promptTokens: usageMetadata.promptTokenCount ?? 0,
|
|
87
|
+
cachedTokens: usageMetadata.cachedContentTokenCount ?? 0,
|
|
88
|
+
completionTokens: usageMetadata.candidatesTokenCount ?? 0,
|
|
89
|
+
reasoningTokens: usageMetadata.thoughtsTokenCount ?? 0,
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// stateful Interactions API — different field names entirely (verified live against v1beta/interactions)
|
|
94
|
+
function normalizeGeminiInteractionUsage(usage, model) {
|
|
95
|
+
if (!usage) return null
|
|
96
|
+
return {
|
|
97
|
+
model,
|
|
98
|
+
promptTokens: usage.total_input_tokens ?? 0,
|
|
99
|
+
cachedTokens: usage.total_cached_tokens ?? 0,
|
|
100
|
+
completionTokens: usage.total_output_tokens ?? 0,
|
|
101
|
+
reasoningTokens: usage.total_thought_tokens ?? 0,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ─── OpenAI adapters ─────────────────────────────────────────────────────────
|
|
106
|
+
|
|
107
|
+
async function openaiStream({ apiKey, model, messages, genConfig, conversationId, stateful, res, signal }) {
|
|
108
|
+
if (stateful) {
|
|
109
|
+
// stateful: Responses API
|
|
110
|
+
const endpoint = "https://api.openai.com/v1/responses"
|
|
111
|
+
const body = {
|
|
112
|
+
model,
|
|
113
|
+
input: messages,
|
|
114
|
+
stream: true,
|
|
115
|
+
...(conversationId && { previous_response_id: conversationId }),
|
|
116
|
+
...(genConfig?.maxTokens && { max_output_tokens: genConfig.maxTokens }),
|
|
117
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
118
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
119
|
+
context_management: [{ type: "compaction", compact_threshold: 80000 }],
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const response = await fetch(endpoint, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
|
|
125
|
+
body: JSON.stringify(body),
|
|
126
|
+
signal,
|
|
127
|
+
})
|
|
128
|
+
if (!response.ok) throw new Error(`OpenAI Responses API error (${response.status}): ${await response.text()}`)
|
|
129
|
+
|
|
130
|
+
const reader = response.body.getReader()
|
|
131
|
+
const decoder = new TextDecoder()
|
|
132
|
+
let buffer = ""
|
|
133
|
+
let sentConversationId = false
|
|
134
|
+
|
|
135
|
+
while (true) {
|
|
136
|
+
const { done, value } = await reader.read()
|
|
137
|
+
if (done) break
|
|
138
|
+
buffer += decoder.decode(value, { stream: true })
|
|
139
|
+
const lines = buffer.split("\n")
|
|
140
|
+
buffer = lines.pop() || ""
|
|
141
|
+
for (const line of lines) {
|
|
142
|
+
const trimmed = line.trim()
|
|
143
|
+
if (!trimmed || !trimmed.startsWith("data:")) continue
|
|
144
|
+
const payload = trimmed.slice(5).trim()
|
|
145
|
+
if (payload === "[DONE]") { res.write("data: [DONE]\n\n"); res.end(); return }
|
|
146
|
+
try {
|
|
147
|
+
const parsed = JSON.parse(payload)
|
|
148
|
+
if (!sentConversationId && parsed.type === "response.created" && parsed.response?.id) {
|
|
149
|
+
res.write(`data: ${JSON.stringify({ conversationId: parsed.response.id })}\n\n`)
|
|
150
|
+
sentConversationId = true
|
|
151
|
+
}
|
|
152
|
+
if (parsed.type === "response.output_text.delta" && parsed.delta != null) {
|
|
153
|
+
res.write(`data: ${JSON.stringify({ token: parsed.delta })}\n\n`)
|
|
154
|
+
}
|
|
155
|
+
if (parsed.type === "response.completed" && parsed.response?.usage) {
|
|
156
|
+
const usage = normalizeOpenAIResponsesUsage(parsed.response.usage, model)
|
|
157
|
+
if (usage) res.write(`data: ${JSON.stringify({ usage })}\n\n`)
|
|
158
|
+
}
|
|
159
|
+
} catch (_) {}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
} else {
|
|
163
|
+
// stateless: Chat Completions
|
|
164
|
+
const endpoint = "https://api.openai.com/v1/chat/completions"
|
|
165
|
+
const body = {
|
|
166
|
+
model,
|
|
167
|
+
messages,
|
|
168
|
+
stream: true,
|
|
169
|
+
stream_options: { include_usage: true },
|
|
170
|
+
...(genConfig?.maxTokens && { max_tokens: genConfig.maxTokens }),
|
|
171
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
172
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const response = await fetch(endpoint, {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
|
|
178
|
+
body: JSON.stringify(body),
|
|
179
|
+
signal,
|
|
180
|
+
})
|
|
181
|
+
if (!response.ok) throw new Error(`OpenAI API error (${response.status}): ${await response.text()}`)
|
|
182
|
+
|
|
183
|
+
const reader = response.body.getReader()
|
|
184
|
+
const decoder = new TextDecoder()
|
|
185
|
+
let buffer = ""
|
|
186
|
+
|
|
187
|
+
while (true) {
|
|
188
|
+
const { done, value } = await reader.read()
|
|
189
|
+
if (done) break
|
|
190
|
+
buffer += decoder.decode(value, { stream: true })
|
|
191
|
+
const lines = buffer.split("\n")
|
|
192
|
+
buffer = lines.pop() || ""
|
|
193
|
+
for (const line of lines) {
|
|
194
|
+
const trimmed = line.trim()
|
|
195
|
+
if (!trimmed || !trimmed.startsWith("data:")) continue
|
|
196
|
+
const payload = trimmed.slice(5).trim()
|
|
197
|
+
if (payload === "[DONE]") { res.write("data: [DONE]\n\n"); res.end(); return }
|
|
198
|
+
try {
|
|
199
|
+
const parsed = JSON.parse(payload)
|
|
200
|
+
const token = parsed.choices?.[0]?.delta?.content
|
|
201
|
+
if (token != null) res.write(`data: ${JSON.stringify({ token })}\n\n`)
|
|
202
|
+
if (parsed.usage) {
|
|
203
|
+
const usage = normalizeOpenAIChatUsage(parsed.usage, model)
|
|
204
|
+
if (usage) res.write(`data: ${JSON.stringify({ usage })}\n\n`)
|
|
205
|
+
}
|
|
206
|
+
} catch (_) {}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
res.write("data: [DONE]\n\n")
|
|
212
|
+
res.end()
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function openaiGenerate({ apiKey, model, messages, genConfig, conversationId, stateful }) {
|
|
216
|
+
if (stateful) {
|
|
217
|
+
const endpoint = "https://api.openai.com/v1/responses"
|
|
218
|
+
const body = {
|
|
219
|
+
model,
|
|
220
|
+
input: messages,
|
|
221
|
+
stream: false,
|
|
222
|
+
...(conversationId && { previous_response_id: conversationId }),
|
|
223
|
+
...(genConfig?.maxTokens && { max_output_tokens: genConfig.maxTokens }),
|
|
224
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
225
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
226
|
+
}
|
|
227
|
+
const response = await fetch(endpoint, {
|
|
228
|
+
method: "POST",
|
|
229
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
|
|
230
|
+
body: JSON.stringify(body),
|
|
231
|
+
})
|
|
232
|
+
if (!response.ok) throw new Error(`OpenAI Responses API error (${response.status}): ${await response.text()}`)
|
|
233
|
+
const data = await response.json()
|
|
234
|
+
const output = data.output?.find((o) => o.type === "message")?.content?.find((c) => c.type === "output_text")?.text ?? ""
|
|
235
|
+
return { output, conversationId: data.id ?? null, usage: normalizeOpenAIResponsesUsage(data.usage, model) }
|
|
236
|
+
} else {
|
|
237
|
+
const endpoint = "https://api.openai.com/v1/chat/completions"
|
|
238
|
+
const body = {
|
|
239
|
+
model,
|
|
240
|
+
messages,
|
|
241
|
+
stream: false,
|
|
242
|
+
...(genConfig?.maxTokens && { max_tokens: genConfig.maxTokens }),
|
|
243
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
244
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
245
|
+
}
|
|
246
|
+
const response = await fetch(endpoint, {
|
|
247
|
+
method: "POST",
|
|
248
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
|
|
249
|
+
body: JSON.stringify(body),
|
|
250
|
+
})
|
|
251
|
+
if (!response.ok) throw new Error(`OpenAI API error (${response.status}): ${await response.text()}`)
|
|
252
|
+
const data = await response.json()
|
|
253
|
+
return { output: data.choices?.[0]?.message?.content ?? "", conversationId: null, usage: normalizeOpenAIChatUsage(data.usage, model) }
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ─── Gemini adapters ──────────────────────────────────────────────────────────
|
|
258
|
+
|
|
259
|
+
function toGeminiContents(messages) {
|
|
260
|
+
return messages
|
|
261
|
+
.filter((m) => m.role !== "system")
|
|
262
|
+
.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: [{ text: m.content }] }))
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function geminiSystemInstruction(messages) {
|
|
266
|
+
const sys = messages.find((m) => m.role === "system")
|
|
267
|
+
return sys ? { parts: [{ text: sys.content }] } : undefined
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Interactions API (v1beta/interactions) takes system_instruction as a plain string —
|
|
271
|
+
// unlike generateContent/streamGenerateContent, which need { parts: [{ text }] }.
|
|
272
|
+
// Confirmed via live 400: "Expected string, unexpected character: '{'"
|
|
273
|
+
function geminiInteractionsSystemInstruction(messages) {
|
|
274
|
+
const sys = messages.find((m) => m.role === "system")
|
|
275
|
+
return sys ? sys.content : undefined
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function geminiStream({ apiKey, model, messages, genConfig, conversationId, stateful, res, signal }) {
|
|
279
|
+
if (stateful) {
|
|
280
|
+
// stateful: Interactions API (v1beta2)
|
|
281
|
+
const endpoint = "https://generativelanguage.googleapis.com/v1beta/interactions"
|
|
282
|
+
const sys = geminiInteractionsSystemInstruction(messages)
|
|
283
|
+
const lastUserMsg = [...messages].reverse().find((m) => m.role === "user")?.content ?? ""
|
|
284
|
+
const body = {
|
|
285
|
+
model: `models/${model}`,
|
|
286
|
+
input: lastUserMsg,
|
|
287
|
+
stream: true,
|
|
288
|
+
...(conversationId && { previous_interaction_id: conversationId }),
|
|
289
|
+
...(sys && { system_instruction: sys }),
|
|
290
|
+
generation_config: {
|
|
291
|
+
...(genConfig?.maxTokens && { max_output_tokens: genConfig.maxTokens }),
|
|
292
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
293
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
294
|
+
},
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const response = await fetch(endpoint, {
|
|
298
|
+
method: "POST",
|
|
299
|
+
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
|
|
300
|
+
body: JSON.stringify(body),
|
|
301
|
+
signal,
|
|
302
|
+
})
|
|
303
|
+
if (!response.ok) throw new Error(`Gemini Interactions API error (${response.status}): ${await response.text()}`)
|
|
304
|
+
|
|
305
|
+
const reader = response.body.getReader()
|
|
306
|
+
const decoder = new TextDecoder()
|
|
307
|
+
let buffer = ""
|
|
308
|
+
|
|
309
|
+
while (true) {
|
|
310
|
+
const { done, value } = await reader.read()
|
|
311
|
+
if (done) break
|
|
312
|
+
buffer += decoder.decode(value, { stream: true })
|
|
313
|
+
const lines = buffer.split("\n")
|
|
314
|
+
buffer = lines.pop() || ""
|
|
315
|
+
for (const line of lines) {
|
|
316
|
+
const trimmed = line.trim()
|
|
317
|
+
if (!trimmed || !trimmed.startsWith("data:")) continue
|
|
318
|
+
const payload = trimmed.slice(5).trim()
|
|
319
|
+
if (payload === "[DONE]") { res.write("data: [DONE]\n\n"); res.end(); return }
|
|
320
|
+
try {
|
|
321
|
+
const parsed = JSON.parse(payload)
|
|
322
|
+
if (parsed.event_type === "step.delta" && parsed.delta?.type === "text" && parsed.delta.text) {
|
|
323
|
+
res.write(`data: ${JSON.stringify({ token: parsed.delta.text })}\n\n`)
|
|
324
|
+
}
|
|
325
|
+
if (parsed.event_type === "interaction.completed" && parsed.interaction?.id) {
|
|
326
|
+
console.log(`[catalyst-ai] gemini session id: ${parsed.interaction.id}`)
|
|
327
|
+
res.write(`data: ${JSON.stringify({ conversationId: parsed.interaction.id })}\n\n`)
|
|
328
|
+
const usage = normalizeGeminiInteractionUsage(parsed.interaction?.usage, model)
|
|
329
|
+
if (usage) res.write(`data: ${JSON.stringify({ usage })}\n\n`)
|
|
330
|
+
}
|
|
331
|
+
} catch (_) {}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
} else {
|
|
335
|
+
// stateless: streamGenerateContent
|
|
336
|
+
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse`
|
|
337
|
+
const sys = geminiSystemInstruction(messages)
|
|
338
|
+
const body = {
|
|
339
|
+
contents: toGeminiContents(messages),
|
|
340
|
+
...(sys && { system_instruction: sys }),
|
|
341
|
+
generationConfig: {
|
|
342
|
+
...(genConfig?.maxTokens && { maxOutputTokens: genConfig.maxTokens }),
|
|
343
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
344
|
+
...(genConfig?.topP != null && { topP: genConfig.topP }),
|
|
345
|
+
},
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const response = await fetch(endpoint, {
|
|
349
|
+
method: "POST",
|
|
350
|
+
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
|
|
351
|
+
body: JSON.stringify(body),
|
|
352
|
+
signal,
|
|
353
|
+
})
|
|
354
|
+
if (!response.ok) throw new Error(`Gemini API error (${response.status}): ${await response.text()}`)
|
|
355
|
+
|
|
356
|
+
const reader = response.body.getReader()
|
|
357
|
+
const decoder = new TextDecoder()
|
|
358
|
+
let buffer = ""
|
|
359
|
+
|
|
360
|
+
while (true) {
|
|
361
|
+
const { done, value } = await reader.read()
|
|
362
|
+
if (done) break
|
|
363
|
+
buffer += decoder.decode(value, { stream: true })
|
|
364
|
+
const lines = buffer.split("\n")
|
|
365
|
+
buffer = lines.pop() || ""
|
|
366
|
+
for (const line of lines) {
|
|
367
|
+
const trimmed = line.trim()
|
|
368
|
+
if (!trimmed || !trimmed.startsWith("data:")) continue
|
|
369
|
+
const payload = trimmed.slice(5).trim()
|
|
370
|
+
if (payload === "[DONE]") { res.write("data: [DONE]\n\n"); res.end(); return }
|
|
371
|
+
try {
|
|
372
|
+
const parsed = JSON.parse(payload)
|
|
373
|
+
const token = parsed.candidates?.[0]?.content?.parts?.[0]?.text
|
|
374
|
+
if (token != null) res.write(`data: ${JSON.stringify({ token })}\n\n`)
|
|
375
|
+
if (parsed.usageMetadata) {
|
|
376
|
+
const usage = normalizeGeminiUsage(parsed.usageMetadata, model)
|
|
377
|
+
if (usage) res.write(`data: ${JSON.stringify({ usage })}\n\n`)
|
|
378
|
+
}
|
|
379
|
+
} catch (_) {}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
res.write("data: [DONE]\n\n")
|
|
385
|
+
res.end()
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function geminiGenerate({ apiKey, model, messages, genConfig, conversationId, stateful }) {
|
|
389
|
+
if (stateful) {
|
|
390
|
+
// stateful non-streaming: Interactions API (v1beta2)
|
|
391
|
+
const endpoint = "https://generativelanguage.googleapis.com/v1beta/interactions"
|
|
392
|
+
const sys = geminiInteractionsSystemInstruction(messages)
|
|
393
|
+
const lastUserMsg = [...messages].reverse().find((m) => m.role === "user")?.content ?? ""
|
|
394
|
+
const body = {
|
|
395
|
+
model: `models/${model}`,
|
|
396
|
+
input: lastUserMsg,
|
|
397
|
+
stream: false,
|
|
398
|
+
...(conversationId && { previous_interaction_id: conversationId }),
|
|
399
|
+
...(sys && { system_instruction: sys }),
|
|
400
|
+
generation_config: {
|
|
401
|
+
...(genConfig?.maxTokens && { max_output_tokens: genConfig.maxTokens }),
|
|
402
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
403
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
404
|
+
},
|
|
405
|
+
}
|
|
406
|
+
const response = await fetch(endpoint, {
|
|
407
|
+
method: "POST",
|
|
408
|
+
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
|
|
409
|
+
body: JSON.stringify(body),
|
|
410
|
+
})
|
|
411
|
+
if (!response.ok) throw new Error(`Gemini Interactions API error (${response.status}): ${await response.text()}`)
|
|
412
|
+
const data = await response.json()
|
|
413
|
+
const text = data.steps?.find((s) => s.type === "model_output")?.content?.[0]?.text ?? ""
|
|
414
|
+
return { output: text, conversationId: data.id ?? null, usage: normalizeGeminiInteractionUsage(data.usage, model) }
|
|
415
|
+
} else {
|
|
416
|
+
// stateless non-streaming: generateContent
|
|
417
|
+
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`
|
|
418
|
+
const sys = geminiSystemInstruction(messages)
|
|
419
|
+
const body = {
|
|
420
|
+
contents: toGeminiContents(messages),
|
|
421
|
+
...(sys && { system_instruction: sys }),
|
|
422
|
+
generationConfig: {
|
|
423
|
+
...(genConfig?.maxTokens && { maxOutputTokens: genConfig.maxTokens }),
|
|
424
|
+
...(genConfig?.temperature != null && { temperature: genConfig.temperature }),
|
|
425
|
+
...(genConfig?.topP != null && { top_p: genConfig.topP }),
|
|
426
|
+
},
|
|
427
|
+
}
|
|
428
|
+
const response = await fetch(endpoint, {
|
|
429
|
+
method: "POST",
|
|
430
|
+
headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
|
|
431
|
+
body: JSON.stringify(body),
|
|
432
|
+
})
|
|
433
|
+
if (!response.ok) throw new Error(`Gemini API error (${response.status}): ${await response.text()}`)
|
|
434
|
+
const data = await response.json()
|
|
435
|
+
return { output: data.candidates?.[0]?.content?.parts?.[0]?.text ?? "", conversationId: null, usage: normalizeGeminiUsage(data.usageMetadata, model) }
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ─── provider registry ────────────────────────────────────────────────────────
|
|
440
|
+
|
|
441
|
+
const PROVIDERS = {
|
|
442
|
+
openai: { stream: openaiStream, generate: openaiGenerate },
|
|
443
|
+
gemini: { stream: geminiStream, generate: geminiGenerate },
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// ─── routes ───────────────────────────────────────────────────────────────────
|
|
447
|
+
|
|
448
|
+
// GET /ai/providers — returns list of configured provider ids, no keys exposed
|
|
449
|
+
router.get("/providers", (req, res) => {
|
|
450
|
+
if (!isAIEnabled()) { res.status(403).json({ error: "AI is disabled. Set AI_CONFIG.enabled=true to enable." }); return }
|
|
451
|
+
const providers = Object.entries(getAIConfig()?.providers ?? {})
|
|
452
|
+
.filter(([, cfg]) => cfg?.apiKey)
|
|
453
|
+
.map(([id, cfg]) => ({ id, defaultModel: cfg.defaultModel ?? null }))
|
|
454
|
+
res.json({ providers })
|
|
455
|
+
})
|
|
456
|
+
|
|
457
|
+
router.post("/:provider/stream", async (req, res) => {
|
|
458
|
+
if (!isAIEnabled()) { res.status(403).json({ error: "AI is disabled. Set AI_CONFIG.enabled=true to enable." }); return }
|
|
459
|
+
const { provider } = req.params
|
|
460
|
+
const adapter = PROVIDERS[provider]
|
|
461
|
+
if (!adapter) { res.status(404).json({ error: `Unknown provider: ${provider}` }); return }
|
|
462
|
+
|
|
463
|
+
const cfg = getProviderConfig(provider)
|
|
464
|
+
if (!cfg) { res.status(404).json({ error: `Provider "${provider}" not configured` }); return }
|
|
465
|
+
|
|
466
|
+
const validationError = validateRequestBody(req, cfg)
|
|
467
|
+
if (validationError) { res.status(400).json({ error: validationError }); return }
|
|
468
|
+
|
|
469
|
+
const { messages, genConfig = {}, conversationId, model } = req.body
|
|
470
|
+
const stateful = "conversationId" in req.body
|
|
471
|
+
const resolvedModel = model || cfg.defaultModel
|
|
472
|
+
|
|
473
|
+
const abortController = new AbortController()
|
|
474
|
+
const timeout = setTimeout(() => abortController.abort(), STREAM_TIMEOUT_MS)
|
|
475
|
+
// res "close" fires when the response socket actually closes (client disconnect
|
|
476
|
+
// or response finished) — req "close" fires as soon as the request body has been
|
|
477
|
+
// fully read, which for a small JSON POST body happens almost immediately and
|
|
478
|
+
// would abort the stream before it starts.
|
|
479
|
+
res.on("close", () => abortController.abort())
|
|
480
|
+
|
|
481
|
+
sseHeaders(res)
|
|
482
|
+
try {
|
|
483
|
+
await adapter.stream({
|
|
484
|
+
apiKey: cfg.apiKey,
|
|
485
|
+
model: resolvedModel,
|
|
486
|
+
messages,
|
|
487
|
+
genConfig,
|
|
488
|
+
conversationId,
|
|
489
|
+
stateful,
|
|
490
|
+
res,
|
|
491
|
+
signal: abortController.signal,
|
|
492
|
+
})
|
|
493
|
+
} catch (err) {
|
|
494
|
+
console.error("[catalyst-ai] %s stream error:", provider, err.message)
|
|
495
|
+
if (!res.writableEnded) {
|
|
496
|
+
res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`)
|
|
497
|
+
res.end()
|
|
498
|
+
}
|
|
499
|
+
} finally {
|
|
500
|
+
clearTimeout(timeout)
|
|
501
|
+
}
|
|
502
|
+
})
|
|
503
|
+
|
|
504
|
+
router.post("/:provider/generate", async (req, res) => {
|
|
505
|
+
if (!isAIEnabled()) { res.status(403).json({ error: "AI is disabled. Set AI_CONFIG.enabled=true to enable." }); return }
|
|
506
|
+
const { provider } = req.params
|
|
507
|
+
const adapter = PROVIDERS[provider]
|
|
508
|
+
if (!adapter) { res.status(404).json({ error: `Unknown provider: ${provider}` }); return }
|
|
509
|
+
|
|
510
|
+
const cfg = getProviderConfig(provider)
|
|
511
|
+
if (!cfg) { res.status(404).json({ error: `Provider "${provider}" not configured` }); return }
|
|
512
|
+
|
|
513
|
+
const validationError = validateRequestBody(req, cfg)
|
|
514
|
+
if (validationError) { res.status(400).json({ error: validationError }); return }
|
|
515
|
+
|
|
516
|
+
const { messages, genConfig = {}, conversationId, model } = req.body
|
|
517
|
+
const stateful = "conversationId" in req.body
|
|
518
|
+
const resolvedModel = model || cfg.defaultModel
|
|
519
|
+
|
|
520
|
+
try {
|
|
521
|
+
const result = await adapter.generate({ apiKey: cfg.apiKey, model: resolvedModel, messages, genConfig, conversationId, stateful })
|
|
522
|
+
res.json({ ...result, model: resolvedModel })
|
|
523
|
+
} catch (err) {
|
|
524
|
+
console.error("[catalyst-ai] %s generate error:", provider, err.message)
|
|
525
|
+
res.status(500).json({ error: err.message })
|
|
526
|
+
}
|
|
527
|
+
})
|
|
528
|
+
|
|
529
|
+
module.exports = router
|