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.
package/src/raters.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * How many distinct counterparties are behind a wallet's reputation — and the
3
+ * two ways of reconstructing that number that are both WRONG.
4
+ *
5
+ * Contributed by **MeshRelay**, `#agents` on MeshRelay, **2026-08-30**. The
6
+ * seven lines of the helper are not the contribution; the two measurements are,
7
+ * and they are the reason this file has a docstring longer than its code.
8
+ */
9
+
10
+ /**
11
+ * The distinct-rater count of a wallet, or `null` when there is none to give.
12
+ *
13
+ * ## 🔴 Read this before you use the number
14
+ *
15
+ * `distinct_raters` at the top level of `GET /wallets/{wallet}/chains` is
16
+ * `COUNT(DISTINCT client)` across every chain AND every identity: one rater who
17
+ * reviewed on two chains counts **once**. There is no way to rebuild that from
18
+ * the per-chain rows, and MeshRelay measured both attempts on 2026-08-30:
19
+ *
20
+ * * **Summing the chains DOUBLE-COUNTS** whoever rated on more than one of
21
+ * them. Measured case: the karma-hello wallet reads **9** distinct raters
22
+ * globally while its per-chain figures add up to **11**.
23
+ * * **Taking the maximum UNDERESTIMATES.** Measured case: 3 raters on base and
24
+ * 4 *different* ones on avalanche is **7** real counterparties, and the
25
+ * maximum answers **4**.
26
+ *
27
+ * So the per-chain maximum is a **LOWER BOUND — never the answer**, and summing
28
+ * is not a second-best either: it is wrong in the opposite direction. That pair
29
+ * of sentences is the contribution; without them this helper reads like a
30
+ * one-liner and gets used as the truth.
31
+ *
32
+ * **One live vector proves all three branches at once.** Verified against
33
+ * `api.describe.net` on 2026-08-30 (free route), wallet
34
+ * `0xcc28…4821`: global `distinct_raters` **129**, per chain base **113** and
35
+ * ethereum **21**. The maximum answers 113 (**16 short**), the sum answers 134
36
+ * (**5 over**), and only the global figure is right. It is the fixture this
37
+ * file's test pins, because a vector where two wrong answers land on opposite
38
+ * sides of the true one cannot be passed by accident.
39
+ *
40
+ * ## 🔴 The fallback is a COMPATIBILITY path, not a normal one
41
+ *
42
+ * ⚠️ Corrected while writing this, and the correction matters more than the
43
+ * line it replaces: an earlier draft called the per-chain maximum a "fallback
44
+ * for when the global figure is not there", which invites a reader to treat the
45
+ * global field as optional. It is not. describe.net has served wallet-level
46
+ * `distinct_raters` since `b753c9c` — *"el dato ya estaba y no lo leíamos"*,
47
+ * committed **2026-08-28**, which MeshRelay's own note dates 08-29 (the day they
48
+ * read it; both are written here because a reader will find the other one and
49
+ * think one of us is wrong) — and their comment says the maximum is kept *"only
50
+ * as a fallback for a cached response predating that deploy"*
51
+ * (`meshrelay/meshrelayserv/describenet.js:228-230`,
52
+ * read 2026-08-30). Confirmed live the same day: the free route serves
53
+ * `distinct_raters` at the top level on every wallet.
54
+ *
55
+ * So in a client written after that date the fallback branch is unreachable
56
+ * unless you cache responses and outlive one of their deploys — which MeshRelay
57
+ * does, and is why the branch exists at all. It is kept for them and for anyone
58
+ * replaying a stored payload, not because the field might be missing today.
59
+ *
60
+ * ## What this function therefore does
61
+ *
62
+ * Prefers the global count whenever the object carries one; falls back to the
63
+ * per-chain maximum only when it does not. What comes back is exact in the first
64
+ * case and a lower bound in the second, and there is no third answer it could
65
+ * give. **It never sums, and neither should you.**
66
+ *
67
+ * ## 🔴 Why this is not called `maxDistinctRaters`
68
+ *
69
+ * Because MeshRelay, who wrote it under that name, asked for the rename when
70
+ * they handed it over (2026-08-30): *"ese nombre invita a creer que el máximo es
71
+ * la respuesta correcta, cuando es el último recurso. El mío está mal nombrado y
72
+ * lo arrastro de cuando el nivel wallet no existía."*
73
+ *
74
+ * That is worth keeping written down, because the old name is what a reader will
75
+ * search for and because it is the failure this whole file guards against
76
+ * arriving through the API surface: a function named after its fallback
77
+ * advertises the fallback, and the fallback is the wrong answer. Their name
78
+ * survives here, in the provenance, which is where it belongs.
79
+ *
80
+ * ## Two `null`s that are not zero
81
+ *
82
+ * * A wallet with no eligible rating anywhere serves `distinct_raters: null`
83
+ * with `chains: []` — verified live 2026-08-30 against `0xdEaD…BEEF`. The
84
+ * answer is `null`, **never `0`**: "nobody has rated this" and "zero people
85
+ * rated this after we counted" are the same sentence, but `0` is a number a
86
+ * caller will divide by, average, or render as a bar of length zero next to
87
+ * wallets whose bar means something. `Math.max(...[])` is `-Infinity`, which
88
+ * is the concrete bug this branch exists to not have.
89
+ * * A `null` INPUT (the fail-open value of `wallet()`, i.e. "we could not ask
90
+ * describe.net") also gives `null`. Accepting it is deliberate: it lets a
91
+ * caller write `resolveDistinctRaters(await describe.wallet(w))` without a
92
+ * null-check that would only exist to satisfy the compiler, and it keeps the
93
+ * three absences of this package from collapsing — an unreachable index and
94
+ * an unrated wallet both mean "no number", and neither means zero.
95
+ *
96
+ * Structurally typed rather than tied to `WalletReputation` so it also works on
97
+ * a payload you parsed yourself or pulled out of your own cache.
98
+ */
99
+ export function resolveDistinctRaters(
100
+ wallet:
101
+ | {
102
+ distinctRaters: number | null;
103
+ chains: readonly { distinctRaters: number }[];
104
+ }
105
+ | null
106
+ | undefined,
107
+ ): number | null {
108
+ if (!wallet) return null;
109
+ if (wallet.distinctRaters !== null && wallet.distinctRaters !== undefined) {
110
+ return wallet.distinctRaters;
111
+ }
112
+ let best: number | null = null;
113
+ for (const chain of wallet.chains ?? []) {
114
+ const n = chain?.distinctRaters;
115
+ if (typeof n === 'number' && Number.isFinite(n) && (best === null || n > best)) best = n;
116
+ }
117
+ return best;
118
+ }
@@ -0,0 +1,254 @@
1
+ /**
2
+ * What to do INSTEAD — the sentence `transient` cannot say.
3
+ *
4
+ * ## Where this came from, and it is not ours
5
+ *
6
+ * Contributed by **Execution Market** in `#agents` on **2026-08-30**, out of
7
+ * their own 502 body gaining `detail.code`, `detail.retryable` and
8
+ * `detail.recovery` with ten typed codes — *"para que lo codifiquen de su
9
+ * lado"*. Their argument is the measurement that justifies this whole file:
10
+ *
11
+ * > *"SIETE de los diez son TERMINALES (`retryable: false`). Eso es lo que más
12
+ * > les sirve: hoy su flota no puede distinguir 'reintenta' de 'no insistas', y
13
+ * > contra `AUTHORIZATION_EXPIRED` reintentar es quemar llamadas contra una
14
+ * > ventana cerrada hace **317 HORAS**."*
15
+ *
16
+ * 317 hours of retries against a door that closed is the cost of having only
17
+ * the boolean. Measured on our side the same day, before this file existed:
18
+ * `grep -rc recovery src/` was **0** in both SDKs, while `transient` and
19
+ * `serviceFault` were already on every error. So we had exactly half of it — we
20
+ * could say whether retrying helps, and had no way at all to say what to do
21
+ * when it does not. A boolean that says "no" leaves the caller stuck; a
22
+ * sentence that names another door lets them keep going.
23
+ *
24
+ * 🔴 **What was deliberately NOT absorbed: their ten codes.**
25
+ * `AUTHORIZATION_EXPIRED`, escrow, release-to-worker, payout wallets — that is
26
+ * Execution Market's API, and this SDK does not wrap it. It wraps describe.net,
27
+ * which holds no escrow and expires no authorization of its own. A consumer
28
+ * branching on `AUTHORIZATION_EXPIRED` against this index would be writing dead
29
+ * code against a domain we do not touch. The **pattern** is the contribution;
30
+ * the table below is ours and had to be re-derived failure by failure.
31
+ *
32
+ * ## Why a sentence, and not a second enum
33
+ *
34
+ * The machine-readable axis already exists and is `kind` — plus `transient`
35
+ * ("would retrying help?") and `serviceFault` ("is this describe.net's
36
+ * fault?"). A `recoveryCode` enum would be a SECOND taxonomy over the same
37
+ * failures, kept in sync by hand, and consumers would start branching on it
38
+ * instead of on `kind`; the day the two disagree, the branch that fires is the
39
+ * wrong one. What was missing is not another thing to switch on, it is the
40
+ * paragraph a human (or an agent reading its own exception) needs in order to
41
+ * do something else.
42
+ *
43
+ * 🔴 So: **branch on `kind`, read `recovery`.** Never parse it, never match on
44
+ * it — same contract the caveats carry, where `code` is frozen and the text is
45
+ * free to be re-written (`caveats.ts`, and describe.net's own rule: *"EL TEXTO
46
+ * puede cambiar sin aviso; EL CODE jamás"*). The stability a test needs comes
47
+ * from the strings living HERE, once, exported: pin `RECOVERY.payment_required`
48
+ * and the assertion cannot rot into a prose match.
49
+ *
50
+ * ## 🔴 The rule that keeps an empty one honest
51
+ *
52
+ * **A recovery that does not work is worse than no recovery**, because it sends
53
+ * the caller to do something useless with confidence — which is the same shape
54
+ * as the 317 hours, one level up. So a `null` here is a decision that was made,
55
+ * not a field somebody forgot: `timeout` has one and its reasoning is written
56
+ * at the entry.
57
+ *
58
+ * And a recovery is never "retry" in other words — `transient` already says
59
+ * that, and repeating it would be the second copy of a fact this package keeps
60
+ * in one place. Every entry names something ELSE: another route, another field,
61
+ * another mode, or the condition on the caller's side that has to be fixed.
62
+ *
63
+ * ## 🔴 Every string in this file is a literal, and that IS the redaction guard
64
+ *
65
+ * Execution Market's other warning of the same day: an unclassified error *"can
66
+ * carry an RPC URL with its API key inside"*, and they added a test with a fake
67
+ * secret that fails if it leaks. The service side of the house has had that
68
+ * guard for a while — `describe-net/describenet/chain/rpc.py::_redact` replaces
69
+ * the endpoint with `<rpc-url>` in anything about to be logged or raised,
70
+ * because the key lives in the URL path.
71
+ *
72
+ * The SDK equivalent is structural rather than a filter: **this module holds
73
+ * nothing but frozen literals and interpolates nothing.** `recoveryFor()` picks
74
+ * one by key; no call site builds a recovery out of a message, a URL, a cause,
75
+ * or any other string that came from outside this file. A filter can be
76
+ * forgotten at one call site; a table has no call site to forget.
77
+ *
78
+ * That boundary is drawn where it is on purpose, and the neighbouring field is
79
+ * the contrast: `DescribeUnreachable`'s `message` DOES quote `String(error)`,
80
+ * because a transport failure with the cause stripped out is undebuggable. The
81
+ * message is forensic and belongs to whoever is reading the exception; the
82
+ * recovery is advice this package WROTE and is the string most likely to be
83
+ * copied into a log line, a ticket or a Slack message. `recovery.test.ts`
84
+ * mounts a fetch that throws a URL carrying a fake key and asserts the recovery
85
+ * comes back byte-identical to the table.
86
+ *
87
+ * ## 🔴 Parity: what a recovery text is allowed to name
88
+ *
89
+ * The Python SDK ships the same field with the same name and the SAME text, so
90
+ * a consumer who moves stacks does not read two different pieces of advice for
91
+ * one failure. That is only possible if a text names things BOTH SDKs share:
92
+ * HTTP routes, headers, wire fields, env vars, chain ids, and the numbers the
93
+ * service publishes. It may NOT name a language-specific spelling — this
94
+ * package's `jitterMs` is the Python package's `jitter` and it is in SECONDS
95
+ * (see the README's parity note), so a text naming it would have to be either
96
+ * different or wrong. Options are therefore described by what they do, and the
97
+ * caller finds the spelling in their own SDK, one line away.
98
+ */
99
+
100
+ import type { DescribeErrorKind } from './errors';
101
+
102
+ /**
103
+ * The keys of the table.
104
+ *
105
+ * Every `kind`, plus `rate_limited` — the one place where a kind is not fine
106
+ * enough. A 429 and a 422 are both `http_4xx`, and their recoveries are
107
+ * opposites: one says *this is your input, fix it*, the other says *this is not
108
+ * your request at all, spread your fleet*. Merging them would produce a
109
+ * paragraph that is wrong for both, which is exactly the mush this file exists
110
+ * to avoid. The split lives in `recoveryFor()`, on the same `status === 429`
111
+ * condition that already decides `transient` in `DescribeHTTPError`.
112
+ */
113
+ export type RecoveryKey = DescribeErrorKind | 'rate_limited';
114
+
115
+ /**
116
+ * The frozen table. One entry per {@link RecoveryKey}, `null` where there is
117
+ * honestly no other door.
118
+ *
119
+ * The `Record` annotation is half the guard: a `kind` added to the union
120
+ * without an entry here does not compile. The other half is
121
+ * `recovery.test.ts`, which walks every kind at runtime.
122
+ */
123
+ export const RECOVERY: Readonly<Record<RecoveryKey, string | null>> = Object.freeze({
124
+ /**
125
+ * 🔴 **The honest empty, and it is a measured decision — do not fill it in.**
126
+ *
127
+ * A timeout has exactly two levers. The first is retrying, which `transient:
128
+ * true` already announces and which a recovery may not repeat. The second is
129
+ * the client timeout, and the numbers in `config.ts::DEFAULT_TIMEOUT_MS` say
130
+ * raising it past the default buys nothing that can ever arrive: the
131
+ * provider's API Gateway integration ceiling is **29 s** and the default here
132
+ * is 30 000 ms. Telling a caller to raise it would be advice that provably
133
+ * does not work — the exact failure this file's own rule forbids.
134
+ *
135
+ * (The opposite mistake — a timeout set BELOW the 15,2 s cold start, which
136
+ * turned a cold index into a fake outage for Execution Market once — is a
137
+ * configuration fact and already lives, once, in `config.ts`. It is not
138
+ * re-typed here.)
139
+ *
140
+ * What separates this from its neighbour `http_5xx`, which DOES have a
141
+ * recovery: a 5xx is evidence that the service is alive and one query is not,
142
+ * so another route is worth trying. A timeout is no evidence at all.
143
+ */
144
+ timeout: null,
145
+
146
+ http_5xx:
147
+ 'They answered, so the process is alive and one query is not — which makes a different door ' +
148
+ 'worth more than the same one again. `GET /wallets/{wallet}/chains` is free and serves the ' +
149
+ 'coarse version of the same question (which ERC-8004 identities the wallet has, and the score, ' +
150
+ 'review count and distinct raters of each) through another query path. It costs nothing to ' +
151
+ 'find out; if the whole index is down it fails too, and on the free routes that arrives as a ' +
152
+ 'null rather than as this.',
153
+
154
+ http_4xx:
155
+ 'Fix the request before repeating it: a 4xx is your input, not their outage. A 422 is never ' +
156
+ 'absence — an unregistered wallet answers 200 with nulls, so `not_an_address` means the string ' +
157
+ 'is not an address at all (a Solana base58 wallet is case-sensitive and this client sends it ' +
158
+ 'verbatim), and `GET /leaderboard` answers 422 to ANY query parameter because paging moved to ' +
159
+ 'the metered `/leaderboard/page`. To turn a loose id into a question that exists, ask the free ' +
160
+ '`GET /search/{query}` first.',
161
+
162
+ rate_limited:
163
+ 'Not your request: describe.net rate-limits the whole ecosystem out of one bucket with no ' +
164
+ 'per-partner share, so a 429 is usually somebody else spiking. Retrying tighter makes it ' +
165
+ 'worse — spread the fleet instead (this client already sleeps a random jitter before every ' +
166
+ 'request; widening it is the lever) and read the `RateLimit-Policy` response header for the ' +
167
+ 'live budget rather than any number written in a document. The cached free routes ' +
168
+ '(`GET /health`, `/pricing`, `/leaderboard`, `/stats/*`) are served from CloudFront and a hit ' +
169
+ 'does not spend the budget at all.',
170
+
171
+ not_found:
172
+ 'Nothing failed and nothing was charged: the index is saying there is nothing there. The one ' +
173
+ 'case worth acting on is an agent id, because an id alone does not name a row — resolve the ' +
174
+ 'pair for free with `GET /search/{query}` (measured by the service on 2026-08-23: 26.736 of ' +
175
+ '62.814 ids live on two or more chains, and in 100 % of those the owning wallet is a different ' +
176
+ 'one on each). If EVERY route 404s, the base URL is pointing somewhere else.',
177
+
178
+ unreachable:
179
+ 'The request never reached describe.net: nothing was asked, nothing was signed, nothing was ' +
180
+ 'charged. This one is on your side of the socket — DNS, egress or proxy, TLS interception, a ' +
181
+ 'browser CORS block, or a base URL whose host does not exist — and it is the thing to check ' +
182
+ 'before blaming the index, which never saw the request.',
183
+
184
+ unparseable:
185
+ 'Ask WHAT answered rather than asking again: an HTML error page from a proxy, a captive portal ' +
186
+ 'or a gateway arrives exactly like this and is not the index talking. Retrying is measured to ' +
187
+ 'buy nothing (MeshRelay excludes this from its retry set on purpose). If the body really did ' +
188
+ 'come from describe.net, the door that changes the answer is another one: ' +
189
+ '`GET /wallets/{wallet}/chains` is free and serves the coarse version of the same question.',
190
+
191
+ partial_index:
192
+ 'Read the coverage before reading the absence as a verdict: a chain the index does not scan ' +
193
+ 'produces no rows, and that looks identical to an agent nobody rated. `GET /chains` (free) ' +
194
+ 'lists what is indexed and `GET /health` (free) carries the per-chain totals and how current ' +
195
+ 'each one is. If the chain you write to is missing there, no re-reading of this answer will ' +
196
+ 'fix it — that is a question for whoever runs the index.',
197
+
198
+ payment_required:
199
+ 'Nothing was charged: asking the price is free, and asking first is the intended move. Three ' +
200
+ 'doors out. (1) Wire a payer — this SDK ships the x402 adapter behind its own subpath, so a ' +
201
+ 'free-only consumer installs nothing. (2) Enter the partner rail with a wallet on ' +
202
+ 'describe.net\'s allowlist and the metered routes stop charging. (3) Answer the cheaper ' +
203
+ 'question for free — the challenge names it itself: `free_preview.endpoint` is the free route ' +
204
+ 'about THIS subject (a wallet lands on `GET /wallets/{wallet}/chains`) and `see_also` lists ' +
205
+ 'every other free door. If there is nothing there, there is nothing to buy.',
206
+
207
+ payment_refused:
208
+ 'Do NOT retry, and do NOT widen the expected payee to make this pass: the challenge that named ' +
209
+ 'a stranger arrived over the same network that could be lying to you, so it cannot be the ' +
210
+ 'evidence that clears itself. Verify out of band — describe.net publishes the treasury in its ' +
211
+ 'OpenAPI (`GET /openapi.json`, free, where `payTo` must equal that address) and on its own ' +
212
+ 'site. If a rotation is real, upgrade this SDK or set the expected payee yourself once you ' +
213
+ 'have confirmed the new address through a channel that is not this response.',
214
+
215
+ malformed_hash:
216
+ 'Nothing to retry: the same request serves the same bad field, and nothing else in the answer ' +
217
+ 'was touched. Read the mark rather than the `null` — the object that lost the field carries a ' +
218
+ 'malformed-hash list naming it, the notice carries the field\'s wire path, and the value as ' +
219
+ 'served is still in `raw`, which is what belongs in the ticket to whoever runs the index. A ' +
220
+ '`null` with an EMPTY list is the other thing entirely: the field has not been written yet, ' +
221
+ 'which is documented and normal.',
222
+
223
+ partner_unsigned:
224
+ 'Fix the signer, not the request — and do not "fix" it by dropping partner mode, because an ' +
225
+ 'anonymous client is a client that PAYS. The measured common cause is a trailing newline: ' +
226
+ '`KEY=$(cat file)` keeps it, which is why the key is shape-checked before it can reach the ' +
227
+ 'signer. The environment variable is `DESCRIBE_PARTNER_PRIVATE_KEY`. The signer\'s own error ' +
228
+ 'travels as this exception\'s cause and is never copied into any message here — read it there.',
229
+
230
+ partner_rejected:
231
+ 'Fix the rail; do not reach for the payer by reflex. In the order these actually happen: the ' +
232
+ 'wallet is not on describe.net\'s allowlist yet (send them the signing address this error ' +
233
+ 'carries — it is public, which is the point of an allowlist of addresses instead of a token); ' +
234
+ 'the base URL is not `https://api.describe.net`, so the signed authority cannot match (a raw ' +
235
+ 'execute-api host does this); the keyid chain is not 8453; or the clock drifted (more than ' +
236
+ '30 s ahead, or a signature older than 300 s). The attached challenge says what it would have ' +
237
+ 'cost, and paying anyway is an explicit opt-in, never a fallback.',
238
+ });
239
+
240
+ /**
241
+ * The recovery for one failure, or `null` when there honestly is none.
242
+ *
243
+ * Called from exactly one place — the `DescribeError` constructor — so every
244
+ * error in this package gets its recovery from the same table by construction,
245
+ * and a subclass cannot forget to pass one or invent one of its own.
246
+ *
247
+ * `status` is read for one case only: 429 is the single 4xx that is not the
248
+ * caller's bug, and it takes the `rate_limited` entry. Same condition that
249
+ * already decides `transient` one file over.
250
+ */
251
+ export function recoveryFor(kind: DescribeErrorKind, status?: number): string | null {
252
+ if (kind === 'http_4xx' && status === 429) return RECOVERY.rate_limited;
253
+ return RECOVERY[kind];
254
+ }