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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # agentic-server
2
+
3
+ Standalone Express LLM service — agent threads, chat streaming, billing metering, and inference logging via `@constructive-io/express-context`.
4
+
5
+ ## Overview
6
+
7
+ `agentic-server` is the Express-only equivalent of what `graphile-llm` does inside PostGraphile. It provides the same capabilities (agent threads, chat, embeddings, billing, inference logging) but as a standalone Express router that uses `@constructive-io/express-context` for tenant-scoped database access.
8
+
9
+ ## Usage
10
+
11
+ ```typescript
12
+ import express from 'express';
13
+ import { createContextMiddleware } from '@constructive-io/express-context';
14
+ import { createAgenticRouter } from 'agentic-server';
15
+
16
+ const app = express();
17
+
18
+ // Tenant context middleware (domain resolution, JWT, pgSettings, withPgClient)
19
+ app.use(createContextMiddleware());
20
+
21
+ // Mount the agentic router
22
+ app.use(createAgenticRouter());
23
+
24
+ app.listen(3001, () => {
25
+ console.log('agentic-server running on :3001');
26
+ });
27
+ ```
28
+
29
+ ## Endpoints
30
+
31
+ | Method | Path | Description |
32
+ |--------|------|-------------|
33
+ | POST | `/v1/threads` | Create a new conversation thread |
34
+ | POST | `/v1/threads/:thread_id/messages` | Send messages + get AI response (streaming SSE) |
35
+ | POST | `/v1/orgs/:entity_id/threads` | Create thread (entity-scoped) |
36
+ | POST | `/v1/orgs/:entity_id/threads/:thread_id/messages` | Send message (entity-scoped) |
37
+ | POST | `/v1/embed` | Generate embeddings |
38
+
39
+ ## Environment Variables
40
+
41
+ | Variable | Default | Description |
42
+ |----------|---------|-------------|
43
+ | `CHAT_PROVIDER` | `ollama` | Chat LLM provider |
44
+ | `CHAT_MODEL` | `llama3` | Default chat model |
45
+ | `CHAT_BASE_URL` | `http://localhost:11434` | Chat provider URL |
46
+ | `EMBEDDER_PROVIDER` | `ollama` | Embedding provider |
47
+ | `EMBEDDER_MODEL` | `nomic-embed-text` | Default embedding model |
48
+ | `EMBEDDER_BASE_URL` | `http://localhost:11434` | Embedding provider URL |
49
+
50
+ ## Features
51
+
52
+ - **Thread management**: Create and manage conversation threads with system prompts
53
+ - **Streaming chat**: SSE streaming responses (OpenAI-compatible format)
54
+ - **Batch chat**: Non-streaming JSON responses
55
+ - **Embeddings**: Generate vector embeddings via `/v1/embed`
56
+ - **Billing integration**: Automatic quota checks and usage recording (when billing module is provisioned)
57
+ - **Inference logging**: Automatic token usage logging (when inference_log module is provisioned)
58
+ - **RLS enforcement**: All database operations run within tenant-scoped RLS transactions
59
+
60
+ ## Architecture
61
+
62
+ ```
63
+ Cloud Function → POST /v1/threads/:id/messages → agentic-server
64
+ │
65
+ ┌───────────────────┼───────────────────┐
66
+ │ │ │
67
+ express-context OllamaAdapter Billing
68
+ (tenant DB context) (LLM provider) (quota + usage)
69
+ ```
70
+
71
+ The cloud function doesn't need to know about databases, billing, or LLM providers. It just POSTs `{ messages, model }` and gets back a streamed response.
72
+
73
+ ---
74
+
75
+ ## Education and Tutorials
76
+
77
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
78
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
79
+
80
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
81
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
82
+
83
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
84
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
85
+
86
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
87
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
88
+
89
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
90
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
91
+
92
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
93
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
94
+
95
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
96
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
97
+
98
+ ## Related Constructive Tooling
99
+
100
+ ### 📦 Package Management
101
+
102
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
103
+
104
+ ### 🧪 Testing
105
+
106
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
107
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
108
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
109
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
110
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
111
+
112
+ ### 🧠 Parsing & AST
113
+
114
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
115
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
116
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
117
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
118
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
119
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
120
+
121
+ ## Credits
122
+
123
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
124
+
125
+ ## Disclaimer
126
+
127
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
128
+
129
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/billing.d.ts ADDED
@@ -0,0 +1,24 @@
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 { ConstructiveContext } from '@constructive-io/express-context';
8
+ import type { BillingConfig, InferenceLogConfig } from './discovery';
9
+ export declare function checkQuota(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string): Promise<boolean>;
10
+ export declare function recordUsage(ctx: ConstructiveContext, billing: BillingConfig, entityId: string, meterSlug: string, amount: number, metadata: Record<string, unknown>): Promise<void>;
11
+ export interface InferenceLogEntry {
12
+ entityId: string;
13
+ actorId: string;
14
+ model: string;
15
+ provider: string;
16
+ service: string;
17
+ operation: string;
18
+ inputTokens: number;
19
+ outputTokens: number;
20
+ totalTokens: number;
21
+ latencyMs: number;
22
+ status: string;
23
+ }
24
+ export declare function logInference(ctx: ConstructiveContext, logConfig: InferenceLogConfig, entry: InferenceLogEntry): Promise<void>;
package/billing.js ADDED
@@ -0,0 +1,60 @@
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 ADDED
@@ -0,0 +1,16 @@
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 ADDED
@@ -0,0 +1,39 @@
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 ADDED
@@ -0,0 +1,38 @@
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;
package/discovery.js ADDED
@@ -0,0 +1,130 @@
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 ADDED
@@ -0,0 +1,21 @@
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 ADDED
@@ -0,0 +1,40 @@
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 ADDED
@@ -0,0 +1,55 @@
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 ADDED
@@ -0,0 +1,35 @@
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
+ }