@keelcodes/settlement 0.1.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.
Files changed (47) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +316 -0
  3. package/dist/a2a.d.ts +107 -0
  4. package/dist/a2a.d.ts.map +1 -0
  5. package/dist/a2a.js +254 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/erc8183.d.ts +108 -0
  8. package/dist/erc8183.d.ts.map +1 -0
  9. package/dist/erc8183.js +206 -0
  10. package/dist/erc8183.js.map +1 -0
  11. package/dist/index.d.ts +21 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +11 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/ledger.d.ts +37 -0
  16. package/dist/ledger.d.ts.map +1 -0
  17. package/dist/ledger.js +114 -0
  18. package/dist/ledger.js.map +1 -0
  19. package/dist/mpp.d.ts +78 -0
  20. package/dist/mpp.d.ts.map +1 -0
  21. package/dist/mpp.js +129 -0
  22. package/dist/mpp.js.map +1 -0
  23. package/dist/rails.d.ts +132 -0
  24. package/dist/rails.d.ts.map +1 -0
  25. package/dist/rails.js +147 -0
  26. package/dist/rails.js.map +1 -0
  27. package/dist/receipts.d.ts +25 -0
  28. package/dist/receipts.d.ts.map +1 -0
  29. package/dist/receipts.js +44 -0
  30. package/dist/receipts.js.map +1 -0
  31. package/dist/types.d.ts +100 -0
  32. package/dist/types.d.ts.map +1 -0
  33. package/dist/types.js +19 -0
  34. package/dist/types.js.map +1 -0
  35. package/dist/webhooks.d.ts +106 -0
  36. package/dist/webhooks.d.ts.map +1 -0
  37. package/dist/webhooks.js +162 -0
  38. package/dist/webhooks.js.map +1 -0
  39. package/dist/wire.d.ts +31 -0
  40. package/dist/wire.d.ts.map +1 -0
  41. package/dist/wire.js +224 -0
  42. package/dist/wire.js.map +1 -0
  43. package/dist/x402.d.ts +93 -0
  44. package/dist/x402.d.ts.map +1 -0
  45. package/dist/x402.js +196 -0
  46. package/dist/x402.js.map +1 -0
  47. package/package.json +52 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Keel contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,316 @@
1
+ # @keelcodes/settlement
2
+
3
+ Settlement core for agent payments: the protocol layer that turns an HTTP 402
4
+ handshake into a **receipt**, and a ledger that reconciles receipts against what
5
+ was intended.
6
+
7
+ Two protocols, one shape — *challenge → credential → receipt*:
8
+
9
+ | Protocol | Wire format | Status |
10
+ |---|---|---|
11
+ | **x402 v2** | `PAYMENT-REQUIRED` / `PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE` headers | ✅ codec, selection, verification, receipts |
12
+ | **MPP** (IETF `draft-httpauth-payment`) | `WWW-Authenticate: Payment …` / `Authorization: Payment …` / `Payment-Receipt` | ✅ challenge, credential, status semantics |
13
+ | **A2A x402 extension v0.1** | `x402.payment.*` message metadata | ✅ status machine, data structures, receipts |
14
+ | **ERC-8183** (Agentic Commerce) | job lifecycle + escrow | ✅ state machine, role guards, dispute/arbitration, escrow receipt |
15
+ | **Rail routing** (fiat / stablecoin) | rail catalogue + intent | ✅ deterministic `selectRail`, decimal helpers, fiat checkout handles |
16
+
17
+ The reconciliation ledger (intents, receipts, entries, derived balances and an
18
+ `ok`/`unsettled`/`orphans`/`doubleSettled` report) is ✅ today.
19
+
20
+ **Zero runtime dependencies.** Base64 and UTF-8 are hand-rolled against plain
21
+ ES2022, so the package runs in Node, browsers and edge workers alike with no
22
+ `Buffer`, no polyfills and no Keel-internal coupling.
23
+
24
+ > **Boundary: settlement ≠ billing.** This package orchestrates open payment
25
+ > protocols and keeps an audit ledger. It does *not* price anything, hold
26
+ > platform keys, or move a balance on a settled payment — whether a payment
27
+ > debits a balance is a billing concern and lives outside Keel (see
28
+ > `KEEL_PLAN.md` §6.3).
29
+
30
+ ## x402
31
+
32
+ ```ts
33
+ import {
34
+ X402_HEADERS,
35
+ parsePaymentRequired,
36
+ selectRequirement,
37
+ verifyRequirement,
38
+ intentFromRequirement,
39
+ receiptFromX402,
40
+ } from '@keelcodes/settlement';
41
+
42
+ // 1. You asked for a resource and got a 402 back.
43
+ const required = parsePaymentRequired(response.headers[X402_HEADERS.required]);
44
+
45
+ // 2. Pick the cheapest offer you can actually pay.
46
+ const accepted = selectRequirement(required.accepts, {
47
+ scheme: 'exact',
48
+ network: 'eip155:84532',
49
+ maxAmount: 10_000n, // 0.01 USDC at 6 decimals
50
+ });
51
+
52
+ // 3. Anchor the intent, then make the server prove the terms match it.
53
+ const intent = intentFromRequirement(accepted, { id: 'intent-1', payer: account, now: new Date() });
54
+ verifyRequirement(accepted, intent); // throws if payTo/asset/amount/network drifted
55
+
56
+ // 4. Sign a scheme-specific payload (your scheme module builds this) and retry
57
+ // with X402_HEADERS.signature. On success you get X402_HEADERS.response:
58
+ const receipt = receiptFromX402({
59
+ intent,
60
+ requirement: accepted,
61
+ response: parseSettlementResponse(retry.headers[X402_HEADERS.response]),
62
+ settledAt: new Date().toISOString(),
63
+ });
64
+ ```
65
+
66
+ `verifyRequirement` is the point of the whole flow: a server may ask for any
67
+ `payTo` it likes, and the intent is the only thing that catches it.
68
+
69
+ ## MPP
70
+
71
+ ```ts
72
+ import {
73
+ parseWwwAuthenticate,
74
+ decodeMppRequest,
75
+ mppIntent,
76
+ classifyMppResponse,
77
+ formatCredential,
78
+ } from '@keelcodes/settlement';
79
+
80
+ const challenge = parseWwwAuthenticate(res.headers['www-authenticate']);
81
+ const terms = decodeMppRequest<MyMethodRequest>(challenge); // your method spec
82
+
83
+ const intent = mppIntent(challenge, {
84
+ payer: account,
85
+ payee: terms.payee,
86
+ network: terms.network,
87
+ asset: terms.asset,
88
+ amount: BigInt(terms.amount),
89
+ });
90
+
91
+ // Fulfil the challenge, then retry with the credential:
92
+ const retry = await fetch(url, { headers: { authorization: formatCredential(token) } });
93
+
94
+ switch (classifyMppResponse(retry.status)) {
95
+ case 'granted': /* read Payment-Receipt */ break;
96
+ case 'challenge': /* 402: fresh challenge or a problem code */ break;
97
+ case 'policy-denied': /* 403: payment was accepted — do NOT pay again */ break;
98
+ case 'other': /* 401 etc. is not a payment problem */ break;
99
+ }
100
+ ```
101
+
102
+ The 402/403 distinction is deliberate: 403 means the payment *succeeded* and
103
+ policy denied access, so retrying with payment spends money for nothing.
104
+
105
+ ## A2A (agent-to-agent)
106
+
107
+ A2A carries payment state in `Message.metadata` under `x402.payment.*` keys and
108
+ runs a six-state machine (`payment-required → payment-submitted →
109
+ payment-verified → payment-completed | payment-failed`, plus `payment-rejected`).
110
+
111
+ ```ts
112
+ import {
113
+ A2A_METADATA_KEYS,
114
+ parsePaymentMetadata,
115
+ assertA2ATransition,
116
+ a2aIntent,
117
+ verifyA2ARequirement,
118
+ receiptFromA2A,
119
+ } from '@keelcodes/settlement';
120
+
121
+ // Merchant task metadata -> typed payment state.
122
+ const payment = parsePaymentMetadata(task.status.message.metadata);
123
+ assertA2ATransition('payment-required', 'payment-submitted');
124
+
125
+ const accepted = payment.required!.accepts[0]!;
126
+ const intent = a2aIntent(accepted, { id: 'intent-1', payer: account, now: new Date() });
127
+ verifyA2ARequirement(accepted, intent); // merchant may ask for any payTo
128
+
129
+ const receipt = receiptFromA2A({
130
+ intent,
131
+ requirement: accepted,
132
+ response: { success: true, network: accepted.network, transaction: '0xtx' },
133
+ settledAt: new Date().toISOString(),
134
+ });
135
+ ```
136
+
137
+ `X-A2A-Extensions: https://github.com/google-a2a/a2a-x402/v0.1` declares support.
138
+ Keel requires a CAIP-2 `network` even though the v0.1 examples spell it as a bare
139
+ name (`"base"`). The scheme-specific `PaymentPayload.payload` stays opaque.
140
+
141
+ ## ERC-8183 (escrow)
142
+
143
+ Agentic Commerce: a client escrows a budget, a provider submits work, and a
144
+ single evaluator attests it. `applyJobAction` is a pure reducer that enforces
145
+ both the transition table and *who* may trigger each action.
146
+
147
+ ```ts
148
+ import { applyJobAction, escrowOutcome, receiptFromEscrow } from '@keelcodes/settlement';
149
+
150
+ let job = { id, client, provider, evaluator, description, budget: 0n, expiredAt, status: 'Open' };
151
+ job = applyJobAction(job, 'setBudget', { actor: client, amount: 5_000_000n });
152
+ job = applyJobAction(job, 'fund', { actor: client, expectedBudget: 5_000_000n }); // -> Funded
153
+ job = applyJobAction(job, 'submit', { actor: provider, deliverable: '0x…' }); // -> Submitted
154
+ job = applyJobAction(job, 'complete', { actor: evaluator, reason: '0x…' }); // -> Completed
155
+
156
+ escrowOutcome(job.status); // 'release' | 'refund' | 'none'
157
+ const receipt = receiptFromEscrow(job, { network, asset, settledAt });
158
+ ```
159
+
160
+ `reject` moves between roles — the client while `Open`, the evaluator once
161
+ `Funded`/`Submitted` — and `claimRefund` is permissionless after `expiredAt`.
162
+
163
+ ### Disputes and arbitration
164
+
165
+ A funded (or submitted) job can be disputed by any party and is then frozen
166
+ until an arbiter resolves it. The detour composes with the same reducer:
167
+
168
+ ```
169
+ Funded | Submitted --raiseDispute--> Disputed --resolveDispute--> Completed (release)
170
+ \--> Rejected (refund)
171
+ ```
172
+
173
+ ```ts
174
+ import { applyJobAction, isArbiterSet, escrowOutcome } from '@keelcodes/settlement';
175
+
176
+ // arbiter is configured on the job up front.
177
+ const disputed = applyJobAction(job, 'raiseDispute', { actor: provider, reason: '0x…' });
178
+ // -> status 'Disputed', disputeReason recorded
179
+
180
+ const resolved = applyJobAction(disputed, 'resolveDispute', {
181
+ actor: arbiter,
182
+ outcome: 'release', // or 'refund'
183
+ reason: '0x…',
184
+ });
185
+ // release -> status 'Completed'; refund -> status 'Rejected'
186
+ escrowOutcome(resolved.status); // 'release' | 'refund'
187
+ ```
188
+
189
+ - `raiseDispute` is allowed for `client`, `provider` or `evaluator`, requires an
190
+ arbiter to be configured and a non-empty reason.
191
+ - `resolveDispute` is allowed **only** for the `arbiter`; `outcome` must be
192
+ `release` (escrow to the provider) or `refund` (escrow to the client).
193
+ - A `Disputed` job has no path to `complete`, `reject`, `claimRefund` or a second
194
+ `raiseDispute` — arbitration cannot be bypassed.
195
+ - `receiptFromEscrow` attests a dispute resolved to `release`, recording
196
+ `proof.resolution` and `proof.disputeReason`; a resolution to `refund` yields
197
+ no release receipt (the client is made whole instead).
198
+
199
+ ## Rail selection (fiat / stablecoin)
200
+
201
+ x402 and MPP fix *how* a payment travels; a **rail** fixes *where* it can travel.
202
+ `selectRail` filters a catalogue of `PaymentRail` descriptors against a
203
+ `PaymentIntent` and a set of constraints, then picks one deterministically.
204
+
205
+ ```ts
206
+ import { selectRail, resolveRailAsset, parseUnits, formatUnits } from '@keelcodes/settlement';
207
+
208
+ const plan = selectRail(rails, intent, {
209
+ kinds: ['chain', 'fiat'], // optional allowlists
210
+ networks: ['eip155:8453', 'iso4217:USD'],
211
+ assets: ['USDC', 'usd'],
212
+ maxAmount: parseUnits('5', 6), // cap on amount + cost
213
+ });
214
+
215
+ plan.amountDecimal; // amount rendered against the asset's decimals
216
+ plan.total; // amount + rail cost
217
+ plan.checkoutHandle; // opaque, present only for fiat rails
218
+ ```
219
+
220
+ - Rail kinds: `x402`, `mpp`, `chain` (direct on-chain stablecoin transfer) and
221
+ `fiat` (hosted checkout). Each rail carries its networks (CAIP-2), accepted
222
+ assets (`address`, `symbol`, `decimals`), an opaque `payTo`, a `cost` and a
223
+ `priority` hint.
224
+ - Selection order is **deterministic**: cheapest `cost`, then lowest `priority`,
225
+ then a fixed kind order (`RAIL_KIND_ORDER`), then rail `id`.
226
+ - Constraints (`kinds`, `networks`, `assets`, `maxAmount`) must all be
227
+ satisfiable; otherwise `selectRail` throws
228
+ `SettlementError('no-acceptable-requirement')` rather than silently routing.
229
+ - `parseUnits` / `formatUnits` are hand-rolled bigint helpers. They round-trip
230
+ exactly and reject more precision than the asset supports — unlike viem's
231
+ `parseUnits`, which rounds. `rails.units.viem.test.ts` is a differential test
232
+ pinning both the agreement on the accepted domain and that divergence.
233
+ `resolveRailAsset` proves an asset is accepted on the requested network.
234
+
235
+ > **Fiat is host-side.** A `fiat` rail only carries an opaque `checkout` handle
236
+ > that `selectRail` copies into `plan.checkoutHandle` verbatim. Keel does not
237
+ > integrate a payment service provider, create checkout sessions, or inspect the
238
+ > handle — the hosted-checkout specifics live entirely in the host.
239
+
240
+ ## What is deliberately opaque
241
+
242
+ Both protocols delegate the payment-method specifics to separate specs, and this
243
+ package does not guess at them:
244
+
245
+ - **x402** — the `PAYMENT-SIGNATURE` payload (EIP-3009 authorization, permit, …)
246
+ is built by your scheme module and carried verbatim.
247
+ - **MPP** — the challenge's `request` blob is method-specific; decode it with
248
+ your method spec via `decodeMppRequest`.
249
+
250
+ What Keel fixes is the part the core specs actually define: headers, the
251
+ requirements object, selection, the intent match, and the receipt.
252
+
253
+ ## Reconciliation
254
+
255
+ ```ts
256
+ import { Ledger } from '@keelcodes/settlement';
257
+
258
+ const ledger = new Ledger();
259
+ ledger.append({ kind: 'intent', at: t0, intent });
260
+ ledger.append({ kind: 'receipt', at: t1, receipt });
261
+
262
+ ledger.statusOf(intent.id); // 'pending' | 'settled' | 'failed'
263
+ ledger.balanceOf(account, { network, asset }); // signed sum of `entry` movements
264
+ ledger.reconcile(); // { unsettled, orphans, doubleSettled, ok }
265
+ ```
266
+
267
+ The ledger is append-only and nothing is stored mutably — status and balances are
268
+ folded from the log, so it can be replayed or shipped anywhere. Receipt ids are
269
+ deduplicated on append: a replayed settlement raises `duplicate-receipt` rather
270
+ than counting twice.
271
+
272
+ ## Webhooks
273
+
274
+ Every rail folds into the same ledger event log, so outbound notifications need
275
+ one normalised shape. `WebhookDispatcher` matches events to subscriptions and
276
+ delivers them with retries and a per-delivery audit trail.
277
+
278
+ ```ts
279
+ import { WebhookDispatcher, webhookEventFromLedgerEvent } from '@keelcodes/settlement';
280
+
281
+ const dispatcher = new WebhookDispatcher({
282
+ transport: async ({ url, body, headers }) => {
283
+ const res = await fetch(url, { method: 'POST', body, headers });
284
+ return { status: res.status };
285
+ },
286
+ signer: ({ secret, timestamp, body }) => hmacSha256Hex(secret, `${timestamp}.${body}`),
287
+ });
288
+
289
+ for (const event of ledger.events) {
290
+ await dispatcher.dispatch(subscriptions, webhookEventFromLedgerEvent(event));
291
+ }
292
+ ```
293
+
294
+ Event types: `intent.created`, `settlement.succeeded`, `settlement.failed`,
295
+ `ledger.entry`. A subscription may filter by event type and by rail
296
+ (`protocols`), and a delivery is retried on a non-2xx or thrown request (default
297
+ 3 tries, exponential backoff). Signing is a **port** — the core carries no crypto
298
+ dependency, so the host wires its own HMAC; a delivery is signed only when the
299
+ subscription has a `secret` and a signer is configured.
300
+
301
+ ## Develop
302
+
303
+ ```bash
304
+ pnpm --filter @keelcodes/settlement test
305
+ pnpm --filter @keelcodes/settlement typecheck
306
+ ```
307
+
308
+ ## Sources
309
+
310
+ - x402 v2: <https://docs.x402.org/core-concepts/http-402> and the
311
+ [x402 specification v2](https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md)
312
+ - MPP: IETF [`draft-httpauth-payment-00`](https://www.ietf.org/archive/id/draft-httpauth-payment-00.html)
313
+ ("The *Payment* HTTP Authentication Scheme", Tempo Labs / Stripe)
314
+ - A2A x402 payments extension v0.1:
315
+ [a2a-x402](https://github.com/google-agentic-commerce/a2a-x402)
316
+ - ERC-8183 Agentic Commerce: [eips.ethereum.org/EIPS/eip-8183](https://eips.ethereum.org/EIPS/eip-8183)
package/dist/a2a.d.ts ADDED
@@ -0,0 +1,107 @@
1
+ import { type Caip2, type PaymentIntent, type SettlementReceipt } from './types.js';
2
+ /**
3
+ * x402 Payments Extension for the Agent-to-Agent (A2A) protocol, v0.1
4
+ * (https://github.com/google-a2a/a2a-x402).
5
+ *
6
+ * A2A carries payment state in the `metadata` of its `Message` objects under
7
+ * `x402.payment.*` keys and layers a six-state payment machine on top of the
8
+ * A2A task state. Keel models the transport-neutral part the extension fixes:
9
+ * the metadata keys, the status machine, the data structures and the error
10
+ * codes. The scheme-specific `PaymentPayload.payload` blob stays opaque.
11
+ *
12
+ * The v0.1 examples spell `network` as a bare name (`"base"`); Keel requires a
13
+ * CAIP-2 id (`eip155:8453`) everywhere it carries a chain, and validates it on
14
+ * the way in.
15
+ */
16
+ export declare const A2A_X402_EXTENSION_URI = "https://github.com/google-a2a/a2a-x402/v0.1";
17
+ /** Clients request extension activation and servers echo it back here. */
18
+ export declare const A2A_EXTENSIONS_HEADER = "X-A2A-Extensions";
19
+ /** `Message.metadata` keys defined by the extension. */
20
+ export declare const A2A_METADATA_KEYS: {
21
+ readonly status: "x402.payment.status";
22
+ readonly required: "x402.payment.required";
23
+ readonly payload: "x402.payment.payload";
24
+ readonly receipts: "x402.payment.receipts";
25
+ readonly error: "x402.payment.error";
26
+ };
27
+ export type A2APaymentStatus = 'payment-required' | 'payment-submitted' | 'payment-rejected' | 'payment-verified' | 'payment-completed' | 'payment-failed';
28
+ export declare function isTerminalA2AStatus(status: A2APaymentStatus): boolean;
29
+ export declare function canTransitionA2A(from: A2APaymentStatus, to: A2APaymentStatus): boolean;
30
+ /** Guards a status change — an out-of-order status write is a protocol bug. */
31
+ export declare function assertA2ATransition(from: A2APaymentStatus, to: A2APaymentStatus): void;
32
+ /** Error codes the extension defines for `x402.payment.error`. */
33
+ export declare const A2A_ERROR_CODES: readonly ["INSUFFICIENT_FUNDS", "INVALID_SIGNATURE", "EXPIRED_PAYMENT", "DUPLICATE_NONCE", "NETWORK_MISMATCH", "INVALID_AMOUNT", "SETTLEMENT_FAILED"];
34
+ export type A2AErrorCode = (typeof A2A_ERROR_CODES)[number];
35
+ export declare function isA2AErrorCode(value: string): value is A2AErrorCode;
36
+ /** One accepted payment option (`PaymentRequirements`). */
37
+ export interface A2APaymentRequirements {
38
+ scheme: string;
39
+ network: Caip2;
40
+ asset: string;
41
+ payTo: string;
42
+ /** Atomic units, as a decimal string. */
43
+ maxAmountRequired: string;
44
+ resource?: string;
45
+ description?: string;
46
+ maxTimeoutSeconds?: number;
47
+ extra?: Record<string, unknown>;
48
+ }
49
+ /** `x402PaymentRequiredResponse`, sent by the merchant in the task metadata. */
50
+ export interface A2APaymentRequiredResponse {
51
+ x402Version: number;
52
+ accepts: A2APaymentRequirements[];
53
+ }
54
+ /** A signed payment authorization; `payload` is scheme-specific and opaque. */
55
+ export interface A2APaymentPayload {
56
+ x402Version: number;
57
+ network: string;
58
+ scheme: string;
59
+ payload: Record<string, unknown>;
60
+ }
61
+ /** `x402SettleResponse`, appended verbatim to `x402.payment.receipts`. */
62
+ export interface A2ASettleResponse {
63
+ success: boolean;
64
+ network: string;
65
+ transaction?: string;
66
+ payer?: string;
67
+ errorReason?: string;
68
+ }
69
+ /** The decoded contents of a `Message.metadata` record, payment-wise. */
70
+ export interface A2APaymentMetadata {
71
+ status: A2APaymentStatus;
72
+ required?: A2APaymentRequiredResponse;
73
+ payload?: A2APaymentPayload;
74
+ receipts?: A2ASettleResponse[];
75
+ error?: string;
76
+ }
77
+ /** Parses an `x402PaymentRequiredResponse` (the `x402.payment.required` value). */
78
+ export declare function parsePaymentRequiredResponse(value: unknown): A2APaymentRequiredResponse;
79
+ /** Parses a `PaymentPayload` envelope; the scheme payload stays opaque. */
80
+ export declare function parsePaymentPayload(value: unknown): A2APaymentPayload;
81
+ /** Parses an `x402SettleResponse` receipt. */
82
+ export declare function parseSettleResponse(value: unknown): A2ASettleResponse;
83
+ /** Reads the `x402.payment.*` keys out of a message metadata record. */
84
+ export declare function parsePaymentMetadata(metadata: Record<string, unknown>): A2APaymentMetadata;
85
+ /** Serialises the payment fields back into a `Message.metadata` record. */
86
+ export declare function buildPaymentMetadata(entry: A2APaymentMetadata): Record<string, unknown>;
87
+ export interface A2AIntentArgs {
88
+ id: string;
89
+ payer: string;
90
+ reference?: string;
91
+ /** Anchors `expiresAt` from `maxTimeoutSeconds` when both are present. */
92
+ now?: Date;
93
+ }
94
+ /** Builds the client-side intent from the requirement the client accepted. */
95
+ export declare function a2aIntent(requirement: A2APaymentRequirements, args: A2AIntentArgs): PaymentIntent;
96
+ /** The anti-tamper gate: a merchant may ask for any `payTo` it likes. */
97
+ export declare function verifyA2ARequirement(requirement: A2APaymentRequirements, intent: PaymentIntent): void;
98
+ export interface A2AReceiptArgs {
99
+ intent: PaymentIntent;
100
+ requirement: A2APaymentRequirements;
101
+ response: A2ASettleResponse;
102
+ /** ISO-8601 timestamp of settlement. */
103
+ settledAt: string;
104
+ }
105
+ /** Turns a successful A2A settle response into a receipt, re-checking terms. */
106
+ export declare function receiptFromA2A(args: A2AReceiptArgs): SettlementReceipt;
107
+ //# sourceMappingURL=a2a.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"a2a.d.ts","sourceRoot":"","sources":["../src/a2a.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,KAAK,EACV,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACvB,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,sBAAsB,gDAAgD,CAAC;AAEpF,0EAA0E;AAC1E,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD,wDAAwD;AACxD,eAAO,MAAM,iBAAiB;;;;;;CAMpB,CAAC;AAEX,MAAM,MAAM,gBAAgB,GACxB,kBAAkB,GAClB,mBAAmB,GACnB,kBAAkB,GAClB,kBAAkB,GAClB,mBAAmB,GACnB,gBAAgB,CAAC;AAgBrB,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAErE;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,gBAAgB,EAAE,EAAE,EAAE,gBAAgB,GAAG,OAAO,CAEtF;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,gBAAgB,EAAE,EAAE,EAAE,gBAAgB,GAAG,IAAI,CAItF;AAED,kEAAkE;AAClE,eAAO,MAAM,eAAe,uJAQlB,CAAC;AAEX,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,CAAC,CAAC;AAE5D,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,K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