@agentbadge/database 0.6.18 → 0.6.21
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/database.d.ts +2 -0
- package/dist/database.js +3 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/prisma/contract.json +779 -7
- package/dist/repositories/commerce-repository.d.ts +4 -0
- package/dist/repositories/commerce-repository.js +20 -3
- package/dist/repositories/commerce-store.d.ts +10 -0
- package/dist/repositories/commerce-store.js +14 -2
- package/dist/repositories/interaction-repository.d.ts +95 -0
- package/dist/repositories/interaction-repository.js +287 -0
- package/dist/repositories/spend-approval-repository.d.ts +3 -1
- package/dist/repositories/spend-approval-repository.js +12 -1
- package/package.json +1 -1
|
@@ -31,6 +31,10 @@ export declare class CommerceAgreementRepository implements CommerceAgreementSto
|
|
|
31
31
|
create(a: CommerceAgreementInsert): Promise<CommerceAgreementRow | null>;
|
|
32
32
|
getById(id: string): Promise<CommerceAgreementRow | null>;
|
|
33
33
|
getByTaskId(taskId: string): Promise<CommerceAgreementRow | null>;
|
|
34
|
+
listByTaskId(taskId: string): Promise<CommerceAgreementRow[]>;
|
|
35
|
+
countByTaskId(taskId: string, opts?: {
|
|
36
|
+
excludeStatuses?: string[];
|
|
37
|
+
}): Promise<number>;
|
|
34
38
|
getByOfferId(offerId: string): Promise<CommerceAgreementRow | null>;
|
|
35
39
|
applyStatus(id: string, expectedFrom: string, to: string, patch?: AgreementStatusPatch): Promise<CommerceAgreementRow | null>;
|
|
36
40
|
}
|
|
@@ -23,6 +23,7 @@ const toTaskRow = (r) => ({
|
|
|
23
23
|
requirements: r.requirements,
|
|
24
24
|
budget: decOrNull(r.budget),
|
|
25
25
|
currency: r.currency,
|
|
26
|
+
maxProviders: r.maxProviders,
|
|
26
27
|
expiresAtMs: numOrNull(r.expiresAtMs),
|
|
27
28
|
status: r.status,
|
|
28
29
|
payload: r.payload,
|
|
@@ -64,6 +65,7 @@ const toSubmissionRow = (r) => ({
|
|
|
64
65
|
providerWallet: r.providerWallet,
|
|
65
66
|
summary: r.summary,
|
|
66
67
|
resultUrl: r.resultUrl,
|
|
68
|
+
milestoneRef: r.milestoneRef,
|
|
67
69
|
status: r.status,
|
|
68
70
|
reviewNote: r.reviewNote,
|
|
69
71
|
submittedAtMs: Number(r.submittedAtMs),
|
|
@@ -135,6 +137,7 @@ export class CommerceTaskRepository {
|
|
|
135
137
|
? t.budget
|
|
136
138
|
: null,
|
|
137
139
|
currency: t.currency ?? "USD",
|
|
140
|
+
maxProviders: t.maxProviders ?? 1,
|
|
138
141
|
expiresAtMs: t.expiresAtMs != null
|
|
139
142
|
? BigInt(t.expiresAtMs)
|
|
140
143
|
: null,
|
|
@@ -231,8 +234,6 @@ export class CommerceAgreementRepository {
|
|
|
231
234
|
async create(a) {
|
|
232
235
|
if (await this.getById(a.id))
|
|
233
236
|
return null;
|
|
234
|
-
if (await this.getByTaskId(a.taskId))
|
|
235
|
-
return null;
|
|
236
237
|
if (await this.getByOfferId(a.offerId))
|
|
237
238
|
return null;
|
|
238
239
|
const row = await catchUnique(this.orm.create({
|
|
@@ -257,9 +258,24 @@ export class CommerceAgreementRepository {
|
|
|
257
258
|
return r ? toAgreementRow(r) : null;
|
|
258
259
|
}
|
|
259
260
|
async getByTaskId(taskId) {
|
|
260
|
-
const r = await this.orm
|
|
261
|
+
const r = await this.orm
|
|
262
|
+
.where({ taskId })
|
|
263
|
+
.orderBy((x) => x.createdAt.asc())
|
|
264
|
+
.first();
|
|
261
265
|
return r ? toAgreementRow(r) : null;
|
|
262
266
|
}
|
|
267
|
+
async listByTaskId(taskId) {
|
|
268
|
+
const rows = await this.orm
|
|
269
|
+
.where({ taskId })
|
|
270
|
+
.orderBy((x) => x.createdAt.asc())
|
|
271
|
+
.all();
|
|
272
|
+
return rows.map(toAgreementRow);
|
|
273
|
+
}
|
|
274
|
+
async countByTaskId(taskId, opts) {
|
|
275
|
+
const ex = opts?.excludeStatuses ?? [];
|
|
276
|
+
const rows = await this.orm.where({ taskId }).all();
|
|
277
|
+
return rows.filter((r) => !ex.includes(r.status)).length;
|
|
278
|
+
}
|
|
263
279
|
async getByOfferId(offerId) {
|
|
264
280
|
const r = await this.orm.where({ offerId }).first();
|
|
265
281
|
return r ? toAgreementRow(r) : null;
|
|
@@ -295,6 +311,7 @@ export class CommerceSubmissionRepository {
|
|
|
295
311
|
providerWallet: s.providerWallet,
|
|
296
312
|
summary: s.summary,
|
|
297
313
|
resultUrl: s.resultUrl ?? null,
|
|
314
|
+
milestoneRef: s.milestoneRef ?? null,
|
|
298
315
|
status: s.status,
|
|
299
316
|
reviewNote: s.reviewNote ?? null,
|
|
300
317
|
submittedAtMs: BigInt(s.submittedAtMs),
|
|
@@ -8,6 +8,7 @@ export interface CommerceTaskInsert {
|
|
|
8
8
|
requirements?: JsonValue | null;
|
|
9
9
|
budget?: string | null;
|
|
10
10
|
currency?: string;
|
|
11
|
+
maxProviders?: number | null;
|
|
11
12
|
expiresAtMs?: number | null;
|
|
12
13
|
status: string;
|
|
13
14
|
payload: JsonValue;
|
|
@@ -73,6 +74,10 @@ export interface CommerceAgreementStore {
|
|
|
73
74
|
create(a: CommerceAgreementInsert): Promise<CommerceAgreementRow | null>;
|
|
74
75
|
getById(id: string): Promise<CommerceAgreementRow | null>;
|
|
75
76
|
getByTaskId(taskId: string): Promise<CommerceAgreementRow | null>;
|
|
77
|
+
listByTaskId(taskId: string): Promise<CommerceAgreementRow[]>;
|
|
78
|
+
countByTaskId(taskId: string, opts?: {
|
|
79
|
+
excludeStatuses?: string[];
|
|
80
|
+
}): Promise<number>;
|
|
76
81
|
getByOfferId(offerId: string): Promise<CommerceAgreementRow | null>;
|
|
77
82
|
applyStatus(id: string, expectedFrom: string, to: string, patch?: AgreementStatusPatch): Promise<CommerceAgreementRow | null>;
|
|
78
83
|
}
|
|
@@ -82,6 +87,7 @@ export interface CommerceSubmissionInsert {
|
|
|
82
87
|
providerWallet: string;
|
|
83
88
|
summary: string;
|
|
84
89
|
resultUrl?: string | null;
|
|
90
|
+
milestoneRef?: string | null;
|
|
85
91
|
status: string;
|
|
86
92
|
reviewNote?: string | null;
|
|
87
93
|
submittedAtMs: number;
|
|
@@ -223,6 +229,10 @@ export declare class InMemoryCommerceAgreementStore implements CommerceAgreement
|
|
|
223
229
|
create(a: CommerceAgreementInsert): Promise<CommerceAgreementRow | null>;
|
|
224
230
|
getById(id: string): Promise<CommerceAgreementRow | null>;
|
|
225
231
|
getByTaskId(taskId: string): Promise<CommerceAgreementRow | null>;
|
|
232
|
+
listByTaskId(taskId: string): Promise<CommerceAgreementRow[]>;
|
|
233
|
+
countByTaskId(taskId: string, opts?: {
|
|
234
|
+
excludeStatuses?: string[];
|
|
235
|
+
}): Promise<number>;
|
|
226
236
|
getByOfferId(offerId: string): Promise<CommerceAgreementRow | null>;
|
|
227
237
|
applyStatus(id: string, expectedFrom: string, to: string, patch?: AgreementStatusPatch): Promise<CommerceAgreementRow | null>;
|
|
228
238
|
}
|
|
@@ -11,6 +11,7 @@ export class InMemoryCommerceTaskStore {
|
|
|
11
11
|
requirements: t.requirements ?? null,
|
|
12
12
|
budget: t.budget ?? null,
|
|
13
13
|
currency: t.currency ?? "USD",
|
|
14
|
+
maxProviders: t.maxProviders ?? 1,
|
|
14
15
|
expiresAtMs: t.expiresAtMs ?? null,
|
|
15
16
|
createdAt: ts,
|
|
16
17
|
updatedAt: ts,
|
|
@@ -81,7 +82,7 @@ export class InMemoryCommerceAgreementStore {
|
|
|
81
82
|
if (this.rows.has(a.id))
|
|
82
83
|
return null;
|
|
83
84
|
for (const x of this.rows.values()) {
|
|
84
|
-
if (x.
|
|
85
|
+
if (x.offerId === a.offerId)
|
|
85
86
|
return null;
|
|
86
87
|
}
|
|
87
88
|
const ts = nowIso();
|
|
@@ -100,7 +101,17 @@ export class InMemoryCommerceAgreementStore {
|
|
|
100
101
|
return this.rows.get(id) ?? null;
|
|
101
102
|
}
|
|
102
103
|
async getByTaskId(taskId) {
|
|
103
|
-
|
|
104
|
+
const all = await this.listByTaskId(taskId);
|
|
105
|
+
return all[0] ?? null;
|
|
106
|
+
}
|
|
107
|
+
async listByTaskId(taskId) {
|
|
108
|
+
return [...this.rows.values()]
|
|
109
|
+
.filter((r) => r.taskId === taskId)
|
|
110
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
111
|
+
}
|
|
112
|
+
async countByTaskId(taskId, opts) {
|
|
113
|
+
const ex = new Set(opts?.excludeStatuses ?? []);
|
|
114
|
+
return (await this.listByTaskId(taskId)).filter((r) => !ex.has(r.status)).length;
|
|
104
115
|
}
|
|
105
116
|
async getByOfferId(offerId) {
|
|
106
117
|
return [...this.rows.values()].find((r) => r.offerId === offerId) ?? null;
|
|
@@ -130,6 +141,7 @@ export class InMemoryCommerceSubmissionStore {
|
|
|
130
141
|
const row = {
|
|
131
142
|
...s,
|
|
132
143
|
resultUrl: s.resultUrl ?? null,
|
|
144
|
+
milestoneRef: s.milestoneRef ?? null,
|
|
133
145
|
reviewNote: s.reviewNote ?? null,
|
|
134
146
|
reviewedAtMs: s.reviewedAtMs ?? null,
|
|
135
147
|
createdAt: ts,
|
|
@@ -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,287 @@
|
|
|
1
|
+
const TERMINAL = new Set(["completed", "failed"]);
|
|
2
|
+
const toBig = (n) => BigInt(n);
|
|
3
|
+
const toBigOrNull = (n) => n == null ? null : BigInt(n);
|
|
4
|
+
function isUniqueViolation(err) {
|
|
5
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
6
|
+
return /unique|duplicate/i.test(m);
|
|
7
|
+
}
|
|
8
|
+
export class InteractionRepository {
|
|
9
|
+
db;
|
|
10
|
+
constructor(db) {
|
|
11
|
+
this.db = db;
|
|
12
|
+
}
|
|
13
|
+
async get(id) {
|
|
14
|
+
return this.db.orm.public.AgentRequest.where({ id }).first();
|
|
15
|
+
}
|
|
16
|
+
async findByIdempotency(idempotencyKey, fpHash) {
|
|
17
|
+
return this.db.orm.public.AgentRequest.where({
|
|
18
|
+
idempotencyKey,
|
|
19
|
+
fpHash,
|
|
20
|
+
}).first();
|
|
21
|
+
}
|
|
22
|
+
async submitInteraction(input, events) {
|
|
23
|
+
if (input.idempotencyKey) {
|
|
24
|
+
const existing = await this.findByIdempotency(input.idempotencyKey, input.fpHash);
|
|
25
|
+
if (existing)
|
|
26
|
+
return { row: existing, duplicate: true };
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
const row = await this.db.transaction(async (tx) => {
|
|
30
|
+
const r = await tx.orm.public.AgentRequest.create({
|
|
31
|
+
id: input.id,
|
|
32
|
+
state: input.state,
|
|
33
|
+
kind: input.kind ?? null,
|
|
34
|
+
payload: input.payload,
|
|
35
|
+
fingerprint: input.fingerprint,
|
|
36
|
+
fpHash: input.fpHash,
|
|
37
|
+
agentId: input.agentId ?? null,
|
|
38
|
+
verified: input.verified ?? false,
|
|
39
|
+
response: null,
|
|
40
|
+
spamFlag: false,
|
|
41
|
+
publishToQa: input.publishToQa ?? false,
|
|
42
|
+
idempotencyKey: input.idempotencyKey ?? null,
|
|
43
|
+
expiresAtMs: toBig(input.expiresAtMs),
|
|
44
|
+
createdAtMs: toBig(input.createdAtMs),
|
|
45
|
+
respondedAtMs: null,
|
|
46
|
+
actorResolution: input.actorResolution,
|
|
47
|
+
actorRef: input.actorRef ?? null,
|
|
48
|
+
sessionId: input.sessionId ?? null,
|
|
49
|
+
channel: input.channel,
|
|
50
|
+
intent: null,
|
|
51
|
+
signalType: null,
|
|
52
|
+
outcome: null,
|
|
53
|
+
knowledgeGap: false,
|
|
54
|
+
topics: null,
|
|
55
|
+
entities: null,
|
|
56
|
+
demandSignals: null,
|
|
57
|
+
classifiedBy: null,
|
|
58
|
+
});
|
|
59
|
+
await this.appendEventsTx(tx.orm, r.id, events, input.createdAtMs);
|
|
60
|
+
if (input.sessionId) {
|
|
61
|
+
await this.touchSessionTx(tx.orm, {
|
|
62
|
+
id: input.sessionId,
|
|
63
|
+
actorRef: input.actorRef ?? null,
|
|
64
|
+
seenAtMs: input.createdAtMs,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return r;
|
|
68
|
+
});
|
|
69
|
+
return { row, duplicate: false };
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
if (isUniqueViolation(err) && input.idempotencyKey) {
|
|
73
|
+
const existing = await this.findByIdempotency(input.idempotencyKey, input.fpHash);
|
|
74
|
+
if (existing)
|
|
75
|
+
return { row: existing, duplicate: true };
|
|
76
|
+
}
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async classify(id, patch, events, nowMs) {
|
|
81
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
82
|
+
const out = await this.db.transaction(async (tx) => {
|
|
83
|
+
const cur = await tx.orm.public.AgentRequest.where({ id }).first();
|
|
84
|
+
if (!cur)
|
|
85
|
+
return null;
|
|
86
|
+
const update = {};
|
|
87
|
+
if (patch.intent !== undefined)
|
|
88
|
+
update.intent = patch.intent;
|
|
89
|
+
if (patch.signalType !== undefined)
|
|
90
|
+
update.signalType = patch.signalType;
|
|
91
|
+
if (patch.outcome !== undefined)
|
|
92
|
+
update.outcome = patch.outcome;
|
|
93
|
+
if (patch.knowledgeGap !== undefined)
|
|
94
|
+
update.knowledgeGap = patch.knowledgeGap;
|
|
95
|
+
if (patch.topics !== undefined)
|
|
96
|
+
update.topics = patch.topics;
|
|
97
|
+
if (patch.entities !== undefined)
|
|
98
|
+
update.entities = patch.entities;
|
|
99
|
+
if (patch.demandSignals !== undefined)
|
|
100
|
+
update.demandSignals = patch.demandSignals;
|
|
101
|
+
if (patch.classifiedBy !== undefined)
|
|
102
|
+
update.classifiedBy = patch.classifiedBy;
|
|
103
|
+
const transitioned = cur.state === "submitted";
|
|
104
|
+
if (transitioned)
|
|
105
|
+
update.state = "working";
|
|
106
|
+
const row = await tx.orm.public.AgentRequest.where({
|
|
107
|
+
id,
|
|
108
|
+
state: cur.state,
|
|
109
|
+
}).update(update);
|
|
110
|
+
if (!row)
|
|
111
|
+
return { raced: true };
|
|
112
|
+
await this.appendEventsTx(tx.orm, id, events, nowMs);
|
|
113
|
+
return { row, transitioned, raced: false };
|
|
114
|
+
});
|
|
115
|
+
if (out === null)
|
|
116
|
+
return null;
|
|
117
|
+
if (!out.raced)
|
|
118
|
+
return { row: out.row, transitioned: out.transitioned };
|
|
119
|
+
}
|
|
120
|
+
const cur = await this.get(id);
|
|
121
|
+
return cur ? { row: cur, transitioned: false } : null;
|
|
122
|
+
}
|
|
123
|
+
async respond(id, response, events, nowMs) {
|
|
124
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
125
|
+
const out = await this.db.transaction(async (tx) => {
|
|
126
|
+
const cur = await tx.orm.public.AgentRequest.where({ id }).first();
|
|
127
|
+
if (!cur)
|
|
128
|
+
return { row: null, transitioned: false, raced: false };
|
|
129
|
+
if (TERMINAL.has(cur.state)) {
|
|
130
|
+
return { row: cur, transitioned: false, raced: false };
|
|
131
|
+
}
|
|
132
|
+
const row = await tx.orm.public.AgentRequest.where({
|
|
133
|
+
id,
|
|
134
|
+
state: cur.state,
|
|
135
|
+
}).update({
|
|
136
|
+
state: "completed",
|
|
137
|
+
response: { answer: response.body },
|
|
138
|
+
respondedAtMs: toBigOrNull(nowMs),
|
|
139
|
+
});
|
|
140
|
+
if (!row)
|
|
141
|
+
return { raced: true };
|
|
142
|
+
await tx.orm.public.InteractionResponse.create({
|
|
143
|
+
id: response.id,
|
|
144
|
+
requestId: response.requestId,
|
|
145
|
+
operatorRef: response.operatorRef,
|
|
146
|
+
body: response.body,
|
|
147
|
+
createdAtMs: BigInt(response.createdAtMs),
|
|
148
|
+
});
|
|
149
|
+
await this.appendEventsTx(tx.orm, id, events, nowMs);
|
|
150
|
+
return { row, transitioned: true, raced: false };
|
|
151
|
+
});
|
|
152
|
+
if (!out.raced) {
|
|
153
|
+
return { row: out.row ?? null, transitioned: out.transitioned ?? false };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const cur = await this.get(id);
|
|
157
|
+
return { row: cur, transitioned: false };
|
|
158
|
+
}
|
|
159
|
+
async reject(id, events, nowMs) {
|
|
160
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
161
|
+
const out = await this.db.transaction(async (tx) => {
|
|
162
|
+
const cur = await tx.orm.public.AgentRequest.where({ id }).first();
|
|
163
|
+
if (!cur)
|
|
164
|
+
return { row: null, transitioned: false, raced: false };
|
|
165
|
+
if (TERMINAL.has(cur.state)) {
|
|
166
|
+
return { row: cur, transitioned: false, raced: false };
|
|
167
|
+
}
|
|
168
|
+
const row = await tx.orm.public.AgentRequest.where({
|
|
169
|
+
id,
|
|
170
|
+
state: cur.state,
|
|
171
|
+
}).update({ state: "failed" });
|
|
172
|
+
if (!row)
|
|
173
|
+
return { raced: true };
|
|
174
|
+
await this.appendEventsTx(tx.orm, id, events, nowMs);
|
|
175
|
+
return { row, transitioned: true, raced: false };
|
|
176
|
+
});
|
|
177
|
+
if (!out.raced) {
|
|
178
|
+
return { row: out.row ?? null, transitioned: out.transitioned ?? false };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const cur = await this.get(id);
|
|
182
|
+
return { row: cur, transitioned: false };
|
|
183
|
+
}
|
|
184
|
+
async listQueue(opts) {
|
|
185
|
+
let q = this.db.orm.public.AgentRequest.orderBy((r) => r.createdAtMs.asc());
|
|
186
|
+
if (opts?.state !== undefined)
|
|
187
|
+
q = q.where({ state: opts.state });
|
|
188
|
+
if (opts?.actorResolution !== undefined) {
|
|
189
|
+
q = q.where({ actorResolution: opts.actorResolution });
|
|
190
|
+
}
|
|
191
|
+
const rows = await q.limit(opts?.limit ?? 500).all();
|
|
192
|
+
return opts?.beforeMs === undefined
|
|
193
|
+
? rows
|
|
194
|
+
: rows.filter((r) => Number(r.createdAtMs) < opts.beforeMs);
|
|
195
|
+
}
|
|
196
|
+
async listBySession(sessionId, limit = 100) {
|
|
197
|
+
return this.db.orm.public.AgentRequest.where({ sessionId })
|
|
198
|
+
.orderBy((r) => r.createdAtMs.asc())
|
|
199
|
+
.limit(limit)
|
|
200
|
+
.all();
|
|
201
|
+
}
|
|
202
|
+
async getSession(id) {
|
|
203
|
+
return this.db.orm.public.InteractionSession.where({ id }).first();
|
|
204
|
+
}
|
|
205
|
+
async upsertSession(input) {
|
|
206
|
+
try {
|
|
207
|
+
return await this.db.transaction(async (tx) => this.touchSessionTx(tx.orm, input));
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
if (!isUniqueViolation(err))
|
|
211
|
+
throw err;
|
|
212
|
+
return this.db.transaction(async (tx) => this.touchSessionTx(tx.orm, input));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async touchSessionTx(orm, input) {
|
|
216
|
+
const cur = await orm.public.InteractionSession.where({
|
|
217
|
+
id: input.id,
|
|
218
|
+
}).first();
|
|
219
|
+
const seen = BigInt(input.seenAtMs);
|
|
220
|
+
if (!cur) {
|
|
221
|
+
const session = await orm.public.InteractionSession.create({
|
|
222
|
+
id: input.id,
|
|
223
|
+
actorRef: input.actorRef ?? null,
|
|
224
|
+
firstSeenAtMs: seen,
|
|
225
|
+
lastSeenAtMs: seen,
|
|
226
|
+
requestCount: 1,
|
|
227
|
+
});
|
|
228
|
+
return { session, created: true };
|
|
229
|
+
}
|
|
230
|
+
const update = {
|
|
231
|
+
lastSeenAtMs: seen,
|
|
232
|
+
requestCount: cur.requestCount + 1,
|
|
233
|
+
};
|
|
234
|
+
if (cur.actorRef == null && input.actorRef != null) {
|
|
235
|
+
update.actorRef = input.actorRef;
|
|
236
|
+
}
|
|
237
|
+
const session = await orm.public.InteractionSession.where({
|
|
238
|
+
id: input.id,
|
|
239
|
+
}).update(update);
|
|
240
|
+
return { session: session, created: false };
|
|
241
|
+
}
|
|
242
|
+
async listResponses(requestId) {
|
|
243
|
+
return this.db.orm.public.InteractionResponse.where({ requestId })
|
|
244
|
+
.orderBy((r) => r.createdAtMs.asc())
|
|
245
|
+
.all();
|
|
246
|
+
}
|
|
247
|
+
async appendEvents(requestId, events, nowMs) {
|
|
248
|
+
try {
|
|
249
|
+
return await this.db.transaction(async (tx) => this.appendEventsTx(tx.orm, requestId, events, nowMs));
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
if (!isUniqueViolation(err))
|
|
253
|
+
throw err;
|
|
254
|
+
return this.db.transaction(async (tx) => this.appendEventsTx(tx.orm, requestId, events, nowMs));
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async appendEventsTx(orm, requestId, events, nowMs) {
|
|
258
|
+
if (events.length === 0)
|
|
259
|
+
return [];
|
|
260
|
+
const existing = await orm.public.InteractionEvent.where({
|
|
261
|
+
requestId,
|
|
262
|
+
}).all();
|
|
263
|
+
let seq = existing.reduce((m, e) => Math.max(m, e.seq), 0);
|
|
264
|
+
const out = [];
|
|
265
|
+
for (const e of events) {
|
|
266
|
+
seq += 1;
|
|
267
|
+
out.push(await orm.public.InteractionEvent.create({
|
|
268
|
+
id: e.id ?? crypto.randomUUID(),
|
|
269
|
+
requestId,
|
|
270
|
+
seq,
|
|
271
|
+
kind: e.kind,
|
|
272
|
+
visibility: e.visibility,
|
|
273
|
+
payload: e.payload,
|
|
274
|
+
createdAtMs: BigInt(e.createdAtMs ?? nowMs),
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
async listEvents(requestId, opts) {
|
|
280
|
+
const rows = await this.db.orm.public.InteractionEvent.where({ requestId })
|
|
281
|
+
.orderBy((e) => e.seq.asc())
|
|
282
|
+
.all();
|
|
283
|
+
return opts?.visibility === undefined
|
|
284
|
+
? rows
|
|
285
|
+
: rows.filter((r) => r.visibility === opts.visibility);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -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
|
-
|
|
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
|
|
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