@agentbadge/database 0.6.2 → 0.6.4

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.
@@ -90,6 +90,21 @@ const toPriceRow = (r) => ({
90
90
  createdAt: r.createdAt,
91
91
  updatedAt: r.updatedAt,
92
92
  });
93
+ const toUsageRecordRow = (r) => ({
94
+ id: r.id,
95
+ paymentId: r.paymentId,
96
+ agentId: r.agentId,
97
+ resource: r.resource,
98
+ requestId: r.requestId,
99
+ amount: dec(r.amount),
100
+ currency: r.currency,
101
+ network: r.network,
102
+ payerAddress: r.payerAddress,
103
+ txHash: r.txHash,
104
+ createdAtMs: num(r.createdAtMs),
105
+ payload: r.payload,
106
+ createdAt: r.createdAt,
107
+ });
93
108
  export class PaymentRepository {
94
109
  db;
95
110
  constructor(db) {
@@ -265,6 +280,35 @@ export class PaymentAttemptRepository {
265
280
  }
266
281
  return out;
267
282
  }
283
+ async listPayable(nowMs) {
284
+ const out = [];
285
+ const openStatuses = ["CREATED", "PENDING", "PROCESSING"].filter((s) => !TERMINAL_ATTEMPT_STATUSES.includes(s));
286
+ for (const status of openStatuses) {
287
+ const rows = await this.orm.where({ status }).all();
288
+ for (const r of rows) {
289
+ const exp = numOrNull(r.expiresAtMs);
290
+ if (exp === null || exp > nowMs)
291
+ out.push(toAttemptRow(r));
292
+ }
293
+ }
294
+ return out;
295
+ }
296
+ async listRecentTerminal(sinceMs) {
297
+ const out = [];
298
+ for (const status of TERMINAL_ATTEMPT_STATUSES) {
299
+ const rows = await this.orm
300
+ .where({ status })
301
+ .all();
302
+ for (const r of rows) {
303
+ const stamp = r.updatedAt
304
+ ? new Date(r.updatedAt).getTime()
305
+ : (numOrNull(r.confirmedAtMs) ?? 0);
306
+ if (stamp >= sinceMs)
307
+ out.push(toAttemptRow(r));
308
+ }
309
+ }
310
+ return out;
311
+ }
268
312
  }
269
313
  export class PaymentReceiptRepository {
270
314
  db;
@@ -433,13 +477,148 @@ export class PaymentPriceRepository {
433
477
  return rows.map(toPriceRow);
434
478
  }
435
479
  }
480
+ const toExceptionRow = (r) => ({
481
+ id: r.id,
482
+ paymentId: r.paymentId ?? undefined,
483
+ attemptId: r.attemptId ?? undefined,
484
+ kind: r.kind,
485
+ severity: r.severity,
486
+ details: r.details && typeof r.details === "object"
487
+ ? r.details
488
+ : undefined,
489
+ status: r.status,
490
+ createdAtMs: numOrNull(r.createdAtMs) ?? 0,
491
+ resolvedAtMs: numOrNull(r.resolvedAtMs),
492
+ resolutionNote: r.resolutionNote ?? null,
493
+ createdAt: r.createdAt,
494
+ });
495
+ export class PaymentExceptionRepository {
496
+ db;
497
+ constructor(db) {
498
+ this.db = db;
499
+ }
500
+ get orm() {
501
+ return this.db.orm.public.PaymentException;
502
+ }
503
+ async append(e) {
504
+ if (await this.getById(e.id))
505
+ return null;
506
+ const row = await this.orm.create({
507
+ id: e.id,
508
+ paymentId: e.paymentId ?? null,
509
+ attemptId: e.attemptId ?? null,
510
+ kind: e.kind,
511
+ severity: e.severity,
512
+ details: (e.details ?? null),
513
+ status: e.status,
514
+ createdAtMs: e.createdAtMs,
515
+ });
516
+ return toExceptionRow(row);
517
+ }
518
+ async getById(id) {
519
+ const r = await this.orm.where({ id }).first();
520
+ return r ? toExceptionRow(r) : null;
521
+ }
522
+ async listByPayment(paymentId) {
523
+ const rows = await this.orm.where({ paymentId }).all();
524
+ return rows.map(toExceptionRow);
525
+ }
526
+ async list(opts = {}) {
527
+ const rows = await this.orm.all();
528
+ let out = rows
529
+ .map(toExceptionRow)
530
+ .filter((r) => (opts.status === undefined || r.status === opts.status) &&
531
+ (opts.kind === undefined || r.kind === opts.kind) &&
532
+ (opts.sinceMs === undefined || r.createdAtMs >= opts.sinceMs));
533
+ out.sort((a, b) => b.createdAtMs - a.createdAtMs);
534
+ if (opts.limit !== undefined)
535
+ out = out.slice(0, opts.limit);
536
+ return out;
537
+ }
538
+ async resolve(id, status, note) {
539
+ const cur = await this.getById(id);
540
+ if (!cur || cur.status !== "OPEN")
541
+ return null;
542
+ const row = await this.orm.where({ id, status: "OPEN" }).update({
543
+ status,
544
+ resolvedAtMs: Date.now(),
545
+ resolutionNote: note ?? null,
546
+ });
547
+ return row ? toExceptionRow(row) : null;
548
+ }
549
+ }
550
+ export class UsageRecordRepository {
551
+ db;
552
+ constructor(db) {
553
+ this.db = db;
554
+ }
555
+ get orm() {
556
+ return this.db.orm.public.UsageRecord;
557
+ }
558
+ async append(r) {
559
+ if (await this.getById(r.id))
560
+ return null;
561
+ if (await this.getByRequestId(r.requestId))
562
+ return null;
563
+ const row = await this.orm.create({
564
+ id: r.id,
565
+ paymentId: r.paymentId,
566
+ agentId: r.agentId ?? null,
567
+ resource: r.resource,
568
+ requestId: r.requestId,
569
+ amount: r.amount,
570
+ currency: r.currency ?? "USDC",
571
+ network: r.network,
572
+ payerAddress: r.payerAddress,
573
+ txHash: r.txHash ?? null,
574
+ createdAtMs: BigInt(r.createdAtMs),
575
+ payload: r.payload,
576
+ });
577
+ return toUsageRecordRow(row);
578
+ }
579
+ async getById(id) {
580
+ const r = await this.orm.where({ id }).first();
581
+ return r ? toUsageRecordRow(r) : null;
582
+ }
583
+ async getByRequestId(requestId) {
584
+ const r = await this.orm.where({ requestId }).first();
585
+ return r ? toUsageRecordRow(r) : null;
586
+ }
587
+ async listByPayment(paymentId) {
588
+ const rows = await this.orm
589
+ .orderBy((e) => e.createdAtMs.desc())
590
+ .where({ paymentId })
591
+ .all();
592
+ return rows.map(toUsageRecordRow);
593
+ }
594
+ async listByAgent(agentId, limit) {
595
+ let q = this.orm
596
+ .orderBy((e) => e.createdAtMs.desc())
597
+ .where({ agentId });
598
+ if (limit !== undefined)
599
+ q = q.limit(limit);
600
+ const rows = await q.all();
601
+ return rows.map(toUsageRecordRow);
602
+ }
603
+ async listByResource(resource, limit) {
604
+ let q = this.orm
605
+ .orderBy((e) => e.createdAtMs.desc())
606
+ .where({ resource });
607
+ if (limit !== undefined)
608
+ q = q.limit(limit);
609
+ const rows = await q.all();
610
+ return rows.map(toUsageRecordRow);
611
+ }
612
+ }
436
613
  export function createPrismaPaymentStores(db) {
437
614
  return {
438
615
  payments: new PaymentRepository(db),
439
616
  attempts: new PaymentAttemptRepository(db),
440
617
  receipts: new PaymentReceiptRepository(db),
441
618
  events: new PaymentEventRepository(db),
619
+ exceptions: new PaymentExceptionRepository(db),
442
620
  products: new PaymentProductRepository(db),
443
621
  prices: new PaymentPriceRepository(db),
622
+ usageRecords: new UsageRecordRepository(db),
444
623
  };
445
624
  }
@@ -62,6 +62,8 @@ export interface PaymentAttemptStore {
62
62
  getByTxHash(transactionHash: string): Promise<PaymentAttemptRow | null>;
63
63
  applyStatus(id: string, expectedFrom: string, to: string, updatedAtMs: number, patch?: AttemptStatusPatch): Promise<PaymentAttemptRow | null>;
64
64
  listExpired(nowMs: number): Promise<PaymentAttemptRow[]>;
65
+ listPayable(nowMs: number): Promise<PaymentAttemptRow[]>;
66
+ listRecentTerminal(sinceMs: number): Promise<PaymentAttemptRow[]>;
65
67
  }
66
68
  export interface PaymentReceiptInsert {
67
69
  id: string;
@@ -149,13 +151,67 @@ export interface PaymentPriceStore {
149
151
  activeOnly?: boolean;
150
152
  }): Promise<PaymentPriceRow[]>;
151
153
  }
154
+ export interface PaymentExceptionInsert {
155
+ id: string;
156
+ paymentId?: string;
157
+ attemptId?: string;
158
+ kind: string;
159
+ severity: string;
160
+ details?: Record<string, unknown>;
161
+ status: string;
162
+ createdAtMs: number;
163
+ }
164
+ export interface PaymentExceptionRow extends PaymentExceptionInsert {
165
+ resolvedAtMs?: number | null;
166
+ resolutionNote?: string | null;
167
+ createdAt?: string;
168
+ }
169
+ export interface PaymentExceptionStore {
170
+ append(e: PaymentExceptionInsert): Promise<PaymentExceptionRow | null>;
171
+ getById(id: string): Promise<PaymentExceptionRow | null>;
172
+ listByPayment(paymentId: string): Promise<PaymentExceptionRow[]>;
173
+ list(opts?: {
174
+ status?: string;
175
+ kind?: string;
176
+ sinceMs?: number;
177
+ limit?: number;
178
+ }): Promise<PaymentExceptionRow[]>;
179
+ resolve(id: string, status: "RESOLVED" | "IGNORED", note?: string): Promise<PaymentExceptionRow | null>;
180
+ }
181
+ export interface UsageRecordInsert {
182
+ id: string;
183
+ paymentId: string;
184
+ agentId?: string | null;
185
+ resource: string;
186
+ requestId: string;
187
+ amount: string;
188
+ currency?: string;
189
+ network: string;
190
+ payerAddress: string;
191
+ txHash?: string | null;
192
+ createdAtMs: number;
193
+ payload: JsonValue;
194
+ }
195
+ export interface UsageRecordRow extends UsageRecordInsert {
196
+ createdAt?: string;
197
+ }
198
+ export interface UsageRecordStore {
199
+ append(r: UsageRecordInsert): Promise<UsageRecordRow | null>;
200
+ getById(id: string): Promise<UsageRecordRow | null>;
201
+ getByRequestId(requestId: string): Promise<UsageRecordRow | null>;
202
+ listByPayment(paymentId: string): Promise<UsageRecordRow[]>;
203
+ listByAgent(agentId: string, limit?: number): Promise<UsageRecordRow[]>;
204
+ listByResource(resource: string, limit?: number): Promise<UsageRecordRow[]>;
205
+ }
152
206
  export interface PaymentStores {
153
207
  payments: PaymentStore;
154
208
  attempts: PaymentAttemptStore;
155
209
  receipts: PaymentReceiptStore;
156
210
  events: PaymentEventStore;
211
+ exceptions: PaymentExceptionStore;
157
212
  products: PaymentProductStore;
158
213
  prices: PaymentPriceStore;
214
+ usageRecords: UsageRecordStore;
159
215
  }
160
216
  export declare class InMemoryPaymentStore implements PaymentStore {
161
217
  private readonly rows;
@@ -176,6 +232,9 @@ export declare class InMemoryPaymentAttemptStore implements PaymentAttemptStore
176
232
  getByTxHash(transactionHash: string): Promise<PaymentAttemptRow | null>;
177
233
  applyStatus(id: string, expectedFrom: string, to: string, updatedAtMs: number, patch?: AttemptStatusPatch): Promise<PaymentAttemptRow | null>;
178
234
  listExpired(nowMs: number): Promise<PaymentAttemptRow[]>;
235
+ listPayable(nowMs: number): Promise<PaymentAttemptRow[]>;
236
+ listRecentTerminal(sinceMs: number): Promise<PaymentAttemptRow[]>;
237
+ private readonly terminalStampMs;
179
238
  }
180
239
  export declare class InMemoryPaymentReceiptStore implements PaymentReceiptStore {
181
240
  private readonly rows;
@@ -207,4 +266,26 @@ export declare class InMemoryPaymentPriceStore implements PaymentPriceStore {
207
266
  activeOnly?: boolean;
208
267
  }): Promise<PaymentPriceRow[]>;
209
268
  }
269
+ export declare class InMemoryPaymentExceptionStore implements PaymentExceptionStore {
270
+ private readonly rows;
271
+ append(e: PaymentExceptionInsert): Promise<PaymentExceptionRow | null>;
272
+ getById(id: string): Promise<PaymentExceptionRow | null>;
273
+ listByPayment(paymentId: string): Promise<PaymentExceptionRow[]>;
274
+ list(opts?: {
275
+ status?: string;
276
+ kind?: string;
277
+ sinceMs?: number;
278
+ limit?: number;
279
+ }): Promise<PaymentExceptionRow[]>;
280
+ resolve(id: string, status: "RESOLVED" | "IGNORED", note?: string): Promise<PaymentExceptionRow | null>;
281
+ }
282
+ export declare class InMemoryUsageRecordStore implements UsageRecordStore {
283
+ private readonly rows;
284
+ append(r: UsageRecordInsert): Promise<UsageRecordRow | null>;
285
+ getById(id: string): Promise<UsageRecordRow | null>;
286
+ getByRequestId(requestId: string): Promise<UsageRecordRow | null>;
287
+ listByPayment(paymentId: string): Promise<UsageRecordRow[]>;
288
+ listByAgent(agentId: string, limit?: number): Promise<UsageRecordRow[]>;
289
+ listByResource(resource: string, limit?: number): Promise<UsageRecordRow[]>;
290
+ }
210
291
  export declare function createInMemoryPaymentStores(): PaymentStores;
@@ -126,6 +126,9 @@ export class InMemoryPaymentAttemptStore {
126
126
  updatedAt: nowIso(),
127
127
  };
128
128
  this.rows.set(id, updated);
129
+ if (TERMINAL_ATTEMPT_STATUSES.includes(to)) {
130
+ this.terminalStampMs.set(id, updatedAtMs);
131
+ }
129
132
  return updated;
130
133
  }
131
134
  async listExpired(nowMs) {
@@ -133,6 +136,19 @@ export class InMemoryPaymentAttemptStore {
133
136
  r.expiresAtMs < nowMs &&
134
137
  !TERMINAL_ATTEMPT_STATUSES.includes(r.status));
135
138
  }
139
+ async listPayable(nowMs) {
140
+ return [...this.rows.values()].filter((r) => !TERMINAL_ATTEMPT_STATUSES.includes(r.status) &&
141
+ (r.expiresAtMs == null || r.expiresAtMs > nowMs));
142
+ }
143
+ async listRecentTerminal(sinceMs) {
144
+ return [...this.rows.values()].filter((r) => {
145
+ if (!TERMINAL_ATTEMPT_STATUSES.includes(r.status))
146
+ return false;
147
+ const stamp = this.terminalStampMs.get(r.id) ?? r.confirmedAtMs;
148
+ return stamp == null || stamp >= sinceMs;
149
+ });
150
+ }
151
+ terminalStampMs = new Map();
136
152
  }
137
153
  export class InMemoryPaymentReceiptStore {
138
154
  rows = new Map();
@@ -257,13 +273,102 @@ export class InMemoryPaymentPriceStore {
257
273
  return all;
258
274
  }
259
275
  }
276
+ export class InMemoryPaymentExceptionStore {
277
+ rows = new Map();
278
+ async append(e) {
279
+ if (this.rows.has(e.id))
280
+ return null;
281
+ const row = {
282
+ ...e,
283
+ resolvedAtMs: null,
284
+ resolutionNote: null,
285
+ createdAt: nowIso(),
286
+ };
287
+ this.rows.set(row.id, row);
288
+ return row;
289
+ }
290
+ async getById(id) {
291
+ return this.rows.get(id) ?? null;
292
+ }
293
+ async listByPayment(paymentId) {
294
+ return [...this.rows.values()].filter((r) => r.paymentId === paymentId);
295
+ }
296
+ async list(opts = {}) {
297
+ let out = [...this.rows.values()].filter((r) => (opts.status === undefined || r.status === opts.status) &&
298
+ (opts.kind === undefined || r.kind === opts.kind) &&
299
+ (opts.sinceMs === undefined || r.createdAtMs >= opts.sinceMs));
300
+ out.sort((a, b) => b.createdAtMs - a.createdAtMs);
301
+ if (opts.limit !== undefined)
302
+ out = out.slice(0, opts.limit);
303
+ return out;
304
+ }
305
+ async resolve(id, status, note) {
306
+ const row = this.rows.get(id);
307
+ if (!row || row.status !== "OPEN")
308
+ return null;
309
+ const next = {
310
+ ...row,
311
+ status,
312
+ resolvedAtMs: Date.now(),
313
+ resolutionNote: note ?? null,
314
+ };
315
+ this.rows.set(id, next);
316
+ return next;
317
+ }
318
+ }
319
+ export class InMemoryUsageRecordStore {
320
+ rows = new Map();
321
+ async append(r) {
322
+ if (this.rows.has(r.id))
323
+ return null;
324
+ for (const x of this.rows.values()) {
325
+ if (x.requestId === r.requestId)
326
+ return null;
327
+ }
328
+ const row = {
329
+ ...r,
330
+ agentId: r.agentId ?? null,
331
+ currency: r.currency ?? "USDC",
332
+ txHash: r.txHash ?? null,
333
+ createdAt: nowIso(),
334
+ };
335
+ this.rows.set(row.id, row);
336
+ return row;
337
+ }
338
+ async getById(id) {
339
+ return this.rows.get(id) ?? null;
340
+ }
341
+ async getByRequestId(requestId) {
342
+ return ([...this.rows.values()].find((r) => r.requestId === requestId) ??
343
+ null);
344
+ }
345
+ async listByPayment(paymentId) {
346
+ return [...this.rows.values()]
347
+ .filter((r) => r.paymentId === paymentId)
348
+ .sort((a, b) => b.createdAtMs - a.createdAtMs);
349
+ }
350
+ async listByAgent(agentId, limit) {
351
+ const out = [...this.rows.values()]
352
+ .filter((r) => r.agentId === agentId)
353
+ .sort((a, b) => b.createdAtMs - a.createdAtMs);
354
+ return limit === undefined ? out : out.slice(0, limit);
355
+ }
356
+ async listByResource(resource, limit) {
357
+ const out = [...this.rows.values()]
358
+ .filter((r) => r.resource === resource)
359
+ .sort((a, b) => b.createdAtMs - a.createdAtMs);
360
+ return limit === undefined ? out : out.slice(0, limit);
361
+ }
362
+ }
260
363
  export function createInMemoryPaymentStores() {
261
364
  return {
262
365
  payments: new InMemoryPaymentStore(),
263
366
  attempts: new InMemoryPaymentAttemptStore(),
264
367
  receipts: new InMemoryPaymentReceiptStore(),
265
368
  events: new InMemoryPaymentEventStore(),
369
+ exceptions: new InMemoryPaymentExceptionStore(),
266
370
  products: new InMemoryPaymentProductStore(),
267
371
  prices: new InMemoryPaymentPriceStore(),
372
+ usageRecords: new InMemoryUsageRecordStore(),
268
373
  };
269
374
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",