agentic-server 0.4.1 → 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/discovery.js DELETED
@@ -1,130 +0,0 @@
1
- "use strict";
2
- /**
3
- * discovery — Runtime resolution of agent and billing module tables
4
- *
5
- * Queries metaschema_modules_public to find:
6
- * - agent_chat_module: thread/message/task table names
7
- * - billing_module: billing function names (check_quota, record_usage)
8
- * - inference_log_module: inference log table name
9
- *
10
- * Results are cached with a TTL to avoid per-request database hits.
11
- */
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.getAgentDiscovery = getAgentDiscovery;
14
- exports.getDatabaseConfig = getDatabaseConfig;
15
- exports.clearAgentCache = clearAgentCache;
16
- exports.clearConfigCache = clearConfigCache;
17
- const cache_1 = require("./cache");
18
- // ─── SQL ────────────────────────────────────────────────────────────────────
19
- const AGENT_DISCOVERY_SQL = `
20
- SELECT
21
- s.schema_name,
22
- acm.thread_table_name,
23
- acm.message_table_name,
24
- acm.task_table_name
25
- FROM metaschema_modules_public.agent_chat_module acm
26
- JOIN metaschema_public.schema s ON s.id = acm.schema_id
27
- LIMIT 1
28
- `;
29
- const SCHEMA_EXISTS_SQL = `
30
- SELECT 1 FROM information_schema.schemata WHERE schema_name = $1 LIMIT 1
31
- `;
32
- const BILLING_MODULE_SQL = `
33
- SELECT
34
- s.schema_name AS public_schema,
35
- ps.schema_name AS private_schema,
36
- bm.record_usage_function
37
- FROM metaschema_modules_public.billing_module bm
38
- JOIN metaschema_public.schema s ON bm.schema_id = s.id
39
- JOIN metaschema_public.schema ps ON bm.private_schema_id = ps.id
40
- WHERE bm.database_id = $1
41
- LIMIT 1
42
- `;
43
- const INFERENCE_LOG_MODULE_SQL = `
44
- SELECT
45
- s.schema_name AS schema,
46
- ilm.inference_log_table_name AS table_name
47
- FROM metaschema_modules_public.inference_log_module ilm
48
- JOIN metaschema_public.schema s ON ilm.schema_id = s.id
49
- WHERE ilm.database_id = $1
50
- LIMIT 1
51
- `;
52
- // ─── Caches ─────────────────────────────────────────────────────────────────
53
- const agentCache = new cache_1.TtlCache(60_000); // 1 minute
54
- const configCache = new cache_1.TtlCache(5 * 60_000); // 5 minutes
55
- // ─── Agent Discovery ────────────────────────────────────────────────────────
56
- async function getAgentDiscovery(pool, dbname) {
57
- const cached = agentCache.get(dbname);
58
- if (cached !== undefined)
59
- return cached;
60
- let discovery = null;
61
- try {
62
- const { rows } = await pool.query(AGENT_DISCOVERY_SQL);
63
- if (rows.length > 0) {
64
- const row = rows[0];
65
- const schemaName = row.schema_name;
66
- discovery = {
67
- thread: row.thread_table_name
68
- ? { schemaName, tableName: row.thread_table_name }
69
- : null,
70
- message: row.message_table_name
71
- ? { schemaName, tableName: row.message_table_name }
72
- : null,
73
- task: row.task_table_name
74
- ? { schemaName, tableName: row.task_table_name }
75
- : null,
76
- };
77
- }
78
- }
79
- catch {
80
- // Module not provisioned in this database
81
- }
82
- agentCache.set(dbname, discovery);
83
- return discovery;
84
- }
85
- // ─── Database Config (Billing + Inference Log) ──────────────────────────────
86
- async function getDatabaseConfig(pool, databaseId) {
87
- const cached = configCache.get(databaseId);
88
- if (cached !== undefined)
89
- return cached;
90
- let billing = null;
91
- let inferenceLog = null;
92
- try {
93
- const schemaCheck = await pool.query(SCHEMA_EXISTS_SQL, ['metaschema_modules_public']);
94
- if (schemaCheck.rows.length > 0) {
95
- const [billingResult, logResult] = await Promise.all([
96
- pool.query(BILLING_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
97
- pool.query(INFERENCE_LOG_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
98
- ]);
99
- const bRow = billingResult.rows[0];
100
- if (bRow?.record_usage_function) {
101
- billing = {
102
- publicSchema: bRow.public_schema,
103
- privateSchema: bRow.private_schema,
104
- recordUsageFunction: bRow.record_usage_function,
105
- checkBillingQuotaFunction: 'check_billing_quota',
106
- };
107
- }
108
- const lRow = logResult.rows[0];
109
- if (lRow?.schema && lRow?.table_name) {
110
- inferenceLog = {
111
- schema: lRow.schema,
112
- tableName: lRow.table_name,
113
- };
114
- }
115
- }
116
- }
117
- catch {
118
- // metaschema not provisioned
119
- }
120
- const entry = { billing, inferenceLog };
121
- configCache.set(databaseId, entry);
122
- return entry;
123
- }
124
- // ─── Cache Management ───────────────────────────────────────────────────────
125
- function clearAgentCache() {
126
- agentCache.clear();
127
- }
128
- function clearConfigCache() {
129
- configCache.clear();
130
- }
package/env.d.ts DELETED
@@ -1,21 +0,0 @@
1
- /**
2
- * env — LLM provider configuration from environment variables
3
- *
4
- * Environment variables:
5
- * EMBEDDER_PROVIDER - Embedding provider ('ollama')
6
- * EMBEDDER_MODEL - Embedding model (default: 'nomic-embed-text')
7
- * EMBEDDER_BASE_URL - Embedding provider URL (default: 'http://localhost:11434')
8
- * CHAT_PROVIDER - Chat provider ('ollama')
9
- * CHAT_MODEL - Chat model (default: 'llama3')
10
- * CHAT_BASE_URL - Chat provider URL (default: 'http://localhost:11434')
11
- */
12
- export interface ProviderConfig {
13
- provider: string;
14
- model: string;
15
- baseUrl: string;
16
- }
17
- export interface EnvOptions {
18
- embedding: ProviderConfig;
19
- chat: ProviderConfig;
20
- }
21
- export declare function getEnvOptions(): EnvOptions;
package/env.js DELETED
@@ -1,40 +0,0 @@
1
- "use strict";
2
- /**
3
- * env — LLM provider configuration from environment variables
4
- *
5
- * Environment variables:
6
- * EMBEDDER_PROVIDER - Embedding provider ('ollama')
7
- * EMBEDDER_MODEL - Embedding model (default: 'nomic-embed-text')
8
- * EMBEDDER_BASE_URL - Embedding provider URL (default: 'http://localhost:11434')
9
- * CHAT_PROVIDER - Chat provider ('ollama')
10
- * CHAT_MODEL - Chat model (default: 'llama3')
11
- * CHAT_BASE_URL - Chat provider URL (default: 'http://localhost:11434')
12
- */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.getEnvOptions = getEnvOptions;
15
- const DEFAULTS = {
16
- embedding: {
17
- provider: 'ollama',
18
- model: 'nomic-embed-text',
19
- baseUrl: 'http://localhost:11434',
20
- },
21
- chat: {
22
- provider: 'ollama',
23
- model: 'llama3',
24
- baseUrl: 'http://localhost:11434',
25
- },
26
- };
27
- function getEnvOptions() {
28
- return {
29
- embedding: {
30
- provider: process.env.EMBEDDER_PROVIDER ?? DEFAULTS.embedding.provider,
31
- model: process.env.EMBEDDER_MODEL ?? DEFAULTS.embedding.model,
32
- baseUrl: process.env.EMBEDDER_BASE_URL ?? DEFAULTS.embedding.baseUrl,
33
- },
34
- chat: {
35
- provider: process.env.CHAT_PROVIDER ?? DEFAULTS.chat.provider,
36
- model: process.env.CHAT_MODEL ?? DEFAULTS.chat.model,
37
- baseUrl: process.env.CHAT_BASE_URL ?? DEFAULTS.chat.baseUrl,
38
- },
39
- };
40
- }
package/esm/billing.js DELETED
@@ -1,55 +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 { Logger } from '@pgpmjs/logger';
8
- const log = new Logger('agentic-server:billing');
9
- // ─── Quota Check ────────────────────────────────────────────────────────────
10
- export async function checkQuota(ctx, billing, entityId, meterSlug) {
11
- try {
12
- return await ctx.withPgClient(async (client) => {
13
- const sql = `SELECT "${billing.privateSchema}"."${billing.checkBillingQuotaFunction}"($1, $2::uuid, $3) AS allowed`;
14
- const result = await client.query(sql, [meterSlug, entityId, 1]);
15
- return result.rows[0]?.allowed !== false;
16
- });
17
- }
18
- catch (e) {
19
- const message = e instanceof Error ? e.message : String(e);
20
- log.warn(`check_billing_quota failed (allowing): ${message}`);
21
- return true;
22
- }
23
- }
24
- // ─── Usage Recording ────────────────────────────────────────────────────────
25
- export async function recordUsage(ctx, billing, entityId, meterSlug, amount, metadata) {
26
- try {
27
- await ctx.withPgClient(async (client) => {
28
- const sql = `SELECT "${billing.privateSchema}"."${billing.recordUsageFunction}"($1, $2::uuid, $3, $4::jsonb)`;
29
- await client.query(sql, [meterSlug, entityId, amount, JSON.stringify(metadata)]);
30
- });
31
- }
32
- catch (e) {
33
- const message = e instanceof Error ? e.message : String(e);
34
- log.warn(`record_usage failed (non-fatal): ${message}`);
35
- }
36
- }
37
- export async function logInference(ctx, logConfig, entry) {
38
- try {
39
- await ctx.withPgClient(async (client) => {
40
- await client.query(`INSERT INTO "${logConfig.schema}"."${logConfig.tableName}"
41
- (entity_id, actor_id, model, provider, service, operation,
42
- input_tokens, output_tokens, total_tokens, latency_ms, status)
43
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
44
- entry.entityId, entry.actorId, entry.model,
45
- entry.provider, entry.service, entry.operation,
46
- entry.inputTokens, entry.outputTokens, entry.totalTokens,
47
- entry.latencyMs, entry.status,
48
- ]);
49
- });
50
- }
51
- catch (e) {
52
- const message = e instanceof Error ? e.message : String(e);
53
- log.warn(`inference log INSERT failed (non-fatal): ${message}`);
54
- }
55
- }
package/esm/cache.js DELETED
@@ -1,35 +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 class TtlCache {
8
- store = new Map();
9
- ttlMs;
10
- constructor(ttlMs) {
11
- this.ttlMs = ttlMs;
12
- }
13
- get(key) {
14
- const entry = this.store.get(key);
15
- if (!entry)
16
- return undefined;
17
- if (Date.now() > entry.expiresAt) {
18
- this.store.delete(key);
19
- return undefined;
20
- }
21
- return entry.value;
22
- }
23
- set(key, value) {
24
- this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs });
25
- }
26
- delete(key) {
27
- this.store.delete(key);
28
- }
29
- clear() {
30
- this.store.clear();
31
- }
32
- get size() {
33
- return this.store.size;
34
- }
35
- }
package/esm/discovery.js DELETED
@@ -1,124 +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 { TtlCache } from './cache';
12
- // ─── SQL ────────────────────────────────────────────────────────────────────
13
- const AGENT_DISCOVERY_SQL = `
14
- SELECT
15
- s.schema_name,
16
- acm.thread_table_name,
17
- acm.message_table_name,
18
- acm.task_table_name
19
- FROM metaschema_modules_public.agent_chat_module acm
20
- JOIN metaschema_public.schema s ON s.id = acm.schema_id
21
- LIMIT 1
22
- `;
23
- const SCHEMA_EXISTS_SQL = `
24
- SELECT 1 FROM information_schema.schemata WHERE schema_name = $1 LIMIT 1
25
- `;
26
- const BILLING_MODULE_SQL = `
27
- SELECT
28
- s.schema_name AS public_schema,
29
- ps.schema_name AS private_schema,
30
- bm.record_usage_function
31
- FROM metaschema_modules_public.billing_module bm
32
- JOIN metaschema_public.schema s ON bm.schema_id = s.id
33
- JOIN metaschema_public.schema ps ON bm.private_schema_id = ps.id
34
- WHERE bm.database_id = $1
35
- LIMIT 1
36
- `;
37
- const INFERENCE_LOG_MODULE_SQL = `
38
- SELECT
39
- s.schema_name AS schema,
40
- ilm.inference_log_table_name AS table_name
41
- FROM metaschema_modules_public.inference_log_module ilm
42
- JOIN metaschema_public.schema s ON ilm.schema_id = s.id
43
- WHERE ilm.database_id = $1
44
- LIMIT 1
45
- `;
46
- // ─── Caches ─────────────────────────────────────────────────────────────────
47
- const agentCache = new TtlCache(60_000); // 1 minute
48
- const configCache = new TtlCache(5 * 60_000); // 5 minutes
49
- // ─── Agent Discovery ────────────────────────────────────────────────────────
50
- export async function getAgentDiscovery(pool, dbname) {
51
- const cached = agentCache.get(dbname);
52
- if (cached !== undefined)
53
- return cached;
54
- let discovery = null;
55
- try {
56
- const { rows } = await pool.query(AGENT_DISCOVERY_SQL);
57
- if (rows.length > 0) {
58
- const row = rows[0];
59
- const schemaName = row.schema_name;
60
- discovery = {
61
- thread: row.thread_table_name
62
- ? { schemaName, tableName: row.thread_table_name }
63
- : null,
64
- message: row.message_table_name
65
- ? { schemaName, tableName: row.message_table_name }
66
- : null,
67
- task: row.task_table_name
68
- ? { schemaName, tableName: row.task_table_name }
69
- : null,
70
- };
71
- }
72
- }
73
- catch {
74
- // Module not provisioned in this database
75
- }
76
- agentCache.set(dbname, discovery);
77
- return discovery;
78
- }
79
- // ─── Database Config (Billing + Inference Log) ──────────────────────────────
80
- export async function getDatabaseConfig(pool, databaseId) {
81
- const cached = configCache.get(databaseId);
82
- if (cached !== undefined)
83
- return cached;
84
- let billing = null;
85
- let inferenceLog = null;
86
- try {
87
- const schemaCheck = await pool.query(SCHEMA_EXISTS_SQL, ['metaschema_modules_public']);
88
- if (schemaCheck.rows.length > 0) {
89
- const [billingResult, logResult] = await Promise.all([
90
- pool.query(BILLING_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
91
- pool.query(INFERENCE_LOG_MODULE_SQL, [databaseId]).catch(() => ({ rows: [] })),
92
- ]);
93
- const bRow = billingResult.rows[0];
94
- if (bRow?.record_usage_function) {
95
- billing = {
96
- publicSchema: bRow.public_schema,
97
- privateSchema: bRow.private_schema,
98
- recordUsageFunction: bRow.record_usage_function,
99
- checkBillingQuotaFunction: 'check_billing_quota',
100
- };
101
- }
102
- const lRow = logResult.rows[0];
103
- if (lRow?.schema && lRow?.table_name) {
104
- inferenceLog = {
105
- schema: lRow.schema,
106
- tableName: lRow.table_name,
107
- };
108
- }
109
- }
110
- }
111
- catch {
112
- // metaschema not provisioned
113
- }
114
- const entry = { billing, inferenceLog };
115
- configCache.set(databaseId, entry);
116
- return entry;
117
- }
118
- // ─── Cache Management ───────────────────────────────────────────────────────
119
- export function clearAgentCache() {
120
- agentCache.clear();
121
- }
122
- export function clearConfigCache() {
123
- configCache.clear();
124
- }
package/esm/env.js DELETED
@@ -1,37 +0,0 @@
1
- /**
2
- * env — LLM provider configuration from environment variables
3
- *
4
- * Environment variables:
5
- * EMBEDDER_PROVIDER - Embedding provider ('ollama')
6
- * EMBEDDER_MODEL - Embedding model (default: 'nomic-embed-text')
7
- * EMBEDDER_BASE_URL - Embedding provider URL (default: 'http://localhost:11434')
8
- * CHAT_PROVIDER - Chat provider ('ollama')
9
- * CHAT_MODEL - Chat model (default: 'llama3')
10
- * CHAT_BASE_URL - Chat provider URL (default: 'http://localhost:11434')
11
- */
12
- const DEFAULTS = {
13
- embedding: {
14
- provider: 'ollama',
15
- model: 'nomic-embed-text',
16
- baseUrl: 'http://localhost:11434',
17
- },
18
- chat: {
19
- provider: 'ollama',
20
- model: 'llama3',
21
- baseUrl: 'http://localhost:11434',
22
- },
23
- };
24
- export function getEnvOptions() {
25
- return {
26
- embedding: {
27
- provider: process.env.EMBEDDER_PROVIDER ?? DEFAULTS.embedding.provider,
28
- model: process.env.EMBEDDER_MODEL ?? DEFAULTS.embedding.model,
29
- baseUrl: process.env.EMBEDDER_BASE_URL ?? DEFAULTS.embedding.baseUrl,
30
- },
31
- chat: {
32
- provider: process.env.CHAT_PROVIDER ?? DEFAULTS.chat.provider,
33
- model: process.env.CHAT_MODEL ?? DEFAULTS.chat.model,
34
- baseUrl: process.env.CHAT_BASE_URL ?? DEFAULTS.chat.baseUrl,
35
- },
36
- };
37
- }