agentic-server 0.4.0 → 0.5.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/router.js CHANGED
@@ -13,6 +13,10 @@
13
13
  * All routes require `req.constructive` (from @constructive-io/express-context).
14
14
  * Billing (check_quota + record_usage) and inference logging are automatic
15
15
  * when the billing/inference_log modules are provisioned.
16
+ *
17
+ * LLM provider config is resolved per-database via `ctx.useLlm()` from the
18
+ * llm_module table, falling back to env vars (EMBEDDER_*, CHAT_*) when the
19
+ * module is not provisioned.
16
20
  */
17
21
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
22
  if (k2 === undefined) k2 = k;
@@ -49,31 +53,26 @@ var __importStar = (this && this.__importStar) || (function () {
49
53
  })();
50
54
  Object.defineProperty(exports, "__esModule", { value: true });
51
55
  exports.createAgenticRouter = createAgenticRouter;
52
- const express_1 = __importStar(require("express"));
53
- const logger_1 = require("@pgpmjs/logger");
54
56
  const ollama_1 = require("@agentic-kit/ollama");
55
- const billing_1 = require("./billing");
56
- const env_1 = require("./env");
57
+ const logger_1 = require("@pgpmjs/logger");
58
+ const express_1 = __importStar(require("express"));
59
+ const llm_env_1 = require("@constructive-io/llm-env");
57
60
  const log = new logger_1.Logger('agentic-server');
58
- // ─── Helpers ────────────────────────────────────────────────────────────────
59
- function resolveOllamaAdapter() {
60
- const { chat } = (0, env_1.getEnvOptions)();
61
- if (chat.provider === 'ollama') {
62
- return {
63
- adapter: new ollama_1.OllamaAdapter(chat.baseUrl),
64
- model: chat.model,
65
- baseUrl: chat.baseUrl,
66
- };
61
+ function resolveChatAdapter(llm) {
62
+ const provider = llm?.chatProvider ?? (0, llm_env_1.getEnvOptions)().chat.provider;
63
+ const model = llm?.chatModel ?? (0, llm_env_1.getEnvOptions)().chat.model;
64
+ const baseUrl = llm?.chatBaseUrl ?? (0, llm_env_1.getEnvOptions)().chat.baseUrl;
65
+ if (provider === 'ollama') {
66
+ return { adapter: new ollama_1.OllamaAdapter(baseUrl), model, baseUrl, provider };
67
67
  }
68
68
  return null;
69
69
  }
70
- function resolveEmbeddingAdapter() {
71
- const { embedding } = (0, env_1.getEnvOptions)();
72
- if (embedding.provider === 'ollama') {
73
- return {
74
- adapter: new ollama_1.OllamaAdapter(embedding.baseUrl),
75
- model: embedding.model,
76
- };
70
+ function resolveEmbeddingAdapter(llm) {
71
+ const provider = llm?.embeddingProvider ?? (0, llm_env_1.getEnvOptions)().embedding.provider;
72
+ const model = llm?.embeddingModel ?? (0, llm_env_1.getEnvOptions)().embedding.model;
73
+ const baseUrl = llm?.embeddingBaseUrl ?? (0, llm_env_1.getEnvOptions)().embedding.baseUrl;
74
+ if (provider === 'ollama') {
75
+ return { adapter: new ollama_1.OllamaAdapter(baseUrl), model, provider };
77
76
  }
78
77
  return null;
79
78
  }
@@ -101,7 +100,7 @@ async function handleCreateThread(req, res, entityId) {
101
100
  body.mode ?? 'ask',
102
101
  body.model ?? null,
103
102
  body.system_prompt ?? null,
104
- body.title ?? null,
103
+ body.title ?? null
105
104
  ]);
106
105
  return rows[0];
107
106
  });
@@ -111,7 +110,7 @@ async function handleCreateThread(req, res, entityId) {
111
110
  model: result.model,
112
111
  system_prompt: result.system_prompt,
113
112
  status: result.status,
114
- created_at: result.created_at,
113
+ created_at: result.created_at
115
114
  });
116
115
  }
117
116
  async function handleSendMessage(req, res, entityId) {
@@ -144,27 +143,23 @@ async function handleSendMessage(req, res, entityId) {
144
143
  res.status(404).json({ error: 'Thread not found' });
145
144
  return;
146
145
  }
147
- // Resolve billing + inference log config via loaders
148
- const [billing, inferenceLog] = await Promise.all([
149
- ctx.useModule('billing'),
150
- ctx.useModule('inferenceLog'),
151
- ]);
152
- const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
153
- const ollama = resolveOllamaAdapter();
154
- if (!ollama) {
146
+ // Resolve shared billing client and LLM config (lazy, cached per request)
147
+ const [billing, llm] = await Promise.all([ctx.useBilling(), ctx.useLlm()]);
148
+ const chatAdapter = resolveChatAdapter(llm);
149
+ if (!chatAdapter) {
155
150
  res.status(503).json({ error: 'No LLM provider configured' });
156
151
  return;
157
152
  }
158
- const model = body.model ?? threadRow.model ?? ollama.model;
153
+ const model = body.model ?? threadRow.model ?? chatAdapter.model;
159
154
  const meterSlug = model;
160
155
  // Quota check
161
- if (dbConfig.billing) {
162
- const allowed = await (0, billing_1.checkQuota)(ctx, dbConfig.billing, entityId, meterSlug);
156
+ if (billing) {
157
+ const allowed = await billing.checkQuota(meterSlug);
163
158
  if (!allowed) {
164
159
  res.status(429).json({
165
160
  error: 'Token quota exceeded',
166
161
  meter: meterSlug,
167
- entity_id: entityId,
162
+ entity_id: entityId
168
163
  });
169
164
  return;
170
165
  }
@@ -200,7 +195,7 @@ async function handleSendMessage(req, res, entityId) {
200
195
  if (textContent) {
201
196
  llmMessages.push({
202
197
  role: row.author_role === 'user' ? 'user' : 'assistant',
203
- content: textContent,
198
+ content: textContent
204
199
  });
205
200
  }
206
201
  }
@@ -208,44 +203,44 @@ async function handleSendMessage(req, res, entityId) {
208
203
  const shouldStream = body.stream !== false;
209
204
  if (shouldStream) {
210
205
  await handleStreamingResponse(req, res, {
211
- ctx, ollama, model, llmMessages, body,
206
+ ctx, chatAdapter, model, llmMessages, body,
212
207
  entityId, userId, threadId,
213
208
  schemaName, threadTableName, messageTableName,
214
- dbConfig, startTime, meterSlug,
209
+ billing, startTime, meterSlug
215
210
  });
216
211
  }
217
212
  else {
218
213
  await handleBatchResponse(req, res, {
219
- ctx, ollama, model, llmMessages, body,
214
+ ctx, chatAdapter, model, llmMessages, body,
220
215
  entityId, userId, threadId,
221
216
  schemaName, threadTableName, messageTableName,
222
- dbConfig, startTime, meterSlug,
217
+ billing, startTime, meterSlug
223
218
  });
224
219
  }
225
220
  }
226
221
  async function handleStreamingResponse(_req, res, mc) {
227
- const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
222
+ const { ctx, chatAdapter, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, billing, startTime, meterSlug } = mc;
228
223
  res.writeHead(200, {
229
224
  'Content-Type': 'text/event-stream',
230
225
  'Cache-Control': 'no-cache',
231
- 'Connection': 'keep-alive',
232
- 'X-Accel-Buffering': 'no',
226
+ Connection: 'keep-alive',
227
+ 'X-Accel-Buffering': 'no'
233
228
  });
234
229
  const messageId = `msg_${Date.now()}`;
235
230
  try {
236
231
  const systemMsg = llmMessages.find(m => m.role === 'system');
237
232
  const nonSystem = llmMessages.filter(m => m.role !== 'system');
238
- const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
233
+ const modelDesc = chatAdapter.adapter.createModel(model, { maxOutputTokens: undefined });
239
234
  const context = {
240
235
  systemPrompt: systemMsg?.content,
241
236
  messages: nonSystem.map((m) => ({
242
237
  role: m.role,
243
238
  content: m.content,
244
- timestamp: Date.now(),
245
- })),
239
+ timestamp: Date.now()
240
+ }))
246
241
  };
247
- const stream = ollama.adapter.stream(modelDesc, context, {
248
- temperature: body.temperature,
242
+ const stream = chatAdapter.adapter.stream(modelDesc, context, {
243
+ temperature: body.temperature
249
244
  });
250
245
  let streamedContent = '';
251
246
  for await (const event of stream) {
@@ -256,9 +251,9 @@ async function handleStreamingResponse(_req, res, mc) {
256
251
  choices: [{
257
252
  index: 0,
258
253
  delta: { content: event.delta, role: 'assistant' },
259
- finish_reason: null,
254
+ finish_reason: null
260
255
  }],
261
- model,
256
+ model
262
257
  };
263
258
  res.write(`data: ${JSON.stringify(sseEvent)}\n\n`);
264
259
  }
@@ -272,7 +267,7 @@ async function handleStreamingResponse(_req, res, mc) {
272
267
  reasoning: result.usage.reasoning,
273
268
  cacheRead: result.usage.cacheRead,
274
269
  cacheWrite: result.usage.cacheWrite,
275
- totalTokens: result.usage.totalTokens,
270
+ totalTokens: result.usage.totalTokens
276
271
  };
277
272
  res.write('data: [DONE]\n\n');
278
273
  res.end();
@@ -284,25 +279,22 @@ async function handleStreamingResponse(_req, res, mc) {
284
279
  VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
285
280
  }).catch((err) => log.error('Failed to persist assistant message:', err));
286
281
  }
287
- // Record billing usage (fire-and-forget)
288
- if (dbConfig.billing && usage.totalTokens > 0) {
289
- (0, billing_1.recordUsage)(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
282
+ // Record billing usage + inference log (fire-and-forget)
283
+ if (billing && usage.totalTokens > 0) {
284
+ billing.recordUsage(meterSlug, usage.totalTokens, {
290
285
  input_tokens: usage.input,
291
286
  output_tokens: usage.output,
292
287
  cache_read_tokens: usage.cacheRead,
293
288
  cache_write_tokens: usage.cacheWrite,
294
289
  model,
295
290
  latency_ms: latencyMs,
296
- stream: true,
291
+ stream: true
297
292
  }).catch(() => { });
298
- }
299
- // Inference log (fire-and-forget)
300
- if (dbConfig.inferenceLog) {
301
- (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
302
- entityId, actorId: userId, model, provider: 'ollama',
293
+ billing.logInference({
294
+ entityId, actorId: userId, model, provider: chatAdapter.provider,
303
295
  service: 'llm', operation: 'chat',
304
296
  inputTokens: usage.input, outputTokens: usage.output,
305
- totalTokens: usage.totalTokens, latencyMs, status: 'ok',
297
+ totalTokens: usage.totalTokens, latencyMs, status: 'ok'
306
298
  }).catch(() => { });
307
299
  }
308
300
  }
@@ -315,20 +307,20 @@ async function handleStreamingResponse(_req, res, mc) {
315
307
  }
316
308
  }
317
309
  async function handleBatchResponse(_req, res, mc) {
318
- const { ctx, ollama, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, dbConfig, startTime, meterSlug } = mc;
310
+ const { ctx, chatAdapter, model, llmMessages, body, entityId, userId, threadId, schemaName, threadTableName, messageTableName, billing, startTime, meterSlug } = mc;
319
311
  const systemMsg = llmMessages.find(m => m.role === 'system');
320
312
  const nonSystem = llmMessages.filter(m => m.role !== 'system');
321
- const modelDesc = ollama.adapter.createModel(model, { maxOutputTokens: undefined });
313
+ const modelDesc = chatAdapter.adapter.createModel(model, { maxOutputTokens: undefined });
322
314
  const context = {
323
315
  systemPrompt: systemMsg?.content,
324
316
  messages: nonSystem.map((m) => ({
325
317
  role: m.role,
326
318
  content: m.content,
327
- timestamp: Date.now(),
328
- })),
319
+ timestamp: Date.now()
320
+ }))
329
321
  };
330
- const stream = ollama.adapter.stream(modelDesc, context, {
331
- temperature: body.temperature,
322
+ const stream = chatAdapter.adapter.stream(modelDesc, context, {
323
+ temperature: body.temperature
332
324
  });
333
325
  const result = await stream.result();
334
326
  const content = result.content
@@ -342,7 +334,7 @@ async function handleBatchResponse(_req, res, mc) {
342
334
  reasoning: result.usage.reasoning,
343
335
  cacheRead: result.usage.cacheRead,
344
336
  cacheWrite: result.usage.cacheWrite,
345
- totalTokens: result.usage.totalTokens,
337
+ totalTokens: result.usage.totalTokens
346
338
  };
347
339
  // Persist assistant message
348
340
  await ctx.withPgClient(async (client) => {
@@ -351,23 +343,21 @@ async function handleBatchResponse(_req, res, mc) {
351
343
  VALUES ($1, $2, (SELECT entity_id FROM "${schemaName}"."${threadTableName}" WHERE id = $1), $3, $4, $5)`, [threadId, userId, 'assistant', JSON.stringify([{ type: 'text', text: content }]), model]);
352
344
  });
353
345
  // Record billing + inference log (fire-and-forget)
354
- if (dbConfig.billing && usage.totalTokens > 0) {
355
- (0, billing_1.recordUsage)(ctx, dbConfig.billing, entityId, meterSlug, usage.totalTokens, {
346
+ if (billing && usage.totalTokens > 0) {
347
+ billing.recordUsage(meterSlug, usage.totalTokens, {
356
348
  input_tokens: usage.input,
357
349
  output_tokens: usage.output,
358
350
  cache_read_tokens: usage.cacheRead,
359
351
  cache_write_tokens: usage.cacheWrite,
360
352
  model,
361
353
  latency_ms: latencyMs,
362
- stream: false,
354
+ stream: false
363
355
  }).catch(() => { });
364
- }
365
- if (dbConfig.inferenceLog) {
366
- (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
367
- entityId, actorId: userId, model, provider: 'ollama',
356
+ billing.logInference({
357
+ entityId, actorId: userId, model, provider: chatAdapter.provider,
368
358
  service: 'llm', operation: 'chat',
369
359
  inputTokens: usage.input, outputTokens: usage.output,
370
- totalTokens: usage.totalTokens, latencyMs, status: 'ok',
360
+ totalTokens: usage.totalTokens, latencyMs, status: 'ok'
371
361
  }).catch(() => { });
372
362
  }
373
363
  res.json({
@@ -375,14 +365,14 @@ async function handleBatchResponse(_req, res, mc) {
375
365
  choices: [{
376
366
  index: 0,
377
367
  message: { role: 'assistant', content },
378
- finish_reason: 'stop',
368
+ finish_reason: 'stop'
379
369
  }],
380
370
  model,
381
371
  usage: {
382
372
  prompt_tokens: usage.input,
383
373
  completion_tokens: usage.output,
384
- total_tokens: usage.totalTokens,
385
- },
374
+ total_tokens: usage.totalTokens
375
+ }
386
376
  });
387
377
  }
388
378
  // ─── Embedding Handler ──────────────────────────────────────────────────────
@@ -397,22 +387,19 @@ async function handleEmbed(req, res) {
397
387
  res.status(400).json({ error: 'input is required' });
398
388
  return;
399
389
  }
400
- const embedder = resolveEmbeddingAdapter();
401
- if (!embedder) {
390
+ const llm = await ctx.useLlm();
391
+ const embedAdapter = resolveEmbeddingAdapter(llm);
392
+ if (!embedAdapter) {
402
393
  res.status(503).json({ error: 'No embedding provider configured' });
403
394
  return;
404
395
  }
405
- const model = body.model ?? embedder.model;
396
+ const model = body.model ?? embedAdapter.model;
406
397
  const inputs = Array.isArray(body.input) ? body.input : [body.input];
407
- // Resolve billing + inference log config via loaders
408
- const [billing, inferenceLog] = await Promise.all([
409
- ctx.useModule('billing'),
410
- ctx.useModule('inferenceLog'),
411
- ]);
412
- const dbConfig = { billing: billing ?? null, inferenceLog: inferenceLog ?? null };
398
+ // Resolve shared billing client
399
+ const billing = await ctx.useBilling();
413
400
  // Quota check
414
- if (dbConfig.billing) {
415
- const allowed = await (0, billing_1.checkQuota)(ctx, dbConfig.billing, ctx.userId, model);
401
+ if (billing) {
402
+ const allowed = await billing.checkQuota(model);
416
403
  if (!allowed) {
417
404
  res.status(429).json({ error: 'Embedding quota exceeded', meter: model });
418
405
  return;
@@ -420,31 +407,29 @@ async function handleEmbed(req, res) {
420
407
  }
421
408
  const startTime = Date.now();
422
409
  try {
423
- const results = await Promise.all(inputs.map((text) => embedder.adapter.embed(text, model)));
410
+ const results = await Promise.all(inputs.map((text) => embedAdapter.adapter.embed(text, model)));
424
411
  const latencyMs = Date.now() - startTime;
425
412
  const totalTokens = results.reduce((sum, r) => sum + r.promptTokens, 0);
426
- // Record usage (fire-and-forget)
427
- if (dbConfig.billing && totalTokens > 0) {
428
- (0, billing_1.recordUsage)(ctx, dbConfig.billing, ctx.userId, model, totalTokens, {
413
+ // Record usage + inference log (fire-and-forget)
414
+ if (billing && totalTokens > 0) {
415
+ billing.recordUsage(model, totalTokens, {
429
416
  input_tokens: totalTokens,
430
417
  model,
431
418
  latency_ms: latencyMs,
432
- batch_size: inputs.length,
419
+ batch_size: inputs.length
433
420
  }).catch(() => { });
434
- }
435
- if (dbConfig.inferenceLog) {
436
- (0, billing_1.logInference)(ctx, dbConfig.inferenceLog, {
421
+ billing.logInference({
437
422
  entityId: ctx.userId,
438
423
  actorId: ctx.userId,
439
424
  model,
440
- provider: 'ollama',
425
+ provider: embedAdapter.provider,
441
426
  service: 'embedding',
442
427
  operation: 'embed',
443
428
  inputTokens: totalTokens,
444
429
  outputTokens: 0,
445
430
  totalTokens,
446
431
  latencyMs,
447
- status: 'ok',
432
+ status: 'ok'
448
433
  }).catch(() => { });
449
434
  }
450
435
  res.json({
@@ -452,13 +437,13 @@ async function handleEmbed(req, res) {
452
437
  data: results.map((r, i) => ({
453
438
  object: 'embedding',
454
439
  index: i,
455
- embedding: r.embedding,
440
+ embedding: r.embedding
456
441
  })),
457
442
  model,
458
443
  usage: {
459
444
  prompt_tokens: totalTokens,
460
- total_tokens: totalTokens,
461
- },
445
+ total_tokens: totalTokens
446
+ }
462
447
  });
463
448
  }
464
449
  catch (err) {
package/billing.d.ts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * billing — Quota check and usage recording via tenant database
3
- *
4
- * Calls the billing functions discovered from billing_module.
5
- * Gracefully allows requests if billing is not provisioned or errors.
6
- */
7
- import type { BillingConfig, ConstructiveContext, InferenceLogConfig } from '@constructive-io/express-context';
8
- export declare function checkQuota(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string): Promise<boolean>;
9
- export declare function recordUsage(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string, amount: number, metadata: Record<string, unknown>): Promise<void>;
10
- export interface InferenceLogEntry {
11
- entityId: string;
12
- actorId: string;
13
- model: string;
14
- provider: string;
15
- service: string;
16
- operation: string;
17
- inputTokens: number;
18
- outputTokens: number;
19
- totalTokens: number;
20
- latencyMs: number;
21
- status: string;
22
- }
23
- export declare function logInference(ctx: ConstructiveContext, logConfig: InferenceLogConfig, entry: InferenceLogEntry): Promise<void>;
package/billing.js DELETED
@@ -1,60 +0,0 @@
1
- "use strict";
2
- /**
3
- * billing — Quota check and usage recording via tenant database
4
- *
5
- * Calls the billing functions discovered from billing_module.
6
- * Gracefully allows requests if billing is not provisioned or errors.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.checkQuota = checkQuota;
10
- exports.recordUsage = recordUsage;
11
- exports.logInference = logInference;
12
- const logger_1 = require("@pgpmjs/logger");
13
- const log = new logger_1.Logger('agentic-server:billing');
14
- // ─── Quota Check ────────────────────────────────────────────────────────────
15
- async function checkQuota(ctx, billing, entityId, meterSlug) {
16
- try {
17
- return await ctx.withPgClient(async (client) => {
18
- const sql = `SELECT "${billing.privateSchema}"."${billing.checkBillingQuotaFunction}"($1, $2::uuid, $3) AS allowed`;
19
- const result = await client.query(sql, [meterSlug, entityId, 1]);
20
- return result.rows[0]?.allowed !== false;
21
- });
22
- }
23
- catch (e) {
24
- const message = e instanceof Error ? e.message : String(e);
25
- log.warn(`check_billing_quota failed (allowing): ${message}`);
26
- return true;
27
- }
28
- }
29
- // ─── Usage Recording ────────────────────────────────────────────────────────
30
- async function recordUsage(ctx, billing, entityId, meterSlug, amount, metadata) {
31
- try {
32
- await ctx.withPgClient(async (client) => {
33
- const sql = `SELECT "${billing.privateSchema}"."${billing.recordUsageFunction}"($1, $2::uuid, $3, $4::jsonb)`;
34
- await client.query(sql, [meterSlug, entityId, amount, JSON.stringify(metadata)]);
35
- });
36
- }
37
- catch (e) {
38
- const message = e instanceof Error ? e.message : String(e);
39
- log.warn(`record_usage failed (non-fatal): ${message}`);
40
- }
41
- }
42
- async function logInference(ctx, logConfig, entry) {
43
- try {
44
- await ctx.withPgClient(async (client) => {
45
- await client.query(`INSERT INTO "${logConfig.schema}"."${logConfig.tableName}"
46
- (entity_id, actor_id, model, provider, service, operation,
47
- input_tokens, output_tokens, total_tokens, latency_ms, status)
48
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
49
- entry.entityId, entry.actorId, entry.model,
50
- entry.provider, entry.service, entry.operation,
51
- entry.inputTokens, entry.outputTokens, entry.totalTokens,
52
- entry.latencyMs, entry.status,
53
- ]);
54
- });
55
- }
56
- catch (e) {
57
- const message = e instanceof Error ? e.message : String(e);
58
- log.warn(`inference log INSERT failed (non-fatal): ${message}`);
59
- }
60
- }
package/cache.d.ts DELETED
@@ -1,16 +0,0 @@
1
- /**
2
- * cache — Simple TTL cache for module discovery results
3
- *
4
- * Avoids a dependency on graphile-cache by providing a minimal
5
- * Map + TTL implementation. Entries expire after the configured TTL.
6
- */
7
- export declare class TtlCache<T> {
8
- private store;
9
- private ttlMs;
10
- constructor(ttlMs: number);
11
- get(key: string): T | undefined;
12
- set(key: string, value: T): void;
13
- delete(key: string): void;
14
- clear(): void;
15
- get size(): number;
16
- }
package/cache.js DELETED
@@ -1,39 +0,0 @@
1
- "use strict";
2
- /**
3
- * cache — Simple TTL cache for module discovery results
4
- *
5
- * Avoids a dependency on graphile-cache by providing a minimal
6
- * Map + TTL implementation. Entries expire after the configured TTL.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.TtlCache = void 0;
10
- class TtlCache {
11
- store = new Map();
12
- ttlMs;
13
- constructor(ttlMs) {
14
- this.ttlMs = ttlMs;
15
- }
16
- get(key) {
17
- const entry = this.store.get(key);
18
- if (!entry)
19
- return undefined;
20
- if (Date.now() > entry.expiresAt) {
21
- this.store.delete(key);
22
- return undefined;
23
- }
24
- return entry.value;
25
- }
26
- set(key, value) {
27
- this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs });
28
- }
29
- delete(key) {
30
- this.store.delete(key);
31
- }
32
- clear() {
33
- this.store.clear();
34
- }
35
- get size() {
36
- return this.store.size;
37
- }
38
- }
39
- exports.TtlCache = TtlCache;
package/discovery.d.ts DELETED
@@ -1,38 +0,0 @@
1
- /**
2
- * discovery — Runtime resolution of agent and billing module tables
3
- *
4
- * Queries metaschema_modules_public to find:
5
- * - agent_chat_module: thread/message/task table names
6
- * - billing_module: billing function names (check_quota, record_usage)
7
- * - inference_log_module: inference log table name
8
- *
9
- * Results are cached with a TTL to avoid per-request database hits.
10
- */
11
- import type { Pool } from 'pg';
12
- export interface AgentTableInfo {
13
- schemaName: string;
14
- tableName: string;
15
- }
16
- export interface AgentDiscovery {
17
- thread: AgentTableInfo | null;
18
- message: AgentTableInfo | null;
19
- task: AgentTableInfo | null;
20
- }
21
- export interface BillingConfig {
22
- privateSchema: string;
23
- publicSchema: string;
24
- recordUsageFunction: string;
25
- checkBillingQuotaFunction: string;
26
- }
27
- export interface InferenceLogConfig {
28
- schema: string;
29
- tableName: string;
30
- }
31
- export interface DatabaseConfig {
32
- billing: BillingConfig | null;
33
- inferenceLog: InferenceLogConfig | null;
34
- }
35
- export declare function getAgentDiscovery(pool: Pool, dbname: string): Promise<AgentDiscovery | null>;
36
- export declare function getDatabaseConfig(pool: Pool, databaseId: string): Promise<DatabaseConfig>;
37
- export declare function clearAgentCache(): void;
38
- export declare function clearConfigCache(): void;