@dolfinhos/db-postgres 0.0.0-stage → 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/dist/index.cjs ADDED
@@ -0,0 +1,711 @@
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
+ createCredentialsTableSQL: () => createCredentialsTableSQL,
24
+ createGovernanceTablesSQL: () => createGovernanceTablesSQL,
25
+ createKnowledgeTablesSQL: () => createKnowledgeTablesSQL,
26
+ createPostgresAdapter: () => createPostgresAdapter,
27
+ createPostgresAuditStore: () => createPostgresAuditStore,
28
+ createPostgresCredentialStore: () => createPostgresCredentialStore,
29
+ createPostgresFactStore: () => createPostgresFactStore,
30
+ createPostgresKnowledgeStore: () => createPostgresKnowledgeStore,
31
+ createPostgresSettingsStore: () => createPostgresSettingsStore,
32
+ createPostgresUsageStore: () => createPostgresUsageStore,
33
+ createSessionsTableSQL: () => createSessionsTableSQL,
34
+ createUsageTableSQL: () => createUsageTableSQL
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+ var import_core4 = require("@dolfinhos/core");
38
+
39
+ // src/governance.ts
40
+ var import_core = require("@dolfinhos/core");
41
+ var IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
42
+ function assertSchema(schema) {
43
+ if (!IDENTIFIER.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
44
+ }
45
+ function createGovernanceTablesSQL(schema = "dolfinhos") {
46
+ assertSchema(schema);
47
+ return `
48
+ create schema if not exists ${schema};
49
+ create table if not exists ${schema}.settings (
50
+ tenant_id text primary key,
51
+ data jsonb not null,
52
+ updated_at timestamptz not null default now()
53
+ );
54
+ create table if not exists ${schema}.audit (
55
+ id text primary key,
56
+ tenant_id text,
57
+ at timestamptz not null,
58
+ actor jsonb,
59
+ channel text,
60
+ session_id text not null,
61
+ run_id text not null,
62
+ agent_id text not null,
63
+ tool_call_id text not null,
64
+ capability text not null,
65
+ kind text not null,
66
+ risk text not null,
67
+ input jsonb,
68
+ decision text not null,
69
+ rule text,
70
+ status text not null,
71
+ error text
72
+ );
73
+ alter table ${schema}.audit add column if not exists decided_by jsonb;
74
+ create index if not exists audit_tenant_at_idx on ${schema}.audit (tenant_id, at desc);
75
+ `.trim();
76
+ }
77
+ var json = (value) => typeof value === "string" ? JSON.parse(value) : value;
78
+ function createPostgresSettingsStore(options) {
79
+ const schema = options.schema ?? "dolfinhos";
80
+ assertSchema(schema);
81
+ const { client } = options;
82
+ const fromRow2 = (row) => ({ ...json(row.data), updatedAt: new Date(row.updated_at).toISOString() });
83
+ return {
84
+ async migrate() {
85
+ await client.query(createGovernanceTablesSQL(schema));
86
+ },
87
+ async get(tenantId) {
88
+ const { rows } = await client.query(`select data, updated_at from ${schema}.settings where tenant_id = $1`, [tenantId]);
89
+ return rows[0] ? fromRow2(rows[0]) : null;
90
+ },
91
+ async set(tenantId, settings) {
92
+ const { updatedAt: _ignored, ...data } = settings;
93
+ const { rows } = await client.query(
94
+ `insert into ${schema}.settings (tenant_id, data, updated_at) values ($1, $2::jsonb, now())
95
+ on conflict (tenant_id) do update set data = excluded.data, updated_at = now()
96
+ returning data, updated_at`,
97
+ [tenantId, JSON.stringify(data)]
98
+ );
99
+ return fromRow2(rows[0]);
100
+ }
101
+ };
102
+ }
103
+ function createPostgresAuditStore(options) {
104
+ const schema = options.schema ?? "dolfinhos";
105
+ assertSchema(schema);
106
+ const { client } = options;
107
+ return {
108
+ async migrate() {
109
+ await client.query(createGovernanceTablesSQL(schema));
110
+ },
111
+ async append(r) {
112
+ await client.query(
113
+ `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)
114
+ values ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18::jsonb)`,
115
+ [
116
+ r.id,
117
+ r.tenantId,
118
+ r.at,
119
+ r.actor ? JSON.stringify(r.actor) : null,
120
+ r.channel,
121
+ r.sessionId,
122
+ r.runId,
123
+ r.agentId,
124
+ r.toolCallId,
125
+ r.capability,
126
+ r.kind,
127
+ r.risk,
128
+ JSON.stringify(r.input ?? null),
129
+ r.decision,
130
+ r.rule ?? null,
131
+ r.status,
132
+ r.error ?? null,
133
+ r.decidedBy ? JSON.stringify(r.decidedBy) : null
134
+ ]
135
+ );
136
+ },
137
+ async list(q) {
138
+ const values = [];
139
+ const where = [];
140
+ const add = (column, op, value) => {
141
+ values.push(value);
142
+ where.push(`${column} ${op} $${values.length}`);
143
+ };
144
+ if (q.tenantId === null) where.push("tenant_id is null");
145
+ else add("tenant_id", "=", q.tenantId);
146
+ if (q.sessionId) add("session_id", "=", q.sessionId);
147
+ if (q.capability) add("capability", "=", q.capability);
148
+ if (q.before) add("at", "<", q.before);
149
+ values.push((0, import_core.auditLimit)(q.limit));
150
+ const { rows } = await client.query(`select * from ${schema}.audit where ${where.join(" and ")} order by at desc limit $${values.length}`, values);
151
+ return rows.map(
152
+ (row) => ({
153
+ id: row.id,
154
+ tenantId: row.tenant_id,
155
+ at: new Date(row.at).toISOString(),
156
+ actor: json(row.actor),
157
+ channel: row.channel,
158
+ sessionId: row.session_id,
159
+ runId: row.run_id,
160
+ agentId: row.agent_id,
161
+ toolCallId: row.tool_call_id,
162
+ capability: row.capability,
163
+ kind: row.kind,
164
+ risk: row.risk,
165
+ input: json(row.input),
166
+ decision: row.decision,
167
+ ...row.rule ? { rule: row.rule } : {},
168
+ status: row.status,
169
+ ...row.error ? { error: row.error } : {},
170
+ ...row.decided_by ? { decidedBy: json(row.decided_by) } : {}
171
+ })
172
+ );
173
+ }
174
+ };
175
+ }
176
+
177
+ // src/usage.ts
178
+ var IDENTIFIER2 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
179
+ function createUsageTableSQL(schema = "dolfinhos") {
180
+ if (!IDENTIFIER2.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
181
+ return `
182
+ create schema if not exists ${schema};
183
+ create table if not exists ${schema}.usage (
184
+ id text primary key,
185
+ tenant_id text,
186
+ at timestamptz not null,
187
+ session_id text not null,
188
+ run_id text not null,
189
+ pod text not null,
190
+ channel text,
191
+ actor jsonb,
192
+ model text not null,
193
+ calls integer not null,
194
+ input_tokens integer not null,
195
+ cached_input_tokens integer not null,
196
+ output_tokens integer not null,
197
+ cost double precision
198
+ );
199
+ create index if not exists usage_tenant_at_idx on ${schema}.usage (tenant_id, at);
200
+ `.trim();
201
+ }
202
+ var totals = (row) => ({
203
+ runs: Number(row.runs),
204
+ calls: Number(row.calls),
205
+ inputTokens: Number(row.input_tokens),
206
+ cachedInputTokens: Number(row.cached_input_tokens),
207
+ outputTokens: Number(row.output_tokens),
208
+ cost: Number(row.cost),
209
+ unpricedCalls: Number(row.unpriced_calls)
210
+ });
211
+ function createPostgresUsageStore(options) {
212
+ const schema = options.schema ?? "dolfinhos";
213
+ if (!IDENTIFIER2.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
214
+ const { client } = options;
215
+ const aggregates = `count(distinct run_id) runs, coalesce(sum(calls), 0) calls, coalesce(sum(input_tokens), 0) input_tokens,
216
+ coalesce(sum(cached_input_tokens), 0) cached_input_tokens, coalesce(sum(output_tokens), 0) output_tokens,
217
+ coalesce(sum(cost), 0) cost, coalesce(sum(calls) filter (where cost is null), 0) unpriced_calls`;
218
+ return {
219
+ async migrate() {
220
+ await client.query(createUsageTableSQL(schema));
221
+ },
222
+ async append(records) {
223
+ for (const r of records) {
224
+ await client.query(
225
+ `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)
226
+ values ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11, $12, $13, $14)`,
227
+ [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]
228
+ );
229
+ }
230
+ },
231
+ async totalCost(q) {
232
+ const tenant = q.tenantId === null ? "tenant_id is null" : "tenant_id = $3";
233
+ const values = q.tenantId === null ? [q.from, q.to] : [q.from, q.to, q.tenantId];
234
+ const { rows } = await client.query(`select coalesce(sum(cost), 0) as cost from ${schema}.usage where ${tenant} and at >= $1 and at < $2`, values);
235
+ return Number(rows[0]?.cost ?? 0);
236
+ },
237
+ async summary(q) {
238
+ const tenant = q.tenantId === null ? "tenant_id is null" : "tenant_id = $3";
239
+ const values = q.tenantId === null ? [q.from, q.to] : [q.from, q.to, q.tenantId];
240
+ const where = `where ${tenant} and at >= $1 and at < $2`;
241
+ const by = (expr) => client.query(`select ${expr} as key, ${aggregates} from ${schema}.usage ${where} group by 1`, values);
242
+ const [total, day, model, channel] = await Promise.all([
243
+ client.query(`select ${aggregates} from ${schema}.usage ${where}`, values),
244
+ by(`to_char(at at time zone 'UTC', 'YYYY-MM-DD')`),
245
+ by("model"),
246
+ by(`coalesce(channel, 'app')`)
247
+ ]);
248
+ const sorted = (list) => list.sort((a, b) => b.cost - a.cost || b.calls - a.calls);
249
+ return {
250
+ total: totals(total.rows[0] ?? {}),
251
+ byDay: day.rows.map((r) => ({ ...totals(r), day: r.key })).sort((a, b) => a.day.localeCompare(b.day)),
252
+ byModel: sorted(model.rows.map((r) => ({ ...totals(r), model: r.key }))),
253
+ byChannel: sorted(channel.rows.map((r) => ({ ...totals(r), channel: r.key })))
254
+ };
255
+ }
256
+ };
257
+ }
258
+
259
+ // src/knowledge.ts
260
+ var import_core2 = require("@dolfinhos/core");
261
+ var IDENTIFIER3 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
262
+ var schemaOf = (options) => {
263
+ const schema = options.schema ?? "dolfinhos";
264
+ if (!IDENTIFIER3.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
265
+ return schema;
266
+ };
267
+ var tenantKey = (tenantId) => tenantId ?? "";
268
+ var json2 = (value) => typeof value === "string" ? JSON.parse(value) : value;
269
+ function createKnowledgeTablesSQL(schema = "dolfinhos") {
270
+ if (!IDENTIFIER3.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
271
+ return `
272
+ create schema if not exists ${schema};
273
+ create table if not exists ${schema}.knowledge_docs (
274
+ tenant_key text not null,
275
+ id text not null,
276
+ tenant_id text,
277
+ title text not null,
278
+ content text not null,
279
+ audience text not null,
280
+ tags jsonb not null default '[]'::jsonb,
281
+ updated_at timestamptz not null default now(),
282
+ updated_by text,
283
+ primary key (tenant_key, id)
284
+ );
285
+ create table if not exists ${schema}.knowledge_chunks (
286
+ tenant_key text not null,
287
+ doc_id text not null,
288
+ idx integer not null,
289
+ text text not null,
290
+ search tsvector not null
291
+ );
292
+ create unique index if not exists knowledge_chunks_key on ${schema}.knowledge_chunks (tenant_key, doc_id, idx);
293
+ create index if not exists knowledge_chunks_search_idx on ${schema}.knowledge_chunks using gin (search);
294
+ create table if not exists ${schema}.facts (
295
+ id text primary key,
296
+ tenant_key text not null,
297
+ tenant_id text,
298
+ subject_type text not null,
299
+ subject_id text not null,
300
+ subject_label text,
301
+ text text not null,
302
+ created_at timestamptz not null default now(),
303
+ created_by jsonb
304
+ );
305
+ create index if not exists facts_subject_idx on ${schema}.facts (tenant_key, subject_type, subject_id, created_at desc);
306
+ `.trim();
307
+ }
308
+ var docFromRow = (row) => ({
309
+ id: row.id,
310
+ tenantId: row.tenant_id,
311
+ title: row.title,
312
+ content: row.content,
313
+ audience: row.audience,
314
+ tags: json2(row.tags) ?? [],
315
+ updatedAt: new Date(row.updated_at).toISOString(),
316
+ ...row.updated_by ? { updatedBy: row.updated_by } : {}
317
+ });
318
+ function createPostgresKnowledgeStore(options) {
319
+ const schema = schemaOf(options);
320
+ const { client } = options;
321
+ return {
322
+ async migrate() {
323
+ await client.query(createKnowledgeTablesSQL(schema));
324
+ },
325
+ async list(tenantId) {
326
+ const { rows } = await client.query(`select * from ${schema}.knowledge_docs where tenant_key = $1 order by title limit 1000`, [tenantKey(tenantId)]);
327
+ return rows.map(docFromRow);
328
+ },
329
+ async get(tenantId, id) {
330
+ const { rows } = await client.query(`select * from ${schema}.knowledge_docs where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
331
+ return rows[0] ? docFromRow(rows[0]) : null;
332
+ },
333
+ async save(doc) {
334
+ const chunks = (0, import_core2.chunkText)(doc.content);
335
+ const { rows } = await client.query(
336
+ `with doc as (
337
+ insert into ${schema}.knowledge_docs (tenant_key, id, tenant_id, title, content, audience, tags, updated_at, updated_by)
338
+ values ($1, $2, $3, $4, $5, $6, $7::jsonb, now(), $8)
339
+ on conflict (tenant_key, id) do update set title = excluded.title, content = excluded.content, audience = excluded.audience,
340
+ tags = excluded.tags, updated_at = now(), updated_by = excluded.updated_by
341
+ returning *
342
+ ), extra as (
343
+ -- Trechos al\xE9m do novo tamanho saem; os outros s\xE3o sobrescritos pela posi\xE7\xE3o. Duas grava\xE7\xF5es
344
+ -- ao mesmo tempo esperam uma pela outra em cada trecho, e a \xFAltima vence inteira.
345
+ delete from ${schema}.knowledge_chunks where tenant_key = $1 and doc_id = $2 and idx >= cardinality($9::text[])
346
+ ), fresh as (
347
+ insert into ${schema}.knowledge_chunks (tenant_key, doc_id, idx, text, search)
348
+ select $1, $2, c.idx - 1, c.text, to_tsvector('portuguese', c.norm)
349
+ from unnest($9::text[], $10::text[]) with ordinality as c(text, norm, idx)
350
+ on conflict (tenant_key, doc_id, idx) do update set text = excluded.text, search = excluded.search
351
+ )
352
+ select * from doc`,
353
+ [
354
+ tenantKey(doc.tenantId),
355
+ doc.id,
356
+ doc.tenantId,
357
+ doc.title,
358
+ doc.content,
359
+ doc.audience,
360
+ JSON.stringify(doc.tags),
361
+ doc.updatedBy ?? null,
362
+ chunks,
363
+ chunks.map((c) => (0, import_core2.normalizeText)(`${doc.title}
364
+ ${c}`))
365
+ ]
366
+ );
367
+ return docFromRow(rows[0]);
368
+ },
369
+ async remove(tenantId, id) {
370
+ await client.query(
371
+ `with gone as (delete from ${schema}.knowledge_chunks where tenant_key = $1 and doc_id = $2)
372
+ delete from ${schema}.knowledge_docs where tenant_key = $1 and id = $2`,
373
+ [tenantKey(tenantId), id]
374
+ );
375
+ },
376
+ async search({ tenantId, query, audience, limit = 4 }) {
377
+ const terms = (0, import_core2.searchTerms)(query);
378
+ if (!terms.length) return [];
379
+ const tsquery = terms.map((t) => `${t}:*`).join(" | ");
380
+ const { rows } = await client.query(
381
+ `select * from (
382
+ select distinct on (c.doc_id) c.doc_id, d.title, c.text, ts_rank_cd(c.search, q) as score
383
+ from ${schema}.knowledge_chunks c
384
+ join ${schema}.knowledge_docs d on d.tenant_key = c.tenant_key and d.id = c.doc_id,
385
+ to_tsquery('portuguese', $2) q
386
+ where c.tenant_key = $1 and c.search @@ q and ($3 = 'internal' or d.audience = 'all')
387
+ order by c.doc_id, score desc
388
+ ) best order by score desc limit $4`,
389
+ [tenantKey(tenantId), tsquery, audience, Math.min(Math.max(limit, 1), 20)]
390
+ );
391
+ return rows.map((r) => ({ docId: r.doc_id, title: r.title, excerpt: r.text, score: Number(r.score) }));
392
+ }
393
+ };
394
+ }
395
+ var factFromRow = (row) => ({
396
+ id: row.id,
397
+ tenantId: row.tenant_id,
398
+ subject: { type: row.subject_type, id: row.subject_id, ...row.subject_label ? { label: row.subject_label } : {} },
399
+ text: row.text,
400
+ createdAt: new Date(row.created_at).toISOString(),
401
+ createdBy: json2(row.created_by) ?? null
402
+ });
403
+ function createPostgresFactStore(options) {
404
+ const schema = schemaOf(options);
405
+ const { client } = options;
406
+ return {
407
+ async migrate() {
408
+ await client.query(createKnowledgeTablesSQL(schema));
409
+ },
410
+ async list({ tenantId, subject, limit = import_core2.MAX_FACTS_PER_SUBJECT }) {
411
+ const { rows } = await client.query(
412
+ `select * from ${schema}.facts where tenant_key = $1 and subject_type = $2 and subject_id = $3 order by created_at desc limit $4`,
413
+ [tenantKey(tenantId), subject.type, subject.id, Math.min(Math.max(limit, 1), import_core2.MAX_FACTS_PER_SUBJECT)]
414
+ );
415
+ return rows.map(factFromRow);
416
+ },
417
+ async subjects({ tenantId, type, limit = 200 }) {
418
+ const { rows } = await client.query(
419
+ `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
420
+ from ${schema}.facts where tenant_key = $1 and ($2::text is null or subject_type = $2)
421
+ group by 1, 2 order by last_at desc limit $3`,
422
+ [tenantKey(tenantId), type ?? null, Math.min(Math.max(limit, 1), 1e3)]
423
+ );
424
+ return rows.map((r) => ({
425
+ type: r.subject_type,
426
+ id: r.subject_id,
427
+ ...r.label ? { label: r.label } : {},
428
+ count: Number(r.count),
429
+ lastAt: new Date(r.last_at).toISOString()
430
+ }));
431
+ },
432
+ async get(tenantId, id) {
433
+ const { rows } = await client.query(`select * from ${schema}.facts where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
434
+ return rows[0] ? factFromRow(rows[0]) : null;
435
+ },
436
+ async add(fact) {
437
+ const { rows } = await client.query(
438
+ `with fresh as (
439
+ insert into ${schema}.facts (id, tenant_key, tenant_id, subject_type, subject_id, subject_label, text, created_at, created_by)
440
+ values ($1, $2, $3, $4, $5, $6, $7, now(), $8::jsonb) returning *
441
+ ), trimmed as (
442
+ delete from ${schema}.facts where id in (
443
+ select id from ${schema}.facts where tenant_key = $2 and subject_type = $4 and subject_id = $5
444
+ order by created_at desc offset $9
445
+ )
446
+ )
447
+ select * from fresh`,
448
+ [
449
+ crypto.randomUUID(),
450
+ tenantKey(fact.tenantId),
451
+ fact.tenantId,
452
+ fact.subject.type,
453
+ fact.subject.id,
454
+ fact.subject.label ?? null,
455
+ fact.text,
456
+ fact.createdBy ? JSON.stringify(fact.createdBy) : null,
457
+ import_core2.MAX_FACTS_PER_SUBJECT - 1
458
+ ]
459
+ );
460
+ return factFromRow(rows[0]);
461
+ },
462
+ async remove(tenantId, id) {
463
+ await client.query(`delete from ${schema}.facts where tenant_key = $1 and id = $2`, [tenantKey(tenantId), id]);
464
+ }
465
+ };
466
+ }
467
+
468
+ // src/credentials.ts
469
+ var import_node_crypto = require("crypto");
470
+ var import_core3 = require("@dolfinhos/core");
471
+ var IDENTIFIER4 = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
472
+ var VERSION = "v1";
473
+ function createCredentialsTableSQL(schema = "dolfinhos") {
474
+ if (!IDENTIFIER4.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
475
+ return `
476
+ create schema if not exists ${schema};
477
+ create table if not exists ${schema}.credentials (
478
+ tenant_key text not null,
479
+ name text not null,
480
+ tenant_id text,
481
+ secret text not null,
482
+ last4 text not null,
483
+ updated_at timestamptz not null default now(),
484
+ updated_by text,
485
+ primary key (tenant_key, name)
486
+ );
487
+ `.trim();
488
+ }
489
+ function createPostgresCredentialStore(options) {
490
+ const schema = options.schema ?? "dolfinhos";
491
+ if (!IDENTIFIER4.test(schema)) throw new Error(`Nome de schema inv\xE1lido: "${schema}".`);
492
+ for (const secret of [options.encryptionKey, ...options.previousEncryptionKeys ?? []]) {
493
+ if (!secret || secret.length < 32) throw new Error("Dolfinhos: `encryptionKey` precisa de pelo menos 32 caracteres (ex.: openssl rand -base64 32).");
494
+ }
495
+ const derive = (secret) => Buffer.from((0, import_node_crypto.hkdfSync)("sha256", secret, "dolfinhos", "credentials-v1", 32));
496
+ const key = derive(options.encryptionKey);
497
+ const previous = (options.previousEncryptionKeys ?? []).map(derive);
498
+ const { client } = options;
499
+ const tenantKey2 = (tenantId) => tenantId ?? "";
500
+ const aad = (tenantId, name) => Buffer.from(`${tenantKey2(tenantId)}\0${name}`);
501
+ const encrypt = (value, tenantId, name) => {
502
+ const iv = (0, import_node_crypto.randomBytes)(12);
503
+ const cipher = (0, import_node_crypto.createCipheriv)("aes-256-gcm", key, iv);
504
+ cipher.setAAD(aad(tenantId, name));
505
+ const data = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
506
+ return `${VERSION}:${Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64")}`;
507
+ };
508
+ const decryptWith = (secretKey, raw, tenantId, name) => {
509
+ const decipher = (0, import_node_crypto.createDecipheriv)("aes-256-gcm", secretKey, raw.subarray(0, 12), { authTagLength: 16 });
510
+ decipher.setAAD(aad(tenantId, name));
511
+ decipher.setAuthTag(raw.subarray(12, 28));
512
+ return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
513
+ };
514
+ const decrypt = (stored, tenantId, name) => {
515
+ const [version, payload] = stored.split(":");
516
+ if (version !== VERSION || !payload) throw new Error("Dolfinhos: formato de chave salva desconhecido.");
517
+ const raw = Buffer.from(payload, "base64");
518
+ if (raw.length < 29) throw new Error("Dolfinhos: chave salva incompleta.");
519
+ for (const [index, candidate] of [key, ...previous].entries()) {
520
+ try {
521
+ return { value: decryptWith(candidate, raw, tenantId, name), rotated: index > 0 };
522
+ } catch {
523
+ }
524
+ }
525
+ throw new Error("Dolfinhos: nenhum segredo abre esta chave.");
526
+ };
527
+ const info = (row) => ({
528
+ name: row.name,
529
+ last4: row.last4,
530
+ updatedAt: new Date(row.updated_at).toISOString(),
531
+ ...row.updated_by ? { updatedBy: row.updated_by } : {}
532
+ });
533
+ return {
534
+ async migrate() {
535
+ await client.query(createCredentialsTableSQL(schema));
536
+ },
537
+ async get(tenantId, name) {
538
+ const { rows } = await client.query(`select secret from ${schema}.credentials where tenant_key = $1 and name = $2`, [tenantKey2(tenantId), name]);
539
+ if (!rows[0]) return null;
540
+ let opened;
541
+ try {
542
+ opened = decrypt(rows[0].secret, tenantId, name);
543
+ } catch {
544
+ throw new Error("Dolfinhos: n\xE3o foi poss\xEDvel ler a chave salva desta empresa (o segredo do servidor mudou?). Cadastre a chave de novo.");
545
+ }
546
+ if (opened.rotated) {
547
+ await client.query(`update ${schema}.credentials set secret = $3 where tenant_key = $1 and name = $2 and secret = $4`, [
548
+ tenantKey2(tenantId),
549
+ name,
550
+ encrypt(opened.value, tenantId, name),
551
+ rows[0].secret
552
+ ]);
553
+ }
554
+ return opened.value;
555
+ },
556
+ async set(tenantId, name, value, updatedBy) {
557
+ const { rows } = await client.query(
558
+ `insert into ${schema}.credentials (tenant_key, name, tenant_id, secret, last4, updated_at, updated_by)
559
+ values ($1, $2, $3, $4, $5, now(), $6)
560
+ on conflict (tenant_key, name) do update set secret = excluded.secret, last4 = excluded.last4, updated_at = now(), updated_by = excluded.updated_by
561
+ returning name, last4, updated_at, updated_by`,
562
+ [tenantKey2(tenantId), name, tenantId, encrypt(value, tenantId, name), (0, import_core3.last4)(value), updatedBy ?? null]
563
+ );
564
+ return info(rows[0]);
565
+ },
566
+ async remove(tenantId, name) {
567
+ await client.query(`delete from ${schema}.credentials where tenant_key = $1 and name = $2`, [tenantKey2(tenantId), name]);
568
+ },
569
+ async list(tenantId) {
570
+ const { rows } = await client.query(`select name, last4, updated_at, updated_by from ${schema}.credentials where tenant_key = $1 order by name`, [tenantKey2(tenantId)]);
571
+ return rows.map(info);
572
+ }
573
+ };
574
+ }
575
+
576
+ // src/index.ts
577
+ var IDENTIFIER5 = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?$/;
578
+ function createSessionsTableSQL(table = "dolfinhos_sessions") {
579
+ assertIdentifier(table);
580
+ const index = `${table.replace(".", "_")}_owner_idx`;
581
+ const pendingIndex = `${table.replace(".", "_")}_pending_idx`;
582
+ const schema = table.includes(".") ? `create schema if not exists ${table.split(".")[0]};
583
+ ` : "";
584
+ return `
585
+ ${schema}create table if not exists ${table} (
586
+ id text primary key,
587
+ tenant_id text,
588
+ user_id text,
589
+ active_agent_id text not null,
590
+ messages jsonb not null default '[]'::jsonb,
591
+ pending jsonb,
592
+ agents jsonb,
593
+ plan jsonb,
594
+ pod text,
595
+ actor jsonb,
596
+ channel text,
597
+ meta jsonb,
598
+ running_until timestamptz,
599
+ version integer not null,
600
+ created_at timestamptz not null default now(),
601
+ updated_at timestamptz not null default now()
602
+ );
603
+ alter table ${table} add column if not exists running_until timestamptz;
604
+ alter table ${table} add column if not exists agents jsonb;
605
+ alter table ${table} add column if not exists plan jsonb;
606
+ alter table ${table} add column if not exists pod text;
607
+ alter table ${table} add column if not exists actor jsonb;
608
+ alter table ${table} add column if not exists channel text;
609
+ alter table ${table} add column if not exists meta jsonb;
610
+ create index if not exists ${index.split(".").pop()} on ${table} (tenant_id, user_id, updated_at desc);
611
+ create index if not exists ${pendingIndex.split(".").pop()} on ${table} (tenant_id, updated_at desc) where pending is not null;
612
+ `.trim();
613
+ }
614
+ function createPostgresAdapter(options) {
615
+ const { client } = options;
616
+ const table = options.table ?? "dolfinhos_sessions";
617
+ assertIdentifier(table);
618
+ return {
619
+ async migrate() {
620
+ await client.query(createSessionsTableSQL(table));
621
+ },
622
+ async load(sessionId) {
623
+ const { rows } = await client.query(`select * from ${table} where id = $1`, [sessionId]);
624
+ return rows[0] ? fromRow(rows[0]) : null;
625
+ },
626
+ async save(state, expectedVersion) {
627
+ const values = [
628
+ state.id,
629
+ state.tenantId,
630
+ state.userId,
631
+ state.activeAgentId,
632
+ JSON.stringify(state.messages),
633
+ state.pending ? JSON.stringify(state.pending) : null,
634
+ state.runningUntil,
635
+ state.agents?.length ? JSON.stringify(state.agents) : null,
636
+ state.plan ? JSON.stringify(state.plan) : null,
637
+ state.pod ?? null,
638
+ state.actor ? JSON.stringify(state.actor) : null,
639
+ state.channel ?? null,
640
+ state.meta ? JSON.stringify(state.meta) : null
641
+ ];
642
+ const { rows } = expectedVersion === 0 ? await client.query(
643
+ `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)
644
+ values ($1, $2, $3, $4, $5::jsonb, $6::jsonb, $7, $8::jsonb, $9::jsonb, $10, $11::jsonb, $12, $13::jsonb, 1, $14, now())
645
+ on conflict (id) do nothing
646
+ returning *`,
647
+ [...values, state.createdAt]
648
+ ) : await client.query(
649
+ `update ${table}
650
+ set tenant_id = $2, user_id = $3, active_agent_id = $4, messages = $5::jsonb, pending = $6::jsonb,
651
+ running_until = $7, agents = $8::jsonb, plan = $9::jsonb, pod = $10, actor = $11::jsonb, channel = $12,
652
+ meta = $13::jsonb, version = version + 1, updated_at = now()
653
+ where id = $1 and version = $14
654
+ returning *`,
655
+ [...values, expectedVersion]
656
+ );
657
+ if (!rows[0]) throw new import_core4.SessionConflictError(state.id);
658
+ return fromRow(rows[0]);
659
+ },
660
+ async delete(sessionId) {
661
+ await client.query(`delete from ${table} where id = $1`, [sessionId]);
662
+ },
663
+ async listPending(tenantId, limit) {
664
+ const { rows } = await client.query(
665
+ `select * from ${table} where ${tenantId === null ? "tenant_id is null" : "tenant_id = $2"} and pending is not null and actor->>'type' = 'service'
666
+ order by updated_at desc limit $1`,
667
+ tenantId === null ? [limit] : [limit, tenantId]
668
+ );
669
+ return rows.map(fromRow);
670
+ }
671
+ };
672
+ }
673
+ function fromRow(row) {
674
+ return {
675
+ id: row.id,
676
+ tenantId: row.tenant_id,
677
+ userId: row.user_id,
678
+ activeAgentId: row.active_agent_id,
679
+ messages: typeof row.messages === "string" ? JSON.parse(row.messages) : row.messages,
680
+ pending: typeof row.pending === "string" ? JSON.parse(row.pending) : row.pending ?? null,
681
+ runningUntil: row.running_until ? new Date(row.running_until).toISOString() : null,
682
+ agents: (typeof row.agents === "string" ? JSON.parse(row.agents) : row.agents) ?? [],
683
+ plan: (typeof row.plan === "string" ? JSON.parse(row.plan) : row.plan) ?? null,
684
+ ...row.pod ? { pod: row.pod } : {},
685
+ ...row.actor ? { actor: typeof row.actor === "string" ? JSON.parse(row.actor) : row.actor } : {},
686
+ ...row.channel ? { channel: row.channel } : {},
687
+ ...row.meta ? { meta: typeof row.meta === "string" ? JSON.parse(row.meta) : row.meta } : {},
688
+ version: Number(row.version),
689
+ createdAt: new Date(row.created_at).toISOString(),
690
+ updatedAt: new Date(row.updated_at).toISOString()
691
+ };
692
+ }
693
+ function assertIdentifier(table) {
694
+ if (!IDENTIFIER5.test(table)) throw new Error(`Nome de tabela inv\xE1lido: "${table}".`);
695
+ }
696
+ // Annotate the CommonJS export names for ESM import in node:
697
+ 0 && (module.exports = {
698
+ createCredentialsTableSQL,
699
+ createGovernanceTablesSQL,
700
+ createKnowledgeTablesSQL,
701
+ createPostgresAdapter,
702
+ createPostgresAuditStore,
703
+ createPostgresCredentialStore,
704
+ createPostgresFactStore,
705
+ createPostgresKnowledgeStore,
706
+ createPostgresSettingsStore,
707
+ createPostgresUsageStore,
708
+ createSessionsTableSQL,
709
+ createUsageTableSQL
710
+ });
711
+ //# sourceMappingURL=index.cjs.map