Spaces:
Runtime error

File size: 19,630 Bytes
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a52f28e
 
 
 
 
 
 
 
 
 
 
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5172d3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa6801f
 
5172d3b
 
 
 
 
 
 
fa6801f
 
5172d3b
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a52f28e
fa6801f
 
 
 
 
 
 
 
 
a52f28e
fa6801f
 
a52f28e
fa6801f
 
 
 
 
 
 
 
a52f28e
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
a52f28e
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a52f28e
fa6801f
 
a52f28e
fa6801f
 
 
 
 
 
 
 
a52f28e
fa6801f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
require('dotenv').config({ path: path.resolve(process.cwd(), '.env') });
const express = require('express');

const PORT = Number(process.env.PORT || 8080);
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || 'change-me';
const MODEL_BACKEND = process.env.MODEL_BACKEND || 'openai-compatible';
const MODEL_NAME = process.env.MODEL_NAME || 'Llama-3.1-8B-Instruct';
const OLLAMA_BASE_URL = process.env.OLLAMA_BASE_URL || 'http://127.0.0.1:11434';
const OPENAI_BASE_URL = process.env.OPENAI_BASE_URL || '';
const OPENAI_API_KEY = process.env.OPENAI_API_KEY || '';
const STORE_PATH = path.resolve(process.cwd(), process.env.PROMPT_STORE_PATH || './data/prompts.json');
const REQUEST_LOG_PATH = path.resolve(process.cwd(), './data/request-log.jsonl');

function nowIso() {
  return new Date().toISOString();
}

function uid(prefix) {
  return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
}

function hashToken(token) {
  return crypto.createHash('sha256').update(String(token)).digest('hex');
}

function normalizeOriginPattern(value) {
  return String(value || '').trim();
}

function parseAllowedOrigins(value) {
  if (!value || typeof value !== 'string') {
    return ['*'];
  }
  return value
    .split(',')
    .map((x) => normalizeOriginPattern(x))
    .filter(Boolean);
}

const DEFAULT_STORE = {
  defaultPromptId: 'default',
  prompts: {
    default: {
      id: 'default',
      name: 'Default Assistant',
      systemPrompt:
        'Du bist ein hilfreicher, präziser Assistent. Antworte knapp, korrekt und ohne unnötige Ausschweifungen.',
      temperature: 0.4,
      maxTokens: 800
    }
  },
  apiKeys: [],
  settings: {
    requireApiKey: true,
    allowedOrigins: parseAllowedOrigins(process.env.ALLOWED_ORIGINS || '*'),
    defaultRateLimitPerMin: Number(process.env.DEFAULT_RATE_LIMIT_PER_MIN || 60)
  }
};

function ensureFileDir(filepath) {
  const dir = path.dirname(filepath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
}

function ensureStore() {
  ensureFileDir(STORE_PATH);
  if (!fs.existsSync(STORE_PATH)) {
    const bootKey = `sk_${crypto.randomBytes(18).toString('base64url')}`;
    const bootStore = JSON.parse(JSON.stringify(DEFAULT_STORE));
    bootStore.apiKeys.push({
      id: uid('key'),
      name: 'extension-default',
      tokenHash: hashToken(bootKey),
      enabled: true,
      rateLimitPerMin: bootStore.settings.defaultRateLimitPerMin,
      createdAt: nowIso(),
      lastUsedAt: null
    });
    fs.writeFileSync(STORE_PATH, JSON.stringify(bootStore, null, 2), 'utf8');

    const bootInfoPath = path.resolve(process.cwd(), './data/bootstrap-credentials.txt');
    fs.writeFileSync(
      bootInfoPath,
      `Created: ${nowIso()}\nAdmin token: ${ADMIN_TOKEN}\nInitial API key: ${bootKey}\n`,
      'utf8'
    );

    console.log(`Bootstrap credentials written to: ${bootInfoPath}`);
  }
}

function readStore() {
  ensureStore();
  try {
    const parsed = JSON.parse(fs.readFileSync(STORE_PATH, 'utf8'));
    return {
      defaultPromptId: parsed.defaultPromptId || 'default',
      prompts: parsed.prompts || DEFAULT_STORE.prompts,
      apiKeys: Array.isArray(parsed.apiKeys) ? parsed.apiKeys : [],
      settings: {
        requireApiKey:
          typeof parsed.settings?.requireApiKey === 'boolean'
            ? parsed.settings.requireApiKey
            : DEFAULT_STORE.settings.requireApiKey,
        allowedOrigins: Array.isArray(parsed.settings?.allowedOrigins)
          ? parsed.settings.allowedOrigins
          : DEFAULT_STORE.settings.allowedOrigins,
        defaultRateLimitPerMin: Number(parsed.settings?.defaultRateLimitPerMin || DEFAULT_STORE.settings.defaultRateLimitPerMin)
      }
    };
  } catch (_error) {
    return JSON.parse(JSON.stringify(DEFAULT_STORE));
  }
}

let storeCache = readStore();

function persistStore() {
  ensureFileDir(STORE_PATH);
  fs.writeFileSync(STORE_PATH, JSON.stringify(storeCache, null, 2), 'utf8');
}

function appendRequestLog(entry) {
  ensureFileDir(REQUEST_LOG_PATH);
  fs.appendFileSync(REQUEST_LOG_PATH, `${JSON.stringify(entry)}\n`, 'utf8');
}

function authAdmin(req, res, next) {
  const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
  const token = bearer || req.headers['x-admin-token'];
  if (!token || token !== ADMIN_TOKEN) {
    return res.status(401).json({ error: 'unauthorized' });
  }
  next();
}

function matchOrigin(origin, pattern) {
  if (pattern === '*') {
    return true;
  }
  if (pattern.endsWith('*')) {
    return origin.startsWith(pattern.slice(0, -1));
  }
  return origin === pattern;
}

function corsMiddleware(req, res, next) {
  const origin = req.headers.origin;
  const allowed = storeCache.settings.allowedOrigins || ['*'];

  if (!origin) {
    if (req.method === 'OPTIONS') {
      return res.status(204).end();
    }
    return next();
  }

  const isAllowed = allowed.some((pattern) => matchOrigin(origin, String(pattern)));
  if (!isAllowed) {
    if (req.path.startsWith('/v1') || req.path.startsWith('/admin')) {
      return res.status(403).json({ error: 'origin_not_allowed' });
    }
    return next();
  }

  res.setHeader('Access-Control-Allow-Origin', origin);
  res.setHeader('Vary', 'Origin');
  res.setHeader('Access-Control-Allow-Headers', 'content-type, authorization, x-admin-token');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

  if (req.method === 'OPTIONS') {
    return res.status(204).end();
  }

  next();
}

const rateState = new Map();

function authApi(req, res, next) {
  if (!storeCache.settings.requireApiKey) {
    return next();
  }

  const bearer = (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim();
  if (!bearer) {
    return res.status(401).json({ error: 'api_key_required' });
  }

  const tokenHash = hashToken(bearer);
  const keyObj = storeCache.apiKeys.find((k) => k.enabled && k.tokenHash === tokenHash);
  if (!keyObj) {
    return res.status(401).json({ error: 'invalid_api_key' });
  }

  const now = Date.now();
  const bucket = rateState.get(keyObj.id) || { startMs: now, count: 0 };
  if (now - bucket.startMs >= 60_000) {
    bucket.startMs = now;
    bucket.count = 0;
  }

  const limit = Number(keyObj.rateLimitPerMin || storeCache.settings.defaultRateLimitPerMin || 60);
  bucket.count += 1;
  rateState.set(keyObj.id, bucket);

  if (bucket.count > limit) {
    return res.status(429).json({ error: 'rate_limit_exceeded', limit_per_min: limit });
  }

  keyObj.lastUsedAt = nowIso();
  persistStore();

  req.apiKey = {
    id: keyObj.id,
    name: keyObj.name
  };

  next();
}

function sanitizeMessages(messages) {
  if (!Array.isArray(messages)) {
    return [];
  }
  return messages
    .map((m) => ({
      role: String(m.role || '').trim(),
      content: typeof m.content === 'string' ? m.content : String(m.content || '')
    }))
    .filter((m) => ['system', 'user', 'assistant', 'tool'].includes(m.role) && m.content.length > 0)
    .slice(-40);
}

function withSystemPrompt(systemPrompt, messages) {
  const payload = sanitizeMessages(messages);
  return [{ role: 'system', content: systemPrompt }, ...payload.filter((x) => x.role !== 'system')];
}

function resolveSystemPrompt(basePrompt, overridePrompt) {
  if (typeof overridePrompt !== 'string') {
    return basePrompt;
  }
  const trimmed = overridePrompt.trim();
  if (!trimmed) {
    return basePrompt;
  }
  return trimmed.slice(0, 16000);
}

async function callOllama({ model, messages, temperature, maxTokens }) {
  const response = await fetch(`${OLLAMA_BASE_URL}/api/chat`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      model,
      stream: false,
      options: {
        temperature,
        num_predict: maxTokens
      },
      messages
    })
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`ollama_${response.status}: ${text}`);
  }

  const data = await response.json();
  return {
    content: data?.message?.content || '',
    usage: data?.prompt_eval_count
      ? {
          prompt_tokens: data.prompt_eval_count,
          completion_tokens: data.eval_count || 0,
          total_tokens: (data.prompt_eval_count || 0) + (data.eval_count || 0)
        }
      : null
  };
}

async function callOpenAICompatible({ model, messages, temperature, maxTokens }) {
  if (!OPENAI_BASE_URL || !OPENAI_API_KEY) {
    throw new Error('openai_backend_not_configured');
  }

  const requestedModel = String(model || '').trim();
  const candidates = [requestedModel];
  if (requestedModel.toLowerCase() === 'llama-3.1-8b-instruct') {
    candidates.push('meta-llama/llama-3.1-8b-instruct');
    candidates.push('meta-llama-3.1-8b-instruct');
  }

  const uniqueCandidates = [...new Set(candidates.filter(Boolean))];
  let lastError = 'openai_compatible_unknown_error';

  for (let i = 0; i < uniqueCandidates.length; i += 1) {
    const candidateModel = uniqueCandidates[i];
    const response = await fetch(`${OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        authorization: `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: candidateModel,
        messages,
        temperature,
        max_tokens: maxTokens
      })
    });

    if (response.ok) {
      const data = await response.json();
      return {
        content: data?.choices?.[0]?.message?.content || '',
        usage: data?.usage || null
      };
    }

    const text = await response.text();
    lastError = `openai_compatible_${response.status}: ${text}`;

    const isModelError = response.status === 400 && /model/i.test(text);
    const hasNextCandidate = i < uniqueCandidates.length - 1;
    if (!(isModelError && hasNextCandidate)) {
      throw new Error(lastError);
    }
  }

  throw new Error(lastError);
}

async function infer({ model, messages, temperature, maxTokens }) {
  if (MODEL_BACKEND === 'openai-compatible') {
    return callOpenAICompatible({ model, messages, temperature, maxTokens });
  }
  return callOllama({ model, messages, temperature, maxTokens });
}

function publicStoreInfo() {
  return {
    defaultPromptId: storeCache.defaultPromptId,
    prompts: Object.fromEntries(
      Object.entries(storeCache.prompts || {}).map(([id, p]) => [id, { id, name: p.name }])
    ),
    settings: {
      requireApiKey: storeCache.settings.requireApiKey,
      allowedOrigins: storeCache.settings.allowedOrigins,
      defaultRateLimitPerMin: storeCache.settings.defaultRateLimitPerMin
    }
  };
}

const app = express();
app.disable('x-powered-by');
app.use(express.json({ limit: '2mb' }));
app.use(corsMiddleware);
app.use(express.static(path.resolve(process.cwd(), 'public')));

app.get('/health', (_req, res) => {
  res.json({
    ok: true,
    backend: MODEL_BACKEND,
    model: MODEL_NAME,
    time: nowIso()
  });
});

app.get('/v1/models', authApi, (_req, res) => {
  res.json({
    object: 'list',
    data: [{ id: MODEL_NAME, object: 'model', created: Math.floor(Date.now() / 1000), owned_by: MODEL_BACKEND }]
  });
});

app.get('/v1/prompts', authApi, (_req, res) => {
  res.json(publicStoreInfo());
});

app.post('/v1/chat', authApi, async (req, res) => {
  try {
    const { input, promptId, model, temperature, maxTokens, systemPromptOverride } = req.body || {};
    if (!input || typeof input !== 'string') {
      return res.status(400).json({ error: 'input_required' });
    }

    const promptCfg = storeCache.prompts[promptId || storeCache.defaultPromptId];
    if (!promptCfg) {
      return res.status(400).json({ error: 'prompt_not_found' });
    }

    const effectiveSystemPrompt = resolveSystemPrompt(promptCfg.systemPrompt, systemPromptOverride);
    const out = await infer({
      model: model || MODEL_NAME,
      messages: withSystemPrompt(effectiveSystemPrompt, [{ role: 'user', content: input }]),
      temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : promptCfg.temperature,
      maxTokens: Number.isFinite(Number(maxTokens)) ? Number(maxTokens) : promptCfg.maxTokens
    });

    appendRequestLog({
      ts: nowIso(),
      route: '/v1/chat',
      promptId: promptCfg.id,
      systemPromptOverridden: effectiveSystemPrompt !== promptCfg.systemPrompt,
      model: model || MODEL_NAME,
      keyId: req.apiKey?.id || null,
      inputChars: input.length,
      outputChars: out.content.length
    });

    res.json({ ok: true, promptId: promptCfg.id, model: model || MODEL_NAME, content: out.content, usage: out.usage });
  } catch (error) {
    res.status(500).json({ error: 'inference_failed', detail: String(error.message || error) });
  }
});

app.post('/v1/chat/completions', authApi, async (req, res) => {
  try {
    const { messages, promptId, model, temperature, max_tokens, stream, systemPromptOverride } = req.body || {};
    if (stream) {
      return res.status(400).json({ error: 'stream_not_supported_in_this_build' });
    }

    const cleanMessages = sanitizeMessages(messages);
    if (cleanMessages.length === 0) {
      return res.status(400).json({ error: 'messages_required' });
    }

    const promptCfg = storeCache.prompts[promptId || storeCache.defaultPromptId];
    if (!promptCfg) {
      return res.status(400).json({ error: 'prompt_not_found' });
    }

    const usedModel = model || MODEL_NAME;
    const effectiveSystemPrompt = resolveSystemPrompt(promptCfg.systemPrompt, systemPromptOverride);
    const out = await infer({
      model: usedModel,
      messages: withSystemPrompt(effectiveSystemPrompt, cleanMessages),
      temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : promptCfg.temperature,
      maxTokens: Number.isFinite(Number(max_tokens)) ? Number(max_tokens) : promptCfg.maxTokens
    });

    appendRequestLog({
      ts: nowIso(),
      route: '/v1/chat/completions',
      promptId: promptCfg.id,
      systemPromptOverridden: effectiveSystemPrompt !== promptCfg.systemPrompt,
      model: usedModel,
      keyId: req.apiKey?.id || null,
      inputMsgs: cleanMessages.length,
      outputChars: out.content.length
    });

    res.json({
      id: `chatcmpl_${Date.now()}`,
      object: 'chat.completion',
      created: Math.floor(Date.now() / 1000),
      model: usedModel,
      prompt_id: promptCfg.id,
      choices: [
        {
          index: 0,
          finish_reason: 'stop',
          message: { role: 'assistant', content: out.content }
        }
      ],
      usage: out.usage
    });
  } catch (error) {
    res.status(500).json({ error: 'inference_failed', detail: String(error.message || error) });
  }
});

app.get('/admin/state', authAdmin, (_req, res) => {
  const maskedKeys = (storeCache.apiKeys || []).map((k) => ({
    id: k.id,
    name: k.name,
    enabled: Boolean(k.enabled),
    rateLimitPerMin: Number(k.rateLimitPerMin || 60),
    createdAt: k.createdAt,
    lastUsedAt: k.lastUsedAt
  }));

  res.json({
    prompts: storeCache.prompts,
    defaultPromptId: storeCache.defaultPromptId,
    settings: storeCache.settings,
    apiKeys: maskedKeys,
    backend: MODEL_BACKEND,
    model: MODEL_NAME
  });
});

app.put('/admin/prompts/:id', authAdmin, (req, res) => {
  const id = String(req.params.id || '').trim();
  if (!/^[a-zA-Z0-9_-]{2,64}$/.test(id)) {
    return res.status(400).json({ error: 'invalid_prompt_id' });
  }

  const { name, systemPrompt, temperature, maxTokens, setDefault } = req.body || {};
  if (!systemPrompt || typeof systemPrompt !== 'string') {
    return res.status(400).json({ error: 'systemPrompt_required' });
  }

  storeCache.prompts[id] = {
    id,
    name: String(name || id).slice(0, 80),
    systemPrompt: systemPrompt.slice(0, 16000),
    temperature: Number.isFinite(Number(temperature)) ? Number(temperature) : 0.4,
    maxTokens: Number.isFinite(Number(maxTokens)) ? Number(maxTokens) : 800
  };

  if (setDefault) {
    storeCache.defaultPromptId = id;
  }

  persistStore();
  res.json({ ok: true, prompt: storeCache.prompts[id], defaultPromptId: storeCache.defaultPromptId });
});

app.delete('/admin/prompts/:id', authAdmin, (req, res) => {
  const id = String(req.params.id || '').trim();
  if (!storeCache.prompts[id]) {
    return res.status(404).json({ error: 'prompt_not_found' });
  }
  if (id === storeCache.defaultPromptId) {
    return res.status(400).json({ error: 'cannot_delete_default_prompt' });
  }

  delete storeCache.prompts[id];
  persistStore();
  res.json({ ok: true });
});

app.post('/admin/keys', authAdmin, (req, res) => {
  const name = String(req.body?.name || '').trim();
  if (!name) {
    return res.status(400).json({ error: 'name_required' });
  }

  const token = `sk_${crypto.randomBytes(18).toString('base64url')}`;
  const entry = {
    id: uid('key'),
    name: name.slice(0, 80),
    tokenHash: hashToken(token),
    enabled: true,
    rateLimitPerMin: Number(req.body?.rateLimitPerMin || storeCache.settings.defaultRateLimitPerMin || 60),
    createdAt: nowIso(),
    lastUsedAt: null
  };

  storeCache.apiKeys.push(entry);
  persistStore();

  res.json({
    ok: true,
    key: {
      id: entry.id,
      name: entry.name,
      token,
      enabled: entry.enabled,
      rateLimitPerMin: entry.rateLimitPerMin,
      createdAt: entry.createdAt
    }
  });
});

app.patch('/admin/keys/:id', authAdmin, (req, res) => {
  const id = String(req.params.id || '').trim();
  const key = storeCache.apiKeys.find((k) => k.id === id);
  if (!key) {
    return res.status(404).json({ error: 'key_not_found' });
  }

  if (typeof req.body?.enabled === 'boolean') {
    key.enabled = req.body.enabled;
  }
  if (Number.isFinite(Number(req.body?.rateLimitPerMin))) {
    key.rateLimitPerMin = Number(req.body.rateLimitPerMin);
  }
  persistStore();

  res.json({
    ok: true,
    key: {
      id: key.id,
      name: key.name,
      enabled: key.enabled,
      rateLimitPerMin: key.rateLimitPerMin,
      createdAt: key.createdAt,
      lastUsedAt: key.lastUsedAt
    }
  });
});

app.delete('/admin/keys/:id', authAdmin, (req, res) => {
  const id = String(req.params.id || '').trim();
  const idx = storeCache.apiKeys.findIndex((k) => k.id === id);
  if (idx < 0) {
    return res.status(404).json({ error: 'key_not_found' });
  }
  storeCache.apiKeys.splice(idx, 1);
  persistStore();
  res.json({ ok: true });
});

app.put('/admin/settings', authAdmin, (req, res) => {
  const { requireApiKey, allowedOrigins, defaultRateLimitPerMin } = req.body || {};

  if (typeof requireApiKey === 'boolean') {
    storeCache.settings.requireApiKey = requireApiKey;
  }

  if (Array.isArray(allowedOrigins)) {
    storeCache.settings.allowedOrigins = allowedOrigins.map((x) => normalizeOriginPattern(x)).filter(Boolean);
    if (storeCache.settings.allowedOrigins.length === 0) {
      storeCache.settings.allowedOrigins = ['*'];
    }
  }

  if (Number.isFinite(Number(defaultRateLimitPerMin))) {
    storeCache.settings.defaultRateLimitPerMin = Number(defaultRateLimitPerMin);
  }

  persistStore();
  res.json({ ok: true, settings: storeCache.settings });
});

app.post('/admin/reload', authAdmin, (_req, res) => {
  storeCache = readStore();
  res.json({ ok: true });
});

app.use((err, _req, res, _next) => {
  res.status(500).json({ error: 'internal_error', detail: String(err?.message || err) });
});

app.listen(PORT, () => {
  console.log(`Selfhosted AI API listening on http://localhost:${PORT}`);
  console.log(`Backend: ${MODEL_BACKEND} | Model: ${MODEL_NAME}`);
});