@agentbadge/database 0.6.19 → 0.6.22

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,95 @@
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 SessionRow = Models.public_InteractionSession;
6
+ type ResponseRow = Models.public_InteractionResponse;
7
+ type EventRow = Models.public_InteractionEvent;
8
+ export interface InteractionSubmit {
9
+ id: string;
10
+ state: string;
11
+ kind?: string | null;
12
+ payload: JsonValue;
13
+ fingerprint: JsonValue;
14
+ fpHash: string;
15
+ agentId?: string | null;
16
+ verified?: boolean;
17
+ publishToQa?: boolean;
18
+ idempotencyKey?: string | null;
19
+ expiresAtMs: number;
20
+ createdAtMs: number;
21
+ actorResolution: string;
22
+ actorRef?: string | null;
23
+ sessionId?: string | null;
24
+ channel: string;
25
+ }
26
+ export interface InteractionEventInput {
27
+ id?: string;
28
+ kind: string;
29
+ visibility: string;
30
+ payload: JsonValue;
31
+ createdAtMs?: number;
32
+ }
33
+ export interface InteractionClassifyPatch {
34
+ intent?: string | null;
35
+ signalType?: string | null;
36
+ outcome?: string | null;
37
+ knowledgeGap?: boolean;
38
+ topics?: JsonValue | null;
39
+ entities?: JsonValue | null;
40
+ demandSignals?: JsonValue | null;
41
+ classifiedBy?: string | null;
42
+ }
43
+ export interface InteractionResponseInsert {
44
+ id: string;
45
+ requestId: string;
46
+ operatorRef: string;
47
+ body: string;
48
+ createdAtMs: number;
49
+ }
50
+ export declare class InteractionRepository {
51
+ private readonly db;
52
+ constructor(db: PrismaDb);
53
+ get(id: string): Promise<Row | null>;
54
+ findByIdempotency(idempotencyKey: string, fpHash: string): Promise<Row | null>;
55
+ submitInteraction(input: InteractionSubmit, events: InteractionEventInput[]): Promise<{
56
+ row: Row;
57
+ duplicate: boolean;
58
+ }>;
59
+ classify(id: string, patch: InteractionClassifyPatch, events: InteractionEventInput[], nowMs: number): Promise<{
60
+ row: Row;
61
+ transitioned: boolean;
62
+ } | null>;
63
+ respond(id: string, response: InteractionResponseInsert, events: InteractionEventInput[], nowMs: number): Promise<{
64
+ row: Row | null;
65
+ transitioned: boolean;
66
+ }>;
67
+ reject(id: string, events: InteractionEventInput[], nowMs: number): Promise<{
68
+ row: Row | null;
69
+ transitioned: boolean;
70
+ }>;
71
+ listQueue(opts?: {
72
+ state?: string;
73
+ actorResolution?: string;
74
+ limit?: number;
75
+ beforeMs?: number;
76
+ }): Promise<Row[]>;
77
+ listBySession(sessionId: string, limit?: number): Promise<Row[]>;
78
+ getSession(id: string): Promise<SessionRow | null>;
79
+ upsertSession(input: {
80
+ id: string;
81
+ actorRef?: string | null;
82
+ seenAtMs: number;
83
+ }): Promise<{
84
+ session: SessionRow;
85
+ created: boolean;
86
+ }>;
87
+ private touchSessionTx;
88
+ listResponses(requestId: string): Promise<ResponseRow[]>;
89
+ appendEvents(requestId: string, events: InteractionEventInput[], nowMs: number): Promise<EventRow[]>;
90
+ private appendEventsTx;
91
+ listEvents(requestId: string, opts?: {
92
+ visibility?: string;
93
+ }): Promise<EventRow[]>;
94
+ }
95
+ export {};
@@ -0,0 +1,291 @@
1
+ import { param } from "@prisma/orm-postgres/relational-core/expression";
2
+ const TERMINAL = new Set(["completed", "failed"]);
3
+ const toBig = (n) => BigInt(n);
4
+ const toBigOrNull = (n) => n == null ? null : BigInt(n);
5
+ function isUniqueViolation(err) {
6
+ const m = err instanceof Error ? err.message : String(err);
7
+ return /unique|duplicate/i.test(m);
8
+ }
9
+ export class InteractionRepository {
10
+ db;
11
+ constructor(db) {
12
+ this.db = db;
13
+ }
14
+ async get(id) {
15
+ return this.db.orm.public.AgentRequest.where({ id }).first();
16
+ }
17
+ async findByIdempotency(idempotencyKey, fpHash) {
18
+ return this.db.orm.public.AgentRequest.where({
19
+ idempotencyKey,
20
+ fpHash,
21
+ }).first();
22
+ }
23
+ async submitInteraction(input, events) {
24
+ if (input.idempotencyKey) {
25
+ const existing = await this.findByIdempotency(input.idempotencyKey, input.fpHash);
26
+ if (existing)
27
+ return { row: existing, duplicate: true };
28
+ }
29
+ try {
30
+ const row = await this.db.transaction(async (tx) => {
31
+ const r = await tx.orm.public.AgentRequest.create({
32
+ id: input.id,
33
+ state: input.state,
34
+ kind: input.kind ?? null,
35
+ payload: input.payload,
36
+ fingerprint: input.fingerprint,
37
+ fpHash: input.fpHash,
38
+ agentId: input.agentId ?? null,
39
+ verified: input.verified ?? false,
40
+ response: null,
41
+ spamFlag: false,
42
+ publishToQa: input.publishToQa ?? false,
43
+ idempotencyKey: input.idempotencyKey ?? null,
44
+ expiresAtMs: toBig(input.expiresAtMs),
45
+ createdAtMs: toBig(input.createdAtMs),
46
+ respondedAtMs: null,
47
+ actorResolution: input.actorResolution,
48
+ actorRef: input.actorRef ?? null,
49
+ sessionId: input.sessionId ?? null,
50
+ channel: input.channel,
51
+ intent: null,
52
+ signalType: null,
53
+ outcome: null,
54
+ knowledgeGap: false,
55
+ topics: null,
56
+ entities: null,
57
+ demandSignals: null,
58
+ classifiedBy: null,
59
+ });
60
+ await this.appendEventsTx(tx.orm, r.id, events, input.createdAtMs);
61
+ if (input.sessionId) {
62
+ await this.touchSessionTx(tx.orm, {
63
+ id: input.sessionId,
64
+ actorRef: input.actorRef ?? null,
65
+ seenAtMs: input.createdAtMs,
66
+ });
67
+ }
68
+ return r;
69
+ });
70
+ return { row, duplicate: false };
71
+ }
72
+ catch (err) {
73
+ if (isUniqueViolation(err) && input.idempotencyKey) {
74
+ const existing = await this.findByIdempotency(input.idempotencyKey, input.fpHash);
75
+ if (existing)
76
+ return { row: existing, duplicate: true };
77
+ }
78
+ throw err;
79
+ }
80
+ }
81
+ async classify(id, patch, events, nowMs) {
82
+ for (let attempt = 0; attempt < 3; attempt += 1) {
83
+ const out = await this.db.transaction(async (tx) => {
84
+ const cur = await tx.orm.public.AgentRequest.where({ id }).first();
85
+ if (!cur)
86
+ return null;
87
+ const update = {};
88
+ if (patch.intent !== undefined)
89
+ update.intent = patch.intent;
90
+ if (patch.signalType !== undefined)
91
+ update.signalType = patch.signalType;
92
+ if (patch.outcome !== undefined)
93
+ update.outcome = patch.outcome;
94
+ if (patch.knowledgeGap !== undefined)
95
+ update.knowledgeGap = patch.knowledgeGap;
96
+ if (patch.topics !== undefined)
97
+ update.topics = patch.topics;
98
+ if (patch.entities !== undefined)
99
+ update.entities = patch.entities;
100
+ if (patch.demandSignals !== undefined)
101
+ update.demandSignals = patch.demandSignals;
102
+ if (patch.classifiedBy !== undefined)
103
+ update.classifiedBy = patch.classifiedBy;
104
+ const transitioned = cur.state === "submitted";
105
+ if (transitioned) {
106
+ const stats = await tx.execute(this.db.raw
107
+ .sql `UPDATE "agentRequest" SET "state" = 'working' WHERE "id" = ${param(id, { codecId: "pg/text@1" })} AND "state" = 'submitted'`
108
+ .affectedCount()
109
+ .build());
110
+ if (stats.affectedRows === 0)
111
+ return { raced: true };
112
+ }
113
+ const row = await tx.orm.public.AgentRequest.where({
114
+ id,
115
+ }).update(update);
116
+ if (!row)
117
+ return { raced: true };
118
+ await this.appendEventsTx(tx.orm, id, events, nowMs);
119
+ return { row, transitioned, raced: false };
120
+ });
121
+ if (out === null)
122
+ return null;
123
+ if (!out.raced)
124
+ return { row: out.row, transitioned: out.transitioned };
125
+ }
126
+ const cur = await this.get(id);
127
+ return cur ? { row: cur, transitioned: false } : null;
128
+ }
129
+ async respond(id, response, events, nowMs) {
130
+ for (let attempt = 0; attempt < 3; attempt += 1) {
131
+ const out = await this.db.transaction(async (tx) => {
132
+ const cur = await tx.orm.public.AgentRequest.where({ id }).first();
133
+ if (!cur)
134
+ return { row: null, transitioned: false, raced: false };
135
+ if (TERMINAL.has(cur.state)) {
136
+ return { row: cur, transitioned: false, raced: false };
137
+ }
138
+ const stats = await tx.execute(this.db.raw
139
+ .sql `UPDATE "agentRequest" SET "state" = 'completed', "response" = ${param({ answer: response.body }, { codecId: "pg/json@1" })}, "respondedAtMs" = ${param(BigInt(nowMs), { codecId: "pg/int8@1" })} WHERE "id" = ${param(id, { codecId: "pg/text@1" })} AND "state" = ${param(cur.state, { codecId: "pg/text@1" })}`
140
+ .affectedCount()
141
+ .build());
142
+ if (stats.affectedRows === 0)
143
+ return { raced: true };
144
+ const row = await tx.orm.public.AgentRequest.where({ id }).first();
145
+ await tx.orm.public.InteractionResponse.create({
146
+ id: response.id,
147
+ requestId: response.requestId,
148
+ operatorRef: response.operatorRef,
149
+ body: response.body,
150
+ createdAtMs: BigInt(response.createdAtMs),
151
+ });
152
+ await this.appendEventsTx(tx.orm, id, events, nowMs);
153
+ return { row, transitioned: true, raced: false };
154
+ });
155
+ if (!out.raced) {
156
+ return { row: out.row ?? null, transitioned: out.transitioned ?? false };
157
+ }
158
+ }
159
+ const cur = await this.get(id);
160
+ return { row: cur, transitioned: false };
161
+ }
162
+ async reject(id, events, nowMs) {
163
+ for (let attempt = 0; attempt < 3; attempt += 1) {
164
+ const out = await this.db.transaction(async (tx) => {
165
+ const cur = await tx.orm.public.AgentRequest.where({ id }).first();
166
+ if (!cur)
167
+ return { row: null, transitioned: false, raced: false };
168
+ if (TERMINAL.has(cur.state)) {
169
+ return { row: cur, transitioned: false, raced: false };
170
+ }
171
+ const stats = await tx.execute(this.db.raw
172
+ .sql `UPDATE "agentRequest" SET "state" = 'failed' WHERE "id" = ${param(id, { codecId: "pg/text@1" })} AND "state" = ${param(cur.state, { codecId: "pg/text@1" })}`
173
+ .affectedCount()
174
+ .build());
175
+ if (stats.affectedRows === 0)
176
+ return { raced: true };
177
+ const row = await tx.orm.public.AgentRequest.where({ id }).first();
178
+ await this.appendEventsTx(tx.orm, id, events, nowMs);
179
+ return { row, transitioned: true, raced: false };
180
+ });
181
+ if (!out.raced) {
182
+ return { row: out.row ?? null, transitioned: out.transitioned ?? false };
183
+ }
184
+ }
185
+ const cur = await this.get(id);
186
+ return { row: cur, transitioned: false };
187
+ }
188
+ async listQueue(opts) {
189
+ let q = this.db.orm.public.AgentRequest.orderBy((r) => r.createdAtMs.asc());
190
+ if (opts?.state !== undefined)
191
+ q = q.where({ state: opts.state });
192
+ if (opts?.actorResolution !== undefined) {
193
+ q = q.where({ actorResolution: opts.actorResolution });
194
+ }
195
+ const rows = await q.limit(opts?.limit ?? 500).all();
196
+ return opts?.beforeMs === undefined
197
+ ? rows
198
+ : rows.filter((r) => Number(r.createdAtMs) < opts.beforeMs);
199
+ }
200
+ async listBySession(sessionId, limit = 100) {
201
+ return this.db.orm.public.AgentRequest.where({ sessionId })
202
+ .orderBy((r) => r.createdAtMs.asc())
203
+ .limit(limit)
204
+ .all();
205
+ }
206
+ async getSession(id) {
207
+ return this.db.orm.public.InteractionSession.where({ id }).first();
208
+ }
209
+ async upsertSession(input) {
210
+ try {
211
+ return await this.db.transaction(async (tx) => this.touchSessionTx(tx.orm, input));
212
+ }
213
+ catch (err) {
214
+ if (!isUniqueViolation(err))
215
+ throw err;
216
+ return this.db.transaction(async (tx) => this.touchSessionTx(tx.orm, input));
217
+ }
218
+ }
219
+ async touchSessionTx(orm, input) {
220
+ const cur = await orm.public.InteractionSession.where({
221
+ id: input.id,
222
+ }).first();
223
+ const seen = BigInt(input.seenAtMs);
224
+ if (!cur) {
225
+ const session = await orm.public.InteractionSession.create({
226
+ id: input.id,
227
+ actorRef: input.actorRef ?? null,
228
+ firstSeenAtMs: seen,
229
+ lastSeenAtMs: seen,
230
+ requestCount: 1,
231
+ });
232
+ return { session, created: true };
233
+ }
234
+ const update = {
235
+ lastSeenAtMs: seen,
236
+ requestCount: cur.requestCount + 1,
237
+ };
238
+ if (cur.actorRef == null && input.actorRef != null) {
239
+ update.actorRef = input.actorRef;
240
+ }
241
+ const session = await orm.public.InteractionSession.where({
242
+ id: input.id,
243
+ }).update(update);
244
+ return { session: session, created: false };
245
+ }
246
+ async listResponses(requestId) {
247
+ return this.db.orm.public.InteractionResponse.where({ requestId })
248
+ .orderBy((r) => r.createdAtMs.asc())
249
+ .all();
250
+ }
251
+ async appendEvents(requestId, events, nowMs) {
252
+ try {
253
+ return await this.db.transaction(async (tx) => this.appendEventsTx(tx.orm, requestId, events, nowMs));
254
+ }
255
+ catch (err) {
256
+ if (!isUniqueViolation(err))
257
+ throw err;
258
+ return this.db.transaction(async (tx) => this.appendEventsTx(tx.orm, requestId, events, nowMs));
259
+ }
260
+ }
261
+ async appendEventsTx(orm, requestId, events, nowMs) {
262
+ if (events.length === 0)
263
+ return [];
264
+ const existing = await orm.public.InteractionEvent.where({
265
+ requestId,
266
+ }).all();
267
+ let seq = existing.reduce((m, e) => Math.max(m, e.seq), 0);
268
+ const out = [];
269
+ for (const e of events) {
270
+ seq += 1;
271
+ out.push(await orm.public.InteractionEvent.create({
272
+ id: e.id ?? crypto.randomUUID(),
273
+ requestId,
274
+ seq,
275
+ kind: e.kind,
276
+ visibility: e.visibility,
277
+ payload: e.payload,
278
+ createdAtMs: BigInt(e.createdAtMs ?? nowMs),
279
+ }));
280
+ }
281
+ return out;
282
+ }
283
+ async listEvents(requestId, opts) {
284
+ const rows = await this.db.orm.public.InteractionEvent.where({ requestId })
285
+ .orderBy((e) => e.seq.asc())
286
+ .all();
287
+ return opts?.visibility === undefined
288
+ ? rows
289
+ : rows.filter((r) => r.visibility === opts.visibility);
290
+ }
291
+ }
@@ -15,6 +15,7 @@ export interface SpendApprovalUpsert {
15
15
  consumedAtMs?: number | null;
16
16
  expiresAtMs: number;
17
17
  createdAtMs: number;
18
+ dealFingerprint?: string | null;
18
19
  payload: JsonValue;
19
20
  }
20
21
  export declare class SpendApprovalRepository {
@@ -25,7 +26,8 @@ export declare class SpendApprovalRepository {
25
26
  listByWallet(wallet: string, state?: string): Promise<Row[]>;
26
27
  listAll(limit?: number): Promise<Row[]>;
27
28
  decide(id: string, to: "approved" | "rejected", actor: string, decidedAtMs: number, expiresAtMs?: number, payload?: JsonValue): Promise<boolean>;
28
- consume(id: string, consumedAtMs: number, payload?: JsonValue): Promise<boolean>;
29
+ findPendingByFingerprint(wallet: string, dealFingerprint: string): Promise<Row | null>;
30
+ consume(id: string, consumedAtMs: number, payload?: JsonValue, expectedFingerprint?: string): Promise<boolean>;
29
31
  expire(id: string, payload?: JsonValue): Promise<boolean>;
30
32
  listPending(): Promise<Row[]>;
31
33
  }
@@ -20,6 +20,7 @@ export class SpendApprovalRepository {
20
20
  consumedAtMs: toBigOrNull(a.consumedAtMs),
21
21
  expiresAtMs: toBig(a.expiresAtMs),
22
22
  createdAtMs: toBig(a.createdAtMs),
23
+ dealFingerprint: a.dealFingerprint ?? null,
23
24
  payload: a.payload,
24
25
  },
25
26
  update: {
@@ -60,10 +61,20 @@ export class SpendApprovalRepository {
60
61
  });
61
62
  return row !== null;
62
63
  }
63
- async consume(id, consumedAtMs, payload) {
64
+ async findPendingByFingerprint(wallet, dealFingerprint) {
65
+ return this.db.orm.public.SpendApproval.where({
66
+ wallet: wallet.toLowerCase(),
67
+ dealFingerprint,
68
+ state: "pending",
69
+ }).first();
70
+ }
71
+ async consume(id, consumedAtMs, payload, expectedFingerprint) {
64
72
  const row = await this.db.orm.public.SpendApproval.where({
65
73
  id,
66
74
  state: "approved",
75
+ ...(expectedFingerprint !== undefined
76
+ ? { dealFingerprint: expectedFingerprint }
77
+ : {}),
67
78
  }).update({
68
79
  state: "consumed",
69
80
  consumedAtMs: toBig(consumedAtMs),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.19",
3
+ "version": "0.6.22",
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",