@agentbadge/database 0.6.2 → 0.6.3

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.
@@ -0,0 +1,56 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import type { PrismaDb } from "./event-repository.js";
4
+ type Row = Models.public_AgentRequest;
5
+ type QaRow = Models.public_AgentQAPair;
6
+ export interface AgentRequestUpsert {
7
+ id: string;
8
+ state: string;
9
+ kind?: string | null;
10
+ payload?: JsonValue | null;
11
+ fingerprint: JsonValue;
12
+ fpHash: string;
13
+ agentId?: string | null;
14
+ verified?: boolean;
15
+ response?: JsonValue | null;
16
+ spamFlag?: boolean;
17
+ idempotencyKey?: string | null;
18
+ expiresAtMs: number;
19
+ createdAtMs: number;
20
+ respondedAtMs?: number | null;
21
+ }
22
+ export interface AgentQAPairUpsert {
23
+ id: string;
24
+ questionHash: string;
25
+ question: string;
26
+ response: JsonValue;
27
+ sourceRequestId: string;
28
+ createdAtMs: number;
29
+ }
30
+ export declare class AgentRequestRepository {
31
+ private readonly db;
32
+ constructor(db: PrismaDb);
33
+ put(r: AgentRequestUpsert): Promise<Row>;
34
+ get(id: string): Promise<Row | null>;
35
+ findByIdempotency(idempotencyKey: string, fpHash: string): Promise<Row | null>;
36
+ listByState(opts?: {
37
+ state?: string;
38
+ sinceMs?: number;
39
+ limit?: number;
40
+ }): Promise<Row[]>;
41
+ transition(id: string, from: string, to: string, patch?: {
42
+ response?: JsonValue | null;
43
+ respondedAtMs?: number | null;
44
+ spamFlag?: boolean;
45
+ state?: never;
46
+ }): Promise<Row | null>;
47
+ setSpamFlag(id: string, spamFlag: boolean): Promise<Row | null>;
48
+ listExpired(nowMs: number, limit?: number): Promise<Row[]>;
49
+ listPurgeable(cutoffMs: number, limit?: number): Promise<Row[]>;
50
+ purgePayload(id: string): Promise<boolean>;
51
+ delete(id: string): Promise<boolean>;
52
+ upsertQaPair(qa: AgentQAPairUpsert): Promise<QaRow>;
53
+ getQaByHash(questionHash: string): Promise<QaRow | null>;
54
+ searchQa(substring: string, limit?: number): Promise<QaRow[]>;
55
+ }
56
+ export {};
@@ -0,0 +1,145 @@
1
+ const toBig = (n) => BigInt(n);
2
+ const toBigOrNull = (n) => n == null ? null : BigInt(n);
3
+ const REQ_STATES_TERMINAL = ["completed", "failed"];
4
+ export class AgentRequestRepository {
5
+ db;
6
+ constructor(db) {
7
+ this.db = db;
8
+ }
9
+ async put(r) {
10
+ return this.db.orm.public.AgentRequest.upsert({
11
+ create: {
12
+ id: r.id,
13
+ state: r.state,
14
+ kind: r.kind ?? null,
15
+ payload: r.payload ?? null,
16
+ fingerprint: r.fingerprint,
17
+ fpHash: r.fpHash,
18
+ agentId: r.agentId ?? null,
19
+ verified: r.verified ?? false,
20
+ response: r.response ?? null,
21
+ spamFlag: r.spamFlag ?? false,
22
+ idempotencyKey: r.idempotencyKey ?? null,
23
+ expiresAtMs: toBig(r.expiresAtMs),
24
+ createdAtMs: toBig(r.createdAtMs),
25
+ respondedAtMs: toBigOrNull(r.respondedAtMs),
26
+ },
27
+ update: {
28
+ state: r.state,
29
+ kind: r.kind ?? null,
30
+ payload: r.payload ?? null,
31
+ fingerprint: r.fingerprint,
32
+ agentId: r.agentId ?? null,
33
+ verified: r.verified ?? false,
34
+ response: r.response ?? null,
35
+ spamFlag: r.spamFlag ?? false,
36
+ respondedAtMs: toBigOrNull(r.respondedAtMs),
37
+ },
38
+ conflictOn: { id: r.id },
39
+ });
40
+ }
41
+ async get(id) {
42
+ return this.db.orm.public.AgentRequest.where({ id }).first();
43
+ }
44
+ async findByIdempotency(idempotencyKey, fpHash) {
45
+ return this.db.orm.public.AgentRequest.where({
46
+ idempotencyKey,
47
+ fpHash,
48
+ }).first();
49
+ }
50
+ async listByState(opts) {
51
+ let q = this.db.orm.public.AgentRequest.orderBy((r) => r.createdAtMs.desc());
52
+ if (opts?.state !== undefined)
53
+ q = q.where({ state: opts.state });
54
+ const rows = await q.limit(opts?.limit ?? 500).all();
55
+ return opts?.sinceMs === undefined
56
+ ? rows
57
+ : rows.filter((r) => Number(r.createdAtMs) >= opts.sinceMs);
58
+ }
59
+ async transition(id, from, to, patch) {
60
+ const row = await this.db.orm.public.AgentRequest.where({
61
+ id,
62
+ state: from,
63
+ }).update({
64
+ state: to,
65
+ ...(patch?.response !== undefined ? { response: patch.response } : {}),
66
+ ...(patch?.respondedAtMs !== undefined
67
+ ? { respondedAtMs: toBigOrNull(patch.respondedAtMs) }
68
+ : {}),
69
+ ...(patch?.spamFlag !== undefined ? { spamFlag: patch.spamFlag } : {}),
70
+ });
71
+ return row;
72
+ }
73
+ async setSpamFlag(id, spamFlag) {
74
+ return this.db.orm.public.AgentRequest.where({ id }).update({
75
+ spamFlag,
76
+ });
77
+ }
78
+ async listExpired(nowMs, limit = 500) {
79
+ const rows = await this.db.orm.public.AgentRequest.orderBy((r) => r.expiresAtMs.asc())
80
+ .limit(limit)
81
+ .all();
82
+ return rows.filter((r) => Number(r.expiresAtMs) < nowMs);
83
+ }
84
+ async listPurgeable(cutoffMs, limit = 500) {
85
+ const out = [];
86
+ for (const state of REQ_STATES_TERMINAL) {
87
+ const rows = await this.db.orm.public.AgentRequest.where({
88
+ state,
89
+ })
90
+ .orderBy((r) => r.createdAtMs.asc())
91
+ .limit(limit)
92
+ .all();
93
+ for (const r of rows) {
94
+ if (r.payload !== null && Number(r.createdAtMs) < cutoffMs) {
95
+ out.push(r);
96
+ }
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+ async purgePayload(id) {
102
+ const row = await this.db.orm.public.AgentRequest.where({
103
+ id,
104
+ }).update({ payload: null });
105
+ return row !== null;
106
+ }
107
+ async delete(id) {
108
+ return ((await this.db.orm.public.AgentRequest.where({ id }).delete()) !==
109
+ null);
110
+ }
111
+ async upsertQaPair(qa) {
112
+ const existing = await this.db.orm.public.AgentQAPair.where({
113
+ questionHash: qa.questionHash,
114
+ }).first();
115
+ if (existing) {
116
+ const updated = await this.db.orm.public.AgentQAPair.where({
117
+ id: existing.id,
118
+ }).update({ uses: existing.uses + 1 });
119
+ return updated ?? existing;
120
+ }
121
+ return this.db.orm.public.AgentQAPair.create({
122
+ id: qa.id,
123
+ questionHash: qa.questionHash,
124
+ question: qa.question,
125
+ response: qa.response,
126
+ sourceRequestId: qa.sourceRequestId,
127
+ uses: 0,
128
+ createdAtMs: BigInt(qa.createdAtMs),
129
+ });
130
+ }
131
+ async getQaByHash(questionHash) {
132
+ return this.db.orm.public.AgentQAPair.where({
133
+ questionHash,
134
+ }).first();
135
+ }
136
+ async searchQa(substring, limit = 50) {
137
+ const needle = substring.toLowerCase();
138
+ const rows = await this.db.orm.public.AgentQAPair.orderBy((r) => r.createdAtMs.desc())
139
+ .limit(500)
140
+ .all();
141
+ return rows
142
+ .filter((r) => r.question.toLowerCase().includes(needle))
143
+ .slice(0, limit);
144
+ }
145
+ }
@@ -0,0 +1,37 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ import type { Models } from "../prisma/contract.d.js";
3
+ import type { PrismaDb } from "./event-repository.js";
4
+ type SurveyRow = Models.public_AgentSurvey;
5
+ type AnswerRow = Models.public_SurveyAnswer;
6
+ export interface AgentSurveyUpsert {
7
+ id: string;
8
+ title: string;
9
+ questions: JsonValue;
10
+ active?: boolean;
11
+ closesAtMs?: number | null;
12
+ createdAtMs: number;
13
+ }
14
+ export interface SurveyAnswerUpsert {
15
+ id: string;
16
+ surveyId: string;
17
+ agentId?: string | null;
18
+ fpHash?: string | null;
19
+ answers: JsonValue;
20
+ rated?: boolean;
21
+ createdAtMs: number;
22
+ }
23
+ export declare class AgentSurveyRepository {
24
+ private readonly db;
25
+ constructor(db: PrismaDb);
26
+ putSurvey(s: AgentSurveyUpsert): Promise<SurveyRow>;
27
+ getSurvey(id: string): Promise<SurveyRow | null>;
28
+ listOpenSurveys(nowMs: number, limit?: number): Promise<SurveyRow[]>;
29
+ setSurveyActive(id: string, active: boolean): Promise<SurveyRow | null>;
30
+ putAnswer(a: SurveyAnswerUpsert): Promise<AnswerRow>;
31
+ getAnswer(id: string): Promise<AnswerRow | null>;
32
+ findAnswerByAgent(surveyId: string, agentId: string): Promise<AnswerRow | null>;
33
+ findAnswerByFp(surveyId: string, fpHash: string): Promise<AnswerRow | null>;
34
+ listAnswers(surveyId: string, limit?: number): Promise<AnswerRow[]>;
35
+ markRated(id: string): Promise<boolean>;
36
+ }
37
+ export {};
@@ -0,0 +1,82 @@
1
+ const toBigOrNull = (n) => n == null ? null : BigInt(n);
2
+ export class AgentSurveyRepository {
3
+ db;
4
+ constructor(db) {
5
+ this.db = db;
6
+ }
7
+ async putSurvey(s) {
8
+ return this.db.orm.public.AgentSurvey.upsert({
9
+ create: {
10
+ id: s.id,
11
+ title: s.title,
12
+ questions: s.questions,
13
+ active: s.active ?? true,
14
+ closesAtMs: toBigOrNull(s.closesAtMs),
15
+ createdAtMs: BigInt(s.createdAtMs),
16
+ },
17
+ update: {
18
+ title: s.title,
19
+ questions: s.questions,
20
+ active: s.active ?? true,
21
+ closesAtMs: toBigOrNull(s.closesAtMs),
22
+ },
23
+ conflictOn: { id: s.id },
24
+ });
25
+ }
26
+ async getSurvey(id) {
27
+ return this.db.orm.public.AgentSurvey.where({ id }).first();
28
+ }
29
+ async listOpenSurveys(nowMs, limit = 50) {
30
+ const rows = await this.db.orm.public.AgentSurvey.where({
31
+ active: true,
32
+ })
33
+ .orderBy((s) => s.createdAtMs.desc())
34
+ .limit(limit)
35
+ .all();
36
+ return rows.filter((s) => s.closesAtMs === null || Number(s.closesAtMs) > nowMs);
37
+ }
38
+ async setSurveyActive(id, active) {
39
+ return this.db.orm.public.AgentSurvey.where({ id }).update({
40
+ active,
41
+ });
42
+ }
43
+ async putAnswer(a) {
44
+ return this.db.orm.public.SurveyAnswer.create({
45
+ id: a.id,
46
+ surveyId: a.surveyId,
47
+ agentId: a.agentId ?? null,
48
+ fpHash: a.fpHash ?? null,
49
+ answers: a.answers,
50
+ rated: a.rated ?? false,
51
+ createdAtMs: BigInt(a.createdAtMs),
52
+ });
53
+ }
54
+ async getAnswer(id) {
55
+ return this.db.orm.public.SurveyAnswer.where({ id }).first();
56
+ }
57
+ async findAnswerByAgent(surveyId, agentId) {
58
+ return this.db.orm.public.SurveyAnswer.where({
59
+ surveyId,
60
+ agentId,
61
+ }).first();
62
+ }
63
+ async findAnswerByFp(surveyId, fpHash) {
64
+ const rows = await this.db.orm.public.SurveyAnswer.where({
65
+ surveyId,
66
+ }).all();
67
+ return rows.find((r) => r.fpHash === fpHash && r.agentId === null) ?? null;
68
+ }
69
+ async listAnswers(surveyId, limit = 500) {
70
+ return this.db.orm.public.SurveyAnswer.where({ surveyId })
71
+ .orderBy((a) => a.createdAtMs.desc())
72
+ .limit(limit)
73
+ .all();
74
+ }
75
+ async markRated(id) {
76
+ const row = await this.db.orm.public.SurveyAnswer.where({
77
+ id,
78
+ rated: false,
79
+ }).update({ rated: true });
80
+ return row !== null;
81
+ }
82
+ }
@@ -1,5 +1,5 @@
1
1
  import type { PrismaDb } from "./event-repository.js";
2
- import type { AttemptStatusPatch, PaymentAttemptInsert, PaymentAttemptRow, PaymentAttemptStore, PaymentEventInsert, PaymentEventRow, PaymentEventStore, PaymentInsert, PaymentPriceInsert, PaymentPriceRow, PaymentPriceStore, PaymentProductInsert, PaymentProductRow, PaymentProductStore, PaymentReceiptInsert, PaymentReceiptRow, PaymentReceiptStore, PaymentRow, PaymentStore, PaymentStores } from "./payment-store.js";
2
+ import type { AttemptStatusPatch, PaymentAttemptInsert, PaymentAttemptRow, PaymentAttemptStore, PaymentEventInsert, PaymentEventRow, PaymentEventStore, PaymentExceptionInsert, PaymentExceptionRow, PaymentExceptionStore, PaymentInsert, PaymentPriceInsert, PaymentPriceRow, PaymentPriceStore, PaymentProductInsert, PaymentProductRow, PaymentProductStore, PaymentReceiptInsert, PaymentReceiptRow, PaymentReceiptStore, PaymentRow, PaymentStore, PaymentStores, UsageRecordInsert, UsageRecordRow, UsageRecordStore } from "./payment-store.js";
3
3
  export declare class PaymentRepository implements PaymentStore {
4
4
  private readonly db;
5
5
  constructor(db: PrismaDb);
@@ -24,6 +24,8 @@ export declare class PaymentAttemptRepository implements PaymentAttemptStore {
24
24
  getByTxHash(transactionHash: string): Promise<PaymentAttemptRow | null>;
25
25
  applyStatus(id: string, expectedFrom: string, to: string, _updatedAtMs: number, patch?: AttemptStatusPatch): Promise<PaymentAttemptRow | null>;
26
26
  listExpired(nowMs: number): Promise<PaymentAttemptRow[]>;
27
+ listPayable(nowMs: number): Promise<PaymentAttemptRow[]>;
28
+ listRecentTerminal(sinceMs: number): Promise<PaymentAttemptRow[]>;
27
29
  }
28
30
  export declare class PaymentReceiptRepository implements PaymentReceiptStore {
29
31
  private readonly db;
@@ -63,4 +65,30 @@ export declare class PaymentPriceRepository implements PaymentPriceStore {
63
65
  activeOnly?: boolean;
64
66
  }): Promise<PaymentPriceRow[]>;
65
67
  }
68
+ export declare class PaymentExceptionRepository implements PaymentExceptionStore {
69
+ private readonly db;
70
+ constructor(db: PrismaDb);
71
+ private get orm();
72
+ append(e: PaymentExceptionInsert): Promise<PaymentExceptionRow | null>;
73
+ getById(id: string): Promise<PaymentExceptionRow | null>;
74
+ listByPayment(paymentId: string): Promise<PaymentExceptionRow[]>;
75
+ list(opts?: {
76
+ status?: string;
77
+ kind?: string;
78
+ sinceMs?: number;
79
+ limit?: number;
80
+ }): Promise<PaymentExceptionRow[]>;
81
+ resolve(id: string, status: "RESOLVED" | "IGNORED", note?: string): Promise<PaymentExceptionRow | null>;
82
+ }
83
+ export declare class UsageRecordRepository implements UsageRecordStore {
84
+ private readonly db;
85
+ constructor(db: PrismaDb);
86
+ private get orm();
87
+ append(r: UsageRecordInsert): Promise<UsageRecordRow | null>;
88
+ getById(id: string): Promise<UsageRecordRow | null>;
89
+ getByRequestId(requestId: string): Promise<UsageRecordRow | null>;
90
+ listByPayment(paymentId: string): Promise<UsageRecordRow[]>;
91
+ listByAgent(agentId: string, limit?: number): Promise<UsageRecordRow[]>;
92
+ listByResource(resource: string, limit?: number): Promise<UsageRecordRow[]>;
93
+ }
66
94
  export declare function createPrismaPaymentStores(db: PrismaDb): PaymentStores;
@@ -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;