@burtson-labs/bandit-cli 0.0.0-stage → 1.2.1

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/dist/cli.js ADDED
@@ -0,0 +1,4448 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/index.ts
27
+ var import_node_path3 = __toESM(require("path"));
28
+ var import_commander = require("commander");
29
+
30
+ // package.json
31
+ var package_default = {
32
+ name: "@burtson-labs/bandit-cli",
33
+ version: "1.2.1",
34
+ license: "Apache-2.0",
35
+ description: "CLI scaffolding tool for Bandit Engine quickstart projects",
36
+ bin: {
37
+ bandit: "dist/cli.js"
38
+ },
39
+ engines: {
40
+ node: ">=18.17"
41
+ },
42
+ files: [
43
+ "dist",
44
+ "CHANGELOG.md",
45
+ "LICENSE",
46
+ "NOTICE",
47
+ "README.md"
48
+ ],
49
+ repository: {
50
+ type: "git",
51
+ url: "https://github.com/Burtson-Labs/bandit-engine.git"
52
+ },
53
+ homepage: "https://banditailabs.com/npm-package",
54
+ author: "Burtson Labs LLC <team@banditai.ai>",
55
+ keywords: [
56
+ "bandit",
57
+ "cli",
58
+ "scaffold",
59
+ "ai",
60
+ "quickstart"
61
+ ],
62
+ scripts: {
63
+ build: "tsup",
64
+ dev: "tsup --watch",
65
+ protect: "node scripts/add-license-headers.js",
66
+ "validate-protection": "node scripts/validate-protection.js"
67
+ },
68
+ dependencies: {
69
+ commander: "^12.1.0",
70
+ "fs-extra": "^11.3.0",
71
+ prompts: "^2.4.2"
72
+ },
73
+ devDependencies: {
74
+ "@types/fs-extra": "^11.0.4",
75
+ "@types/node": "^24.0.3",
76
+ "@types/prompts": "^2.4.9",
77
+ tsup: "^8.5.0",
78
+ typescript: "5.5.4"
79
+ }
80
+ };
81
+
82
+ // src/createQuickstart.ts
83
+ var import_node_path2 = __toESM(require("path"));
84
+ var import_fs_extra = __toESM(require("fs-extra"));
85
+ var import_prompts = __toESM(require("prompts"));
86
+
87
+ // src/utils.ts
88
+ var import_node_path = __toESM(require("path"));
89
+ var toKebabCase = (value) => {
90
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[\s_./]+/g, "-").replace(/[^a-zA-Z0-9-]+/g, "").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
91
+ };
92
+ var toTitleCase = (value) => {
93
+ const cleaned = value.replace(/[-_/]+/g, " ").replace(/\s+/g, " ").trim();
94
+ if (!cleaned) {
95
+ return "";
96
+ }
97
+ return cleaned.replace(/\b\w/g, (char) => char.toUpperCase());
98
+ };
99
+ var formatJson = (value) => `${JSON.stringify(value, null, 2)}
100
+ `;
101
+ var KNOWN_PROVIDERS = /* @__PURE__ */ new Set(["openai", "azure", "azure-openai", "azureopenai", "anthropic", "xai", "ollama"]);
102
+ var sanitizeModelIdentifier = (value) => {
103
+ const trimmed = value.trim();
104
+ if (!trimmed.includes(":")) {
105
+ return trimmed.toLowerCase();
106
+ }
107
+ const segments = trimmed.split(/:(.+)/).filter(Boolean);
108
+ if (segments.length < 2) {
109
+ return trimmed.toLowerCase();
110
+ }
111
+ const [candidateProvider, rest] = segments;
112
+ const provider = candidateProvider.toLowerCase();
113
+ const cleanRest = rest.trim().replace(/[^a-zA-Z0-9_./:-]/g, "-").replace(/-+/g, "-").toLowerCase();
114
+ if (KNOWN_PROVIDERS.has(provider)) {
115
+ if (provider === "azure-openai" || provider === "azureopenai") {
116
+ return `azure:${cleanRest}`;
117
+ }
118
+ if (provider === "ollama") {
119
+ return cleanRest;
120
+ }
121
+ return `${provider}:${cleanRest}`;
122
+ }
123
+ return [candidateProvider, rest].filter(Boolean).join(":").replace(/[^a-zA-Z0-9_./:-]/g, "-").replace(/-+/g, "-").toLowerCase();
124
+ };
125
+ var normalizeLineEndings = (content) => content.replace(/\r\n/g, "\n");
126
+ var ensureTrailingNewline = (content) => content.endsWith("\n") ? content : `${content}
127
+ `;
128
+
129
+ // src/templates.ts
130
+ var QUOTE = '"';
131
+ var buildPackageJson = (ctx) => formatJson({
132
+ name: ctx.packageName,
133
+ private: true,
134
+ version: "0.1.0",
135
+ type: "module",
136
+ scripts: {
137
+ dev: 'concurrently -k "npm run dev:gateway" "npm run dev:web"',
138
+ "dev:web": "vite",
139
+ "dev:gateway": "node server/gateway.js",
140
+ build: "vite build",
141
+ preview: "vite preview"
142
+ },
143
+ dependencies: {
144
+ "@burtson-labs/bandit-engine": `^${ctx.engineVersion}`,
145
+ "@emotion/react": "^11.14.0",
146
+ "@emotion/styled": "^11.14.0",
147
+ "@mui/material": "^7.1.0",
148
+ "@tanstack/react-query": "^5.59.20",
149
+ "dotenv": "^16.4.5",
150
+ "express": "^4.19.2",
151
+ "react": "^19.0.0",
152
+ "react-dom": "^19.0.0",
153
+ "react-router-dom": "^7.5.0",
154
+ "zustand": "^4.5.6"
155
+ },
156
+ devDependencies: {
157
+ "@types/express": "^4.17.21",
158
+ "@types/node": "^20.17.7",
159
+ "@types/react": "^19.0.0",
160
+ "@types/react-dom": "^19.0.0",
161
+ "@vitejs/plugin-react": "^5.0.0",
162
+ "concurrently": "^8.2.2",
163
+ "typescript": "^5.5.4",
164
+ "vite": "^7.1.9"
165
+ }
166
+ });
167
+ var buildEnvExample = (ctx) => {
168
+ const lines = [
169
+ "# Frontend configuration",
170
+ `VITE_DEV_PORT=${ctx.frontendPort}`,
171
+ `VITE_GATEWAY_URL=${ctx.defaultGatewayUrl}`,
172
+ `VITE_DEFAULT_MODEL=${ctx.defaultModelId}`,
173
+ `VITE_FALLBACK_MODEL=${ctx.fallbackModelId ?? ""}`,
174
+ `VITE_GATEWAY_PROVIDER=${ctx.defaultProvider}`,
175
+ `VITE_BRANDING_TEXT=${ctx.brandingText}`,
176
+ "",
177
+ "# Gateway configuration",
178
+ "# These values power server/gateway.js \u2014 update them before running in production."
179
+ ];
180
+ switch (ctx.defaultProvider) {
181
+ case "openai":
182
+ lines.push("OPENAI_API_KEY=");
183
+ break;
184
+ case "azure":
185
+ lines.push("AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com");
186
+ lines.push("AZURE_OPENAI_API_KEY=");
187
+ lines.push("AZURE_OPENAI_API_VERSION=2024-08-01-preview");
188
+ lines.push("AZURE_OPENAI_CHAT_DEPLOYMENT=gpt-4o");
189
+ lines.push("AZURE_OPENAI_COMPLETIONS_DEPLOYMENT=gpt-35-turbo-instruct");
190
+ lines.push("AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT=text-embedding-3-large");
191
+ break;
192
+ case "anthropic":
193
+ lines.push("ANTHROPIC_API_KEY=");
194
+ lines.push("ANTHROPIC_BASE_URL=https://api.anthropic.com");
195
+ lines.push("ANTHROPIC_API_VERSION=2023-06-01");
196
+ lines.push("ANTHROPIC_MAX_TOKENS=1024");
197
+ break;
198
+ case "xai":
199
+ lines.push("XAI_API_KEY=");
200
+ lines.push("XAI_BASE_URL=https://api.x.ai/v1");
201
+ break;
202
+ case "bandit":
203
+ lines.push("BANDIT_API_KEY=");
204
+ lines.push("BANDIT_BASE_URL=https://api.burtson.ai");
205
+ break;
206
+ case "ollama":
207
+ default:
208
+ lines.push("OLLAMA_URL=http://localhost:11434");
209
+ break;
210
+ }
211
+ lines.push(`PORT=${ctx.gatewayPort}`);
212
+ lines.push(
213
+ "# If you switch providers later, copy the relevant block above and update the credentials."
214
+ );
215
+ lines.push(
216
+ "",
217
+ "# Gateway access",
218
+ "# Listener address. Keep 127.0.0.1 for local development.",
219
+ "HOST=127.0.0.1",
220
+ "# Browser origins allowed to call the gateway (comma separated).",
221
+ "# Default: any http://localhost:<port>, http://127.0.0.1:<port> or http://[::1]:<port>.",
222
+ "# CORS_ORIGINS=http://localhost:" + ctx.frontendPort,
223
+ "# Leave GATEWAY_API_KEY empty for local development: on a loopback HOST the gateway is",
224
+ "# keyless and only accepts requests addressed to localhost from allowed origins.",
225
+ "# Required (32+ characters, e.g. `openssl rand -hex 32`) when HOST is not loopback. When set,",
226
+ "# every request needs `Authorization: Bearer <key>` \u2014 add it from your own server or dev",
227
+ "# proxy, never from browser code.",
228
+ "# GATEWAY_API_KEY=",
229
+ "# Log one line per gateway request.",
230
+ "# DEBUG=1"
231
+ );
232
+ return ensureTrailingNewline(normalizeLineEndings(lines.join("\n")));
233
+ };
234
+ var buildTsConfig = () => formatJson({
235
+ compilerOptions: {
236
+ target: "ESNext",
237
+ useDefineForClassFields: true,
238
+ lib: ["DOM", "DOM.Iterable", "ESNext"],
239
+ allowJs: false,
240
+ skipLibCheck: true,
241
+ esModuleInterop: true,
242
+ allowSyntheticDefaultImports: true,
243
+ strict: true,
244
+ forceConsistentCasingInFileNames: true,
245
+ module: "ESNext",
246
+ moduleResolution: "Node",
247
+ resolveJsonModule: true,
248
+ isolatedModules: true,
249
+ noEmit: true,
250
+ jsx: "react-jsx"
251
+ },
252
+ include: ["src"]
253
+ });
254
+ var buildEnvDts = () => ensureTrailingNewline(
255
+ `/// <reference types="vite/client" />
256
+
257
+ interface ImportMetaEnv {
258
+ readonly VITE_GATEWAY_URL?: string;
259
+ readonly VITE_GATEWAY_PROVIDER?: string;
260
+ readonly VITE_DEFAULT_MODEL?: string;
261
+ readonly VITE_FALLBACK_MODEL?: string;
262
+ readonly VITE_FEEDBACK_EMAIL?: string;
263
+ readonly VITE_BRANDING_TEXT?: string;
264
+ }
265
+
266
+ interface ImportMeta {
267
+ readonly env: ImportMetaEnv;
268
+ }
269
+ `
270
+ );
271
+ var buildViteConfig = (ctx) => ensureTrailingNewline(
272
+ normalizeLineEndings(
273
+ `import { defineConfig, loadEnv } from "vite";
274
+ import react from "@vitejs/plugin-react";
275
+
276
+ export default defineConfig(({ mode }) => {
277
+ const env = loadEnv(mode, process.cwd(), "");
278
+ const parsedPort = Number(env.VITE_DEV_PORT || env.PORT || ${ctx.frontendPort});
279
+ const port = Number.isFinite(parsedPort) ? parsedPort : ${ctx.frontendPort};
280
+
281
+ return {
282
+ plugins: [react()],
283
+ resolve: {
284
+ dedupe: [
285
+ "react",
286
+ "react-dom",
287
+ "@mui/material",
288
+ "@mui/system",
289
+ "@emotion/react",
290
+ "@emotion/styled",
291
+ "react-router-dom"
292
+ ],
293
+ },
294
+ optimizeDeps: {
295
+ include: ["@burtson-labs/bandit-engine"],
296
+ },
297
+ server: {
298
+ port,
299
+ },
300
+ };
301
+ });
302
+ `
303
+ )
304
+ );
305
+ var buildMainTsx = () => ensureTrailingNewline(
306
+ normalizeLineEndings(
307
+ `import React from "react";
308
+ import ReactDOM from "react-dom/client";
309
+ import { BrowserRouter } from "react-router-dom";
310
+ import App from "./App";
311
+ import "./index.css";
312
+
313
+ ReactDOM.createRoot(document.getElementById("root")!).render(
314
+ <React.StrictMode>
315
+ <BrowserRouter>
316
+ <App />
317
+ </BrowserRouter>
318
+ </React.StrictMode>
319
+ );
320
+ `
321
+ )
322
+ );
323
+ var buildIndexCss = () => ensureTrailingNewline(
324
+ normalizeLineEndings(
325
+ `:root {
326
+ font-family: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
327
+ background: radial-gradient(circle at top left, rgba(120, 119, 255, 0.12), transparent 45%),
328
+ radial-gradient(circle at bottom right, rgba(244, 114, 182, 0.1), transparent 55%),
329
+ #05070f;
330
+ color: #f8fafc;
331
+ min-height: 100vh;
332
+ }
333
+
334
+ body {
335
+ margin: 0;
336
+ }
337
+
338
+ * {
339
+ box-sizing: border-box;
340
+ }
341
+ `
342
+ )
343
+ );
344
+ var buildIndexHtml = () => ensureTrailingNewline(
345
+ normalizeLineEndings(
346
+ `<!doctype html>
347
+ <html lang="en">
348
+ <head>
349
+ <meta charset="UTF-8" />
350
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
351
+ <link rel="icon" href="data:," />
352
+ <title>Bandit Quickstart</title>
353
+ </head>
354
+ <body>
355
+ <div id="root"></div>
356
+ <script type="module" src="/src/main.tsx"></script>
357
+ </body>
358
+ </html>
359
+ `
360
+ )
361
+ );
362
+ var buildThemeTs = () => ensureTrailingNewline(
363
+ normalizeLineEndings(
364
+ `import { createTheme } from "@mui/material/styles";
365
+
366
+ export const banditQuickstartTheme = createTheme({
367
+ palette: {
368
+ mode: "dark",
369
+ primary: {
370
+ main: "#f97316",
371
+ },
372
+ secondary: {
373
+ main: "#6366f1",
374
+ },
375
+ background: {
376
+ default: "#05070f",
377
+ paper: "rgba(15, 23, 42, 0.78)",
378
+ },
379
+ },
380
+ typography: {
381
+ fontFamily: '"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
382
+ h1: {
383
+ fontWeight: 700,
384
+ },
385
+ h2: {
386
+ fontWeight: 600,
387
+ },
388
+ },
389
+ components: {
390
+ MuiPaper: {
391
+ styleOverrides: {
392
+ root: {
393
+ backdropFilter: "blur(18px)",
394
+ backgroundImage: "linear-gradient(145deg, rgba(15, 23, 42, 0.92), rgba(2, 6, 23, 0.92))",
395
+ },
396
+ },
397
+ },
398
+ },
399
+ });
400
+ `
401
+ )
402
+ );
403
+ var buildAppTsx = (ctx) => {
404
+ const responseStatusExpr = "${response.status}";
405
+ const gatewayErrorExpr = '${gatewayError ?? "Unknown"}';
406
+ const template = `
407
+ import { useEffect, useState, useMemo, useCallback, type ReactNode } from "react";
408
+ import {
409
+ CssBaseline,
410
+ AppBar,
411
+ Toolbar,
412
+ Typography,
413
+ Container,
414
+ Box,
415
+ Button,
416
+ Chip,
417
+ Tooltip,
418
+ Stack,
419
+ Card,
420
+ CardContent
421
+ } from "@mui/material";
422
+ import { ThemeProvider } from "@mui/material/styles";
423
+ import { Routes, Route, Navigate, Link as RouterLink, useLocation } from "react-router-dom";
424
+ import { ChatProvider, Chat, ChatModal, Management } from "@burtson-labs/bandit-engine";
425
+ import * as BanditEngine from "@burtson-labs/bandit-engine";
426
+ import { banditQuickstartTheme } from "./theme";
427
+
428
+ const gatewayBaseUrl = (import.meta.env.VITE_GATEWAY_URL ?? "${ctx.defaultGatewayUrl}").replace(/\\/$/, "");
429
+ const defaultModelId = import.meta.env.VITE_DEFAULT_MODEL ?? "${ctx.defaultModelId}";
430
+ const fallbackModelId = import.meta.env.VITE_FALLBACK_MODEL ?? ${ctx.fallbackModelId ? `${QUOTE}${ctx.fallbackModelId}${QUOTE}` : "undefined"};
431
+ const brandingText = import.meta.env.VITE_BRANDING_TEXT ?? "${ctx.brandingText}";
432
+ const providerSetting = import.meta.env.VITE_GATEWAY_PROVIDER ?? "${ctx.defaultProvider}";
433
+ // The engine names Azure OpenAI "azure-openai"; the gateway serves it under /api/azure-openai/* too.
434
+ const provider = (providerSetting === "azure" ? "azure-openai" : providerSetting) as "openai" | "ollama" | "azure-openai" | "anthropic" | "xai" | "bandit";
435
+
436
+ const gatewayApiUrl = gatewayBaseUrl.endsWith("/api") ? gatewayBaseUrl : gatewayBaseUrl + "/api";
437
+ const healthEndpoint = gatewayApiUrl + "/health";
438
+
439
+ // Move packageSettings outside the component to prevent recreation on every render
440
+ const packageSettings = {
441
+ defaultModel: defaultModelId,
442
+ fallbackModel: fallbackModelId,
443
+ gatewayApiUrl: gatewayApiUrl,
444
+ brandingConfigUrl: "/config.json",
445
+ aiProvider: {
446
+ type: "gateway" as const,
447
+ gatewayUrl: gatewayApiUrl,
448
+ provider,
449
+ tokenFactory: () => {
450
+ return localStorage.getItem("authToken");
451
+ }
452
+ },
453
+ feedbackEmail: import.meta.env.VITE_FEEDBACK_EMAIL,
454
+ featureFlags: {
455
+ subscriptionType: "premium" as const,
456
+ rolesClaimKey: "roles",
457
+ subscriptionTypeClaimKey: "subscriptionType",
458
+ isSubscribedClaimKey: "isSubscribed",
459
+ jwtStorageKey: "authToken",
460
+ adminRole: "admin",
461
+ // Set to true to see the engine's debug logging in the browser console.
462
+ debug: false,
463
+ featureMatrix: {
464
+ tts: false,
465
+ stt: false,
466
+ semanticSearchSimple: false,
467
+ semanticSearchPremium: false,
468
+ advancedSearch: false,
469
+ advancedMemories: false,
470
+ },
471
+ },
472
+ };
473
+
474
+ const seedQuickstartAuth = () => {
475
+ if (typeof window === "undefined" || typeof localStorage === "undefined") {
476
+ return;
477
+ }
478
+
479
+ const applyAuthToken = (token: string) => {
480
+ localStorage.setItem("authToken", token);
481
+ const maybeService = (BanditEngine as { authenticationService?: { setToken: (token: string) => void } }).authenticationService;
482
+ try {
483
+ maybeService?.setToken(token);
484
+ } catch (error) {
485
+ console.warn("Bandit quickstart: failed to seed authentication service token", error);
486
+ }
487
+ };
488
+
489
+ const existing = localStorage.getItem("authToken");
490
+ if (existing) {
491
+ applyAuthToken(existing);
492
+ return;
493
+ }
494
+
495
+ const header = {
496
+ alg: "HS256",
497
+ typ: "JWT",
498
+ };
499
+ const payload = {
500
+ exp: Math.floor(Date.now() / 1000) + 60 * 60 * 8,
501
+ roles: ["admin"],
502
+ iat: Math.floor(Date.now() / 1000),
503
+ email: "quickstart@burtson.ai",
504
+ sub: "123456789012345678901",
505
+ };
506
+ const encodeSegment = (value: unknown) =>
507
+ btoa(JSON.stringify(value))
508
+ .replace(/=+$/g, "")
509
+ .replace(/\\+/g, "-")
510
+ .replace(/\\//g, "_");
511
+ const mockToken = \`${"${"}encodeSegment(header)}.${"${"}encodeSegment(payload)}.quickstart\`;
512
+ applyAuthToken(mockToken);
513
+ };
514
+
515
+ seedQuickstartAuth();
516
+
517
+ function App() {
518
+ const location = useLocation();
519
+ const [isModalOpen, setIsModalOpen] = useState(false);
520
+ const [gatewayStatus, setGatewayStatus] = useState<"checking" | "healthy" | "error">("checking");
521
+ const [gatewayError, setGatewayError] = useState<string | null>(null);
522
+
523
+ // Separate effect for health checking to avoid re-renders
524
+ useEffect(() => {
525
+ let cancelled = false;
526
+
527
+ const checkHealth = async () => {
528
+ try {
529
+ const response = await fetch(healthEndpoint, { headers: { "Content-Type": "application/json" } });
530
+ if (!response.ok) {
531
+ throw new Error(\`HTTP __RESPONSE_STATUS__\`);
532
+ }
533
+ await response.json();
534
+ if (!cancelled) {
535
+ setGatewayStatus(prevStatus => prevStatus !== "healthy" ? "healthy" : prevStatus);
536
+ setGatewayError(prevError => prevError !== null ? null : prevError);
537
+ }
538
+ } catch (error) {
539
+ if (!cancelled) {
540
+ const errorMessage = error instanceof Error ? error.message : String(error);
541
+ setGatewayStatus(prevStatus => prevStatus !== "error" ? "error" : prevStatus);
542
+ setGatewayError(prevError => prevError !== errorMessage ? errorMessage : prevError);
543
+ }
544
+ }
545
+ };
546
+
547
+ // Initial check
548
+ checkHealth();
549
+
550
+ // Set up interval for periodic checks
551
+ const interval = setInterval(checkHealth, 15000);
552
+
553
+ return () => {
554
+ cancelled = true;
555
+ clearInterval(interval);
556
+ };
557
+ }, []);
558
+
559
+ const gatewayChip = useMemo(() => (
560
+ <Tooltip
561
+ title={
562
+ gatewayStatus === "error"
563
+ ? \`Gateway health check failed. Last error: __GATEWAY_ERROR__\`
564
+ : gatewayStatus === "healthy"
565
+ ? "Gateway reachable"
566
+ : "Checking gateway health..."
567
+ }
568
+ >
569
+ <Chip
570
+ size="small"
571
+ color={gatewayStatus === "healthy" ? "success" : gatewayStatus === "error" ? "error" : "default"}
572
+ variant={gatewayStatus === "healthy" ? "filled" : "outlined"}
573
+ label={
574
+ gatewayStatus === "healthy"
575
+ ? "Gateway: Healthy"
576
+ : gatewayStatus === "error"
577
+ ? "Gateway: Unreachable"
578
+ : "Gateway: Checking..."
579
+ }
580
+ sx={{ fontWeight: 600 }}
581
+ />
582
+ </Tooltip>
583
+ ), [gatewayStatus, gatewayError]);
584
+
585
+ const handleOpenModal = useCallback(() => setIsModalOpen(true), []);
586
+ const handleCloseModal = useCallback(() => setIsModalOpen(false), []);
587
+
588
+ const HomePage = ({ onOpenModal }: { onOpenModal: () => void }) => (
589
+ <Container maxWidth="lg" sx={{ py: { xs: 4, md: 6 } }}>
590
+ <Stack spacing={{ xs: 5, md: 7 }}>
591
+ <Box
592
+ sx={{
593
+ display: "flex",
594
+ flexDirection: { xs: "column-reverse", md: "row" },
595
+ alignItems: "center",
596
+ gap: { xs: 4, md: 8 },
597
+ }}
598
+ >
599
+ <Stack spacing={3} sx={{ flex: 1, width: "100%" }}>
600
+ <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
601
+ <Typography variant="overline" color="primary.light" sx={{ letterSpacing: 2 }}>
602
+ Powered by Bandit Engine
603
+ </Typography>
604
+ </Box>
605
+ <Typography variant="h3" fontWeight={700}>
606
+ {brandingText}
607
+ </Typography>
608
+ <Typography variant="body1" color="text.secondary">
609
+ Build, brand, and launch your assistant with a drop-in chat surface plus a secure gateway for Bandit AI, OpenAI, Azure OpenAI, Anthropic, XAI, or Ollama.
610
+ </Typography>
611
+ <Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
612
+ <Button component={RouterLink} to="/chat" variant="contained" color="primary">
613
+ Go to chat demo
614
+ </Button>
615
+ <Button variant="outlined" color="secondary" onClick={onOpenModal}>
616
+ Open modal assistant
617
+ </Button>
618
+ </Stack>
619
+ </Stack>
620
+ </Box>
621
+ <Box
622
+ sx={{
623
+ display: "grid",
624
+ gap: 3,
625
+ gridTemplateColumns: { xs: "1fr", md: "repeat(3, minmax(0, 1fr))" },
626
+ }}
627
+ >
628
+ <Card sx={{ height: "100%", backdropFilter: "blur(12px)", backgroundColor: "rgba(15, 23, 42, 0.64)" }}>
629
+ <CardContent>
630
+ <Typography variant="h6" gutterBottom>
631
+ Configure in minutes
632
+ </Typography>
633
+ <Typography variant="body2" color="text.secondary">
634
+ Edit <code>public/config.json</code> and <code>.env</code> to tailor models, personas, and branding for your product.
635
+ </Typography>
636
+ </CardContent>
637
+ </Card>
638
+ <Card sx={{ height: "100%", backdropFilter: "blur(12px)", backgroundColor: "rgba(15, 23, 42, 0.64)" }}>
639
+ <CardContent>
640
+ <Typography variant="h6" gutterBottom>
641
+ Ship secure gateways
642
+ </Typography>
643
+ <Typography variant="body2" color="text.secondary">
644
+ Keep API keys server-side while proxying requests to Bandit AI, OpenAI, Azure OpenAI, Anthropic, XAI, or Ollama through the included Express gateway.
645
+ </Typography>
646
+ </CardContent>
647
+ </Card>
648
+ <Card sx={{ height: "100%", backdropFilter: "blur(12px)", backgroundColor: "rgba(15, 23, 42, 0.64)" }}>
649
+ <CardContent>
650
+ <Typography variant="h6" gutterBottom>
651
+ Manage knowledge freely
652
+ </Typography>
653
+ <Typography variant="body2" color="text.secondary">
654
+ Add memories, files, and tools directly in the management console that ships with this quickstart.
655
+ </Typography>
656
+ <Button component={RouterLink} to="/management" variant="text" color="secondary" sx={{ mt: 2, px: 0 }}>
657
+ Explore management console
658
+ </Button>
659
+ </CardContent>
660
+ </Card>
661
+ </Box>
662
+ </Stack>
663
+ </Container>
664
+ );
665
+
666
+ const ChatPage = ({ onOpenModal }: { onOpenModal: () => void }) => (
667
+ <Container maxWidth="lg" sx={{ py: 4, display: "flex", flexDirection: "column", gap: 3 }}>
668
+ <Stack
669
+ direction={{ xs: "column", md: "row" }}
670
+ spacing={2}
671
+ alignItems={{ xs: "stretch", md: "center" }}
672
+ justifyContent="space-between"
673
+ >
674
+ <Box>
675
+ <Typography variant="h4" fontWeight={700} gutterBottom>
676
+ Chat demo
677
+ </Typography>
678
+ <Typography variant="body2" color="text.secondary">
679
+ This route renders the full <code>{\`<Chat />\`}</code> surface powered by your quickstart gateway.
680
+ </Typography>
681
+ </Box>
682
+ <Stack direction={{ xs: "column", sm: "row" }} spacing={1.5}>
683
+ <Button component={RouterLink} to="/management" variant="outlined" color="secondary">
684
+ Management console
685
+ </Button>
686
+ <Button variant="contained" color="primary" onClick={onOpenModal}>
687
+ Open modal assistant
688
+ </Button>
689
+ </Stack>
690
+ </Stack>
691
+ <Box
692
+ sx={{
693
+ flexGrow: 1,
694
+ minHeight: 540,
695
+ borderRadius: 3,
696
+ overflow: "hidden",
697
+ boxShadow: "0 35px 90px rgba(15, 23, 42, 0.55)",
698
+ }}
699
+ >
700
+ <Chat />
701
+ </Box>
702
+ </Container>
703
+ );
704
+
705
+ const Header = ({ gatewayChip }: { gatewayChip: ReactNode }) => (
706
+ <AppBar
707
+ position="sticky"
708
+ color="transparent"
709
+ elevation={0}
710
+ sx={{ borderBottom: "1px solid rgba(148, 163, 184, 0.16)", backdropFilter: "blur(18px)" }}
711
+ >
712
+ <Toolbar sx={{ gap: 2, flexWrap: "wrap" }}>
713
+ <Button
714
+ component={RouterLink}
715
+ to="/"
716
+ color="inherit"
717
+ sx={{
718
+ display: "flex",
719
+ alignItems: "center",
720
+ gap: 1.5,
721
+ py: 1,
722
+ px: 1.5,
723
+ borderRadius: 2,
724
+ textTransform: "none",
725
+ bgcolor: "transparent",
726
+ "&:hover": { bgcolor: "rgba(99, 102, 241, 0.12)" },
727
+ }}
728
+ >
729
+ <Typography variant="h6" sx={{ fontWeight: 600 }}>
730
+ {brandingText}
731
+ </Typography>
732
+ </Button>
733
+ <Box sx={{ flexGrow: 1 }} />
734
+ {gatewayChip}
735
+ <Stack direction="row" spacing={1} flexWrap="wrap" justifyContent="flex-end">
736
+ <Button component={RouterLink} to="/" color="inherit">
737
+ Home
738
+ </Button>
739
+ <Button component={RouterLink} to="/management" color="inherit">
740
+ Management
741
+ </Button>
742
+ <Button component={RouterLink} to="/chat" variant="contained" color="primary">
743
+ Go to chat
744
+ </Button>
745
+ </Stack>
746
+ </Toolbar>
747
+ </AppBar>
748
+ );
749
+
750
+ return (
751
+ <Routes>
752
+ <Route path="/management" element={
753
+ <ChatProvider packageSettings={packageSettings}>
754
+ <Management />
755
+ </ChatProvider>
756
+ } />
757
+ <Route path="/chat" element={
758
+ <ThemeProvider theme={banditQuickstartTheme}>
759
+ <CssBaseline />
760
+ <ChatProvider packageSettings={packageSettings}>
761
+ <Box display="flex" flexDirection="column" minHeight="100vh">
762
+ <Box component="main" sx={{ flexGrow: 1, display: "flex" }}>
763
+ <ChatPage onOpenModal={handleOpenModal} />
764
+ </Box>
765
+ <ChatModal open={isModalOpen} onClose={handleCloseModal} />
766
+ </Box>
767
+ </ChatProvider>
768
+ </ThemeProvider>
769
+ } />
770
+ <Route path="/*" element={
771
+ <ThemeProvider theme={banditQuickstartTheme}>
772
+ <CssBaseline />
773
+ <ChatProvider packageSettings={packageSettings}>
774
+ <Box display="flex" flexDirection="column" minHeight="100vh">
775
+ <Header gatewayChip={gatewayChip} />
776
+ <Box component="main" sx={{ flexGrow: 1, display: "flex" }}>
777
+ <Routes>
778
+ <Route path="/" element={<HomePage onOpenModal={handleOpenModal} />} />
779
+ <Route path="*" element={<Navigate to="/" replace />} />
780
+ </Routes>
781
+ </Box>
782
+ <ChatModal open={isModalOpen} onClose={handleCloseModal} />
783
+ </Box>
784
+ </ChatProvider>
785
+ </ThemeProvider>
786
+ } />
787
+ </Routes>
788
+ );
789
+ }
790
+
791
+ export default App;
792
+ `;
793
+ const withResponse = template.replace(/__RESPONSE_STATUS__/g, responseStatusExpr);
794
+ const withGatewayError = withResponse.replace(/__GATEWAY_ERROR__/g, gatewayErrorExpr);
795
+ return ensureTrailingNewline(normalizeLineEndings(withGatewayError));
796
+ };
797
+ var buildBrandingConfig = (ctx) => formatJson({
798
+ branding: {
799
+ logoBase64: ctx.isDefaultLogo ? null : ctx.logoBase64,
800
+ brandingText: ctx.brandingText,
801
+ theme: "bandit-dark",
802
+ hasTransparentLogo: ctx.isDefaultLogo ? true : ctx.hasTransparentLogo
803
+ },
804
+ knowledgeDocs: []
805
+ });
806
+ var NEXT_CHAT_ROUTE_TEMPLATE = `import { NextRequest, NextResponse } from "next/server";
807
+
808
+ export const dynamic = "force-dynamic";
809
+
810
+ const DEFAULT_PROVIDER = "__DEFAULT_PROVIDER__";
811
+ const DEFAULT_MODEL = "__DEFAULT_MODEL__";
812
+ const FALLBACK_MODEL = __FALLBACK_MODEL__;
813
+
814
+ const OLLAMA_URL = (process.env.OLLAMA_URL ?? "http://localhost:11434").replace(/\\/$/, "");
815
+ const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
816
+ const AZURE_OPENAI_ENDPOINT = process.env.AZURE_OPENAI_ENDPOINT ? process.env.AZURE_OPENAI_ENDPOINT.replace(/\\/$/, "") : undefined;
817
+ const AZURE_OPENAI_API_KEY = process.env.AZURE_OPENAI_API_KEY;
818
+ const AZURE_OPENAI_API_VERSION = process.env.AZURE_OPENAI_API_VERSION ?? "2024-08-01-preview";
819
+ const AZURE_OPENAI_CHAT_DEPLOYMENT = process.env.AZURE_OPENAI_CHAT_DEPLOYMENT;
820
+ const AZURE_OPENAI_COMPLETIONS_DEPLOYMENT = process.env.AZURE_OPENAI_COMPLETIONS_DEPLOYMENT ?? AZURE_OPENAI_CHAT_DEPLOYMENT;
821
+ const AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT = process.env.AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT;
822
+ const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
823
+ const ANTHROPIC_BASE_URL = (process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com").replace(/\\/$/, "");
824
+ const ANTHROPIC_API_VERSION = process.env.ANTHROPIC_API_VERSION ?? "2023-06-01";
825
+ const ANTHROPIC_MAX_TOKENS = Number.isFinite(Number(process.env.ANTHROPIC_MAX_TOKENS))
826
+ ? Number(process.env.ANTHROPIC_MAX_TOKENS)
827
+ : 1024;
828
+ const XAI_API_KEY = process.env.XAI_API_KEY;
829
+ const XAI_BASE_URL = (process.env.XAI_BASE_URL ?? "https://api.x.ai/v1").replace(/\\/$/, "");
830
+ const BANDIT_API_KEY = process.env.BANDIT_API_KEY;
831
+ const BANDIT_BASE_URL = (process.env.BANDIT_BASE_URL ?? "https://api.burtson.ai").replace(/\\/$/, "");
832
+
833
+ const normalizeGatewayImageUrl = (value: unknown): string => {
834
+ if (!value) {
835
+ return "";
836
+ }
837
+ if (typeof value === "string") {
838
+ const trimmed = value.trim();
839
+ if (!trimmed) {
840
+ return "";
841
+ }
842
+ if (/^data:/i.test(trimmed) || /^https?:/i.test(trimmed)) {
843
+ return trimmed;
844
+ }
845
+ return 'data:image/jpeg;base64,' + trimmed;
846
+ }
847
+ if (typeof value === "object") {
848
+ const possibleUrl =
849
+ typeof (value as { url?: string }).url === "string"
850
+ ? (value as { url: string }).url
851
+ : (value as { image_url?: { url?: string } }).image_url && typeof (value as { image_url?: { url?: string } }).image_url?.url === "string"
852
+ ? ((value as { image_url: { url: string } }).image_url.url)
853
+ : "";
854
+ return normalizeGatewayImageUrl(possibleUrl);
855
+ }
856
+ return "";
857
+ };
858
+
859
+ const extractGatewayImageDetail = (value: unknown): string | undefined => {
860
+ if (value && typeof value === "object") {
861
+ const record = value as Record<string, unknown>;
862
+ if (typeof record.detail === "string" && record.detail.trim()) {
863
+ return record.detail;
864
+ }
865
+ const nested = record.image_url;
866
+ if (nested && typeof (nested as Record<string, unknown>).detail === "string" && (nested as Record<string, unknown>).detail.trim()) {
867
+ return (nested as Record<string, unknown>).detail as string;
868
+ }
869
+ }
870
+ return undefined;
871
+ };
872
+
873
+ interface GatewayChatBody {
874
+ provider?: string;
875
+ model?: string;
876
+ messages?: Array<{ role: string; content: unknown }>;
877
+ prompt?: string;
878
+ stream?: boolean;
879
+ temperature?: number;
880
+ max_tokens?: number;
881
+ top_p?: number;
882
+ stop?: string | string[];
883
+ stop_sequences?: string | string[];
884
+ tools?: unknown;
885
+ tool_choice?: unknown;
886
+ metadata?: unknown;
887
+ thinking?: unknown;
888
+ images?: string[];
889
+ [key: string]: unknown;
890
+ }
891
+
892
+ const normalizeProvider = (input: string): "openai" | "azure" | "anthropic" | "ollama" | "xai" | "bandit" => {
893
+ const value = input.toLowerCase();
894
+ if (value === "azure-openai" || value === "azureopenai" || value === "azure") return "azure";
895
+ if (value === "anthropic" || value === "claude") return "anthropic";
896
+ if (value === "ollama") return "ollama";
897
+ if (value === "xai" || value === "grok") return "xai";
898
+ if (value === "bandit" || value === "banditai" || value === "bandit-ai") return "bandit";
899
+ return "openai";
900
+ };
901
+
902
+ const stripPrefix = (model: unknown, prefix: string, fallback: string): string => {
903
+ if (typeof model === "string") {
904
+ return model.replace(new RegExp(\`^\${prefix}:\`), "");
905
+ }
906
+ return fallback;
907
+ };
908
+
909
+ const requireOpenAIKey = () => {
910
+ if (!OPENAI_API_KEY) {
911
+ throw new Error("Missing OPENAI_API_KEY. Add it to your .env file to route requests to OpenAI.");
912
+ }
913
+ return OPENAI_API_KEY;
914
+ };
915
+
916
+ const requireBanditKey = () => {
917
+ if (!BANDIT_API_KEY) {
918
+ throw new Error("Missing BANDIT_API_KEY. Add it to your .env file to route requests to Bandit AI.");
919
+ }
920
+ return BANDIT_API_KEY;
921
+ };
922
+
923
+ const requireXAIKey = () => {
924
+ if (!XAI_API_KEY) {
925
+ throw new Error("Missing XAI_API_KEY. Add it to your .env file to route requests to xAI.");
926
+ }
927
+ return XAI_API_KEY;
928
+ };
929
+
930
+ const requireAnthropicKey = () => {
931
+ if (!ANTHROPIC_API_KEY) {
932
+ throw new Error("Missing ANTHROPIC_API_KEY. Add it to your .env file to route requests to Anthropic.");
933
+ }
934
+ return ANTHROPIC_API_KEY;
935
+ };
936
+
937
+ const isAzureConfigured = () => Boolean(AZURE_OPENAI_ENDPOINT && AZURE_OPENAI_API_KEY);
938
+
939
+ const requireAzureBaseConfig = () => {
940
+ if (!AZURE_OPENAI_ENDPOINT) {
941
+ throw new Error("Missing AZURE_OPENAI_ENDPOINT. Add it to your .env file to route requests to Azure OpenAI.");
942
+ }
943
+ if (!AZURE_OPENAI_API_KEY) {
944
+ throw new Error("Missing AZURE_OPENAI_API_KEY. Add it to your .env file to route requests to Azure OpenAI.");
945
+ }
946
+ return {
947
+ endpoint: AZURE_OPENAI_ENDPOINT,
948
+ apiKey: AZURE_OPENAI_API_KEY,
949
+ };
950
+ };
951
+
952
+ const buildAzureDeploymentUrl = (deployment: string | undefined, suffix: string) => {
953
+ if (!deployment) {
954
+ throw new Error(\`Missing Azure OpenAI \${suffix.split("/")[0]} deployment name.\`);
955
+ }
956
+ const { endpoint } = requireAzureBaseConfig();
957
+ const normalized = suffix.replace(/^\\/+/, "");
958
+ return \`\${endpoint}/openai/deployments/\${deployment}/\${normalized}?api-version=\${AZURE_OPENAI_API_VERSION}\`;
959
+ };
960
+
961
+ const resolveAzureDeployment = (model: unknown, fallback: string | undefined, kind: "chat" | "completions" | "embeddings") => {
962
+ const explicit = typeof model === "string" ? model.replace(/^azure:/, "") : undefined;
963
+ if (explicit) return explicit;
964
+ if (kind === "embeddings") return AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT ?? fallback;
965
+ if (kind === "completions") return AZURE_OPENAI_COMPLETIONS_DEPLOYMENT ?? fallback;
966
+ return AZURE_OPENAI_CHAT_DEPLOYMENT ?? fallback;
967
+ };
968
+
969
+ const flattenGatewayContent = (content: unknown): string => {
970
+ if (typeof content === "string") return content;
971
+ if (Array.isArray(content)) {
972
+ return content
973
+ .map((part) => {
974
+ if (typeof part === "string") return part;
975
+ if (part && typeof part === "object" && "type" in part) {
976
+ const typed = part as { type?: string; text?: string; image_url?: { url?: string } };
977
+ if (typed.type === "text" && typeof typed.text === "string") return typed.text;
978
+ if (typed.type === "image_url" && typed.image_url?.url) return \`[Image: \${typed.image_url.url}]\`;
979
+ }
980
+ return JSON.stringify(part ?? {});
981
+ })
982
+ .join("\\n");
983
+ }
984
+ if (content && typeof content === "object") return JSON.stringify(content);
985
+ return "";
986
+ };
987
+
988
+ const toAnthropicMessages = (messages: Array<{ role: string; content: unknown }> = []) => {
989
+ const anthropicMessages: Array<{ role: "user" | "assistant"; content: Array<{ type: "text"; text: string }> }> = [];
990
+ let systemPrompt = "";
991
+
992
+ for (const message of messages) {
993
+ if (!message) continue;
994
+ const text = flattenGatewayContent(message.content);
995
+ if (message.role === "system") {
996
+ systemPrompt = systemPrompt ? \`\${systemPrompt}\\n\\n\${text}\` : text;
997
+ continue;
998
+ }
999
+ const role = message.role === "assistant" ? "assistant" : "user";
1000
+ anthropicMessages.push({
1001
+ role,
1002
+ content: [{ type: "text", text }],
1003
+ });
1004
+ }
1005
+
1006
+ return { messages: anthropicMessages, system: systemPrompt || undefined };
1007
+ };
1008
+
1009
+ const convertAnthropicResponseToGateway = (responseBody: any, modelName: string) => {
1010
+ if (!responseBody) {
1011
+ return {
1012
+ id: \`anthropic-\${Date.now()}\`,
1013
+ object: "chat.completion",
1014
+ created: Math.floor(Date.now() / 1000),
1015
+ model: modelName.startsWith("anthropic:") ? modelName : \`anthropic:\${modelName}\`,
1016
+ choices: [],
1017
+ };
1018
+ }
1019
+
1020
+ const textContent = Array.isArray(responseBody.content)
1021
+ ? responseBody.content
1022
+ .filter((item: any) => item && item.type === "text" && typeof item.text === "string")
1023
+ .map((item: any) => item.text)
1024
+ .join("\\n")
1025
+ : typeof responseBody.content === "string"
1026
+ ? responseBody.content
1027
+ : "";
1028
+
1029
+ const promptTokens = responseBody.usage?.input_tokens ?? 0;
1030
+ const completionTokens = responseBody.usage?.output_tokens ?? 0;
1031
+
1032
+ return {
1033
+ id: responseBody.id ?? \`anthropic-\${Date.now()}\`,
1034
+ object: "chat.completion",
1035
+ created: Math.floor(Date.now() / 1000),
1036
+ model: modelName.startsWith("anthropic:") ? modelName : \`anthropic:\${modelName}\`,
1037
+ choices: [
1038
+ {
1039
+ index: 0,
1040
+ message: {
1041
+ role: responseBody.role ?? "assistant",
1042
+ content: textContent,
1043
+ },
1044
+ finish_reason: responseBody.stop_reason ?? responseBody.stop_sequence ?? null,
1045
+ },
1046
+ ],
1047
+ usage: responseBody.usage
1048
+ ? {
1049
+ prompt_tokens: promptTokens,
1050
+ completion_tokens: completionTokens,
1051
+ total_tokens: promptTokens + completionTokens,
1052
+ }
1053
+ : undefined,
1054
+ };
1055
+ };
1056
+
1057
+ const passthroughResponse = (upstream: Response) => {
1058
+ const headers = new Headers(upstream.headers);
1059
+ return new Response(upstream.body, {
1060
+ status: upstream.status,
1061
+ statusText: upstream.statusText,
1062
+ headers,
1063
+ });
1064
+ };
1065
+
1066
+ const jsonResponse = async (upstream: Response) => {
1067
+ const data = await upstream.json().catch(async () => ({ raw: await upstream.text() }));
1068
+ return NextResponse.json(data, { status: upstream.status });
1069
+ };
1070
+
1071
+ const errorResponse = (status: number, error: unknown) =>
1072
+ NextResponse.json(
1073
+ {
1074
+ error: error instanceof Error ? error.message : String(error ?? "Unknown error"),
1075
+ },
1076
+ { status }
1077
+ );
1078
+
1079
+ export async function POST(request: NextRequest) {
1080
+ const body = (await request.json()) as GatewayChatBody;
1081
+ const provider = normalizeProvider(body.provider ?? DEFAULT_PROVIDER);
1082
+ const stream = body.stream !== false;
1083
+
1084
+ try {
1085
+ switch (provider) {
1086
+ case "openai": {
1087
+ const openaiKey = requireOpenAIKey();
1088
+ const { provider: _provider, ...cleanBody } = body;
1089
+ const requestBody = {
1090
+ ...cleanBody,
1091
+ stream,
1092
+ model: stripPrefix(body.model ?? DEFAULT_MODEL, "openai", "gpt-4o"),
1093
+ };
1094
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
1095
+ method: "POST",
1096
+ headers: {
1097
+ "Content-Type": "application/json",
1098
+ Authorization: \`Bearer \${openaiKey}\`,
1099
+ },
1100
+ body: JSON.stringify(requestBody),
1101
+ });
1102
+ if (!response.ok) {
1103
+ const details = await response.text();
1104
+ return NextResponse.json({ error: \`OpenAI chat failed: \${response.status}\`, details }, { status: response.status });
1105
+ }
1106
+ return stream ? passthroughResponse(response) : jsonResponse(response);
1107
+ }
1108
+
1109
+ case "bandit": {
1110
+ const banditKey = requireBanditKey();
1111
+ const { provider: _provider, ...cleanBody } = body;
1112
+ const providerName = typeof body.provider === "string" ? body.provider : "bandit";
1113
+ const requestBody = {
1114
+ ...cleanBody,
1115
+ stream,
1116
+ model: stripPrefix(body.model ?? DEFAULT_MODEL, "bandit", "bandit-core-1"),
1117
+ };
1118
+
1119
+ if (
1120
+ providerName !== "ollama" &&
1121
+ Array.isArray(requestBody.images) &&
1122
+ requestBody.images.length > 0 &&
1123
+ Array.isArray(requestBody.messages)
1124
+ ) {
1125
+ const lastUserIndex = requestBody.messages.map((message) => message?.role).lastIndexOf("user");
1126
+ if (lastUserIndex !== -1) {
1127
+ const targetMessage = requestBody.messages[lastUserIndex] ?? {};
1128
+ const baseContent = Array.isArray(targetMessage.content)
1129
+ ? targetMessage.content.filter(Boolean)
1130
+ : typeof targetMessage.content === "string" && targetMessage.content.trim().length > 0
1131
+ ? [{ type: "text", text: targetMessage.content }]
1132
+ : [];
1133
+
1134
+ const imageContent = requestBody.images
1135
+ .map((entry) => {
1136
+ const url = normalizeGatewayImageUrl(entry);
1137
+ if (!url) {
1138
+ return null;
1139
+ }
1140
+ return {
1141
+ type: "image_url",
1142
+ image_url: {
1143
+ url,
1144
+ detail: extractGatewayImageDetail(entry) ?? "auto"
1145
+ }
1146
+ };
1147
+ })
1148
+ .filter(Boolean);
1149
+
1150
+ if (imageContent.length > 0) {
1151
+ requestBody.messages[lastUserIndex] = {
1152
+ ...targetMessage,
1153
+ content: [...baseContent, ...imageContent]
1154
+ };
1155
+ }
1156
+ }
1157
+ delete requestBody.images;
1158
+ }
1159
+
1160
+ const response = await fetch(BANDIT_BASE_URL + "/completions", {
1161
+ method: "POST",
1162
+ headers: {
1163
+ "Content-Type": "application/json",
1164
+ Authorization: \`Bearer \${banditKey}\`,
1165
+ },
1166
+ body: JSON.stringify(requestBody),
1167
+ });
1168
+ if (!response.ok) {
1169
+ const details = await response.text();
1170
+ return NextResponse.json({ error: \`Bandit chat failed: \${response.status}\`, details }, { status: response.status });
1171
+ }
1172
+ return stream ? passthroughResponse(response) : jsonResponse(response);
1173
+ }
1174
+
1175
+ case "xai": {
1176
+ const xaiKey = requireXAIKey();
1177
+ const { provider: _provider, ...cleanBody } = body;
1178
+ const requestBody = {
1179
+ ...cleanBody,
1180
+ stream,
1181
+ model: stripPrefix(body.model ?? DEFAULT_MODEL, "xai", "grok-2-latest"),
1182
+ };
1183
+ const response = await fetch(XAI_BASE_URL + "/chat/completions", {
1184
+ method: "POST",
1185
+ headers: {
1186
+ "Content-Type": "application/json",
1187
+ Authorization: "Bearer " + xaiKey,
1188
+ },
1189
+ body: JSON.stringify(requestBody),
1190
+ });
1191
+ if (!response.ok) {
1192
+ const details = await response.text();
1193
+ return NextResponse.json({ error: "xAI chat failed: " + response.status, details }, { status: response.status });
1194
+ }
1195
+ return stream ? passthroughResponse(response) : jsonResponse(response);
1196
+ }
1197
+
1198
+ case "anthropic": {
1199
+ const anthropicKey = requireAnthropicKey();
1200
+ const requestedModel = stripPrefix(body.model ?? DEFAULT_MODEL, "anthropic", "claude-3-5-haiku-latest");
1201
+ const stopSequences = Array.isArray(body.stop)
1202
+ ? body.stop
1203
+ : Array.isArray(body.stop_sequences)
1204
+ ? body.stop_sequences
1205
+ : body.stop
1206
+ ? [body.stop]
1207
+ : undefined;
1208
+ const { messages, system } = toAnthropicMessages(Array.isArray(body.messages) ? body.messages : []);
1209
+ const fallbackText = typeof body.prompt === "string" && body.prompt.trim().length > 0
1210
+ ? body.prompt
1211
+ : "Hello from Bandit quickstart gateway";
1212
+
1213
+ const requestBody: Record<string, unknown> = {
1214
+ model: requestedModel,
1215
+ messages: messages.length > 0
1216
+ ? messages
1217
+ : [
1218
+ {
1219
+ role: "user",
1220
+ content: [{ type: "text", text: fallbackText }],
1221
+ },
1222
+ ],
1223
+ stream,
1224
+ max_tokens: typeof body.max_tokens === "number" && body.max_tokens > 0 ? body.max_tokens : ANTHROPIC_MAX_TOKENS,
1225
+ };
1226
+
1227
+ if (system) requestBody.system = system;
1228
+ if (typeof body.temperature === "number") requestBody.temperature = body.temperature;
1229
+ if (typeof body.top_p === "number") requestBody.top_p = body.top_p;
1230
+ if (typeof body.top_k === "number") requestBody.top_k = body.top_k;
1231
+ if (stopSequences) requestBody.stop_sequences = stopSequences;
1232
+ if (body.metadata) requestBody.metadata = body.metadata;
1233
+ if (body.tools) requestBody.tools = body.tools;
1234
+ if (body.tool_choice) requestBody.tool_choice = body.tool_choice;
1235
+ if (body.thinking) requestBody.thinking = body.thinking;
1236
+
1237
+ const response = await fetch(\`\${ANTHROPIC_BASE_URL}/v1/messages\`, {
1238
+ method: "POST",
1239
+ headers: {
1240
+ "Content-Type": "application/json",
1241
+ "x-api-key": anthropicKey,
1242
+ "anthropic-version": ANTHROPIC_API_VERSION,
1243
+ },
1244
+ body: JSON.stringify(requestBody),
1245
+ });
1246
+
1247
+ if (!response.ok) {
1248
+ const details = await response.text();
1249
+ return NextResponse.json({ error: \`Anthropic chat failed: \${response.status}\`, details }, { status: response.status });
1250
+ }
1251
+
1252
+ if (stream) {
1253
+ return passthroughResponse(response);
1254
+ }
1255
+
1256
+ const data = await response.json();
1257
+ const normalized = convertAnthropicResponseToGateway(data, requestedModel);
1258
+ return NextResponse.json(normalized);
1259
+ }
1260
+
1261
+ case "azure": {
1262
+ const { apiKey } = requireAzureBaseConfig();
1263
+ const deployment = resolveAzureDeployment(body.model, AZURE_OPENAI_CHAT_DEPLOYMENT, "chat");
1264
+ const { provider: _provider, model: _model, ...cleanBody } = body;
1265
+ const requestBody = {
1266
+ ...cleanBody,
1267
+ stream,
1268
+ };
1269
+
1270
+ const response = await fetch(buildAzureDeploymentUrl(deployment, "chat/completions"), {
1271
+ method: "POST",
1272
+ headers: {
1273
+ "Content-Type": "application/json",
1274
+ "api-key": apiKey,
1275
+ },
1276
+ body: JSON.stringify(requestBody),
1277
+ });
1278
+
1279
+ if (!response.ok) {
1280
+ const details = await response.text();
1281
+ return NextResponse.json({ error: \`Azure OpenAI chat failed: \${response.status}\`, details }, { status: response.status });
1282
+ }
1283
+
1284
+ return stream ? passthroughResponse(response) : jsonResponse(response);
1285
+ }
1286
+
1287
+ case "ollama": {
1288
+ const { provider: _provider, ...cleanBody } = body;
1289
+ const requestBody = {
1290
+ ...cleanBody,
1291
+ stream,
1292
+ model: stripPrefix(body.model ?? DEFAULT_MODEL, "ollama", "llama3.1"),
1293
+ };
1294
+
1295
+ const response = await fetch(\`\${OLLAMA_URL}/api/chat\`, {
1296
+ method: "POST",
1297
+ headers: {
1298
+ "Content-Type": "application/json",
1299
+ },
1300
+ body: JSON.stringify(requestBody),
1301
+ });
1302
+
1303
+ if (!response.ok) {
1304
+ const details = await response.text();
1305
+ return NextResponse.json({ error: \`Ollama chat failed: \${response.status}\`, details }, { status: response.status });
1306
+ }
1307
+
1308
+ return stream ? passthroughResponse(response) : jsonResponse(response);
1309
+ }
1310
+
1311
+ default:
1312
+ return errorResponse(400, \`Unsupported provider: \${provider}\`);
1313
+ }
1314
+ } catch (error) {
1315
+ const message = error instanceof Error ? error.message : String(error);
1316
+ const status = message.startsWith("Missing") ? 400 : 500;
1317
+ return errorResponse(status, error);
1318
+ }
1319
+ }
1320
+
1321
+ `;
1322
+ var NEXT_HEALTH_ROUTE_TEMPLATE = `import { NextResponse } from "next/server";
1323
+
1324
+ export const dynamic = "force-dynamic";
1325
+
1326
+ const QUICKSTART_VERSION = "0.1.0";
1327
+ const OLLAMA_URL = (process.env.OLLAMA_URL ?? "http://localhost:11434").replace(/\\/$/, "");
1328
+ const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
1329
+ const AZURE_OPENAI_ENDPOINT = process.env.AZURE_OPENAI_ENDPOINT ? process.env.AZURE_OPENAI_ENDPOINT.replace(/\\/$/, "") : undefined;
1330
+ const AZURE_OPENAI_API_KEY = process.env.AZURE_OPENAI_API_KEY;
1331
+ const AZURE_OPENAI_API_VERSION = process.env.AZURE_OPENAI_API_VERSION ?? "2024-08-01-preview";
1332
+ const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
1333
+ const ANTHROPIC_BASE_URL = (process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com").replace(/\\/$/, "");
1334
+ const ANTHROPIC_API_VERSION = process.env.ANTHROPIC_API_VERSION ?? "2023-06-01";
1335
+ const XAI_API_KEY = process.env.XAI_API_KEY;
1336
+ const XAI_BASE_URL = (process.env.XAI_BASE_URL ?? "https://api.x.ai/v1").replace(/\\/$/, "");
1337
+
1338
+ const isAzureConfigured = () => Boolean(AZURE_OPENAI_ENDPOINT && AZURE_OPENAI_API_KEY);
1339
+
1340
+ const buildAzurePath = (path: string) => {
1341
+ const normalized = path.replace(/^\\/+/, "");
1342
+ if (!AZURE_OPENAI_ENDPOINT) {
1343
+ throw new Error("Missing AZURE_OPENAI_ENDPOINT. Add it to your .env file to route requests to Azure OpenAI.");
1344
+ }
1345
+ return \`\${AZURE_OPENAI_ENDPOINT}/openai/\${normalized}?api-version=\${AZURE_OPENAI_API_VERSION}\`;
1346
+ };
1347
+
1348
+ export async function GET() {
1349
+ const providers: Array<Record<string, unknown>> = [];
1350
+
1351
+ // OpenAI
1352
+ try {
1353
+ if (OPENAI_API_KEY) {
1354
+ const response = await fetch("https://api.openai.com/v1/models", {
1355
+ headers: { Authorization: \`Bearer \${OPENAI_API_KEY}\` },
1356
+ });
1357
+ providers.push({
1358
+ name: "openai",
1359
+ status: response.ok ? "healthy" : "unhealthy",
1360
+ provider: "openai",
1361
+ });
1362
+ } else {
1363
+ providers.push({
1364
+ name: "openai",
1365
+ status: "unconfigured",
1366
+ provider: "openai",
1367
+ error: "API key not configured",
1368
+ });
1369
+ }
1370
+ } catch (error) {
1371
+ providers.push({
1372
+ name: "openai",
1373
+ status: "unhealthy",
1374
+ provider: "openai",
1375
+ error: error instanceof Error ? error.message : String(error),
1376
+ });
1377
+ }
1378
+
1379
+ // Azure
1380
+ if (AZURE_OPENAI_ENDPOINT || AZURE_OPENAI_API_KEY) {
1381
+ if (!isAzureConfigured()) {
1382
+ providers.push({
1383
+ name: "azure",
1384
+ status: "unconfigured",
1385
+ provider: "azure",
1386
+ error: "Endpoint or API key not configured",
1387
+ endpoint: AZURE_OPENAI_ENDPOINT,
1388
+ });
1389
+ } else {
1390
+ try {
1391
+ const response = await fetch(buildAzurePath("deployments"), {
1392
+ headers: { "api-key": AZURE_OPENAI_API_KEY ?? "" },
1393
+ });
1394
+ providers.push({
1395
+ name: "azure",
1396
+ status: response.ok ? "healthy" : "unhealthy",
1397
+ provider: "azure",
1398
+ endpoint: AZURE_OPENAI_ENDPOINT,
1399
+ });
1400
+ } catch (error) {
1401
+ providers.push({
1402
+ name: "azure",
1403
+ status: "unhealthy",
1404
+ provider: "azure",
1405
+ endpoint: AZURE_OPENAI_ENDPOINT,
1406
+ error: error instanceof Error ? error.message : String(error),
1407
+ });
1408
+ }
1409
+ }
1410
+ } else {
1411
+ providers.push({
1412
+ name: "azure",
1413
+ status: "unconfigured",
1414
+ provider: "azure",
1415
+ error: "Endpoint or API key not configured",
1416
+ });
1417
+ }
1418
+
1419
+ // Anthropic
1420
+ if (ANTHROPIC_API_KEY) {
1421
+ try {
1422
+ const response = await fetch(\`\${ANTHROPIC_BASE_URL}/v1/models\`, {
1423
+ headers: {
1424
+ "x-api-key": ANTHROPIC_API_KEY,
1425
+ "anthropic-version": ANTHROPIC_API_VERSION,
1426
+ },
1427
+ });
1428
+ providers.push({
1429
+ name: "anthropic",
1430
+ status: response.ok ? "healthy" : "unhealthy",
1431
+ provider: "anthropic",
1432
+ endpoint: ANTHROPIC_BASE_URL,
1433
+ });
1434
+ } catch (error) {
1435
+ providers.push({
1436
+ name: "anthropic",
1437
+ status: "unhealthy",
1438
+ provider: "anthropic",
1439
+ endpoint: ANTHROPIC_BASE_URL,
1440
+ error: error instanceof Error ? error.message : String(error),
1441
+ });
1442
+ }
1443
+ } else {
1444
+ providers.push({
1445
+ name: "anthropic",
1446
+ status: "unconfigured",
1447
+ provider: "anthropic",
1448
+ error: "API key not configured",
1449
+ });
1450
+ }
1451
+
1452
+ // xAI
1453
+ if (XAI_API_KEY) {
1454
+ try {
1455
+ const response = await fetch(XAI_BASE_URL + "/models", {
1456
+ headers: { Authorization: "Bearer " + XAI_API_KEY },
1457
+ });
1458
+ providers.push({
1459
+ name: "xai",
1460
+ status: response.ok ? "healthy" : "unhealthy",
1461
+ provider: "xai",
1462
+ endpoint: XAI_BASE_URL,
1463
+ });
1464
+ } catch (error) {
1465
+ providers.push({
1466
+ name: "xai",
1467
+ status: "unhealthy",
1468
+ provider: "xai",
1469
+ endpoint: XAI_BASE_URL,
1470
+ error: error instanceof Error ? error.message : String(error),
1471
+ });
1472
+ }
1473
+ } else {
1474
+ providers.push({
1475
+ name: "xai",
1476
+ status: "unconfigured",
1477
+ provider: "xai",
1478
+ error: "API key not configured",
1479
+ endpoint: XAI_BASE_URL,
1480
+ });
1481
+ }
1482
+
1483
+ // Ollama
1484
+ try {
1485
+ const response = await fetch(\`\${OLLAMA_URL}/api/tags\`);
1486
+ providers.push({
1487
+ name: "ollama",
1488
+ status: response.ok ? "healthy" : "unhealthy",
1489
+ provider: "ollama",
1490
+ url: OLLAMA_URL,
1491
+ });
1492
+ } catch (error) {
1493
+ providers.push({
1494
+ name: "ollama",
1495
+ status: "offline",
1496
+ provider: "ollama",
1497
+ url: OLLAMA_URL,
1498
+ error: error instanceof Error ? error.message : String(error),
1499
+ });
1500
+ }
1501
+
1502
+ const overallHealthy = providers.some((provider) => provider.status === "healthy");
1503
+
1504
+ return NextResponse.json({
1505
+ status: overallHealthy ? "healthy" : "unhealthy",
1506
+ version: QUICKSTART_VERSION,
1507
+ uptime: Math.round(process.uptime()),
1508
+ providers,
1509
+ });
1510
+ }
1511
+
1512
+ `;
1513
+ var NEXT_MODELS_ROUTE_TEMPLATE = `import { NextResponse } from "next/server";
1514
+
1515
+ export const dynamic = "force-dynamic";
1516
+
1517
+ // GET /api/models returns { models: GatewayEngineModel[] } \u2014 the shape the
1518
+ // engine's model picker reads (id, displayName, description, available, ...).
1519
+ const BASE_GATEWAY_MODELS: Array<{ id: string; name: string; provider: string }> = __GATEWAY_MODELS__;
1520
+ const OLLAMA_URL = (process.env.OLLAMA_URL ?? "http://localhost:11434").replace(/\\/$/, "");
1521
+
1522
+ const isProviderConfigured = (provider: string): boolean => {
1523
+ switch (provider) {
1524
+ case "openai": return Boolean(process.env.OPENAI_API_KEY);
1525
+ case "azure": return Boolean(process.env.AZURE_OPENAI_ENDPOINT && process.env.AZURE_OPENAI_API_KEY);
1526
+ case "anthropic": return Boolean(process.env.ANTHROPIC_API_KEY);
1527
+ case "xai": return Boolean(process.env.XAI_API_KEY);
1528
+ case "bandit": return Boolean(process.env.BANDIT_API_KEY);
1529
+ default: return false;
1530
+ }
1531
+ };
1532
+
1533
+ const withTimeout = (ms: number) => AbortSignal.timeout(ms);
1534
+
1535
+ async function ollamaCapabilities(name: string): Promise<string[]> {
1536
+ try {
1537
+ const response = await fetch(OLLAMA_URL + "/api/show", {
1538
+ method: "POST",
1539
+ headers: { "Content-Type": "application/json" },
1540
+ body: JSON.stringify({ model: name }),
1541
+ signal: withTimeout(2000),
1542
+ });
1543
+ if (!response.ok) return [];
1544
+ const body = await response.json();
1545
+ return Array.isArray(body?.capabilities) ? body.capabilities : [];
1546
+ } catch {
1547
+ return [];
1548
+ }
1549
+ }
1550
+
1551
+ // Installed Ollama models, skipping ":cloud" proxies and embedding-only models.
1552
+ async function listOllamaModels() {
1553
+ const response = await fetch(OLLAMA_URL + "/api/tags", { signal: withTimeout(2000), cache: "no-store" });
1554
+ if (!response.ok) throw new Error("Ollama /api/tags returned " + response.status);
1555
+ const body = await response.json();
1556
+ const installed = (Array.isArray(body?.models) ? body.models : []).filter(
1557
+ (model: { name?: unknown }) => typeof model?.name === "string" && !String(model.name).endsWith(":cloud")
1558
+ );
1559
+ const entries = await Promise.all(
1560
+ installed.map(async (model: any) => {
1561
+ const capabilities = await ollamaCapabilities(model.name);
1562
+ if (capabilities.length > 0 && !capabilities.includes("completion")) return null;
1563
+ const details = model.details ?? {};
1564
+ return {
1565
+ id: model.name,
1566
+ name: model.name,
1567
+ displayName: model.name,
1568
+ description: [details.family, details.parameter_size, details.quantization_level].filter(Boolean).join(" "),
1569
+ provider: "ollama",
1570
+ available: true,
1571
+ cloud: false,
1572
+ tier: "local",
1573
+ contextWindow: 0,
1574
+ vision: capabilities.includes("vision"),
1575
+ tools: capabilities.includes("tools"),
1576
+ thinking: capabilities.includes("thinking"),
1577
+ size: model.size,
1578
+ digest: model.digest,
1579
+ modified_at: model.modified_at,
1580
+ details,
1581
+ };
1582
+ })
1583
+ );
1584
+ return entries.filter(Boolean);
1585
+ }
1586
+
1587
+ export async function GET() {
1588
+ let ollama: unknown[] | null = null;
1589
+ try {
1590
+ ollama = await listOllamaModels();
1591
+ } catch {
1592
+ ollama = null;
1593
+ }
1594
+ const hosted = BASE_GATEWAY_MODELS
1595
+ .filter((model) => !(model.provider === "ollama" && ollama))
1596
+ .map((model) => {
1597
+ const available = model.provider !== "ollama" && isProviderConfigured(model.provider);
1598
+ return {
1599
+ ...model,
1600
+ displayName: model.name,
1601
+ description: model.provider + " model",
1602
+ available,
1603
+ cloud: model.provider !== "ollama",
1604
+ tier: model.provider === "ollama" ? "local" : "cloud",
1605
+ contextWindow: 0,
1606
+ vision: false,
1607
+ tools: false,
1608
+ thinking: false,
1609
+ ...(available
1610
+ ? {}
1611
+ : {
1612
+ unavailableReason:
1613
+ model.provider === "ollama"
1614
+ ? "Ollama is not reachable at " + OLLAMA_URL + "."
1615
+ : "Add this provider's credentials to the environment to enable it.",
1616
+ }),
1617
+ };
1618
+ });
1619
+ return NextResponse.json({ models: [...(ollama ?? []), ...hosted] });
1620
+ }
1621
+
1622
+ `;
1623
+ var NEXT_GATEWAY_README_TEMPLATE = `# Next.js Gateway API
1624
+
1625
+ This directory contains a minimal Next.js App Router implementation of the Bandit gateway API. It mirrors the Express gateway in
1626
+ \`server/gateway.js\` but is ready to drop into a Next.js project.
1627
+
1628
+ ## Routes
1629
+
1630
+ - \`app/api/health/route.ts\` \u2013 provider health and availability checks
1631
+ - \`app/api/chat/completions/route.ts\` \u2013 provider-aware chat completions endpoint (Bandit AI, OpenAI, Azure OpenAI, Anthropic, xAI, Ollama)
1632
+ - \`app/api/models/route.ts\` \u2013 exposes the scaffolded gateway model metadata used by the frontend
1633
+
1634
+ ## Usage
1635
+
1636
+ 1. Copy the contents of \`server/next-app/\` into the \`app/\` directory of a Next.js project.
1637
+ 2. Ensure the environment variables listed in \`.env.example\` are available to the Next.js runtime. At minimum you will want the
1638
+ provider API keys you plan to use (Bandit AI, OpenAI, Azure OpenAI, Anthropic, xAI, or Ollama).
1639
+ 3. Start Next.js with \`npm run dev\` (or your project\u2019s equivalent). The routes are server-only (\`export const dynamic = "force-dynamic"\`)
1640
+ and can coexist with any frontend pages.
1641
+
1642
+ The generated routes favour clarity over cleverness so you can extend them with custom auth, logging, and provider routing logic.
1643
+ `;
1644
+ var buildNextChatRoute = (ctx) => {
1645
+ const fallbackModel = ctx.fallbackModelId ? `"${ctx.fallbackModelId}"` : "undefined";
1646
+ return ensureTrailingNewline(
1647
+ normalizeLineEndings(
1648
+ NEXT_CHAT_ROUTE_TEMPLATE.replace(/__DEFAULT_PROVIDER__/g, ctx.defaultProvider).replace(/__DEFAULT_MODEL__/g, ctx.defaultModelId).replace(/__FALLBACK_MODEL__/g, fallbackModel)
1649
+ )
1650
+ );
1651
+ };
1652
+ var buildNextHealthRoute = () => ensureTrailingNewline(normalizeLineEndings(NEXT_HEALTH_ROUTE_TEMPLATE));
1653
+ var buildNextModelsRoute = (ctx) => {
1654
+ const modelsDefinition = JSON.stringify(ctx.gatewayModels, null, 2);
1655
+ return ensureTrailingNewline(
1656
+ normalizeLineEndings(
1657
+ NEXT_MODELS_ROUTE_TEMPLATE.replace("__GATEWAY_MODELS__", modelsDefinition)
1658
+ )
1659
+ );
1660
+ };
1661
+ var buildNextGatewayReadme = () => ensureTrailingNewline(normalizeLineEndings(NEXT_GATEWAY_README_TEMPLATE));
1662
+ var buildGatewayServer = (ctx) => {
1663
+ const modelsDefinition = JSON.stringify(ctx.gatewayModels, null, 2);
1664
+ const gatewaySource = `import express from "express";
1665
+ import dotenv from "dotenv";
1666
+ import { createHash, timingSafeEqual } from "node:crypto";
1667
+
1668
+ dotenv.config();
1669
+
1670
+ const HOST = process.env.HOST || "127.0.0.1";
1671
+ const DEBUG = Boolean(process.env.DEBUG);
1672
+ const debugLog = (...args) => {
1673
+ if (DEBUG) console.log(...args);
1674
+ };
1675
+
1676
+ // ----------------------------------------------------------------------------
1677
+ // Access control
1678
+ //
1679
+ // Local development (default): the gateway listens on 127.0.0.1 and needs no
1680
+ // key. A secret in browser code protects nothing, so the browser never holds
1681
+ // one. Requests must be addressed to localhost (blocks DNS rebinding) and any
1682
+ // browser Origin must be allowed (CORS_ORIGINS, default: local origins only).
1683
+ // Any Authorization header the engine sends is ignored in this mode.
1684
+ //
1685
+ // Shared or remote use: set GATEWAY_API_KEY (32+ characters). Every request then
1686
+ // needs "Authorization: Bearer <key>", added by your own server or dev proxy.
1687
+ // A non-loopback HOST without a key refuses to start.
1688
+ // ----------------------------------------------------------------------------
1689
+ const LOOPBACK_NAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
1690
+ const DEFAULT_ORIGIN = /^http:\\/\\/(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d{1,5})?$/i;
1691
+ const isLoopbackHost = (host) => {
1692
+ const value = String(host || "").trim().toLowerCase();
1693
+ return LOOPBACK_NAMES.has(value) || /^127(\\.\\d{1,3}){3}$/.test(value);
1694
+ };
1695
+ const hostnameOf = (hostHeader) => {
1696
+ const value = String(hostHeader || "").trim().toLowerCase();
1697
+ if (value.startsWith("[")) return value.slice(0, value.indexOf("]") + 1);
1698
+ return value.split(":")[0];
1699
+ };
1700
+ const ALLOWED_ORIGINS = process.env.CORS_ORIGINS
1701
+ ? process.env.CORS_ORIGINS.split(",").map((item) => item.trim().replace(/\\/$/, "")).filter(Boolean)
1702
+ : null;
1703
+ const isOriginAllowed = (origin) => {
1704
+ if (!origin) return false;
1705
+ if (!ALLOWED_ORIGINS) return DEFAULT_ORIGIN.test(origin);
1706
+ return ALLOWED_ORIGINS.includes("*") || ALLOWED_ORIGINS.includes(origin.replace(/\\/$/, ""));
1707
+ };
1708
+ const GATEWAY_API_KEY = (process.env.GATEWAY_API_KEY || "").trim();
1709
+ if (GATEWAY_API_KEY && GATEWAY_API_KEY.length < 32) {
1710
+ console.error("GATEWAY_API_KEY must be a random secret of at least 32 characters (openssl rand -hex 32).");
1711
+ process.exit(1);
1712
+ }
1713
+ if (!GATEWAY_API_KEY && !isLoopbackHost(HOST)) {
1714
+ console.error("HOST=" + HOST + " exposes the gateway beyond this machine. Set GATEWAY_API_KEY to a random secret of at least 32 characters (openssl rand -hex 32), or keep HOST=127.0.0.1.");
1715
+ process.exit(1);
1716
+ }
1717
+ const expectedKeyHash = GATEWAY_API_KEY ? createHash("sha256").update(GATEWAY_API_KEY).digest() : null;
1718
+
1719
+ const app = express();
1720
+
1721
+ // CORS first, so the browser's preflight (which never carries credentials) is
1722
+ // answered before authentication.
1723
+ app.use((req, res, next) => {
1724
+ const origin = req.get("origin");
1725
+ const allowed = isOriginAllowed(origin);
1726
+ if (allowed) {
1727
+ res.setHeader("Access-Control-Allow-Origin", origin);
1728
+ res.setHeader("Vary", "Origin");
1729
+ res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
1730
+ res.setHeader("Access-Control-Allow-Headers", req.get("access-control-request-headers") || "Authorization, Content-Type");
1731
+ res.setHeader("Access-Control-Max-Age", "600");
1732
+ }
1733
+ if (req.method === "OPTIONS") {
1734
+ res.status(allowed ? 204 : 403).end();
1735
+ return;
1736
+ }
1737
+ next();
1738
+ });
1739
+
1740
+ app.use((req, res, next) => {
1741
+ if (expectedKeyHash) {
1742
+ const match = /^Bearer ([^\\s]+)$/i.exec(req.get("authorization") || "");
1743
+ const actual = createHash("sha256").update(match ? match[1] : "").digest();
1744
+ if (!match || !timingSafeEqual(expectedKeyHash, actual)) {
1745
+ res.setHeader("WWW-Authenticate", "Bearer");
1746
+ return res.status(401).json({ error: "Authentication required" });
1747
+ }
1748
+ return next();
1749
+ }
1750
+ if (!isLoopbackHost(hostnameOf(req.get("host")))) {
1751
+ return res.status(403).json({ error: "This keyless gateway only accepts requests addressed to localhost. Set GATEWAY_API_KEY to serve other hosts." });
1752
+ }
1753
+ const origin = req.get("origin");
1754
+ if (origin && !isOriginAllowed(origin)) {
1755
+ return res.status(403).json({ error: "Origin " + origin + " is not allowed. Add it to CORS_ORIGINS." });
1756
+ }
1757
+ next();
1758
+ });
1759
+
1760
+ // Stop in the UI closes the browser request; every upstream fetch uses this
1761
+ // signal so the provider (an Ollama queue in particular) stops generating too.
1762
+ app.use((req, res, next) => {
1763
+ const controller = new AbortController();
1764
+ res.locals.abortSignal = controller.signal;
1765
+ res.on("close", () => {
1766
+ if (!res.writableEnded) controller.abort();
1767
+ });
1768
+ if (DEBUG) {
1769
+ const started = Date.now();
1770
+ res.on("close", () => {
1771
+ console.log(req.method + " " + req.originalUrl + " -> " + res.statusCode + " " + (Date.now() - started) + "ms" + (res.writableFinished ? "" : " (client closed)"));
1772
+ });
1773
+ }
1774
+ next();
1775
+ });
1776
+
1777
+ app.use(express.json({ limit: '50mb' }));
1778
+ // The engine calls Azure OpenAI routes under /api/azure-openai/*; serve them from /api/azure/*.
1779
+ app.use((req, _res, next) => {
1780
+ if (req.url.startsWith("/api/azure-openai/")) req.url = "/api/azure/" + req.url.slice("/api/azure-openai/".length);
1781
+ next();
1782
+ });
1783
+ app.use(express.urlencoded({ limit: '50mb', extended: true }));
1784
+
1785
+ const QUICKSTART_VERSION = "0.1.0";
1786
+ const DEFAULT_PROVIDER = "${ctx.defaultProvider}";
1787
+ const BASE_GATEWAY_MODELS = ${modelsDefinition};
1788
+ const BANDIT_API_KEY = process.env.BANDIT_API_KEY;
1789
+ const BANDIT_BASE_URL = (process.env.BANDIT_BASE_URL ?? "https://api.burtson.ai").replace(/\\/$/, "");
1790
+ const OLLAMA_BASE_URL = (process.env.OLLAMA_URL ?? "http://localhost:11434").replace(/\\/$/, "");
1791
+ const AZURE_OPENAI_ENDPOINT = process.env.AZURE_OPENAI_ENDPOINT ? process.env.AZURE_OPENAI_ENDPOINT.replace(/\\/$/, "") : undefined;
1792
+ const AZURE_OPENAI_API_KEY = process.env.AZURE_OPENAI_API_KEY;
1793
+ const AZURE_OPENAI_API_VERSION = process.env.AZURE_OPENAI_API_VERSION ?? "2024-08-01-preview";
1794
+ const AZURE_OPENAI_CHAT_DEPLOYMENT = process.env.AZURE_OPENAI_CHAT_DEPLOYMENT;
1795
+ const AZURE_OPENAI_COMPLETIONS_DEPLOYMENT = process.env.AZURE_OPENAI_COMPLETIONS_DEPLOYMENT ?? AZURE_OPENAI_CHAT_DEPLOYMENT;
1796
+ const AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT = process.env.AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT;
1797
+ const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
1798
+ const ANTHROPIC_BASE_URL = (process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com").replace(/\\/$/, "");
1799
+ const ANTHROPIC_API_VERSION = process.env.ANTHROPIC_API_VERSION ?? "2023-06-01";
1800
+ const ANTHROPIC_MAX_TOKENS = Number.isFinite(Number(process.env.ANTHROPIC_MAX_TOKENS))
1801
+ ? Number(process.env.ANTHROPIC_MAX_TOKENS)
1802
+ : 1024;
1803
+ const XAI_API_KEY = process.env.XAI_API_KEY;
1804
+ const XAI_BASE_URL = (process.env.XAI_BASE_URL ?? "https://api.x.ai/v1").replace(/\\/$/, "");
1805
+
1806
+ const toGatewayModels = () =>
1807
+ BASE_GATEWAY_MODELS.map((model) => ({
1808
+ ...model,
1809
+ created: Date.now(),
1810
+ modified_at: new Date().toISOString(),
1811
+ size: 0,
1812
+ digest: "",
1813
+ details: {
1814
+ format: "chat",
1815
+ family: model.provider,
1816
+ families: [model.provider],
1817
+ parameter_size: "",
1818
+ quantization_level: "",
1819
+ },
1820
+ }));
1821
+
1822
+ const stripAzureModelPrefix = (value) =>
1823
+ typeof value === "string" ? value.replace(/^azure:/, "") : undefined;
1824
+
1825
+ const requireBanditKey = () => {
1826
+ if (!BANDIT_API_KEY) {
1827
+ throw new Error("Missing BANDIT_API_KEY. Add it to your .env file to route requests to Bandit AI.");
1828
+ }
1829
+ return BANDIT_API_KEY;
1830
+ };
1831
+
1832
+ const isAzureConfigured = () => Boolean(AZURE_OPENAI_ENDPOINT && AZURE_OPENAI_API_KEY);
1833
+
1834
+ const requireAzureBaseConfig = () => {
1835
+ if (!AZURE_OPENAI_ENDPOINT) {
1836
+ throw new Error("Missing AZURE_OPENAI_ENDPOINT. Add it to your .env file to route requests to Azure OpenAI.");
1837
+ }
1838
+ if (!AZURE_OPENAI_API_KEY) {
1839
+ throw new Error("Missing AZURE_OPENAI_API_KEY. Add it to your .env file to route requests to Azure OpenAI.");
1840
+ }
1841
+ return {
1842
+ endpoint: AZURE_OPENAI_ENDPOINT,
1843
+ apiKey: AZURE_OPENAI_API_KEY,
1844
+ apiVersion: AZURE_OPENAI_API_VERSION,
1845
+ };
1846
+ };
1847
+
1848
+ const resolveAzureDeployment = (explicitValue, fallbackValue, kind) => {
1849
+ const fromRequest = stripAzureModelPrefix(explicitValue);
1850
+ if (fromRequest) {
1851
+ return fromRequest;
1852
+ }
1853
+ if (fallbackValue) {
1854
+ return fallbackValue;
1855
+ }
1856
+ throw new Error(\`Missing Azure OpenAI \${kind} deployment name. Set AZURE_OPENAI_\${kind.toUpperCase()}_DEPLOYMENT in your .env file.\`);
1857
+ };
1858
+
1859
+ const buildAzureDeploymentUrl = (deployment, suffix) => {
1860
+ const { endpoint } = requireAzureBaseConfig();
1861
+ const normalizedSuffix = suffix.replace(/^\\//, "");
1862
+ return \`\${endpoint}/openai/deployments/\${deployment}/\${normalizedSuffix}?api-version=\${AZURE_OPENAI_API_VERSION}\`;
1863
+ };
1864
+
1865
+ const buildAzurePath = (suffix) => {
1866
+ const { endpoint } = requireAzureBaseConfig();
1867
+ const normalizedSuffix = suffix.replace(/^\\//, "");
1868
+ const hasQuery = normalizedSuffix.includes("?");
1869
+ const separator = hasQuery ? "&" : "?";
1870
+ return \`\${endpoint}/openai/\${normalizedSuffix}\${separator}api-version=\${AZURE_OPENAI_API_VERSION}\`;
1871
+ };
1872
+
1873
+ const stripAnthropicModelPrefix = (value) =>
1874
+ typeof value === "string" ? value.replace(/^anthropic:/, "") : undefined;
1875
+
1876
+ const isAnthropicConfigured = () => Boolean(ANTHROPIC_API_KEY);
1877
+
1878
+ const requireAnthropicKey = () => {
1879
+ if (!ANTHROPIC_API_KEY) {
1880
+ throw new Error("Missing ANTHROPIC_API_KEY. Add it to your .env file to route requests to Anthropic.");
1881
+ }
1882
+ return ANTHROPIC_API_KEY;
1883
+ };
1884
+
1885
+ const buildAnthropicUrl = (path) => {
1886
+ const normalized = path.replace(/^\\//, "");
1887
+ return \`\${ANTHROPIC_BASE_URL}/v1/\${normalized}\`;
1888
+ };
1889
+
1890
+ const buildAnthropicHeaders = () => ({
1891
+ "Content-Type": "application/json",
1892
+ "x-api-key": requireAnthropicKey(),
1893
+ "anthropic-version": ANTHROPIC_API_VERSION,
1894
+ });
1895
+
1896
+ const flattenGatewayContent = (content) => {
1897
+ if (typeof content === "string") {
1898
+ return content;
1899
+ }
1900
+ if (Array.isArray(content)) {
1901
+ return content
1902
+ .map((part) => {
1903
+ if (typeof part === "string") {
1904
+ return part;
1905
+ }
1906
+ if (part?.type === "text" && typeof part.text === "string") {
1907
+ return part.text;
1908
+ }
1909
+ if (part?.type === "image_url" && part.image_url?.url) {
1910
+ return \`[Image: \${part.image_url.url}]\`;
1911
+ }
1912
+ return JSON.stringify(part ?? {});
1913
+ })
1914
+ .join("\\n");
1915
+ }
1916
+ if (content && typeof content === "object") {
1917
+ return JSON.stringify(content);
1918
+ }
1919
+ return "";
1920
+ };
1921
+
1922
+ const normalizeGatewayImageUrl = (value) => {
1923
+ if (!value) {
1924
+ return "";
1925
+ }
1926
+ if (typeof value === "string") {
1927
+ const trimmed = value.trim();
1928
+ if (!trimmed) {
1929
+ return "";
1930
+ }
1931
+ if (/^data:/i.test(trimmed) || /^https?:/i.test(trimmed)) {
1932
+ return trimmed;
1933
+ }
1934
+ return 'data:image/jpeg;base64,' + trimmed;
1935
+ }
1936
+ if (typeof value === "object") {
1937
+ const possibleUrl =
1938
+ typeof value.url === "string"
1939
+ ? value.url
1940
+ : value.image_url && typeof value.image_url.url === "string"
1941
+ ? value.image_url.url
1942
+ : "";
1943
+ return normalizeGatewayImageUrl(possibleUrl);
1944
+ }
1945
+ return "";
1946
+ };
1947
+
1948
+ const extractGatewayImageDetail = (value) => {
1949
+ if (value && typeof value === "object") {
1950
+ const record = value;
1951
+ if (typeof record.detail === "string" && record.detail.trim()) {
1952
+ return record.detail;
1953
+ }
1954
+ if (record.image_url && typeof record.image_url.detail === "string" && record.image_url.detail.trim()) {
1955
+ return record.image_url.detail;
1956
+ }
1957
+ }
1958
+ return undefined;
1959
+ };
1960
+
1961
+ const toAnthropicMessages = (messages = []) => {
1962
+ const anthropicMessages = [];
1963
+ let systemPrompt = "";
1964
+
1965
+ for (const message of messages) {
1966
+ if (!message) continue;
1967
+ const text = flattenGatewayContent(message.content);
1968
+
1969
+ if (message.role === "system") {
1970
+ systemPrompt = systemPrompt ? \`\${systemPrompt}\\n\\n\${text}\` : text;
1971
+ continue;
1972
+ }
1973
+
1974
+ const role = message.role === "assistant" ? "assistant" : "user";
1975
+ anthropicMessages.push({
1976
+ role,
1977
+ content: [{ type: "text", text }],
1978
+ });
1979
+ }
1980
+
1981
+ return { messages: anthropicMessages, system: systemPrompt || undefined };
1982
+ };
1983
+
1984
+ const convertAnthropicResponseToGateway = (responseBody, modelName) => {
1985
+ if (!responseBody) {
1986
+ return {
1987
+ id: \`anthropic-\${Date.now()}\`,
1988
+ object: "chat.completion",
1989
+ created: Math.floor(Date.now() / 1000),
1990
+ model: modelName.startsWith("anthropic:") ? modelName : \`anthropic:\${modelName}\`,
1991
+ choices: [],
1992
+ };
1993
+ }
1994
+
1995
+ const textContent = Array.isArray(responseBody.content)
1996
+ ? responseBody.content
1997
+ .filter((item) => item && item.type === "text" && typeof item.text === "string")
1998
+ .map((item) => item.text)
1999
+ .join("\\n")
2000
+ : typeof responseBody.content === "string"
2001
+ ? responseBody.content
2002
+ : "";
2003
+
2004
+ const promptTokens = responseBody.usage?.input_tokens ?? 0;
2005
+ const completionTokens = responseBody.usage?.output_tokens ?? 0;
2006
+
2007
+ return {
2008
+ id: responseBody.id ?? \`anthropic-\${Date.now()}\`,
2009
+ object: "chat.completion",
2010
+ created: Math.floor(Date.now() / 1000),
2011
+ model: modelName.startsWith("anthropic:") ? modelName : \`anthropic:\${modelName}\`,
2012
+ choices: [
2013
+ {
2014
+ index: 0,
2015
+ message: {
2016
+ role: responseBody.role ?? "assistant",
2017
+ content: textContent,
2018
+ },
2019
+ finish_reason: responseBody.stop_reason ?? responseBody.stop_sequence ?? null,
2020
+ },
2021
+ ],
2022
+ usage: responseBody.usage
2023
+ ? {
2024
+ prompt_tokens: promptTokens,
2025
+ completion_tokens: completionTokens,
2026
+ total_tokens: promptTokens + completionTokens,
2027
+ }
2028
+ : undefined,
2029
+ };
2030
+ };
2031
+
2032
+ const convertAnthropicResponseToGenerate = (responseBody, modelName) => {
2033
+ const gatewayResponse = convertAnthropicResponseToGateway(responseBody, modelName);
2034
+ const content = gatewayResponse.choices?.[0]?.message?.content ?? "";
2035
+ return {
2036
+ model: gatewayResponse.model,
2037
+ created_at: new Date().toISOString(),
2038
+ response: content,
2039
+ done: true,
2040
+ total_duration: 0,
2041
+ load_duration: 0,
2042
+ prompt_eval_count: gatewayResponse.usage?.prompt_tokens ?? 0,
2043
+ prompt_eval_duration: 0,
2044
+ eval_count: gatewayResponse.usage?.completion_tokens ?? 0,
2045
+ eval_duration: 0,
2046
+ };
2047
+ };
2048
+
2049
+ const requireOpenAIKey = () => {
2050
+ const key = process.env.OPENAI_API_KEY;
2051
+ if (!key) {
2052
+ throw new Error("Missing OPENAI_API_KEY. Add it to your .env file to route requests to OpenAI.");
2053
+ }
2054
+ return key;
2055
+ };
2056
+
2057
+ const requireXAIKey = () => {
2058
+ const key = XAI_API_KEY;
2059
+ if (!key) {
2060
+ throw new Error("Missing XAI_API_KEY. Add it to your .env file to route requests to xAI.");
2061
+ }
2062
+ return key;
2063
+ };
2064
+
2065
+ // Streaming keepalive. Cloudflare drops a proxied connection after 100 s with
2066
+ // no bytes (HTTP 524) and nginx buffers responses unless told not to, so every
2067
+ // streaming response sends the anti-buffering headers and a keepalive every
2068
+ // 20 s of silence (model cold-load, a slow first token). The keepalive is
2069
+ // only written on a frame boundary so it never splits an upstream frame:
2070
+ // SSE gets a comment line, NDJSON gets a single space the client trims.
2071
+ const KEEPALIVE_INTERVAL_MS = 20000;
2072
+
2073
+ const setStreamingHeaders = (res, contentType) => {
2074
+ res.setHeader('Content-Type', contentType);
2075
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
2076
+ res.setHeader('X-Accel-Buffering', 'no');
2077
+ res.setHeader('Connection', 'keep-alive');
2078
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
2079
+ };
2080
+
2081
+ const startKeepalive = (res, format) => {
2082
+ const keepalive = format === 'sse' ? ': ping\\n\\n' : ' ';
2083
+ const boundary = format === 'sse' ? '\\n\\n' : '\\n';
2084
+ let tail = boundary;
2085
+ let lastWrite = Date.now();
2086
+ const timer = setInterval(() => {
2087
+ if (res.writableEnded || Date.now() - lastWrite < KEEPALIVE_INTERVAL_MS) return;
2088
+ if (!tail.endsWith(boundary)) return;
2089
+ res.write(keepalive);
2090
+ lastWrite = Date.now();
2091
+ }, 5000);
2092
+ timer.unref?.();
2093
+ return {
2094
+ write(chunk) {
2095
+ const text = typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
2096
+ tail = (tail + text).slice(-2);
2097
+ lastWrite = Date.now();
2098
+ res.write(chunk);
2099
+ },
2100
+ stop() {
2101
+ clearInterval(timer);
2102
+ },
2103
+ };
2104
+ };
2105
+
2106
+ // Utility function to handle streaming responses
2107
+ const handleStreamingResponse = async (upstreamResponse, res) => {
2108
+ const upstreamType = upstreamResponse.headers.get('content-type') ?? '';
2109
+ const format = upstreamType.includes('text/event-stream') ? 'sse' : 'ndjson';
2110
+ setStreamingHeaders(res, 'text/event-stream');
2111
+ const stream = startKeepalive(res, format);
2112
+
2113
+ try {
2114
+ // Get the readable stream from the response
2115
+ const reader = upstreamResponse.body.getReader();
2116
+
2117
+ while (true) {
2118
+ const { done, value } = await reader.read();
2119
+ if (done) break;
2120
+
2121
+ // Write the chunk to the response
2122
+ stream.write(value);
2123
+ }
2124
+
2125
+ res.end();
2126
+ } catch (error) {
2127
+ if (error?.name !== 'AbortError') console.error('Streaming error:', error);
2128
+ // Headers (and possibly bytes) are already sent, so the only honest
2129
+ // thing left is to end the response.
2130
+ res.end();
2131
+ } finally {
2132
+ stream.stop();
2133
+ }
2134
+ };
2135
+
2136
+ const relayAnthropicStream = async (upstreamResponse, res) => {
2137
+ setStreamingHeaders(res, 'text/event-stream');
2138
+ const stream = startKeepalive(res, 'sse');
2139
+
2140
+ const reader = upstreamResponse.body?.getReader();
2141
+ if (!reader) {
2142
+ const fallback = await upstreamResponse.text();
2143
+ stream.stop();
2144
+ res.write("data: " + JSON.stringify({ choices: [{ delta: { content: fallback } }] }) + "\\n\\n");
2145
+ res.write("data: [DONE]\\n\\n");
2146
+ return res.end();
2147
+ }
2148
+
2149
+ const decoder = new TextDecoder();
2150
+ let buffer = '';
2151
+
2152
+ const sendChunk = (payload) => {
2153
+ stream.write("data: " + JSON.stringify(payload) + "\\n\\n");
2154
+ };
2155
+
2156
+ try {
2157
+ while (true) {
2158
+ const { value, done } = await reader.read();
2159
+ if (done) break;
2160
+ buffer += decoder.decode(value, { stream: true });
2161
+
2162
+ let delimiterIndex;
2163
+ while ((delimiterIndex = buffer.indexOf('\\n\\n')) >= 0) {
2164
+ const rawEvent = buffer.slice(0, delimiterIndex).trim();
2165
+ buffer = buffer.slice(delimiterIndex + 2);
2166
+ if (!rawEvent) continue;
2167
+
2168
+ const lines = rawEvent.split('\\n');
2169
+ const eventLine = lines.find((line) => line.startsWith('event:')) ?? '';
2170
+ const dataLine = lines.find((line) => line.startsWith('data:')) ?? '';
2171
+ const event = eventLine.replace('event:', '').trim();
2172
+ const trimmedData = dataLine.replace('data:', '').trim();
2173
+
2174
+ if (!trimmedData) {
2175
+ continue;
2176
+ }
2177
+
2178
+ let parsed;
2179
+ try {
2180
+ parsed = JSON.parse(trimmedData);
2181
+ } catch (error) {
2182
+ console.error('Anthropic stream parse error', error, { rawEvent });
2183
+ continue;
2184
+ }
2185
+
2186
+ if (event === 'content_block_delta') {
2187
+ const textChunk = parsed?.delta?.text ?? '';
2188
+ if (textChunk) {
2189
+ sendChunk({
2190
+ choices: [
2191
+ {
2192
+ delta: {
2193
+ content: textChunk,
2194
+ },
2195
+ },
2196
+ ],
2197
+ });
2198
+ }
2199
+ } else if (event === 'message_stop') {
2200
+ sendChunk({
2201
+ choices: [
2202
+ {
2203
+ delta: {},
2204
+ finish_reason: 'stop',
2205
+ },
2206
+ ],
2207
+ });
2208
+ }
2209
+ }
2210
+ }
2211
+ } catch (error) {
2212
+ console.error('Anthropic streaming relay error', error);
2213
+ sendChunk({
2214
+ error: error instanceof Error ? error.message : String(error),
2215
+ });
2216
+ } finally {
2217
+ stream.stop();
2218
+ res.write("data: [DONE]\\n\\n");
2219
+ res.end();
2220
+ }
2221
+ };
2222
+
2223
+ // ============================================================================
2224
+ // GENERAL HEALTH & MODELS
2225
+ // ============================================================================
2226
+
2227
+ app.get("/api/health", async (_req, res) => {
2228
+ const providers = [];
2229
+
2230
+ // Check OpenAI
2231
+ try {
2232
+ const openaiKey = process.env.OPENAI_API_KEY;
2233
+ if (openaiKey) {
2234
+ const response = await fetch("https://api.openai.com/v1/models", {
2235
+ signal: res.locals.abortSignal,
2236
+ headers: { "Authorization": \`Bearer \${openaiKey}\` }
2237
+ });
2238
+ providers.push({
2239
+ name: "openai",
2240
+ status: response.ok ? "healthy" : "unhealthy",
2241
+ provider: "openai"
2242
+ });
2243
+ } else {
2244
+ providers.push({
2245
+ name: "openai",
2246
+ status: "unconfigured",
2247
+ provider: "openai",
2248
+ error: "API key not configured"
2249
+ });
2250
+ }
2251
+ } catch (error) {
2252
+ providers.push({
2253
+ name: "openai",
2254
+ status: "unhealthy",
2255
+ provider: "openai",
2256
+ error: error.message
2257
+ });
2258
+ }
2259
+
2260
+ // Check Azure OpenAI
2261
+ if (AZURE_OPENAI_ENDPOINT || AZURE_OPENAI_API_KEY) {
2262
+ if (!isAzureConfigured()) {
2263
+ providers.push({
2264
+ name: "azure",
2265
+ status: "unconfigured",
2266
+ provider: "azure",
2267
+ error: "Endpoint or API key not configured",
2268
+ endpoint: AZURE_OPENAI_ENDPOINT
2269
+ });
2270
+ } else {
2271
+ try {
2272
+ const { endpoint } = requireAzureBaseConfig();
2273
+ const deploymentsUrl = buildAzurePath("deployments");
2274
+ const response = await fetch(deploymentsUrl, {
2275
+ signal: res.locals.abortSignal,
2276
+ headers: { "api-key": AZURE_OPENAI_API_KEY }
2277
+ });
2278
+ providers.push({
2279
+ name: "azure",
2280
+ status: response.ok ? "healthy" : "unhealthy",
2281
+ provider: "azure",
2282
+ endpoint
2283
+ });
2284
+ } catch (error) {
2285
+ providers.push({
2286
+ name: "azure",
2287
+ status: "unhealthy",
2288
+ provider: "azure",
2289
+ error: error instanceof Error ? error.message : String(error),
2290
+ endpoint: AZURE_OPENAI_ENDPOINT
2291
+ });
2292
+ }
2293
+ }
2294
+ } else {
2295
+ providers.push({
2296
+ name: "azure",
2297
+ status: "unconfigured",
2298
+ provider: "azure",
2299
+ error: "Endpoint or API key not configured"
2300
+ });
2301
+ }
2302
+
2303
+ // Check Anthropic
2304
+ if (ANTHROPIC_API_KEY) {
2305
+ try {
2306
+ const response = await fetch(buildAnthropicUrl("models"), {
2307
+ signal: res.locals.abortSignal,
2308
+ headers: buildAnthropicHeaders(),
2309
+ method: "GET"
2310
+ });
2311
+ providers.push({
2312
+ name: "anthropic",
2313
+ status: response.ok ? "healthy" : "unhealthy",
2314
+ provider: "anthropic",
2315
+ endpoint: ANTHROPIC_BASE_URL
2316
+ });
2317
+ } catch (error) {
2318
+ providers.push({
2319
+ name: "anthropic",
2320
+ status: "unhealthy",
2321
+ provider: "anthropic",
2322
+ error: error instanceof Error ? error.message : String(error),
2323
+ endpoint: ANTHROPIC_BASE_URL
2324
+ });
2325
+ }
2326
+ } else {
2327
+ providers.push({
2328
+ name: "anthropic",
2329
+ status: "unconfigured",
2330
+ provider: "anthropic",
2331
+ error: "API key not configured"
2332
+ });
2333
+ }
2334
+
2335
+ // Check xAI
2336
+ if (XAI_API_KEY) {
2337
+ try {
2338
+ const response = await fetch(XAI_BASE_URL + "/models", {
2339
+ signal: res.locals.abortSignal,
2340
+ headers: { "Authorization": "Bearer " + XAI_API_KEY }
2341
+ });
2342
+ providers.push({
2343
+ name: "xai",
2344
+ status: response.ok ? "healthy" : "unhealthy",
2345
+ provider: "xai",
2346
+ endpoint: XAI_BASE_URL
2347
+ });
2348
+ } catch (error) {
2349
+ providers.push({
2350
+ name: "xai",
2351
+ status: "unhealthy",
2352
+ provider: "xai",
2353
+ error: error instanceof Error ? error.message : String(error),
2354
+ endpoint: XAI_BASE_URL
2355
+ });
2356
+ }
2357
+ } else {
2358
+ providers.push({
2359
+ name: "xai",
2360
+ status: "unconfigured",
2361
+ provider: "xai",
2362
+ error: "API key not configured",
2363
+ endpoint: XAI_BASE_URL
2364
+ });
2365
+ }
2366
+
2367
+ // Check Ollama
2368
+ try {
2369
+ debugLog(\`Checking Ollama health at: \${OLLAMA_BASE_URL}/api/tags\`);
2370
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/tags\`);
2371
+ const status = response.ok ? "healthy" : "unhealthy";
2372
+ debugLog(\`Ollama health check result: \${status}\`);
2373
+ providers.push({
2374
+ name: "ollama",
2375
+ status: status,
2376
+ provider: "ollama",
2377
+ url: OLLAMA_BASE_URL
2378
+ });
2379
+ } catch (error) {
2380
+ debugLog(\`Ollama health check error: \${error.message}\`);
2381
+ providers.push({
2382
+ name: "ollama",
2383
+ status: "offline",
2384
+ provider: "ollama",
2385
+ error: error.message,
2386
+ url: OLLAMA_BASE_URL
2387
+ });
2388
+ }
2389
+
2390
+ const overallHealthy = providers.some(p => p.status === "healthy");
2391
+
2392
+ res.json({
2393
+ status: overallHealthy ? "healthy" : "unhealthy",
2394
+ version: QUICKSTART_VERSION,
2395
+ uptime: Math.round(process.uptime()),
2396
+ providers
2397
+ });
2398
+ });
2399
+
2400
+ // GET /api/models returns { models: GatewayEngineModel[] } \u2014 the shape the
2401
+ // engine's model picker reads (id, displayName, description, available, ...).
2402
+ const isProviderConfigured = (provider) => {
2403
+ switch (provider) {
2404
+ case "openai": return Boolean(process.env.OPENAI_API_KEY);
2405
+ case "azure": return isAzureConfigured();
2406
+ case "anthropic": return isAnthropicConfigured();
2407
+ case "xai": return Boolean(XAI_API_KEY);
2408
+ case "bandit": return Boolean(BANDIT_API_KEY);
2409
+ case "ollama": return true;
2410
+ default: return false;
2411
+ }
2412
+ };
2413
+
2414
+ const fetchWithTimeout = async (url, options = {}, timeoutMs = 2000) => {
2415
+ const controller = new AbortController();
2416
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2417
+ try {
2418
+ return await fetch(url, { ...options, signal: controller.signal });
2419
+ } finally {
2420
+ clearTimeout(timer);
2421
+ }
2422
+ };
2423
+
2424
+ const ollamaCapabilities = async (name) => {
2425
+ try {
2426
+ const response = await fetchWithTimeout(OLLAMA_BASE_URL + "/api/show", {
2427
+ method: "POST",
2428
+ headers: { "Content-Type": "application/json" },
2429
+ body: JSON.stringify({ model: name })
2430
+ });
2431
+ if (!response.ok) return [];
2432
+ const body = await response.json();
2433
+ return Array.isArray(body?.capabilities) ? body.capabilities : [];
2434
+ } catch {
2435
+ return [];
2436
+ }
2437
+ };
2438
+
2439
+ // Installed Ollama models, skipping ":cloud" proxies and embedding-only models.
2440
+ const listOllamaModels = async () => {
2441
+ const response = await fetchWithTimeout(OLLAMA_BASE_URL + "/api/tags");
2442
+ if (!response.ok) throw new Error("Ollama /api/tags returned " + response.status);
2443
+ const body = await response.json();
2444
+ const installed = (Array.isArray(body?.models) ? body.models : []).filter(
2445
+ (model) => typeof model?.name === "string" && !model.name.endsWith(":cloud")
2446
+ );
2447
+ const entries = await Promise.all(
2448
+ installed.map(async (model) => {
2449
+ const capabilities = await ollamaCapabilities(model.name);
2450
+ if (capabilities.length > 0 && !capabilities.includes("completion")) return null;
2451
+ const details = model.details ?? {};
2452
+ return {
2453
+ id: model.name,
2454
+ name: model.name,
2455
+ displayName: model.name,
2456
+ description: [details.family, details.parameter_size, details.quantization_level].filter(Boolean).join(" "),
2457
+ provider: "ollama",
2458
+ available: true,
2459
+ cloud: false,
2460
+ tier: "local",
2461
+ contextWindow: 0,
2462
+ vision: capabilities.includes("vision"),
2463
+ tools: capabilities.includes("tools"),
2464
+ thinking: capabilities.includes("thinking"),
2465
+ size: model.size,
2466
+ digest: model.digest,
2467
+ modified_at: model.modified_at,
2468
+ details
2469
+ };
2470
+ })
2471
+ );
2472
+ return entries.filter(Boolean);
2473
+ };
2474
+
2475
+ const listModels = async (providerFilter) => {
2476
+ const wantsOllama = !providerFilter || providerFilter === "ollama";
2477
+ let ollama = null;
2478
+ if (wantsOllama) {
2479
+ try {
2480
+ ollama = await listOllamaModels();
2481
+ } catch (error) {
2482
+ debugLog("Ollama model listing failed: " + (error?.message ?? error));
2483
+ }
2484
+ }
2485
+ const staticModels = toGatewayModels()
2486
+ .filter((model) => !providerFilter || model.provider === providerFilter)
2487
+ // Discovered Ollama models replace the scaffold's placeholder Ollama entries.
2488
+ .filter((model) => !(model.provider === "ollama" && ollama))
2489
+ .map((model) => {
2490
+ const configured = isProviderConfigured(model.provider);
2491
+ const available = configured && model.provider !== "ollama";
2492
+ return {
2493
+ ...model,
2494
+ displayName: model.name,
2495
+ description: model.provider + " model",
2496
+ available,
2497
+ cloud: model.provider !== "ollama",
2498
+ tier: model.provider === "ollama" ? "local" : "cloud",
2499
+ contextWindow: 0,
2500
+ vision: false,
2501
+ tools: false,
2502
+ thinking: false,
2503
+ ...(available
2504
+ ? {}
2505
+ : {
2506
+ unavailableReason:
2507
+ model.provider === "ollama"
2508
+ ? "Ollama is not reachable at " + OLLAMA_BASE_URL + "."
2509
+ : "Add this provider's credentials to .env to enable it."
2510
+ })
2511
+ };
2512
+ });
2513
+ return [...(ollama ?? []), ...staticModels];
2514
+ };
2515
+
2516
+ app.get("/api/models", async (_req, res) => {
2517
+ res.json({ models: await listModels() });
2518
+ });
2519
+
2520
+ app.get("/api/models/:provider", async (req, res) => {
2521
+ res.json({ models: await listModels(req.params.provider) });
2522
+ });
2523
+
2524
+ // ============================================================================
2525
+ // ANTHROPIC ROUTES
2526
+ // ============================================================================
2527
+
2528
+ app.get("/api/anthropic/health", async (_req, res) => {
2529
+ try {
2530
+ requireAnthropicKey();
2531
+ const response = await fetch(buildAnthropicUrl("models"), {
2532
+ signal: res.locals.abortSignal,
2533
+ method: "GET",
2534
+ headers: buildAnthropicHeaders()
2535
+ });
2536
+ const isHealthy = response.ok;
2537
+ res.json({
2538
+ status: isHealthy ? "healthy" : "unhealthy",
2539
+ anthropic_status: isHealthy,
2540
+ provider: "anthropic",
2541
+ endpoint: ANTHROPIC_BASE_URL
2542
+ });
2543
+ } catch (error) {
2544
+ const message = error instanceof Error ? error.message : String(error);
2545
+ res.status(503).json({
2546
+ status: "unhealthy",
2547
+ anthropic_status: false,
2548
+ provider: "anthropic",
2549
+ error: message,
2550
+ endpoint: ANTHROPIC_BASE_URL
2551
+ });
2552
+ }
2553
+ });
2554
+
2555
+ app.post("/api/anthropic/chat/completions", async (req, res) => {
2556
+ try {
2557
+ requireAnthropicKey();
2558
+ const rawBody = req.body ?? {};
2559
+ const isStreaming = rawBody.stream === true;
2560
+ const requestedModel =
2561
+ stripAnthropicModelPrefix(rawBody.model) ??
2562
+ stripAnthropicModelPrefix("${ctx.defaultModelId}") ??
2563
+ "claude-3-5-haiku-latest";
2564
+
2565
+ const stopSequences = Array.isArray(rawBody.stop)
2566
+ ? rawBody.stop
2567
+ : Array.isArray(rawBody.stop_sequences)
2568
+ ? rawBody.stop_sequences
2569
+ : rawBody.stop
2570
+ ? [rawBody.stop]
2571
+ : undefined;
2572
+
2573
+ const { messages: anthropicMessages, system } = toAnthropicMessages(
2574
+ Array.isArray(rawBody.messages) ? rawBody.messages : []
2575
+ );
2576
+
2577
+ const fallbackText =
2578
+ typeof rawBody.prompt === "string" && rawBody.prompt.trim().length > 0
2579
+ ? rawBody.prompt
2580
+ : "Hello from Bandit quickstart gateway";
2581
+
2582
+ const requestBody = {
2583
+ model: requestedModel,
2584
+ messages:
2585
+ anthropicMessages.length > 0
2586
+ ? anthropicMessages
2587
+ : [
2588
+ {
2589
+ role: "user",
2590
+ content: [{ type: "text", text: fallbackText }],
2591
+ },
2592
+ ],
2593
+ stream: isStreaming,
2594
+ max_tokens:
2595
+ typeof rawBody.max_tokens === "number" && rawBody.max_tokens > 0
2596
+ ? rawBody.max_tokens
2597
+ : ANTHROPIC_MAX_TOKENS,
2598
+ };
2599
+
2600
+ if (system) {
2601
+ requestBody.system = system;
2602
+ }
2603
+ if (typeof rawBody.temperature === "number") {
2604
+ requestBody.temperature = rawBody.temperature;
2605
+ }
2606
+ if (typeof rawBody.top_p === "number") {
2607
+ requestBody.top_p = rawBody.top_p;
2608
+ }
2609
+ if (typeof rawBody.top_k === "number") {
2610
+ requestBody.top_k = rawBody.top_k;
2611
+ }
2612
+ if (stopSequences) {
2613
+ requestBody.stop_sequences = stopSequences;
2614
+ }
2615
+ if (rawBody.metadata) {
2616
+ requestBody.metadata = rawBody.metadata;
2617
+ }
2618
+ if (rawBody.tools) {
2619
+ requestBody.tools = rawBody.tools;
2620
+ }
2621
+ if (rawBody.tool_choice) {
2622
+ requestBody.tool_choice = rawBody.tool_choice;
2623
+ }
2624
+ if (rawBody.thinking) {
2625
+ requestBody.thinking = rawBody.thinking;
2626
+ }
2627
+ if (rawBody.extra_headers) {
2628
+ requestBody.extra_headers = rawBody.extra_headers;
2629
+ }
2630
+
2631
+ const response = await fetch(buildAnthropicUrl("messages"), {
2632
+ signal: res.locals.abortSignal,
2633
+ method: "POST",
2634
+ headers: buildAnthropicHeaders(),
2635
+ body: JSON.stringify(requestBody),
2636
+ });
2637
+
2638
+ if (!response.ok) {
2639
+ const errorText = await response.text();
2640
+ return res.status(response.status).json({
2641
+ error: \`Anthropic chat failed: \${response.status}\`,
2642
+ details: errorText,
2643
+ });
2644
+ }
2645
+
2646
+ if (isStreaming) {
2647
+ await relayAnthropicStream(response, res);
2648
+ } else {
2649
+ const data = await response.json();
2650
+ const normalized = convertAnthropicResponseToGateway(data, requestedModel);
2651
+ res.json(normalized);
2652
+ }
2653
+ } catch (error) {
2654
+ const message = error instanceof Error ? error.message : String(error);
2655
+ const status = message.startsWith("Missing ANTHROPIC_API_KEY") ? 400 : 500;
2656
+ res.status(status).json({ error: message });
2657
+ }
2658
+ });
2659
+
2660
+ app.post("/api/anthropic/chat", async (req, res) => {
2661
+ req.url = "/api/anthropic/chat/completions";
2662
+ return app._router.handle(req, res);
2663
+ });
2664
+
2665
+ app.post("/api/anthropic/completions", async (req, res) => {
2666
+ try {
2667
+ requireAnthropicKey();
2668
+ const rawBody = req.body ?? {};
2669
+ const isStreaming = rawBody.stream === true;
2670
+ const requestedModel =
2671
+ stripAnthropicModelPrefix(rawBody.model) ??
2672
+ stripAnthropicModelPrefix("${ctx.defaultModelId}") ??
2673
+ "claude-3-5-sonnet-latest";
2674
+
2675
+ const stopSequences = Array.isArray(rawBody.stop)
2676
+ ? rawBody.stop
2677
+ : Array.isArray(rawBody.stop_sequences)
2678
+ ? rawBody.stop_sequences
2679
+ : rawBody.stop
2680
+ ? [rawBody.stop]
2681
+ : undefined;
2682
+
2683
+ const prompt =
2684
+ typeof rawBody.prompt === "string" && rawBody.prompt.trim().length > 0
2685
+ ? rawBody.prompt
2686
+ : "Hello from Bandit quickstart gateway";
2687
+
2688
+ const { messages, system } = toAnthropicMessages([
2689
+ { role: "user", content: prompt },
2690
+ ]);
2691
+
2692
+ const requestBody = {
2693
+ model: requestedModel,
2694
+ messages,
2695
+ stream: isStreaming,
2696
+ max_tokens:
2697
+ typeof rawBody.max_tokens === "number" && rawBody.max_tokens > 0
2698
+ ? rawBody.max_tokens
2699
+ : ANTHROPIC_MAX_TOKENS,
2700
+ };
2701
+
2702
+ if (system) {
2703
+ requestBody.system = system;
2704
+ }
2705
+ if (typeof rawBody.temperature === "number") {
2706
+ requestBody.temperature = rawBody.temperature;
2707
+ }
2708
+ if (typeof rawBody.top_p === "number") {
2709
+ requestBody.top_p = rawBody.top_p;
2710
+ }
2711
+ if (typeof rawBody.top_k === "number") {
2712
+ requestBody.top_k = rawBody.top_k;
2713
+ }
2714
+ if (stopSequences) {
2715
+ requestBody.stop_sequences = stopSequences;
2716
+ }
2717
+ if (rawBody.metadata) {
2718
+ requestBody.metadata = rawBody.metadata;
2719
+ }
2720
+ if (rawBody.tools) {
2721
+ requestBody.tools = rawBody.tools;
2722
+ }
2723
+ if (rawBody.tool_choice) {
2724
+ requestBody.tool_choice = rawBody.tool_choice;
2725
+ }
2726
+
2727
+ const response = await fetch(buildAnthropicUrl("messages"), {
2728
+ signal: res.locals.abortSignal,
2729
+ method: "POST",
2730
+ headers: buildAnthropicHeaders(),
2731
+ body: JSON.stringify(requestBody),
2732
+ });
2733
+
2734
+ if (!response.ok) {
2735
+ const errorText = await response.text();
2736
+ return res.status(response.status).json({
2737
+ error: \`Anthropic completions failed: \${response.status}\`,
2738
+ details: errorText,
2739
+ });
2740
+ }
2741
+
2742
+ if (isStreaming) {
2743
+ await relayAnthropicStream(response, res);
2744
+ } else {
2745
+ const data = await response.json();
2746
+ const formatted = convertAnthropicResponseToGenerate(data, requestedModel);
2747
+ res.json(formatted);
2748
+ }
2749
+ } catch (error) {
2750
+ const message = error instanceof Error ? error.message : String(error);
2751
+ const status = message.startsWith("Missing ANTHROPIC_API_KEY") ? 400 : 500;
2752
+ res.status(status).json({ error: message });
2753
+ }
2754
+ });
2755
+
2756
+ app.post("/api/anthropic/generate", async (req, res) => {
2757
+ req.url = "/api/anthropic/completions";
2758
+ return app._router.handle(req, res);
2759
+ });
2760
+
2761
+ app.get("/api/anthropic/models", async (_req, res) => {
2762
+ try {
2763
+ requireAnthropicKey();
2764
+ const response = await fetch(buildAnthropicUrl("models"), {
2765
+ signal: res.locals.abortSignal,
2766
+ method: "GET",
2767
+ headers: buildAnthropicHeaders(),
2768
+ });
2769
+
2770
+ if (!response.ok) {
2771
+ const errorText = await response.text();
2772
+ return res.status(response.status).json({
2773
+ error: \`Anthropic models failed: \${response.status}\`,
2774
+ details: errorText,
2775
+ });
2776
+ }
2777
+
2778
+ const text = await response.text();
2779
+ res.setHeader('Content-Type', 'application/json');
2780
+ res.send(text);
2781
+ } catch (error) {
2782
+ const message = error instanceof Error ? error.message : String(error);
2783
+ const status = message.startsWith("Missing ANTHROPIC_API_KEY") ? 400 : 500;
2784
+ res.status(status).json({ error: message });
2785
+ }
2786
+ });
2787
+
2788
+ app.post("/api/anthropic/embed", async (_req, res) => {
2789
+ res.status(501).json({
2790
+ error: "Anthropic embeddings not implemented",
2791
+ message: "Add support for the Anthropic embeddings endpoint if your use case requires it."
2792
+ });
2793
+ });
2794
+
2795
+ // ============================================================================
2796
+ // AZURE OPENAI ROUTES
2797
+ // ============================================================================
2798
+
2799
+ app.get("/api/azure/health", async (_req, res) => {
2800
+ try {
2801
+ const { endpoint } = requireAzureBaseConfig();
2802
+ const deploymentsUrl = buildAzurePath("deployments");
2803
+ const response = await fetch(deploymentsUrl, {
2804
+ signal: res.locals.abortSignal,
2805
+ headers: { "api-key": AZURE_OPENAI_API_KEY }
2806
+ });
2807
+ const isHealthy = response.ok;
2808
+ res.json({
2809
+ status: isHealthy ? "healthy" : "unhealthy",
2810
+ azure_status: isHealthy,
2811
+ provider: "azure",
2812
+ endpoint
2813
+ });
2814
+ } catch (error) {
2815
+ res.status(503).json({
2816
+ status: "unhealthy",
2817
+ azure_status: false,
2818
+ provider: "azure",
2819
+ error: error instanceof Error ? error.message : String(error),
2820
+ endpoint: AZURE_OPENAI_ENDPOINT
2821
+ });
2822
+ }
2823
+ });
2824
+
2825
+ app.post("/api/azure/chat/completions", async (req, res) => {
2826
+ try {
2827
+ const { apiKey } = requireAzureBaseConfig();
2828
+ const deployment = resolveAzureDeployment(req.body?.model, AZURE_OPENAI_CHAT_DEPLOYMENT, "chat");
2829
+ const isStreaming = req.body?.stream === true;
2830
+ const { provider, model, ...cleanBody } = req.body ?? {};
2831
+ const requestBody = { ...cleanBody };
2832
+
2833
+ const response = await fetch(buildAzureDeploymentUrl(deployment, "chat/completions"), {
2834
+ signal: res.locals.abortSignal,
2835
+ method: "POST",
2836
+ headers: {
2837
+ "Content-Type": "application/json",
2838
+ "api-key": apiKey
2839
+ },
2840
+ body: JSON.stringify(requestBody)
2841
+ });
2842
+
2843
+ if (!response.ok) {
2844
+ const errorText = await response.text();
2845
+ return res.status(response.status).json({
2846
+ error: \`Azure OpenAI chat failed: \${response.status}\`,
2847
+ details: errorText
2848
+ });
2849
+ }
2850
+
2851
+ if (isStreaming) {
2852
+ await handleStreamingResponse(response, res);
2853
+ } else {
2854
+ const text = await response.text();
2855
+ res.setHeader('Content-Type', 'application/json');
2856
+ res.send(text);
2857
+ }
2858
+ } catch (error) {
2859
+ const message = error instanceof Error ? error.message : String(error);
2860
+ const status = message.startsWith("Missing Azure OpenAI") ? 400 : 500;
2861
+ res.status(status).json({ error: message });
2862
+ }
2863
+ });
2864
+
2865
+ app.post("/api/azure/chat", async (req, res) => {
2866
+ req.url = "/api/azure/chat/completions";
2867
+ return app._router.handle(req, res);
2868
+ });
2869
+
2870
+ app.post("/api/azure/completions", async (req, res) => {
2871
+ try {
2872
+ const { apiKey } = requireAzureBaseConfig();
2873
+ const deployment = resolveAzureDeployment(req.body?.model, AZURE_OPENAI_COMPLETIONS_DEPLOYMENT, "completions");
2874
+ const isStreaming = req.body?.stream === true;
2875
+ const { provider, model, ...cleanBody } = req.body ?? {};
2876
+ const requestBody = { ...cleanBody };
2877
+
2878
+ const response = await fetch(buildAzureDeploymentUrl(deployment, "completions"), {
2879
+ signal: res.locals.abortSignal,
2880
+ method: "POST",
2881
+ headers: {
2882
+ "Content-Type": "application/json",
2883
+ "api-key": apiKey
2884
+ },
2885
+ body: JSON.stringify(requestBody)
2886
+ });
2887
+
2888
+ if (!response.ok) {
2889
+ const errorText = await response.text();
2890
+ return res.status(response.status).json({
2891
+ error: \`Azure OpenAI completions failed: \${response.status}\`,
2892
+ details: errorText
2893
+ });
2894
+ }
2895
+
2896
+ if (isStreaming) {
2897
+ await handleStreamingResponse(response, res);
2898
+ } else {
2899
+ const text = await response.text();
2900
+ res.setHeader('Content-Type', 'application/json');
2901
+ res.send(text);
2902
+ }
2903
+ } catch (error) {
2904
+ const message = error instanceof Error ? error.message : String(error);
2905
+ const status = message.startsWith("Missing Azure OpenAI") ? 400 : 500;
2906
+ res.status(status).json({ error: message });
2907
+ }
2908
+ });
2909
+
2910
+ app.post("/api/azure/generate", async (req, res) => {
2911
+ try {
2912
+ const { apiKey } = requireAzureBaseConfig();
2913
+ const deployment = resolveAzureDeployment(req.body?.model, AZURE_OPENAI_CHAT_DEPLOYMENT, "chat");
2914
+ const prompt = req.body?.prompt || "";
2915
+ const isStreaming = req.body?.stream === true;
2916
+
2917
+ const chatBody = {
2918
+ messages: [
2919
+ {
2920
+ role: "user",
2921
+ content: prompt
2922
+ }
2923
+ ],
2924
+ stream: isStreaming,
2925
+ max_tokens: req.body?.max_tokens ?? 150,
2926
+ temperature: req.body?.temperature ?? 0.7
2927
+ };
2928
+
2929
+ const response = await fetch(buildAzureDeploymentUrl(deployment, "chat/completions"), {
2930
+ signal: res.locals.abortSignal,
2931
+ method: "POST",
2932
+ headers: {
2933
+ "Content-Type": "application/json",
2934
+ "api-key": apiKey
2935
+ },
2936
+ body: JSON.stringify(chatBody)
2937
+ });
2938
+
2939
+ if (!response.ok) {
2940
+ const errorText = await response.text();
2941
+ return res.status(response.status).json({
2942
+ error: \`Azure OpenAI generate failed: \${response.status}\`,
2943
+ details: errorText
2944
+ });
2945
+ }
2946
+
2947
+ if (isStreaming) {
2948
+ await handleStreamingResponse(response, res);
2949
+ } else {
2950
+ const text = await response.text();
2951
+ res.setHeader('Content-Type', 'application/json');
2952
+ res.send(text);
2953
+ }
2954
+ } catch (error) {
2955
+ const message = error instanceof Error ? error.message : String(error);
2956
+ const status = message.startsWith("Missing Azure OpenAI") ? 400 : 500;
2957
+ res.status(status).json({ error: message });
2958
+ }
2959
+ });
2960
+
2961
+ app.get("/api/azure/models", async (_req, res) => {
2962
+ try {
2963
+ requireAzureBaseConfig();
2964
+
2965
+ const response = await fetch(buildAzurePath("deployments"), {
2966
+ signal: res.locals.abortSignal,
2967
+ headers: { "api-key": AZURE_OPENAI_API_KEY }
2968
+ });
2969
+
2970
+ if (!response.ok) {
2971
+ const errorText = await response.text();
2972
+ return res.status(response.status).json({
2973
+ error: \`Azure OpenAI models failed: \${response.status}\`,
2974
+ details: errorText
2975
+ });
2976
+ }
2977
+
2978
+ const text = await response.text();
2979
+ res.setHeader('Content-Type', 'application/json');
2980
+ res.send(text);
2981
+ } catch (error) {
2982
+ const message = error instanceof Error ? error.message : String(error);
2983
+ const status = message.startsWith("Missing Azure OpenAI") ? 400 : 500;
2984
+ res.status(status).json({ error: message });
2985
+ }
2986
+ });
2987
+
2988
+ app.post("/api/azure/embed", async (req, res) => {
2989
+ try {
2990
+ const { apiKey } = requireAzureBaseConfig();
2991
+ const deployment = resolveAzureDeployment(req.body?.model, AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT, "embeddings");
2992
+ const { provider, model, ...cleanBody } = req.body ?? {};
2993
+ const requestBody = { ...cleanBody };
2994
+
2995
+ const response = await fetch(buildAzureDeploymentUrl(deployment, "embeddings"), {
2996
+ signal: res.locals.abortSignal,
2997
+ method: "POST",
2998
+ headers: {
2999
+ "Content-Type": "application/json",
3000
+ "api-key": apiKey
3001
+ },
3002
+ body: JSON.stringify(requestBody)
3003
+ });
3004
+
3005
+ if (!response.ok) {
3006
+ const errorText = await response.text();
3007
+ return res.status(response.status).json({
3008
+ error: \`Azure OpenAI embed failed: \${response.status}\`,
3009
+ details: errorText
3010
+ });
3011
+ }
3012
+
3013
+ const text = await response.text();
3014
+ res.setHeader('Content-Type', 'application/json');
3015
+ res.send(text);
3016
+ } catch (error) {
3017
+ const message = error instanceof Error ? error.message : String(error);
3018
+ const status = message.startsWith("Missing Azure OpenAI") ? 400 : 500;
3019
+ res.status(status).json({ error: message });
3020
+ }
3021
+ });
3022
+
3023
+ // ============================================================================
3024
+ // XAI ROUTES
3025
+ // ============================================================================
3026
+
3027
+ // xAI Health Check
3028
+ app.get("/api/xai/health", async (_req, res) => {
3029
+ try {
3030
+ const xaiKey = requireXAIKey();
3031
+ const response = await fetch(XAI_BASE_URL + "/models", {
3032
+ signal: res.locals.abortSignal,
3033
+ headers: { "Authorization": "Bearer " + xaiKey }
3034
+ });
3035
+ const isHealthy = response.ok;
3036
+ res.json({
3037
+ status: isHealthy ? "healthy" : "unhealthy",
3038
+ xai_status: isHealthy,
3039
+ provider: "xai"
3040
+ });
3041
+ } catch (error) {
3042
+ res.status(503).json({
3043
+ status: "unhealthy",
3044
+ xai_status: false,
3045
+ error: error instanceof Error ? error.message : String(error),
3046
+ provider: "xai"
3047
+ });
3048
+ }
3049
+ });
3050
+
3051
+ // xAI Chat Completions
3052
+ app.post("/api/xai/chat/completions", async (req, res) => {
3053
+ try {
3054
+ const xaiKey = requireXAIKey();
3055
+ const isStreaming = req.body?.stream === true;
3056
+ const { provider, ...cleanBody } = req.body ?? {};
3057
+ const requestBody = {
3058
+ ...cleanBody,
3059
+ model: req.body?.model?.replace(/^xai:/, "") || "grok-2-latest"
3060
+ };
3061
+
3062
+ const response = await fetch(XAI_BASE_URL + "/chat/completions", {
3063
+ signal: res.locals.abortSignal,
3064
+ method: "POST",
3065
+ headers: {
3066
+ "Content-Type": "application/json",
3067
+ "Authorization": "Bearer " + xaiKey
3068
+ },
3069
+ body: JSON.stringify(requestBody)
3070
+ });
3071
+
3072
+ if (!response.ok) {
3073
+ const errorText = await response.text();
3074
+ return res.status(response.status).json({
3075
+ error: "xAI chat failed: " + response.status,
3076
+ details: errorText
3077
+ });
3078
+ }
3079
+
3080
+ if (isStreaming) {
3081
+ await handleStreamingResponse(response, res);
3082
+ } else {
3083
+ const text = await response.text();
3084
+ res.setHeader('Content-Type', 'application/json');
3085
+ res.send(text);
3086
+ }
3087
+ } catch (error) {
3088
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3089
+ }
3090
+ });
3091
+
3092
+ app.post("/api/xai/chat", async (req, res) => {
3093
+ req.url = "/api/xai/chat/completions";
3094
+ return app._router.handle(req, res);
3095
+ });
3096
+
3097
+ // xAI Completions
3098
+ app.post("/api/xai/completions", async (req, res) => {
3099
+ try {
3100
+ const xaiKey = requireXAIKey();
3101
+ const isStreaming = req.body?.stream === true;
3102
+ const { provider, ...cleanBody } = req.body ?? {};
3103
+ const requestBody = {
3104
+ ...cleanBody,
3105
+ model: req.body?.model?.replace(/^xai:/, "") || "grok-2-mini"
3106
+ };
3107
+
3108
+ const response = await fetch(XAI_BASE_URL + "/completions", {
3109
+ signal: res.locals.abortSignal,
3110
+ method: "POST",
3111
+ headers: {
3112
+ "Content-Type": "application/json",
3113
+ "Authorization": "Bearer " + xaiKey
3114
+ },
3115
+ body: JSON.stringify(requestBody)
3116
+ });
3117
+
3118
+ if (!response.ok) {
3119
+ const errorText = await response.text();
3120
+ return res.status(response.status).json({
3121
+ error: "xAI completions failed: " + response.status,
3122
+ details: errorText
3123
+ });
3124
+ }
3125
+
3126
+ if (isStreaming) {
3127
+ await handleStreamingResponse(response, res);
3128
+ } else {
3129
+ const text = await response.text();
3130
+ res.setHeader('Content-Type', 'application/json');
3131
+ res.send(text);
3132
+ }
3133
+ } catch (error) {
3134
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3135
+ }
3136
+ });
3137
+
3138
+ // xAI Generate
3139
+ app.post("/api/xai/generate", async (req, res) => {
3140
+ try {
3141
+ const xaiKey = requireXAIKey();
3142
+ const prompt = req.body?.prompt || "";
3143
+ const model = req.body?.model?.replace(/^xai:/, "") || "grok-2-latest";
3144
+ const isStreaming = req.body?.stream === true;
3145
+
3146
+ const chatBody = {
3147
+ model,
3148
+ messages: [
3149
+ { role: "user", content: prompt }
3150
+ ],
3151
+ stream: isStreaming,
3152
+ max_tokens: req.body?.max_tokens || 150,
3153
+ temperature: req.body?.temperature ?? 0.7
3154
+ };
3155
+
3156
+ const response = await fetch(XAI_BASE_URL + "/chat/completions", {
3157
+ signal: res.locals.abortSignal,
3158
+ method: "POST",
3159
+ headers: {
3160
+ "Content-Type": "application/json",
3161
+ "Authorization": "Bearer " + xaiKey
3162
+ },
3163
+ body: JSON.stringify(chatBody)
3164
+ });
3165
+
3166
+ if (!response.ok) {
3167
+ const errorText = await response.text();
3168
+ return res.status(response.status).json({
3169
+ error: "xAI generate failed: " + response.status,
3170
+ details: errorText
3171
+ });
3172
+ }
3173
+
3174
+ if (isStreaming) {
3175
+ await handleStreamingResponse(response, res);
3176
+ } else {
3177
+ const data = await response.json();
3178
+ const generateResponse = {
3179
+ model,
3180
+ created_at: new Date().toISOString(),
3181
+ response: data.choices?.[0]?.message?.content || "",
3182
+ done: true,
3183
+ context: [],
3184
+ total_duration: 0,
3185
+ load_duration: 0,
3186
+ prompt_eval_count: data.usage?.prompt_tokens || 0,
3187
+ prompt_eval_duration: 0,
3188
+ eval_count: data.usage?.completion_tokens || 0,
3189
+ eval_duration: 0
3190
+ };
3191
+ res.json(generateResponse);
3192
+ }
3193
+ } catch (error) {
3194
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3195
+ }
3196
+ });
3197
+
3198
+ // xAI Models
3199
+ app.get("/api/xai/models", async (_req, res) => {
3200
+ try {
3201
+ const xaiKey = requireXAIKey();
3202
+ const response = await fetch(XAI_BASE_URL + "/models", {
3203
+ signal: res.locals.abortSignal,
3204
+ headers: { "Authorization": "Bearer " + xaiKey }
3205
+ });
3206
+
3207
+ if (!response.ok) {
3208
+ const errorText = await response.text();
3209
+ return res.status(response.status).json({
3210
+ error: "xAI models failed: " + response.status,
3211
+ details: errorText
3212
+ });
3213
+ }
3214
+
3215
+ const text = await response.text();
3216
+ res.setHeader('Content-Type', 'application/json');
3217
+ res.send(text);
3218
+ } catch (error) {
3219
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3220
+ }
3221
+ });
3222
+
3223
+ // ============================================================================
3224
+ // BANDIT AI ROUTES
3225
+ // ============================================================================
3226
+
3227
+ app.get("/api/bandit/health", async (_req, res) => {
3228
+ try {
3229
+ const banditKey = requireBanditKey();
3230
+ const response = await fetch(BANDIT_BASE_URL + "/models", {
3231
+ signal: res.locals.abortSignal,
3232
+ headers: { "Authorization": \`Bearer \${banditKey}\` }
3233
+ });
3234
+ const isHealthy = response.ok;
3235
+ res.json({
3236
+ status: isHealthy ? "healthy" : "unhealthy",
3237
+ bandit_status: isHealthy,
3238
+ provider: "bandit",
3239
+ endpoint: BANDIT_BASE_URL
3240
+ });
3241
+ } catch (error) {
3242
+ res.status(503).json({
3243
+ status: "unhealthy",
3244
+ bandit_status: false,
3245
+ error: error instanceof Error ? error.message : String(error),
3246
+ provider: "bandit",
3247
+ endpoint: BANDIT_BASE_URL
3248
+ });
3249
+ }
3250
+ });
3251
+
3252
+ app.post("/api/bandit/chat/completions", async (req, res) => {
3253
+ try {
3254
+ const banditKey = requireBanditKey();
3255
+ const isStreaming = req.body?.stream === true;
3256
+ const { provider, ...cleanBody } = req.body ?? {};
3257
+ const providerName = typeof provider === "string" ? provider : "bandit";
3258
+ const requestBody = {
3259
+ ...cleanBody,
3260
+ model: req.body?.model?.replace(/^bandit:/, "") || "bandit-core-1"
3261
+ };
3262
+
3263
+ if (
3264
+ providerName !== "ollama" &&
3265
+ Array.isArray(requestBody.images) &&
3266
+ requestBody.images.length > 0 &&
3267
+ Array.isArray(requestBody.messages)
3268
+ ) {
3269
+ const lastUserIndex = requestBody.messages.map((message) => message?.role).lastIndexOf("user");
3270
+ if (lastUserIndex !== -1) {
3271
+ const targetMessage = requestBody.messages[lastUserIndex] ?? {};
3272
+ const baseContent = Array.isArray(targetMessage.content)
3273
+ ? targetMessage.content.filter(Boolean)
3274
+ : typeof targetMessage.content === "string" && targetMessage.content.trim().length > 0
3275
+ ? [{ type: "text", text: targetMessage.content }]
3276
+ : [];
3277
+
3278
+ const imageContent = requestBody.images
3279
+ .map((entry) => {
3280
+ const url = normalizeGatewayImageUrl(entry);
3281
+ if (!url) {
3282
+ return null;
3283
+ }
3284
+ return {
3285
+ type: "image_url",
3286
+ image_url: {
3287
+ url,
3288
+ detail: extractGatewayImageDetail(entry) ?? "auto"
3289
+ }
3290
+ };
3291
+ })
3292
+ .filter(Boolean);
3293
+
3294
+ if (imageContent.length > 0) {
3295
+ requestBody.messages[lastUserIndex] = {
3296
+ ...targetMessage,
3297
+ content: [...baseContent, ...imageContent]
3298
+ };
3299
+ }
3300
+ }
3301
+ delete requestBody.images;
3302
+ }
3303
+
3304
+ const response = await fetch(BANDIT_BASE_URL + "/completions", {
3305
+ signal: res.locals.abortSignal,
3306
+ method: "POST",
3307
+ headers: {
3308
+ "Content-Type": "application/json",
3309
+ "Authorization": \`Bearer \${banditKey}\`
3310
+ },
3311
+ body: JSON.stringify(requestBody)
3312
+ });
3313
+
3314
+ if (!response.ok) {
3315
+ const errorText = await response.text();
3316
+ return res.status(response.status).json({
3317
+ error: \`Bandit chat failed: \${response.status}\`,
3318
+ details: errorText
3319
+ });
3320
+ }
3321
+
3322
+ if (isStreaming) {
3323
+ await handleStreamingResponse(response, res);
3324
+ } else {
3325
+ const text = await response.text();
3326
+ res.setHeader('Content-Type', 'application/json');
3327
+ res.send(text);
3328
+ }
3329
+ } catch (error) {
3330
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3331
+ }
3332
+ });
3333
+
3334
+ app.post("/api/bandit/chat", async (req, res) => {
3335
+ req.url = "/api/bandit/chat/completions";
3336
+ return app._router.handle(req, res);
3337
+ });
3338
+
3339
+ app.post("/api/bandit/completions", async (req, res) => {
3340
+ try {
3341
+ const banditKey = requireBanditKey();
3342
+ const isStreaming = req.body?.stream === true;
3343
+ const { provider, ...cleanBody } = req.body ?? {};
3344
+ const requestBody = {
3345
+ ...cleanBody,
3346
+ model: req.body?.model?.replace(/^bandit:/, "") || "bandit-core-1"
3347
+ };
3348
+
3349
+ const response = await fetch(BANDIT_BASE_URL + "/completions", {
3350
+ signal: res.locals.abortSignal,
3351
+ method: "POST",
3352
+ headers: {
3353
+ "Content-Type": "application/json",
3354
+ "Authorization": \`Bearer \${banditKey}\`
3355
+ },
3356
+ body: JSON.stringify(requestBody)
3357
+ });
3358
+
3359
+ if (!response.ok) {
3360
+ const errorText = await response.text();
3361
+ return res.status(response.status).json({
3362
+ error: \`Bandit completions failed: \${response.status}\`,
3363
+ details: errorText
3364
+ });
3365
+ }
3366
+
3367
+ if (isStreaming) {
3368
+ await handleStreamingResponse(response, res);
3369
+ } else {
3370
+ const text = await response.text();
3371
+ res.setHeader('Content-Type', 'application/json');
3372
+ res.send(text);
3373
+ }
3374
+ } catch (error) {
3375
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3376
+ }
3377
+ });
3378
+
3379
+ app.post("/api/bandit/generate", async (req, res) => {
3380
+ try {
3381
+ const banditKey = requireBanditKey();
3382
+ const prompt = req.body?.prompt || "";
3383
+ const model = req.body?.model?.replace(/^bandit:/, "") || "bandit-core-1";
3384
+ const isStreaming = req.body?.stream === true;
3385
+
3386
+ const chatBody = {
3387
+ model,
3388
+ messages: [
3389
+ { role: "user", content: prompt }
3390
+ ],
3391
+ stream: isStreaming,
3392
+ max_tokens: req.body?.max_tokens || 256,
3393
+ temperature: req.body?.temperature ?? 0.7
3394
+ };
3395
+
3396
+ const response = await fetch(BANDIT_BASE_URL + "/completions", {
3397
+ signal: res.locals.abortSignal,
3398
+ method: "POST",
3399
+ headers: {
3400
+ "Content-Type": "application/json",
3401
+ "Authorization": \`Bearer \${banditKey}\`
3402
+ },
3403
+ body: JSON.stringify(chatBody)
3404
+ });
3405
+
3406
+ if (!response.ok) {
3407
+ const errorText = await response.text();
3408
+ return res.status(response.status).json({
3409
+ error: \`Bandit generate failed: \${response.status}\`,
3410
+ details: errorText
3411
+ });
3412
+ }
3413
+
3414
+ if (isStreaming) {
3415
+ await handleStreamingResponse(response, res);
3416
+ } else {
3417
+ const data = await response.json();
3418
+ const generateResponse = {
3419
+ model,
3420
+ created_at: new Date().toISOString(),
3421
+ response: data.choices?.[0]?.message?.content || "",
3422
+ done: true,
3423
+ context: [],
3424
+ total_duration: 0,
3425
+ load_duration: 0,
3426
+ prompt_eval_count: data.usage?.prompt_tokens || 0,
3427
+ prompt_eval_duration: 0,
3428
+ eval_count: data.usage?.completion_tokens || 0,
3429
+ eval_duration: 0
3430
+ };
3431
+ res.json(generateResponse);
3432
+ }
3433
+ } catch (error) {
3434
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3435
+ }
3436
+ });
3437
+
3438
+ app.get("/api/bandit/models", async (_req, res) => {
3439
+ try {
3440
+ const banditKey = requireBanditKey();
3441
+ const response = await fetch(BANDIT_BASE_URL + "/models", {
3442
+ signal: res.locals.abortSignal,
3443
+ headers: { "Authorization": \`Bearer \${banditKey}\` }
3444
+ });
3445
+
3446
+ if (!response.ok) {
3447
+ const errorText = await response.text();
3448
+ return res.status(response.status).json({
3449
+ error: \`Bandit models failed: \${response.status}\`,
3450
+ details: errorText
3451
+ });
3452
+ }
3453
+
3454
+ const text = await response.text();
3455
+ res.setHeader('Content-Type', 'application/json');
3456
+ res.send(text);
3457
+ } catch (error) {
3458
+ res.status(500).json({ error: error instanceof Error ? error.message : String(error) });
3459
+ }
3460
+ });
3461
+
3462
+ // ============================================================================
3463
+ // OPENAI ROUTES
3464
+ // ============================================================================
3465
+
3466
+ // OpenAI Health Check
3467
+ app.get("/api/openai/health", async (_req, res) => {
3468
+ try {
3469
+ const openaiKey = process.env.OPENAI_API_KEY;
3470
+ if (!openaiKey) {
3471
+ return res.status(503).json({
3472
+ status: "unhealthy",
3473
+ openai_status: false,
3474
+ error: "OpenAI API key not configured",
3475
+ provider: "openai"
3476
+ });
3477
+ }
3478
+
3479
+ const response = await fetch("https://api.openai.com/v1/models", {
3480
+ signal: res.locals.abortSignal,
3481
+ headers: { "Authorization": \`Bearer \${openaiKey}\` }
3482
+ });
3483
+
3484
+ const isHealthy = response.ok;
3485
+ res.json({
3486
+ status: isHealthy ? "healthy" : "unhealthy",
3487
+ openai_status: isHealthy,
3488
+ provider: "openai"
3489
+ });
3490
+ } catch (error) {
3491
+ res.status(503).json({
3492
+ status: "unhealthy",
3493
+ openai_status: false,
3494
+ error: error.message,
3495
+ provider: "openai"
3496
+ });
3497
+ }
3498
+ });
3499
+
3500
+ // OpenAI Chat Completions
3501
+ app.post("/api/openai/chat/completions", async (req, res) => {
3502
+ try {
3503
+ const openaiKey = requireOpenAIKey();
3504
+ const isStreaming = req.body?.stream === true;
3505
+
3506
+ // Strip the openai: prefix from model name and remove provider field
3507
+ const { provider, ...cleanBody } = req.body;
3508
+ const requestBody = {
3509
+ ...cleanBody,
3510
+ model: req.body?.model?.replace(/^openai:/, "") || "gpt-4o"
3511
+ };
3512
+
3513
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
3514
+ signal: res.locals.abortSignal,
3515
+ method: "POST",
3516
+ headers: {
3517
+ "Content-Type": "application/json",
3518
+ "Authorization": \`Bearer \${openaiKey}\`
3519
+ },
3520
+ body: JSON.stringify(requestBody)
3521
+ });
3522
+
3523
+ if (!response.ok) {
3524
+ const errorText = await response.text();
3525
+ return res.status(response.status).json({
3526
+ error: \`OpenAI chat failed: \${response.status}\`,
3527
+ details: errorText
3528
+ });
3529
+ }
3530
+
3531
+ if (isStreaming) {
3532
+ await handleStreamingResponse(response, res);
3533
+ } else {
3534
+ const text = await response.text();
3535
+ res.setHeader('Content-Type', 'application/json');
3536
+ res.send(text);
3537
+ }
3538
+ } catch (error) {
3539
+ res.status(500).json({ error: error.message });
3540
+ }
3541
+ });
3542
+
3543
+ // OpenAI Chat (alternative route)
3544
+ app.post("/api/openai/chat", async (req, res) => {
3545
+ // Route to the completions endpoint for compatibility
3546
+ req.url = "/api/openai/chat/completions";
3547
+ return app._router.handle(req, res);
3548
+ });
3549
+
3550
+ // OpenAI Completions
3551
+ app.post("/api/openai/completions", async (req, res) => {
3552
+ try {
3553
+ const openaiKey = requireOpenAIKey();
3554
+ const isStreaming = req.body?.stream === true;
3555
+
3556
+ // Strip the openai: prefix from model name and remove provider field
3557
+ const { provider, ...cleanBody } = req.body;
3558
+ const requestBody = {
3559
+ ...cleanBody,
3560
+ model: req.body?.model?.replace(/^openai:/, "") || "gpt-3.5-turbo-instruct"
3561
+ };
3562
+
3563
+ const response = await fetch("https://api.openai.com/v1/completions", {
3564
+ signal: res.locals.abortSignal,
3565
+ method: "POST",
3566
+ headers: {
3567
+ "Content-Type": "application/json",
3568
+ "Authorization": \`Bearer \${openaiKey}\`
3569
+ },
3570
+ body: JSON.stringify(requestBody)
3571
+ });
3572
+
3573
+ if (!response.ok) {
3574
+ const errorText = await response.text();
3575
+ return res.status(response.status).json({
3576
+ error: \`OpenAI completions failed: \${response.status}\`,
3577
+ details: errorText
3578
+ });
3579
+ }
3580
+
3581
+ if (isStreaming) {
3582
+ await handleStreamingResponse(response, res);
3583
+ } else {
3584
+ const text = await response.text();
3585
+ res.setHeader('Content-Type', 'application/json');
3586
+ res.send(text);
3587
+ }
3588
+ } catch (error) {
3589
+ res.status(500).json({ error: error.message });
3590
+ }
3591
+ });
3592
+
3593
+ // OpenAI Generate (converts to chat format for conversation starters)
3594
+ app.post("/api/openai/generate", async (req, res) => {
3595
+ try {
3596
+ const openaiKey = requireOpenAIKey();
3597
+ const prompt = req.body?.prompt || "";
3598
+ const model = req.body?.model?.replace(/^openai:/, "") || "gpt-4o";
3599
+ const isStreaming = req.body?.stream === true;
3600
+
3601
+ // Convert generate request to chat format
3602
+ const chatBody = {
3603
+ model: model,
3604
+ messages: [
3605
+ {
3606
+ role: "user",
3607
+ content: prompt
3608
+ }
3609
+ ],
3610
+ stream: isStreaming,
3611
+ max_tokens: req.body?.max_tokens || 150,
3612
+ temperature: req.body?.temperature || 0.7
3613
+ };
3614
+
3615
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
3616
+ signal: res.locals.abortSignal,
3617
+ method: "POST",
3618
+ headers: {
3619
+ "Content-Type": "application/json",
3620
+ "Authorization": \`Bearer \${openaiKey}\`
3621
+ },
3622
+ body: JSON.stringify(chatBody)
3623
+ });
3624
+
3625
+ if (!response.ok) {
3626
+ const errorText = await response.text();
3627
+ return res.status(response.status).json({
3628
+ error: \`OpenAI generate failed: \${response.status}\`,
3629
+ details: errorText
3630
+ });
3631
+ }
3632
+
3633
+ if (isStreaming) {
3634
+ await handleStreamingResponse(response, res);
3635
+ } else {
3636
+ const data = await response.json();
3637
+ // Convert chat response back to generate format
3638
+ const generateResponse = {
3639
+ model: model,
3640
+ created_at: new Date().toISOString(),
3641
+ response: data.choices?.[0]?.message?.content || "",
3642
+ done: true,
3643
+ context: [],
3644
+ total_duration: 0,
3645
+ load_duration: 0,
3646
+ prompt_eval_count: 0,
3647
+ prompt_eval_duration: 0,
3648
+ eval_count: data.usage?.completion_tokens || 0,
3649
+ eval_duration: 0
3650
+ };
3651
+ res.json(generateResponse);
3652
+ }
3653
+ } catch (error) {
3654
+ res.status(500).json({ error: error.message });
3655
+ }
3656
+ });
3657
+
3658
+ // OpenAI Models
3659
+ app.get("/api/openai/models", async (_req, res) => {
3660
+ try {
3661
+ const openaiKey = requireOpenAIKey();
3662
+
3663
+ const response = await fetch("https://api.openai.com/v1/models", {
3664
+ signal: res.locals.abortSignal,
3665
+ headers: { "Authorization": \`Bearer \${openaiKey}\` }
3666
+ });
3667
+
3668
+ if (!response.ok) {
3669
+ const errorText = await response.text();
3670
+ return res.status(response.status).json({
3671
+ error: \`OpenAI models failed: \${response.status}\`,
3672
+ details: errorText
3673
+ });
3674
+ }
3675
+
3676
+ const text = await response.text();
3677
+ res.setHeader('Content-Type', 'application/json');
3678
+ res.send(text);
3679
+ } catch (error) {
3680
+ res.status(500).json({ error: error.message });
3681
+ }
3682
+ });
3683
+
3684
+ // ============================================================================
3685
+ // OLLAMA ROUTES
3686
+ // ============================================================================
3687
+
3688
+ // Ollama Health Check
3689
+ app.get("/api/ollama/health", async (_req, res) => {
3690
+ try {
3691
+ debugLog(\`Ollama health check at: \${OLLAMA_BASE_URL}/api/tags\`);
3692
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/tags\`);
3693
+ const isHealthy = response.ok;
3694
+
3695
+ res.json({
3696
+ status: isHealthy ? "healthy" : "unhealthy",
3697
+ ollama_status: isHealthy,
3698
+ provider: "ollama",
3699
+ url: OLLAMA_BASE_URL
3700
+ });
3701
+ } catch (error) {
3702
+ debugLog(\`Ollama health check error: \${error.message}\`);
3703
+ res.status(503).json({
3704
+ status: "offline",
3705
+ ollama_status: false,
3706
+ error: error.message,
3707
+ provider: "ollama",
3708
+ url: OLLAMA_BASE_URL
3709
+ });
3710
+ }
3711
+ });
3712
+
3713
+ // Ollama Chat
3714
+ app.post("/api/ollama/chat", async (req, res) => {
3715
+ try {
3716
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/chat\`, {
3717
+ signal: res.locals.abortSignal,
3718
+ method: "POST",
3719
+ headers: { "Content-Type": "application/json" },
3720
+ body: JSON.stringify(req.body)
3721
+ });
3722
+
3723
+ if (!response.ok) {
3724
+ const errorText = await response.text();
3725
+ return res.status(response.status).json({
3726
+ error: \`Ollama chat failed: \${response.status}\`,
3727
+ details: errorText
3728
+ });
3729
+ }
3730
+
3731
+ // Ollama streams unless the request says stream: false.
3732
+ const isStreaming = req.body?.stream !== false;
3733
+ if (isStreaming) {
3734
+ await handleStreamingResponse(response, res);
3735
+ } else {
3736
+ const text = await response.text();
3737
+ res.setHeader('Content-Type', 'application/json');
3738
+ res.send(text);
3739
+ }
3740
+ } catch (error) {
3741
+ res.status(500).json({ error: error.message });
3742
+ }
3743
+ });
3744
+
3745
+ // Ollama Generate
3746
+ app.post("/api/ollama/generate", async (req, res) => {
3747
+ try {
3748
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/generate\`, {
3749
+ signal: res.locals.abortSignal,
3750
+ method: "POST",
3751
+ headers: { "Content-Type": "application/json" },
3752
+ body: JSON.stringify(req.body)
3753
+ });
3754
+
3755
+ if (!response.ok) {
3756
+ const errorText = await response.text();
3757
+ return res.status(response.status).json({
3758
+ error: \`Ollama generate failed: \${response.status}\`,
3759
+ details: errorText
3760
+ });
3761
+ }
3762
+
3763
+ // Ollama streams unless the request says stream: false.
3764
+ const isStreaming = req.body?.stream !== false;
3765
+ if (isStreaming) {
3766
+ await handleStreamingResponse(response, res);
3767
+ } else {
3768
+ const text = await response.text();
3769
+ res.setHeader('Content-Type', 'application/json');
3770
+ res.send(text);
3771
+ }
3772
+ } catch (error) {
3773
+ res.status(500).json({ error: error.message });
3774
+ }
3775
+ });
3776
+
3777
+ // Ollama Models
3778
+ app.get("/api/ollama/models", async (_req, res) => {
3779
+ try {
3780
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/tags\`);
3781
+
3782
+ if (!response.ok) {
3783
+ const errorText = await response.text();
3784
+ return res.status(response.status).json({
3785
+ error: \`Ollama models failed: \${response.status}\`,
3786
+ details: errorText
3787
+ });
3788
+ }
3789
+
3790
+ const text = await response.text();
3791
+ res.setHeader('Content-Type', 'application/json');
3792
+ res.send(text);
3793
+ } catch (error) {
3794
+ res.status(500).json({ error: error.message });
3795
+ }
3796
+ });
3797
+
3798
+ // Ollama Embedding
3799
+ app.post("/api/ollama/embed", async (req, res) => {
3800
+ try {
3801
+ const response = await fetch(\`\${OLLAMA_BASE_URL}/api/embeddings\`, {
3802
+ signal: res.locals.abortSignal,
3803
+ method: "POST",
3804
+ headers: { "Content-Type": "application/json" },
3805
+ body: JSON.stringify(req.body)
3806
+ });
3807
+
3808
+ if (!response.ok) {
3809
+ const errorText = await response.text();
3810
+ return res.status(response.status).json({
3811
+ error: \`Ollama embed failed: \${response.status}\`,
3812
+ details: errorText
3813
+ });
3814
+ }
3815
+
3816
+ const text = await response.text();
3817
+ res.setHeader('Content-Type', 'application/json');
3818
+ res.send(text);
3819
+ } catch (error) {
3820
+ res.status(500).json({ error: error.message });
3821
+ }
3822
+ });
3823
+
3824
+ // ============================================================================
3825
+ // TTS ROUTES (not implemented - placeholder for compatibility)
3826
+ // ============================================================================
3827
+
3828
+ // TTS Main endpoint
3829
+ app.post("/api/tts", async (_req, res) => {
3830
+ res.status(501).json({
3831
+ error: "TTS integration not implemented",
3832
+ message: "Text-to-speech functionality is not available in this quickstart gateway"
3833
+ });
3834
+ });
3835
+
3836
+ // TTS Stream endpoint
3837
+ app.post("/api/tts/stream", async (_req, res) => {
3838
+ res.status(501).json({
3839
+ error: "TTS streaming not implemented",
3840
+ message: "Text-to-speech streaming functionality is not available in this quickstart gateway"
3841
+ });
3842
+ });
3843
+
3844
+ // TTS Real-time stream endpoint
3845
+ app.post("/api/tts/stream-realtime", async (_req, res) => {
3846
+ res.status(501).json({
3847
+ error: "TTS real-time streaming not implemented",
3848
+ message: "Text-to-speech real-time streaming functionality is not available in this quickstart gateway"
3849
+ });
3850
+ });
3851
+
3852
+ // TTS Models endpoint - returns empty models
3853
+ app.get("/api/tts/models", async (_req, res) => {
3854
+ res.json({
3855
+ models: []
3856
+ });
3857
+ });
3858
+
3859
+ // TTS Available models endpoint - returns empty models with defaults
3860
+ app.get("/api/tts/available-models", async (_req, res) => {
3861
+ res.json({
3862
+ models: [],
3863
+ defaultModel: null,
3864
+ fallbackModel: null
3865
+ });
3866
+ });
3867
+
3868
+ // ============================================================================
3869
+ // MCP (Model Context Protocol) TOOL ROUTES
3870
+ // ============================================================================
3871
+
3872
+ // MCP Health Check
3873
+ app.get("/api/mcp/health", async (_req, res) => {
3874
+ res.json({
3875
+ status: "healthy",
3876
+ timestamp: new Date().toISOString(),
3877
+ totalTools: 0,
3878
+ enabledTools: 0,
3879
+ availableTools: [],
3880
+ message: "MCP tools are not implemented in this quickstart gateway"
3881
+ });
3882
+ });
3883
+
3884
+ // Get available MCP tools
3885
+ app.get("/api/mcp/tools", async (_req, res) => {
3886
+ res.json([]);
3887
+ });
3888
+
3889
+ // News endpoint - placeholder implementation
3890
+ app.get("/api/mcp/news", async (req, res) => {
3891
+ const { topic = "general", count = 10, headlines = false } = req.query;
3892
+
3893
+ res.status(501).json({
3894
+ error: "News service not implemented",
3895
+ message: "MCP news functionality is not available in this quickstart gateway",
3896
+ suggestion: "Implement this endpoint to connect to a news API service",
3897
+ requestedParams: { topic, count, headlines }
3898
+ });
3899
+ });
3900
+
3901
+ // Weather endpoint - placeholder implementation
3902
+ app.get("/api/mcp/weather", async (req, res) => {
3903
+ const { zip, latitude, longitude } = req.query;
3904
+
3905
+ res.status(501).json({
3906
+ error: "Weather service not implemented",
3907
+ message: "MCP weather functionality is not available in this quickstart gateway",
3908
+ suggestion: "Implement this endpoint to connect to a weather API service",
3909
+ requestedParams: { zip, latitude, longitude }
3910
+ });
3911
+ });
3912
+
3913
+ // Documentation search endpoint - placeholder implementation
3914
+ app.get("/api/mcp/docs", async (req, res) => {
3915
+ const { query, framework, count = 10 } = req.query;
3916
+
3917
+ if (!query) {
3918
+ return res.status(400).json({
3919
+ error: "Query parameter is required",
3920
+ message: "Please provide a search query"
3921
+ });
3922
+ }
3923
+
3924
+ res.status(501).json({
3925
+ error: "Documentation search not implemented",
3926
+ message: "MCP docs functionality is not available in this quickstart gateway",
3927
+ suggestion: "Implement this endpoint to connect to a documentation search service",
3928
+ requestedParams: { query, framework, count }
3929
+ });
3930
+ });
3931
+
3932
+ // Get supported documentation frameworks
3933
+ app.get("/api/mcp/docs/frameworks", async (_req, res) => {
3934
+ res.json({
3935
+ frameworks: [],
3936
+ message: "Documentation frameworks not configured in this quickstart gateway"
3937
+ });
3938
+ });
3939
+
3940
+ // Sports scores endpoint - placeholder implementation
3941
+ app.get("/api/mcp/sports", async (req, res) => {
3942
+ const { league, date } = req.query;
3943
+
3944
+ res.status(501).json({
3945
+ error: "Sports service not implemented",
3946
+ message: "MCP sports functionality is not available in this quickstart gateway",
3947
+ suggestion: "Implement this endpoint to connect to a sports API service",
3948
+ requestedParams: { league, date }
3949
+ });
3950
+ });
3951
+
3952
+ // Get supported sports leagues
3953
+ app.get("/api/mcp/sports/leagues", async (_req, res) => {
3954
+ res.json({
3955
+ leagues: [],
3956
+ message: "Sports leagues not configured in this quickstart gateway"
3957
+ });
3958
+ });
3959
+
3960
+ // Image generation endpoint - placeholder implementation
3961
+ app.post("/api/mcp/generate-image", async (req, res) => {
3962
+ const { prompt, size, quality, style } = req.body;
3963
+
3964
+ if (!prompt) {
3965
+ return res.status(400).json({
3966
+ error: "Prompt is required",
3967
+ message: "Please provide a prompt for image generation"
3968
+ });
3969
+ }
3970
+
3971
+ res.status(501).json({
3972
+ success: false,
3973
+ error: "Image generation not implemented",
3974
+ message: "MCP image generation functionality is not available in this quickstart gateway",
3975
+ suggestion: "Implement this endpoint to connect to an image generation API service",
3976
+ requestedParams: { prompt, size, quality, style }
3977
+ });
3978
+ });
3979
+
3980
+ // ============================================================================
3981
+ // NOT IMPLEMENTED ROUTES (for graceful degradation)
3982
+ // ============================================================================
3983
+
3984
+ app.all("/api/anthropic/*", (_req, res) => {
3985
+ res.status(501).json({
3986
+ error: "Anthropic route not implemented",
3987
+ message: "Extend the quickstart gateway if you need additional Anthropic endpoints beyond the defaults."
3988
+ });
3989
+ });
3990
+
3991
+ const port = Number(process.env.PORT ?? ${ctx.gatewayPort});
3992
+ app.listen(port, HOST, () => {
3993
+ console.log("\u26A1 Bandit quickstart gateway ready on http://" + HOST + ":" + port);
3994
+ if (!expectedKeyHash) {
3995
+ console.log("\u{1F513} No GATEWAY_API_KEY set: accepting keyless requests addressed to localhost from local browser origins only.");
3996
+ }
3997
+ console.log("\u{1F4E1} Supported providers: Bandit AI, OpenAI, Azure OpenAI, Anthropic, XAI, Ollama");
3998
+ console.log("\u{1F517} Provider-specific routes:");
3999
+ console.log(" \u2022 /api/bandit/* - Bandit AI endpoints");
4000
+ console.log(" \u2022 /api/openai/* - OpenAI endpoints");
4001
+ console.log(" \u2022 /api/azure/* - Azure OpenAI endpoints");
4002
+ console.log(" \u2022 /api/anthropic/* - Anthropic endpoints");
4003
+ console.log(" \u2022 /api/xai/* - XAI endpoints");
4004
+ console.log(" \u2022 /api/ollama/* - Ollama endpoints");
4005
+ console.log(" \u2022 /api/health - Overall health check");
4006
+ });
4007
+ `;
4008
+ return ensureTrailingNewline(normalizeLineEndings(gatewaySource));
4009
+ };
4010
+ var buildGitignore = () => ensureTrailingNewline(
4011
+ normalizeLineEndings(
4012
+ `node_modules
4013
+ .env
4014
+ .vite
4015
+ .idea
4016
+ .DS_Store
4017
+ coverage
4018
+ dist
4019
+ `
4020
+ )
4021
+ );
4022
+ var buildReadme = (ctx) => {
4023
+ const providerStep = ctx.defaultProvider === "ollama" ? "- Make sure Ollama is running with at least one model pulled (`ollama pull gemma3:4b`). No `.env` is needed for local Ollama; copy `.env.example` to `.env` only to change a default." : "- `cp .env.example .env` and add your provider credentials.";
4024
+ const lines = [
4025
+ `# ${ctx.projectTitle} \u2014 Bandit Quickstart`,
4026
+ "",
4027
+ "This project was generated by `@burtson-labs/bandit-cli`. It ships with a React + Vite frontend that consumes `@burtson-labs/bandit-engine`, a small Express gateway (`server/gateway.js`) you can adapt for production, and a Next.js App Router API scaffold in `server/next-app/`.",
4028
+ "",
4029
+ "## Next steps",
4030
+ "- `npm install`",
4031
+ providerStep,
4032
+ "- `npm run dev`",
4033
+ "",
4034
+ `The command runs the gateway (http://localhost:${ctx.gatewayPort}) and the frontend together. Visit http://localhost:${ctx.frontendPort} to see the chat and modal in action.`,
4035
+ "",
4036
+ "## How the browser talks to the gateway",
4037
+ "In local development the gateway listens on `127.0.0.1` and needs no key: a secret in browser code would be readable by anyone, so the browser never holds one. The gateway answers CORS preflights from local origins, only accepts requests addressed to `localhost`, and rejects other web pages' origins (`CORS_ORIGINS` changes the allow-list).",
4038
+ "",
4039
+ "To share the gateway, set `GATEWAY_API_KEY` (32+ characters, `openssl rand -hex 32`). Every request then needs `Authorization: Bearer <key>`, which your own server or a dev proxy (for example Vite's `server.proxy` with a `headers` entry) adds. Starting on a non-loopback `HOST` without a key refuses to start.",
4040
+ "",
4041
+ "## Models",
4042
+ "`GET /api/models` lists the models installed in Ollama (skipping `:cloud` and embedding-only models) plus the hosted models configured in `.env`, in the shape the engine's model picker reads: `id`, `displayName`, `description`, `available`, `vision`, `tools`, `thinking`.",
4043
+ "",
4044
+ "## Customizing your assistant",
4045
+ "- **Branding & personas**: edit `public/config.json` to tweak logos, colors, and starter models.",
4046
+ "- **Provider defaults**: update `.env` to switch providers or change the default upstream model IDs.",
4047
+ "- **Gateway routes**: open `server/gateway.js` to add auth, logging, or connect additional providers. Set `DEBUG=1` to log each request.",
4048
+ "",
4049
+ "## What\u2019s inside",
4050
+ "- React + Vite with Material UI theming",
4051
+ "- Bandit chat surface + modal wired via `ChatProvider`",
4052
+ "- Express gateway proxying Bandit AI, OpenAI, Azure OpenAI, Anthropic, xAI, or Ollama to keep API keys server-side",
4053
+ "- Next.js App Router gateway scaffold in `server/next-app/` for projects that prefer Next",
4054
+ "",
4055
+ "Run `npx @burtson-labs/bandit-cli create --help` to see the scaffold options."
4056
+ ];
4057
+ return ensureTrailingNewline(normalizeLineEndings(lines.join("\n")));
4058
+ };
4059
+
4060
+ // src/createQuickstart.ts
4061
+ var ENGINE_VERSION = "2.2.2";
4062
+ var createQuickstartProject = async (options) => {
4063
+ const resolvedDir = import_node_path2.default.resolve(process.cwd(), options.targetDir);
4064
+ const rawProjectName = options.projectName ?? import_node_path2.default.basename(resolvedDir);
4065
+ const packageName = normalizePackageName(rawProjectName);
4066
+ const projectTitle = toTitleCase(rawProjectName) || "Bandit Quickstart";
4067
+ await ensureWritableDirectory(resolvedDir, Boolean(options.force));
4068
+ const skipPrompts = Boolean(options.skipPrompts);
4069
+ const provider = options.provider ? normalizeProvider(options.provider) : skipPrompts ? "ollama" : await promptForProvider();
4070
+ const promptAnswers = skipPrompts ? {} : await promptForMissingData({
4071
+ brandingText: options.brandingText,
4072
+ provider
4073
+ });
4074
+ const brandingText = options.brandingText ?? (typeof promptAnswers.brandingText === "string" && promptAnswers.brandingText.trim().length > 0 ? promptAnswers.brandingText.trim() : `${projectTitle} Assistant`);
4075
+ const logoResolution = {
4076
+ dataUrl: "",
4077
+ fileName: "",
4078
+ fileContent: Buffer.alloc(0),
4079
+ hasTransparentLogo: true,
4080
+ isDefault: true
4081
+ };
4082
+ const gatewayPort = sanitizePort(options.gatewayPort ?? promptAnswers.gatewayPort ?? 8080);
4083
+ const frontendPort = sanitizePort(options.frontendPort ?? promptAnswers.frontendPort ?? 5183);
4084
+ const detectedOllamaModel = provider === "ollama" && !options.defaultModelId ? await detectOllamaModel() : void 0;
4085
+ const defaultModelId = sanitizeModelIdentifier(
4086
+ options.defaultModelId ?? detectedOllamaModel ?? inferDefaultModelId(provider)
4087
+ );
4088
+ const fallbackModelRaw = options.fallbackModelId ? options.fallbackModelId : inferFallbackModelId(provider, defaultModelId);
4089
+ const fallbackModelId = fallbackModelRaw ? sanitizeModelIdentifier(fallbackModelRaw) : void 0;
4090
+ const inputs = {
4091
+ targetDir: resolvedDir,
4092
+ projectTitle,
4093
+ packageName,
4094
+ brandingText,
4095
+ provider,
4096
+ defaultModelId,
4097
+ fallbackModelId,
4098
+ gatewayPort,
4099
+ frontendPort,
4100
+ logo: logoResolution
4101
+ };
4102
+ const createdFiles = await writeProject(inputs);
4103
+ return {
4104
+ projectDir: resolvedDir,
4105
+ provider,
4106
+ packageName,
4107
+ brandingText,
4108
+ defaultModelId,
4109
+ fallbackModelId,
4110
+ gatewayPort,
4111
+ frontendPort,
4112
+ createdFiles
4113
+ };
4114
+ };
4115
+ var normalizePackageName = (input) => {
4116
+ const fallback = "bandit-quickstart";
4117
+ const kebab = toKebabCase(input || fallback);
4118
+ if (!kebab) {
4119
+ return fallback;
4120
+ }
4121
+ return /^[a-z]/.test(kebab) ? kebab : `bandit-${kebab}`;
4122
+ };
4123
+ var ensureWritableDirectory = async (dir, force) => {
4124
+ const exists = await import_fs_extra.default.pathExists(dir);
4125
+ if (!exists) {
4126
+ await import_fs_extra.default.ensureDir(dir);
4127
+ return;
4128
+ }
4129
+ const entries = await import_fs_extra.default.readdir(dir);
4130
+ if (entries.length > 0 && !force) {
4131
+ throw new Error(
4132
+ `Target directory "${dir}" is not empty. Re-run with --force to overwrite or choose a new folder.`
4133
+ );
4134
+ }
4135
+ };
4136
+ var normalizeProvider = (value) => {
4137
+ const normalized = (value ?? "openai").toLowerCase();
4138
+ if (normalized === "ollama") {
4139
+ return "ollama";
4140
+ }
4141
+ if (normalized === "azure" || normalized === "azure-openai" || normalized === "azureopenai") {
4142
+ return "azure";
4143
+ }
4144
+ if (normalized === "anthropic") {
4145
+ return "anthropic";
4146
+ }
4147
+ if (normalized === "xai" || normalized === "grok") {
4148
+ return "xai";
4149
+ }
4150
+ if (normalized === "bandit" || normalized === "banditai" || normalized === "bandit-ai") {
4151
+ return "bandit";
4152
+ }
4153
+ return "openai";
4154
+ };
4155
+ var inferDefaultModelId = (provider) => {
4156
+ if (provider === "ollama") {
4157
+ return "llama3.1";
4158
+ }
4159
+ if (provider === "azure") {
4160
+ return "azure:gpt-4o";
4161
+ }
4162
+ if (provider === "anthropic") {
4163
+ return "anthropic:claude-3-5-haiku-latest";
4164
+ }
4165
+ if (provider === "xai") {
4166
+ return "xai:grok-2-latest";
4167
+ }
4168
+ if (provider === "bandit") {
4169
+ return "bandit-core-1";
4170
+ }
4171
+ return "openai:gpt-4o-mini";
4172
+ };
4173
+ var detectOllamaModel = async () => {
4174
+ const base = (process.env.OLLAMA_URL ?? "http://localhost:11434").replace(/\/$/, "");
4175
+ try {
4176
+ const response = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(1500) });
4177
+ if (!response.ok) return void 0;
4178
+ const body = await response.json();
4179
+ const candidates = (body.models ?? []).filter(
4180
+ (model) => typeof model.name === "string" && !model.name.endsWith(":cloud") && !/embed/i.test(model.name) && !/bert/i.test(model.details?.family ?? "")
4181
+ );
4182
+ const bySize = (a, b) => (a.size || Number.MAX_SAFE_INTEGER) - (b.size || Number.MAX_SAFE_INTEGER);
4183
+ const library = candidates.filter((model) => !model.name.includes("/")).sort(bySize);
4184
+ return (library[0] ?? [...candidates].sort(bySize)[0])?.name;
4185
+ } catch {
4186
+ return void 0;
4187
+ }
4188
+ };
4189
+ var inferFallbackModelId = (provider, defaultId) => {
4190
+ if (provider === "ollama") {
4191
+ const normalized = defaultId.toLowerCase();
4192
+ if (normalized.startsWith("llama3")) {
4193
+ return "llama2";
4194
+ }
4195
+ return "llama3";
4196
+ }
4197
+ if (provider === "azure") {
4198
+ return defaultId === "azure:gpt-4o-mini" ? "azure:gpt-4o" : "azure:gpt-4o-mini";
4199
+ }
4200
+ if (provider === "anthropic") {
4201
+ return defaultId === "anthropic:claude-3-5-haiku-latest" ? "anthropic:claude-3-haiku-20240307" : "anthropic:claude-3-5-haiku-latest";
4202
+ }
4203
+ if (provider === "xai") {
4204
+ return defaultId === "xai:grok-2-mini" ? "xai:grok-2-latest" : "xai:grok-2-mini";
4205
+ }
4206
+ if (provider === "bandit") {
4207
+ return void 0;
4208
+ }
4209
+ return defaultId === "openai:gpt-4.1-mini" ? "openai:gpt-4o-mini" : "openai:gpt-4.1-mini";
4210
+ };
4211
+ var promptForProvider = async () => {
4212
+ const providerOptions = [
4213
+ { label: "Ollama (self-hosted) \u2014 default", value: "ollama" },
4214
+ { label: "OpenAI", value: "openai" },
4215
+ { label: "Bandit AI (Bandit Core)", value: "bandit" },
4216
+ { label: "Azure OpenAI", value: "azure" },
4217
+ { label: "Anthropic", value: "anthropic" },
4218
+ { label: "xAI (Grok)", value: "xai" }
4219
+ ];
4220
+ const messageLines = [
4221
+ "Which provider should we configure for the gateway?",
4222
+ ...providerOptions.map((option, index) => ` ${index + 1}. ${option.label}`),
4223
+ "Enter a number:"
4224
+ ];
4225
+ const onCancel = () => {
4226
+ throw new Error("Command cancelled.");
4227
+ };
4228
+ const answers = await (0, import_prompts.default)(
4229
+ {
4230
+ type: "number",
4231
+ name: "providerIndex",
4232
+ message: messageLines.join("\n"),
4233
+ initial: 1,
4234
+ validate: (input) => {
4235
+ if (!Number.isInteger(input)) {
4236
+ return "Enter a whole number.";
4237
+ }
4238
+ return input >= 1 && input <= providerOptions.length ? true : `Enter a number between 1 and ${providerOptions.length}.`;
4239
+ }
4240
+ },
4241
+ { onCancel }
4242
+ );
4243
+ const selectedIndex = typeof answers.providerIndex === "number" && answers.providerIndex >= 1 ? answers.providerIndex - 1 : 0;
4244
+ return providerOptions[selectedIndex]?.value ?? "ollama";
4245
+ };
4246
+ var sanitizePort = (value) => {
4247
+ const port = Number(value);
4248
+ if (Number.isNaN(port) || port <= 0 || port >= 65535) {
4249
+ return 8080;
4250
+ }
4251
+ return port;
4252
+ };
4253
+ var promptForMissingData = async (options) => {
4254
+ const questions = [];
4255
+ if (!options.brandingText) {
4256
+ questions.push({
4257
+ type: "text",
4258
+ name: "brandingText",
4259
+ message: "What should we display for the app name? (Press Enter to accept)",
4260
+ initial: "Bandit Quickstart"
4261
+ });
4262
+ }
4263
+ const defaultGatewayPort = 8080;
4264
+ const defaultFrontendPort = 5183;
4265
+ questions.push({
4266
+ type: "text",
4267
+ name: "frontendPort",
4268
+ message: "Frontend port (Press Enter to accept)",
4269
+ initial: String(defaultFrontendPort),
4270
+ validate: (value) => {
4271
+ if (typeof value !== "string" || value.trim().length === 0) {
4272
+ return true;
4273
+ }
4274
+ const numericValue = Number(value);
4275
+ return Number.isFinite(numericValue) && numericValue > 0 && numericValue < 65535 ? true : "Enter a port between 1 and 65535";
4276
+ }
4277
+ });
4278
+ questions.push({
4279
+ type: "text",
4280
+ name: "gatewayPort",
4281
+ message: "Gateway port (Press Enter to accept)",
4282
+ initial: String(defaultGatewayPort),
4283
+ validate: (value) => {
4284
+ if (typeof value !== "string" || value.trim().length === 0) {
4285
+ return true;
4286
+ }
4287
+ const numericValue = Number(value);
4288
+ return Number.isFinite(numericValue) && numericValue > 0 && numericValue < 65535 ? true : "Enter a port between 1 and 65535";
4289
+ }
4290
+ });
4291
+ const onCancel = () => {
4292
+ throw new Error("Command cancelled.");
4293
+ };
4294
+ const answers = await (0, import_prompts.default)(questions, { onCancel });
4295
+ const parsedGatewayPort = typeof answers.gatewayPort === "number" ? answers.gatewayPort : typeof answers.gatewayPort === "string" && answers.gatewayPort.trim().length > 0 ? Number(answers.gatewayPort) : defaultGatewayPort;
4296
+ const parsedFrontendPort = typeof answers.frontendPort === "number" ? answers.frontendPort : typeof answers.frontendPort === "string" && answers.frontendPort.trim().length > 0 ? Number(answers.frontendPort) : defaultFrontendPort;
4297
+ return {
4298
+ brandingText: typeof answers.brandingText === "string" ? answers.brandingText : void 0,
4299
+ gatewayPort: Number.isFinite(parsedGatewayPort) ? parsedGatewayPort : defaultGatewayPort,
4300
+ frontendPort: Number.isFinite(parsedFrontendPort) ? parsedFrontendPort : defaultFrontendPort
4301
+ };
4302
+ };
4303
+ var writeProject = async (inputs) => {
4304
+ const { targetDir } = inputs;
4305
+ const createdFiles = [];
4306
+ const context = {
4307
+ packageName: inputs.packageName,
4308
+ projectTitle: inputs.projectTitle,
4309
+ engineVersion: ENGINE_VERSION,
4310
+ brandingText: inputs.brandingText,
4311
+ logoBase64: inputs.logo.dataUrl,
4312
+ hasTransparentLogo: inputs.logo.hasTransparentLogo,
4313
+ isDefaultLogo: inputs.logo.isDefault,
4314
+ gatewayPort: inputs.gatewayPort,
4315
+ frontendPort: inputs.frontendPort,
4316
+ defaultProvider: inputs.provider,
4317
+ defaultGatewayUrl: `http://localhost:${inputs.gatewayPort}`,
4318
+ defaultModelId: inputs.defaultModelId,
4319
+ fallbackModelId: inputs.fallbackModelId,
4320
+ gatewayModels: buildGatewayModels(inputs)
4321
+ };
4322
+ const files = {
4323
+ "package.json": buildPackageJson(context),
4324
+ "tsconfig.json": buildTsConfig(),
4325
+ "src/env.d.ts": buildEnvDts(),
4326
+ "vite.config.ts": buildViteConfig(context),
4327
+ "src/main.tsx": buildMainTsx(),
4328
+ "index.html": buildIndexHtml(),
4329
+ "src/App.tsx": buildAppTsx(context),
4330
+ "src/index.css": buildIndexCss(),
4331
+ "src/theme.ts": buildThemeTs(),
4332
+ "public/config.json": buildBrandingConfig(context),
4333
+ "server/gateway.js": buildGatewayServer(context),
4334
+ "server/next-app/app/api/chat/completions/route.ts": buildNextChatRoute(context),
4335
+ "server/next-app/app/api/health/route.ts": buildNextHealthRoute(),
4336
+ "server/next-app/app/api/models/route.ts": buildNextModelsRoute(context),
4337
+ "server/next-app/README.md": buildNextGatewayReadme(),
4338
+ ".env.example": buildEnvExample(context),
4339
+ ".gitignore": buildGitignore(),
4340
+ "README.md": buildReadme(context)
4341
+ };
4342
+ if (!inputs.logo.isDefault && inputs.logo.fileName) {
4343
+ files[import_node_path2.default.posix.join("public", inputs.logo.fileName)] = inputs.logo.fileContent;
4344
+ }
4345
+ for (const [relativePath, content] of Object.entries(files)) {
4346
+ const destination = import_node_path2.default.join(targetDir, relativePath);
4347
+ await import_fs_extra.default.ensureDir(import_node_path2.default.dirname(destination));
4348
+ if (Buffer.isBuffer(content)) {
4349
+ await import_fs_extra.default.writeFile(destination, content);
4350
+ } else {
4351
+ await import_fs_extra.default.writeFile(destination, ensureTrailingNewline(content), "utf8");
4352
+ }
4353
+ createdFiles.push(relativePath);
4354
+ }
4355
+ return createdFiles;
4356
+ };
4357
+ var HOSTED_PROVIDER_PREFIXES = /* @__PURE__ */ new Set(["openai", "azure", "anthropic", "xai", "bandit"]);
4358
+ var buildGatewayModels = (inputs) => {
4359
+ const seen = /* @__PURE__ */ new Set();
4360
+ const models = [];
4361
+ const pushModel = (modelId) => {
4362
+ if (!modelId) return;
4363
+ if (seen.has(modelId)) return;
4364
+ seen.add(modelId);
4365
+ const prefix = modelId.includes(":") ? modelId.split(":")[0] : "";
4366
+ const hasProviderPrefix = HOSTED_PROVIDER_PREFIXES.has(prefix);
4367
+ const provider = hasProviderPrefix ? prefix : inputs.provider;
4368
+ const nameSegment = hasProviderPrefix ? modelId.slice(prefix.length + 1) : modelId;
4369
+ models.push({
4370
+ id: modelId,
4371
+ name: provider === "ollama" ? modelId : toTitleCase(nameSegment.replace(/[-_.]/g, " ")),
4372
+ provider
4373
+ });
4374
+ };
4375
+ pushModel(inputs.defaultModelId);
4376
+ pushModel(inputs.fallbackModelId);
4377
+ return models;
4378
+ };
4379
+
4380
+ // src/index.ts
4381
+ var logIntro = () => {
4382
+ console.log("\u{1F977} Bandit CLI \u2014 Burtson Labs \u{1F9EA}");
4383
+ };
4384
+ var program = new import_commander.Command();
4385
+ program.name("bandit").description("Bandit Engine developer utilities").version(package_default.version).showHelpAfterError();
4386
+ program.command("create").description("Scaffold a Bandit quickstart project with a frontend and gateway").argument("[directory]", "Relative path for your new project", "bandit-quickstart").option("-f, --force", "Overwrite the target directory if it already contains files", false).option("--branding-text <text>", "Assistant display name shown in the UI").option(
4387
+ "--provider <provider>",
4388
+ "Default gateway provider (ollama, openai, azure, anthropic, xai, bandit)"
4389
+ ).option(
4390
+ "--frontend-port <port>",
4391
+ "Frontend dev server port (default: 5183)",
4392
+ (value) => parseInt(value, 10)
4393
+ ).option("--gateway-port <port>", "Gateway port (default: 8080)", (value) => parseInt(value, 10)).option("-y, --yes", "Skip interactive prompts and accept defaults", false).option("--skip-prompts", "Alias for --yes", false).action(async (directory, cmdOptions) => {
4394
+ try {
4395
+ const targetDir = directory ?? "bandit-quickstart";
4396
+ const projectName = import_node_path3.default.basename(import_node_path3.default.resolve(process.cwd(), targetDir));
4397
+ logIntro();
4398
+ const skipPrompts = Boolean(cmdOptions.skipPrompts || cmdOptions.yes);
4399
+ const result = await createQuickstartProject({
4400
+ targetDir,
4401
+ projectName,
4402
+ force: Boolean(cmdOptions.force),
4403
+ brandingText: cmdOptions.brandingText,
4404
+ provider: typeof cmdOptions.provider === "string" ? cmdOptions.provider : void 0,
4405
+ frontendPort: Number.isFinite(cmdOptions.frontendPort) ? cmdOptions.frontendPort : void 0,
4406
+ gatewayPort: Number.isFinite(cmdOptions.gatewayPort) ? cmdOptions.gatewayPort : void 0,
4407
+ skipPrompts
4408
+ });
4409
+ const relativeDir = import_node_path3.default.relative(process.cwd(), result.projectDir) || ".";
4410
+ console.log("\n\u2705 Quickstart ready!");
4411
+ console.log(` Location: ${result.projectDir}`);
4412
+ console.log(` Package: ${result.packageName}`);
4413
+ console.log(` App name: ${result.brandingText}`);
4414
+ console.log(` Frontend: http://localhost:${result.frontendPort}`);
4415
+ console.log(` Gateway: http://localhost:${result.gatewayPort}`);
4416
+ console.log("\nNext steps:");
4417
+ console.log(` cd ${relativeDir}`);
4418
+ console.log(" npm install");
4419
+ if (result.provider !== "ollama") {
4420
+ console.log(" cp .env.example .env # add your provider credentials");
4421
+ }
4422
+ console.log(" npm run dev");
4423
+ console.log("");
4424
+ console.log("\u{1F50D} Before you dive in:");
4425
+ if (result.provider === "ollama") {
4426
+ console.log(` \u2022 Using Ollama model "${result.defaultModelId}" by default; the chat's model picker lists every installed model.`);
4427
+ console.log(" \u2022 No .env needed for local Ollama. Copy .env.example to .env only to change a default.");
4428
+ } else {
4429
+ console.log(" \u2022 Open .env to confirm the provider credentials and URLs match your setup.");
4430
+ }
4431
+ console.log(" \u2022 server/gateway.js is a scaffold Express proxy that keeps API keys server-side\u2014extend it with auth, logging, and your production logic.");
4432
+ console.log(" \u2022 If you prefer Next.js App Router, check server/next-app/ for a starter route handler.");
4433
+ console.log("");
4434
+ } catch (error) {
4435
+ const message = error instanceof Error ? error.message : "Failed to create Bandit quickstart project.";
4436
+ console.error(`
4437
+ \u274C ${message}`);
4438
+ process.exitCode = 1;
4439
+ }
4440
+ });
4441
+ async function main() {
4442
+ await program.parseAsync(process.argv);
4443
+ }
4444
+ main().catch((error) => {
4445
+ console.error(error instanceof Error ? error.message : error);
4446
+ process.exit(1);
4447
+ });
4448
+ //# sourceMappingURL=cli.js.map