@devlab.group/agent-commerce 2.4.1 → 2.6.0
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/README.md +168 -16
- package/dist/ap2.d.ts +42 -17
- package/dist/ap2.js +83 -27
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
- package/dist/chunk-DRLBML7Z.js.map +1 -0
- package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
- package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
- package/dist/chunk-GA3O2A7R.js +92 -0
- package/dist/chunk-GA3O2A7R.js.map +1 -0
- package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
- package/dist/chunk-M52FBNJX.js.map +1 -0
- package/dist/chunk-M6BSXXTF.js +8 -0
- package/dist/chunk-M6BSXXTF.js.map +1 -0
- package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
- package/dist/chunk-M6MQ3FYS.js.map +1 -0
- package/dist/chunk-M6WW6QIT.js +18 -0
- package/dist/chunk-M6WW6QIT.js.map +1 -0
- package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
- package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
- package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
- package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
- package/dist/cli/chunk-4KLYFXMW.js +8 -0
- package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
- package/dist/cli/chunk-663ALDZA.js +92 -0
- package/dist/cli/chunk-663ALDZA.js.map +1 -0
- package/dist/cli/chunk-6R6WJ4FD.js +18 -0
- package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
- package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
- package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
- package/dist/cli/chunk-DHFMIBPG.js +107 -0
- package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
- package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
- package/dist/cli/chunk-GET3CZGR.js.map +1 -0
- package/dist/cli/chunk-NSYSMDQN.js +1544 -0
- package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
- package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
- package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
- package/dist/cli/chunk-SYQLJXIU.js +105 -0
- package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
- package/dist/cli/chunk-TFV3K6YS.js +373 -0
- package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
- package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
- package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
- package/dist/cli/chunk-VJH6RYRK.js +119 -0
- package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
- package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
- package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
- package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
- package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
- package/dist/cli/config-3K65QJ22.js +12 -0
- package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
- package/dist/cli/index.js +753 -212
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
- package/dist/cli/mcp-6F64A7KE.js.map +1 -0
- package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
- package/dist/cli/near-U6365VFX.js.map +1 -0
- package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
- package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
- package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
- package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
- package/dist/cli/receipts-I4IIE7U6.js +8 -0
- package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
- package/dist/cli/reconcile-55WNCSFC.js +4 -0
- package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
- package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
- package/dist/cli/run-2P6ZGFUE.js.map +1 -0
- package/dist/cli/svm-KDSPDFJG.js +48 -0
- package/dist/cli/svm-KDSPDFJG.js.map +1 -0
- package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
- package/dist/cli/x402-4LPIIELI.js.map +1 -0
- package/dist/index.d.ts +116 -113
- package/dist/index.js +1928 -351
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.js +2 -1
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +48 -19
- package/dist/mpp.js.map +1 -1
- package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
- package/dist/near-FH7HPZV3.js.map +1 -0
- package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
- package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
- package/dist/store-kIIMpUA-.d.ts +372 -0
- package/dist/svm-KNC3PHMS.js +48 -0
- package/dist/svm-KNC3PHMS.js.map +1 -0
- package/dist/testing.d.ts +51 -0
- package/dist/testing.js +1896 -0
- package/dist/testing.js.map +1 -0
- package/dist/transaction-Dv0UFGg5.d.ts +129 -0
- package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
- package/dist/x402.d.ts +2 -1
- package/dist/x402.js +6 -5
- package/dist/x402.js.map +1 -1
- package/package.json +5 -1
- package/dist/authorization-DjAecwuW.d.ts +0 -115
- package/dist/chunk-CXWC5LWM.js.map +0 -1
- package/dist/chunk-DTKU3Z2M.js.map +0 -1
- package/dist/chunk-KA2AX5FH.js +0 -44
- package/dist/chunk-KA2AX5FH.js.map +0 -1
- package/dist/chunk-QPV3EGJO.js.map +0 -1
- package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
- package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
- package/dist/cli/chunk-GJIMDMYT.js +0 -639
- package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
- package/dist/cli/chunk-ITWNSS2B.js +0 -8
- package/dist/cli/chunk-OSTCU6ZK.js +0 -44
- package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
- package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
- package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
- package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
- package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
- package/dist/cli/config-UI4EDG4L.js +0 -11
- package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
- package/dist/cli/near-5AY3HWYF.js.map +0 -1
- package/dist/cli/provider-I2ESL6RS.js.map +0 -1
- package/dist/cli/run-JK4ERPJV.js.map +0 -1
- package/dist/cli/svm-3MMYFPC7.js +0 -33
- package/dist/cli/svm-3MMYFPC7.js.map +0 -1
- package/dist/cli/x402-7WBFZQXV.js.map +0 -1
- package/dist/near-D6C42VPE.js.map +0 -1
- package/dist/svm-QEUAUNPQ.js +0 -33
- package/dist/svm-QEUAUNPQ.js.map +0 -1
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { CommerceError, redactedErrorText } from './chunk-SYQLJXIU.js';
|
|
2
|
+
|
|
3
|
+
// src/core/execution/reconcile.ts
|
|
4
|
+
var DEFAULT_RECONCILE_MIN_AGE_MS = 15 * 60 * 1e3;
|
|
5
|
+
var PAGE = 200;
|
|
6
|
+
var OUTCOMES = ["settled", "not-settled", "unknown"];
|
|
7
|
+
function journalOf(store) {
|
|
8
|
+
const {
|
|
9
|
+
listTransactions,
|
|
10
|
+
getTransaction,
|
|
11
|
+
getPaymentAttempt,
|
|
12
|
+
resolvePaymentAttempt,
|
|
13
|
+
recordTransactionStep
|
|
14
|
+
} = store;
|
|
15
|
+
if (!listTransactions || !getTransaction || !getPaymentAttempt || !resolvePaymentAttempt || !recordTransactionStep) {
|
|
16
|
+
throw new CommerceError("STORAGE_ERROR", "The receipt store has no transaction journal");
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
listTransactions: listTransactions.bind(store),
|
|
20
|
+
getTransaction: getTransaction.bind(store),
|
|
21
|
+
getPaymentAttempt: getPaymentAttempt.bind(store),
|
|
22
|
+
resolvePaymentAttempt: resolvePaymentAttempt.bind(store),
|
|
23
|
+
recordTransactionStep: recordTransactionStep.bind(store)
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
async function runReconcile(options) {
|
|
27
|
+
const { store, providers, clock, actor, logger } = options;
|
|
28
|
+
const dryRun = options.dryRun === true;
|
|
29
|
+
const journal = journalOf(store);
|
|
30
|
+
const candidates = await collectCandidates(options, journal);
|
|
31
|
+
const entries = [];
|
|
32
|
+
for (const { attempt, transactionId, locator } of candidates) {
|
|
33
|
+
const provider = providers.find((candidate) => candidate.name === attempt.provider);
|
|
34
|
+
const result = await ask(provider, attempt, locator, clock, logger);
|
|
35
|
+
let written = false;
|
|
36
|
+
let error;
|
|
37
|
+
if (!dryRun && result.outcome !== "unknown") {
|
|
38
|
+
try {
|
|
39
|
+
written = await journal.resolvePaymentAttempt({
|
|
40
|
+
attemptId: attempt.id,
|
|
41
|
+
expectedStatus: attempt.status,
|
|
42
|
+
status: result.outcome === "settled" ? "settled" : "rejected",
|
|
43
|
+
...result.outcome === "not-settled" ? { rejectionReason: "not_settled" } : {},
|
|
44
|
+
resolution: {
|
|
45
|
+
method: "reconcile",
|
|
46
|
+
actor,
|
|
47
|
+
reason: result.reason,
|
|
48
|
+
at: clock.nowIso(),
|
|
49
|
+
...result.externalReference !== void 0 ? { externalReference: result.externalReference } : {},
|
|
50
|
+
...result.evidence !== void 0 ? { evidence: result.evidence } : {}
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
} catch (err) {
|
|
54
|
+
logger?.warn(
|
|
55
|
+
{ attemptId: attempt.id, err: redactedErrorText(err) },
|
|
56
|
+
"reconcile: could not save the resolution"
|
|
57
|
+
);
|
|
58
|
+
error = "storage_error";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
entries.push({
|
|
62
|
+
attemptId: attempt.id,
|
|
63
|
+
...transactionId !== void 0 ? { transactionId } : {},
|
|
64
|
+
requestId: attempt.requestId,
|
|
65
|
+
provider: attempt.provider,
|
|
66
|
+
status: attempt.status,
|
|
67
|
+
outcome: result.outcome,
|
|
68
|
+
reason: result.reason,
|
|
69
|
+
written,
|
|
70
|
+
...error !== void 0 ? { error } : {},
|
|
71
|
+
...result.externalReference !== void 0 ? { externalReference: result.externalReference } : {},
|
|
72
|
+
...result.retryAfter !== void 0 ? { retryAfter: result.retryAfter } : {}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const authorizationProviders = options.authorizationProviders ?? [];
|
|
76
|
+
const holds = [];
|
|
77
|
+
const orphanHolds = [];
|
|
78
|
+
const failedScans = [];
|
|
79
|
+
const limit = options.limit ?? Number.POSITIVE_INFINITY;
|
|
80
|
+
const scan = async (name, run) => {
|
|
81
|
+
try {
|
|
82
|
+
await run();
|
|
83
|
+
} catch (err) {
|
|
84
|
+
logger?.warn({ scan: name, err: redactedErrorText(err) }, "reconcile: a hold scan failed");
|
|
85
|
+
failedScans.push(name);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
if (authorizationProviders.length > 0) {
|
|
89
|
+
await scan(
|
|
90
|
+
"holds",
|
|
91
|
+
() => alignPendingHolds(holds, limit, dryRun, { journal, authorizationProviders, clock, logger })
|
|
92
|
+
);
|
|
93
|
+
await scan("orphan-holds", () => releaseOrphanHolds(orphanHolds, options, limit, dryRun));
|
|
94
|
+
}
|
|
95
|
+
return { dryRun, entries, holds, orphanHolds, failedScans };
|
|
96
|
+
}
|
|
97
|
+
async function alignPendingHolds(holds, limit, dryRun, deps) {
|
|
98
|
+
let cursor;
|
|
99
|
+
for (; ; ) {
|
|
100
|
+
const page = await deps.journal.listTransactions({
|
|
101
|
+
pendingHold: true,
|
|
102
|
+
limit: PAGE,
|
|
103
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
104
|
+
});
|
|
105
|
+
for (const transaction of page.transactions) {
|
|
106
|
+
const target = holdTarget(transaction);
|
|
107
|
+
if (target === void 0) continue;
|
|
108
|
+
if (holds.length >= limit) return;
|
|
109
|
+
holds.push(
|
|
110
|
+
dryRun ? holdEntry(transaction, target, false) : await alignHold(transaction, target, deps)
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
cursor = page.nextCursor;
|
|
114
|
+
if (cursor === void 0) return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function releaseOrphanHolds(entries, options, limit, dryRun) {
|
|
118
|
+
const { store, clock, logger } = options;
|
|
119
|
+
if (store.listOrphanAuthorizationHolds === void 0) return;
|
|
120
|
+
const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;
|
|
121
|
+
const updatedBefore = new Date(clock.now().getTime() - minAgeMs).toISOString();
|
|
122
|
+
const providers = options.authorizationProviders ?? [];
|
|
123
|
+
const seen = /* @__PURE__ */ new Set();
|
|
124
|
+
while (entries.length < limit) {
|
|
125
|
+
const page = await store.listOrphanAuthorizationHolds({
|
|
126
|
+
updatedBefore,
|
|
127
|
+
limit: Math.min(PAGE, limit - entries.length)
|
|
128
|
+
});
|
|
129
|
+
const fresh = page.filter((hold) => !seen.has(hold.reference));
|
|
130
|
+
if (fresh.length === 0) break;
|
|
131
|
+
for (const hold of fresh) {
|
|
132
|
+
seen.add(hold.reference);
|
|
133
|
+
const entry = {
|
|
134
|
+
reference: hold.reference,
|
|
135
|
+
method: hold.method,
|
|
136
|
+
requestId: hold.requestId,
|
|
137
|
+
resourceId: hold.resourceId,
|
|
138
|
+
updatedAt: hold.updatedAt
|
|
139
|
+
};
|
|
140
|
+
const provider = providers.find((candidate) => candidate.name === hold.method);
|
|
141
|
+
if (provider === void 0) {
|
|
142
|
+
entries.push({ ...entry, released: false, reason: "provider_not_enabled" });
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (dryRun) {
|
|
146
|
+
entries.push({ ...entry, released: false });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
await provider.release(hold.reference, {
|
|
151
|
+
requestId: hold.requestId,
|
|
152
|
+
resourceId: hold.resourceId
|
|
153
|
+
});
|
|
154
|
+
entries.push({ ...entry, released: true });
|
|
155
|
+
} catch (err) {
|
|
156
|
+
logger?.warn(
|
|
157
|
+
{ reference: hold.reference, method: hold.method, err: redactedErrorText(err) },
|
|
158
|
+
"reconcile: authorization provider could not release an orphan hold"
|
|
159
|
+
);
|
|
160
|
+
entries.push({ ...entry, released: false, reason: "provider_error" });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
var REFUSAL_MESSAGES = {
|
|
166
|
+
already_resolved: "The payment attempt already has a resolution",
|
|
167
|
+
not_resolvable: "Only reserved, settlement-uncertain and failed payment attempts can be resolved",
|
|
168
|
+
too_recent: "The payment attempt is reserved and may still be in flight; retry once it is 15 minutes old",
|
|
169
|
+
not_expired: "The recorded authorization expiry is still in the future",
|
|
170
|
+
expiry_unknown: "No expiry is recorded for this authorization; confirm that it has expired"
|
|
171
|
+
};
|
|
172
|
+
var MAX_ACTOR_LENGTH = 256;
|
|
173
|
+
var MAX_REASON_LENGTH = 1024;
|
|
174
|
+
var MAX_REFERENCE_LENGTH = 256;
|
|
175
|
+
var RESOLVABLE = [
|
|
176
|
+
"reserved",
|
|
177
|
+
"settlement-uncertain",
|
|
178
|
+
"failed"
|
|
179
|
+
];
|
|
180
|
+
async function resolveManually(options) {
|
|
181
|
+
const { clock, logger, attemptId, status, externalReference } = options;
|
|
182
|
+
if (status !== "settled" && status !== "rejected") {
|
|
183
|
+
throw invalid("status", 'status must be "settled" or "rejected"');
|
|
184
|
+
}
|
|
185
|
+
const actor = requiredText(options.actor, "actor", MAX_ACTOR_LENGTH);
|
|
186
|
+
const reason = requiredText(options.reason, "reason", MAX_REASON_LENGTH);
|
|
187
|
+
if (externalReference !== void 0) {
|
|
188
|
+
requiredText(externalReference, "externalReference", MAX_REFERENCE_LENGTH);
|
|
189
|
+
}
|
|
190
|
+
const journal = journalOf(options.store);
|
|
191
|
+
const attempt = await journal.getPaymentAttempt(attemptId);
|
|
192
|
+
if (attempt === void 0) {
|
|
193
|
+
throw new CommerceError("RESOURCE_NOT_FOUND", `Payment attempt "${attemptId}" was not found`);
|
|
194
|
+
}
|
|
195
|
+
const refuse = (refusal, current2 = attempt) => ({
|
|
196
|
+
resolved: false,
|
|
197
|
+
refusal,
|
|
198
|
+
message: REFUSAL_MESSAGES[refusal],
|
|
199
|
+
attempt: current2
|
|
200
|
+
});
|
|
201
|
+
if (attempt.resolution !== void 0) return refuse("already_resolved");
|
|
202
|
+
if (!RESOLVABLE.includes(attempt.status)) return refuse("not_resolvable");
|
|
203
|
+
if (attempt.status === "reserved" && !(clock.now().getTime() - Date.parse(attempt.createdAt) >= DEFAULT_RECONCILE_MIN_AGE_MS)) {
|
|
204
|
+
return refuse("too_recent");
|
|
205
|
+
}
|
|
206
|
+
const transaction = attempt.transactionId !== void 0 ? await journal.getTransaction(attempt.transactionId) : void 0;
|
|
207
|
+
if (status === "rejected") {
|
|
208
|
+
const expiresAt = Date.parse(transaction?.payment.expiresAt ?? "");
|
|
209
|
+
if (expiresAt > clock.now().getTime()) return refuse("not_expired");
|
|
210
|
+
if (Number.isNaN(expiresAt) && options.confirmExpired !== true) {
|
|
211
|
+
return refuse("expiry_unknown");
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const written = await journal.resolvePaymentAttempt({
|
|
215
|
+
attemptId,
|
|
216
|
+
expectedStatus: attempt.status,
|
|
217
|
+
status,
|
|
218
|
+
...status === "rejected" ? { rejectionReason: "not_settled" } : {},
|
|
219
|
+
resolution: {
|
|
220
|
+
method: "manual",
|
|
221
|
+
actor,
|
|
222
|
+
reason,
|
|
223
|
+
at: clock.nowIso(),
|
|
224
|
+
...externalReference !== void 0 ? { externalReference } : {}
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
const current = await journal.getPaymentAttempt(attemptId) ?? attempt;
|
|
228
|
+
if (!written) {
|
|
229
|
+
return refuse(
|
|
230
|
+
current.resolution !== void 0 ? "already_resolved" : "not_resolvable",
|
|
231
|
+
current
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
const resolved = transaction !== void 0 ? await journal.getTransaction(transaction.id) : void 0;
|
|
235
|
+
const target = resolved !== void 0 ? holdTarget(resolved) : void 0;
|
|
236
|
+
const hold = resolved !== void 0 && target !== void 0 ? await alignHold(resolved, target, {
|
|
237
|
+
journal,
|
|
238
|
+
authorizationProviders: options.authorizationProviders,
|
|
239
|
+
clock,
|
|
240
|
+
logger
|
|
241
|
+
}) : void 0;
|
|
242
|
+
return { resolved: true, attempt: current, ...hold !== void 0 ? { hold } : {} };
|
|
243
|
+
}
|
|
244
|
+
function requiredText(value, field, max) {
|
|
245
|
+
if (value.trim() === "" || value.length > max) {
|
|
246
|
+
throw invalid(field, `${field} must be non-empty and at most ${max} characters`);
|
|
247
|
+
}
|
|
248
|
+
return value;
|
|
249
|
+
}
|
|
250
|
+
function invalid(field, message) {
|
|
251
|
+
return new CommerceError("INPUT_INVALID", message, { details: { field } });
|
|
252
|
+
}
|
|
253
|
+
function holdTarget(transaction) {
|
|
254
|
+
const hold = transaction.authorization?.hold;
|
|
255
|
+
if (hold !== "reserved" && hold !== "uncertain") return void 0;
|
|
256
|
+
if (transaction.payment.status === "settled") return "consumed";
|
|
257
|
+
if (transaction.payment.status === "rejected") return "released";
|
|
258
|
+
return void 0;
|
|
259
|
+
}
|
|
260
|
+
function holdEntry(transaction, hold, written, reason) {
|
|
261
|
+
return {
|
|
262
|
+
transactionId: transaction.id,
|
|
263
|
+
attemptId: transaction.payment.attemptId,
|
|
264
|
+
method: transaction.authorization?.method ?? "",
|
|
265
|
+
hold,
|
|
266
|
+
written,
|
|
267
|
+
...reason !== void 0 ? { reason } : {}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
async function alignHold(transaction, target, deps) {
|
|
271
|
+
const authorization = transaction.authorization;
|
|
272
|
+
const provider = deps.authorizationProviders.find(
|
|
273
|
+
(candidate) => candidate.name === authorization?.method
|
|
274
|
+
);
|
|
275
|
+
if (authorization === void 0 || provider === void 0) {
|
|
276
|
+
return holdEntry(transaction, target, false, "provider_not_enabled");
|
|
277
|
+
}
|
|
278
|
+
const context = { requestId: transaction.requestId, resourceId: transaction.resourceId };
|
|
279
|
+
try {
|
|
280
|
+
if (target === "consumed") await provider.consume(authorization.reservationId, context);
|
|
281
|
+
else await provider.release(authorization.reservationId, context);
|
|
282
|
+
} catch (err) {
|
|
283
|
+
deps.logger?.warn(
|
|
284
|
+
{ transactionId: transaction.id, method: provider.name, err: redactedErrorText(err) },
|
|
285
|
+
"reconcile: authorization provider threw"
|
|
286
|
+
);
|
|
287
|
+
return holdEntry(transaction, target, false, "provider_error");
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
await deps.journal.recordTransactionStep({
|
|
291
|
+
transactionId: transaction.id,
|
|
292
|
+
at: deps.clock.nowIso(),
|
|
293
|
+
kind: "hold",
|
|
294
|
+
hold: target
|
|
295
|
+
});
|
|
296
|
+
} catch (err) {
|
|
297
|
+
deps.logger?.warn(
|
|
298
|
+
{ transactionId: transaction.id, err: redactedErrorText(err) },
|
|
299
|
+
"reconcile: could not record the hold update"
|
|
300
|
+
);
|
|
301
|
+
return holdEntry(transaction, target, false, "journal_error");
|
|
302
|
+
}
|
|
303
|
+
return holdEntry(transaction, target, true);
|
|
304
|
+
}
|
|
305
|
+
async function collectCandidates(options, journal) {
|
|
306
|
+
const { store, clock } = options;
|
|
307
|
+
const limit = options.limit ?? Number.POSITIVE_INFINITY;
|
|
308
|
+
const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;
|
|
309
|
+
const now = clock.now().getTime();
|
|
310
|
+
const eligible = (attempt) => attempt.resolution === void 0 && (attempt.status === "settlement-uncertain" || attempt.status === "failed" || attempt.status === "reserved" && now - Date.parse(attempt.createdAt) >= minAgeMs);
|
|
311
|
+
const candidates = [];
|
|
312
|
+
const seen = /* @__PURE__ */ new Set();
|
|
313
|
+
for (const state of ["payment-uncertain", "payment-pending", "delivery-started"]) {
|
|
314
|
+
let cursor;
|
|
315
|
+
do {
|
|
316
|
+
const page = await journal.listTransactions({
|
|
317
|
+
state,
|
|
318
|
+
limit: PAGE,
|
|
319
|
+
...cursor !== void 0 ? { cursor } : {}
|
|
320
|
+
});
|
|
321
|
+
for (const transaction of page.transactions) {
|
|
322
|
+
if (candidates.length >= limit) return candidates;
|
|
323
|
+
const { attemptId, status, locator } = transaction.payment;
|
|
324
|
+
if (status !== "settlement-uncertain" && status !== "failed" && status !== "reserved") {
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
const attempt = await journal.getPaymentAttempt(attemptId);
|
|
328
|
+
if (attempt === void 0 || !eligible(attempt) || seen.has(attempt.id)) continue;
|
|
329
|
+
seen.add(attempt.id);
|
|
330
|
+
candidates.push({
|
|
331
|
+
attempt,
|
|
332
|
+
transactionId: transaction.id,
|
|
333
|
+
...locator !== void 0 ? { locator } : {}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
cursor = page.nextCursor;
|
|
337
|
+
} while (cursor !== void 0);
|
|
338
|
+
}
|
|
339
|
+
for (const attempt of await store.listPaymentAttempts({ uncertain: true, limit: 500 })) {
|
|
340
|
+
if (candidates.length >= limit) break;
|
|
341
|
+
if (attempt.transactionId !== void 0 || seen.has(attempt.id) || !eligible(attempt)) continue;
|
|
342
|
+
seen.add(attempt.id);
|
|
343
|
+
candidates.push({ attempt });
|
|
344
|
+
}
|
|
345
|
+
return candidates;
|
|
346
|
+
}
|
|
347
|
+
async function ask(provider, attempt, locator, clock, logger) {
|
|
348
|
+
if (provider === void 0) return { outcome: "unknown", reason: "provider_not_enabled" };
|
|
349
|
+
if (provider.reconcile === void 0) {
|
|
350
|
+
return { outcome: "unknown", reason: "reconcile_unsupported" };
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
const result = await provider.reconcile({
|
|
354
|
+
attempt,
|
|
355
|
+
...locator !== void 0 ? { locator } : {},
|
|
356
|
+
now: clock.nowIso()
|
|
357
|
+
});
|
|
358
|
+
if (!OUTCOMES.includes(result.outcome) || typeof result.reason !== "string") {
|
|
359
|
+
return { outcome: "unknown", reason: "invalid_provider_result" };
|
|
360
|
+
}
|
|
361
|
+
return result;
|
|
362
|
+
} catch (err) {
|
|
363
|
+
logger?.warn(
|
|
364
|
+
{ attemptId: attempt.id, provider: attempt.provider, err: redactedErrorText(err) },
|
|
365
|
+
"reconcile: provider threw"
|
|
366
|
+
);
|
|
367
|
+
return { outcome: "unknown", reason: "provider_error" };
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export { DEFAULT_RECONCILE_MIN_AGE_MS, journalOf, resolveManually, runReconcile };
|
|
372
|
+
//# sourceMappingURL=chunk-TFV3K6YS.js.map
|
|
373
|
+
//# sourceMappingURL=chunk-TFV3K6YS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/execution/reconcile.ts"],"names":["current"],"mappings":";;;AAwBO,IAAM,4BAAA,GAA+B,KAAK,EAAA,GAAK;A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AAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,SAAA,CAAU;AAAA,MACtC,OAAA;AAAA,MACA,GAAI,OAAA,KAAY,KAAA,CAAA,GAAY,EAAE,OAAA,KAAY,EAAC;AAAA,MAC3C,GAAA,EAAK,MAAM,MAAA;AAAO,KACnB,CAAA;AACD,IAAA,IAAI,CAAC,SAAS,QAAA,CAAS,MAAA,CAAO,OAAO,CAAA,IAAK,OAAO,MAAA,CAAO,MAAA,KAAW,QAAA,EAAU;AAC3E,MAAA,OAAO,EAAE,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,yBAAA,EAA0B;AAAA,IACjE;AACA,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,GAAA,EAAK;AACZ,IAAA,MAAA,EAAQ,IAAA;AAAA,MACN,EAAE,SAAA,EAAW,OAAA,CAAQ,EAAA,EAAI,QAAA,EAAU,QAAQ,QAAA,EAAU,GAAA,EAAK,iBAAA,CAAkB,GAAG,CAAA,EAAE;AAAA,MACjF;AAAA,KACF;AACA,IAAA,OAAO,EAAE,OAAA,EAAS,SAAA,EAAW,MAAA,EAAQ,gBAAA,EAAiB;AAAA,EACxD;AACF","file":"chunk-TFV3K6YS.js","sourcesContent":["/**\n * Reconciliation records chain-evidence outcomes, and manual resolution\n * records operator verdicts, through conditional payment-attempt updates.\n * Neither path settles, refunds or retries delivery.\n *\n * An `unknown` result leaves the attempt unresolved. Later runs skip resolved\n * attempts as payment candidates but can retry their pending authorization\n * holds. Both paths attempt hold updates after recording payment resolution.\n *\n * Reconciliation also attempts to release old orphan holds: `reserved` holds\n * whose request has no current or archived payment attempt. The pipeline\n * reserves an attempt before calling settlement; the age threshold reduces\n * races with requests still between those steps.\n */\nimport type { AuthorizationProvider } from '../domain/authorization';\nimport type { PaymentProvider, PaymentReconciliationResult } from '../domain/payment';\nimport type { PaymentAttempt } from '../domain/receipt';\nimport type { Transaction } from '../domain/transaction';\nimport { CommerceError, redactedErrorText } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { Clock } from '../interfaces/runtime';\nimport type { ReceiptStore } from '../interfaces/store';\n\n/** Default age threshold for reserved attempts, to reduce races with a running gateway */\nexport const DEFAULT_RECONCILE_MIN_AGE_MS = 15 * 60 * 1000;\n\n// Journal page size while collecting candidates\nconst PAGE = 200;\n\nconst OUTCOMES: readonly string[] = ['settled', 'not-settled', 'unknown'];\n\nexport interface ReconcileRunOptions {\n readonly store: ReceiptStore;\n readonly providers: readonly PaymentProvider[];\n readonly clock: Clock;\n /** Stored with each resolution */\n readonly actor: string;\n /** Check provider evidence and report without recording resolutions */\n readonly dryRun?: boolean;\n readonly minAgeMs?: number;\n /** Separate caps on payment candidates checked and hold updates attempted */\n readonly limit?: number;\n /** Providers for hold updates; an omitted or empty list skips both hold scans */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly logger?: Logger;\n}\n\n/** Reconciliation result for one candidate */\nexport interface ReconcileEntry {\n readonly attemptId: string;\n /** Absent for attempts without a journal entry */\n readonly transactionId?: string;\n readonly requestId: string;\n readonly provider: string;\n readonly status: PaymentAttempt['status'];\n readonly outcome: PaymentReconciliationResult['outcome'];\n readonly reason: string;\n /** True when this run saved the attempt's resolution */\n readonly written: boolean;\n /** Set when saving the resolution throws */\n readonly error?: 'storage_error';\n readonly externalReference?: string;\n readonly retryAfter?: string;\n}\n\n/** Requested hold update for one resolved payment */\nexport interface HoldEntry {\n readonly transactionId: string;\n readonly attemptId: string;\n readonly method: string;\n /** `consumed` for a settled payment, `released` for a rejected one */\n readonly hold: 'consumed' | 'released';\n /** True when the provider call succeeded and the journal hold was recorded */\n readonly written: boolean;\n /**\n * Why the journal hold remains pending; `journal_error` means the provider\n * call succeeded but the journal write failed\n */\n readonly reason?: 'provider_not_enabled' | 'provider_error' | 'journal_error';\n}\n\n/** An orphan hold found during reconciliation, with its release result */\nexport interface OrphanHoldEntry {\n readonly reference: string;\n readonly method: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly updatedAt: string;\n /** True when the provider's release call succeeds */\n readonly released: boolean;\n readonly reason?: 'provider_not_enabled' | 'provider_error';\n}\n\nexport interface ReconcileReport {\n readonly dryRun: boolean;\n readonly entries: readonly ReconcileEntry[];\n readonly holds: readonly HoldEntry[];\n /** Empty when the store provides no orphan-hold listing method */\n readonly orphanHolds: readonly OrphanHoldEntry[];\n /**\n * Hold scans that failed, including on a store read error. Previously saved\n * resolutions remain committed; the report retains partial hold results.\n */\n readonly failedScans: readonly ('holds' | 'orphan-holds')[];\n}\n\ninterface Candidate {\n readonly attempt: PaymentAttempt;\n readonly transactionId?: string;\n readonly locator?: Readonly<Record<string, unknown>>;\n}\n\n/** Store methods required by reconciliation, manual resolution and the operator view */\nexport type Journal = Required<\n Pick<\n ReceiptStore,\n | 'listTransactions'\n | 'getTransaction'\n | 'getPaymentAttempt'\n | 'resolvePaymentAttempt'\n | 'recordTransactionStep'\n >\n>;\n\n/** Binds the required journal methods to the store, or throws `STORAGE_ERROR` if one is missing */\nexport function journalOf(store: ReceiptStore): Journal {\n const {\n listTransactions,\n getTransaction,\n getPaymentAttempt,\n resolvePaymentAttempt,\n recordTransactionStep,\n } = store;\n if (\n !listTransactions ||\n !getTransaction ||\n !getPaymentAttempt ||\n !resolvePaymentAttempt ||\n !recordTransactionStep\n ) {\n throw new CommerceError('STORAGE_ERROR', 'The receipt store has no transaction journal');\n }\n return {\n listTransactions: listTransactions.bind(store),\n getTransaction: getTransaction.bind(store),\n getPaymentAttempt: getPaymentAttempt.bind(store),\n resolvePaymentAttempt: resolvePaymentAttempt.bind(store),\n recordTransactionStep: recordTransactionStep.bind(store),\n };\n}\n\nexport async function runReconcile(options: ReconcileRunOptions): Promise<ReconcileReport> {\n const { store, providers, clock, actor, logger } = options;\n const dryRun = options.dryRun === true;\n const journal = journalOf(store);\n\n const candidates = await collectCandidates(options, journal);\n const entries: ReconcileEntry[] = [];\n for (const { attempt, transactionId, locator } of candidates) {\n const provider = providers.find((candidate) => candidate.name === attempt.provider);\n const result = await ask(provider, attempt, locator, clock, logger);\n let written = false;\n let error: ReconcileEntry['error'];\n if (!dryRun && result.outcome !== 'unknown') {\n // Report a failed resolution write and continue with the remaining candidates\n try {\n written = await journal.resolvePaymentAttempt({\n attemptId: attempt.id,\n expectedStatus: attempt.status,\n status: result.outcome === 'settled' ? 'settled' : 'rejected',\n ...(result.outcome === 'not-settled' ? { rejectionReason: 'not_settled' } : {}),\n resolution: {\n method: 'reconcile',\n actor,\n reason: result.reason,\n at: clock.nowIso(),\n ...(result.externalReference !== undefined\n ? { externalReference: result.externalReference }\n : {}),\n ...(result.evidence !== undefined ? { evidence: result.evidence } : {}),\n },\n });\n } catch (err) {\n logger?.warn(\n { attemptId: attempt.id, err: redactedErrorText(err) },\n 'reconcile: could not save the resolution',\n );\n error = 'storage_error';\n }\n }\n entries.push({\n attemptId: attempt.id,\n ...(transactionId !== undefined ? { transactionId } : {}),\n requestId: attempt.requestId,\n provider: attempt.provider,\n status: attempt.status,\n outcome: result.outcome,\n reason: result.reason,\n written,\n ...(error !== undefined ? { error } : {}),\n ...(result.externalReference !== undefined\n ? { externalReference: result.externalReference }\n : {}),\n ...(result.retryAfter !== undefined ? { retryAfter: result.retryAfter } : {}),\n });\n }\n\n const authorizationProviders = options.authorizationProviders ?? [];\n const holds: HoldEntry[] = [];\n const orphanHolds: OrphanHoldEntry[] = [];\n const failedScans: ReconcileReport['failedScans'][number][] = [];\n const limit = options.limit ?? Number.POSITIVE_INFINITY;\n // Preserve the report and any saved resolutions if a hold scan fails\n const scan = async (name: (typeof failedScans)[number], run: () => Promise<void>) => {\n try {\n await run();\n } catch (err) {\n logger?.warn({ scan: name, err: redactedErrorText(err) }, 'reconcile: a hold scan failed');\n failedScans.push(name);\n }\n };\n if (authorizationProviders.length > 0) {\n await scan('holds', () =>\n alignPendingHolds(holds, limit, dryRun, { journal, authorizationProviders, clock, logger }),\n );\n await scan('orphan-holds', () => releaseOrphanHolds(orphanHolds, options, limit, dryRun));\n }\n return { dryRun, entries, holds, orphanHolds, failedScans };\n}\n\n// Include pending holds left by earlier runs. Hold updates have no age\n// filter: the pipeline attempts finalization before recording a settled or\n// rejected payment status.\nasync function alignPendingHolds(\n holds: HoldEntry[],\n limit: number,\n dryRun: boolean,\n deps: AlignDeps,\n): Promise<void> {\n let cursor: string | undefined;\n for (;;) {\n const page = await deps.journal.listTransactions({\n pendingHold: true,\n limit: PAGE,\n ...(cursor !== undefined ? { cursor } : {}),\n });\n for (const transaction of page.transactions) {\n const target = holdTarget(transaction);\n if (target === undefined) continue;\n if (holds.length >= limit) return;\n holds.push(\n dryRun ? holdEntry(transaction, target, false) : await alignHold(transaction, target, deps),\n );\n }\n cursor = page.nextCursor;\n if (cursor === undefined) return;\n }\n}\n\n// A hold with no payment attempt keeps blocking reuse until it is released.\n// Wait for the age threshold to reduce races with requests between reservations.\nasync function releaseOrphanHolds(\n entries: OrphanHoldEntry[],\n options: ReconcileRunOptions,\n limit: number,\n dryRun: boolean,\n): Promise<void> {\n const { store, clock, logger } = options;\n if (store.listOrphanAuthorizationHolds === undefined) return;\n const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;\n const updatedBefore = new Date(clock.now().getTime() - minAgeMs).toISOString();\n const providers = options.authorizationProviders ?? [];\n // Released holds leave the list. Track seen references because unreleased\n // holds can occupy the first page again; stop when it has no unseen holds.\n // A dry run reports at most one PAGE-sized page. Scanning beyond unreleased\n // rows would require a cursor in listOrphanAuthorizationHolds.\n const seen = new Set<string>();\n while (entries.length < limit) {\n const page = await store.listOrphanAuthorizationHolds({\n updatedBefore,\n limit: Math.min(PAGE, limit - entries.length),\n });\n const fresh = page.filter((hold) => !seen.has(hold.reference));\n if (fresh.length === 0) break;\n for (const hold of fresh) {\n seen.add(hold.reference);\n const entry = {\n reference: hold.reference,\n method: hold.method,\n requestId: hold.requestId,\n resourceId: hold.resourceId,\n updatedAt: hold.updatedAt,\n };\n const provider = providers.find((candidate) => candidate.name === hold.method);\n if (provider === undefined) {\n entries.push({ ...entry, released: false, reason: 'provider_not_enabled' });\n continue;\n }\n if (dryRun) {\n entries.push({ ...entry, released: false });\n continue;\n }\n try {\n // The AP2 provider's reservation id is the hold reference\n await provider.release(hold.reference, {\n requestId: hold.requestId,\n resourceId: hold.resourceId,\n });\n entries.push({ ...entry, released: true });\n } catch (err) {\n logger?.warn(\n { reference: hold.reference, method: hold.method, err: redactedErrorText(err) },\n 'reconcile: authorization provider could not release an orphan hold',\n );\n entries.push({ ...entry, released: false, reason: 'provider_error' });\n }\n }\n }\n}\n\n/** Input to {@link resolveManually}; `actor` is a caller-supplied label */\nexport interface ManualResolveOptions {\n readonly store: ReceiptStore;\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger?: Logger;\n readonly attemptId: string;\n /** `settled` or `rejected`; anything else is `INPUT_INVALID` */\n readonly status: string;\n readonly actor: string;\n readonly reason: string;\n /** Recorded as the operator's claim without checking the chain */\n readonly externalReference?: string;\n /** Required for rejection when no valid expiry is recorded */\n readonly confirmExpired?: boolean;\n}\n\n/** Why a manual resolution was not written */\nexport type ManualResolveRefusal =\n | 'already_resolved'\n | 'not_resolvable'\n | 'too_recent'\n | 'not_expired'\n | 'expiry_unknown';\n\nexport type ManualResolveResult =\n | {\n readonly resolved: true;\n readonly attempt: PaymentAttempt;\n /** Present when the attempt's transaction holds an authorization to align */\n readonly hold?: HoldEntry;\n }\n | {\n readonly resolved: false;\n readonly refusal: ManualResolveRefusal;\n readonly message: string;\n readonly attempt: PaymentAttempt;\n };\n\nconst REFUSAL_MESSAGES: Record<ManualResolveRefusal, string> = {\n already_resolved: 'The payment attempt already has a resolution',\n not_resolvable: 'Only reserved, settlement-uncertain and failed payment attempts can be resolved',\n too_recent:\n 'The payment attempt is reserved and may still be in flight; retry once it is 15 minutes old',\n not_expired: 'The recorded authorization expiry is still in the future',\n expiry_unknown: 'No expiry is recorded for this authorization; confirm that it has expired',\n};\n\n// Bounds on operator-supplied text stored with the resolution\nconst MAX_ACTOR_LENGTH = 256;\nconst MAX_REASON_LENGTH = 1024;\nconst MAX_REFERENCE_LENGTH = 256;\n\nconst RESOLVABLE: readonly PaymentAttempt['status'][] = [\n 'reserved',\n 'settlement-uncertain',\n 'failed',\n];\n\n/**\n * Record an operator's verdict on an unresolved payment attempt, then try to\n * update its pending authorization hold. A `reserved` attempt younger than\n * {@link DEFAULT_RECONCILE_MIN_AGE_MS} is refused because the gateway may still\n * be settling it. A `rejected` verdict is refused while\n * the recorded expiry is in the future. Without a valid expiry, `confirmExpired`\n * is required. Throws `INPUT_INVALID` for invalid input and\n * `RESOURCE_NOT_FOUND` for an unknown attempt.\n */\nexport async function resolveManually(options: ManualResolveOptions): Promise<ManualResolveResult> {\n const { clock, logger, attemptId, status, externalReference } = options;\n if (status !== 'settled' && status !== 'rejected') {\n throw invalid('status', 'status must be \"settled\" or \"rejected\"');\n }\n const actor = requiredText(options.actor, 'actor', MAX_ACTOR_LENGTH);\n const reason = requiredText(options.reason, 'reason', MAX_REASON_LENGTH);\n if (externalReference !== undefined) {\n requiredText(externalReference, 'externalReference', MAX_REFERENCE_LENGTH);\n }\n const journal = journalOf(options.store);\n\n const attempt = await journal.getPaymentAttempt(attemptId);\n if (attempt === undefined) {\n throw new CommerceError('RESOURCE_NOT_FOUND', `Payment attempt \"${attemptId}\" was not found`);\n }\n const refuse = (refusal: ManualResolveRefusal, current = attempt): ManualResolveResult => ({\n resolved: false,\n refusal,\n message: REFUSAL_MESSAGES[refusal],\n attempt: current,\n });\n if (attempt.resolution !== undefined) return refuse('already_resolved');\n if (!RESOLVABLE.includes(attempt.status)) return refuse('not_resolvable');\n if (\n attempt.status === 'reserved' &&\n !(clock.now().getTime() - Date.parse(attempt.createdAt) >= DEFAULT_RECONCILE_MIN_AGE_MS)\n ) {\n return refuse('too_recent');\n }\n\n const transaction =\n attempt.transactionId !== undefined\n ? await journal.getTransaction(attempt.transactionId)\n : undefined;\n if (status === 'rejected') {\n const expiresAt = Date.parse(transaction?.payment.expiresAt ?? '');\n if (expiresAt > clock.now().getTime()) return refuse('not_expired');\n if (Number.isNaN(expiresAt) && options.confirmExpired !== true) {\n return refuse('expiry_unknown');\n }\n }\n\n const written = await journal.resolvePaymentAttempt({\n attemptId,\n expectedStatus: attempt.status,\n status,\n ...(status === 'rejected' ? { rejectionReason: 'not_settled' } : {}),\n resolution: {\n method: 'manual',\n actor,\n reason,\n at: clock.nowIso(),\n ...(externalReference !== undefined ? { externalReference } : {}),\n },\n });\n const current = (await journal.getPaymentAttempt(attemptId)) ?? attempt;\n // The conditional update lost a race; use the current attempt to classify it\n if (!written) {\n return refuse(\n current.resolution !== undefined ? 'already_resolved' : 'not_resolvable',\n current,\n );\n }\n\n const resolved =\n transaction !== undefined ? await journal.getTransaction(transaction.id) : undefined;\n const target = resolved !== undefined ? holdTarget(resolved) : undefined;\n const hold =\n resolved !== undefined && target !== undefined\n ? await alignHold(resolved, target, {\n journal,\n authorizationProviders: options.authorizationProviders,\n clock,\n logger,\n })\n : undefined;\n return { resolved: true, attempt: current, ...(hold !== undefined ? { hold } : {}) };\n}\n\nfunction requiredText(value: string, field: string, max: number): string {\n if (value.trim() === '' || value.length > max) {\n throw invalid(field, `${field} must be non-empty and at most ${max} characters`);\n }\n return value;\n}\n\nfunction invalid(field: string, message: string): CommerceError {\n return new CommerceError('INPUT_INVALID', message, { details: { field } });\n}\n\n// Desired state for a resolved payment's journal hold still reserved or uncertain\nfunction holdTarget(transaction: Transaction): HoldEntry['hold'] | undefined {\n const hold = transaction.authorization?.hold;\n if (hold !== 'reserved' && hold !== 'uncertain') return undefined;\n if (transaction.payment.status === 'settled') return 'consumed';\n if (transaction.payment.status === 'rejected') return 'released';\n return undefined;\n}\n\nfunction holdEntry(\n transaction: Transaction,\n hold: HoldEntry['hold'],\n written: boolean,\n reason?: HoldEntry['reason'],\n): HoldEntry {\n return {\n transactionId: transaction.id,\n attemptId: transaction.payment.attemptId,\n method: transaction.authorization?.method ?? '',\n hold,\n written,\n ...(reason !== undefined ? { reason } : {}),\n };\n}\n\ninterface AlignDeps {\n readonly journal: Journal;\n readonly authorizationProviders: readonly AuthorizationProvider[];\n readonly clock: Clock;\n readonly logger: Logger | undefined;\n}\n\n// Call the provider before updating the journal, so a crash can leave the\n// journal hold pending. After an AP2 consume/release succeeds, repeating it\n// leaves replay state unchanged; the request guard protects later reservations.\nasync function alignHold(\n transaction: Transaction,\n target: HoldEntry['hold'],\n deps: AlignDeps,\n): Promise<HoldEntry> {\n const authorization = transaction.authorization;\n const provider = deps.authorizationProviders.find(\n (candidate) => candidate.name === authorization?.method,\n );\n if (authorization === undefined || provider === undefined) {\n return holdEntry(transaction, target, false, 'provider_not_enabled');\n }\n // Bind the update to this transaction's reserving request\n const context = { requestId: transaction.requestId, resourceId: transaction.resourceId };\n try {\n if (target === 'consumed') await provider.consume(authorization.reservationId, context);\n else await provider.release(authorization.reservationId, context);\n } catch (err) {\n deps.logger?.warn(\n { transactionId: transaction.id, method: provider.name, err: redactedErrorText(err) },\n 'reconcile: authorization provider threw',\n );\n return holdEntry(transaction, target, false, 'provider_error');\n }\n // If the provider call succeeded but journaling fails, report the pending\n // journal update so a later run can retry both calls\n try {\n await deps.journal.recordTransactionStep({\n transactionId: transaction.id,\n at: deps.clock.nowIso(),\n kind: 'hold',\n hold: target,\n });\n } catch (err) {\n deps.logger?.warn(\n { transactionId: transaction.id, err: redactedErrorText(err) },\n 'reconcile: could not record the hold update',\n );\n return holdEntry(transaction, target, false, 'journal_error');\n }\n return holdEntry(transaction, target, true);\n}\n\n// Include uncertain and legacy `failed` attempts, plus `reserved` attempts\n// whose journal entries are present and whose age meets the threshold.\n// Journal rows supply locators; older attempts may have none.\nasync function collectCandidates(\n options: ReconcileRunOptions,\n journal: Journal,\n): Promise<readonly Candidate[]> {\n const { store, clock } = options;\n const limit = options.limit ?? Number.POSITIVE_INFINITY;\n const minAgeMs = options.minAgeMs ?? DEFAULT_RECONCILE_MIN_AGE_MS;\n const now = clock.now().getTime();\n const eligible = (attempt: PaymentAttempt) =>\n attempt.resolution === undefined &&\n (attempt.status === 'settlement-uncertain' ||\n attempt.status === 'failed' ||\n (attempt.status === 'reserved' && now - Date.parse(attempt.createdAt) >= minAgeMs));\n\n const candidates: Candidate[] = [];\n const seen = new Set<string>();\n // Scan states that can contain unresolved payments. delivery-started also\n // includes settled payments, which the attempt-status check below skips.\n for (const state of ['payment-uncertain', 'payment-pending', 'delivery-started'] as const) {\n let cursor: string | undefined;\n do {\n const page = await journal.listTransactions({\n state,\n limit: PAGE,\n ...(cursor !== undefined ? { cursor } : {}),\n });\n for (const transaction of page.transactions) {\n if (candidates.length >= limit) return candidates;\n const { attemptId, status, locator } = transaction.payment;\n if (status !== 'settlement-uncertain' && status !== 'failed' && status !== 'reserved') {\n continue;\n }\n const attempt = await journal.getPaymentAttempt(attemptId);\n if (attempt === undefined || !eligible(attempt) || seen.has(attempt.id)) continue;\n seen.add(attempt.id);\n candidates.push({\n attempt,\n transactionId: transaction.id,\n ...(locator !== undefined ? { locator } : {}),\n });\n }\n cursor = page.nextCursor;\n } while (cursor !== undefined);\n }\n\n // ponytail: attempts without journal entries are capped at one page; paginate for larger legacy stores\n for (const attempt of await store.listPaymentAttempts({ uncertain: true, limit: 500 })) {\n if (candidates.length >= limit) break;\n if (attempt.transactionId !== undefined || seen.has(attempt.id) || !eligible(attempt)) continue;\n seen.add(attempt.id);\n candidates.push({ attempt });\n }\n return candidates;\n}\n\nasync function ask(\n provider: PaymentProvider | undefined,\n attempt: PaymentAttempt,\n locator: Readonly<Record<string, unknown>> | undefined,\n clock: Clock,\n logger: Logger | undefined,\n): Promise<PaymentReconciliationResult> {\n if (provider === undefined) return { outcome: 'unknown', reason: 'provider_not_enabled' };\n if (provider.reconcile === undefined) {\n return { outcome: 'unknown', reason: 'reconcile_unsupported' };\n }\n try {\n const result = await provider.reconcile({\n attempt,\n ...(locator !== undefined ? { locator } : {}),\n now: clock.nowIso(),\n });\n if (!OUTCOMES.includes(result.outcome) || typeof result.reason !== 'string') {\n return { outcome: 'unknown', reason: 'invalid_provider_result' };\n }\n return result;\n } catch (err) {\n logger?.warn(\n { attemptId: attempt.id, provider: attempt.provider, err: redactedErrorText(err) },\n 'reconcile: provider threw',\n );\n return { outcome: 'unknown', reason: 'provider_error' };\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CommerceError } from './chunk-
|
|
1
|
+
import { CommerceError } from './chunk-SYQLJXIU.js';
|
|
2
2
|
import { existsSync, accessSync, constants, closeSync, openSync, mkdirSync, chmodSync } from 'fs';
|
|
3
3
|
import { dirname } from 'path';
|
|
4
4
|
import Database from 'better-sqlite3';
|
|
@@ -66,5 +66,5 @@ function restrictDatabasePermissions(path, label, logger) {
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
export { openSqliteDatabase };
|
|
69
|
-
//# sourceMappingURL=chunk-
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
69
|
+
//# sourceMappingURL=chunk-VJ4EO4LE.js.map
|
|
70
|
+
//# sourceMappingURL=chunk-VJ4EO4LE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage/sqlite.ts"],"names":["fsConstants"],"mappings":";;;;;AA6BO,SAAS,mBAAmB,OAAA,EAA+C;AAChF,EAAA,MAAM,EAAE,IAAA,EAAM,KAAA,EAAO,MAAA,EAAO,GAAI,OAAA;AAChC,EAAA,MAAM,eAAe,IAAA,KAAS,UAAA;AAE9B,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,IAAI;AACF,MAAA,eAAA,CAAgB,OAAA,CAAQ,IAAI,CAAC,CAAA;AAAA,IAC/B,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,IAAI,aAAA;AAAA,QACR,eAAA;AAAA,QACA,CAAA,EAAG,KAAK,CAAA,YAAA,EAAe,OAAA,CAAQ,IAAI,CAAC,CAAA,qBAAA,EAAwB,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM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,CAAA;AAC1B,EAAA,IAAI,MAAA,KAAW,GAAA,EAAK,eAAA,CAAgB,MAAM,CAAA;AAC1C,EAAA,IAAI;AACF,IAAA,SAAA,CAAU,GAAA,EAAK,EAAE,IAAA,EAAM,GAAA,EAAO,CAAA;AAAA,EAChC,SAAS,KAAA,EAAO;AAEd,IAAA,IAAK,KAAA,CAAgC,IAAA,KAAS,QAAA,EAAU,MAAM,KAAA;AAAA,EAChE;AACF;AAWA,SAAS,2BAAA,CAA4B,IAAA,EAAc,KAAA,EAAe,MAAA,EAAsB;AACtF,EAAA,KAAA,MAAW,IAAA,IAAQ,CAAC,IAAA,EAAM,CAAA,EAAG,IAAI,CAAA,IAAA,CAAA,EAAQ,CAAA,EAAG,IAAI,CAAA,IAAA,CAAM,CAAA,EAAG;AACvD,IAAA,IAAI;AACF,MAAA,SAAA,CAAU,MAAM,GAAK,CAAA;AAAA,IACvB,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,OAAQ,KAAA,CAAgC,IAAA;AAC9C,MAAA,IAAI,SAAS,QAAA,EAAU;AACvB,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,QAAQ,SAAA,EAAU;AAAA,QACxC;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"chunk-VJ4EO4LE.js","sourcesContent":["/**\n * Opens a SQLite file with owner-only permissions. Every store that keeps a\n * SQLite file opens it here, so the hardening below exists once: the file is\n * pre-created at 0600, the WAL sidecars are narrowed once WAL creates them, and\n * an existing but unwritable file fails at startup.\n *\n * Callers own their schema; this function migrates nothing.\n */\nimport {\n accessSync,\n chmodSync,\n closeSync,\n existsSync,\n constants as fsConstants,\n mkdirSync,\n openSync,\n} from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { CommerceError, type Logger } from '../core';\n\nexport interface OpenSqliteOptions {\n /** File path, or ':memory:' for tests. Parent directory is created if missing */\n readonly path: string;\n /** Names the database in operator-facing errors, e.g. \"Receipt database\" */\n readonly label: string;\n readonly logger: Logger;\n}\n\nexport function openSqliteDatabase(options: OpenSqliteOptions): Database.Database {\n const { path, label, logger } = options;\n const isFileBacked = path !== ':memory:';\n\n if (isFileBacked) {\n try {\n createDirectory(dirname(path));\n } catch (cause) {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} directory \"${dirname(path)}\" cannot be created: ${cause instanceof Error ? cause.message : String(cause)}`,\n { details: { path }, cause },\n );\n }\n }\n\n // Check write access at startup. SQLite can open a read-only database and\n // report the problem only when the first write is attempted.\n if (isFileBacked && existsSync(path)) {\n try {\n accessSync(path, fsConstants.W_OK);\n } catch {\n throw new CommerceError(\n 'STORAGE_ERROR',\n `${label} \"${path}\" exists but is not writable by this process (uid ${typeof process.getuid === 'function' ? process.getuid() : 'unknown'}). If this is a container that recently changed user, an existing volume may still be owned by the previous one - recreate it (docker compose down -v) or fix its ownership.`,\n { details: { path } },\n );\n }\n }\n\n // Create the file at 0600 before SQLite creates it at 0644 (less the umask).\n // A chmod afterwards is too late: a local user who opens the file in between\n // keeps a readable descriptor across the chmod. SQLite copies the main file's\n // mode onto the -wal/-shm sidecars, so this covers all three. `mode` applies\n // on creation only; an existing file is left to the chmod below.\n if (isFileBacked) {\n try {\n closeSync(openSync(path, 'a', 0o600));\n } catch {\n // Silent on purpose: `new Database` reports the same cause with a better\n // message, or the failure is harmless and the chmod below covers it\n }\n }\n\n const db = new Database(path);\n db.pragma('journal_mode = WAL');\n db.pragma('foreign_keys = ON');\n if (isFileBacked) restrictDatabasePermissions(path, label, logger);\n return db;\n}\n\n// Create missing directory levels at 0700, preserving existing modes. Explicit\n// recursion avoids the recursive mkdir hang observed on Node 24.8.0 when /proc\n// returns ENOENT for a directory it cannot create.\nfunction createDirectory(dir: string): void {\n if (existsSync(dir)) return;\n const parent = dirname(dir);\n if (parent !== dir) createDirectory(parent);\n try {\n mkdirSync(dir, { mode: 0o700 });\n } catch (error) {\n // Created by someone else in the meantime\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n}\n\n/**\n * Narrows the database and its WAL sidecars to owner-only. The receipt ledger\n * holds no key material, but it does hold payer and payee addresses, amounts,\n * settlement hashes, replay keys and the commerce event log.\n *\n * Runs after `journal_mode = WAL`, which creates the sidecars, and also\n * tightens a database that already existed with a looser mode. A failure only\n * warns: a filesystem without POSIX modes must not stop the gateway starting.\n */\nfunction restrictDatabasePermissions(path: string, label: string, logger: Logger): void {\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n logger.warn(\n { file, label, error: code ?? 'unknown' },\n 'could not restrict database permissions to owner-only',\n );\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './chunk-PTL7SNOI.js';
|
|
2
|
+
|
|
3
|
+
// src/protocols/a2a/constants.ts
|
|
4
|
+
var A2A_SPEC_VERSION = "1.0.1";
|
|
5
|
+
var A2A_PROTOCOL_VERSION = "1.0";
|
|
6
|
+
var A2A_PROTOCOL_BINDING = "JSONRPC";
|
|
7
|
+
var A2A_AGENT_CARD_PATH = "/.well-known/agent-card.json";
|
|
8
|
+
var A2A_DEFAULT_MOUNT_PATH = "/a2a";
|
|
9
|
+
var A2A_JSON_MEDIA_TYPE = "application/json";
|
|
10
|
+
var A2A_DEFAULT_AGENT_NAME = "agent-commerce";
|
|
11
|
+
var A2A_VERSION_HEADER = "a2a-version";
|
|
12
|
+
var A2A_METHOD_SEND_MESSAGE = "SendMessage";
|
|
13
|
+
var A2A_PUSH_CONFIG_METHODS = [
|
|
14
|
+
"CreateTaskPushNotificationConfig",
|
|
15
|
+
"GetTaskPushNotificationConfig",
|
|
16
|
+
"ListTaskPushNotificationConfigs",
|
|
17
|
+
"DeleteTaskPushNotificationConfig"
|
|
18
|
+
];
|
|
19
|
+
var A2A_UNSUPPORTED_METHODS = [
|
|
20
|
+
"SendStreamingMessage",
|
|
21
|
+
"GetTask",
|
|
22
|
+
"ListTasks",
|
|
23
|
+
"CancelTask",
|
|
24
|
+
"SubscribeToTask",
|
|
25
|
+
...A2A_PUSH_CONFIG_METHODS,
|
|
26
|
+
"GetExtendedAgentCard"
|
|
27
|
+
];
|
|
28
|
+
var A2A_TASK_LOOKUP_METHODS = ["GetTask", "CancelTask"];
|
|
29
|
+
var A2A_TASK_STATE_COMPLETED = "TASK_STATE_COMPLETED";
|
|
30
|
+
var A2A_TASK_STATE_FAILED = "TASK_STATE_FAILED";
|
|
31
|
+
var A2A_TASK_STATE_INPUT_REQUIRED = "TASK_STATE_INPUT_REQUIRED";
|
|
32
|
+
var A2A_EXTENSIONS_HEADER = "a2a-extensions";
|
|
33
|
+
|
|
34
|
+
// src/protocols/a2a/descriptor.ts
|
|
35
|
+
var A2A_CAPABILITIES = [
|
|
36
|
+
"agent-card",
|
|
37
|
+
"jsonrpc",
|
|
38
|
+
"SendMessage",
|
|
39
|
+
// The x402 A2A transport, opt-in per request
|
|
40
|
+
"x402-extension"
|
|
41
|
+
];
|
|
42
|
+
var A2A_UNSUPPORTED = [
|
|
43
|
+
// Methods, as the protocol names them; the transport refuses the same list
|
|
44
|
+
...A2A_UNSUPPORTED_METHODS,
|
|
45
|
+
// Transports other than the one binding served
|
|
46
|
+
"HTTP+JSON/REST binding",
|
|
47
|
+
"gRPC binding",
|
|
48
|
+
// Behaviors
|
|
49
|
+
"SSE",
|
|
50
|
+
"long-running task persistence",
|
|
51
|
+
"task resumption other than an x402 extension payment",
|
|
52
|
+
"push notifications",
|
|
53
|
+
"multi-turn conversational continuation",
|
|
54
|
+
"authenticated extended agent cards",
|
|
55
|
+
"A2A authentication schemes",
|
|
56
|
+
"artifact types beyond Agent Commerce outcome data",
|
|
57
|
+
// Instances with separate receipt stores cannot resume each other's tasks
|
|
58
|
+
"x402 extension payments across gateway instances"
|
|
59
|
+
];
|
|
60
|
+
function buildDescriptor(implementationVersion) {
|
|
61
|
+
return {
|
|
62
|
+
name: "a2a",
|
|
63
|
+
kind: "protocol",
|
|
64
|
+
implementationVersion,
|
|
65
|
+
supportedSpec: A2A_SPEC_VERSION,
|
|
66
|
+
capabilities: A2A_CAPABILITIES,
|
|
67
|
+
status: "experimental",
|
|
68
|
+
unsupported: A2A_UNSUPPORTED
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/protocols/acp/descriptor.ts
|
|
73
|
+
var ACP_CAPABILITIES = [
|
|
74
|
+
"rest transport",
|
|
75
|
+
"well-known discovery",
|
|
76
|
+
"bearer authentication",
|
|
77
|
+
"API-Version enforcement",
|
|
78
|
+
// Forwarded as received: the gateway verifies neither signature header
|
|
79
|
+
"request header forwarding to the merchant",
|
|
80
|
+
"checkout service",
|
|
81
|
+
...ACP_CHECKOUT_OPERATIONS
|
|
82
|
+
];
|
|
83
|
+
var ACP_UNSUPPORTED = [
|
|
84
|
+
// Services this seller does not implement, named as ACP names them. The
|
|
85
|
+
// discovery document advertises `checkout` alone, and these are the reason.
|
|
86
|
+
"carts service",
|
|
87
|
+
"feed service",
|
|
88
|
+
"standalone orders service",
|
|
89
|
+
"delegate_payment",
|
|
90
|
+
"delegate_authentication",
|
|
91
|
+
// Bindings and delivery directions
|
|
92
|
+
"ACP MCP transport binding",
|
|
93
|
+
"webhooks",
|
|
94
|
+
"outbound merchant-to-agent delivery",
|
|
95
|
+
"ACP client role",
|
|
96
|
+
// Request authentication beyond the bearer token
|
|
97
|
+
"Signature header verification",
|
|
98
|
+
"Timestamp replay-window verification",
|
|
99
|
+
// Extensions, versioning and payment handlers
|
|
100
|
+
"discount extension",
|
|
101
|
+
"general ACP extension framework",
|
|
102
|
+
"multiple ACP API versions",
|
|
103
|
+
"seller-backed payment handler integration"
|
|
104
|
+
];
|
|
105
|
+
function buildDescriptor2(implementationVersion) {
|
|
106
|
+
return {
|
|
107
|
+
name: "acp",
|
|
108
|
+
kind: "protocol",
|
|
109
|
+
implementationVersion,
|
|
110
|
+
supportedSpec: ACP_SPEC_VERSION,
|
|
111
|
+
capabilities: ACP_CAPABILITIES,
|
|
112
|
+
status: "experimental",
|
|
113
|
+
unsupported: ACP_UNSUPPORTED
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export { A2A_AGENT_CARD_PATH, A2A_DEFAULT_AGENT_NAME, A2A_DEFAULT_MOUNT_PATH, A2A_EXTENSIONS_HEADER, A2A_JSON_MEDIA_TYPE, A2A_METHOD_SEND_MESSAGE, A2A_PROTOCOL_BINDING, A2A_PROTOCOL_VERSION, A2A_PUSH_CONFIG_METHODS, A2A_SPEC_VERSION, A2A_TASK_LOOKUP_METHODS, A2A_TASK_STATE_COMPLETED, A2A_TASK_STATE_FAILED, A2A_TASK_STATE_INPUT_REQUIRED, A2A_UNSUPPORTED, A2A_UNSUPPORTED_METHODS, A2A_VERSION_HEADER, ACP_UNSUPPORTED, buildDescriptor, buildDescriptor2 };
|
|
118
|
+
//# sourceMappingURL=chunk-VJH6RYRK.js.map
|
|
119
|
+
//# sourceMappingURL=chunk-VJH6RYRK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/protocols/a2a/constants.ts","../../src/protocols/a2a/descriptor.ts","../../src/protocols/acp/descriptor.ts"],"names":["buildDescriptor"],"mappings":";;;AAUO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,oBAAA,GAAuB;AAG7B,IAAM,oBAAA,GAAuB;AAO7B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAG/B,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAM/B,IAAM,kBAAA,GAAqB;AAG3B,IAAM,uBAAA,GAA0B;AAMhC,IAAM,uBAAA,GAA6C;AAAA,EACxD,kCAAA;AAAA,EACA,+BAAA;AAAA,EACA,iCAAA;AAAA,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A;AAAA,EACA,kBAAA;AAAA,EACA,yBAAA;AAAA;AAAA,EAEA,2BAAA;AAAA,EACA,UAAA;AAAA,EACA,qCAAA;AAAA,EACA,iBAAA;AAAA;AAAA,EAEA,+BAAA;AAAA,EACA,sCAAA;AAAA;AAAA,EAEA,oBAAA;AAAA,EACA,iCAAA;AAAA,EACA,2BAAA;AAAA,EACA;AACF;AAEO,SAASA,iBAAgB,qBAAA,EAAkD;AAChF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAA;AAAA,IACN,IAAA,EAAM,UAAA;AAAA,IACN,qBAAA;AAAA,IACA,aAAA,EAAe,gBAAA;AAAA,IACf,YAAA,EAAc,gBAAA;AAAA,IACd,MAAA,EAAQ,cAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AACF","file":"chunk-VJH6RYRK.js","sourcesContent":["/**\n * A2A pins, kept in one place so nothing infers one version from another.\n *\n * The specification revision and the negotiation version look alike but\n * differ: `1.0.1` names the document this adapter was written against, `1.0`\n * is what a client negotiates on the wire. Neither is this package's version\n * (`PACKAGE_VERSION`).\n */\n\n/** A2A specification revision this adapter targets */\nexport const A2A_SPEC_VERSION = '1.0.1';\n\n/** Protocol negotiation version carried on the wire */\nexport const A2A_PROTOCOL_VERSION = '1.0';\n\n/** The only transport binding this adapter serves */\nexport const A2A_PROTOCOL_BINDING = 'JSONRPC';\n\n/**\n * Fixed by the A2A specification: a client fetches the card from this exact\n * path, so it is not configurable. `src/config` reserves it against adapter\n * mounts for the same reason.\n */\nexport const A2A_AGENT_CARD_PATH = '/.well-known/agent-card.json';\n\n/** Mount serving the JSON-RPC endpoint, unless configuration says otherwise */\nexport const A2A_DEFAULT_MOUNT_PATH = '/a2a';\n\n/** Content type on both sides of every supported A2A exchange */\nexport const A2A_JSON_MEDIA_TYPE = 'application/json';\n\n/** Card identity when the operator names none. Matches the MCP adapter's default server name */\nexport const A2A_DEFAULT_AGENT_NAME = 'agent-commerce';\n\n/**\n * Version negotiation header. An absent or empty value means `0.3`, which\n * this adapter does not serve.\n */\nexport const A2A_VERSION_HEADER = 'a2a-version';\n\n/** The one JSON-RPC method this adapter serves, not the legacy `message/send` */\nexport const A2A_METHOD_SEND_MESSAGE = 'SendMessage';\n\n/**\n * Push notification configuration methods. The card declares no push\n * support, so these return `PushNotificationNotSupportedError`.\n */\nexport const A2A_PUSH_CONFIG_METHODS: readonly string[] = [\n 'CreateTaskPushNotificationConfig',\n 'GetTaskPushNotificationConfig',\n 'ListTaskPushNotificationConfigs',\n 'DeleteTaskPushNotificationConfig',\n];\n\n/**\n * A2A methods that exist and are not served here, kept apart from unknown\n * methods so a caller learns whether it hit a refused method or a typo. The\n * descriptor and the transport both read this one list.\n * `A2A_TASK_LOOKUP_METHODS` get a different error code on the wire.\n */\nexport const A2A_UNSUPPORTED_METHODS: readonly string[] = [\n 'SendStreamingMessage',\n 'GetTask',\n 'ListTasks',\n 'CancelTask',\n 'SubscribeToTask',\n ...A2A_PUSH_CONFIG_METHODS,\n 'GetExtendedAgentCard',\n];\n\n/**\n * Methods A2A gives an agent no capability flag to decline. No task can be\n * read back or canceled, so they answer `TaskNotFoundError`.\n */\nexport const A2A_TASK_LOOKUP_METHODS: readonly string[] = ['GetTask', 'CancelTask'];\n\n/**\n * Terminal states for completed and failed calls. An unpaid x402 extension\n * task instead waits in `TASK_STATE_INPUT_REQUIRED`. `GetTask` finds no task\n * in any state.\n */\nexport const A2A_TASK_STATE_COMPLETED = 'TASK_STATE_COMPLETED';\nexport const A2A_TASK_STATE_FAILED = 'TASK_STATE_FAILED';\n\n/** An unpaid x402 extension task waiting for a payment message */\nexport const A2A_TASK_STATE_INPUT_REQUIRED = 'TASK_STATE_INPUT_REQUIRED';\n\n/** Extension activation header, a comma-separated list of extension URIs */\nexport const A2A_EXTENSIONS_HEADER = 'a2a-extensions';\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the A2A specification revision (`1.0.1`), never the\n * negotiation version (`1.0`) and never this package's version. Status is\n * `experimental` while the adapter lacks the features in the unsupported list\n * below; an entry leaves that list only when its feature is implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { A2A_SPEC_VERSION, A2A_UNSUPPORTED_METHODS } from './constants';\n\n// What this adapter implements\nconst A2A_CAPABILITIES: readonly string[] = [\n 'agent-card',\n 'jsonrpc',\n 'SendMessage',\n // The x402 A2A transport, opt-in per request\n 'x402-extension',\n];\n\n/**\n * Major A2A features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const A2A_UNSUPPORTED: readonly string[] = [\n // Methods, as the protocol names them; the transport refuses the same list\n ...A2A_UNSUPPORTED_METHODS,\n // Transports other than the one binding served\n 'HTTP+JSON/REST binding',\n 'gRPC binding',\n // Behaviors\n 'SSE',\n 'long-running task persistence',\n 'task resumption other than an x402 extension payment',\n 'push notifications',\n 'multi-turn conversational continuation',\n 'authenticated extended agent cards',\n 'A2A authentication schemes',\n 'artifact types beyond Agent Commerce outcome data',\n // Instances with separate receipt stores cannot resume each other's tasks\n 'x402 extension payments across gateway instances',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'a2a',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: A2A_SPEC_VERSION,\n capabilities: A2A_CAPABILITIES,\n status: 'experimental',\n unsupported: A2A_UNSUPPORTED,\n };\n}\n","/**\n * Adapter self-description.\n *\n * `supportedSpec` is the pinned ACP snapshot, never this package's version.\n * Status is `experimental` while the adapter lacks the features in the\n * unsupported list below; an entry leaves that list only when its feature is\n * implemented.\n */\nimport type { AdapterDescriptor } from '../../core';\nimport { ACP_CHECKOUT_OPERATIONS, ACP_SPEC_VERSION } from './constants';\n\n// What this adapter implements\nconst ACP_CAPABILITIES: readonly string[] = [\n 'rest transport',\n 'well-known discovery',\n 'bearer authentication',\n 'API-Version enforcement',\n // Forwarded as received: the gateway verifies neither signature header\n 'request header forwarding to the merchant',\n 'checkout service',\n ...ACP_CHECKOUT_OPERATIONS,\n];\n\n/**\n * Major ACP features this adapter does not implement, served on\n * `/.well-known/agent-commerce` and printed by `doctor`, so no client assumes\n * full protocol support\n */\nexport const ACP_UNSUPPORTED: readonly string[] = [\n // Services this seller does not implement, named as ACP names them. The\n // discovery document advertises `checkout` alone, and these are the reason.\n 'carts service',\n 'feed service',\n 'standalone orders service',\n 'delegate_payment',\n 'delegate_authentication',\n // Bindings and delivery directions\n 'ACP MCP transport binding',\n 'webhooks',\n 'outbound merchant-to-agent delivery',\n 'ACP client role',\n // Request authentication beyond the bearer token\n 'Signature header verification',\n 'Timestamp replay-window verification',\n // Extensions, versioning and payment handlers\n 'discount extension',\n 'general ACP extension framework',\n 'multiple ACP API versions',\n 'seller-backed payment handler integration',\n];\n\nexport function buildDescriptor(implementationVersion: string): AdapterDescriptor {\n return {\n name: 'acp',\n kind: 'protocol',\n implementationVersion,\n supportedSpec: ACP_SPEC_VERSION,\n capabilities: ACP_CAPABILITIES,\n status: 'experimental',\n unsupported: ACP_UNSUPPORTED,\n };\n}\n"]}
|