uvd-describe-sdk 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.
@@ -0,0 +1,1537 @@
1
+ /**
2
+ * The failure taxonomy — and, more importantly, WHICH failures are allowed to
3
+ * disappear.
4
+ *
5
+ * ## Why the names are not new
6
+ *
7
+ * The three live consumers of describe.net each invented their own. Measured
8
+ * on 2026-08-30, they agree on the POLICY (absence is not zero; degrade
9
+ * without taking the caller down) and share not one MECHANISM:
10
+ *
11
+ * * Execution Market raises typed exceptions
12
+ * (`timeout | http_5xx | unreachable | unparseable | partial_index`).
13
+ * * MeshRelay returns null and CACHES the failure, splitting `http_4xx` out
14
+ * of EM's catch-all bucket (`describenet.js:52-58`).
15
+ * * KarmaKadabra falls through to a second source (the facilitator).
16
+ *
17
+ * So there was no de-facto contract to copy — there were three answers to one
18
+ * question, and this SDK had to pick one and defend it. It keeps EM's five
19
+ * `kind` strings verbatim (they are the reference implementation, and the
20
+ * Python SDK mirrors them) and adopts MeshRelay's `http_4xx` split, because an
21
+ * SDK — unlike a reconciler job — has to tell its caller apart from the
22
+ * network. Then it adds the two neither of them has, because neither pays.
23
+ *
24
+ * ## The two axes, and why one boolean was not enough
25
+ *
26
+ * `transient` answers "would retrying help?".
27
+ * `serviceFault` answers "is this describe.net's fault?" — i.e. is this the
28
+ * "describe está caído" that `failOpen` exists for (Saul, 2026-08-28).
29
+ *
30
+ * They are not the same question and collapsing them breaks in both
31
+ * directions. A 422 `not_an_address` is neither: swallowing it under
32
+ * `failOpen` would hide a caller's bug forever behind "this wallet has no
33
+ * reputation" — the exact confusion `null`-never-`0` exists to prevent. A
34
+ * garbled body from a 502-ing proxy IS describe's fault (so `failOpen` covers
35
+ * it) but retrying it immediately is pointless, and MeshRelay measured that:
36
+ * its retry set is `TIMEOUT | HTTP_5XX | UNREACHABLE` and deliberately excludes
37
+ * `UNPARSEABLE` (`describenet.js:161-164`).
38
+ *
39
+ * ## The third axis, added 2026-08-30: was there money in flight?
40
+ *
41
+ * `serviceFault` decides what `failOpen` may swallow — but only on the FREE
42
+ * routes. On a metered route the question never gets asked, because the answer
43
+ * would be irrelevant: a swallowed failure after settlement is a spent
44
+ * credential with no receipt (see `client.ts`, "the paid routes never fail
45
+ * open"). So `DescribeError` gained an optional `payment`, and its mere
46
+ * presence is the statement *"a signed envelope had already left this process
47
+ * when this failed"*. Read it with `failedAfterPaying()`.
48
+ *
49
+ * ## The half the booleans never had, added 2026-08-30: what to do INSTEAD
50
+ *
51
+ * `transient` answers *would retrying help?* and stops there. A `false` leaves
52
+ * the caller holding a failure and no next move, which is how a fleet ends up
53
+ * hammering a door that closed — **Execution Market**, `#agents`, 2026-08-30,
54
+ * measuring their own: *"contra `AUTHORIZATION_EXPIRED` reintentar es quemar
55
+ * llamadas contra una ventana cerrada hace 317 HORAS"*. They typed a `recovery`
56
+ * into their 502 and asked the ecosystem to do the same.
57
+ *
58
+ * So every error carries `recovery`: one sentence naming ANOTHER thing to do —
59
+ * another route (usually a free one), another field, or the condition on the
60
+ * caller's side that has to be fixed. It is `null` when there honestly is none,
61
+ * which is a decision and not an omission. The texts live in `recovery.ts`,
62
+ * frozen, one per kind, and this constructor is the only thing that reads them.
63
+ *
64
+ * 🔴 What was NOT copied is their ten codes — escrow, payout wallets,
65
+ * `AUTHORIZATION_EXPIRED` — because that is their API's vocabulary and this SDK
66
+ * wraps describe.net. The pattern crossed over; the table was re-derived here.
67
+ */
68
+ /** The closed set. Consumers switch on `kind`, never on `message`. */
69
+ type DescribeErrorKind =
70
+ /** The request outlived the client timeout — includes provider cold starts. */
71
+ 'timeout'
72
+ /** describe.net answered 5xx. Its fault, and retryable. */
73
+ | 'http_5xx'
74
+ /**
75
+ * describe.net answered 4xx. Ours, not theirs: 422 `not_an_address` is the
76
+ * common member. 429 (the shared 20 rps) also lands here and is the one 4xx
77
+ * that IS transient — see `transient` on the instance, not on the kind.
78
+ */
79
+ | 'http_4xx'
80
+ /**
81
+ * The route answered 404. **This is data, not a failure** — and it is the
82
+ * one entry of this union that never reaches a caller as a thrown error.
83
+ *
84
+ * R4 is absolute: no exception for "there is no data". A 404 says exactly
85
+ * that, so the method returns its absence value (`null`) whether `failOpen`
86
+ * is on or off — `failOpen` is about outages and this is about absence, two
87
+ * different axes.
88
+ *
89
+ * It is still reported through `onFailure`, and that is deliberate: a
90
+ * mistyped `baseUrl` makes every route 404, and a silent `null` forever
91
+ * would be indistinguishable from "nobody in this index has any reputation".
92
+ * `transient` is false and the kind names itself, so a caller who expects
93
+ * misses can filter it in one line.
94
+ *
95
+ * As of 2026-08-30 no route this SDK wraps returns 404 for a valid input:
96
+ * an unregistered wallet is a **200** with nulls, and a malformed one is a
97
+ * **422**. It is here for the agent route and for whatever the API adds.
98
+ */
99
+ | 'not_found'
100
+ /** Transport died before any status: DNS, connect, reset, CORS, offline. */
101
+ | 'unreachable'
102
+ /** A body arrived and could not be read into the typed shape. */
103
+ | 'unparseable'
104
+ /**
105
+ * The index answered, but its coverage is partial for what was asked.
106
+ *
107
+ * This SDK never raises it — a partial index is served as a 200 whose
108
+ * `chains[]` simply lacks rows, which is data. It exists so a caller that
109
+ * DETECTS partial coverage (a chain it writes to that the index does not
110
+ * scan) can classify it inside the same taxonomy instead of inventing a
111
+ * sixth one. Kept for parity with EM's reference (`types.py:82-92`).
112
+ */
113
+ | 'partial_index'
114
+ /**
115
+ * A metered route answered 402 and this client has no `payer` configured.
116
+ *
117
+ * Protocol, not absence: the index is up and told us its price. Never
118
+ * swallowed by `failOpen` — a caller who forgot to wire a payer must find
119
+ * out, and the challenge is attached so they can read the price without
120
+ * paying (asking is free, and is the intended first move).
121
+ */
122
+ | 'payment_required'
123
+ /**
124
+ * A 402 challenge named a `payTo` that is not the pinned treasury.
125
+ *
126
+ * `DO_NOT_PAY`. Never a retry, never `failOpen`-able: the one failure where
127
+ * continuing quietly costs real USDC to a stranger.
128
+ */
129
+ | 'payment_refused'
130
+ /**
131
+ * A hash field arrived carrying something that is not a hash.
132
+ *
133
+ * 🔴 **Never thrown.** It travels only through `onFailure`, and the class that
134
+ * carries it says so in its own first line — see {@link DescribeMalformedHash}.
135
+ * Branch on this `kind`, never on a `catch` that will not fire.
136
+ */
137
+ | 'malformed_hash'
138
+ /**
139
+ * Partner mode is configured and the signature could not be produced AT ALL.
140
+ *
141
+ * The CALLER's configuration, not describe.net's: an unset env var, a signer
142
+ * that refuses, a wallet that is locked. `serviceFault: false`, so `failOpen`
143
+ * never swallows it — on a free route either. A partner client that silently
144
+ * loses its signature is a partner client that silently starts paying, and
145
+ * that is the whole failure this rail exists to make impossible.
146
+ */
147
+ | 'partner_unsigned'
148
+ /**
149
+ * We signed, and describe.net charged anyway.
150
+ *
151
+ * The signature was produced and sent, and the metered route still answered
152
+ * 402 — so the gate did not exempt us. Measured causes, in the order they
153
+ * happen in real life (`describe-net/describenet/partner.py`):
154
+ *
155
+ * * the wallet is not in the allowlist (`partner.py:242`), i.e. nobody has
156
+ * added this partner yet — Execution Market is registered, KarmaKadabra
157
+ * and MeshRelay are NOT, as of 2026-08-30;
158
+ * * the signed `@authority` is not `api.describe.net` (`partner.py:84`) —
159
+ * which is what a custom `baseUrl` produces, including the raw
160
+ * execute-api host behind CloudFront, deliberately;
161
+ * * the keyid's chain is not 8453 (`partner.py:90`);
162
+ * * the clock is off by more than 30 s ahead or the signature is older than
163
+ * 300 s (`partner.py:95-96`).
164
+ *
165
+ * `payment` is ABSENT and that is load-bearing: nothing was signed, nothing
166
+ * was sent, nothing was spent. This error is the moment BEFORE the money.
167
+ */
168
+ | 'partner_rejected';
169
+ /**
170
+ * What this SDK can honestly say about the USDC when a metered call fails.
171
+ *
172
+ * ## Why an object and not a boolean
173
+ *
174
+ * A bare `DescribeTimeout` cannot tell "it died before we paid" (you spent
175
+ * nothing) from "it died after" (you may have spent and got nothing back).
176
+ * Those are different conversations — the first is a retry, the second is a
177
+ * reconciliation — and the exception has to carry which one it is.
178
+ *
179
+ * ## The rule, and it is the whole point of this type
180
+ *
181
+ * **`error.payment` exists ⇔ a signed `X-PAYMENT` envelope had already left
182
+ * this process.** Its ABSENCE on a metered failure is therefore itself an
183
+ * answer: nothing was transmitted, so nothing could have settled. That covers
184
+ * the 402 with no payer, the `DO_NOT_PAY` refusal, the 404 (which arrives
185
+ * before any challenge is even read), and a payer that threw while signing —
186
+ * an EIP-3009 authorization that never leaves the payer moves no money, because
187
+ * money moves when the SELLER submits it, not when the buyer signs it.
188
+ *
189
+ * ## `settlement`, and the one thing it will not do is guess
190
+ *
191
+ * `'settled'` is asserted only against proof in hand: `X-Payment-Receipt`, whose
192
+ * value is the settlement transaction hash (or the literal `"pending"`). Read on
193
+ * 2026-08-30 in the service's own middleware —
194
+ * `describe-net/describenet/paywall.py:1031-1065` — the paywall settles inside
195
+ * `authorize()` **before** `call_next(request)` runs the handler, and then
196
+ * attaches the receipt headers to whatever response comes back. A non-2xx
197
+ * response with a receipt is therefore a settlement that happened, stated by the
198
+ * seller.
199
+ *
200
+ * `'unknown'` is everything else, and it is honest rather than pessimistic. Two
201
+ * measured holes forbid upgrading it to a verdict:
202
+ *
203
+ * 1. **A 500 can be settled and carry no receipt.** If the handler raises,
204
+ * Starlette's `ServerErrorMiddleware` — which sits OUTSIDE the paywall
205
+ * middleware, verified 2026-08-30: `api.py:2110` is the only
206
+ * `add_middleware` for it and `api.py` registers no exception handler —
207
+ * answers 500 without the header line ever running. The money moved in
208
+ * `authorize()` regardless.
209
+ * 2. **A dead socket proves nothing.** `fetch` rejects the same way whether
210
+ * the connection died before the request bytes were written or while the
211
+ * response was coming back.
212
+ *
213
+ * So: `'settled'` means *we hold the hash*. `'unknown'` means *ask the chain* —
214
+ * never *"nothing happened"*. If you need the stronger answer, the receipt of a
215
+ * later successful call and the on-chain transfer to the treasury are where it
216
+ * lives; this SDK will not infer it for you.
217
+ */
218
+ interface PaymentAttempt {
219
+ /** `'settled'` only with a receipt in hand. See the header of this type. */
220
+ settlement: 'settled' | 'unknown';
221
+ /** `X-Payment-Receipt` — the settlement tx hash, or `"pending"`. */
222
+ receipt: string | null;
223
+ /** `X-Payment-Reused: true` means an earlier receipt was replayed, no new charge. */
224
+ reused: boolean | null;
225
+ /** The status of the answer that failed, when an answer arrived at all. */
226
+ status?: number;
227
+ /** What the challenge asked for. Copied, never re-priced. */
228
+ amount?: string;
229
+ token?: string;
230
+ /** The recipient we verified against the pinned treasury before signing. */
231
+ payTo?: string;
232
+ }
233
+ declare class DescribeError extends Error {
234
+ readonly kind: DescribeErrorKind;
235
+ /** Would retrying help? Drives backoff, never `failOpen`. */
236
+ readonly transient: boolean;
237
+ /** Is this describe.net's fault? Drives `failOpen`, never retry. */
238
+ readonly serviceFault: boolean;
239
+ /** Present when a status was actually received. */
240
+ readonly status?: number;
241
+ /**
242
+ * What to do INSTEAD, in one sentence — or `null` when there honestly is
243
+ * nothing beyond the retry `transient` already announces (`timeout` is the
244
+ * one, and `recovery.ts` says why at the entry).
245
+ *
246
+ * 🔴 **Branch on `kind`, read this.** It is prose meant for a human or an
247
+ * agent, it is free to be re-worded, and matching on it is the mistake the
248
+ * caveat codes exist to prevent one level up.
249
+ *
250
+ * 🔴 It is always one of the frozen literals in `recovery.ts` — never built
251
+ * from a message, a URL or a `cause`. That is the redaction guard: a
252
+ * transport exception can carry an endpoint with an API key in it, and this
253
+ * is the string most likely to end up pasted into a ticket.
254
+ */
255
+ readonly recovery: string | null;
256
+ /**
257
+ * Set **only** when a signed envelope was already in flight. Not readonly for
258
+ * one reason: the failure is built deep in the transport, which knows nothing
259
+ * about payment, and `attachPayment()` stamps it on the way out. Treat it as
260
+ * readonly — nothing in this package writes it twice.
261
+ */
262
+ payment?: PaymentAttempt;
263
+ constructor(kind: DescribeErrorKind, message: string, opts?: {
264
+ transient: boolean;
265
+ serviceFault: boolean;
266
+ status?: number;
267
+ cause?: unknown;
268
+ });
269
+ }
270
+ declare class DescribeTimeout extends DescribeError {
271
+ constructor(message: string, cause?: unknown);
272
+ }
273
+ declare class DescribeUnreachable extends DescribeError {
274
+ constructor(message: string, cause?: unknown);
275
+ }
276
+ declare class DescribeUnparseable extends DescribeError {
277
+ constructor(message: string, cause?: unknown);
278
+ }
279
+ /**
280
+ * A hash field arrived with something that is not a hash.
281
+ *
282
+ * Contributed by **KarmaKadabra** (`#agents`, 2026-08-30), out of the finding
283
+ * they call *"el 200 sin tx"*: *"si nosotros no chequeáramos el tx, habríamos
284
+ * contado 14 ratings que no existen"*. A 200 that did not do the thing is worse
285
+ * than a 503, because the client takes it for good.
286
+ *
287
+ * 🔴 **THIS IS NEVER THROWN. Do not write a `catch` for it.** It travels only as
288
+ * the `error` of a {@link DescribeFailure} handed to `onFailure`, and it exists
289
+ * as a class for one mechanical reason: that channel is typed
290
+ * `DescribeError`, so reusing the channel the consumer is ALREADY watching —
291
+ * which is what KarmaKadabra asked for — requires the fact to BE a
292
+ * `DescribeError`. Branch on `kind === 'malformed_hash'` or on `instanceof`,
293
+ * never on a `try/catch` that will not fire.
294
+ *
295
+ * ⚠️ There is a tension with this taxonomy and it is declared rather than
296
+ * papered over: `partial_index` is also documented as never raised, and it is
297
+ * kept only for parity with Execution Market's reference. Publishing exceptions
298
+ * nobody throws invites dead `catch` blocks. What separates the two is what the
299
+ * class is FOR: `partial_index` exists so someone can catch it and nobody will,
300
+ * this one exists to ride a channel that is already typed, and its first line
301
+ * shouts as much. If `onFailure` ever accepts something wider than a
302
+ * `DescribeError`, this class stops being necessary.
303
+ *
304
+ * Why the failure does NOT take the read down: the rest of the response is very
305
+ * likely useful, and killing a whole reputation breakdown over an accessory
306
+ * field would be worse than the bug being hunted — especially on a metered
307
+ * route, where the read has already been paid for. The typed field is left
308
+ * `null` so nobody builds an explorer link out of garbage, and the raw value
309
+ * survives in the result's `raw`, which is where it gets investigated.
310
+ *
311
+ * 🔴 **Absent and malformed are NOT the same thing, and the result keeps them
312
+ * apart** (R1, one level below where it usually lives):
313
+ *
314
+ * ```
315
+ * rating.txHash === null, malformedHashes empty → IT DID NOT COME
316
+ * rating.txHash === null, 'tx_hash' in malformedHashes → GARBAGE CAME
317
+ * ```
318
+ *
319
+ * `fields` carries the location of each one, with an index when it is inside a
320
+ * list: `['ratings[3].tx_hash', 'snapshot.inputs_digest']`. Wire names, not
321
+ * ours, because this string ends up in a ticket to whoever runs the index.
322
+ *
323
+ * `serviceFault` is **false** even though the bad data is describe.net's: this
324
+ * flag drives `failOpen`, and a read that succeeded has nothing to fail open
325
+ * INTO. `transient` is false for the same kind of reason — the same request will
326
+ * bring the same bad field back.
327
+ */
328
+ declare class DescribeMalformedHash extends DescribeError {
329
+ /** Qualified paths of the fields that arrived malformed, in order. */
330
+ readonly fields: string[];
331
+ constructor(message: string, fields: string[]);
332
+ }
333
+ /**
334
+ * 404 — absence.
335
+ *
336
+ * ⚠️ **CORRECTED 2026-08-30, and the old text is left below because somebody
337
+ * will come looking for it.** It used to say: *"`DescribeClient.guard` converts
338
+ * it to `null` before any caller sees it, which is why this class is not
339
+ * exported from the package index: 'a 404 never reaches the caller as an error'
340
+ * is structural here"*. That stopped being true when the metered methods lost
341
+ * their `| null` return: `walletBreakdown()` and `agent()` have no absence value
342
+ * left to degrade INTO, so on those two routes a 404 arrives as this exception,
343
+ * and the class is now exported so `instanceof` works.
344
+ *
345
+ * On the free routes nothing changed — still `null`, still announced through
346
+ * `onFailure`, still regardless of `failOpen`.
347
+ *
348
+ * Absence did not become a failure; it changed clothes. It keeps
349
+ * `transient: false`, `serviceFault: false`, and — the load-bearing part — **no
350
+ * `payment`**: a metered 404 is checked before the challenge is even read, so
351
+ * nothing was signed and nothing was spent to learn that there is nothing there.
352
+ */
353
+ declare class DescribeNotFound extends DescribeError {
354
+ constructor(message: string);
355
+ }
356
+ declare class DescribeHTTPError extends DescribeError {
357
+ constructor(status: number, message: string);
358
+ }
359
+ /** The parsed 402, as served. Kept raw: we read it, we never re-price it. */
360
+ interface X402Challenge {
361
+ /** Human price, e.g. `"0.01"`. From the challenge — never typed by us. */
362
+ amount?: string;
363
+ /** Default recipient. Checked against the pinned treasury before paying. */
364
+ recipient?: string;
365
+ recipients?: Record<string, string | undefined>;
366
+ token?: string;
367
+ supportedChains?: number[];
368
+ accepts?: Array<Record<string, unknown>>;
369
+ /** Everything else the challenge carried, untouched (passthrough rule). */
370
+ [key: string]: unknown;
371
+ }
372
+ declare class DescribePaymentRequired extends DescribeError {
373
+ readonly challenge: X402Challenge;
374
+ constructor(message: string, challenge: X402Challenge);
375
+ }
376
+ declare class DescribePaymentRefused extends DescribeError {
377
+ readonly challenge: X402Challenge;
378
+ readonly expected: string;
379
+ readonly offered: string | undefined;
380
+ constructor(expected: string, offered: string | undefined, challenge: X402Challenge);
381
+ }
382
+ /**
383
+ * Partner mode is on and the signature could not be produced.
384
+ *
385
+ * ## Why this THROWS instead of quietly paying, on every route
386
+ *
387
+ * The alternative is the one thing a partner rail must never do. Without a
388
+ * signature the request is an ordinary anonymous request: describe.net answers
389
+ * 402 on a metered route and the configured payer settles it, in USDC, silently
390
+ * — the consumer keeps getting answers and only finds out at the invoice. Saul
391
+ * asked for a rail where our own products read for free; a rail that degrades
392
+ * into paying is not that rail, it is a bill.
393
+ *
394
+ * So this is a CALLER-fault error (`serviceFault: false`), which means
395
+ * `failOpenCovers()` is `false` for it and `failOpen: true` does not swallow it
396
+ * — not even on the free routes, where the signature costs nothing and buys
397
+ * nothing. That is deliberate and not an oversight: a partner whose signer is
398
+ * broken on `/health` has the same broken signer on
399
+ * `/reputation/wallet/{w}` thirty seconds later, and the free call is the
400
+ * cheapest possible place to find out.
401
+ *
402
+ * It carries no `payment` — nothing was sent, so nothing could have settled.
403
+ *
404
+ * 🔴 `cause` is the signer's own error and this class never reads it, never
405
+ * reformats it and never puts it in `message`. A signer that fails on a
406
+ * malformed key can have key material inside its exception (measured: see
407
+ * `partner/index.ts`, the ethers `invalid BytesLike value` finding), and this
408
+ * SDK will not be the thing that copies it into a log line.
409
+ */
410
+ declare class DescribePartnerUnsigned extends DescribeError {
411
+ /** The signing address, when the signer published one. Public by design. */
412
+ readonly address: string | undefined;
413
+ constructor(path: string, address: string | undefined, cause: unknown);
414
+ }
415
+ /**
416
+ * We signed as a partner and describe.net asked for money anyway.
417
+ *
418
+ * ## The case this class exists for, and it is the important one
419
+ *
420
+ * A partner client that gets a 402 has lost its free rail. If it falls through
421
+ * to the payer, the fall is invisible: same answers, same latency, same shape —
422
+ * and USDC leaving a wallet that budgeted none. The alternative failure (a loud
423
+ * throw) costs one broken read and a fixable configuration; the silent one costs
424
+ * money for as long as nobody looks.
425
+ *
426
+ * So partner mode does NOT pay by default. `partnerFallsBackToPaying: true`
427
+ * turns it back on as an explicit, typed decision by the caller — the flag
428
+ * exists so that "pay anyway" is something someone WROTE, never something that
429
+ * happened.
430
+ *
431
+ * The challenge is attached unpaid, so a caller who decides to pay after all can
432
+ * read exactly what it would have cost. And `payment` is absent: this is thrown
433
+ * before `payer.pay()` is ever reached, so nothing was signed and nothing moved.
434
+ */
435
+ declare class DescribePartnerRejected extends DescribeError {
436
+ readonly challenge: X402Challenge;
437
+ /** The address we signed with. Public by design — the allowlist is public. */
438
+ readonly address: string | undefined;
439
+ constructor(path: string, address: string | undefined, challenge: X402Challenge);
440
+ }
441
+ /**
442
+ * Does `failOpen` cover this failure?
443
+ *
444
+ * The single predicate, so the rule lives in one place instead of being
445
+ * re-derived at each call site. Saul's words were "pon un fallback si es que
446
+ * describe está caído" — `serviceFault` is the typed form of "está caído", and
447
+ * nothing else qualifies.
448
+ *
449
+ * ⚠️ **Corrected 2026-08-30 — this predicate answers a smaller question than it
450
+ * used to.** It was the ONLY gate: every method ran its failure through it, so
451
+ * `walletBreakdown()` and `agent()` returned `null` on any `serviceFault`,
452
+ * including a timeout that arrived AFTER settlement. That is a spent credential
453
+ * with no receipt, and the caller never learned they had paid. The rule now has
454
+ * a term this predicate cannot see — *was there money in flight* — so the
455
+ * metered methods never call it at all. It is still exported, and calling it
456
+ * yourself on a paid failure answers a question you should not be asking: use
457
+ * `failedAfterPaying()` instead.
458
+ */
459
+ declare function failOpenCovers(error: unknown): error is DescribeError;
460
+ /**
461
+ * Did this failure happen with a signed envelope already in flight?
462
+ *
463
+ * `true` means the money MAY have moved and you should reconcile; read
464
+ * `error.payment` for the receipt (proof) or the `'unknown'` that says the SDK
465
+ * cannot tell. `false` means nothing was transmitted — a 402 with no payer, a
466
+ * `DO_NOT_PAY`, a 404, a payer that declined, or any failure on a free route.
467
+ */
468
+ declare function failedAfterPaying(error: unknown): error is DescribeError & {
469
+ payment: PaymentAttempt;
470
+ };
471
+
472
+ /**
473
+ * The caveat codes, exported as a contract.
474
+ *
475
+ * ## The rule, and it is theirs, not ours
476
+ *
477
+ * describe.net declares it in `describenet/caveats.py:88-93`:
478
+ *
479
+ * > **EL TEXTO puede cambiar sin aviso** —re-redactarse, re-medirse, hasta
480
+ * > traducirse—; **EL CODE jamás.**
481
+ *
482
+ * So a consumer branches on `code` and renders `text`, never the reverse. This
483
+ * is not hygiene, it is a repair: until 2026-08-28 a caveat was a bare Spanish
484
+ * string, ecosystem consumers matched on the prose, and when the thin-evidence
485
+ * cut moved on 2026-08-25 every one of those matches broke silently — the
486
+ * string comparison kept returning false and nobody was told.
487
+ *
488
+ * Exporting the set is one of the four "día 0" requirements the platform team
489
+ * put on any SDK of the house (`D9-c0der.md:234-241`): *los caveat `code`s como
490
+ * contrato exportado*. Typing them here means a consumer never re-types them,
491
+ * and a typo is a compile error rather than a branch that is never taken.
492
+ *
493
+ * ## Why the type is not a closed union
494
+ *
495
+ * `CaveatCode | (string & {})` gives autocomplete on the eight codes that exist
496
+ * today AND still accepts a ninth one the server adds tomorrow. A closed union
497
+ * would turn every new server-side code into a type error in code that is
498
+ * already deployed and working — the passthrough rule (tipar lo conocido,
499
+ * CONSERVAR lo que no) applied to the type system. The measured precedent is
500
+ * `Facet.direction`: FastAPI silently dropped a field nobody had declared, and
501
+ * the response looked correct with the data missing.
502
+ *
503
+ * The codes carry no version and never bump `POLICY_VERSION`: a caveat is
504
+ * advisory by construction and identifies a CUT, it never moves a score.
505
+ */
506
+ /**
507
+ * The eight cuts served on 2026-08-30, copied from the frozen set in
508
+ * `describenet/caveats.py:172-183` (which its own
509
+ * `tests/test_caveat_codes.py` pins literally, so adding or renaming one over
510
+ * there goes red on purpose).
511
+ *
512
+ * Only `no-score` and `burn-address` are computable from public data, so the
513
+ * free routes serve a documented SUBSET — an empty `caveats: []` on a free
514
+ * response means "no public-data caveat", NOT "clean". The other six need the
515
+ * grain and ride the metered routes. See `CAVEAT_SCOPE_FREE`.
516
+ */
517
+ declare const CAVEAT_CODES: readonly ["no-score", "concentration-degraded", "single-rater", "few-raters", "top-client-share", "campaign-per-rater", "self-rated", "burn-address"];
518
+ /** The eight known codes as a union — for `switch`, not for validation. */
519
+ type KnownCaveatCode = (typeof CAVEAT_CODES)[number];
520
+ /**
521
+ * What a caveat's `code` may be: one of the eight, or any string the server
522
+ * starts sending. The `(string & {})` half is what keeps autocomplete alive
523
+ * while leaving the union open.
524
+ */
525
+ type CaveatCode = KnownCaveatCode | (string & {});
526
+ /** As served since 2026-08-28: `{code, text}`, never a bare string. */
527
+ interface Caveat {
528
+ /** The contract. Stable, kebab-case. Branch on this. */
529
+ code: CaveatCode;
530
+ /** Prose. May be re-worded, re-measured or translated without notice. Render this. */
531
+ text: string;
532
+ }
533
+ /**
534
+ * What an empty `caveats: []` claims on a FREE route.
535
+ *
536
+ * describe.net's own definition (given 2026-08-29, recorded in
537
+ * `meshrelay/describenet.js:265-277`): on the free routes `[]` means "no
538
+ * PUBLIC-DATA caveat", not "no caveats" — the evidence-quality cuts are only
539
+ * computable behind the metered routes. A surface that renders a bare `[]` as
540
+ * "clean" publishes a claim the index never made. Carry the scope with the
541
+ * list, the same discipline as the `n/m` coverage next to any aggregate.
542
+ */
543
+ declare const CAVEAT_SCOPE_FREE = "public-data-subset";
544
+ /** Everything a metered route can fire — the free subset plus the six from the grain. */
545
+ declare const CAVEAT_SCOPE_METERED = "full";
546
+ /**
547
+ * Is this code known to the version of the SDK you have installed?
548
+ *
549
+ * Deliberately NOT a validator: a `false` means "we have not heard of it",
550
+ * never "it is invalid". An unknown code is served through untouched.
551
+ */
552
+ declare function isKnownCaveatCode(code: string): code is KnownCaveatCode;
553
+ /**
554
+ * Does this result carry `code`?
555
+ *
556
+ * Exists so consumers stop writing `caveats.some(c => c.text.includes('...'))`
557
+ * — the exact line that broke silently on 2026-08-25.
558
+ */
559
+ declare function hasCaveat(subject: {
560
+ caveats?: readonly Caveat[];
561
+ } | null | undefined, code: CaveatCode): boolean;
562
+
563
+ /**
564
+ * The wire shapes — hand-written, and here is the argument for that.
565
+ *
566
+ * ## Why not generated from the OpenAPI
567
+ *
568
+ * The schema is live, complete (20 paths, `securitySchemes.x402`, every field
569
+ * typed) and generating from it would tie these types to it for free. It was
570
+ * measured and rejected for three reasons, in increasing order of weight:
571
+ *
572
+ * 1. **Surface.** This SDK wraps 4 of the 20 paths. `openapi.snapshot.json`
573
+ * carries 41 component schemas; generating produces every one of them, so a
574
+ * package whose whole public surface is six methods would ship ~40
575
+ * interfaces nobody reviewed. Unreviewed code in a package other people
576
+ * install is a liability, not a saving.
577
+ *
578
+ * 2. **A build dependency for a package that has none.** The whole dependency
579
+ * argument of this SDK is that a free-only consumer installs nothing. Adding
580
+ * a generator plus its runtime to make that true is a strange trade.
581
+ *
582
+ * 3. **And the real one: the schema cannot say what matters here.** It says
583
+ * `global_score: number | null`. It does NOT say that the `null` means "no
584
+ * evidence" and must never be coerced to `0` — which is the single most
585
+ * important fact about this API, the invariant the index is built around,
586
+ * and the thing every consumer gets wrong first. Generated types carry no
587
+ * docstring, so the schema's shape would be pinned and the product's thesis
588
+ * would be nowhere. In this package the comment IS the deliverable.
589
+ *
590
+ * ## What replaces generation
591
+ *
592
+ * The third way: hand-written types PLUS a test that compares them against the
593
+ * schema, at two speeds.
594
+ *
595
+ * * `types.schema.test.ts` runs in the normal loop, offline, against
596
+ * `schema/openapi.snapshot.json` — a pinned copy of the live schema fetched
597
+ * 2026-08-30. It fails when a hand-written type drifts from the schema.
598
+ * * `npm run schema:check` re-fetches the live schema and diffs it against
599
+ * the snapshot. It fails when the SERVER moves. Deliberate, networked, and
600
+ * never in the test loop (tests do not touch the network).
601
+ *
602
+ * Two gates because there are two different failures: we drifted, and they
603
+ * moved. Generation conflates them into "the build broke" and tells you
604
+ * nothing about which happened.
605
+ */
606
+
607
+ /** The eleven indexed chains are strings on the wire. Never an enum here: the index adds chains. */
608
+ type Network = string;
609
+ /** ISO-8601 as served. `null` means "not recorded" — never "just now". */
610
+ type Timestamp = string | null;
611
+ /**
612
+ * The receipt headers describe.net's paywall has been emitting since
613
+ * 2026-08-25 and that, as of 2026-08-30, NO client reads.
614
+ *
615
+ * `X-Payment-Receipt` is the settlement id; `X-Payment-Reused` says the call
616
+ * was served against a receipt already settled rather than a fresh payment.
617
+ * Surfacing them is the point: without them a caller who paid has no local
618
+ * record of having paid, and cannot tell a re-served response from a second
619
+ * charge. Present only on metered responses that actually went through payment.
620
+ */
621
+ interface PaymentEvidence {
622
+ /**
623
+ * The settlement id, or `null` when none was served **or when what was served
624
+ * was not one** — `malformedHashes` tells the two apart.
625
+ *
626
+ * Validated with its own rule (`hashes.looksLikeSettlementReceipt`) because
627
+ * this is the one field where `"pending"` is a legitimate value: the live
628
+ * OpenAPI declares the header as the settlement transaction hash *"or
629
+ * `pending` if settlement has not reported one"*. Treating that as garbage
630
+ * would fire an alarm on the happy path of every fresh payment.
631
+ */
632
+ receipt: string | null;
633
+ reused: boolean;
634
+ /**
635
+ * `['receipt']` when the header carried something that is neither a hash nor
636
+ * `pending`. Empty in the normal case, and empty when no header came at all.
637
+ *
638
+ * ⚠️ This is the one malformed value that does NOT survive in a result's
639
+ * `raw`, and the reason is structural: `raw` is the response BODY and this
640
+ * arrived as a header. So the offending string is put in the `onFailure`
641
+ * message instead — it is the only place it can be kept.
642
+ */
643
+ malformedHashes: string[];
644
+ }
645
+ /**
646
+ * Every result of this SDK carries its composition seal.
647
+ *
648
+ * R2 and it is the product's thesis, not a convention: *"un score sin sus
649
+ * calificadores es un rumor"*. There is deliberately NO method here that
650
+ * returns a bare `number`, and adding one would erase the reason the index
651
+ * exists. If you want the number alone you take it off the object by hand, and
652
+ * that friction is the feature.
653
+ *
654
+ * `policyVersion` travels because a score is only comparable to another score
655
+ * under the SAME policy: KarmaKadabra measured its flagship wallet going
656
+ * 86.33 → 81.41 with MORE reviews, purely because the policy revised. Two
657
+ * numbers from different `policy_version`s are not two measurements of one
658
+ * thing.
659
+ */
660
+ interface Sealed {
661
+ /** e.g. `equal-weight-per-chain@2`. Compare scores only within one value of this. */
662
+ policyVersion: string | null;
663
+ /** Advisory. Branch on `code`, render `text`. Never moves a score. */
664
+ caveats: Caveat[];
665
+ /** `public-data-subset` on free routes, `full` on metered ones. */
666
+ caveatScope: string;
667
+ /** Which route produced this — `chain_rankings_mv`, a matview name, etc. */
668
+ source: string | null;
669
+ /** When the index last recomputed the value. `null` = not recorded. */
670
+ refreshedAt: Timestamp;
671
+ /** The exact JSON as served, unmodified. See `raw` below. */
672
+ raw: Record<string, unknown>;
673
+ }
674
+ /**
675
+ * `raw` on every result is the passthrough rule made concrete.
676
+ *
677
+ * Tipar lo conocido, CONSERVAR lo que no. The measured lesson is
678
+ * `Facet.direction`: a field the server was serving got dropped by a layer that
679
+ * had not declared it, and the response came back 200, correctly shaped, with
680
+ * the data gone. A typed field that this SDK version has not heard of yet is
681
+ * still in `raw`, so a consumer is never blocked on our release cycle to read
682
+ * something describe.net already publishes.
683
+ */
684
+ /** One chain's row of a wallet's reputation. */
685
+ interface WalletChainRow {
686
+ network: Network;
687
+ agentCount: number;
688
+ agentIds: string[] | null;
689
+ /**
690
+ * 🔴 `null`, NEVER `0`. "No eligible ratings here" and "rated badly" are
691
+ * different facts and the index refuses to collapse them. A `0` asserts the
692
+ * second where the API asserted the first.
693
+ */
694
+ finalScore: number | null;
695
+ totalReviews: number;
696
+ distinctRaters: number;
697
+ }
698
+ /**
699
+ * `GET /wallets/{wallet}/chains` — the free per-wallet answer.
700
+ *
701
+ * Verified live 2026-08-30 against an address with no identity
702
+ * (`0xdEaD…BEEF`): **HTTP 200**, `chains: []`, `global_score: null`,
703
+ * `distinct_raters: null`. That is a RESPONSE, not an error — the A2A gate of
704
+ * the same service says it in its own voice: *"That is an answer, not an
705
+ * error."* This SDK never throws for it (R1, R4).
706
+ */
707
+ interface WalletReputation extends Sealed {
708
+ /** As served. EVM is normalised server-side; Solana base58 is case-SENSITIVE. */
709
+ wallet: string;
710
+ chains: WalletChainRow[];
711
+ /**
712
+ * Mean of the per-chain means — one chain, one vote. `null` when there is no
713
+ * eligible rating anywhere. Full precision: format with `formatScore`.
714
+ */
715
+ globalScore: number | null;
716
+ /**
717
+ * `COUNT(DISTINCT client)` across every chain AND every identity, so a rater
718
+ * who reviewed on two chains counts once.
719
+ *
720
+ * `null` when the index has nothing to count — and the difference from `0`
721
+ * matters: MeshRelay measured that taking the per-chain MAXIMUM instead
722
+ * reports 4 for a wallet with 3 raters on base and 4 different ones on
723
+ * avalanche (7 distinct counterparties), and that SUMMING double-counts
724
+ * whoever rated on more than one chain (karma-hello reads 9 globally while
725
+ * the per-chain figures add to 11). Neither reconstruction is correct; this
726
+ * field is.
727
+ */
728
+ distinctRaters: number | null;
729
+ identityCount: number;
730
+ chainsWithIdentity: number;
731
+ chainsWithReputation: number;
732
+ totalReviews: number;
733
+ }
734
+ /** How lopsided the evidence is. `null` when there is not enough to say. */
735
+ interface Concentration {
736
+ distinctRaters: number;
737
+ /** Share of ratings written by the single loudest client, 0..1. */
738
+ topClientShare: number | null;
739
+ topClient: string | null;
740
+ }
741
+ /** Wilson interval over distinct raters. Read `interval` before acting on `band`. */
742
+ interface Confidence {
743
+ /** `no_ratings` | `low` | `medium` | `high` — the server's own bands. */
744
+ band: string;
745
+ distinctRaters: number;
746
+ interval: {
747
+ lower: number;
748
+ upper: number;
749
+ } | null;
750
+ /** The cut points, published live so nobody re-types them. */
751
+ thresholds: Record<string, number>;
752
+ advice: string;
753
+ confidencePolicy: string;
754
+ }
755
+ interface SelfRated {
756
+ count: number;
757
+ score: number | null;
758
+ /** Distance between the self-rating and everyone else's. */
759
+ gap: number | null;
760
+ }
761
+ interface Activity {
762
+ firstRatingAt: Timestamp;
763
+ lastRatingAt: Timestamp;
764
+ }
765
+ /** One facet (`tag1`), as declared on-chain. */
766
+ interface Facet {
767
+ score: number | null;
768
+ count: number;
769
+ distinctRaters: number;
770
+ revokedCount: number;
771
+ outOfDomainCount: number;
772
+ selfRatedCount: number;
773
+ /**
774
+ * ⚠️ `tag1` is FREE TEXT on-chain. The longest facet in this index is 471
775
+ * characters — a paragraph about gardening used as a label. Escape
776
+ * everything that comes from the chain before it reaches a DOM.
777
+ */
778
+ direction: string | null;
779
+ directionCategory: string | null;
780
+ directionMeaning: string | null;
781
+ }
782
+ /** A citable computation: same `inputsDigest`, same numbers. */
783
+ interface Snapshot {
784
+ id: number;
785
+ /**
786
+ * A bare `sha256` hexdigest — 64 hex, **no `0x`** (`aggregate.py:1920`).
787
+ *
788
+ * `null` when it did not come **or** when what came was not a digest;
789
+ * `malformedHashes` is what tells those apart. It is nullable rather than `''`
790
+ * on purpose: this is the field that makes an answer citable, and an empty
791
+ * string here would be a citation to nothing wearing the clothes of a
792
+ * citation.
793
+ */
794
+ inputsDigest: string | null;
795
+ policyVersion: string;
796
+ computedAt: string;
797
+ /**
798
+ * `['inputs_digest']` when the digest arrived malformed. Empty means "nothing
799
+ * arrived malformed" — it says nothing about what arrived.
800
+ */
801
+ malformedHashes: string[];
802
+ }
803
+ /**
804
+ * `GET /reputation/wallet/{wallet}` — metered ($0.01; $0.05 with a citable
805
+ * snapshot). The decomposition: who rated, how many times, how concentrated.
806
+ */
807
+ interface WalletBreakdown extends Sealed {
808
+ wallet: string;
809
+ finalScore: number | null;
810
+ weightedScore: number | null;
811
+ raterWeightPolicy: string;
812
+ chainCount: number;
813
+ totalReviews: number;
814
+ /** Keyed by network. Values keep the server's shape. */
815
+ perChain: Record<string, unknown>;
816
+ facets: Record<string, Facet>;
817
+ selfRated: SelfRated | null;
818
+ concentration: Concentration | null;
819
+ confidence: Confidence | null;
820
+ activity: Activity | null;
821
+ snapshot: Snapshot | null;
822
+ /** What was actually paid, if anything was. */
823
+ payment: PaymentEvidence | null;
824
+ }
825
+ /**
826
+ * One rating, at the grain. `tag1`/`tag2` are on-chain free text: escape them.
827
+ *
828
+ * 🔴 **Its three hash fields arrive shape-validated** (`txHash`, `feedbackHash`,
829
+ * `revokedTx`) — KarmaKadabra's contribution of 2026-08-30, from *"el 200 sin
830
+ * tx"*. Anything that is not a hash is dropped to `null` and its wire name goes
831
+ * into `malformedHashes`. **Absent and malformed are not the same thing**: read
832
+ * the list, not the `null`. See `hashes.ts`.
833
+ */
834
+ interface Rating {
835
+ client: string;
836
+ feedbackIndex: number;
837
+ value: number;
838
+ valueDecimals: number;
839
+ normalizedValue: number | null;
840
+ tag1: string | null;
841
+ tag2: string | null;
842
+ isRevoked: boolean;
843
+ isSelf: boolean;
844
+ /**
845
+ * The transaction that wrote this rating — `0x` + 64 hex on the EVM chains, a
846
+ * base58 signature on Solana. `null` means it did not come **or** it came
847
+ * malformed; `malformedHashes` separates them. The schema's own note: *"null
848
+ * until the log scan reaches this entry, not null forever"*, so a hole here is
849
+ * normal and is not reported.
850
+ */
851
+ txHash: string | null;
852
+ blockNumber: number | null;
853
+ logIndex: number | null;
854
+ feedbackUri: string | null;
855
+ /** Host of `feedbackURI`. What the ISSUER declared — advisory, never a score. */
856
+ issuerHost: string | null;
857
+ issuer: string | null;
858
+ issuerOrg: string | null;
859
+ /**
860
+ * The content hash the rater committed to. `bytes32`, so `0x` + 64 hex — and
861
+ * **NULL on purpose on Solana** (`solana_indexer.py`), so absence here is
862
+ * correct and is not reported.
863
+ *
864
+ * ⚠️ A well-shaped hash is not a meaningful one: an EVM rater that declared
865
+ * nothing writes 32 zero bytes, which passes the shape check as
866
+ * `0x0000…0000`. This SDK will not decide that for you — a shape check says
867
+ * "this could be a hash", never "this hash means something".
868
+ */
869
+ feedbackHash: string | null;
870
+ /** The transaction that killed this rating, if it was revoked. Same shapes. */
871
+ revokedTx: string | null;
872
+ /**
873
+ * Which of the three hash fields above arrived with something that is not a
874
+ * hash. Empty in the normal case.
875
+ *
876
+ * 🔴 Branch on this, not on `txHash === null`.
877
+ */
878
+ malformedHashes: string[];
879
+ }
880
+ /** Whether reputation was inherited across an identity transfer. */
881
+ interface Ownership {
882
+ ownerUpdatedBlock: number;
883
+ identityTransferred: boolean | null;
884
+ inheritedReviewCount: number;
885
+ inheritedScore: number | null;
886
+ currentEraReviewCount: number;
887
+ currentEraScore: number | null;
888
+ undeterminedReviewCount: number;
889
+ inheritedShare: number | null;
890
+ }
891
+ /** `GET /reputation/agent/{network}/{agent_id}` — metered ($0.02). */
892
+ interface AgentReputation extends Sealed {
893
+ network: Network;
894
+ agentId: string;
895
+ /**
896
+ * The wallet that owns this identity TODAY (`agents.current_owner`), never
897
+ * the minter of the `Registered` event — that is almost always the
898
+ * facilitator, and attributing by it would file the whole index under one
899
+ * address.
900
+ */
901
+ currentOwner: string | null;
902
+ /**
903
+ * ⚠️ NOT a type. 283 770 of 470 064 agents (60,4 %, measured 2026-08-30) are
904
+ * `unknown`, and the second largest "type" is the URL of the EIP schema —
905
+ * with its typo variant. ERC-8004 has no type field. Never treat it as
906
+ * verification. Read it live from `GET /stats/types`.
907
+ */
908
+ declaredType: string | null;
909
+ agentUri: string | null;
910
+ indexedIdentity: boolean;
911
+ score: number | null;
912
+ reviewCount: number;
913
+ revokedCount: number;
914
+ outOfDomainCount: number;
915
+ selfRated: SelfRated | null;
916
+ facets: Record<string, Facet>;
917
+ concentration: Concentration | null;
918
+ ownership: Ownership | null;
919
+ confidence: Confidence | null;
920
+ ratings: Rating[];
921
+ payment: PaymentEvidence | null;
922
+ }
923
+ /**
924
+ * ⚠️ The leaderboard does NOT order by average. It orders by `shrunkScore`
925
+ * (Bayesian shrinkage over distinct raters), which is why row 1 can show a
926
+ * lower `finalScore` than row 2. Ordering by `finalScore` client-side
927
+ * reproduces the bug the shrinkage exists to prevent: a wallet with one
928
+ * 100-point rating outranking one with two hundred.
929
+ */
930
+ interface LeaderboardRow {
931
+ rank: number;
932
+ wallet: string;
933
+ finalScore: number | null;
934
+ shrunkScore: number | null;
935
+ distinctRaters: number;
936
+ chainCount: number;
937
+ totalReviews: number;
938
+ networks: Network[];
939
+ declaredTypes: Array<string | null>;
940
+ /** The row exactly as served. */
941
+ raw: Record<string, unknown>;
942
+ }
943
+ interface HealthChain {
944
+ network: Network;
945
+ lastScannedBlock: number | null;
946
+ updatedAt: Timestamp;
947
+ /** When this chain is next due. The freshness pointer worth polling against. */
948
+ nextSyncAt: Timestamp;
949
+ lastError: string | null;
950
+ raw: Record<string, unknown>;
951
+ }
952
+ /**
953
+ * `GET /health` — free, and the ONLY authority on the index's totals.
954
+ *
955
+ * "Toda cifra o se lee viva o lleva fecha": never type a total of this index
956
+ * into a UI, a README or a doc. Read it here. That is also why
957
+ * `readingPolicy` and `confidenceThresholds` come through as maps rather than
958
+ * as constants of this package — they are the server's calibrable values,
959
+ * published live precisely so no consumer re-types them (invariante 10).
960
+ *
961
+ * Slowest free endpoint (~1,6 s measured, 2,4 s on 2026-08-30) and deliberately
962
+ * uncached at the edge — never probe it with a sub-3 s timeout.
963
+ */
964
+ interface IndexHealth {
965
+ status: string;
966
+ policyVersion: string;
967
+ orderingPolicy: string;
968
+ raterWeightPolicy: string;
969
+ confidencePolicy: string;
970
+ /** e.g. `{no_ratings: 0, low: 1, medium: 3, high: 6}` — live, never re-typed. */
971
+ confidenceThresholds: Record<string, number>;
972
+ /** e.g. `{min_raters: 3, campaign_per_rater: 20, top_share: 0.5, ...}`. */
973
+ readingPolicy: Record<string, unknown>;
974
+ /** Which commit is serving. Useful when a shape changes under you. */
975
+ buildSha: string | null;
976
+ agents: number;
977
+ feedbackEntries: number;
978
+ indexerPeriodSeconds: number | null;
979
+ chains: HealthChain[];
980
+ raw: Record<string, unknown>;
981
+ }
982
+
983
+ /**
984
+ * `DescribeClient` — six methods, four of which touch the network.
985
+ *
986
+ * ## The one thing to read before changing anything here
987
+ *
988
+ * There are THREE different absences in this file and collapsing any two of
989
+ * them is the failure this package exists to prevent:
990
+ *
991
+ * 1. **`globalScore: null` inside a returned object** — "the index looked and
992
+ * there is no eligible rating". Verified live on 2026-08-30 against
993
+ * `0xdEaD…BEEF`: HTTP 200, `chains: []`, `global_score: null`. Data.
994
+ * 2. **The method returning `null`** — "we could not ask" (`failOpen`).
995
+ * describe.net is down, or slow, or answered something unreadable.
996
+ * 3. **A thrown `DescribeError`** — the caller's request was wrong, or a 402
997
+ * arrived with no payer, or a challenge named the wrong treasury.
998
+ *
999
+ * A fail-open that is silent turns (2) into (1) — "describe is down" becomes
1000
+ * "this wallet has no reputation" — which is precisely the confusion R1 exists
1001
+ * to forbid, arriving through the back door. That is why `onFailure` is not
1002
+ * optional decoration: it is the half of `failOpen` that keeps it honest, and
1003
+ * `client.test.ts` asserts a failure is always announced before `null` is
1004
+ * returned.
1005
+ *
1006
+ * ## 🔴 The paid routes never fail open — added 2026-08-30, and it is a money rule
1007
+ *
1008
+ * `wallet()`, `leaderboard()` and `health()` are free, so absence (2) costs
1009
+ * nothing and a `null` is the kindest answer: without it every consumer writes
1010
+ * the same try/catch around a lookup, which is the duplication this package
1011
+ * exists to delete.
1012
+ *
1013
+ * `walletBreakdown()` and `agent()` are NOT free, and there they return no
1014
+ * absence value at all — they throw, always, **including with `failOpen: true`
1015
+ * set explicitly**. The line is not "how many methods", it is *was there money
1016
+ * in flight*.
1017
+ *
1018
+ * ⚠️ **This is a correction of what shipped, left written because it is the
1019
+ * whole reason this rule exists.** Until 2026-08-30 these two returned
1020
+ * `| null` and ran their failures through `failOpenCovers()`, which is `true`
1021
+ * for every `serviceFault`. Measured against a dead port that same day: a
1022
+ * timeout on a metered route returned `null`. The paywall settles **before**
1023
+ * running the query (`describe-net/describenet/paywall.py:1031-1047`), so that
1024
+ * `null` could be handed back with the USDC already moved — and nothing in it
1025
+ * distinguished "I paid and it fell over" from "there was nothing to fetch".
1026
+ * That is not degrading gracefully, it is a spent credential with no receipt.
1027
+ *
1028
+ * A loud failure after paying is recoverable: the caller can retry, log or
1029
+ * claim. A silent `null` is not, and no flag the caller sets can buy the right
1030
+ * to swallow a receipt — availability is a preference, a settled payment is a
1031
+ * fact. What the exception carries instead is `error.payment` (see
1032
+ * `errors.ts::PaymentAttempt`) and `failedAfterPaying()` reads it.
1033
+ *
1034
+ * ## 🔴 The partner rail has a THIRD money rule — added 2026-08-30
1035
+ *
1036
+ * With `partner` configured (see `PartnerSigner` below and
1037
+ * `uvd-describe-sdk/partner`), every request is signed and the metered routes
1038
+ * are supposed to be free. Two failures are therefore CALLER-fault and neither
1039
+ * one degrades:
1040
+ *
1041
+ * 1. the signature could not be produced → `DescribePartnerUnsigned`, thrown
1042
+ * on every route including the free ones, `failOpen` or not;
1043
+ * 2. the signature was produced and the route charged anyway →
1044
+ * `DescribePartnerRejected`, thrown BEFORE the payer is ever called.
1045
+ *
1046
+ * Both are `serviceFault: false`, so `failOpenCovers()` refuses them. The
1047
+ * symmetry with the paid-route rule is exact and deliberate: there, money that
1048
+ * already moved may not be swallowed; here, money that is ABOUT to move may not
1049
+ * be spent by accident. A partner rail that quietly falls back to paying is
1050
+ * indistinguishable from a working one until the invoice arrives.
1051
+ *
1052
+ * ## What this client deliberately does NOT do
1053
+ *
1054
+ * **No cache.** MeshRelay has one (a `Map`, 12-minute TTL) and needs it: it
1055
+ * recomputes channel scores on a route reachable from the internet, so an
1056
+ * uncached lookup would let a stranger burn our share of a rate limit that has
1057
+ * no per-partner bucket (the live figure is 50 rps sustained / burst 40, and
1058
+ * the `RateLimit-Policy` response header is the authority — see the correction
1059
+ * in `config.ts`). EM and KarmaKadabra have none. One of three is not a
1060
+ * mandate, and a cache in a library is a policy
1061
+ * decision about staleness that belongs to the app: MeshRelay's split of
1062
+ * `refreshWallets` (async, network) from `getCached` (sync, NEVER network)
1063
+ * exists because ITS threat model needed it, and baking a TTL in here would
1064
+ * hand every consumer a staleness they did not choose. Documented in the README
1065
+ * with MeshRelay's shape as the recipe.
1066
+ *
1067
+ * ⚠️ **Ratified 2026-08-30 by the only consumer that has a cache.** MeshRelay
1068
+ * reviewed this decision in `#agents` and agreed the cache must not move into
1069
+ * the library: *"una librería que decide cuánto tiempo miente por vos es peor
1070
+ * que una que no cachea"*. The paragraph above now has two signatures, not one —
1071
+ * which is the difference between a preference and a decision.
1072
+ *
1073
+ * **No retry.** Same reason, plus a measured one: MeshRelay retries a transient
1074
+ * failure at most ONCE, "hammering a permanent failure is how EM turned one
1075
+ * error into a four-hour storm" (`describenet.js:150-151`). A retry policy
1076
+ * inside a library multiplies against whatever the caller already has.
1077
+ * `DescribeError.transient` is exported so a caller can build the policy they
1078
+ * want on a fact instead of on a string match.
1079
+ *
1080
+ * ## What it DOES do without being asked, and there is exactly one — added 2026-08-30
1081
+ *
1082
+ * **It sleeps `[0, 400) ms` before the first request of every call.** That is
1083
+ * the one thing in this list that goes the other way, so it carries the burden
1084
+ * of proof: the number and the measurement are KarmaKadabra's (27 agents on one
1085
+ * EventBridge schedule, against a rate limit shared with no per-partner bucket —
1086
+ * *"sin jitter, un enjambre es un DDoS educado"*), and the argument for shipping
1087
+ * it ON is in `config.ts::DEFAULT_JITTER_MS`. `jitterMs: 0` turns it off.
1088
+ *
1089
+ * It is NOT the retry policy above wearing a different hat, and `jitter.ts`
1090
+ * spells out why: jitter disperses a herd that has not asked for anything yet,
1091
+ * backoff yields to a service that has already said no. The first goes before
1092
+ * the first request; the second would go before a retry this package does not
1093
+ * have.
1094
+ *
1095
+ * ## The second thing `onFailure` announces — added 2026-08-30
1096
+ *
1097
+ * A hash field that arrives as something other than a hash is dropped to `null`
1098
+ * and announced as `kind: 'malformed_hash'` (KarmaKadabra's *"el 200 sin tx"*;
1099
+ * see `hashes.ts` and `announceMalformed` below). It does not throw — one bad
1100
+ * accessory field must not destroy a decomposition that was paid for — and it
1101
+ * does not pass through, which is what bit them.
1102
+ */
1103
+
1104
+ /**
1105
+ * How a metered call gets paid.
1106
+ *
1107
+ * 🔴 This SDK NEVER signs, never touches a private key and never builds an
1108
+ * EIP-3009 authorization. That is `uvd-x402-sdk`'s job and reimplementing it
1109
+ * here would be the house's cardinal sin (upstream-first: if the payment SDK
1110
+ * lacks something, it is added THERE and consumed from here). This interface is
1111
+ * the seam, and it is one method wide on purpose — anything wider would start
1112
+ * to encode payment knowledge we have no business having.
1113
+ *
1114
+ * The canonical implementation ships at `uvd-describe-sdk/x402` and wraps the
1115
+ * payment SDK's `X402Client`. It lives behind a subpath so this module never
1116
+ * imports it: a consumer who only reads free routes installs nothing.
1117
+ */
1118
+ interface X402Payer {
1119
+ /**
1120
+ * Given the parsed 402 challenge, return the value for the `X-PAYMENT`
1121
+ * header. Throwing aborts the call — nothing is replayed.
1122
+ */
1123
+ pay(challenge: X402Challenge): Promise<string>;
1124
+ }
1125
+ /**
1126
+ * How a request proves it comes from a partner of the house.
1127
+ *
1128
+ * ## The seam, and why it is exactly one method wide
1129
+ *
1130
+ * Same shape and same reason as {@link X402Payer}: this package holds no key,
1131
+ * builds no signature and knows no cryptography. It hands a request over and
1132
+ * gets headers back. Anything wider would start encoding signing knowledge that
1133
+ * belongs to `uvd-x402-sdk`, and the canonical implementation — which does
1134
+ * nothing but call that SDK's ERC-8128 signer — ships at
1135
+ * `uvd-describe-sdk/partner`, behind a subpath, so the main entry keeps its zero
1136
+ * runtime imports.
1137
+ *
1138
+ * ## What the other side does with it
1139
+ *
1140
+ * describe.net has no accounts and no API keys — *"el pago es la
1141
+ * autenticación"* — so the free rail for our own products could not be a token.
1142
+ * It is an allowlist of PUBLIC ADDRESSES plus a per-request ERC-8128 signature
1143
+ * (`describe-net/describenet/partner.py`, read 2026-08-30). The service
1144
+ * therefore custodies no secret of ours: a breach of describe.net leaks a list
1145
+ * of addresses, which are already public. That property is the reason this is a
1146
+ * signature and not the `X-API-Key` everybody expects, and it is worth
1147
+ * protecting when extending this interface.
1148
+ *
1149
+ * The gate verifies with a policy pinned to `api.describe.net`, chain 8453 and a
1150
+ * 300 s window, and then — the line that makes it a gate — looks the recovered
1151
+ * address up in the allowlist (`partner.py:242`). A valid signature from an
1152
+ * unlisted wallet pays like everybody else.
1153
+ *
1154
+ * ## Throwing is the contract
1155
+ *
1156
+ * `sign()` MUST throw rather than return partial or unsigned headers. The client
1157
+ * turns that throw into `DescribePartnerUnsigned` and raises it — it never
1158
+ * proceeds unsigned, because an unsigned request from a partner client is an
1159
+ * anonymous request, and an anonymous request pays.
1160
+ */
1161
+ interface PartnerSigner {
1162
+ /**
1163
+ * Sign one request; return the headers to add to it.
1164
+ *
1165
+ * For describe.net's GET-only surface that is `Signature` and
1166
+ * `Signature-Input` (RFC 9421). `Content-Digest` appears only for a request
1167
+ * with a body, and this client never sends one.
1168
+ */
1169
+ sign(request: {
1170
+ method: string;
1171
+ url: string;
1172
+ }): Promise<Record<string, string>>;
1173
+ /**
1174
+ * The signing address, if the implementation cares to publish it. Used ONLY
1175
+ * to write a useful error message. It is never sent as a header and never
1176
+ * trusted: the server decides from the address it RECOVERS, not one we claim.
1177
+ */
1178
+ readonly address?: string;
1179
+ }
1180
+ /** What `onFailure` is handed. Enough to log, alert or fall back on. */
1181
+ interface DescribeFailure {
1182
+ /** The route that failed, e.g. `/wallets/0x…/chains`. */
1183
+ path: string;
1184
+ error: DescribeError;
1185
+ /** Shorthand for `error.kind`, so a logger never has to reach in. */
1186
+ kind: DescribeError['kind'];
1187
+ /** Would retrying help? */
1188
+ transient: boolean;
1189
+ }
1190
+ interface DescribeClientConfig {
1191
+ /** Default `https://api.describe.net`. */
1192
+ baseUrl?: string;
1193
+ /** Default 30 000 ms. See `config.ts` for why that number and not another. */
1194
+ timeoutMs?: number;
1195
+ /**
1196
+ * Your product's name, appended to the `User-Agent` as `(+name)`.
1197
+ *
1198
+ * Strongly recommended and free: the rate limit is shared across the
1199
+ * ecosystem with no per-partner bucket, and the UA is the only thing that
1200
+ * makes your share of it attributable when something gets loud. The ceiling
1201
+ * itself is not typed here — the `RateLimit-Policy` response header is the
1202
+ * authority (see the correction in `config.ts`).
1203
+ */
1204
+ product?: string;
1205
+ /**
1206
+ * Default **true**, and it is what Saul asked for in those words: *"pon un
1207
+ * fallback si es que describe está caído"* (2026-08-28).
1208
+ *
1209
+ * `true` — a describe.net-side failure returns `null` and calls `onFailure`.
1210
+ * `false` — the same failure throws a typed `DescribeError`.
1211
+ *
1212
+ * **Scope: the free routes only** — `wallet()`, `leaderboard()`, `health()`.
1213
+ * `walletBreakdown()` and `agent()` ignore this flag in both positions and
1214
+ * always throw; see the header of this file for why money removes the choice.
1215
+ *
1216
+ * Either way a 4xx that is the CALLER's fault still throws: `failOpen`
1217
+ * protects you from their outage, not from your own bug.
1218
+ */
1219
+ failOpen?: boolean;
1220
+ /**
1221
+ * Where a swallowed fact goes. **`onFailure` announces everything this client
1222
+ * swallowed, and nothing it handed you.** Two things qualify:
1223
+ *
1224
+ * 1. a `null` returned instead of an answer (the fail-open, free routes
1225
+ * only) — announced BEFORE the `null`, always;
1226
+ * 2. a hash field dropped because it was not a hash
1227
+ * (`kind: 'malformed_hash'`, metered routes, added 2026-08-30).
1228
+ *
1229
+ * A failure that reaches you as a throw is never announced here: you are
1230
+ * already holding it.
1231
+ *
1232
+ * ⚠️ **This is a restatement, and the old wording is left because someone will
1233
+ * look for it.** It read: *"fires if and only if a method hands back `null`…
1234
+ * the paid routes therefore never call this at all"*. That was a description
1235
+ * of the only case that existed, not of the rule — and the rule it protected
1236
+ * is that nothing disappears quietly. A field that vanished out of a 200 is
1237
+ * exactly as invisible as a silent fail-open, so it belongs on the same
1238
+ * channel. Filter it in one line if you only page on outages:
1239
+ * `if (f.kind === 'malformed_hash') return;` — it is `transient: false` and
1240
+ * `serviceFault: false`, and the paid routes still never fail open.
1241
+ *
1242
+ * Leaving this unset with `failOpen: true` is the one configuration this
1243
+ * package will not defend: it converts "describe is down" into "this wallet
1244
+ * has no reputation" with nothing written down anywhere. It is allowed
1245
+ * because a hard requirement would be a `throw` in the constructor of a
1246
+ * read-only client, but the README says it plainly and so does this comment.
1247
+ */
1248
+ onFailure?: (failure: DescribeFailure) => void;
1249
+ /**
1250
+ * Sleep a random `[0, jitterMs)` before **every** request, so a fleet waking
1251
+ * on one schedule does not arrive as one spike. **Default 400**, and `0` turns
1252
+ * it off.
1253
+ *
1254
+ * ⚠️ *Every* request, the replay of a paid one included: a method that fires
1255
+ * two requests sleeps twice. The intuitive rule — once per public call — was
1256
+ * written here first and is wrong, because it disperses the first request and
1257
+ * lets the rest out in a pack. `jitter()` below carries the correction and the
1258
+ * call site in KarmaKadabra's own code that settles it.
1259
+ *
1260
+ * The number and the reason are KarmaKadabra's, measured on a fleet of 27
1261
+ * (2026-08-30) — see `config.ts::DEFAULT_JITTER_MS` for why it ships ON, and
1262
+ * `jitter.ts` for why this is not backoff and why it is not a CSPRNG.
1263
+ *
1264
+ * Set it to `0` in your own unit tests: a suite that sleeps 200 ms per mocked
1265
+ * call is paying for a behaviour it is not testing. This package's own suite
1266
+ * does exactly that.
1267
+ *
1268
+ * A value that is not a finite number ≥ 0 falls back to the **default**, not
1269
+ * to off: a typo must not silently remove a protection the rest of the
1270
+ * ecosystem is relying on. Only a real `0` disables it.
1271
+ */
1272
+ jitterMs?: number;
1273
+ /** Pay metered routes. Without it, a 402 throws `DescribePaymentRequired`. */
1274
+ payer?: X402Payer;
1275
+ /**
1276
+ * Enter through the partner rail: sign every request as a wallet the house
1277
+ * has allowlisted, and read the metered routes for free.
1278
+ *
1279
+ * Build one with `partnerFromEnv()` or `partnerFromSigner()` from
1280
+ * `uvd-describe-sdk/partner`. Both are the same rail — one reads a key the
1281
+ * environment holds, the other takes a signer you already have.
1282
+ *
1283
+ * 🔴 EVERY request is signed, free routes included, and that is a decision
1284
+ * with a reason: the alternative is a table in this package saying which
1285
+ * routes are metered, which would be a second copy of the service's
1286
+ * `pricing.TIERS` and would silently start paying the day a free route
1287
+ * becomes metered. The server already knows which is which; we do not need
1288
+ * to. What it costs, measured on this machine 2026-08-30 (Node v23.11.0, 200
1289
+ * signatures with an in-process ethers wallet, after 20 warm-up rounds):
1290
+ * **0,67 ms** per signature, against a 30 000 ms request timeout. Four ten-
1291
+ * thousandths of the budget for the request it rides on.
1292
+ */
1293
+ partner?: PartnerSigner;
1294
+ /**
1295
+ * 🔴 Default **false**, and the default is the point.
1296
+ *
1297
+ * With partner mode on, a metered route that answers 402 means the free rail
1298
+ * did not work. By default that throws `DescribePartnerRejected` and NOTHING
1299
+ * IS PAID. Set this to `true` to fall through to the `payer` instead — an
1300
+ * explicit decision to spend USDC when the rail is down, which is a
1301
+ * reasonable thing to want and an unreasonable thing to get by accident.
1302
+ *
1303
+ * With no `partner` configured this flag does nothing at all.
1304
+ */
1305
+ partnerFallsBackToPaying?: boolean;
1306
+ /**
1307
+ * The only address this client will pay. Defaults to the pinned treasury.
1308
+ * Override only if you have verified a rotation out of band — see
1309
+ * `config.ts::TREASURY_EVM` for the failure mode of pinning.
1310
+ */
1311
+ expectedPayTo?: string;
1312
+ /** Injectable for tests. Defaults to the global `fetch`. */
1313
+ fetchImpl?: typeof fetch;
1314
+ }
1315
+ /** Read reputation from describe.net. */
1316
+ declare class DescribeClient {
1317
+ private readonly baseUrl;
1318
+ private readonly timeoutMs;
1319
+ private readonly ua;
1320
+ private readonly failOpen;
1321
+ private readonly onFailure?;
1322
+ private readonly jitterMs;
1323
+ private readonly payer?;
1324
+ private readonly partner?;
1325
+ private readonly partnerFallsBackToPaying;
1326
+ private readonly expectedPayTo;
1327
+ private readonly fetchImpl;
1328
+ constructor(config?: DescribeClientConfig);
1329
+ /**
1330
+ * `GET /wallets/{wallet}/chains` — **free**. The happy path starts here.
1331
+ *
1332
+ * Gratis-primero is not politeness, it is the shape of the product: the 402
1333
+ * challenge of the metered route says it itself — *"si ahí no hay nada, no
1334
+ * hay nada que comprar"*. Ask for free whether there is anything, and only
1335
+ * then buy the decomposition.
1336
+ *
1337
+ * `wallet` goes through VERBATIM. EVM is normalised server-side, but Solana
1338
+ * base58 is case-SENSITIVE and lower-casing it here would silently ask about
1339
+ * a different wallet.
1340
+ *
1341
+ * @returns the reputation (whose `globalScore` may be `null` — that is an
1342
+ * answer), or `null` when describe.net could not be reached and `failOpen`
1343
+ * is on.
1344
+ */
1345
+ wallet(address: string): Promise<WalletReputation | null>;
1346
+ /**
1347
+ * `GET /leaderboard` — **free**, first page.
1348
+ *
1349
+ * Takes NO parameters: `?limit=2` answers 422 `leaderboard_takes_no_params`
1350
+ * (verified live 2026-08-30). Paging is the metered `/leaderboard/page`.
1351
+ *
1352
+ * ⚠️ Ordered by `shrunkScore`, not by `finalScore`. Re-sorting client-side by
1353
+ * `finalScore` undoes the shrinkage and puts a single 100-point rating above
1354
+ * two hundred real ones.
1355
+ */
1356
+ leaderboard(): Promise<LeaderboardRow[] | null>;
1357
+ /**
1358
+ * `GET /health` — **free**, and the authority on this index's totals.
1359
+ *
1360
+ * Also the live source for `readingPolicy` and `confidenceThresholds`: the
1361
+ * server publishes its own calibrable values so that no consumer re-types
1362
+ * them. Read them here rather than hardcoding a threshold that will drift.
1363
+ */
1364
+ health(): Promise<IndexHealth | null>;
1365
+ /**
1366
+ * The badge URL. **Builds a string, opens no socket, cannot fail.**
1367
+ *
1368
+ * `GET /badge/{wallet}.svg` is free and returns `image/svg+xml` (604 bytes,
1369
+ * verified 2026-08-30). Drop it in an `<img>` and a page shows a live score
1370
+ * with its distinct raters and the date of the data, with no JavaScript and
1371
+ * no dependency on this package at all.
1372
+ */
1373
+ badgeUrl(address: string): string;
1374
+ /** Where a human reads the same wallet. On surfaces without hover, THIS is the attribution. */
1375
+ profileUrl(address: string, siteUrl?: string): string;
1376
+ /**
1377
+ * `GET /reputation/wallet/{wallet}` — **metered, $0.01** ($0.05 with a
1378
+ * citable snapshot). Who rated, how many times, how concentrated.
1379
+ *
1380
+ * The price above is documentation with a date on it, not a value this SDK
1381
+ * uses: what gets paid is what the live challenge says. We never type a
1382
+ * price into a code path.
1383
+ *
1384
+ * 🔴 **Not nullable, and never fail-open** — not even with `failOpen: true`.
1385
+ * There is money in flight here, and a swallowed failure is a spent
1386
+ * credential with no receipt. Every failure arrives as a typed throw, and one
1387
+ * that happened after the envelope left carries `error.payment`
1388
+ * (`failedAfterPaying()`). Note this includes a 404: it is still absence and
1389
+ * still costs nothing (it is checked before the challenge is read), but with
1390
+ * no `| null` left there is nowhere to degrade it to.
1391
+ *
1392
+ * Without a `payer`, throws `DescribePaymentRequired` with the challenge
1393
+ * attached — asking is free and is the intended first move, so you can read
1394
+ * the price without paying.
1395
+ */
1396
+ walletBreakdown(address: string): Promise<WalletBreakdown>;
1397
+ /**
1398
+ * `GET /reputation/agent/{network}/{agentId}` — **metered, $0.02**. One
1399
+ * ERC-8004 identity, down to the individual ratings.
1400
+ *
1401
+ * 🔴 Same money rule as `walletBreakdown()`: not nullable, never fail-open,
1402
+ * throws on everything including a 404 for an agent id that does not exist.
1403
+ */
1404
+ agent(network: string, agentId: string | number): Promise<AgentReputation>;
1405
+ /**
1406
+ * The fail-open gate — **for the free routes, and only for them**.
1407
+ *
1408
+ * ⚠️ Corrected 2026-08-30. The old comment here read *"every network method
1409
+ * goes through exactly one of these so the rule cannot drift between
1410
+ * methods"*, and the intent was right while the scope was wrong: routing the
1411
+ * paid methods through it is what let a post-settlement timeout come back as
1412
+ * `null`. The rule that must not drift is R5, and R5 has a term this function
1413
+ * cannot see. So the paid methods do not call it — deliberately, and a test
1414
+ * named `MOUNTS THE BAD STATE` goes red if anyone puts them back.
1415
+ *
1416
+ * Whoever adds the sixth method: free ⇒ wrap it here; metered ⇒ do not.
1417
+ */
1418
+ private guard;
1419
+ /**
1420
+ * The pause that disperses a fleet. **Before EVERY request** — called from the
1421
+ * top of `request()` and from nowhere else, so a method that makes two
1422
+ * requests sleeps twice.
1423
+ *
1424
+ * ⚠️ **Corrected 2026-08-30, and the wrong version is left written because it
1425
+ * is the intuitive one and someone will want it back.** This first sat in
1426
+ * `getJson()` / `getPaidJson()`, i.e. *once per public call, before the FIRST
1427
+ * request*, on the theory that the metered flow should not sleep twice. That
1428
+ * is a hole: a call that fires N requests would disperse one of them and let
1429
+ * the other N−1 out in a pack, which is the exact problem this contribution
1430
+ * came to fix. KarmaKadabra's own call site settles it — their sleep lives
1431
+ * inside the function that performs the GET (`reputation_scan.py:123`), and
1432
+ * that function runs twice on their real path (`:242` for the EVM address,
1433
+ * `:245` for the Solana one). Their jitter is per REQUEST, and the reason they
1434
+ * wrote beside it (`:121-122`) is per-PROCESS: agents that wake together
1435
+ * against a shared ceiling.
1436
+ *
1437
+ * The paid replay sleeps too, and that was the hardest half of the correction
1438
+ * to accept. The argument for exempting it was that delaying a signed envelope
1439
+ * widens the window in which a crash loses a receipt — but the challenge this
1440
+ * client answers carries `maxTimeoutSeconds: 120`, so 400 ms is a third of a
1441
+ * percent of the envelope's own validity, while the herd argument applies to
1442
+ * the replay in full: 27 agents that get their 402 in the same second replay
1443
+ * in the same second.
1444
+ *
1445
+ * **Before the signature, and before the clock.** `request()` calls this
1446
+ * first, so an ERC-8128 signature is never left ageing against its 300 s
1447
+ * window while we sleep, and the sleep is not charged to `timeoutMs`.
1448
+ */
1449
+ private jitter;
1450
+ /**
1451
+ * Announce a malformed hash field, if there is one — KarmaKadabra's *"el 200
1452
+ * sin tx"*, reaching the caller.
1453
+ *
1454
+ * ⚠️ **This is the second thing `onFailure` announces, and invariant 4 is
1455
+ * restated rather than broken.** It used to read *"`onFailure` fires if and
1456
+ * only if a method hands back `null`"*, and that wording was a description of
1457
+ * the only case that existed on 2026-08-30 at noon. The rule it was protecting
1458
+ * is bigger and now reads: **`onFailure` announces everything that was
1459
+ * silently swallowed — a `null` handed back instead of an answer, and a field
1460
+ * dropped because it was not what it claimed to be — and nothing that reaches
1461
+ * you as a throw.** A failure you are holding does not need announcing; a
1462
+ * field that vanished out of a 200 does, and it is exactly as invisible as a
1463
+ * silent fail-open.
1464
+ *
1465
+ * That is why it is not a second callback: the channel a consumer is already
1466
+ * watching is where KarmaKadabra asked for this to land, and a new one would
1467
+ * be a channel nobody wired. The notice is filterable in one line
1468
+ * (`f.kind === 'malformed_hash'`), carries `transient: false` and
1469
+ * `serviceFault: false`, and the error it carries is never thrown.
1470
+ *
1471
+ * 🔴 The callback is wrapped, and this call site is the reason: it fires after
1472
+ * a metered read that already SETTLED. An observer that throws would destroy a
1473
+ * response the caller paid for, which is the same class of bug as swallowing a
1474
+ * receipt — with the sign flipped. (The `guard()` call site is deliberately
1475
+ * left unwrapped: there the answer is already `null`, so a throwing observer
1476
+ * costs nothing that was bought.)
1477
+ */
1478
+ private announceMalformed;
1479
+ /**
1480
+ * The partner headers for one request, or `{}` when there is no partner.
1481
+ *
1482
+ * 🔴 THIS RUNS OUTSIDE `request()`'s try/catch AND THAT IS THE WHOLE POINT.
1483
+ * Inside it, a signer that threw would be caught by the transport handler and
1484
+ * re-thrown as `DescribeUnreachable` — which is `serviceFault: true`, which
1485
+ * `failOpen` swallows, which turns "my partner key is missing" into a `null`
1486
+ * that reads as "this wallet has no reputation". The most expensive bug in
1487
+ * this file, one indentation level away.
1488
+ */
1489
+ private partnerHeaders;
1490
+ private request;
1491
+ private readJson;
1492
+ /** A free route: any non-2xx is a typed HTTP error. */
1493
+ private getJson;
1494
+ /**
1495
+ * A metered route: ask free, read the challenge, verify WHO we are about to
1496
+ * pay, pay through the injected payer, replay the identical request.
1497
+ *
1498
+ * The order matters and the third step is the one people skip. The published
1499
+ * guide says it in the imperative — *"verify who you are about to pay — do
1500
+ * this every time"* — because the challenge arrives over the same network
1501
+ * that could be lying to you, and it names its own recipient.
1502
+ *
1503
+ * There is one line in this function that changes what a failure MEANS, and
1504
+ * it is marked: everything above `payer.pay()` returning is a failure that
1505
+ * cost nothing, everything below it may have cost real USDC. Failures below
1506
+ * it are stamped with a `PaymentAttempt` so the caller does not have to infer
1507
+ * which side of that line they landed on. Nothing above it is stamped, and
1508
+ * that asymmetry IS the signal — see `errors.ts::PaymentAttempt`.
1509
+ */
1510
+ private getPaidJson;
1511
+ /**
1512
+ * Read the 402 challenge from wherever it is.
1513
+ *
1514
+ * The header FIRST, then the body — and that order is measured, not
1515
+ * defensive: of 40 live x402 resources probed on 2026-08-20, 36 of 36 that
1516
+ * answered 402 carried the challenge in the header and none in the body
1517
+ * (`uvd-x402-sdk-typescript/src/utils/x402.ts`). describe.net serves BOTH
1518
+ * (verified 2026-08-30: `Payment-Required` base64 header AND a JSON body), so
1519
+ * either path works here — the order is for the ecosystem, not for us.
1520
+ */
1521
+ private readChallenge;
1522
+ /**
1523
+ * `DO_NOT_PAY` unless every recipient in the challenge is the pinned
1524
+ * treasury.
1525
+ *
1526
+ * Checks the top-level `recipient` AND every `accepts[].payTo`, because a
1527
+ * challenge that names the right treasury up top and a stranger in one of six
1528
+ * `accepts` entries is exactly the shape an attack would take: the caller's
1529
+ * chain selection decides which one gets paid. Case-insensitive, since EVM
1530
+ * addresses travel in mixed checksum case (the live challenge serves
1531
+ * `0xe4dc963c56979E0260fc146b87eE24F18220e545` while the path parameter is
1532
+ * lowercase).
1533
+ */
1534
+ private assertPayableTo;
1535
+ }
1536
+
1537
+ export { type AgentReputation as A, type WalletChainRow as B, CAVEAT_CODES as C, type DescribeErrorKind as D, type X402Payer as E, type Facet as F, failOpenCovers as G, type HealthChain as H, type IndexHealth as I, failedAfterPaying as J, type KnownCaveatCode as K, type LeaderboardRow as L, hasCaveat as M, type Network as N, type Ownership as O, type PaymentEvidence as P, isKnownCaveatCode as Q, type Rating as R, type Sealed as S, type Timestamp as T, type WalletBreakdown as W, type X402Challenge as X, type WalletReputation as a, type Activity as b, CAVEAT_SCOPE_FREE as c, CAVEAT_SCOPE_METERED as d, type Caveat as e, type CaveatCode as f, type Concentration as g, type Confidence as h, DescribeClient as i, type DescribeClientConfig as j, DescribeError as k, type DescribeFailure as l, DescribeHTTPError as m, DescribeMalformedHash as n, DescribeNotFound as o, DescribePartnerRejected as p, DescribePartnerUnsigned as q, DescribePaymentRefused as r, DescribePaymentRequired as s, DescribeTimeout as t, DescribeUnparseable as u, DescribeUnreachable as v, type PartnerSigner as w, type PaymentAttempt as x, type SelfRated as y, type Snapshot as z };