@agentbadge/database 0.6.15 → 0.6.17

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.
@@ -14,6 +14,7 @@ export interface AgentRequestUpsert {
14
14
  verified?: boolean;
15
15
  response?: JsonValue | null;
16
16
  spamFlag?: boolean;
17
+ publishToQa?: boolean;
17
18
  idempotencyKey?: string | null;
18
19
  expiresAtMs: number;
19
20
  createdAtMs: number;
@@ -50,6 +51,7 @@ export declare class AgentRequestRepository {
50
51
  purgePayload(id: string): Promise<boolean>;
51
52
  delete(id: string): Promise<boolean>;
52
53
  upsertQaPair(qa: AgentQAPairUpsert): Promise<QaRow>;
54
+ retractQaPair(id: string, reason: string, retractedAtMs: number): Promise<QaRow | null>;
53
55
  getQaByHash(questionHash: string): Promise<QaRow | null>;
54
56
  searchQa(substring: string, limit?: number): Promise<QaRow[]>;
55
57
  }
@@ -19,6 +19,7 @@ export class AgentRequestRepository {
19
19
  verified: r.verified ?? false,
20
20
  response: r.response ?? null,
21
21
  spamFlag: r.spamFlag ?? false,
22
+ publishToQa: r.publishToQa ?? false,
22
23
  idempotencyKey: r.idempotencyKey ?? null,
23
24
  expiresAtMs: toBig(r.expiresAtMs),
24
25
  createdAtMs: toBig(r.createdAtMs),
@@ -128,10 +129,24 @@ export class AgentRequestRepository {
128
129
  createdAtMs: BigInt(qa.createdAtMs),
129
130
  });
130
131
  }
132
+ async retractQaPair(id, reason, retractedAtMs) {
133
+ const existing = await this.db.orm.public.AgentQAPair.where({
134
+ id,
135
+ }).first();
136
+ if (!existing)
137
+ return null;
138
+ if (existing.retractedAtMs != null)
139
+ return existing;
140
+ return this.db.orm.public.AgentQAPair.where({ id }).update({
141
+ retractedAtMs: BigInt(retractedAtMs),
142
+ retractReason: reason,
143
+ });
144
+ }
131
145
  async getQaByHash(questionHash) {
132
- return this.db.orm.public.AgentQAPair.where({
146
+ const row = await this.db.orm.public.AgentQAPair.where({
133
147
  questionHash,
134
148
  }).first();
149
+ return row != null && row.retractedAtMs == null ? row : null;
135
150
  }
136
151
  async searchQa(substring, limit = 50) {
137
152
  const needle = substring.toLowerCase();
@@ -139,7 +154,8 @@ export class AgentRequestRepository {
139
154
  .limit(500)
140
155
  .all();
141
156
  return rows
142
- .filter((r) => r.question.toLowerCase().includes(needle))
157
+ .filter((r) => r.retractedAtMs == null &&
158
+ r.question.toLowerCase().includes(needle))
143
159
  .slice(0, limit);
144
160
  }
145
161
  }
@@ -1,5 +1,6 @@
1
1
  import type { PrismaDb } from "./event-repository.js";
2
2
  import type { AdminActionInsert, AdminActionRow, AdminActionStore, FinopsStores, ReconciliationExceptionInsert, ReconciliationExceptionRow, ReconciliationExceptionStore, RefundIntentInsert, RefundIntentRow, RefundIntentStore } from "./finops-store.js";
3
+ export declare const decimalFromDb: (v: unknown) => string;
3
4
  export declare class AdminActionRepository implements AdminActionStore {
4
5
  private readonly db;
5
6
  constructor(db: PrismaDb);
@@ -21,10 +22,13 @@ export declare class RefundIntentRepository implements RefundIntentStore {
21
22
  private get orm();
22
23
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
23
24
  getById(id: string): Promise<RefundIntentRow | null>;
25
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
24
26
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
25
27
  list(opts?: {
26
28
  status?: string;
27
29
  limit?: number;
30
+ completedSinceMs?: number;
31
+ completedUntilMs?: number;
28
32
  }): Promise<RefundIntentRow[]>;
29
33
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
30
34
  }
@@ -1,6 +1,27 @@
1
+ function isUniqueViolation(e) {
2
+ if (e === null || typeof e !== "object")
3
+ return false;
4
+ const code = e.code;
5
+ if (code === "23505")
6
+ return true;
7
+ const msg = e instanceof Error ? e.message : String(e);
8
+ return /unique constraint|duplicate key/i.test(msg);
9
+ }
1
10
  const num = (v) => Number(v);
2
11
  const numOrNull = (v) => v === null || v === undefined ? null : Number(v);
3
- const dec = (v) => String(v);
12
+ export const decimalFromDb = (v) => {
13
+ const s = String(v);
14
+ if (/[eE]/.test(s))
15
+ throw new Error(`exponent form from DB: ${s}`);
16
+ const m = /^(-?\d+)(?:\.(\d+))?$/.exec(s);
17
+ if (!m)
18
+ throw new Error(`non-canonical decimal from DB: ${s}`);
19
+ const frac = (m[2] ?? "").replace(/0+$/, "");
20
+ if (frac.length > 6) {
21
+ throw new Error(`decimal exceeds 6dp scale from DB: ${s}`);
22
+ }
23
+ return frac ? `${m[1]}.${frac}` : m[1];
24
+ };
4
25
  const toActionRow = (r) => ({
5
26
  id: r.id,
6
27
  action: r.action,
@@ -15,7 +36,7 @@ const toRefundRow = (r) => ({
15
36
  id: r.id,
16
37
  paymentId: r.paymentId,
17
38
  payee: r.payee,
18
- amount: dec(r.amount),
39
+ amount: decimalFromDb(r.amount),
19
40
  currency: r.currency,
20
41
  reason: r.reason,
21
42
  evidence: r.evidence ?? undefined,
@@ -116,7 +137,7 @@ export class RefundIntentRepository {
116
137
  status: r.status,
117
138
  operator: r.operator,
118
139
  createdAtMs: BigInt(r.createdAtMs),
119
- payload: (r.payload ?? null),
140
+ payload: (r.payload ?? {}),
120
141
  });
121
142
  return toRefundRow(row);
122
143
  }
@@ -124,6 +145,10 @@ export class RefundIntentRepository {
124
145
  const r = await this.orm.where({ id }).first();
125
146
  return r ? toRefundRow(r) : null;
126
147
  }
148
+ async getByTxHash(txHash) {
149
+ const r = await this.orm.where({ txHash }).first();
150
+ return r ? toRefundRow(r) : null;
151
+ }
127
152
  async listByPayment(paymentId) {
128
153
  const rows = await this.orm
129
154
  .orderBy((e) => e.createdAtMs.desc())
@@ -134,18 +159,31 @@ export class RefundIntentRepository {
134
159
  async list(opts = {}) {
135
160
  const q = this.orm.orderBy((e) => e.createdAtMs.desc());
136
161
  const scoped = opts.status !== undefined ? q.where({ status: opts.status }) : q;
137
- const rows = opts.limit !== undefined
138
- ? await scoped.limit(opts.limit).all()
139
- : await scoped.all();
140
- return rows.map(toRefundRow);
162
+ let rows = (await scoped.all())
163
+ .map(toRefundRow)
164
+ .filter((r) => (opts.completedSinceMs === undefined ||
165
+ (r.completedAtMs ?? 0) >= opts.completedSinceMs) &&
166
+ (opts.completedUntilMs === undefined ||
167
+ (r.completedAtMs ?? 0) <= opts.completedUntilMs));
168
+ if (opts.limit !== undefined)
169
+ rows = rows.slice(0, opts.limit);
170
+ return rows;
141
171
  }
142
172
  async complete(id, txHash, completedBy, completedAtMs) {
143
- const row = await this.orm.where({ id, status: "OPEN" }).update({
144
- status: "COMPLETED",
145
- txHash,
146
- completedBy,
147
- completedAtMs: BigInt(completedAtMs),
148
- });
173
+ let row;
174
+ try {
175
+ row = await this.orm.where({ id, status: "OPEN" }).update({
176
+ status: "COMPLETED",
177
+ txHash,
178
+ completedBy,
179
+ completedAtMs: BigInt(completedAtMs),
180
+ });
181
+ }
182
+ catch (e) {
183
+ if (isUniqueViolation(e))
184
+ return null;
185
+ throw e;
186
+ }
149
187
  return row ? toRefundRow(row) : null;
150
188
  }
151
189
  }
@@ -1,5 +1,5 @@
1
1
  import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
- export declare const ADMIN_ACTIONS: readonly ["REVIEW", "RETRY_VERIFY", "MARK_EXTERNAL_REVIEWED", "REFUND", "RESOLVE_EXCEPTION"];
2
+ export declare const ADMIN_ACTIONS: readonly ["REVIEW", "RETRY_VERIFY", "MARK_EXTERNAL_REVIEWED", "REFUND", "RESOLVE_EXCEPTION", "DETECT_EXCEPTIONS"];
3
3
  export type AdminActionKind = (typeof ADMIN_ACTIONS)[number];
4
4
  export interface AdminActionInsert {
5
5
  id: string;
@@ -48,10 +48,13 @@ export interface RefundIntentRow extends RefundIntentInsert {
48
48
  export interface RefundIntentStore {
49
49
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
50
50
  getById(id: string): Promise<RefundIntentRow | null>;
51
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
51
52
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
52
53
  list(opts?: {
53
54
  status?: string;
54
55
  limit?: number;
56
+ completedSinceMs?: number;
57
+ completedUntilMs?: number;
55
58
  }): Promise<RefundIntentRow[]>;
56
59
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
57
60
  }
@@ -107,10 +110,13 @@ export declare class InMemoryRefundIntentStore implements RefundIntentStore {
107
110
  private readonly rows;
108
111
  create(r: RefundIntentInsert): Promise<RefundIntentRow | null>;
109
112
  getById(id: string): Promise<RefundIntentRow | null>;
113
+ getByTxHash(txHash: string): Promise<RefundIntentRow | null>;
110
114
  listByPayment(paymentId: string): Promise<RefundIntentRow[]>;
111
115
  list(opts?: {
112
116
  status?: string;
113
117
  limit?: number;
118
+ completedSinceMs?: number;
119
+ completedUntilMs?: number;
114
120
  }): Promise<RefundIntentRow[]>;
115
121
  complete(id: string, txHash: string, completedBy: string, completedAtMs: number): Promise<RefundIntentRow | null>;
116
122
  }
@@ -4,6 +4,7 @@ export const ADMIN_ACTIONS = [
4
4
  "MARK_EXTERNAL_REVIEWED",
5
5
  "REFUND",
6
6
  "RESOLVE_EXCEPTION",
7
+ "DETECT_EXCEPTIONS",
7
8
  ];
8
9
  export const RECONCILIATION_EXCEPTION_TYPES = [
9
10
  "AMOUNT_MISMATCH",
@@ -71,13 +72,24 @@ export class InMemoryRefundIntentStore {
71
72
  async getById(id) {
72
73
  return this.rows.get(id) ?? null;
73
74
  }
75
+ async getByTxHash(txHash) {
76
+ for (const r of this.rows.values()) {
77
+ if (r.txHash === txHash)
78
+ return r;
79
+ }
80
+ return null;
81
+ }
74
82
  async listByPayment(paymentId) {
75
83
  return [...this.rows.values()]
76
84
  .filter((r) => r.paymentId === paymentId)
77
85
  .sort((a, b) => b.createdAtMs - a.createdAtMs);
78
86
  }
79
87
  async list(opts = {}) {
80
- let out = [...this.rows.values()].filter((r) => opts.status === undefined || r.status === opts.status);
88
+ let out = [...this.rows.values()].filter((r) => (opts.status === undefined || r.status === opts.status) &&
89
+ (opts.completedSinceMs === undefined ||
90
+ (r.completedAtMs ?? 0) >= opts.completedSinceMs) &&
91
+ (opts.completedUntilMs === undefined ||
92
+ (r.completedAtMs ?? 0) <= opts.completedUntilMs));
81
93
  out.sort((a, b) => b.createdAtMs - a.createdAtMs);
82
94
  if (opts.limit !== undefined)
83
95
  out = out.slice(0, opts.limit);
@@ -87,6 +99,10 @@ export class InMemoryRefundIntentStore {
87
99
  const row = this.rows.get(id);
88
100
  if (!row || row.status !== "OPEN")
89
101
  return null;
102
+ for (const r of this.rows.values()) {
103
+ if (r.id !== id && r.txHash === txHash)
104
+ return null;
105
+ }
90
106
  const next = {
91
107
  ...row,
92
108
  status: "COMPLETED",
@@ -0,0 +1,84 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ import type { PrismaDb } from "./event-repository.js";
3
+ import type { DisputeInsert, DisputeRow, DisputeStore, MilestoneInsert, MilestonePlanInsert, MilestonePlanRow, MilestonePlanStore, MilestoneRow, MilestoneStatusPatch, MilestoneStore, PayoutIntentInsert, PayoutIntentRow, PayoutIntentStatusPatch, PayoutIntentStore, PayoutLegInsert, PayoutLegRow, PayoutLegStore, SettlementAnchorInsert, SettlementAnchorRow, SettlementAnchorStore, SettlementStores } from "./settlement-store.js";
4
+ export declare class MilestonePlanRepository implements MilestonePlanStore {
5
+ private readonly db;
6
+ constructor(db: PrismaDb);
7
+ private get orm();
8
+ create(p: MilestonePlanInsert): Promise<MilestonePlanRow | null>;
9
+ getById(id: string): Promise<MilestonePlanRow | null>;
10
+ getByAgreement(agreementRef: string): Promise<MilestonePlanRow | null>;
11
+ list(opts?: {
12
+ status?: string;
13
+ buyerWallet?: string;
14
+ providerWallet?: string;
15
+ limit?: number;
16
+ }): Promise<MilestonePlanRow[]>;
17
+ applyStatus(id: string, expectedFrom: string, to: string): Promise<MilestonePlanRow | null>;
18
+ }
19
+ export declare class MilestoneRepository implements MilestoneStore {
20
+ private readonly db;
21
+ constructor(db: PrismaDb);
22
+ private get orm();
23
+ create(m: MilestoneInsert): Promise<MilestoneRow | null>;
24
+ getById(id: string): Promise<MilestoneRow | null>;
25
+ getByPlanMilestone(planId: string, milestoneId: string): Promise<MilestoneRow | null>;
26
+ listByPlan(planId: string): Promise<MilestoneRow[]>;
27
+ applyStatus(id: string, expectedFrom: string, to: string, patch?: MilestoneStatusPatch): Promise<MilestoneRow | null>;
28
+ }
29
+ export declare class PayoutIntentRepository implements PayoutIntentStore {
30
+ private readonly db;
31
+ constructor(db: PrismaDb);
32
+ private get orm();
33
+ create(i: PayoutIntentInsert): Promise<PayoutIntentRow | null>;
34
+ getById(id: string): Promise<PayoutIntentRow | null>;
35
+ getByMilestone(milestoneRef: string): Promise<PayoutIntentRow | null>;
36
+ list(opts?: {
37
+ status?: string;
38
+ limit?: number;
39
+ }): Promise<PayoutIntentRow[]>;
40
+ applyStatus(id: string, expectedFrom: string, to: string, patch?: PayoutIntentStatusPatch): Promise<PayoutIntentRow | null>;
41
+ }
42
+ export declare class PayoutLegRepository implements PayoutLegStore {
43
+ private readonly db;
44
+ constructor(db: PrismaDb);
45
+ private get orm();
46
+ create(l: PayoutLegInsert): Promise<PayoutLegRow | null>;
47
+ getById(id: string): Promise<PayoutLegRow | null>;
48
+ getByTxHash(network: string, txHash: string): Promise<PayoutLegRow | null>;
49
+ listByIntent(intentId: string): Promise<PayoutLegRow[]>;
50
+ complete(id: string, expectedFrom: string, txHash: string, completedBy: string, completedAtMs: number): Promise<PayoutLegRow | null>;
51
+ applyStatus(id: string, expectedFrom: string, to: string): Promise<PayoutLegRow | null>;
52
+ }
53
+ export declare class DisputeRepository implements DisputeStore {
54
+ private readonly db;
55
+ constructor(db: PrismaDb);
56
+ private get orm();
57
+ create(d: DisputeInsert): Promise<DisputeRow | null>;
58
+ getById(id: string): Promise<DisputeRow | null>;
59
+ listBySubject(subjectType: string, subjectRef: string): Promise<DisputeRow[]>;
60
+ list(opts?: {
61
+ status?: string;
62
+ limit?: number;
63
+ }): Promise<DisputeRow[]>;
64
+ resolve(id: string, resolution: string, resolvedBy: string, resolvedAtMs: number, extra?: {
65
+ splitAmounts?: JsonValue;
66
+ resolverRef?: string | null;
67
+ }): Promise<DisputeRow | null>;
68
+ }
69
+ export declare class SettlementAnchorRepository implements SettlementAnchorStore {
70
+ private readonly db;
71
+ constructor(db: PrismaDb);
72
+ private get orm();
73
+ create(a: SettlementAnchorInsert): Promise<SettlementAnchorRow | null>;
74
+ getById(id: string): Promise<SettlementAnchorRow | null>;
75
+ getByReceiptRef(receiptRef: string): Promise<SettlementAnchorRow | null>;
76
+ list(opts?: {
77
+ status?: string;
78
+ statuses?: readonly string[];
79
+ limit?: number;
80
+ }): Promise<SettlementAnchorRow[]>;
81
+ markAnchored(id: string, txHash: string, anchoredAtMs: number): Promise<SettlementAnchorRow | null>;
82
+ markAttempt(id: string, lastError: string | null, failed: boolean): Promise<SettlementAnchorRow | null>;
83
+ }
84
+ export declare function createPrismaSettlementStores(db: PrismaDb): SettlementStores;