agentic-server 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * agentic-server — Standalone Express LLM service
3
+ *
4
+ * Express-only equivalent of graphile-llm: agent threads, chat streaming,
5
+ * billing metering, and inference logging. Uses @constructive-io/express-context
6
+ * for tenant-scoped database access.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import express from 'express';
11
+ * import { createContextMiddleware } from '@constructive-io/express-context';
12
+ * import { createAgenticRouter } from 'agentic-server';
13
+ *
14
+ * const app = express();
15
+ * app.use(createContextMiddleware());
16
+ * app.use(createAgenticRouter());
17
+ * app.listen(3001);
18
+ * ```
19
+ */
20
+ export { createAgenticRouter } from './router';
21
+ export { getEnvOptions } from './env';
22
+ export type { EnvOptions, ProviderConfig } from './env';
23
+ export { getAgentDiscovery, getDatabaseConfig, clearAgentCache, clearConfigCache } from './discovery';
24
+ export type { AgentDiscovery, AgentTableInfo, BillingConfig, DatabaseConfig, InferenceLogConfig, } from './discovery';
25
+ export { checkQuota, recordUsage, logInference } from './billing';
26
+ export type { InferenceLogEntry } from './billing';
27
+ export { TtlCache } from './cache';
package/index.js ADDED
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ /**
3
+ * agentic-server — Standalone Express LLM service
4
+ *
5
+ * Express-only equivalent of graphile-llm: agent threads, chat streaming,
6
+ * billing metering, and inference logging. Uses @constructive-io/express-context
7
+ * for tenant-scoped database access.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import express from 'express';
12
+ * import { createContextMiddleware } from '@constructive-io/express-context';
13
+ * import { createAgenticRouter } from 'agentic-server';
14
+ *
15
+ * const app = express();
16
+ * app.use(createContextMiddleware());
17
+ * app.use(createAgenticRouter());
18
+ * app.listen(3001);
19
+ * ```
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.TtlCache = exports.logInference = exports.recordUsage = exports.checkQuota = exports.clearConfigCache = exports.clearAgentCache = exports.getDatabaseConfig = exports.getAgentDiscovery = exports.getEnvOptions = exports.createAgenticRouter = void 0;
23
+ var router_1 = require("./router");
24
+ Object.defineProperty(exports, "createAgenticRouter", { enumerable: true, get: function () { return router_1.createAgenticRouter; } });
25
+ var env_1 = require("./env");
26
+ Object.defineProperty(exports, "getEnvOptions", { enumerable: true, get: function () { return env_1.getEnvOptions; } });
27
+ var discovery_1 = require("./discovery");
28
+ Object.defineProperty(exports, "getAgentDiscovery", { enumerable: true, get: function () { return discovery_1.getAgentDiscovery; } });
29
+ Object.defineProperty(exports, "getDatabaseConfig", { enumerable: true, get: function () { return discovery_1.getDatabaseConfig; } });
30
+ Object.defineProperty(exports, "clearAgentCache", { enumerable: true, get: function () { return discovery_1.clearAgentCache; } });
31
+ Object.defineProperty(exports, "clearConfigCache", { enumerable: true, get: function () { return discovery_1.clearConfigCache; } });
32
+ var billing_1 = require("./billing");
33
+ Object.defineProperty(exports, "checkQuota", { enumerable: true, get: function () { return billing_1.checkQuota; } });
34
+ Object.defineProperty(exports, "recordUsage", { enumerable: true, get: function () { return billing_1.recordUsage; } });
35
+ Object.defineProperty(exports, "logInference", { enumerable: true, get: function () { return billing_1.logInference; } });
36
+ var cache_1 = require("./cache");
37
+ Object.defineProperty(exports, "TtlCache", { enumerable: true, get: function () { return cache_1.TtlCache; } });
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "agentic-server",
3
+ "version": "0.2.0",
4
+ "description": "Standalone Express LLM service — agent threads, chat streaming, billing metering, and inference logging via express-context",
5
+ "author": "Constructive <developers@constructive.io>",
6
+ "homepage": "https://github.com/constructive-io/constructive",
7
+ "license": "MIT",
8
+ "main": "index.js",
9
+ "module": "esm/index.js",
10
+ "types": "index.d.ts",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest --forceExit",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "dependencies": {
32
+ "@agentic-kit/ollama": "^2.0.0",
33
+ "@constructive-io/express-context": "^0.2.0",
34
+ "@pgpmjs/logger": "^2.11.0",
35
+ "pg": "^8.21.0",
36
+ "pg-cache": "^3.11.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/express": "^5.0.6",
40
+ "@types/node": "^22.19.11",
41
+ "@types/pg": "^8.20.0",
42
+ "express": "^5.2.1",
43
+ "makage": "^0.3.0"
44
+ },
45
+ "peerDependencies": {
46
+ "express": "^5.0.0"
47
+ },
48
+ "keywords": [
49
+ "agentic-kit",
50
+ "express",
51
+ "llm",
52
+ "ollama",
53
+ "streaming",
54
+ "billing",
55
+ "metering",
56
+ "constructive"
57
+ ],
58
+ "gitHead": "c0d04574f7719d92e67becb58d60791ae978c5f5"
59
+ }
package/router.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * router — Express router for the agentic-server
3
+ *
4
+ * Provides REST endpoints for AI agent conversations:
5
+ *
6
+ * POST /v1/threads → create thread
7
+ * POST /v1/threads/:thread_id/messages → send message + stream response
8
+ * POST /v1/orgs/:entity_id/threads → create thread (entity-scoped)
9
+ * POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message (entity-scoped)
10
+ * POST /v1/embed → generate embedding
11
+ *
12
+ * All routes require `req.constructive` (from @constructive-io/express-context).
13
+ * Billing (check_quota + record_usage) and inference logging are automatic
14
+ * when the billing/inference_log modules are provisioned.
15
+ */
16
+ import { Router } from 'express';
17
+ export declare function createAgenticRouter(): Router;
package/router.js ADDED
@@ -0,0 +1,539 @@
1
+ "use strict";
2
+ /**
3
+ * router — Express router for the agentic-server
4
+ *
5
+ * Provides REST endpoints for AI agent conversations:
6
+ *
7
+ * POST /v1/threads → create thread
8
+ * POST /v1/threads/:thread_id/messages → send message + stream response
9
+ * POST /v1/orgs/:entity_id/threads → create thread (entity-scoped)
10
+ * POST /v1/orgs/:entity_id/threads/:thread_id/messages → send message (entity-scoped)
11
+ * POST /v1/embed → generate embedding
12
+ *
13
+ * All routes require `req.constructive` (from @constructive-io/express-context).
14
+ * Billing (check_quota + record_usage) and inference logging are automatic
15
+ * when the billing/inference_log modules are provisioned.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || (function () {
34
+ var ownKeys = function(o) {
35
+ ownKeys = Object.getOwnPropertyNames || function (o) {
36
+ var ar = [];
37
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
+ return ar;
39
+ };
40
+ return ownKeys(o);
41
+ };
42
+ return function (mod) {
43
+ if (mod && mod.__esModule) return mod;
44
+ var result = {};
45
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
+ __setModuleDefault(result, mod);
47
+ return result;
48
+ };
49
+ })();
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.createAgenticRouter = createAgenticRouter;
52
+ const express_1 = __importStar(require("express"));
53
+ const logger_1 = require("@pgpmjs/logger");
54
+ const ollama_1 = require("@agentic-kit/ollama");
55
+ const billing_1 = require("./billing");
56
+ const discovery_1 = require("./discovery");
57
+ const env_1 = require("./env");
58
+ const log = new logger_1.Logger('agentic-server');
59
+ // ─── Helpers ────────────────────────────────────────────────────────────────
60
+ function resolveOllamaAdapter() {
61
+ const { chat } = (0, env_1.getEnvOptions)();
62
+ if (chat.provider === 'ollama') {
63
+ return {
64
+ adapter: new ollama_1.OllamaAdapter(chat.baseUrl),
65
+ model: chat.model,
66
+ baseUrl: chat.baseUrl,
67
+ };
68
+ }
69
+ return null;
70
+ }
71
+ function resolveEmbeddingAdapter() {
72
+ const { embedding } = (0, env_1.getEnvOptions)();
73
+ if (embedding.provider === 'ollama') {
74
+ return {
75
+ adapter: new ollama_1.OllamaAdapter(embedding.baseUrl),
76
+ model: embedding.model,
77
+ };
78
+ }
79
+ return null;
80
+ }
81
+ // ─── Route Handlers ─────────────────────────────────────────────────────────
82
+ async function handleCreateThread(req, res, entityId) {
83
+ const ctx = req.constructive;
84
+ if (!ctx?.userId) {
85
+ res.status(401).json({ error: 'Authentication required' });
86
+ return;
87
+ }
88
+ if (!ctx.api.dbname) {
89
+ res.status(400).json({ error: 'Database not resolved' });
90
+ return;
91
+ }
92
+ const discovery = await (0, discovery_1.getAgentDiscovery)(ctx.pool, ctx.api.dbname);
93
+ if (!discovery?.thread) {
94
+ res.status(404).json({ error: 'Agent module not provisioned for this database' });
95
+ return;
96
+ }
97
+ const body = req.body || {};
98
+ const { thread } = discovery;
99
+ const result = await ctx.withPgClient(async (client) => {
100
+ const { rows } = await client.query(`INSERT INTO "${thread.schemaName}"."${thread.tableName}"
101
+ (entity_id, owner_id, mode, model, system_prompt, title)
102
+ VALUES ($1, $2, $3, $4, $5, $6)
103
+ RETURNING id, mode, model, system_prompt, status, created_at`, [
104
+ entityId,
105
+ ctx.userId,
106
+ body.mode ?? 'ask',
107
+ body.model ?? null,
108
+ body.system_prompt ?? null,
109
+ body.title ?? null,
110
+ ]);
111
+ return rows[0];
112
+ });
113
+ res.status(201).json({
114
+ id: result.id,
115
+ mode: result.mode,
116
+ model: result.model,
117
+ system_prompt: result.system_prompt,
118
+ status: result.status,
119
+ created_at: result.created_at,
120
+ });
121
+ }
122
+ async function handleSendMessage(req, res, entityId) {
123
+ const ctx = req.constructive;
124
+ if (!ctx?.userId) {
125
+ res.status(401).json({ error: 'Authentication required' });
126
+ return;
127
+ }
128
+ if (!ctx.api.dbname) {
129
+ res.status(400).json({ error: 'Database not resolved' });
130
+ return;
131
+ }
132
+ const discovery = await (0, discovery_1.getAgentDiscovery)(ctx.pool, ctx.api.dbname);
133
+ if (!discovery?.thread || !discovery?.message) {
134
+ res.status(404).json({ error: 'Agent module not provisioned for this database' });
135
+ return;
136
+ }
137
+ const body = req.body || {};
138
+ if (!body.messages?.length) {
139
+ res.status(400).json({ error: 'messages[] is required and must not be empty' });
140
+ return;
141
+ }
142
+ const { thread, message: msgTable } = discovery;
143
+ const threadId = req.params.thread_id;
144
+ const userId = ctx.userId;
145
+ // Verify thread exists (RLS enforced)
146
+ const threadRow = await ctx.withPgClient(async (client) => {
147
+ const { rows } = await client.query(`SELECT id, mode, model, system_prompt, status
148
+ FROM "${thread.schemaName}"."${thread.tableName}"
149
+ WHERE id = $1`, [threadId]);
150
+ return rows[0];
151
+ });
152
+ if (!threadRow) {
153
+ res.status(404).json({ error: 'Thread not found' });
154
+ return;
155
+ }
156
+ // Resolve billing + inference log config
157
+ const dbConfig = ctx.databaseId
158
+ ? await (0, discovery_1.getDatabaseConfig)(ctx.pool, ctx.databaseId)
159
+ : { billing: null, inferenceLog: null };
160
+ const ollama = resolveOllamaAdapter();
161
+ if (!ollama) {
162
+ res.status(503).json({ error: 'No LLM provider configured' });
163
+ return;
164
+ }
165
+ const model = body.model ?? threadRow.model ?? ollama.model;
166
+ const meterSlug = model;
167
+ // Quota check
168
+ if (dbConfig.billing) {
169
+ const allowed = await (0, billing_1.checkQuota)(ctx, dbConfig.billing, entityId, meterSlug);
170
+ if (!allowed) {
171
+ res.status(429).json({
172
+ error: 'Token quota exceeded',
173
+ meter: meterSlug,
174
+ entity_id: entityId,
175
+ });
176
+ return;
177
+ }
178
+ }
179
+ // Persist user messages
180
+ await ctx.withPgClient(async (client) => {
181
+ for (const msg of body.messages) {
182
+ if (msg.role === 'user') {
183
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
184
+ (thread_id, owner_id, entity_id, author_role, parts)
185
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4)`, [threadId, userId, 'user', JSON.stringify([{ type: 'text', text: msg.content }])]);
186
+ }
187
+ }
188
+ });
189
+ // Load full thread history
190
+ const history = await ctx.withPgClient(async (client) => {
191
+ const { rows } = await client.query(`SELECT author_role, parts, created_at
192
+ FROM "${msgTable.schemaName}"."${msgTable.tableName}"
193
+ WHERE thread_id = $1
194
+ ORDER BY created_at ASC`, [threadId]);
195
+ return rows;
196
+ });
197
+ const llmMessages = [];
198
+ if (threadRow.system_prompt) {
199
+ llmMessages.push({ role: 'system', content: threadRow.system_prompt });
200
+ }
201
+ for (const row of history) {
202
+ const parts = Array.isArray(row.parts) ? row.parts : [];
203
+ const textContent = parts
204
+ .filter((p) => p.type === 'text')
205
+ .map((p) => p.text)
206
+ .join('');
207
+ if (textContent) {
208
+ llmMessages.push({
209
+ role: row.author_role === 'user' ? 'user' : 'assistant',
210
+ content: textContent,
211
+ });
212
+ }
213
+ }
214
+ const startTime = Date.now();
215
+ const shouldStream = body.stream !== false;
216
+ if (shouldStream) {
217
+ await handleStreamingResponse(req, res, {
218
+ ctx, ollama, model, llmMessages, body,
219
+ entityId, userId, threadId,
220
+ thread, msgTable, dbConfig, startTime, meterSlug,
221
+ });
222
+ }
223
+ else {
224
+ await handleBatchResponse(req, res, {
225
+ ctx, ollama, model, llmMessages, body,
226
+ entityId, userId, threadId,
227
+ thread, msgTable, dbConfig, startTime, meterSlug,
228
+ });
229
+ }
230
+ }
231
+ async function handleStreamingResponse(_req, res, mc) {
232
+ const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, thread, msgTable, dbConfig, startTime, meterSlug } = mc;
233
+ res.writeHead(200, {
234
+ 'Content-Type': 'text/event-stream',
235
+ 'Cache-Control': 'no-cache',
236
+ 'Connection': 'keep-alive',
237
+ 'X-Accel-Buffering': 'no',
238
+ });
239
+ const messageId = `msg_${Date.now()}`;
240
+ try {
241
+ const systemMsg = llmMessages.find(m => m.role === 'system');
242
+ const nonSystem = llmMessages.filter(m => m.role !== 'system');
243
+ const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
244
+ const context = {
245
+ systemPrompt: systemMsg?.content,
246
+ messages: nonSystem.map((m) => ({
247
+ role: m.role,
248
+ content: m.content,
249
+ timestamp: Date.now(),
250
+ })),
251
+ };
252
+ const stream = ollama.adapter.stream(modelDesc, context, {
253
+ temperature: body.temperature,
254
+ });
255
+ let streamedContent = '';
256
+ for await (const event of stream) {
257
+ if (event.type === 'text_delta') {
258
+ streamedContent += event.delta;
259
+ const sseEvent = {
260
+ id: messageId,
261
+ choices: [{
262
+ index: 0,
263
+ delta: { content: event.delta, role: 'assistant' },
264
+ finish_reason: null,
265
+ }],
266
+ model,
267
+ };
268
+ res.write(`data: ${JSON.stringify(sseEvent)}\n\n`);
269
+ }
270
+ }
271
+ const result = await stream.result();
272
+ const content = streamedContent;
273
+ const latencyMs = Date.now() - startTime;
274
+ const usage = {
275
+ input: result.usage.input,
276
+ output: result.usage.output,
277
+ reasoning: result.usage.reasoning,
278
+ cacheRead: result.usage.cacheRead,
279
+ cacheWrite: result.usage.cacheWrite,
280
+ totalTokens: result.usage.totalTokens,
281
+ };
282
+ res.write('data: [DONE]\n\n');
283
+ res.end();
284
+ // Persist assistant message (fire-and-forget)
285
+ if (content) {
286
+ ctx.withPgClient(async (client) => {
287
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
288
+ (thread_id, owner_id, entity_id, author_role, parts, model)
289
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
290
+ }).catch((err) => log.error('Failed to persist assistant message:', err));
291
+ }
292
+ // Record billing usage (fire-and-forget)
293
+ if (dbConfig.billing && usage.totalTokens > 0) {
294
+ (0, billing_1.recordUsage)(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
295
+ input_tokens: usage.input,
296
+ output_tokens: usage.output,
297
+ cache_read_tokens: usage.cacheRead,
298
+ cache_write_tokens: usage.cacheWrite,
299
+ model,
300
+ latency_ms: latencyMs,
301
+ stream: true,
302
+ }).catch(() => { });
303
+ }
304
+ // Inference log (fire-and-forget)
305
+ if (dbConfig.inferenceLog) {
306
+ (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
307
+ entityId, actorId: userId, model, provider: 'ollama',
308
+ service: 'llm', operation: 'chat',
309
+ inputTokens: usage.input, outputTokens: usage.output,
310
+ totalTokens: usage.totalTokens, latencyMs, status: 'ok',
311
+ }).catch(() => { });
312
+ }
313
+ }
314
+ catch (streamErr) {
315
+ log.error('Streaming error:', streamErr);
316
+ const errorEvent = { error: { message: streamErr.message, type: 'stream_error' } };
317
+ res.write(`data: ${JSON.stringify(errorEvent)}\n\n`);
318
+ res.write('data: [DONE]\n\n');
319
+ res.end();
320
+ }
321
+ }
322
+ async function handleBatchResponse(_req, res, mc) {
323
+ const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, thread, msgTable, dbConfig, startTime, meterSlug } = mc;
324
+ const systemMsg = llmMessages.find(m => m.role === 'system');
325
+ const nonSystem = llmMessages.filter(m => m.role !== 'system');
326
+ const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
327
+ const context = {
328
+ systemPrompt: systemMsg?.content,
329
+ messages: nonSystem.map((m) => ({
330
+ role: m.role,
331
+ content: m.content,
332
+ timestamp: Date.now(),
333
+ })),
334
+ };
335
+ const stream = ollama.adapter.stream(modelDesc, context, {
336
+ temperature: body.temperature,
337
+ });
338
+ const result = await stream.result();
339
+ const content = result.content
340
+ .filter((block) => block.type === 'text')
341
+ .map((block) => block.text)
342
+ .join('');
343
+ const latencyMs = Date.now() - startTime;
344
+ const usage = {
345
+ input: result.usage.input,
346
+ output: result.usage.output,
347
+ reasoning: result.usage.reasoning,
348
+ cacheRead: result.usage.cacheRead,
349
+ cacheWrite: result.usage.cacheWrite,
350
+ totalTokens: result.usage.totalTokens,
351
+ };
352
+ // Persist assistant message
353
+ await ctx.withPgClient(async (client) => {
354
+ await client.query(`INSERT INTO "${msgTable.schemaName}"."${msgTable.tableName}"
355
+ (thread_id, owner_id, entity_id, author_role, parts, model)
356
+ VALUES ($1, $2, (SELECT entity_id FROM "${thread.schemaName}"."${thread.tableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
357
+ });
358
+ // Record billing + inference log (fire-and-forget)
359
+ if (dbConfig.billing && usage.totalTokens > 0) {
360
+ (0, billing_1.recordUsage)(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
361
+ input_tokens: usage.input,
362
+ output_tokens: usage.output,
363
+ cache_read_tokens: usage.cacheRead,
364
+ cache_write_tokens: usage.cacheWrite,
365
+ model,
366
+ latency_ms: latencyMs,
367
+ stream: false,
368
+ }).catch(() => { });
369
+ }
370
+ if (dbConfig.inferenceLog) {
371
+ (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
372
+ entityId, actorId: userId, model, provider: 'ollama',
373
+ service: 'llm', operation: 'chat',
374
+ inputTokens: usage.input, outputTokens: usage.output,
375
+ totalTokens: usage.totalTokens, latencyMs, status: 'ok',
376
+ }).catch(() => { });
377
+ }
378
+ res.json({
379
+ id: `msg_${Date.now()}`,
380
+ choices: [{
381
+ index: 0,
382
+ message: { role: 'assistant', content },
383
+ finish_reason: 'stop',
384
+ }],
385
+ model,
386
+ usage: {
387
+ prompt_tokens: usage.input,
388
+ completion_tokens: usage.output,
389
+ total_tokens: usage.totalTokens,
390
+ },
391
+ });
392
+ }
393
+ // ─── Embedding Handler ──────────────────────────────────────────────────────
394
+ async function handleEmbed(req, res) {
395
+ const ctx = req.constructive;
396
+ if (!ctx?.userId) {
397
+ res.status(401).json({ error: 'Authentication required' });
398
+ return;
399
+ }
400
+ const body = req.body || {};
401
+ if (!body.input) {
402
+ res.status(400).json({ error: 'input is required' });
403
+ return;
404
+ }
405
+ const embedder = resolveEmbeddingAdapter();
406
+ if (!embedder) {
407
+ res.status(503).json({ error: 'No embedding provider configured' });
408
+ return;
409
+ }
410
+ const model = body.model ?? embedder.model;
411
+ const inputs = Array.isArray(body.input) ? body.input : [body.input];
412
+ const dbConfig = ctx.databaseId
413
+ ? await (0, discovery_1.getDatabaseConfig)(ctx.pool, ctx.databaseId)
414
+ : { billing: null, inferenceLog: null };
415
+ // Quota check
416
+ if (dbConfig.billing) {
417
+ const allowed = await (0, billing_1.checkQuota)(ctx, dbConfig.billing, ctx.userId, model);
418
+ if (!allowed) {
419
+ res.status(429).json({ error: 'Embedding quota exceeded', meter: model });
420
+ return;
421
+ }
422
+ }
423
+ const startTime = Date.now();
424
+ try {
425
+ const results = await Promise.all(inputs.map((text) => embedder.adapter.embed(text, model)));
426
+ const latencyMs = Date.now() - startTime;
427
+ const totalTokens = results.reduce((sum, r) => sum + r.promptTokens, 0);
428
+ // Record usage (fire-and-forget)
429
+ if (dbConfig.billing && totalTokens > 0) {
430
+ (0, billing_1.recordUsage)(ctx, dbConfig.billing, ctx.userId, model, totalTokens, {
431
+ input_tokens: totalTokens,
432
+ model,
433
+ latency_ms: latencyMs,
434
+ batch_size: inputs.length,
435
+ }).catch(() => { });
436
+ }
437
+ if (dbConfig.inferenceLog) {
438
+ (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
439
+ entityId: ctx.userId,
440
+ actorId: ctx.userId,
441
+ model,
442
+ provider: 'ollama',
443
+ service: 'embedding',
444
+ operation: 'embed',
445
+ inputTokens: totalTokens,
446
+ outputTokens: 0,
447
+ totalTokens,
448
+ latencyMs,
449
+ status: 'ok',
450
+ }).catch(() => { });
451
+ }
452
+ res.json({
453
+ object: 'list',
454
+ data: results.map((r, i) => ({
455
+ object: 'embedding',
456
+ index: i,
457
+ embedding: r.embedding,
458
+ })),
459
+ model,
460
+ usage: {
461
+ prompt_tokens: totalTokens,
462
+ total_tokens: totalTokens,
463
+ },
464
+ });
465
+ }
466
+ catch (err) {
467
+ log.error('Embedding error:', err);
468
+ res.status(500).json({ error: err.message ?? 'Embedding failed' });
469
+ }
470
+ }
471
+ // ─── Router Factory ─────────────────────────────────────────────────────────
472
+ function createAgenticRouter() {
473
+ const router = (0, express_1.Router)();
474
+ router.use(express_1.default.json());
475
+ // Entity-scoped routes
476
+ router.post('/v1/orgs/:entity_id/threads', async (req, res) => {
477
+ try {
478
+ await handleCreateThread(req, res, req.params.entity_id);
479
+ }
480
+ catch (err) {
481
+ log.error('Error creating thread:', err);
482
+ if (!res.headersSent)
483
+ res.status(500).json({ error: 'Internal server error' });
484
+ }
485
+ });
486
+ router.post('/v1/orgs/:entity_id/threads/:thread_id/messages', async (req, res) => {
487
+ try {
488
+ await handleSendMessage(req, res, req.params.entity_id);
489
+ }
490
+ catch (err) {
491
+ log.error('Error in messages endpoint:', err);
492
+ if (!res.headersSent)
493
+ res.status(500).json({ error: 'Internal server error' });
494
+ }
495
+ });
496
+ // Global routes (entity_id = user_id from JWT)
497
+ router.post('/v1/threads', async (req, res) => {
498
+ try {
499
+ const userId = req.constructive?.userId;
500
+ if (!userId) {
501
+ res.status(401).json({ error: 'Authentication required' });
502
+ return;
503
+ }
504
+ await handleCreateThread(req, res, userId);
505
+ }
506
+ catch (err) {
507
+ log.error('Error creating thread:', err);
508
+ if (!res.headersSent)
509
+ res.status(500).json({ error: 'Internal server error' });
510
+ }
511
+ });
512
+ router.post('/v1/threads/:thread_id/messages', async (req, res) => {
513
+ try {
514
+ const userId = req.constructive?.userId;
515
+ if (!userId) {
516
+ res.status(401).json({ error: 'Authentication required' });
517
+ return;
518
+ }
519
+ await handleSendMessage(req, res, userId);
520
+ }
521
+ catch (err) {
522
+ log.error('Error in messages endpoint:', err);
523
+ if (!res.headersSent)
524
+ res.status(500).json({ error: 'Internal server error' });
525
+ }
526
+ });
527
+ // Embedding endpoint
528
+ router.post('/v1/embed', async (req, res) => {
529
+ try {
530
+ await handleEmbed(req, res);
531
+ }
532
+ catch (err) {
533
+ log.error('Error in embed endpoint:', err);
534
+ if (!res.headersSent)
535
+ res.status(500).json({ error: 'Internal server error' });
536
+ }
537
+ });
538
+ return router;
539
+ }