@constructive-io/graphql-server 4.31.5 → 4.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -245,14 +245,21 @@ const buildPreset = (pool, schemas, anonRole, roleName, databaseSettings) => {
245
245
  if (req.token.access_level === 'read_only') {
246
246
  pgSettings['default_transaction_read_only'] = 'on';
247
247
  }
248
+ if (req.requestId) {
249
+ pgSettings['request.id'] = req.requestId;
250
+ }
248
251
  return { pgSettings };
249
252
  }
250
253
  }
254
+ const anonSettings = {
255
+ role: anonRole,
256
+ ...context,
257
+ };
258
+ if (req?.requestId) {
259
+ anonSettings['request.id'] = req.requestId;
260
+ }
251
261
  return {
252
- pgSettings: {
253
- role: anonRole,
254
- ...context,
255
- },
262
+ pgSettings: anonSettings,
256
263
  };
257
264
  },
258
265
  },
@@ -0,0 +1,575 @@
1
+ /**
2
+ * LLM API Router
3
+ *
4
+ * Express router providing REST streaming endpoints for AI agent conversations.
5
+ * Uses the agent tables (agent_thread, agent_message) discovered from the
6
+ * agent_chat_module config table at runtime.
7
+ *
8
+ * Hybrid architecture:
9
+ * - GraphQL handles CRUD (threads, messages, tasks) via PostGraphile
10
+ * - REST handles SSE streaming for chat completions (what GraphQL can't do)
11
+ *
12
+ * Routes (entity-scoped):
13
+ * POST /v1/orgs/:entity_id/threads → create thread
14
+ * POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message + stream response
15
+ *
16
+ * Routes (global — bills to actor_id from JWT):
17
+ * POST /v1/threads → create thread (entity_id = user_id)
18
+ * POST /v1/threads/:thread_id/messages → send message + stream response
19
+ *
20
+ * Auth: JWT from the auth middleware (req.token) → pg SET LOCAL context for RLS
21
+ * Metering: check_billing_quota → LLM call → record_usage with real token counts
22
+ */
23
+ import express, { Router } from 'express';
24
+ import { Logger } from '@pgpmjs/logger';
25
+ import { getPgPool } from 'pg-cache';
26
+ import { OllamaAdapter } from '@agentic-kit/ollama';
27
+ import { ModuleConfigCache } from 'graphile-cache';
28
+ import { getLlmEnvOptions, getAgentDiscovery, getLlmBillingConfig, } from 'graphile-llm';
29
+ const log = new Logger('llm-api');
30
+ // ─── Helpers ────────────────────────────────────────────────────────────────
31
+ function getPgSettings(req) {
32
+ const settings = {};
33
+ if (req.token?.user_id) {
34
+ settings['jwt.claims.user_id'] = req.token.user_id;
35
+ settings['role'] = 'authenticated';
36
+ }
37
+ if (req.databaseId) {
38
+ settings['jwt.claims.database_id'] = req.databaseId;
39
+ }
40
+ if (req.requestId) {
41
+ settings['request.id'] = req.requestId;
42
+ }
43
+ return settings;
44
+ }
45
+ async function withRlsClient(pool, pgSettings, fn) {
46
+ const client = await pool.connect();
47
+ try {
48
+ await client.query('BEGIN');
49
+ for (const [key, value] of Object.entries(pgSettings)) {
50
+ await client.query('SELECT set_config($1, $2, true)', [key, value]);
51
+ }
52
+ const result = await fn(client);
53
+ await client.query('COMMIT');
54
+ return result;
55
+ }
56
+ catch (err) {
57
+ await client.query('ROLLBACK').catch(() => { });
58
+ throw err;
59
+ }
60
+ finally {
61
+ client.release();
62
+ }
63
+ }
64
+ function resolveOllamaAdapter() {
65
+ const { chat } = getLlmEnvOptions();
66
+ if (chat.provider === 'ollama') {
67
+ return {
68
+ adapter: new OllamaAdapter(chat.baseUrl),
69
+ model: chat.model,
70
+ baseUrl: chat.baseUrl,
71
+ };
72
+ }
73
+ return null;
74
+ }
75
+ // ─── Billing Helpers ────────────────────────────────────────────────────────
76
+ async function checkQuota(pool, pgSettings, billing, entityId, meterSlug) {
77
+ try {
78
+ return await withRlsClient(pool, pgSettings, async (client) => {
79
+ const sql = `SELECT "${billing.privateSchema}"."${billing.checkBillingQuotaFunction}"($1, $2::uuid, $3) AS allowed`;
80
+ const result = await client.query(sql, [meterSlug, entityId, 1]);
81
+ return result.rows[0]?.allowed !== false;
82
+ });
83
+ }
84
+ catch (e) {
85
+ const message = e instanceof Error ? e.message : String(e);
86
+ log.warn(`[llm-api] check_billing_quota failed (allowing): ${message}`);
87
+ return true;
88
+ }
89
+ }
90
+ async function recordUsage(pool, pgSettings, billing, entityId, meterSlug, amount, metadata) {
91
+ try {
92
+ await withRlsClient(pool, pgSettings, async (client) => {
93
+ const sql = `SELECT "${billing.privateSchema}"."${billing.recordUsageFunction}"($1, $2::uuid, $3, $4::jsonb)`;
94
+ await client.query(sql, [meterSlug, entityId, amount, JSON.stringify(metadata)]);
95
+ });
96
+ }
97
+ catch (e) {
98
+ const message = e instanceof Error ? e.message : String(e);
99
+ log.warn(`[llm-api] record_usage failed (non-fatal): ${message}`);
100
+ }
101
+ }
102
+ async function resolveBilling(pool, pgSettings, databaseId) {
103
+ try {
104
+ let billing = null;
105
+ await withRlsClient(pool, pgSettings, async (client) => {
106
+ const entry = await getLlmBillingConfig(client, databaseId);
107
+ billing = entry.billing;
108
+ });
109
+ return billing;
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ const INFERENCE_LOG_DISCOVERY_SQL = `
116
+ SELECT s.schema_name, ilm.inference_log_table_name
117
+ FROM metaschema_modules_public.inference_log_module ilm
118
+ JOIN metaschema_public.schema s ON s.id = ilm.schema_id
119
+ LIMIT 1
120
+ `;
121
+ const inferenceLogCache = new ModuleConfigCache({
122
+ name: 'inference-log',
123
+ ttlMs: 60_000,
124
+ });
125
+ async function getInferenceLogInfo(pool, dbname) {
126
+ const cached = inferenceLogCache.get(dbname);
127
+ if (cached !== undefined)
128
+ return cached;
129
+ let info = null;
130
+ try {
131
+ const { rows } = await pool.query(INFERENCE_LOG_DISCOVERY_SQL);
132
+ if (rows.length > 0) {
133
+ info = {
134
+ schemaName: rows[0].schema_name,
135
+ tableName: rows[0].inference_log_table_name,
136
+ };
137
+ }
138
+ }
139
+ catch {
140
+ // Module not provisioned
141
+ }
142
+ inferenceLogCache.set(dbname, info);
143
+ return info;
144
+ }
145
+ async function logInference(pool, pgSettings, logInfo, data) {
146
+ try {
147
+ await withRlsClient(pool, pgSettings, async (client) => {
148
+ await client.query(`INSERT INTO "${logInfo.schemaName}"."${logInfo.tableName}"
149
+ (entity_id, actor_id, model, provider, service, operation, input_tokens, output_tokens, total_tokens, latency_ms, status)
150
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
151
+ data.entityId,
152
+ data.actorId,
153
+ data.model,
154
+ data.provider,
155
+ data.service,
156
+ data.operation,
157
+ data.inputTokens,
158
+ data.outputTokens,
159
+ data.totalTokens,
160
+ data.latencyMs,
161
+ data.status,
162
+ ]);
163
+ });
164
+ }
165
+ catch (e) {
166
+ const message = e instanceof Error ? e.message : String(e);
167
+ log.warn(`[llm-api] inference log INSERT failed (non-fatal): ${message}`);
168
+ }
169
+ }
170
+ // ─── Route Handlers ─────────────────────────────────────────────────────────
171
+ async function handleCreateThread(req, res, entityId) {
172
+ if (!req.token?.user_id) {
173
+ res.status(401).json({ error: 'Authentication required' });
174
+ return;
175
+ }
176
+ const dbname = req.api?.dbname;
177
+ if (!dbname) {
178
+ res.status(400).json({ error: 'Database not resolved' });
179
+ return;
180
+ }
181
+ const pool = getPgPool({ database: dbname });
182
+ const discovery = await getAgentDiscovery(pool, dbname);
183
+ if (!discovery?.thread) {
184
+ res.status(404).json({ error: 'Agent module not provisioned for this database' });
185
+ return;
186
+ }
187
+ const body = req.body || {};
188
+ const { thread } = discovery;
189
+ const pgSettings = getPgSettings(req);
190
+ const result = await withRlsClient(pool, pgSettings, async (client) => {
191
+ const { rows } = await client.query(`INSERT INTO "${thread.schemaName}"."${thread.tableName}"
192
+ (entity_id, owner_id, mode, model, system_prompt, title)
193
+ VALUES ($1, $2, $3, $4, $5, $6)
194
+ RETURNING id, mode, model, system_prompt, status, created_at`, [
195
+ entityId,
196
+ req.token.user_id,
197
+ body.mode ?? 'ask',
198
+ body.model ?? null,
199
+ body.system_prompt ?? null,
200
+ body.title ?? null,
201
+ ]);
202
+ return rows[0];
203
+ });
204
+ res.status(201).json({
205
+ id: result.id,
206
+ mode: result.mode,
207
+ model: result.model,
208
+ system_prompt: result.system_prompt,
209
+ status: result.status,
210
+ created_at: result.created_at,
211
+ });
212
+ }
213
+ async function handleSendMessage(req, res, entityId) {
214
+ if (!req.token?.user_id) {
215
+ res.status(401).json({ error: 'Authentication required' });
216
+ return;
217
+ }
218
+ const dbname = req.api?.dbname;
219
+ if (!dbname) {
220
+ res.status(400).json({ error: 'Database not resolved' });
221
+ return;
222
+ }
223
+ const pool = getPgPool({ database: dbname });
224
+ const discovery = await getAgentDiscovery(pool, dbname);
225
+ if (!discovery?.thread || !discovery?.message) {
226
+ res.status(404).json({ error: 'Agent module not provisioned for this database' });
227
+ return;
228
+ }
229
+ const body = req.body || {};
230
+ if (!body.messages?.length) {
231
+ res.status(400).json({ error: 'messages[] is required and must not be empty' });
232
+ return;
233
+ }
234
+ const { thread, message: msgTable } = discovery;
235
+ const pgSettings = getPgSettings(req);
236
+ const threadId = req.params.thread_id;
237
+ const userId = req.token.user_id;
238
+ const databaseId = req.databaseId;
239
+ // 1. Verify thread exists and user owns it (RLS enforced)
240
+ const threadRow = await withRlsClient(pool, pgSettings, async (client) => {
241
+ const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
242
+ FROM "${thread.schemaName}"."${thread.tableName}"
243
+ WHERE id = $1`, [threadId]);
244
+ return rows[0];
245
+ });
246
+ if (!threadRow) {
247
+ res.status(404).json({ error: 'Thread not found' });
248
+ return;
249
+ }
250
+ // 2. Resolve billing config + inference log discovery
251
+ const billing = databaseId
252
+ ? await resolveBilling(pool, pgSettings, databaseId)
253
+ : null;
254
+ const inferenceLog = await getInferenceLogInfo(pool, dbname);
255
+ const ollama = resolveOllamaAdapter();
256
+ if (!ollama) {
257
+ res.status(503).json({ error: 'No LLM provider configured' });
258
+ return;
259
+ }
260
+ const model = body.model ?? threadRow.model ?? ollama.model;
261
+ const meterSlug = model;
262
+ if (billing) {
263
+ const allowed = await checkQuota(pool, pgSettings, billing, entityId, meterSlug);
264
+ if (!allowed) {
265
+ res.status(429).json({
266
+ error: 'Token quota exceeded',
267
+ meter: meterSlug,
268
+ entity_id: entityId,
269
+ });
270
+ return;
271
+ }
272
+ }
273
+ // 3. Persist user message(s)
274
+ await withRlsClient(pool, pgSettings, async (client) => {
275
+ for (const msg of body.messages) {
276
+ if (msg.role === 'user') {
277
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
278
+ (thread_id, owner_id, entity_id, author_role, parts)
279
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4)`, [
280
+ threadId,
281
+ userId,
282
+ 'user',
283
+ JSON.stringify([{ type: 'text', text: msg.content }]),
284
+ ]);
285
+ }
286
+ }
287
+ });
288
+ // 4. Load full thread history for context
289
+ const history = await withRlsClient(pool, pgSettings, async (client) => {
290
+ const { rows } = await client.query(`SELECT author_role, parts, created_at
291
+ FROM "${msgTable.schemaName}"."${msgTable.tableName}"
292
+ WHERE thread_id = $1
293
+ ORDER BY created_at ASC`, [threadId]);
294
+ return rows;
295
+ });
296
+ const llmMessages = [];
297
+ const systemPrompt = threadRow.system_prompt;
298
+ if (systemPrompt) {
299
+ llmMessages.push({ role: 'system', content: systemPrompt });
300
+ }
301
+ for (const row of history) {
302
+ const parts = Array.isArray(row.parts) ? row.parts : [];
303
+ const textContent = parts
304
+ .filter((p) => p.type === 'text')
305
+ .map((p) => p.text)
306
+ .join('');
307
+ if (textContent) {
308
+ llmMessages.push({
309
+ role: row.author_role === 'user' ? 'user' : 'assistant',
310
+ content: textContent,
311
+ });
312
+ }
313
+ }
314
+ // 5. Call LLM with token usage tracking
315
+ const shouldStream = body.stream !== false;
316
+ const startTime = Date.now();
317
+ if (shouldStream) {
318
+ // ── SSE Streaming via OllamaAdapter ─────────────────────────────────
319
+ res.writeHead(200, {
320
+ 'Content-Type': 'text/event-stream',
321
+ 'Cache-Control': 'no-cache',
322
+ 'Connection': 'keep-alive',
323
+ 'X-Accel-Buffering': 'no',
324
+ });
325
+ const messageId = `msg_${Date.now()}`;
326
+ try {
327
+ const systemMsg = llmMessages.find(m => m.role === 'system');
328
+ const nonSystem = llmMessages.filter(m => m.role !== 'system');
329
+ const modelDesc = ollama.adapter.createModel(model, {
330
+ maxOutputTokens: undefined,
331
+ });
332
+ const context = {
333
+ systemPrompt: systemMsg?.content,
334
+ messages: nonSystem.map((m) => ({
335
+ role: m.role,
336
+ content: m.content,
337
+ timestamp: Date.now(),
338
+ })),
339
+ };
340
+ const stream = ollama.adapter.stream(modelDesc, context, {
341
+ temperature: body.temperature,
342
+ });
343
+ let streamedContent = '';
344
+ for await (const event of stream) {
345
+ if (event.type === 'text_delta') {
346
+ streamedContent += event.delta;
347
+ const sseEvent = {
348
+ id: messageId,
349
+ choices: [{
350
+ index: 0,
351
+ delta: { content: event.delta, role: 'assistant' },
352
+ finish_reason: null,
353
+ }],
354
+ model,
355
+ };
356
+ res.write(`data: ${JSON.stringify(sseEvent)}\n\n`);
357
+ }
358
+ }
359
+ const result = await stream.result();
360
+ const content = streamedContent;
361
+ const latencyMs = Date.now() - startTime;
362
+ const usage = {
363
+ input: result.usage.input,
364
+ output: result.usage.output,
365
+ reasoning: result.usage.reasoning,
366
+ cacheRead: result.usage.cacheRead,
367
+ cacheWrite: result.usage.cacheWrite,
368
+ totalTokens: result.usage.totalTokens,
369
+ };
370
+ // Send [DONE] marker
371
+ res.write('data: [DONE]\n\n');
372
+ res.end();
373
+ // 6. Persist assistant message with model (fire-and-forget)
374
+ if (content) {
375
+ withRlsClient(pool, pgSettings, async (client) => {
376
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
377
+ (thread_id, owner_id, entity_id, author_role, parts, model)
378
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [
379
+ threadId,
380
+ userId,
381
+ 'assistant',
382
+ JSON.stringify([{ type: 'text', text: content }]),
383
+ model,
384
+ ]);
385
+ }).catch((err) => {
386
+ log.error('[llm-api] Failed to persist assistant message:', err);
387
+ });
388
+ }
389
+ // 7. Record billing usage (fire-and-forget)
390
+ if (billing && usage.totalTokens > 0) {
391
+ recordUsage(pool, pgSettings, billing, entityId, meterSlug, usage.totalTokens, {
392
+ input_tokens: usage.input,
393
+ output_tokens: usage.output,
394
+ cache_read_tokens: usage.cacheRead,
395
+ cache_write_tokens: usage.cacheWrite,
396
+ model,
397
+ latency_ms: latencyMs,
398
+ stream: true,
399
+ }).catch(() => { });
400
+ }
401
+ // 8. Inference log (fire-and-forget)
402
+ if (inferenceLog) {
403
+ logInference(pool, pgSettings, inferenceLog, {
404
+ entityId,
405
+ actorId: userId,
406
+ model,
407
+ provider: 'ollama',
408
+ service: 'llm',
409
+ operation: 'chat',
410
+ inputTokens: usage.input,
411
+ outputTokens: usage.output,
412
+ totalTokens: usage.totalTokens,
413
+ latencyMs,
414
+ status: 'ok',
415
+ }).catch(() => { });
416
+ }
417
+ }
418
+ catch (streamErr) {
419
+ log.error('[llm-api] Streaming error:', streamErr);
420
+ const errorEvent = { error: { message: streamErr.message, type: 'stream_error' } };
421
+ res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
422
+ res.write('data: [DONE]\n\n');
423
+ res.end();
424
+ }
425
+ }
426
+ else {
427
+ // ── Non-streaming (batch) via OllamaAdapter ─────────────────────────
428
+ const systemMsg = llmMessages.find(m => m.role === 'system');
429
+ const nonSystem = llmMessages.filter(m => m.role !== 'system');
430
+ const modelDesc = ollama.adapter.createModel(model, {
431
+ maxOutputTokens: undefined,
432
+ });
433
+ const context = {
434
+ systemPrompt: systemMsg?.content,
435
+ messages: nonSystem.map((m) => ({
436
+ role: m.role,
437
+ content: m.content,
438
+ timestamp: Date.now(),
439
+ })),
440
+ };
441
+ const stream = ollama.adapter.stream(modelDesc, context, {
442
+ temperature: body.temperature,
443
+ });
444
+ const result = await stream.result();
445
+ const content = result.content
446
+ .filter((block) => block.type === 'text')
447
+ .map((block) => block.text)
448
+ .join('');
449
+ const latencyMs = Date.now() - startTime;
450
+ const usage = {
451
+ input: result.usage.input,
452
+ output: result.usage.output,
453
+ reasoning: result.usage.reasoning,
454
+ cacheRead: result.usage.cacheRead,
455
+ cacheWrite: result.usage.cacheWrite,
456
+ totalTokens: result.usage.totalTokens,
457
+ };
458
+ // Persist assistant message with model
459
+ await withRlsClient(pool, pgSettings, async (client) => {
460
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
461
+ (thread_id, owner_id, entity_id, author_role, parts, model)
462
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [
463
+ threadId,
464
+ userId,
465
+ 'assistant',
466
+ JSON.stringify([{ type: 'text', text: content }]),
467
+ model,
468
+ ]);
469
+ });
470
+ // Record billing usage
471
+ if (billing && usage.totalTokens > 0) {
472
+ recordUsage(pool, pgSettings, billing, entityId, meterSlug, usage.totalTokens, {
473
+ input_tokens: usage.input,
474
+ output_tokens: usage.output,
475
+ cache_read_tokens: usage.cacheRead,
476
+ cache_write_tokens: usage.cacheWrite,
477
+ model,
478
+ latency_ms: latencyMs,
479
+ stream: false,
480
+ }).catch(() => { });
481
+ }
482
+ // Inference log
483
+ if (inferenceLog) {
484
+ logInference(pool, pgSettings, inferenceLog, {
485
+ entityId,
486
+ actorId: userId,
487
+ model,
488
+ provider: 'ollama',
489
+ service: 'llm',
490
+ operation: 'chat',
491
+ inputTokens: usage.input,
492
+ outputTokens: usage.output,
493
+ totalTokens: usage.totalTokens,
494
+ latencyMs,
495
+ status: 'ok',
496
+ }).catch(() => { });
497
+ }
498
+ res.json({
499
+ id: `msg_${Date.now()}`,
500
+ choices: [{
501
+ index: 0,
502
+ message: { role: 'assistant', content },
503
+ finish_reason: 'stop',
504
+ }],
505
+ model,
506
+ usage: {
507
+ prompt_tokens: usage.input,
508
+ completion_tokens: usage.output,
509
+ total_tokens: usage.totalTokens,
510
+ },
511
+ });
512
+ }
513
+ }
514
+ // ─── Router Factory ─────────────────────────────────────────────────────────
515
+ export function createLlmApiRouter() {
516
+ const router = Router();
517
+ router.use(express.json());
518
+ // ── Entity-scoped routes ─────────────────────────────────────────────────
519
+ router.post('/v1/orgs/:entity_id/threads', async (req, res) => {
520
+ try {
521
+ await handleCreateThread(req, res, req.params.entity_id);
522
+ }
523
+ catch (err) {
524
+ log.error('[llm-api] Error creating thread:', err);
525
+ if (!res.headersSent) {
526
+ res.status(500).json({ error: 'Internal server error' });
527
+ }
528
+ }
529
+ });
530
+ router.post('/v1/orgs/:entity_id/threads/:thread_id/messages', async (req, res) => {
531
+ try {
532
+ await handleSendMessage(req, res, req.params.entity_id);
533
+ }
534
+ catch (err) {
535
+ log.error('[llm-api] Error in messages endpoint:', err);
536
+ if (!res.headersSent) {
537
+ res.status(500).json({ error: 'Internal server error' });
538
+ }
539
+ }
540
+ });
541
+ // ── Global routes (no entity_id — bills to actor_id from JWT) ────────────
542
+ router.post('/v1/threads', async (req, res) => {
543
+ try {
544
+ const userId = req.token?.user_id;
545
+ if (!userId) {
546
+ res.status(401).json({ error: 'Authentication required' });
547
+ return;
548
+ }
549
+ await handleCreateThread(req, res, userId);
550
+ }
551
+ catch (err) {
552
+ log.error('[llm-api] Error creating thread:', err);
553
+ if (!res.headersSent) {
554
+ res.status(500).json({ error: 'Internal server error' });
555
+ }
556
+ }
557
+ });
558
+ router.post('/v1/threads/:thread_id/messages', async (req, res) => {
559
+ try {
560
+ const userId = req.token?.user_id;
561
+ if (!userId) {
562
+ res.status(401).json({ error: 'Authentication required' });
563
+ return;
564
+ }
565
+ await handleSendMessage(req, res, userId);
566
+ }
567
+ catch (err) {
568
+ log.error('[llm-api] Error in messages endpoint:', err);
569
+ if (!res.headersSent) {
570
+ res.status(500).json({ error: 'Internal server error' });
571
+ }
572
+ }
573
+ });
574
+ return router;
575
+ }
package/esm/server.js CHANGED
@@ -27,6 +27,7 @@ import { createRequestLogger } from './middleware/observability/request-logger';
27
27
  import { createCaptchaMiddleware } from './middleware/captcha';
28
28
  import { parseCookieValue, SESSION_COOKIE_NAME } from './middleware/cookie';
29
29
  import { createUploadAuthenticateMiddleware, uploadRoute } from './middleware/upload';
30
+ import { createLlmApiRouter } from './middleware/llm-api';
30
31
  import { startDebugSampler } from './diagnostics/debug-sampler';
31
32
  const log = new Logger('server');
32
33
  /**
@@ -167,6 +168,9 @@ class Server {
167
168
  };
168
169
  app.use(csrfSetToken); // Set CSRF token cookie on all requests
169
170
  app.use('/graphql', csrfProtect); // Enforce CSRF on GraphQL mutations
171
+ // LLM Agent REST API — mounted before graphile so SSE streaming
172
+ // routes are handled without going through PostGraphile
173
+ app.use(createLlmApiRouter());
170
174
  app.use(graphile(effectiveOpts));
171
175
  app.use(flush);
172
176
  // Error handling - MUST be LAST
@@ -254,14 +254,21 @@ const buildPreset = (pool, schemas, anonRole, roleName, databaseSettings) => {
254
254
  if (req.token.access_level === 'read_only') {
255
255
  pgSettings['default_transaction_read_only'] = 'on';
256
256
  }
257
+ if (req.requestId) {
258
+ pgSettings['request.id'] = req.requestId;
259
+ }
257
260
  return { pgSettings };
258
261
  }
259
262
  }
263
+ const anonSettings = {
264
+ role: anonRole,
265
+ ...context,
266
+ };
267
+ if (req?.requestId) {
268
+ anonSettings['request.id'] = req.requestId;
269
+ }
260
270
  return {
261
- pgSettings: {
262
- role: anonRole,
263
- ...context,
264
- },
271
+ pgSettings: anonSettings,
265
272
  };
266
273
  },
267
274
  },
@@ -0,0 +1,24 @@
1
+ /**
2
+ * LLM API Router
3
+ *
4
+ * Express router providing REST streaming endpoints for AI agent conversations.
5
+ * Uses the agent tables (agent_thread, agent_message) discovered from the
6
+ * agent_chat_module config table at runtime.
7
+ *
8
+ * Hybrid architecture:
9
+ * - GraphQL handles CRUD (threads, messages, tasks) via PostGraphile
10
+ * - REST handles SSE streaming for chat completions (what GraphQL can't do)
11
+ *
12
+ * Routes (entity-scoped):
13
+ * POST /v1/orgs/:entity_id/threads → create thread
14
+ * POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message + stream response
15
+ *
16
+ * Routes (global — bills to actor_id from JWT):
17
+ * POST /v1/threads → create thread (entity_id = user_id)
18
+ * POST /v1/threads/:thread_id/messages → send message + stream response
19
+ *
20
+ * Auth: JWT from the auth middleware (req.token) → pg SET LOCAL context for RLS
21
+ * Metering: check_billing_quota → LLM call → record_usage with real token counts
22
+ */
23
+ import { Router } from 'express';
24
+ export declare function createLlmApiRouter(): Router;