@dolfinhos/db-postgres 0.0.0-stage → 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dolfinsis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @dolfinhos/db-postgres
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Armazenamentos do Dolfinhos no Postgres: sessões, regras por empresa, auditoria, uso, base de conhecimento (busca de texto em português, sem depender de acento nem de extensão) e memória de fatos. Recebe qualquer cliente com `query(text, values)` no formato do `pg`.
4
+
5
+ ```bash
6
+ npm install @dolfinhos/db-postgres pg
7
+ ```
8
+
9
+ ```ts
10
+ import pg from 'pg';
11
+ import { createPostgresAdapter, createPostgresKnowledgeStore, createPostgresUsageStore } from '@dolfinhos/db-postgres';
12
+
13
+ const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
14
+ const memory = createPostgresAdapter({ client: pool, table: 'dolfinhos.sessions' });
15
+ const knowledge = createPostgresKnowledgeStore({ client: pool });
16
+ const usage = createPostgresUsageStore({ client: pool });
17
+ ```
18
+
19
+ Cada armazenamento tem `migrate()` (o módulo NestJS chama ao subir). Para rodar na sua ferramenta de migração, use `createSessionsTableSQL`, `createGovernanceTablesSQL`, `createUsageTableSQL` e `createKnowledgeTablesSQL`.
20
+
21
+ Documentação completa no [repositório do Dolfinhos Toolkit](https://github.com/dolfinsis/dolfinhos-toolkit). Licença MIT.
package/dist/index.cjs ADDED
@@ -0,0 +1,599 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createGovernanceTablesSQL: () => createGovernanceTablesSQL,
24
+ createKnowledgeTablesSQL: () => createKnowledgeTablesSQL,
25
+ createPostgresAdapter: () => createPostgresAdapter,
26
+ createPostgresAuditStore: () => createPostgresAuditStore,
27
+ createPostgresFactStore: () => createPostgresFactStore,
28
+ createPostgresKnowledgeStore: () => createPostgresKnowledgeStore,
29
+ createPostgresSettingsStore: () => createPostgresSettingsStore,
30
+ createPostgresUsageStore: () => createPostgresUsageStore,
31
+ createSessionsTableSQL: () => createSessionsTableSQL,
32
+ createUsageTableSQL: () => createUsageTableSQL
33
+ });
34
+ module.exports = __toCommonJS(index_exports);
35
+ var import_core3 = require("@dolfinhos/core");
36
+
37
+ // src/governance.ts
38
+ var import_core = require("@dolfinhos/core");
39
+ var IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
40
+ function assertSchema(schema) {
41
+ if (!IDENTIFIER.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
42
+ }
43
+ function createGovernanceTablesSQL(schema = "dolfinhos") {
44
+ assertSchema(schema);
45
+ return `
46
+ create schema if not exists ${schema};
47
+ create table if not exists ${schema}.settings (
48
+ tenant_id text primary key,
49
+ data jsonb not null,
50
+ updated_at timestamptz not null default now()
51
+ );
52
+ create table if not exists ${schema}.audit (
53
+ id text primary key,
54
+ tenant_id text,
55
+ at timestamptz not null,
56
+ actor jsonb,
57
+ channel text,
58
+ session_id text not null,
59
+ run_id text not null,
60
+ agent_id text not null,
61
+ tool_call_id text not null,
62
+ capability text not null,
63
+ kind text not null,
64
+ risk text not null,
65
+ input jsonb,
66
+ decision text not null,
67
+ rule text,
68
+ status text not null,
69
+ error text
70
+ );
71
+ alter table ${schema}.audit add column if not exists decided_by jsonb;
72
+ create index if not exists audit_tenant_at_idx on ${schema}.audit (tenant_id, at desc);
73
+ `.trim();
74
+ }
75
+ var json = (value) => typeof value === "string" ? JSON.parse(value) : value;
76
+ function createPostgresSettingsStore(options) {
77
+ const schema = options.schema ?? "dolfinhos";
78
+ assertSchema(schema);
79
+ const { client } = options;
80
+ const fromRow2 = (row) => ({ ...json(row.data), updatedAt: new Date(row.updated_at).toISOString() });
81
+ return {
82
+ async migrate() {
83
+ await client.query(createGovernanceTablesSQL(schema));
84
+ },
85
+ async get(tenantId) {
86
+ const { rows } = await client.query(`select data, updated_at from ${schema}.settings where tenant_id = $1`, [tenantId]);
87
+ return rows[0] ? fromRow2(rows[0]) : null;
88
+ },
89
+ async set(tenantId, settings) {
90
+ const { updatedAt: _ignored, ...data } = settings;
91
+ const { rows } = await client.query(
92
+ `insert into ${schema}.settings (tenant_id, data, updated_at) values ($1, $2::jsonb, now())
93
+ on conflict (tenant_id) do update set data = excluded.data, updated_at = now()
94
+ returning data, updated_at`,
95
+ [tenantId, JSON.stringify(data)]
96
+ );
97
+ return fromRow2(rows[0]);
98
+ }
99
+ };
100
+ }
101
+ function createPostgresAuditStore(options) {
102
+ const schema = options.schema ?? "dolfinhos";
103
+ assertSchema(schema);
104
+ const { client } = options;
105
+ return {
106
+ async migrate() {
107
+ await client.query(createGovernanceTablesSQL(schema));
108
+ },
109
+ async append(r) {
110
+ await client.query(
111
+ `insert into ${schema}.audit (id, tenant_id, at, actor, channel, session_id, run_id, agent_id, tool_call_id, capability, kind, risk, input, decision, rule, status, error, decided_by)
112
+ values ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18::jsonb)`,
113
+ [
114
+ r.id,
115
+ r.tenantId,
116
+ r.at,
117
+ r.actor ? JSON.stringify(r.actor) : null,
118
+ r.channel,
119
+ r.sessionId,
120
+ r.runId,
121
+ r.agentId,
122
+ r.toolCallId,
123
+ r.capability,
124
+ r.kind,
125
+ r.risk,
126
+ JSON.stringify(r.input ?? null),
127
+ r.decision,
128
+ r.rule ?? null,
129
+ r.status,
130
+ r.error ?? null,
131
+ r.decidedBy ? JSON.stringify(r.decidedBy) : null
132
+ ]
133
+ );
134
+ },
135
+ async list(q) {
136
+ const values = [];
137
+ const where = [];
138
+ const add = (column, op, value) => {
139
+ values.push(value);
140
+ where.push(`${column} ${op} $${values.length}`);
141
+ };
142
+ if (q.tenantId === null) where.push("tenant_id is null");
143
+ else add("tenant_id", "=", q.tenantId);
144
+ if (q.sessionId) add("session_id", "=", q.sessionId);
145
+ if (q.capability) add("capability", "=", q.capability);
146
+ if (q.before) add("at", "<", q.before);
147
+ values.push((0, import_core.auditLimit)(q.limit));
148
+ const { rows } = await client.query(`select * from ${schema}.audit where ${where.join(" and ")} order by at desc limit $${values.length}`, values);
149
+ return rows.map(
150
+ (row) => ({
151
+ id: row.id,
152
+ tenantId: row.tenant_id,
153
+ at: new Date(row.at).toISOString(),
154
+ actor: json(row.actor),
155
+ channel: row.channel,
156
+ sessionId: row.session_id,
157
+ runId: row.run_id,
158
+ agentId: row.agent_id,
159
+ toolCallId: row.tool_call_id,
160
+ capability: row.capability,
161
+ kind: row.kind,
162
+ risk: row.risk,
163
+ input: json(row.input),
164
+ decision: row.decision,
165
+ ...row.rule ? { rule: row.rule } : {},
166
+ status: row.status,
167
+ ...row.error ? { error: row.error } : {},
168
+ ...row.decided_by ? { decidedBy: json(row.decided_by) } : {}
169
+ })
170
+ );
171
+ }
172
+ };
173
+ }
174
+
175
+ // src/usage.ts
176
+ var IDENTIFIER2 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
177
+ function createUsageTableSQL(schema = "dolfinhos") {
178
+ if (!IDENTIFIER2.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
179
+ return `
180
+ create schema if not exists ${schema};
181
+ create table if not exists ${schema}.usage (
182
+ id text primary key,
183
+ tenant_id text,
184
+ at timestamptz not null,
185
+ session_id text not null,
186
+ run_id text not null,
187
+ pod text not null,
188
+ channel text,
189
+ actor jsonb,
190
+ model text not null,
191
+ calls integer not null,
192
+ input_tokens integer not null,
193
+ cached_input_tokens integer not null,
194
+ output_tokens integer not null,
195
+ cost double precision
196
+ );
197
+ create index if not exists usage_tenant_at_idx on ${schema}.usage (tenant_id, at);
198
+ `.trim();
199
+ }
200
+ var totals = (row) => ({
201
+ runs: Number(row.runs),
202
+ calls: Number(row.calls),
203
+ inputTokens: Number(row.input_tokens),
204
+ cachedInputTokens: Number(row.cached_input_tokens),
205
+ outputTokens: Number(row.output_tokens),
206
+ cost: Number(row.cost),
207
+ unpricedCalls: Number(row.unpriced_calls)
208
+ });
209
+ function createPostgresUsageStore(options) {
210
+ const schema = options.schema ?? "dolfinhos";
211
+ if (!IDENTIFIER2.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
212
+ const { client } = options;
213
+ const aggregates = `count(distinct run_id) runs, coalesce(sum(calls), 0) calls, coalesce(sum(input_tokens), 0) input_tokens,
214
+ coalesce(sum(cached_input_tokens), 0) cached_input_tokens, coalesce(sum(output_tokens), 0) output_tokens,
215
+ coalesce(sum(cost), 0) cost, coalesce(sum(calls) filter (where cost is null), 0) unpriced_calls`;
216
+ return {
217
+ async migrate() {
218
+ await client.query(createUsageTableSQL(schema));
219
+ },
220
+ async append(records) {
221
+ for (const r of records) {
222
+ await client.query(
223
+ `insert into ${schema}.usage (id, tenant_id, at, session_id, run_id, pod, channel, actor, model, calls, input_tokens, cached_input_tokens, output_tokens, cost)
224
+ values ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14)`,
225
+ [r.id, r.tenantId, r.at, r.sessionId, r.runId, r.pod, r.channel, r.actor ? JSON.stringify(r.actor) : null, r.model, r.calls, r.inputTokens, r.cachedInputTokens, r.outputTokens, r.cost]
226
+ );
227
+ }
228
+ },
229
+ async totalCost(q) {
230
+ const tenant = q.tenantId === null ? "tenant_id is null" : "tenant_id = $3";
231
+ const values = q.tenantId === null ? [q.from, q.to] : [q.from, q.to, q.tenantId];
232
+ const { rows } = await client.query(`select coalesce(sum(cost), 0) as cost from ${schema}.usage where ${tenant} and at >= $1 and at < $2`, values);
233
+ return Number(rows[0]?.cost ?? 0);
234
+ },
235
+ async summary(q) {
236
+ const tenant = q.tenantId === null ? "tenant_id is null" : "tenant_id = $3";
237
+ const values = q.tenantId === null ? [q.from, q.to] : [q.from, q.to, q.tenantId];
238
+ const where = `where ${tenant} and at >= $1 and at < $2`;
239
+ const by = (expr) => client.query(`select ${expr} as key, ${aggregates} from ${schema}.usage ${where} group by 1`, values);
240
+ const [total, day, model, channel] = await Promise.all([
241
+ client.query(`select ${aggregates} from ${schema}.usage ${where}`, values),
242
+ by(`to_char(at at time zone 'UTC', 'YYYY-MM-DD')`),
243
+ by("model"),
244
+ by(`coalesce(channel, 'app')`)
245
+ ]);
246
+ const sorted = (list) => list.sort((a, b) => b.cost - a.cost || b.calls - a.calls);
247
+ return {
248
+ total: totals(total.rows[0] ?? {}),
249
+ byDay: day.rows.map((r) => ({ ...totals(r), day: r.key })).sort((a, b) => a.day.localeCompare(b.day)),
250
+ byModel: sorted(model.rows.map((r) => ({ ...totals(r), model: r.key }))),
251
+ byChannel: sorted(channel.rows.map((r) => ({ ...totals(r), channel: r.key })))
252
+ };
253
+ }
254
+ };
255
+ }
256
+
257
+ // src/knowledge.ts
258
+ var import_core2 = require("@dolfinhos/core");
259
+ var IDENTIFIER3 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
260
+ var schemaOf = (options) => {
261
+ const schema = options.schema ?? "dolfinhos";
262
+ if (!IDENTIFIER3.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
263
+ return schema;
264
+ };
265
+ var tenantKey = (tenantId) => tenantId ?? "";
266
+ var json2 = (value) => typeof value === "string" ? JSON.parse(value) : value;
267
+ function createKnowledgeTablesSQL(schema = "dolfinhos") {
268
+ if (!IDENTIFIER3.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
269
+ return `
270
+ create schema if not exists ${schema};
271
+ create table if not exists ${schema}.knowledge_docs (
272
+ tenant_key text not null,
273
+ id text not null,
274
+ tenant_id text,
275
+ title text not null,
276
+ content text not null,
277
+ audience text not null,
278
+ tags jsonb not null default '[]'::jsonb,
279
+ updated_at timestamptz not null default now(),
280
+ updated_by text,
281
+ primary key (tenant_key, id)
282
+ );
283
+ create table if not exists ${schema}.knowledge_chunks (
284
+ tenant_key text not null,
285
+ doc_id text not null,
286
+ idx integer not null,
287
+ text text not null,
288
+ search tsvector not null
289
+ );
290
+ create unique index if not exists knowledge_chunks_key on ${schema}.knowledge_chunks (tenant_key, doc_id, idx);
291
+ create index if not exists knowledge_chunks_search_idx on ${schema}.knowledge_chunks using gin (search);
292
+ create table if not exists ${schema}.facts (
293
+ id text primary key,
294
+ tenant_key text not null,
295
+ tenant_id text,
296
+ subject_type text not null,
297
+ subject_id text not null,
298
+ subject_label text,
299
+ text text not null,
300
+ created_at timestamptz not null default now(),
301
+ created_by jsonb
302
+ );
303
+ create index if not exists facts_subject_idx on ${schema}.facts (tenant_key, subject_type, subject_id, created_at desc);
304
+ `.trim();
305
+ }
306
+ var docFromRow = (row) => ({
307
+ id: row.id,
308
+ tenantId: row.tenant_id,
309
+ title: row.title,
310
+ content: row.content,
311
+ audience: row.audience,
312
+ tags: json2(row.tags) ?? [],
313
+ updatedAt: new Date(row.updated_at).toISOString(),
314
+ ...row.updated_by ? { updatedBy: row.updated_by } : {}
315
+ });
316
+ function createPostgresKnowledgeStore(options) {
317
+ const schema = schemaOf(options);
318
+ const { client } = options;
319
+ return {
320
+ async migrate() {
321
+ await client.query(createKnowledgeTablesSQL(schema));
322
+ },
323
+ async list(tenantId) {
324
+ const { rows } = await client.query(`select * from ${schema}.knowledge_docs where tenant_key = $1 order by title limit 1000`, [tenantKey(tenantId)]);
325
+ return rows.map(docFromRow);
326
+ },
327
+ async get(tenantId, id) {
328
+ const { rows } = await client.query(`select * from ${schema}.knowledge_docs where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
329
+ return rows[0] ? docFromRow(rows[0]) : null;
330
+ },
331
+ async save(doc) {
332
+ const chunks = (0, import_core2.chunkText)(doc.content);
333
+ const { rows } = await client.query(
334
+ `with doc as (
335
+ insert into ${schema}.knowledge_docs (tenant_key, id, tenant_id, title, content, audience, tags, updated_at, updated_by)
336
+ values ($1, $2, $3, $4, $5, $6, $7::jsonb, now(), $8)
337
+ on conflict (tenant_key, id) do update set title = excluded.title, content = excluded.content, audience = excluded.audience,
338
+ tags = excluded.tags, updated_at = now(), updated_by = excluded.updated_by
339
+ returning *
340
+ ), extra as (
341
+ -- Trechos al\xE9m do novo tamanho saem; os outros s\xE3o sobrescritos pela posi\xE7\xE3o. Duas grava\xE7\xF5es
342
+ -- ao mesmo tempo esperam uma pela outra em cada trecho, e a \xFAltima vence inteira.
343
+ delete from ${schema}.knowledge_chunks where tenant_key = $1 and doc_id = $2 and idx >= cardinality($9::text[])
344
+ ), fresh as (
345
+ insert into ${schema}.knowledge_chunks (tenant_key, doc_id, idx, text, search)
346
+ select $1, $2, c.idx - 1, c.text, to_tsvector('portuguese', c.norm)
347
+ from unnest($9::text[], $10::text[]) with ordinality as c(text, norm, idx)
348
+ on conflict (tenant_key, doc_id, idx) do update set text = excluded.text, search = excluded.search
349
+ )
350
+ select * from doc`,
351
+ [
352
+ tenantKey(doc.tenantId),
353
+ doc.id,
354
+ doc.tenantId,
355
+ doc.title,
356
+ doc.content,
357
+ doc.audience,
358
+ JSON.stringify(doc.tags),
359
+ doc.updatedBy ?? null,
360
+ chunks,
361
+ chunks.map((c) => (0, import_core2.normalizeText)(`${doc.title}
362
+ ${c}`))
363
+ ]
364
+ );
365
+ return docFromRow(rows[0]);
366
+ },
367
+ async remove(tenantId, id) {
368
+ await client.query(
369
+ `with gone as (delete from ${schema}.knowledge_chunks where tenant_key = $1 and doc_id = $2)
370
+ delete from ${schema}.knowledge_docs where tenant_key = $1 and id = $2`,
371
+ [tenantKey(tenantId), id]
372
+ );
373
+ },
374
+ async search({ tenantId, query, audience, limit = 4 }) {
375
+ const terms = (0, import_core2.searchTerms)(query);
376
+ if (!terms.length) return [];
377
+ const tsquery = terms.map((t) => `${t}:*`).join(" | ");
378
+ const { rows } = await client.query(
379
+ `select * from (
380
+ select distinct on (c.doc_id) c.doc_id, d.title, c.text, ts_rank_cd(c.search, q) as score
381
+ from ${schema}.knowledge_chunks c
382
+ join ${schema}.knowledge_docs d on d.tenant_key = c.tenant_key and d.id = c.doc_id,
383
+ to_tsquery('portuguese', $2) q
384
+ where c.tenant_key = $1 and c.search @@ q and ($3 = 'internal' or d.audience = 'all')
385
+ order by c.doc_id, score desc
386
+ ) best order by score desc limit $4`,
387
+ [tenantKey(tenantId), tsquery, audience, Math.min(Math.max(limit, 1), 20)]
388
+ );
389
+ return rows.map((r) => ({ docId: r.doc_id, title: r.title, excerpt: r.text, score: Number(r.score) }));
390
+ }
391
+ };
392
+ }
393
+ var factFromRow = (row) => ({
394
+ id: row.id,
395
+ tenantId: row.tenant_id,
396
+ subject: { type: row.subject_type, id: row.subject_id, ...row.subject_label ? { label: row.subject_label } : {} },
397
+ text: row.text,
398
+ createdAt: new Date(row.created_at).toISOString(),
399
+ createdBy: json2(row.created_by) ?? null
400
+ });
401
+ function createPostgresFactStore(options) {
402
+ const schema = schemaOf(options);
403
+ const { client } = options;
404
+ return {
405
+ async migrate() {
406
+ await client.query(createKnowledgeTablesSQL(schema));
407
+ },
408
+ async list({ tenantId, subject, limit = import_core2.MAX_FACTS_PER_SUBJECT }) {
409
+ const { rows } = await client.query(
410
+ `select * from ${schema}.facts where tenant_key = $1 and subject_type = $2 and subject_id = $3 order by created_at desc limit $4`,
411
+ [tenantKey(tenantId), subject.type, subject.id, Math.min(Math.max(limit, 1), import_core2.MAX_FACTS_PER_SUBJECT)]
412
+ );
413
+ return rows.map(factFromRow);
414
+ },
415
+ async subjects({ tenantId, type, limit = 200 }) {
416
+ const { rows } = await client.query(
417
+ `select subject_type, subject_id, (array_agg(subject_label order by created_at desc))[1] as label, count(*) as count, max(created_at) as last_at
418
+ from ${schema}.facts where tenant_key = $1 and ($2::text is null or subject_type = $2)
419
+ group by 1, 2 order by last_at desc limit $3`,
420
+ [tenantKey(tenantId), type ?? null, Math.min(Math.max(limit, 1), 1e3)]
421
+ );
422
+ return rows.map((r) => ({
423
+ type: r.subject_type,
424
+ id: r.subject_id,
425
+ ...r.label ? { label: r.label } : {},
426
+ count: Number(r.count),
427
+ lastAt: new Date(r.last_at).toISOString()
428
+ }));
429
+ },
430
+ async get(tenantId, id) {
431
+ const { rows } = await client.query(`select * from ${schema}.facts where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
432
+ return rows[0] ? factFromRow(rows[0]) : null;
433
+ },
434
+ async add(fact) {
435
+ const { rows } = await client.query(
436
+ `with fresh as (
437
+ insert into ${schema}.facts (id, tenant_key, tenant_id, subject_type, subject_id, subject_label, text, created_at, created_by)
438
+ values ($1, $2, $3, $4, $5, $6, $7, now(), $8::jsonb) returning *
439
+ ), trimmed as (
440
+ delete from ${schema}.facts where id in (
441
+ select id from ${schema}.facts where tenant_key = $2 and subject_type = $4 and subject_id = $5
442
+ order by created_at desc offset $9
443
+ )
444
+ )
445
+ select * from fresh`,
446
+ [
447
+ crypto.randomUUID(),
448
+ tenantKey(fact.tenantId),
449
+ fact.tenantId,
450
+ fact.subject.type,
451
+ fact.subject.id,
452
+ fact.subject.label ?? null,
453
+ fact.text,
454
+ fact.createdBy ? JSON.stringify(fact.createdBy) : null,
455
+ import_core2.MAX_FACTS_PER_SUBJECT - 1
456
+ ]
457
+ );
458
+ return factFromRow(rows[0]);
459
+ },
460
+ async remove(tenantId, id) {
461
+ await client.query(`delete from ${schema}.facts where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
462
+ }
463
+ };
464
+ }
465
+
466
+ // src/index.ts
467
+ var IDENTIFIER4 = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?$/;
468
+ function createSessionsTableSQL(table = "dolfinhos_sessions") {
469
+ assertIdentifier(table);
470
+ const index = `${table.replace(".", "_")}_owner_idx`;
471
+ const pendingIndex = `${table.replace(".", "_")}_pending_idx`;
472
+ const schema = table.includes(".") ? `create schema if not exists ${table.split(".")[0]};
473
+ ` : "";
474
+ return `
475
+ ${schema}create table if not exists ${table} (
476
+ id text primary key,
477
+ tenant_id text,
478
+ user_id text,
479
+ active_agent_id text not null,
480
+ messages jsonb not null default '[]'::jsonb,
481
+ pending jsonb,
482
+ agents jsonb,
483
+ plan jsonb,
484
+ pod text,
485
+ actor jsonb,
486
+ channel text,
487
+ meta jsonb,
488
+ running_until timestamptz,
489
+ version integer not null,
490
+ created_at timestamptz not null default now(),
491
+ updated_at timestamptz not null default now()
492
+ );
493
+ alter table ${table} add column if not exists running_until timestamptz;
494
+ alter table ${table} add column if not exists agents jsonb;
495
+ alter table ${table} add column if not exists plan jsonb;
496
+ alter table ${table} add column if not exists pod text;
497
+ alter table ${table} add column if not exists actor jsonb;
498
+ alter table ${table} add column if not exists channel text;
499
+ alter table ${table} add column if not exists meta jsonb;
500
+ create index if not exists ${index.split(".").pop()} on ${table} (tenant_id, user_id, updated_at desc);
501
+ create index if not exists ${pendingIndex.split(".").pop()} on ${table} (tenant_id, updated_at desc) where pending is not null;
502
+ `.trim();
503
+ }
504
+ function createPostgresAdapter(options) {
505
+ const { client } = options;
506
+ const table = options.table ?? "dolfinhos_sessions";
507
+ assertIdentifier(table);
508
+ return {
509
+ async migrate() {
510
+ await client.query(createSessionsTableSQL(table));
511
+ },
512
+ async load(sessionId) {
513
+ const { rows } = await client.query(`select * from ${table} where id = $1`, [sessionId]);
514
+ return rows[0] ? fromRow(rows[0]) : null;
515
+ },
516
+ async save(state, expectedVersion) {
517
+ const values = [
518
+ state.id,
519
+ state.tenantId,
520
+ state.userId,
521
+ state.activeAgentId,
522
+ JSON.stringify(state.messages),
523
+ state.pending ? JSON.stringify(state.pending) : null,
524
+ state.runningUntil,
525
+ state.agents?.length ? JSON.stringify(state.agents) : null,
526
+ state.plan ? JSON.stringify(state.plan) : null,
527
+ state.pod ?? null,
528
+ state.actor ? JSON.stringify(state.actor) : null,
529
+ state.channel ?? null,
530
+ state.meta ? JSON.stringify(state.meta) : null
531
+ ];
532
+ const { rows } = expectedVersion === 0 ? await client.query(
533
+ `insert into ${table} (id, tenant_id, user_id, active_agent_id, messages, pending, running_until, agents, plan, pod, actor, channel, meta, version, created_at, updated_at)
534
+ values ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7, $8::jsonb, $9::jsonb, $10, $11::jsonb, $12, $13::jsonb, 1, $14, now())
535
+ on conflict (id) do nothing
536
+ returning *`,
537
+ [...values, state.createdAt]
538
+ ) : await client.query(
539
+ `update ${table}
540
+ set tenant_id = $2, user_id = $3, active_agent_id = $4, messages = $5::jsonb, pending = $6::jsonb,
541
+ running_until = $7, agents = $8::jsonb, plan = $9::jsonb, pod = $10, actor = $11::jsonb, channel = $12,
542
+ meta = $13::jsonb, version = version + 1, updated_at = now()
543
+ where id = $1 and version = $14
544
+ returning *`,
545
+ [...values, expectedVersion]
546
+ );
547
+ if (!rows[0]) throw new import_core3.SessionConflictError(state.id);
548
+ return fromRow(rows[0]);
549
+ },
550
+ async delete(sessionId) {
551
+ await client.query(`delete from ${table} where id = $1`, [sessionId]);
552
+ },
553
+ async listPending(tenantId, limit) {
554
+ const { rows } = await client.query(
555
+ `select * from ${table} where ${tenantId === null ? "tenant_id is null" : "tenant_id = $2"} and pending is not null and actor->>'type' = 'service'
556
+ order by updated_at desc limit $1`,
557
+ tenantId === null ? [limit] : [limit, tenantId]
558
+ );
559
+ return rows.map(fromRow);
560
+ }
561
+ };
562
+ }
563
+ function fromRow(row) {
564
+ return {
565
+ id: row.id,
566
+ tenantId: row.tenant_id,
567
+ userId: row.user_id,
568
+ activeAgentId: row.active_agent_id,
569
+ messages: typeof row.messages === "string" ? JSON.parse(row.messages) : row.messages,
570
+ pending: typeof row.pending === "string" ? JSON.parse(row.pending) : row.pending ?? null,
571
+ runningUntil: row.running_until ? new Date(row.running_until).toISOString() : null,
572
+ agents: (typeof row.agents === "string" ? JSON.parse(row.agents) : row.agents) ?? [],
573
+ plan: (typeof row.plan === "string" ? JSON.parse(row.plan) : row.plan) ?? null,
574
+ ...row.pod ? { pod: row.pod } : {},
575
+ ...row.actor ? { actor: typeof row.actor === "string" ? JSON.parse(row.actor) : row.actor } : {},
576
+ ...row.channel ? { channel: row.channel } : {},
577
+ ...row.meta ? { meta: typeof row.meta === "string" ? JSON.parse(row.meta) : row.meta } : {},
578
+ version: Number(row.version),
579
+ createdAt: new Date(row.created_at).toISOString(),
580
+ updatedAt: new Date(row.updated_at).toISOString()
581
+ };
582
+ }
583
+ function assertIdentifier(table) {
584
+ if (!IDENTIFIER4.test(table)) throw new Error(`Nome de tabela inv\xE1lido: "${table}".`);
585
+ }
586
+ // Annotate the CommonJS export names for ESM import in node:
587
+ 0 && (module.exports = {
588
+ createGovernanceTablesSQL,
589
+ createKnowledgeTablesSQL,
590
+ createPostgresAdapter,
591
+ createPostgresAuditStore,
592
+ createPostgresFactStore,
593
+ createPostgresKnowledgeStore,
594
+ createPostgresSettingsStore,
595
+ createPostgresUsageStore,
596
+ createSessionsTableSQL,
597
+ createUsageTableSQL
598
+ });
599
+ //# sourceMappingURL=index.cjs.map