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/LICENSE +21 -0
- package/README.md +612 -0
- package/dist/client-s3KrgrCt.d.mts +1537 -0
- package/dist/client-s3KrgrCt.d.ts +1537 -0
- package/dist/config-Y2VK_neB.d.mts +169 -0
- package/dist/config-Y2VK_neB.d.ts +169 -0
- package/dist/index.d.mts +488 -0
- package/dist/index.d.ts +488 -0
- package/dist/index.js +1082 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1038 -0
- package/dist/index.mjs.map +1 -0
- package/dist/partner/index.d.mts +194 -0
- package/dist/partner/index.d.ts +194 -0
- package/dist/partner/index.js +77 -0
- package/dist/partner/index.js.map +1 -0
- package/dist/partner/index.mjs +71 -0
- package/dist/partner/index.mjs.map +1 -0
- package/dist/x402/index.d.mts +91 -0
- package/dist/x402/index.d.ts +91 -0
- package/dist/x402/index.js +29 -0
- package/dist/x402/index.js.map +1 -0
- package/dist/x402/index.mjs +26 -0
- package/dist/x402/index.mjs.map +1 -0
- package/package.json +97 -0
- package/src/caveats.ts +124 -0
- package/src/client.ts +953 -0
- package/src/config.ts +181 -0
- package/src/errors.ts +596 -0
- package/src/format.ts +67 -0
- package/src/hashes.ts +229 -0
- package/src/index.ts +192 -0
- package/src/jitter.ts +112 -0
- package/src/parse.ts +388 -0
- package/src/partner/index.ts +295 -0
- package/src/raters.ts +118 -0
- package/src/recovery.ts +254 -0
- package/src/types.ts +457 -0
- package/src/x402/index.ts +123 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/recovery.ts","../src/errors.ts","../src/hashes.ts","../src/jitter.ts","../src/caveats.ts","../src/parse.ts","../src/client.ts","../src/format.ts","../src/raters.ts"],"names":[],"mappings":";AAeO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,gBAAA,GAAmB;AAkBzB,IAAM,kBAAA,GAAqB;AA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CAAC,CAAC,CAAA;AAC5C;AAYO,SAAS,WAAW,KAAA,EAAiD;AAC1E,EAAA,IAAI,OAAO,UAAU,QAAA,IAAY,CAAC,OAAO,QAAA,CAAS,KAAK,GAAG,OAAO,IAAA;AACjE,EAAA,OAAO,UAAA,CAAW,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAC,CAAA;AACpC;;;ACgCO,SAAS,sBACd,MAAA,EAOe;AACf,EAAA,IAAI,CAAC,QAAQ,OAAO,IAAA;AACpB,EAAA,IAAI,MAAA,CAAO,cAAA,KAAmB,IAAA,IAAQ,MAAA,CAAO,mBAAmB,MAAA,EAAW;AACzE,IAAA,OAAO,MAAA,CAAO,cAAA;AAAA,EAChB;AACA,EAAA,IAAI,IAAA,GAAsB,IAAA;AAC1B,EAAA,KAAA,MAAW,KAAA,IAAS,MAAA,CAAO,MAAA,IAAU,EAAC,EAAG;AACvC,IAAA,MAAM,IAAI,KAAA,EAAO,cAAA;AACjB,IAAA,IAAI,OAAO,CAAA,KAAM,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,KAAM,IAAA,KAAS,IAAA,IAAQ,CAAA,GAAI,IAAA,CAAA,EAAO,IAAA,GAAO,CAAA;AAAA,EACzF;AACA,EAAA,OAAO,IAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * The only place this package defines a calibrable value.\n *\n * House rule (decisión de Saul, 2026-08-26, born from a measured case in\n * describe.net: one threshold written with TWO DIFFERENT VALUES across four\n * surfaces, and the one charged was not the one the site promised). Nothing\n * else in this package re-types these numbers — modules import them.\n *\n * What does NOT live here, by the same rule: anything that moves a score or a\n * price. This SDK computes neither, so the list is short: `POLICY_VERSION` and\n * the prices are the server's and travel in its responses. We never type a\n * price. See `errors.ts` for what we do with a 402 challenge instead.\n */\n\n/** Where the index answers. Overridable per client for a staging deploy. */\nexport const DEFAULT_BASE_URL = 'https://api.describe.net';\n\n/** Where a human reads the same wallet. Never fetched — only linked. */\nexport const DEFAULT_SITE_URL = 'https://describe.net';\n\n/**\n * 30 s, and the number is not taste — it is the one number of the three live\n * consumers that came with its measurement written down (EM `client.py:19-23`,\n * INC-2026-08-19):\n *\n * * the provider's Lambda cold start was measured at **15,2 s**, so anything\n * under it turns a cold index into a fake outage. An 8 s timeout already\n * broke a real integration once.\n * * its API Gateway integration ceiling is **29 s**, so waiting past 30 buys\n * nothing the gateway will ever deliver.\n * * it is deliberately DISTINCT from the Facilitator's 45 s so two clocks can\n * never expire in the same second and produce an error nobody can attribute.\n *\n * Measured across the ecosystem on 2026-08-30: EM 30 s, MeshRelay 30 000 ms,\n * KarmaKadabra 25 s. Two of three already sit here.\n */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * 400 ms, **on by default**, and the default is the decision — so here is the\n * argument, because it is the one thing about this package that spends the\n * caller's latency without being asked.\n *\n * The number is not ours: it is what **KarmaKadabra** sleeps before every read\n * (`random.uniform(0, 0.4)`), contributed on 2026-08-30 with the measurement\n * that produced it — *\"27 agentes despiertan al MISMO tiempo por EventBridge y\n * pegan simultáneo contra su límite de rps COMPARTIDO con los otros\n * consumidores. Sin jitter, un enjambre es un DDoS educado.\"* They run the\n * largest fleet against this index, so their calibration beats our taste.\n *\n * ## Why ON, when a library that sleeps unasked is a surprise\n *\n * The surprise is real and it is the honest objection. Three things outweigh it:\n *\n * 1. **The cost of the mistake does not land on whoever makes it.** The rate\n * limit is shared with no per-partner bucket (see `userAgent` below), so an\n * unjittered swarm is paid for by the OTHER consumer, who gets the 429 and\n * has no lever to fix it. When the cost of a default falls on someone who\n * cannot change it, the default has to be the safe one.\n * 2. **Opt-out is discoverable; opt-in is not.** `jitterMs: 0` is one field\n * away and typed. The other direction cannot be found by reading your own\n * code: you learn you needed jitter from someone else's incident, and by\n * then you have already spent their budget. KarmaKadabra's own framing —\n * whoever writes a single script never finds out the problem exists until\n * they have a fleet.\n * 3. **It is bounded and small against this package's own numbers.** At most\n * 400 ms, 200 ms on average, against a 30 000 ms timeout and a provider\n * cold start measured at 15,2 s. And it is the same shape of default this\n * client already ships: `failOpen: true` also changes behaviour without\n * being asked, for the same reason — the safe thing, loudly documented,\n * with one field to turn it off.\n *\n * ## What is NOT written here, on purpose\n *\n * The rate limit itself. KarmaKadabra's own note cited 20 rps, which was the\n * documentation's figure and is now stale (it is 50 sustained / burst 40 since\n * 2026-08-28). A number that has already gone stale once in one hop between two\n * teams does not belong in a constant: **the `RateLimit-Policy` response header\n * is the authority**, and this value is calibrated against a fleet size, not\n * against a ceiling. See the correction in `userAgent`.\n */\nexport const DEFAULT_JITTER_MS = 400;\n\n/**\n * The treasury this SDK will pay, and NOTHING else.\n *\n * Read live from the 402 challenge of `GET /reputation/wallet/{w}` on\n * 2026-08-30 (`recipient`, and `payTo` on all six `accepts[]` entries — base,\n * avalanche, arbitrum, optimism, polygon, celo — identical on every one).\n *\n * Pinning it is the point: an x402 challenge is fetched over the network and\n * names its own recipient, so a client that pays whatever `payTo` arrives will\n * happily pay an attacker who can answer as the API. A challenge whose `payTo`\n * is not this address is `DO_NOT_PAY` — never a retry, never a warning that a\n * caller can ignore.\n *\n * 🔴 THE FAILURE MODE OF PINNING, written down because it will happen: if\n * describe.net rotates its treasury, every published version of this SDK stops\n * paying until it is republished. That is the SAFE direction of the failure\n * (refusing to pay a stranger beats paying one), and the escape hatch is\n * `expectedPayTo` in the client config — a caller who has verified the new\n * address out of band can move without waiting for us.\n */\nexport const TREASURY_EVM = '0xe4dc963c56979E0260fc146b87eE24F18220e545';\n\n/**\n * The chain id that goes in the ERC-8128 keyid of a partner signature.\n *\n * 8453 (Base). Not a preference — it is what the gate accepts:\n * `describe-net/describenet/partner.py:90` sets `CHAIN_ID = 8453` and passes it\n * as the ONLY member of `allowed_chain_ids`, with its own comment explaining\n * that `None` (accept any chain) would be \"innecesariamente laxo para una\n * allowlist de tres servicios propios\". Read 2026-08-30.\n *\n * The payment SDK's own default happens to be 8453 too, and this constant\n * deliberately does not lean on that: this value belongs to describe.net's\n * policy, not to the signer's convenience, and the day one moves the other must\n * not follow by accident. Measured failure mode of getting it wrong: the gate\n * answers `chain_not_allowed` and the route charges — loud, since partner mode\n * throws `DescribePartnerRejected` instead of paying.\n */\nexport const PARTNER_CHAIN_ID = 8453;\n\n/**\n * The environment variable `partnerFromEnv()` reads the signing key from.\n *\n * A variable name is not a secret; the value it holds is. Naming it here means\n * a consumer can grep for it, a deploy manifest can set it, and nobody has to\n * guess — while `partnerFromEnv()` staying the ONLY reader means the key has\n * exactly one path into this package.\n */\nexport const PARTNER_KEY_ENV = 'DESCRIBE_PARTNER_PRIVATE_KEY';\n\n/**\n * The package version, for the `User-Agent`.\n *\n * MeshRelay reads its version from `package.json` at runtime because \"a\n * User-Agent that lies about the version is worse than none\"\n * (`describenet.js:39`). It can afford the `readFileSync`: it is a server, not\n * a bundled library. We cannot — a library that reads its own manifest at\n * runtime either bundles `package.json` into the artifact or breaks in a\n * browser, and this package has to run in a browser.\n *\n * So the constant is typed here and `config.test.ts` asserts it equals\n * `package.json`'s `version`. Same guarantee (the UA cannot lie), paid at test\n * time instead of at runtime. Bumping the version without the constant is a\n * red test, not a silent lie in someone's access log.\n */\nexport const SDK_VERSION = '0.1.0';\n\n/** `uvd-describe-sdk-ts/0.1.0`, plus `(+<product>)` when the caller names itself. */\nexport const SDK_NAME = 'uvd-describe-sdk-ts';\n\n/**\n * Build the `User-Agent`.\n *\n * The provider's rate limit is **shared by every consumer with no per-partner\n * bucket**, so identifying ourselves is the only thing that makes our share of\n * it attributable at all. That is why the UA is on by default and `product` is\n * the one field a caller should bother to fill.\n *\n * ⚠️ CORRECTION 2026-08-30, left written rather than swapped: this comment\n * first said \"20 rps\", copied from `meshrelay/describenet.js:19-20`. The live\n * OpenAPI says **50 requests/second sustained, bursts up to 40**, at the API\n * Gateway edge, and it also says where the truth lives: *\"Every response\n * carries the policy as a header, `RateLimit-Policy: 50;w=1;burst=40` … and\n * **that header is the authority**\"*. So neither number belongs in this file —\n * read the header. Cached free routes (`/health`, `/pricing`, `/leaderboard`,\n * `/stats/*`) are served by CloudFront and do not consume the budget on a hit.\n * The 20 was probably right when MeshRelay wrote it; a dated figure does not\n * stop being stale, it only stops being a lie.\n *\n * ⚠️ It is attribution, not authentication. describe.net has no accounts and\n * no API keys — \"el pago es la autenticación\" — so anyone can send any UA.\n * Never treat this string as identity, on either side.\n */\nexport function userAgent(product?: string): string {\n const base = `${SDK_NAME}/${SDK_VERSION}`;\n const trimmed = (product ?? '').trim();\n return trimmed ? `${base} (+${trimmed})` : base;\n}\n","/**\n * What to do INSTEAD — the sentence `transient` cannot say.\n *\n * ## Where this came from, and it is not ours\n *\n * Contributed by **Execution Market** in `#agents` on **2026-08-30**, out of\n * their own 502 body gaining `detail.code`, `detail.retryable` and\n * `detail.recovery` with ten typed codes — *\"para que lo codifiquen de su\n * lado\"*. Their argument is the measurement that justifies this whole file:\n *\n * > *\"SIETE de los diez son TERMINALES (`retryable: false`). Eso es lo que más\n * > les sirve: hoy su flota no puede distinguir 'reintenta' de 'no insistas', y\n * > contra `AUTHORIZATION_EXPIRED` reintentar es quemar llamadas contra una\n * > ventana cerrada hace **317 HORAS**.\"*\n *\n * 317 hours of retries against a door that closed is the cost of having only\n * the boolean. Measured on our side the same day, before this file existed:\n * `grep -rc recovery src/` was **0** in both SDKs, while `transient` and\n * `serviceFault` were already on every error. So we had exactly half of it — we\n * could say whether retrying helps, and had no way at all to say what to do\n * when it does not. A boolean that says \"no\" leaves the caller stuck; a\n * sentence that names another door lets them keep going.\n *\n * 🔴 **What was deliberately NOT absorbed: their ten codes.**\n * `AUTHORIZATION_EXPIRED`, escrow, release-to-worker, payout wallets — that is\n * Execution Market's API, and this SDK does not wrap it. It wraps describe.net,\n * which holds no escrow and expires no authorization of its own. A consumer\n * branching on `AUTHORIZATION_EXPIRED` against this index would be writing dead\n * code against a domain we do not touch. The **pattern** is the contribution;\n * the table below is ours and had to be re-derived failure by failure.\n *\n * ## Why a sentence, and not a second enum\n *\n * The machine-readable axis already exists and is `kind` — plus `transient`\n * (\"would retrying help?\") and `serviceFault` (\"is this describe.net's\n * fault?\"). A `recoveryCode` enum would be a SECOND taxonomy over the same\n * failures, kept in sync by hand, and consumers would start branching on it\n * instead of on `kind`; the day the two disagree, the branch that fires is the\n * wrong one. What was missing is not another thing to switch on, it is the\n * paragraph a human (or an agent reading its own exception) needs in order to\n * do something else.\n *\n * 🔴 So: **branch on `kind`, read `recovery`.** Never parse it, never match on\n * it — same contract the caveats carry, where `code` is frozen and the text is\n * free to be re-written (`caveats.ts`, and describe.net's own rule: *\"EL TEXTO\n * puede cambiar sin aviso; EL CODE jamás\"*). The stability a test needs comes\n * from the strings living HERE, once, exported: pin `RECOVERY.payment_required`\n * and the assertion cannot rot into a prose match.\n *\n * ## 🔴 The rule that keeps an empty one honest\n *\n * **A recovery that does not work is worse than no recovery**, because it sends\n * the caller to do something useless with confidence — which is the same shape\n * as the 317 hours, one level up. So a `null` here is a decision that was made,\n * not a field somebody forgot: `timeout` has one and its reasoning is written\n * at the entry.\n *\n * And a recovery is never \"retry\" in other words — `transient` already says\n * that, and repeating it would be the second copy of a fact this package keeps\n * in one place. Every entry names something ELSE: another route, another field,\n * another mode, or the condition on the caller's side that has to be fixed.\n *\n * ## 🔴 Every string in this file is a literal, and that IS the redaction guard\n *\n * Execution Market's other warning of the same day: an unclassified error *\"can\n * carry an RPC URL with its API key inside\"*, and they added a test with a fake\n * secret that fails if it leaks. The service side of the house has had that\n * guard for a while — `describe-net/describenet/chain/rpc.py::_redact` replaces\n * the endpoint with `<rpc-url>` in anything about to be logged or raised,\n * because the key lives in the URL path.\n *\n * The SDK equivalent is structural rather than a filter: **this module holds\n * nothing but frozen literals and interpolates nothing.** `recoveryFor()` picks\n * one by key; no call site builds a recovery out of a message, a URL, a cause,\n * or any other string that came from outside this file. A filter can be\n * forgotten at one call site; a table has no call site to forget.\n *\n * That boundary is drawn where it is on purpose, and the neighbouring field is\n * the contrast: `DescribeUnreachable`'s `message` DOES quote `String(error)`,\n * because a transport failure with the cause stripped out is undebuggable. The\n * message is forensic and belongs to whoever is reading the exception; the\n * recovery is advice this package WROTE and is the string most likely to be\n * copied into a log line, a ticket or a Slack message. `recovery.test.ts`\n * mounts a fetch that throws a URL carrying a fake key and asserts the recovery\n * comes back byte-identical to the table.\n *\n * ## 🔴 Parity: what a recovery text is allowed to name\n *\n * The Python SDK ships the same field with the same name and the SAME text, so\n * a consumer who moves stacks does not read two different pieces of advice for\n * one failure. That is only possible if a text names things BOTH SDKs share:\n * HTTP routes, headers, wire fields, env vars, chain ids, and the numbers the\n * service publishes. It may NOT name a language-specific spelling — this\n * package's `jitterMs` is the Python package's `jitter` and it is in SECONDS\n * (see the README's parity note), so a text naming it would have to be either\n * different or wrong. Options are therefore described by what they do, and the\n * caller finds the spelling in their own SDK, one line away.\n */\n\nimport type { DescribeErrorKind } from './errors';\n\n/**\n * The keys of the table.\n *\n * Every `kind`, plus `rate_limited` — the one place where a kind is not fine\n * enough. A 429 and a 422 are both `http_4xx`, and their recoveries are\n * opposites: one says *this is your input, fix it*, the other says *this is not\n * your request at all, spread your fleet*. Merging them would produce a\n * paragraph that is wrong for both, which is exactly the mush this file exists\n * to avoid. The split lives in `recoveryFor()`, on the same `status === 429`\n * condition that already decides `transient` in `DescribeHTTPError`.\n */\nexport type RecoveryKey = DescribeErrorKind | 'rate_limited';\n\n/**\n * The frozen table. One entry per {@link RecoveryKey}, `null` where there is\n * honestly no other door.\n *\n * The `Record` annotation is half the guard: a `kind` added to the union\n * without an entry here does not compile. The other half is\n * `recovery.test.ts`, which walks every kind at runtime.\n */\nexport const RECOVERY: Readonly<Record<RecoveryKey, string | null>> = Object.freeze({\n /**\n * 🔴 **The honest empty, and it is a measured decision — do not fill it in.**\n *\n * A timeout has exactly two levers. The first is retrying, which `transient:\n * true` already announces and which a recovery may not repeat. The second is\n * the client timeout, and the numbers in `config.ts::DEFAULT_TIMEOUT_MS` say\n * raising it past the default buys nothing that can ever arrive: the\n * provider's API Gateway integration ceiling is **29 s** and the default here\n * is 30 000 ms. Telling a caller to raise it would be advice that provably\n * does not work — the exact failure this file's own rule forbids.\n *\n * (The opposite mistake — a timeout set BELOW the 15,2 s cold start, which\n * turned a cold index into a fake outage for Execution Market once — is a\n * configuration fact and already lives, once, in `config.ts`. It is not\n * re-typed here.)\n *\n * What separates this from its neighbour `http_5xx`, which DOES have a\n * recovery: a 5xx is evidence that the service is alive and one query is not,\n * so another route is worth trying. A timeout is no evidence at all.\n */\n timeout: null,\n\n http_5xx:\n 'They answered, so the process is alive and one query is not — which makes a different door ' +\n 'worth more than the same one again. `GET /wallets/{wallet}/chains` is free and serves the ' +\n 'coarse version of the same question (which ERC-8004 identities the wallet has, and the score, ' +\n 'review count and distinct raters of each) through another query path. It costs nothing to ' +\n 'find out; if the whole index is down it fails too, and on the free routes that arrives as a ' +\n 'null rather than as this.',\n\n http_4xx:\n 'Fix the request before repeating it: a 4xx is your input, not their outage. A 422 is never ' +\n 'absence — an unregistered wallet answers 200 with nulls, so `not_an_address` means the string ' +\n 'is not an address at all (a Solana base58 wallet is case-sensitive and this client sends it ' +\n 'verbatim), and `GET /leaderboard` answers 422 to ANY query parameter because paging moved to ' +\n 'the metered `/leaderboard/page`. To turn a loose id into a question that exists, ask the free ' +\n '`GET /search/{query}` first.',\n\n rate_limited:\n 'Not your request: describe.net rate-limits the whole ecosystem out of one bucket with no ' +\n 'per-partner share, so a 429 is usually somebody else spiking. Retrying tighter makes it ' +\n 'worse — spread the fleet instead (this client already sleeps a random jitter before every ' +\n 'request; widening it is the lever) and read the `RateLimit-Policy` response header for the ' +\n 'live budget rather than any number written in a document. The cached free routes ' +\n '(`GET /health`, `/pricing`, `/leaderboard`, `/stats/*`) are served from CloudFront and a hit ' +\n 'does not spend the budget at all.',\n\n not_found:\n 'Nothing failed and nothing was charged: the index is saying there is nothing there. The one ' +\n 'case worth acting on is an agent id, because an id alone does not name a row — resolve the ' +\n 'pair for free with `GET /search/{query}` (measured by the service on 2026-08-23: 26.736 of ' +\n '62.814 ids live on two or more chains, and in 100 % of those the owning wallet is a different ' +\n 'one on each). If EVERY route 404s, the base URL is pointing somewhere else.',\n\n unreachable:\n 'The request never reached describe.net: nothing was asked, nothing was signed, nothing was ' +\n 'charged. This one is on your side of the socket — DNS, egress or proxy, TLS interception, a ' +\n 'browser CORS block, or a base URL whose host does not exist — and it is the thing to check ' +\n 'before blaming the index, which never saw the request.',\n\n unparseable:\n 'Ask WHAT answered rather than asking again: an HTML error page from a proxy, a captive portal ' +\n 'or a gateway arrives exactly like this and is not the index talking. Retrying is measured to ' +\n 'buy nothing (MeshRelay excludes this from its retry set on purpose). If the body really did ' +\n 'come from describe.net, the door that changes the answer is another one: ' +\n '`GET /wallets/{wallet}/chains` is free and serves the coarse version of the same question.',\n\n partial_index:\n 'Read the coverage before reading the absence as a verdict: a chain the index does not scan ' +\n 'produces no rows, and that looks identical to an agent nobody rated. `GET /chains` (free) ' +\n 'lists what is indexed and `GET /health` (free) carries the per-chain totals and how current ' +\n 'each one is. If the chain you write to is missing there, no re-reading of this answer will ' +\n 'fix it — that is a question for whoever runs the index.',\n\n payment_required:\n 'Nothing was charged: asking the price is free, and asking first is the intended move. Three ' +\n 'doors out. (1) Wire a payer — this SDK ships the x402 adapter behind its own subpath, so a ' +\n 'free-only consumer installs nothing. (2) Enter the partner rail with a wallet on ' +\n 'describe.net\\'s allowlist and the metered routes stop charging. (3) Answer the cheaper ' +\n 'question for free — the challenge names it itself: `free_preview.endpoint` is the free route ' +\n 'about THIS subject (a wallet lands on `GET /wallets/{wallet}/chains`) and `see_also` lists ' +\n 'every other free door. If there is nothing there, there is nothing to buy.',\n\n payment_refused:\n 'Do NOT retry, and do NOT widen the expected payee to make this pass: the challenge that named ' +\n 'a stranger arrived over the same network that could be lying to you, so it cannot be the ' +\n 'evidence that clears itself. Verify out of band — describe.net publishes the treasury in its ' +\n 'OpenAPI (`GET /openapi.json`, free, where `payTo` must equal that address) and on its own ' +\n 'site. If a rotation is real, upgrade this SDK or set the expected payee yourself once you ' +\n 'have confirmed the new address through a channel that is not this response.',\n\n malformed_hash:\n 'Nothing to retry: the same request serves the same bad field, and nothing else in the answer ' +\n 'was touched. Read the mark rather than the `null` — the object that lost the field carries a ' +\n 'malformed-hash list naming it, the notice carries the field\\'s wire path, and the value as ' +\n 'served is still in `raw`, which is what belongs in the ticket to whoever runs the index. A ' +\n '`null` with an EMPTY list is the other thing entirely: the field has not been written yet, ' +\n 'which is documented and normal.',\n\n partner_unsigned:\n 'Fix the signer, not the request — and do not \"fix\" it by dropping partner mode, because an ' +\n 'anonymous client is a client that PAYS. The measured common cause is a trailing newline: ' +\n '`KEY=$(cat file)` keeps it, which is why the key is shape-checked before it can reach the ' +\n 'signer. The environment variable is `DESCRIBE_PARTNER_PRIVATE_KEY`. The signer\\'s own error ' +\n 'travels as this exception\\'s cause and is never copied into any message here — read it there.',\n\n partner_rejected:\n 'Fix the rail; do not reach for the payer by reflex. In the order these actually happen: the ' +\n 'wallet is not on describe.net\\'s allowlist yet (send them the signing address this error ' +\n 'carries — it is public, which is the point of an allowlist of addresses instead of a token); ' +\n 'the base URL is not `https://api.describe.net`, so the signed authority cannot match (a raw ' +\n 'execute-api host does this); the keyid chain is not 8453; or the clock drifted (more than ' +\n '30 s ahead, or a signature older than 300 s). The attached challenge says what it would have ' +\n 'cost, and paying anyway is an explicit opt-in, never a fallback.',\n});\n\n/**\n * The recovery for one failure, or `null` when there honestly is none.\n *\n * Called from exactly one place — the `DescribeError` constructor — so every\n * error in this package gets its recovery from the same table by construction,\n * and a subclass cannot forget to pass one or invent one of its own.\n *\n * `status` is read for one case only: 429 is the single 4xx that is not the\n * caller's bug, and it takes the `rate_limited` entry. Same condition that\n * already decides `transient` one file over.\n */\nexport function recoveryFor(kind: DescribeErrorKind, status?: number): string | null {\n if (kind === 'http_4xx' && status === 429) return RECOVERY.rate_limited;\n return RECOVERY[kind];\n}\n","/**\n * The failure taxonomy — and, more importantly, WHICH failures are allowed to\n * disappear.\n *\n * ## Why the names are not new\n *\n * The three live consumers of describe.net each invented their own. Measured\n * on 2026-08-30, they agree on the POLICY (absence is not zero; degrade\n * without taking the caller down) and share not one MECHANISM:\n *\n * * Execution Market raises typed exceptions\n * (`timeout | http_5xx | unreachable | unparseable | partial_index`).\n * * MeshRelay returns null and CACHES the failure, splitting `http_4xx` out\n * of EM's catch-all bucket (`describenet.js:52-58`).\n * * KarmaKadabra falls through to a second source (the facilitator).\n *\n * So there was no de-facto contract to copy — there were three answers to one\n * question, and this SDK had to pick one and defend it. It keeps EM's five\n * `kind` strings verbatim (they are the reference implementation, and the\n * Python SDK mirrors them) and adopts MeshRelay's `http_4xx` split, because an\n * SDK — unlike a reconciler job — has to tell its caller apart from the\n * network. Then it adds the two neither of them has, because neither pays.\n *\n * ## The two axes, and why one boolean was not enough\n *\n * `transient` answers \"would retrying help?\".\n * `serviceFault` answers \"is this describe.net's fault?\" — i.e. is this the\n * \"describe está caído\" that `failOpen` exists for (Saul, 2026-08-28).\n *\n * They are not the same question and collapsing them breaks in both\n * directions. A 422 `not_an_address` is neither: swallowing it under\n * `failOpen` would hide a caller's bug forever behind \"this wallet has no\n * reputation\" — the exact confusion `null`-never-`0` exists to prevent. A\n * garbled body from a 502-ing proxy IS describe's fault (so `failOpen` covers\n * it) but retrying it immediately is pointless, and MeshRelay measured that:\n * its retry set is `TIMEOUT | HTTP_5XX | UNREACHABLE` and deliberately excludes\n * `UNPARSEABLE` (`describenet.js:161-164`).\n *\n * ## The third axis, added 2026-08-30: was there money in flight?\n *\n * `serviceFault` decides what `failOpen` may swallow — but only on the FREE\n * routes. On a metered route the question never gets asked, because the answer\n * would be irrelevant: a swallowed failure after settlement is a spent\n * credential with no receipt (see `client.ts`, \"the paid routes never fail\n * open\"). So `DescribeError` gained an optional `payment`, and its mere\n * presence is the statement *\"a signed envelope had already left this process\n * when this failed\"*. Read it with `failedAfterPaying()`.\n *\n * ## The half the booleans never had, added 2026-08-30: what to do INSTEAD\n *\n * `transient` answers *would retrying help?* and stops there. A `false` leaves\n * the caller holding a failure and no next move, which is how a fleet ends up\n * hammering a door that closed — **Execution Market**, `#agents`, 2026-08-30,\n * measuring their own: *\"contra `AUTHORIZATION_EXPIRED` reintentar es quemar\n * llamadas contra una ventana cerrada hace 317 HORAS\"*. They typed a `recovery`\n * into their 502 and asked the ecosystem to do the same.\n *\n * So every error carries `recovery`: one sentence naming ANOTHER thing to do —\n * another route (usually a free one), another field, or the condition on the\n * caller's side that has to be fixed. It is `null` when there honestly is none,\n * which is a decision and not an omission. The texts live in `recovery.ts`,\n * frozen, one per kind, and this constructor is the only thing that reads them.\n *\n * 🔴 What was NOT copied is their ten codes — escrow, payout wallets,\n * `AUTHORIZATION_EXPIRED` — because that is their API's vocabulary and this SDK\n * wraps describe.net. The pattern crossed over; the table was re-derived here.\n */\n\nimport { recoveryFor } from './recovery';\n\n/** The closed set. Consumers switch on `kind`, never on `message`. */\nexport type DescribeErrorKind =\n /** The request outlived the client timeout — includes provider cold starts. */\n | 'timeout'\n /** describe.net answered 5xx. Its fault, and retryable. */\n | 'http_5xx'\n /**\n * describe.net answered 4xx. Ours, not theirs: 422 `not_an_address` is the\n * common member. 429 (the shared 20 rps) also lands here and is the one 4xx\n * that IS transient — see `transient` on the instance, not on the kind.\n */\n | 'http_4xx'\n /**\n * The route answered 404. **This is data, not a failure** — and it is the\n * one entry of this union that never reaches a caller as a thrown error.\n *\n * R4 is absolute: no exception for \"there is no data\". A 404 says exactly\n * that, so the method returns its absence value (`null`) whether `failOpen`\n * is on or off — `failOpen` is about outages and this is about absence, two\n * different axes.\n *\n * It is still reported through `onFailure`, and that is deliberate: a\n * mistyped `baseUrl` makes every route 404, and a silent `null` forever\n * would be indistinguishable from \"nobody in this index has any reputation\".\n * `transient` is false and the kind names itself, so a caller who expects\n * misses can filter it in one line.\n *\n * As of 2026-08-30 no route this SDK wraps returns 404 for a valid input:\n * an unregistered wallet is a **200** with nulls, and a malformed one is a\n * **422**. It is here for the agent route and for whatever the API adds.\n */\n | 'not_found'\n /** Transport died before any status: DNS, connect, reset, CORS, offline. */\n | 'unreachable'\n /** A body arrived and could not be read into the typed shape. */\n | 'unparseable'\n /**\n * The index answered, but its coverage is partial for what was asked.\n *\n * This SDK never raises it — a partial index is served as a 200 whose\n * `chains[]` simply lacks rows, which is data. It exists so a caller that\n * DETECTS partial coverage (a chain it writes to that the index does not\n * scan) can classify it inside the same taxonomy instead of inventing a\n * sixth one. Kept for parity with EM's reference (`types.py:82-92`).\n */\n | 'partial_index'\n /**\n * A metered route answered 402 and this client has no `payer` configured.\n *\n * Protocol, not absence: the index is up and told us its price. Never\n * swallowed by `failOpen` — a caller who forgot to wire a payer must find\n * out, and the challenge is attached so they can read the price without\n * paying (asking is free, and is the intended first move).\n */\n | 'payment_required'\n /**\n * A 402 challenge named a `payTo` that is not the pinned treasury.\n *\n * `DO_NOT_PAY`. Never a retry, never `failOpen`-able: the one failure where\n * continuing quietly costs real USDC to a stranger.\n */\n | 'payment_refused'\n /**\n * A hash field arrived carrying something that is not a hash.\n *\n * 🔴 **Never thrown.** It travels only through `onFailure`, and the class that\n * carries it says so in its own first line — see {@link DescribeMalformedHash}.\n * Branch on this `kind`, never on a `catch` that will not fire.\n */\n | 'malformed_hash'\n /**\n * Partner mode is configured and the signature could not be produced AT ALL.\n *\n * The CALLER's configuration, not describe.net's: an unset env var, a signer\n * that refuses, a wallet that is locked. `serviceFault: false`, so `failOpen`\n * never swallows it — on a free route either. A partner client that silently\n * loses its signature is a partner client that silently starts paying, and\n * that is the whole failure this rail exists to make impossible.\n */\n | 'partner_unsigned'\n /**\n * We signed, and describe.net charged anyway.\n *\n * The signature was produced and sent, and the metered route still answered\n * 402 — so the gate did not exempt us. Measured causes, in the order they\n * happen in real life (`describe-net/describenet/partner.py`):\n *\n * * the wallet is not in the allowlist (`partner.py:242`), i.e. nobody has\n * added this partner yet — Execution Market is registered, KarmaKadabra\n * and MeshRelay are NOT, as of 2026-08-30;\n * * the signed `@authority` is not `api.describe.net` (`partner.py:84`) —\n * which is what a custom `baseUrl` produces, including the raw\n * execute-api host behind CloudFront, deliberately;\n * * the keyid's chain is not 8453 (`partner.py:90`);\n * * the clock is off by more than 30 s ahead or the signature is older than\n * 300 s (`partner.py:95-96`).\n *\n * `payment` is ABSENT and that is load-bearing: nothing was signed, nothing\n * was sent, nothing was spent. This error is the moment BEFORE the money.\n */\n | 'partner_rejected';\n\n/**\n * What this SDK can honestly say about the USDC when a metered call fails.\n *\n * ## Why an object and not a boolean\n *\n * A bare `DescribeTimeout` cannot tell \"it died before we paid\" (you spent\n * nothing) from \"it died after\" (you may have spent and got nothing back).\n * Those are different conversations — the first is a retry, the second is a\n * reconciliation — and the exception has to carry which one it is.\n *\n * ## The rule, and it is the whole point of this type\n *\n * **`error.payment` exists ⇔ a signed `X-PAYMENT` envelope had already left\n * this process.** Its ABSENCE on a metered failure is therefore itself an\n * answer: nothing was transmitted, so nothing could have settled. That covers\n * the 402 with no payer, the `DO_NOT_PAY` refusal, the 404 (which arrives\n * before any challenge is even read), and a payer that threw while signing —\n * an EIP-3009 authorization that never leaves the payer moves no money, because\n * money moves when the SELLER submits it, not when the buyer signs it.\n *\n * ## `settlement`, and the one thing it will not do is guess\n *\n * `'settled'` is asserted only against proof in hand: `X-Payment-Receipt`, whose\n * value is the settlement transaction hash (or the literal `\"pending\"`). Read on\n * 2026-08-30 in the service's own middleware —\n * `describe-net/describenet/paywall.py:1031-1065` — the paywall settles inside\n * `authorize()` **before** `call_next(request)` runs the handler, and then\n * attaches the receipt headers to whatever response comes back. A non-2xx\n * response with a receipt is therefore a settlement that happened, stated by the\n * seller.\n *\n * `'unknown'` is everything else, and it is honest rather than pessimistic. Two\n * measured holes forbid upgrading it to a verdict:\n *\n * 1. **A 500 can be settled and carry no receipt.** If the handler raises,\n * Starlette's `ServerErrorMiddleware` — which sits OUTSIDE the paywall\n * middleware, verified 2026-08-30: `api.py:2110` is the only\n * `add_middleware` for it and `api.py` registers no exception handler —\n * answers 500 without the header line ever running. The money moved in\n * `authorize()` regardless.\n * 2. **A dead socket proves nothing.** `fetch` rejects the same way whether\n * the connection died before the request bytes were written or while the\n * response was coming back.\n *\n * So: `'settled'` means *we hold the hash*. `'unknown'` means *ask the chain* —\n * never *\"nothing happened\"*. If you need the stronger answer, the receipt of a\n * later successful call and the on-chain transfer to the treasury are where it\n * lives; this SDK will not infer it for you.\n */\nexport interface PaymentAttempt {\n /** `'settled'` only with a receipt in hand. See the header of this type. */\n settlement: 'settled' | 'unknown';\n /** `X-Payment-Receipt` — the settlement tx hash, or `\"pending\"`. */\n receipt: string | null;\n /** `X-Payment-Reused: true` means an earlier receipt was replayed, no new charge. */\n reused: boolean | null;\n /** The status of the answer that failed, when an answer arrived at all. */\n status?: number;\n /** What the challenge asked for. Copied, never re-priced. */\n amount?: string;\n token?: string;\n /** The recipient we verified against the pinned treasury before signing. */\n payTo?: string;\n}\n\nexport class DescribeError extends Error {\n readonly kind: DescribeErrorKind;\n /** Would retrying help? Drives backoff, never `failOpen`. */\n readonly transient: boolean;\n /** Is this describe.net's fault? Drives `failOpen`, never retry. */\n readonly serviceFault: boolean;\n /** Present when a status was actually received. */\n readonly status?: number;\n /**\n * What to do INSTEAD, in one sentence — or `null` when there honestly is\n * nothing beyond the retry `transient` already announces (`timeout` is the\n * one, and `recovery.ts` says why at the entry).\n *\n * 🔴 **Branch on `kind`, read this.** It is prose meant for a human or an\n * agent, it is free to be re-worded, and matching on it is the mistake the\n * caveat codes exist to prevent one level up.\n *\n * 🔴 It is always one of the frozen literals in `recovery.ts` — never built\n * from a message, a URL or a `cause`. That is the redaction guard: a\n * transport exception can carry an endpoint with an API key in it, and this\n * is the string most likely to end up pasted into a ticket.\n */\n readonly recovery: string | null;\n /**\n * Set **only** when a signed envelope was already in flight. Not readonly for\n * one reason: the failure is built deep in the transport, which knows nothing\n * about payment, and `attachPayment()` stamps it on the way out. Treat it as\n * readonly — nothing in this package writes it twice.\n */\n payment?: PaymentAttempt;\n\n constructor(\n kind: DescribeErrorKind,\n message: string,\n opts: { transient: boolean; serviceFault: boolean; status?: number; cause?: unknown } = {\n transient: false,\n serviceFault: false,\n },\n ) {\n super(message, { cause: opts.cause });\n this.name = 'DescribeError';\n this.kind = kind;\n this.transient = opts.transient;\n this.serviceFault = opts.serviceFault;\n this.status = opts.status;\n // Derived here and NOWHERE else: every subclass gets its recovery from the\n // same table by construction, so none can forget one, invent one, or build\n // one out of a string that came from outside this package. The status is\n // passed for the single case where a kind is not fine enough — 429, the one\n // 4xx that is not the caller's bug.\n this.recovery = recoveryFor(kind, opts.status);\n }\n}\n\nexport class DescribeTimeout extends DescribeError {\n constructor(message: string, cause?: unknown) {\n super('timeout', message, { transient: true, serviceFault: true, cause });\n this.name = 'DescribeTimeout';\n }\n}\n\nexport class DescribeUnreachable extends DescribeError {\n constructor(message: string, cause?: unknown) {\n super('unreachable', message, { transient: true, serviceFault: true, cause });\n this.name = 'DescribeUnreachable';\n }\n}\n\nexport class DescribeUnparseable extends DescribeError {\n constructor(message: string, cause?: unknown) {\n // serviceFault: they answered and the answer was unreadable — that is on\n // them, so failOpen covers it. NOT transient: MeshRelay measured that\n // retrying an unparseable body buys nothing (`describenet.js:161-164`).\n super('unparseable', message, { transient: false, serviceFault: true, cause });\n this.name = 'DescribeUnparseable';\n }\n}\n\n/**\n * A hash field arrived with something that is not a hash.\n *\n * Contributed by **KarmaKadabra** (`#agents`, 2026-08-30), out of the finding\n * they call *\"el 200 sin tx\"*: *\"si nosotros no chequeáramos el tx, habríamos\n * contado 14 ratings que no existen\"*. A 200 that did not do the thing is worse\n * than a 503, because the client takes it for good.\n *\n * 🔴 **THIS IS NEVER THROWN. Do not write a `catch` for it.** It travels only as\n * the `error` of a {@link DescribeFailure} handed to `onFailure`, and it exists\n * as a class for one mechanical reason: that channel is typed\n * `DescribeError`, so reusing the channel the consumer is ALREADY watching —\n * which is what KarmaKadabra asked for — requires the fact to BE a\n * `DescribeError`. Branch on `kind === 'malformed_hash'` or on `instanceof`,\n * never on a `try/catch` that will not fire.\n *\n * ⚠️ There is a tension with this taxonomy and it is declared rather than\n * papered over: `partial_index` is also documented as never raised, and it is\n * kept only for parity with Execution Market's reference. Publishing exceptions\n * nobody throws invites dead `catch` blocks. What separates the two is what the\n * class is FOR: `partial_index` exists so someone can catch it and nobody will,\n * this one exists to ride a channel that is already typed, and its first line\n * shouts as much. If `onFailure` ever accepts something wider than a\n * `DescribeError`, this class stops being necessary.\n *\n * Why the failure does NOT take the read down: the rest of the response is very\n * likely useful, and killing a whole reputation breakdown over an accessory\n * field would be worse than the bug being hunted — especially on a metered\n * route, where the read has already been paid for. The typed field is left\n * `null` so nobody builds an explorer link out of garbage, and the raw value\n * survives in the result's `raw`, which is where it gets investigated.\n *\n * 🔴 **Absent and malformed are NOT the same thing, and the result keeps them\n * apart** (R1, one level below where it usually lives):\n *\n * ```\n * rating.txHash === null, malformedHashes empty → IT DID NOT COME\n * rating.txHash === null, 'tx_hash' in malformedHashes → GARBAGE CAME\n * ```\n *\n * `fields` carries the location of each one, with an index when it is inside a\n * list: `['ratings[3].tx_hash', 'snapshot.inputs_digest']`. Wire names, not\n * ours, because this string ends up in a ticket to whoever runs the index.\n *\n * `serviceFault` is **false** even though the bad data is describe.net's: this\n * flag drives `failOpen`, and a read that succeeded has nothing to fail open\n * INTO. `transient` is false for the same kind of reason — the same request will\n * bring the same bad field back.\n */\nexport class DescribeMalformedHash extends DescribeError {\n /** Qualified paths of the fields that arrived malformed, in order. */\n readonly fields: string[];\n constructor(message: string, fields: string[]) {\n super('malformed_hash', message, { transient: false, serviceFault: false });\n this.name = 'DescribeMalformedHash';\n this.fields = [...fields];\n }\n}\n\n/**\n * 404 — absence.\n *\n * ⚠️ **CORRECTED 2026-08-30, and the old text is left below because somebody\n * will come looking for it.** It used to say: *\"`DescribeClient.guard` converts\n * it to `null` before any caller sees it, which is why this class is not\n * exported from the package index: 'a 404 never reaches the caller as an error'\n * is structural here\"*. That stopped being true when the metered methods lost\n * their `| null` return: `walletBreakdown()` and `agent()` have no absence value\n * left to degrade INTO, so on those two routes a 404 arrives as this exception,\n * and the class is now exported so `instanceof` works.\n *\n * On the free routes nothing changed — still `null`, still announced through\n * `onFailure`, still regardless of `failOpen`.\n *\n * Absence did not become a failure; it changed clothes. It keeps\n * `transient: false`, `serviceFault: false`, and — the load-bearing part — **no\n * `payment`**: a metered 404 is checked before the challenge is even read, so\n * nothing was signed and nothing was spent to learn that there is nothing there.\n */\nexport class DescribeNotFound extends DescribeError {\n constructor(message: string) {\n super('not_found', message, { transient: false, serviceFault: false, status: 404 });\n this.name = 'DescribeNotFound';\n }\n}\n\nexport class DescribeHTTPError extends DescribeError {\n constructor(status: number, message: string) {\n const server = status >= 500;\n super(server ? 'http_5xx' : 'http_4xx', message, {\n // 429 is the one 4xx worth retrying: the 20 rps ceiling is shared with\n // every other UVD consumer, so it says \"someone else is loud right now\",\n // not \"your request is wrong\".\n transient: server || status === 429,\n // A 4xx is the caller's fault and must NOT vanish into failOpen — except\n // 429, which is the shared limit and reads exactly like a brief outage.\n serviceFault: server || status === 429,\n status,\n });\n this.name = 'DescribeHTTPError';\n }\n}\n\n/** The parsed 402, as served. Kept raw: we read it, we never re-price it. */\nexport interface X402Challenge {\n /** Human price, e.g. `\"0.01\"`. From the challenge — never typed by us. */\n amount?: string;\n /** Default recipient. Checked against the pinned treasury before paying. */\n recipient?: string;\n recipients?: Record<string, string | undefined>;\n token?: string;\n supportedChains?: number[];\n accepts?: Array<Record<string, unknown>>;\n /** Everything else the challenge carried, untouched (passthrough rule). */\n [key: string]: unknown;\n}\n\nexport class DescribePaymentRequired extends DescribeError {\n readonly challenge: X402Challenge;\n constructor(message: string, challenge: X402Challenge) {\n super('payment_required', message, { transient: false, serviceFault: false, status: 402 });\n this.name = 'DescribePaymentRequired';\n this.challenge = challenge;\n }\n}\n\nexport class DescribePaymentRefused extends DescribeError {\n readonly challenge: X402Challenge;\n readonly expected: string;\n readonly offered: string | undefined;\n constructor(expected: string, offered: string | undefined, challenge: X402Challenge) {\n super(\n 'payment_refused',\n `DO_NOT_PAY: the 402 challenge asks to pay ${offered ?? '(no recipient)'}, ` +\n `not the pinned treasury ${expected}. Nothing was signed.`,\n { transient: false, serviceFault: false, status: 402 },\n );\n this.name = 'DescribePaymentRefused';\n this.challenge = challenge;\n this.expected = expected;\n this.offered = offered;\n }\n}\n\n/**\n * Partner mode is on and the signature could not be produced.\n *\n * ## Why this THROWS instead of quietly paying, on every route\n *\n * The alternative is the one thing a partner rail must never do. Without a\n * signature the request is an ordinary anonymous request: describe.net answers\n * 402 on a metered route and the configured payer settles it, in USDC, silently\n * — the consumer keeps getting answers and only finds out at the invoice. Saul\n * asked for a rail where our own products read for free; a rail that degrades\n * into paying is not that rail, it is a bill.\n *\n * So this is a CALLER-fault error (`serviceFault: false`), which means\n * `failOpenCovers()` is `false` for it and `failOpen: true` does not swallow it\n * — not even on the free routes, where the signature costs nothing and buys\n * nothing. That is deliberate and not an oversight: a partner whose signer is\n * broken on `/health` has the same broken signer on\n * `/reputation/wallet/{w}` thirty seconds later, and the free call is the\n * cheapest possible place to find out.\n *\n * It carries no `payment` — nothing was sent, so nothing could have settled.\n *\n * 🔴 `cause` is the signer's own error and this class never reads it, never\n * reformats it and never puts it in `message`. A signer that fails on a\n * malformed key can have key material inside its exception (measured: see\n * `partner/index.ts`, the ethers `invalid BytesLike value` finding), and this\n * SDK will not be the thing that copies it into a log line.\n */\nexport class DescribePartnerUnsigned extends DescribeError {\n /** The signing address, when the signer published one. Public by design. */\n readonly address: string | undefined;\n constructor(path: string, address: string | undefined, cause: unknown) {\n super(\n 'partner_unsigned',\n `Partner mode is configured but signing GET ${path} failed` +\n `${address ? ` for ${address}` : ''}. This is a CALLER configuration ` +\n 'failure, and it is raised rather than downgraded on purpose: without a ' +\n 'signature this client is an anonymous client, and an anonymous client ' +\n 'PAYS. Read `error.cause` for the signer\\'s own error.',\n { transient: false, serviceFault: false, cause },\n );\n this.name = 'DescribePartnerUnsigned';\n this.address = address;\n }\n}\n\n/**\n * We signed as a partner and describe.net asked for money anyway.\n *\n * ## The case this class exists for, and it is the important one\n *\n * A partner client that gets a 402 has lost its free rail. If it falls through\n * to the payer, the fall is invisible: same answers, same latency, same shape —\n * and USDC leaving a wallet that budgeted none. The alternative failure (a loud\n * throw) costs one broken read and a fixable configuration; the silent one costs\n * money for as long as nobody looks.\n *\n * So partner mode does NOT pay by default. `partnerFallsBackToPaying: true`\n * turns it back on as an explicit, typed decision by the caller — the flag\n * exists so that \"pay anyway\" is something someone WROTE, never something that\n * happened.\n *\n * The challenge is attached unpaid, so a caller who decides to pay after all can\n * read exactly what it would have cost. And `payment` is absent: this is thrown\n * before `payer.pay()` is ever reached, so nothing was signed and nothing moved.\n */\nexport class DescribePartnerRejected extends DescribeError {\n readonly challenge: X402Challenge;\n /** The address we signed with. Public by design — the allowlist is public. */\n readonly address: string | undefined;\n constructor(path: string, address: string | undefined, challenge: X402Challenge) {\n super(\n 'partner_rejected',\n `GET ${path} answered 402 even though this client signed it as a partner` +\n `${address ? ` with ${address}` : ''}. The free rail is NOT active: the ` +\n 'address may not be in describe.net\\'s allowlist, the signed @authority ' +\n 'may not be api.describe.net (a custom baseUrl does that), the keyid ' +\n 'chain may not be 8453, or the clock may be off. NOTHING WAS PAID — ' +\n 'this throw is what stops a partner from silently spending USDC. Read ' +\n '`error.challenge` for the price, or set `partnerFallsBackToPaying: true` ' +\n 'to pay on purpose.',\n { transient: false, serviceFault: false, status: 402 },\n );\n this.name = 'DescribePartnerRejected';\n this.challenge = challenge;\n this.address = address;\n }\n}\n\n/**\n * Does `failOpen` cover this failure?\n *\n * The single predicate, so the rule lives in one place instead of being\n * re-derived at each call site. Saul's words were \"pon un fallback si es que\n * describe está caído\" — `serviceFault` is the typed form of \"está caído\", and\n * nothing else qualifies.\n *\n * ⚠️ **Corrected 2026-08-30 — this predicate answers a smaller question than it\n * used to.** It was the ONLY gate: every method ran its failure through it, so\n * `walletBreakdown()` and `agent()` returned `null` on any `serviceFault`,\n * including a timeout that arrived AFTER settlement. That is a spent credential\n * with no receipt, and the caller never learned they had paid. The rule now has\n * a term this predicate cannot see — *was there money in flight* — so the\n * metered methods never call it at all. It is still exported, and calling it\n * yourself on a paid failure answers a question you should not be asking: use\n * `failedAfterPaying()` instead.\n */\nexport function failOpenCovers(error: unknown): error is DescribeError {\n return error instanceof DescribeError && error.serviceFault;\n}\n\n/**\n * Did this failure happen with a signed envelope already in flight?\n *\n * `true` means the money MAY have moved and you should reconcile; read\n * `error.payment` for the receipt (proof) or the `'unknown'` that says the SDK\n * cannot tell. `false` means nothing was transmitted — a 402 with no payer, a\n * `DO_NOT_PAY`, a 404, a payer that declined, or any failure on a free route.\n */\nexport function failedAfterPaying(\n error: unknown,\n): error is DescribeError & { payment: PaymentAttempt } {\n return error instanceof DescribeError && error.payment !== undefined;\n}\n\n/**\n * Stamp a failure with what we know about the payment, on its way out.\n *\n * Internal: `client.ts` is the only caller, because it is the only place that\n * knows where the envelope was when things broke. Non-`DescribeError` throws\n * pass through untouched — a payer that throws its own `Error` is not ours to\n * annotate, and it never got as far as sending anything anyway.\n */\nexport function attachPayment(error: unknown, attempt: PaymentAttempt): unknown {\n if (error instanceof DescribeError) error.payment = attempt;\n return error;\n}\n","/**\n * Shape validation for the hash fields — *\"el 200 sin tx\"*, from KarmaKadabra.\n *\n * Pure: no network, no clock, no state. Strings in, booleans out.\n *\n * ## Where this comes from\n *\n * Contributed by **KarmaKadabra**, `#agents` on MeshRelay, **2026-08-30**. Their\n * words:\n *\n * > *\"Un 200 que no hizo la cosa es peor que un 503, porque el cliente lo toma\n * > por bueno: si nosotros no chequeáramos el tx, habríamos contado 14 ratings\n * > que no existen. Nosotros lo cazamos con un sello que exige forma de hash —\n * > pero el contrato debería decirlo, no cada cliente descubrirlo.\"*\n *\n * The second half is why this lives in the SDK: the check is a property of the\n * CONTRACT, and three consumers each discovering it separately is three chances\n * to get it wrong. Verified before writing a line: neither this SDK nor its\n * Python twin validated the shape of any hash field on 2026-08-30.\n *\n * ## 🔴 Why `^0x[0-9a-f]{64}$` alone would have been a disaster\n *\n * The obvious version of this file — one EVM regex — would have flagged **every\n * Solana rating in the index** as malformed. Two independent confirmations, both\n * read 2026-08-30:\n *\n * * from the writer: `describe-net/describenet/solana_indexer.py:436` puts\n * `firma[\"signature\"]` — a base58 signature — into the `tx_hash` column of\n * the INSERT at `indexer.py:153-157`, the same column the EVM indexer fills\n * with `0x…`. Solana writes to the same tables on purpose, so this is by\n * construction and not an accident of one sample;\n * * from the wire (measured by the Python twin against `GET /feed`): avalanche\n * and celo serve 66-char `0x` + 64 hex, solana serves 87- and 88-char base58\n * with no prefix.\n *\n * An alarm that screams about good data is worse than no alarm: people learn to\n * ignore it, and then it is silent on the day it is right. So this validates the\n * **union** of the legitimate shapes, never the intersection.\n *\n * The shapes the index emits today, each with its source:\n *\n * 1. **EVM hash** — `0x` + 64 hex. `chain/decode.py:253` does `\"0x\" + …hex()`\n * over a `bytes32` (`_NEW_FEEDBACK_TYPES:85`). This is `tx_hash`,\n * `revoked_tx` and `feedback_hash` on the ten EVM chains.\n * 2. **Solana signature** — base58 (Bitcoin alphabet: no `0`, `O`, `I`, `l`),\n * 86–88 characters. 64 bytes in base58 is 87–88; 86 is reachable with leading\n * zero bytes. On Solana `feedback_hash` is **NULL on purpose**, so a hole\n * there is correct and not a fault.\n * 3. **Bare digest** — 64 hex with **no** `0x`. That is `Snapshot.inputs_digest`,\n * which comes out of `hashlib.sha256(...).hexdigest()` in `aggregate.py:1920`.\n * Demanding the `0x` prefix would have marked every citable snapshot as\n * malformed.\n * 4. **The `pending` sentinel** — only on the `X-Payment-Receipt` header, whose\n * own OpenAPI declares it: the settlement hash *\"or `pending` if settlement\n * has not reported one\"*. It is a LEGITIMATE value, which is why\n * {@link looksLikeSettlementReceipt} exists separately: treating it as\n * garbage would fire an alarm on the happy path of every fresh payment.\n *\n * ## 🔴 What is deliberately NOT validated: `build_sha`\n *\n * `IndexHealth.buildSha` looks like a hash and is not one, and the measurement\n * that settles it is `describe-net/scripts/build_lambda_zip.py:64` (read\n * 2026-08-30): `estampa = sha + (\"-dirty\" if sucio else \"\")`. A legitimate\n * deploy can therefore publish `\"<40 hex>-dirty\"`, and a validator would scream\n * about a perfectly good build — forever, on every `/health` call. The general\n * rule that falls out of it, and it is the one to apply to the next field:\n * **validate the identifiers a caller will carry somewhere to verify (an\n * explorer, a digest comparison); leave alone the strings that only describe a\n * build.** Nobody looks up a `build_sha`; the service already refuses to publish\n * its `unknown` default as if it were a SHA (`api.py:2439-2456`).\n *\n * ## The question this module answers — and the one it does not\n *\n * It answers **\"does this have the shape of an on-chain identifier?\"**. It does\n * NOT answer \"does this transaction exist?\" or \"does it say what the index says\n * it says\": that is verified in an explorer, which is the entire point of the\n * field (the service's own schema: *\"go verify it in an explorer, which is the\n * point\"*). A shape check cannot prove existence and does not pretend to.\n *\n * What it does catch is what bit KarmaKadabra: the empty string, `\"null\"`,\n * `\"undefined\"`, `\"0x\"`, `\"0x0\"`, a truncated hash, an error message parked in\n * the field. Every one of those sails through an `if (rating.txHash)` today with\n * nothing making a sound.\n *\n * 🔴 **And it deliberately does not validate per chain.** A `feedback_hash`\n * shaped like a Solana signature is accepted even though Solana emits none\n * today. Being strict per field would trade a cheap false negative (letting an\n * odd-but-valid shape through) for an expensive false positive (screaming about\n * good data the day the service extends a field), and that contradicts the\n * passthrough rule this package is built on: type what is known, PRESERVE what\n * is not.\n */\n\n/**\n * `0x` + 64 hex. Case-insensitive: the index serves lowercase, but a hash\n * written in mixed case is the same hash and flagging it would be a false\n * positive.\n */\nconst EVM_HASH = /^0x[0-9a-fA-F]{64}$/;\n\n/** 64 hex with NO prefix — a `sha256(...).hexdigest()`, i.e. `inputs_digest`. */\nconst BARE_DIGEST = /^[0-9a-fA-F]{64}$/;\n\n/**\n * Base58, Bitcoin alphabet (no `0`, `O`, `I`, `l`), 86–88 characters: a Solana\n * transaction signature. Both high lengths measured live on 2026-08-30.\n */\nconst BASE58_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{86,88}$/;\n\n/**\n * The one non-hash value the `X-Payment-Receipt` header declares legitimate.\n *\n * The live OpenAPI says it, not us: the settlement transaction hash *\"or\n * `pending` if settlement has not reported one\"*.\n */\nexport const SETTLEMENT_PENDING = 'pending';\n\n/**\n * Does `value` have the shape of an on-chain identifier this index emits?\n *\n * The UNION of the three measured shapes (EVM hash, Solana signature, bare\n * digest) — never the intersection. See the module header for why an EVM-only\n * regex would have marked every Solana rating as malformed.\n *\n * It does not prove the transaction exists. That is the explorer's job.\n */\nexport function looksLikeOnchainId(value: string): boolean {\n return EVM_HASH.test(value) || BASE58_SIGNATURE.test(value) || BARE_DIGEST.test(value);\n}\n\n/**\n * The same, plus the `pending` sentinel. For `X-Payment-Receipt` and nothing\n * else.\n *\n * `pending` is not garbage: it is the seller saying *\"I charged you and\n * settlement has not reported the hash yet\"*, and it is in their OpenAPI.\n * Marking it malformed would turn the happy path of every freshly settled\n * payment into an alarm.\n */\nexport function looksLikeSettlementReceipt(value: string): boolean {\n return value === SETTLEMENT_PENDING || looksLikeOnchainId(value);\n}\n\n/**\n * Read one hash field off a wire object: keep it if it has the shape of a hash,\n * otherwise `null` **and a mark**.\n *\n * 🔴 **Absent and malformed are not the same thing** (R1, applied one level\n * below where it usually lives) and this function is where the distinction is\n * made, so read the two cases carefully:\n *\n * ```\n * did not come → null, and `key` does NOT enter `malformed`. This is normal\n * and documented: the schema itself says tx_hash is \"null\n * until the log scan reaches this entry, not null forever\",\n * and Solana writes feedback_hash NULL on purpose.\n * came garbage → null AND `key` in `malformed`. THIS is the one that shouts.\n * ```\n *\n * A caller therefore branches on the list, never on `field === null`.\n *\n * Why the value is dropped rather than passed through: the field exists so\n * somebody can build an explorer link out of it, and a link built from garbage\n * is the \"200 that did not do the thing\" arriving one layer later. Why it does\n * not throw: the rest of the response is very likely useful, and killing a whole\n * reputation breakdown over an accessory field would be worse than the bug being\n * hunted. The original value is not lost — it stays in the result's `raw`, which\n * is where it gets investigated.\n *\n * A non-string that is not `null`/`undefined` (a number, an object) counts as\n * garbage, not as absence: the wire said something and it was not a hash.\n */\nexport function hashField(\n row: Record<string, unknown>,\n key: string,\n malformed: string[],\n ok: (value: string) => boolean = looksLikeOnchainId,\n): string | null {\n const value = row[key];\n if (value === null || value === undefined) return null;\n if (typeof value === 'string' && ok(value)) return value;\n malformed.push(key);\n return null;\n}\n\n/** Anything that carries the marks of its own malformed hash fields. */\ninterface MalformedCarrier {\n malformedHashes?: readonly string[];\n}\n\n/**\n * Every malformed hash field of a result, located.\n *\n * Walks the places a hash can hide in a parsed result and returns qualified\n * paths, in the order they appear:\n *\n * ```ts\n * ['ratings[3].tx_hash', 'snapshot.inputs_digest', 'payment.receipt']\n * ```\n *\n * Wire names (`tx_hash`), not ours (`txHash`), on purpose: this string is what\n * ends up in a log line or a ticket to whoever runs the index, and it has to\n * name the field the way the API does.\n *\n * An empty array is the normal case and means \"no field arrived malformed\" — it\n * says nothing about which fields arrived at all. An absent hash is legitimate\n * and is not reported here.\n */\nexport function malformedHashReport(\n result:\n | {\n ratings?: readonly MalformedCarrier[];\n snapshot?: MalformedCarrier | null;\n payment?: MalformedCarrier | null;\n }\n | null\n | undefined,\n): string[] {\n if (!result) return [];\n const fields: string[] = [];\n (result.ratings ?? []).forEach((rating, i) => {\n for (const name of rating.malformedHashes ?? []) fields.push(`ratings[${i}].${name}`);\n });\n for (const attr of ['snapshot', 'payment'] as const) {\n const part = result[attr];\n if (part) for (const name of part.malformedHashes ?? []) fields.push(`${attr}.${name}`);\n }\n return fields;\n}\n","/**\n * A short random pause before a read, so a fleet does not arrive as one spike.\n *\n * ## Where this comes from, and what not having it cost\n *\n * Contributed by **KarmaKadabra**, `#agents` on MeshRelay, **2026-08-30**. They\n * operate the largest fleet against this index — 27 agents — and their sentence\n * is the whole specification:\n *\n * > *\"27 agentes despiertan al MISMO tiempo por EventBridge y pegan simultáneo\n * > contra su límite de rps COMPARTIDO con los otros consumidores. Sin jitter,\n * > un enjambre es un DDoS educado.\"*\n *\n * They sleep `random.uniform(0, 0.4)` before every read\n * (`karmakadabra/lib/reputation_scan.py:123`). Verified before writing a line:\n * `grep -riE 'jitter|random|sleep' src/` in **both** SDKs returned zero hits on\n * 2026-08-30. Neither of us had it.\n *\n * Two halves of what follows are theirs and two are ours, and the line matters\n * because provenance is the reason to trust a number: **measured at\n * KarmaKadabra** are the 0.4 s and the non-cryptographic uniform draw.\n * **Designed here** are everything about it being a parameter at all — the\n * default being ON, `0` switching it off, and a garbage value falling back to\n * the default rather than to off. KarmaKadabra has no jitter option; they have\n * a literal.\n *\n * The word that makes it the library's problem and not the fleet's is\n * **COMPARTIDO**. describe.net's rate limit has no per-partner bucket (already\n * written down in `config.ts`), so the agent that pays for an unjittered swarm\n * is not the swarm's owner — it is the other consumer whose read gets the 429,\n * and who has no lever to fix it. That is the shape of an externality, and a\n * default that leaves the cost on someone with no lever is the wrong default.\n *\n * ## 🔴 Jitter is NOT backoff, and the day someone adds a retry this matters\n *\n * They look alike (both sleep) and they answer opposite questions. **Jitter\n * disperses a herd that has not asked for anything yet**; it goes before a\n * request and its size is about how many of us there are. **Backoff yields to a\n * service that has already said no**; it goes before a RETRY and its size is\n * about how hard it just refused. So a retry — this package has none,\n * deliberately, see `client.ts` — takes backoff, never this.\n *\n * ## 🔴 It goes before EVERY request, not once per public call\n *\n * ⚠️ **This is a correction of the rule this file was first written with, and\n * the old one is left here because it is the intuitive reading and the next\n * person to touch this will want to \"optimise\" back to it.** The first version\n * said *\"once per public call, before the FIRST request\"*. It sounds\n * equivalent. It is not: a call that fires N requests would disperse one and\n * let the other N−1 out in a pack — the exact problem this contribution came to\n * fix, reintroduced through the back door.\n *\n * KarmaKadabra's own call site settles it, and it was read rather than assumed\n * (2026-08-30): the sleep lives INSIDE `_scan_describenet()`, the function that\n * performs the GET (`reputation_scan.py:123`), and that function runs **twice**\n * on the real path — `:242` for the EVM address, `:245` for the Solana one. So\n * their jitter is per REQUEST, and the reason they wrote next to it\n * (`:121-122`) is per-PROCESS: it is anti-thundering-herd between agents that\n * wake together against a shared ceiling, not a spacer inside one call.\n *\n * The paid replay sleeps too, and that is the same correction. It was going to\n * be the one exception here, on the argument that delaying a signed envelope\n * widens the window in which a crash loses a receipt. Measured against the\n * numbers, that argument does not hold: the challenge this client answers\n * carries `maxTimeoutSeconds: 120`, so 400 ms is a third of a percent of the\n * envelope's own validity, while the herd argument applies to the replay in\n * full — 27 agents that get their 402 in the same second replay in the same\n * second. One rule with no exception, and nothing in the money path is\n * measurably worse for it.\n *\n * ## 🔴 `Math.random`, and never `crypto.getRandomValues`\n *\n * This is dispersion, not a secret. Nothing about the delay needs to be\n * unguessable: an adversary who predicts that this process will wait 213 ms\n * learns nothing worth knowing, and cannot use it. Reaching for a CSPRNG here\n * would be worse than useless — it tells the next reader that unpredictability\n * is a security property of this value, which invites them to \"harden\" a\n * sleep. `Math.random` is uniform enough for spreading arrivals, is available\n * in every runtime this package targets (browser included), and costs nothing.\n */\n\n/**\n * How long to wait, in milliseconds: a uniform draw from `[0, maxMs)`.\n *\n * Pure, so it is tested exhaustively without a clock. `random` is injectable for\n * exactly that reason and for no other — production always passes `Math.random`.\n *\n * Garbage in gives the caller's own configured default nothing to stand on, so\n * this function's contract is narrow: it clamps rather than throws. A `maxMs`\n * that is not a finite positive number yields `0`, because a library that dies\n * at read time over a mistyped option is worse than one that does not sleep.\n * The decision about what a garbage OPTION means (fall back to the default, not\n * to off) belongs one level up, in `DescribeClient` — see `jitterMs` there.\n */\nexport function jitterDelayMs(maxMs: number, random: () => number = Math.random): number {\n if (!Number.isFinite(maxMs) || maxMs <= 0) return 0;\n const draw = random();\n if (!Number.isFinite(draw) || draw < 0) return 0;\n return Math.min(draw, 1) * maxMs;\n}\n\n/**\n * The only timer in this package.\n *\n * `setTimeout` and not a busy loop, obviously — but also not `unref()`d: a\n * process that exits while a read is pending would have dropped that read\n * anyway, and `unref` is Node-only, which would break the browser target this\n * package keeps.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * The caveat codes, exported as a contract.\n *\n * ## The rule, and it is theirs, not ours\n *\n * describe.net declares it in `describenet/caveats.py:88-93`:\n *\n * > **EL TEXTO puede cambiar sin aviso** —re-redactarse, re-medirse, hasta\n * > traducirse—; **EL CODE jamás.**\n *\n * So a consumer branches on `code` and renders `text`, never the reverse. This\n * is not hygiene, it is a repair: until 2026-08-28 a caveat was a bare Spanish\n * string, ecosystem consumers matched on the prose, and when the thin-evidence\n * cut moved on 2026-08-25 every one of those matches broke silently — the\n * string comparison kept returning false and nobody was told.\n *\n * Exporting the set is one of the four \"día 0\" requirements the platform team\n * put on any SDK of the house (`D9-c0der.md:234-241`): *los caveat `code`s como\n * contrato exportado*. Typing them here means a consumer never re-types them,\n * and a typo is a compile error rather than a branch that is never taken.\n *\n * ## Why the type is not a closed union\n *\n * `CaveatCode | (string & {})` gives autocomplete on the eight codes that exist\n * today AND still accepts a ninth one the server adds tomorrow. A closed union\n * would turn every new server-side code into a type error in code that is\n * already deployed and working — the passthrough rule (tipar lo conocido,\n * CONSERVAR lo que no) applied to the type system. The measured precedent is\n * `Facet.direction`: FastAPI silently dropped a field nobody had declared, and\n * the response looked correct with the data missing.\n *\n * The codes carry no version and never bump `POLICY_VERSION`: a caveat is\n * advisory by construction and identifies a CUT, it never moves a score.\n */\n\n/**\n * The eight cuts served on 2026-08-30, copied from the frozen set in\n * `describenet/caveats.py:172-183` (which its own\n * `tests/test_caveat_codes.py` pins literally, so adding or renaming one over\n * there goes red on purpose).\n *\n * Only `no-score` and `burn-address` are computable from public data, so the\n * free routes serve a documented SUBSET — an empty `caveats: []` on a free\n * response means \"no public-data caveat\", NOT \"clean\". The other six need the\n * grain and ride the metered routes. See `CAVEAT_SCOPE_FREE`.\n */\nexport const CAVEAT_CODES = [\n /** No score to qualify: there is no eligible rating at all. */\n 'no-score',\n /** The concentration signal itself is degraded and should not be leaned on. */\n 'concentration-degraded',\n /** Exactly one distinct counterparty is behind this score. */\n 'single-rater',\n /** Below the evidence bar (`reading_policy.min_raters`, 3 as of 2026-08-30). */\n 'few-raters',\n /** One client wrote more than `reading_policy.top_share` of the ratings. */\n 'top-client-share',\n /** Ratings-per-rater above `reading_policy.campaign_per_rater` — looks like a campaign. */\n 'campaign-per-rater',\n /** The subject rated itself. */\n 'self-rated',\n /**\n * The subject is a burn address: nobody controls it, anyone may rate it, and\n * nobody can answer for its reputation. The ratings are real on-chain facts\n * — which is why they are still served — but the subject is not an identity.\n */\n 'burn-address',\n] as const;\n\n/** The eight known codes as a union — for `switch`, not for validation. */\nexport type KnownCaveatCode = (typeof CAVEAT_CODES)[number];\n\n/**\n * What a caveat's `code` may be: one of the eight, or any string the server\n * starts sending. The `(string & {})` half is what keeps autocomplete alive\n * while leaving the union open.\n */\nexport type CaveatCode = KnownCaveatCode | (string & {});\n\n/** As served since 2026-08-28: `{code, text}`, never a bare string. */\nexport interface Caveat {\n /** The contract. Stable, kebab-case. Branch on this. */\n code: CaveatCode;\n /** Prose. May be re-worded, re-measured or translated without notice. Render this. */\n text: string;\n}\n\n/**\n * What an empty `caveats: []` claims on a FREE route.\n *\n * describe.net's own definition (given 2026-08-29, recorded in\n * `meshrelay/describenet.js:265-277`): on the free routes `[]` means \"no\n * PUBLIC-DATA caveat\", not \"no caveats\" — the evidence-quality cuts are only\n * computable behind the metered routes. A surface that renders a bare `[]` as\n * \"clean\" publishes a claim the index never made. Carry the scope with the\n * list, the same discipline as the `n/m` coverage next to any aggregate.\n */\nexport const CAVEAT_SCOPE_FREE = 'public-data-subset';\n\n/** Everything a metered route can fire — the free subset plus the six from the grain. */\nexport const CAVEAT_SCOPE_METERED = 'full';\n\n/**\n * Is this code known to the version of the SDK you have installed?\n *\n * Deliberately NOT a validator: a `false` means \"we have not heard of it\",\n * never \"it is invalid\". An unknown code is served through untouched.\n */\nexport function isKnownCaveatCode(code: string): code is KnownCaveatCode {\n return (CAVEAT_CODES as readonly string[]).includes(code);\n}\n\n/**\n * Does this result carry `code`?\n *\n * Exists so consumers stop writing `caveats.some(c => c.text.includes('...'))`\n * — the exact line that broke silently on 2026-08-25.\n */\nexport function hasCaveat(\n subject: { caveats?: readonly Caveat[] } | null | undefined,\n code: CaveatCode,\n): boolean {\n return (subject?.caveats ?? []).some((c) => c.code === code);\n}\n","/**\n * Wire JSON → typed shape.\n *\n * Three rules, and each one is a bug that already happened somewhere:\n *\n * 1. **`null` survives.** `optNumber` returns `null` for `null` and NEVER `0`.\n * Every `|| 0` in a parser is an invariant-7 violation waiting for its first\n * unrated wallet.\n * 2. **Unknown fields survive.** Every result keeps `raw`. The server may add a\n * field tomorrow and a consumer must not wait for our release to read it.\n * 3. **A body that is not the shape we asked for is `unparseable`, not\n * garbage-in-silence.** The failure that has to be impossible here is a\n * response that parses \"successfully\" into an object full of zeros.\n * 4. **A hash field that is not a hash is dropped and MARKED, never passed\n * through.** Added 2026-08-30 from KarmaKadabra's *\"el 200 sin tx\"*. The\n * typed field goes `null` — nobody builds an explorer link out of garbage —\n * and its wire name goes into the `malformedHashes` of the object that owns\n * it, so that **absent** (`null`, list empty) stays distinguishable from\n * **malformed** (`null`, name in the list). It is rule 1 one level down: the\n * absence of a value and a value that is nonsense are different facts, and\n * collapsing them is the failure this file exists to prevent. See\n * `hashes.ts`, and `client.ts` for how the fact reaches the caller.\n */\n\nimport { CAVEAT_SCOPE_FREE, CAVEAT_SCOPE_METERED, type Caveat } from './caveats';\nimport { DescribeUnparseable } from './errors';\nimport { hashField } from './hashes';\nimport type {\n Activity,\n AgentReputation,\n Concentration,\n Confidence,\n Facet,\n HealthChain,\n IndexHealth,\n LeaderboardRow,\n Ownership,\n PaymentEvidence,\n Rating,\n SelfRated,\n Snapshot,\n WalletBreakdown,\n WalletChainRow,\n WalletReputation,\n} from './types';\n\ntype Obj = Record<string, unknown>;\n\nconst isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/**\n * `null` in, `null` out. The single most load-bearing line of this file.\n *\n * A missing score is `null`; a present score is a number. There is no third\n * branch, and in particular there is no branch that produces `0`.\n *\n * Verified discriminant on 2026-08-30 by mounting the bad state: replacing the\n * body below with `Number(v ?? 0)` turns three tests in `client.test.ts`\n * (\"R1 — null never 0\") red, including the one that asserts an unrated wallet\n * stays distinguishable from a wallet actually scored zero. A green suite with\n * this function broken is not reachable, which is the only reason to trust the\n * green one.\n */\nfunction optNumber(v: unknown): number | null {\n if (v === null || v === undefined) return null;\n const n = Number(v);\n return Number.isFinite(n) ? n : null;\n}\n\nfunction num(v: unknown, fallback = 0): number {\n const n = Number(v);\n return Number.isFinite(n) ? n : fallback;\n}\n\nfunction optString(v: unknown): string | null {\n return typeof v === 'string' ? v : null;\n}\n\nfunction strArray(v: unknown): string[] | null {\n return Array.isArray(v) ? v.map(String) : null;\n}\n\n/**\n * Caveats, keeping BOTH halves.\n *\n * EM's Python reference keeps only the `code` (`types.py:269-273`) so nobody\n * can render the volatile prose. That is right for a reconciler and wrong for\n * an SDK: a UI has to print SOMETHING, and if we drop `text` every consumer\n * re-writes the eight strings by hand — the duplication this package exists to\n * remove, and in the one field the index says may change without notice. So we\n * carry both and the docs say which is the contract (`caveats.ts`).\n *\n * An entry that is not `{code, text}` is dropped rather than guessed at: a\n * caveat we cannot name is a caveat we cannot let anyone branch on.\n */\nfunction parseCaveats(v: unknown): Caveat[] {\n if (!Array.isArray(v)) return [];\n const out: Caveat[] = [];\n for (const entry of v) {\n if (isObj(entry) && typeof entry.code === 'string') {\n out.push({ code: entry.code, text: typeof entry.text === 'string' ? entry.text : '' });\n }\n }\n return out;\n}\n\nfunction parseFacets(v: unknown): Record<string, Facet> {\n if (!isObj(v)) return {};\n const out: Record<string, Facet> = {};\n for (const [key, raw] of Object.entries(v)) {\n if (!isObj(raw)) continue;\n out[key] = {\n score: optNumber(raw.score),\n count: num(raw.count),\n distinctRaters: num(raw.distinct_raters),\n revokedCount: num(raw.revoked_count),\n outOfDomainCount: num(raw.out_of_domain_count),\n selfRatedCount: num(raw.self_rated_count),\n direction: optString(raw.direction),\n directionCategory: optString(raw.direction_category),\n directionMeaning: optString(raw.direction_meaning),\n };\n }\n return out;\n}\n\nfunction parseSelfRated(v: unknown): SelfRated | null {\n if (!isObj(v)) return null;\n return { count: num(v.count), score: optNumber(v.score), gap: optNumber(v.gap) };\n}\n\nfunction parseConcentration(v: unknown): Concentration | null {\n if (!isObj(v)) return null;\n return {\n distinctRaters: num(v.distinct_raters),\n topClientShare: optNumber(v.top_client_share),\n topClient: optString(v.top_client),\n };\n}\n\nfunction parseConfidence(v: unknown): Confidence | null {\n if (!isObj(v)) return null;\n const iv = v.interval;\n return {\n band: String(v.band ?? ''),\n distinctRaters: num(v.distinct_raters),\n interval: isObj(iv) ? { lower: num(iv.lower), upper: num(iv.upper) } : null,\n thresholds: isObj(v.thresholds) ? (v.thresholds as Record<string, number>) : {},\n advice: String(v.advice ?? ''),\n confidencePolicy: String(v.confidence_policy ?? ''),\n };\n}\n\nfunction parseActivity(v: unknown): Activity | null {\n if (!isObj(v)) return null;\n return { firstRatingAt: optString(v.first_rating_at), lastRatingAt: optString(v.last_rating_at) };\n}\n\nfunction parseSnapshot(v: unknown): Snapshot | null {\n if (!isObj(v)) return null;\n const malformed: string[] = [];\n return {\n id: num(v.id),\n // A bare sha256 hexdigest, no `0x` (`aggregate.py:1920`). This one is worth\n // validating precisely because it is the citable field: two snapshots with\n // the same digest are supposed to say the same thing, and a comparison\n // between two garbage strings can agree by accident.\n inputsDigest: hashField(v, 'inputs_digest', malformed),\n policyVersion: String(v.policy_version ?? ''),\n computedAt: String(v.computed_at ?? ''),\n malformedHashes: malformed,\n };\n}\n\nfunction parseOwnership(v: unknown): Ownership | null {\n if (!isObj(v)) return null;\n return {\n ownerUpdatedBlock: num(v.owner_updated_block),\n identityTransferred: typeof v.identity_transferred === 'boolean' ? v.identity_transferred : null,\n inheritedReviewCount: num(v.inherited_review_count),\n inheritedScore: optNumber(v.inherited_score),\n currentEraReviewCount: num(v.current_era_review_count),\n currentEraScore: optNumber(v.current_era_score),\n undeterminedReviewCount: num(v.undetermined_review_count),\n inheritedShare: optNumber(v.inherited_share),\n };\n}\n\n/**\n * One rating, with its THREE hash fields shape-validated.\n *\n * KarmaKadabra's contribution (2026-08-30): a `tx_hash` that is not a hash is a\n * 200 that did not do the thing, and *\"si nosotros no chequeáramos el tx,\n * habríamos contado 14 ratings que no existen\"*. Anything that is not a hash\n * becomes `null` and its wire name goes into the rating's `malformedHashes` —\n * never an exception, because one bad accessory field must not destroy a\n * decomposition the caller paid for. See `hashes.ts` for the four legitimate\n * shapes and for why an EVM-only regex would have flagged all of Solana.\n */\nfunction parseRatings(v: unknown): Rating[] {\n if (!Array.isArray(v)) return [];\n return v.filter(isObj).map((r) => {\n const malformed: string[] = [];\n return {\n client: String(r.client ?? ''),\n feedbackIndex: num(r.feedback_index),\n value: num(r.value),\n valueDecimals: num(r.value_decimals),\n normalizedValue: optNumber(r.normalized_value),\n tag1: optString(r.tag1),\n tag2: optString(r.tag2),\n isRevoked: r.is_revoked === true,\n isSelf: r.is_self === true,\n txHash: hashField(r, 'tx_hash', malformed),\n blockNumber: optNumber(r.block_number),\n logIndex: optNumber(r.log_index),\n feedbackUri: optString(r.feedback_uri),\n issuerHost: optString(r.issuer_host),\n issuer: optString(r.issuer),\n issuerOrg: optString(r.issuer_org),\n feedbackHash: hashField(r, 'feedback_hash', malformed),\n revokedTx: hashField(r, 'revoked_tx', malformed),\n malformedHashes: malformed,\n };\n });\n}\n\n// ---------------------------------------------------------------------------\n\n/** `GET /wallets/{wallet}/chains`. Requires `wallet` — everything else may be absent. */\nexport function parseWalletReputation(payload: unknown): WalletReputation {\n if (!isObj(payload) || typeof payload.wallet !== 'string') {\n throw new DescribeUnparseable('wallet-chains response is missing its essential shape (wallet)');\n }\n const rows = Array.isArray(payload.chains) ? payload.chains : [];\n const chains: WalletChainRow[] = rows.filter(isObj).map((row) => ({\n network: String(row.network ?? ''),\n agentCount: num(row.agent_count),\n agentIds: strArray(row.agent_ids),\n finalScore: optNumber(row.final_score),\n totalReviews: num(row.total_reviews),\n distinctRaters: num(row.distinct_raters),\n }));\n\n return {\n wallet: payload.wallet,\n chains,\n globalScore: optNumber(payload.global_score),\n distinctRaters: optNumber(payload.distinct_raters),\n identityCount: num(payload.identity_count),\n chainsWithIdentity: num(payload.chains_with_identity),\n chainsWithReputation: num(payload.chains_with_reputation),\n totalReviews: num(payload.total_reviews),\n policyVersion: optString(payload.policy_version),\n caveats: parseCaveats(payload.caveats),\n caveatScope: CAVEAT_SCOPE_FREE,\n source: optString(payload.source),\n refreshedAt: optString(payload.refreshed_at),\n raw: payload,\n };\n}\n\n/** `GET /reputation/wallet/{wallet}` — metered. */\nexport function parseWalletBreakdown(\n payload: unknown,\n payment: PaymentEvidence | null,\n): WalletBreakdown {\n if (!isObj(payload) || typeof payload.wallet !== 'string') {\n throw new DescribeUnparseable('wallet-breakdown response is missing its essential shape (wallet)');\n }\n return {\n wallet: payload.wallet,\n finalScore: optNumber(payload.final_score),\n weightedScore: optNumber(payload.weighted_score),\n raterWeightPolicy: String(payload.rater_weight_policy ?? ''),\n chainCount: num(payload.chain_count),\n totalReviews: num(payload.total_reviews),\n perChain: isObj(payload.per_chain) ? payload.per_chain : {},\n facets: parseFacets(payload.facets),\n selfRated: parseSelfRated(payload.self_rated),\n concentration: parseConcentration(payload.concentration),\n confidence: parseConfidence(payload.confidence),\n activity: parseActivity(payload.activity),\n snapshot: parseSnapshot(payload.snapshot),\n payment,\n policyVersion: optString(payload.policy_version),\n caveats: parseCaveats(payload.caveats),\n caveatScope: CAVEAT_SCOPE_METERED,\n source: optString(payload.source),\n refreshedAt: optString(payload.refreshed_at),\n raw: payload,\n };\n}\n\n/** `GET /reputation/agent/{network}/{agent_id}` — metered. */\nexport function parseAgentReputation(\n payload: unknown,\n payment: PaymentEvidence | null,\n): AgentReputation {\n if (!isObj(payload) || payload.agent_id === undefined) {\n throw new DescribeUnparseable('agent response is missing its essential shape (agent_id)');\n }\n return {\n network: String(payload.network ?? ''),\n agentId: String(payload.agent_id),\n currentOwner: optString(payload.current_owner),\n declaredType: optString(payload.declared_type),\n agentUri: optString(payload.agent_uri),\n indexedIdentity: payload.indexed_identity === true,\n score: optNumber(payload.score),\n reviewCount: num(payload.review_count),\n revokedCount: num(payload.revoked_count),\n outOfDomainCount: num(payload.out_of_domain_count),\n selfRated: parseSelfRated(payload.self_rated),\n facets: parseFacets(payload.facets),\n concentration: parseConcentration(payload.concentration),\n ownership: parseOwnership(payload.ownership),\n confidence: parseConfidence(payload.confidence),\n ratings: parseRatings(payload.ratings),\n payment,\n policyVersion: optString(payload.policy_version),\n caveats: parseCaveats(payload.caveats),\n caveatScope: CAVEAT_SCOPE_METERED,\n source: optString(payload.source),\n refreshedAt: optString(payload.refreshed_at),\n raw: payload,\n };\n}\n\n/**\n * `GET /leaderboard` — a bare JSON array (verified live 2026-08-30: 100 rows,\n * no envelope). NOT `{rows: [...]}`, which is what a reader expecting a\n * paginated shape would assume.\n */\nexport function parseLeaderboard(payload: unknown): LeaderboardRow[] {\n if (!Array.isArray(payload)) {\n throw new DescribeUnparseable('leaderboard response is not an array');\n }\n return payload.filter(isObj).map((row) => ({\n rank: num(row.rank),\n wallet: String(row.wallet ?? ''),\n finalScore: optNumber(row.final_score),\n shrunkScore: optNumber(row.shrunk_score),\n distinctRaters: num(row.distinct_raters),\n chainCount: num(row.chain_count),\n totalReviews: num(row.total_reviews),\n networks: Array.isArray(row.networks) ? row.networks.map(String) : [],\n declaredTypes: Array.isArray(row.declared_types)\n ? row.declared_types.map((t) => (typeof t === 'string' ? t : null))\n : [],\n raw: row,\n }));\n}\n\n/** `GET /health`. */\nexport function parseHealth(payload: unknown): IndexHealth {\n if (!isObj(payload) || typeof payload.status !== 'string') {\n throw new DescribeUnparseable('health response is missing its essential shape (status)');\n }\n const chains: HealthChain[] = (Array.isArray(payload.chains) ? payload.chains : [])\n .filter(isObj)\n .map((row) => ({\n network: String(row.network ?? ''),\n lastScannedBlock: optNumber(row.last_scanned_block),\n updatedAt: optString(row.updated_at),\n nextSyncAt: optString(row.next_sync_at),\n lastError: optString(row.last_error),\n raw: row,\n }));\n\n return {\n status: payload.status,\n policyVersion: String(payload.policy_version ?? ''),\n orderingPolicy: String(payload.ordering_policy ?? ''),\n raterWeightPolicy: String(payload.rater_weight_policy ?? ''),\n confidencePolicy: String(payload.confidence_policy ?? ''),\n confidenceThresholds: isObj(payload.confidence_thresholds)\n ? (payload.confidence_thresholds as Record<string, number>)\n : {},\n readingPolicy: isObj(payload.reading_policy) ? payload.reading_policy : {},\n buildSha: optString(payload.build_sha),\n agents: num(payload.agents),\n feedbackEntries: num(payload.feedback_entries),\n indexerPeriodSeconds: optNumber(payload.indexer_period_seconds),\n chains,\n raw: payload,\n };\n}\n","/**\n * `DescribeClient` — six methods, four of which touch the network.\n *\n * ## The one thing to read before changing anything here\n *\n * There are THREE different absences in this file and collapsing any two of\n * them is the failure this package exists to prevent:\n *\n * 1. **`globalScore: null` inside a returned object** — \"the index looked and\n * there is no eligible rating\". Verified live on 2026-08-30 against\n * `0xdEaD…BEEF`: HTTP 200, `chains: []`, `global_score: null`. Data.\n * 2. **The method returning `null`** — \"we could not ask\" (`failOpen`).\n * describe.net is down, or slow, or answered something unreadable.\n * 3. **A thrown `DescribeError`** — the caller's request was wrong, or a 402\n * arrived with no payer, or a challenge named the wrong treasury.\n *\n * A fail-open that is silent turns (2) into (1) — \"describe is down\" becomes\n * \"this wallet has no reputation\" — which is precisely the confusion R1 exists\n * to forbid, arriving through the back door. That is why `onFailure` is not\n * optional decoration: it is the half of `failOpen` that keeps it honest, and\n * `client.test.ts` asserts a failure is always announced before `null` is\n * returned.\n *\n * ## 🔴 The paid routes never fail open — added 2026-08-30, and it is a money rule\n *\n * `wallet()`, `leaderboard()` and `health()` are free, so absence (2) costs\n * nothing and a `null` is the kindest answer: without it every consumer writes\n * the same try/catch around a lookup, which is the duplication this package\n * exists to delete.\n *\n * `walletBreakdown()` and `agent()` are NOT free, and there they return no\n * absence value at all — they throw, always, **including with `failOpen: true`\n * set explicitly**. The line is not \"how many methods\", it is *was there money\n * in flight*.\n *\n * ⚠️ **This is a correction of what shipped, left written because it is the\n * whole reason this rule exists.** Until 2026-08-30 these two returned\n * `| null` and ran their failures through `failOpenCovers()`, which is `true`\n * for every `serviceFault`. Measured against a dead port that same day: a\n * timeout on a metered route returned `null`. The paywall settles **before**\n * running the query (`describe-net/describenet/paywall.py:1031-1047`), so that\n * `null` could be handed back with the USDC already moved — and nothing in it\n * distinguished \"I paid and it fell over\" from \"there was nothing to fetch\".\n * That is not degrading gracefully, it is a spent credential with no receipt.\n *\n * A loud failure after paying is recoverable: the caller can retry, log or\n * claim. A silent `null` is not, and no flag the caller sets can buy the right\n * to swallow a receipt — availability is a preference, a settled payment is a\n * fact. What the exception carries instead is `error.payment` (see\n * `errors.ts::PaymentAttempt`) and `failedAfterPaying()` reads it.\n *\n * ## 🔴 The partner rail has a THIRD money rule — added 2026-08-30\n *\n * With `partner` configured (see `PartnerSigner` below and\n * `uvd-describe-sdk/partner`), every request is signed and the metered routes\n * are supposed to be free. Two failures are therefore CALLER-fault and neither\n * one degrades:\n *\n * 1. the signature could not be produced → `DescribePartnerUnsigned`, thrown\n * on every route including the free ones, `failOpen` or not;\n * 2. the signature was produced and the route charged anyway →\n * `DescribePartnerRejected`, thrown BEFORE the payer is ever called.\n *\n * Both are `serviceFault: false`, so `failOpenCovers()` refuses them. The\n * symmetry with the paid-route rule is exact and deliberate: there, money that\n * already moved may not be swallowed; here, money that is ABOUT to move may not\n * be spent by accident. A partner rail that quietly falls back to paying is\n * indistinguishable from a working one until the invoice arrives.\n *\n * ## What this client deliberately does NOT do\n *\n * **No cache.** MeshRelay has one (a `Map`, 12-minute TTL) and needs it: it\n * recomputes channel scores on a route reachable from the internet, so an\n * uncached lookup would let a stranger burn our share of a rate limit that has\n * no per-partner bucket (the live figure is 50 rps sustained / burst 40, and\n * the `RateLimit-Policy` response header is the authority — see the correction\n * in `config.ts`). EM and KarmaKadabra have none. One of three is not a\n * mandate, and a cache in a library is a policy\n * decision about staleness that belongs to the app: MeshRelay's split of\n * `refreshWallets` (async, network) from `getCached` (sync, NEVER network)\n * exists because ITS threat model needed it, and baking a TTL in here would\n * hand every consumer a staleness they did not choose. Documented in the README\n * with MeshRelay's shape as the recipe.\n *\n * ⚠️ **Ratified 2026-08-30 by the only consumer that has a cache.** MeshRelay\n * reviewed this decision in `#agents` and agreed the cache must not move into\n * the library: *\"una librería que decide cuánto tiempo miente por vos es peor\n * que una que no cachea\"*. The paragraph above now has two signatures, not one —\n * which is the difference between a preference and a decision.\n *\n * **No retry.** Same reason, plus a measured one: MeshRelay retries a transient\n * failure at most ONCE, \"hammering a permanent failure is how EM turned one\n * error into a four-hour storm\" (`describenet.js:150-151`). A retry policy\n * inside a library multiplies against whatever the caller already has.\n * `DescribeError.transient` is exported so a caller can build the policy they\n * want on a fact instead of on a string match.\n *\n * ## What it DOES do without being asked, and there is exactly one — added 2026-08-30\n *\n * **It sleeps `[0, 400) ms` before the first request of every call.** That is\n * the one thing in this list that goes the other way, so it carries the burden\n * of proof: the number and the measurement are KarmaKadabra's (27 agents on one\n * EventBridge schedule, against a rate limit shared with no per-partner bucket —\n * *\"sin jitter, un enjambre es un DDoS educado\"*), and the argument for shipping\n * it ON is in `config.ts::DEFAULT_JITTER_MS`. `jitterMs: 0` turns it off.\n *\n * It is NOT the retry policy above wearing a different hat, and `jitter.ts`\n * spells out why: jitter disperses a herd that has not asked for anything yet,\n * backoff yields to a service that has already said no. The first goes before\n * the first request; the second would go before a retry this package does not\n * have.\n *\n * ## The second thing `onFailure` announces — added 2026-08-30\n *\n * A hash field that arrives as something other than a hash is dropped to `null`\n * and announced as `kind: 'malformed_hash'` (KarmaKadabra's *\"el 200 sin tx\"*;\n * see `hashes.ts` and `announceMalformed` below). It does not throw — one bad\n * accessory field must not destroy a decomposition that was paid for — and it\n * does not pass through, which is what bit them.\n */\n\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_JITTER_MS,\n DEFAULT_SITE_URL,\n DEFAULT_TIMEOUT_MS,\n TREASURY_EVM,\n userAgent,\n} from './config';\nimport {\n attachPayment,\n DescribeError,\n DescribeHTTPError,\n DescribeMalformedHash,\n DescribeNotFound,\n DescribePartnerRejected,\n DescribePartnerUnsigned,\n DescribePaymentRefused,\n DescribePaymentRequired,\n DescribeTimeout,\n DescribeUnparseable,\n DescribeUnreachable,\n failOpenCovers,\n type PaymentAttempt,\n type X402Challenge,\n} from './errors';\nimport { looksLikeSettlementReceipt, malformedHashReport } from './hashes';\nimport { jitterDelayMs, sleep } from './jitter';\nimport {\n parseAgentReputation,\n parseHealth,\n parseLeaderboard,\n parseWalletBreakdown,\n parseWalletReputation,\n} from './parse';\nimport type {\n AgentReputation,\n IndexHealth,\n LeaderboardRow,\n PaymentEvidence,\n WalletBreakdown,\n WalletReputation,\n} from './types';\n\n/**\n * How a metered call gets paid.\n *\n * 🔴 This SDK NEVER signs, never touches a private key and never builds an\n * EIP-3009 authorization. That is `uvd-x402-sdk`'s job and reimplementing it\n * here would be the house's cardinal sin (upstream-first: if the payment SDK\n * lacks something, it is added THERE and consumed from here). This interface is\n * the seam, and it is one method wide on purpose — anything wider would start\n * to encode payment knowledge we have no business having.\n *\n * The canonical implementation ships at `uvd-describe-sdk/x402` and wraps the\n * payment SDK's `X402Client`. It lives behind a subpath so this module never\n * imports it: a consumer who only reads free routes installs nothing.\n */\nexport interface X402Payer {\n /**\n * Given the parsed 402 challenge, return the value for the `X-PAYMENT`\n * header. Throwing aborts the call — nothing is replayed.\n */\n pay(challenge: X402Challenge): Promise<string>;\n}\n\n/**\n * How a request proves it comes from a partner of the house.\n *\n * ## The seam, and why it is exactly one method wide\n *\n * Same shape and same reason as {@link X402Payer}: this package holds no key,\n * builds no signature and knows no cryptography. It hands a request over and\n * gets headers back. Anything wider would start encoding signing knowledge that\n * belongs to `uvd-x402-sdk`, and the canonical implementation — which does\n * nothing but call that SDK's ERC-8128 signer — ships at\n * `uvd-describe-sdk/partner`, behind a subpath, so the main entry keeps its zero\n * runtime imports.\n *\n * ## What the other side does with it\n *\n * describe.net has no accounts and no API keys — *\"el pago es la\n * autenticación\"* — so the free rail for our own products could not be a token.\n * It is an allowlist of PUBLIC ADDRESSES plus a per-request ERC-8128 signature\n * (`describe-net/describenet/partner.py`, read 2026-08-30). The service\n * therefore custodies no secret of ours: a breach of describe.net leaks a list\n * of addresses, which are already public. That property is the reason this is a\n * signature and not the `X-API-Key` everybody expects, and it is worth\n * protecting when extending this interface.\n *\n * The gate verifies with a policy pinned to `api.describe.net`, chain 8453 and a\n * 300 s window, and then — the line that makes it a gate — looks the recovered\n * address up in the allowlist (`partner.py:242`). A valid signature from an\n * unlisted wallet pays like everybody else.\n *\n * ## Throwing is the contract\n *\n * `sign()` MUST throw rather than return partial or unsigned headers. The client\n * turns that throw into `DescribePartnerUnsigned` and raises it — it never\n * proceeds unsigned, because an unsigned request from a partner client is an\n * anonymous request, and an anonymous request pays.\n */\nexport interface PartnerSigner {\n /**\n * Sign one request; return the headers to add to it.\n *\n * For describe.net's GET-only surface that is `Signature` and\n * `Signature-Input` (RFC 9421). `Content-Digest` appears only for a request\n * with a body, and this client never sends one.\n */\n sign(request: { method: string; url: string }): Promise<Record<string, string>>;\n /**\n * The signing address, if the implementation cares to publish it. Used ONLY\n * to write a useful error message. It is never sent as a header and never\n * trusted: the server decides from the address it RECOVERS, not one we claim.\n */\n readonly address?: string;\n}\n\n/** What `onFailure` is handed. Enough to log, alert or fall back on. */\nexport interface DescribeFailure {\n /** The route that failed, e.g. `/wallets/0x…/chains`. */\n path: string;\n error: DescribeError;\n /** Shorthand for `error.kind`, so a logger never has to reach in. */\n kind: DescribeError['kind'];\n /** Would retrying help? */\n transient: boolean;\n}\n\nexport interface DescribeClientConfig {\n /** Default `https://api.describe.net`. */\n baseUrl?: string;\n /** Default 30 000 ms. See `config.ts` for why that number and not another. */\n timeoutMs?: number;\n /**\n * Your product's name, appended to the `User-Agent` as `(+name)`.\n *\n * Strongly recommended and free: the rate limit is shared across the\n * ecosystem with no per-partner bucket, and the UA is the only thing that\n * makes your share of it attributable when something gets loud. The ceiling\n * itself is not typed here — the `RateLimit-Policy` response header is the\n * authority (see the correction in `config.ts`).\n */\n product?: string;\n /**\n * Default **true**, and it is what Saul asked for in those words: *\"pon un\n * fallback si es que describe está caído\"* (2026-08-28).\n *\n * `true` — a describe.net-side failure returns `null` and calls `onFailure`.\n * `false` — the same failure throws a typed `DescribeError`.\n *\n * **Scope: the free routes only** — `wallet()`, `leaderboard()`, `health()`.\n * `walletBreakdown()` and `agent()` ignore this flag in both positions and\n * always throw; see the header of this file for why money removes the choice.\n *\n * Either way a 4xx that is the CALLER's fault still throws: `failOpen`\n * protects you from their outage, not from your own bug.\n */\n failOpen?: boolean;\n /**\n * Where a swallowed fact goes. **`onFailure` announces everything this client\n * swallowed, and nothing it handed you.** Two things qualify:\n *\n * 1. a `null` returned instead of an answer (the fail-open, free routes\n * only) — announced BEFORE the `null`, always;\n * 2. a hash field dropped because it was not a hash\n * (`kind: 'malformed_hash'`, metered routes, added 2026-08-30).\n *\n * A failure that reaches you as a throw is never announced here: you are\n * already holding it.\n *\n * ⚠️ **This is a restatement, and the old wording is left because someone will\n * look for it.** It read: *\"fires if and only if a method hands back `null`…\n * the paid routes therefore never call this at all\"*. That was a description\n * of the only case that existed, not of the rule — and the rule it protected\n * is that nothing disappears quietly. A field that vanished out of a 200 is\n * exactly as invisible as a silent fail-open, so it belongs on the same\n * channel. Filter it in one line if you only page on outages:\n * `if (f.kind === 'malformed_hash') return;` — it is `transient: false` and\n * `serviceFault: false`, and the paid routes still never fail open.\n *\n * Leaving this unset with `failOpen: true` is the one configuration this\n * package will not defend: it converts \"describe is down\" into \"this wallet\n * has no reputation\" with nothing written down anywhere. It is allowed\n * because a hard requirement would be a `throw` in the constructor of a\n * read-only client, but the README says it plainly and so does this comment.\n */\n onFailure?: (failure: DescribeFailure) => void;\n /**\n * Sleep a random `[0, jitterMs)` before **every** request, so a fleet waking\n * on one schedule does not arrive as one spike. **Default 400**, and `0` turns\n * it off.\n *\n * ⚠️ *Every* request, the replay of a paid one included: a method that fires\n * two requests sleeps twice. The intuitive rule — once per public call — was\n * written here first and is wrong, because it disperses the first request and\n * lets the rest out in a pack. `jitter()` below carries the correction and the\n * call site in KarmaKadabra's own code that settles it.\n *\n * The number and the reason are KarmaKadabra's, measured on a fleet of 27\n * (2026-08-30) — see `config.ts::DEFAULT_JITTER_MS` for why it ships ON, and\n * `jitter.ts` for why this is not backoff and why it is not a CSPRNG.\n *\n * Set it to `0` in your own unit tests: a suite that sleeps 200 ms per mocked\n * call is paying for a behaviour it is not testing. This package's own suite\n * does exactly that.\n *\n * A value that is not a finite number ≥ 0 falls back to the **default**, not\n * to off: a typo must not silently remove a protection the rest of the\n * ecosystem is relying on. Only a real `0` disables it.\n */\n jitterMs?: number;\n /** Pay metered routes. Without it, a 402 throws `DescribePaymentRequired`. */\n payer?: X402Payer;\n /**\n * Enter through the partner rail: sign every request as a wallet the house\n * has allowlisted, and read the metered routes for free.\n *\n * Build one with `partnerFromEnv()` or `partnerFromSigner()` from\n * `uvd-describe-sdk/partner`. Both are the same rail — one reads a key the\n * environment holds, the other takes a signer you already have.\n *\n * 🔴 EVERY request is signed, free routes included, and that is a decision\n * with a reason: the alternative is a table in this package saying which\n * routes are metered, which would be a second copy of the service's\n * `pricing.TIERS` and would silently start paying the day a free route\n * becomes metered. The server already knows which is which; we do not need\n * to. What it costs, measured on this machine 2026-08-30 (Node v23.11.0, 200\n * signatures with an in-process ethers wallet, after 20 warm-up rounds):\n * **0,67 ms** per signature, against a 30 000 ms request timeout. Four ten-\n * thousandths of the budget for the request it rides on.\n */\n partner?: PartnerSigner;\n /**\n * 🔴 Default **false**, and the default is the point.\n *\n * With partner mode on, a metered route that answers 402 means the free rail\n * did not work. By default that throws `DescribePartnerRejected` and NOTHING\n * IS PAID. Set this to `true` to fall through to the `payer` instead — an\n * explicit decision to spend USDC when the rail is down, which is a\n * reasonable thing to want and an unreasonable thing to get by accident.\n *\n * With no `partner` configured this flag does nothing at all.\n */\n partnerFallsBackToPaying?: boolean;\n /**\n * The only address this client will pay. Defaults to the pinned treasury.\n * Override only if you have verified a rotation out of band — see\n * `config.ts::TREASURY_EVM` for the failure mode of pinning.\n */\n expectedPayTo?: string;\n /** Injectable for tests. Defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}\n\n/** Read reputation from describe.net. */\nexport class DescribeClient {\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly ua: string;\n private readonly failOpen: boolean;\n private readonly onFailure?: (failure: DescribeFailure) => void;\n private readonly jitterMs: number;\n private readonly payer?: X402Payer;\n private readonly partner?: PartnerSigner;\n private readonly partnerFallsBackToPaying: boolean;\n private readonly expectedPayTo: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: DescribeClientConfig = {}) {\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.ua = userAgent(config.product);\n this.failOpen = config.failOpen ?? true;\n this.onFailure = config.onFailure;\n // Garbage falls back to the DEFAULT, never to off, and never throws here: a\n // mistyped option must not silently drop a protection the rest of the\n // ecosystem relies on, and a library that dies in its constructor over one\n // is worse than one that ignores it. Only a real 0 disables the jitter.\n this.jitterMs =\n typeof config.jitterMs === 'number' && Number.isFinite(config.jitterMs) && config.jitterMs >= 0\n ? config.jitterMs\n : DEFAULT_JITTER_MS;\n this.payer = config.payer;\n this.partner = config.partner;\n this.partnerFallsBackToPaying = config.partnerFallsBackToPaying ?? false;\n this.expectedPayTo = config.expectedPayTo ?? TREASURY_EVM;\n const impl = config.fetchImpl ?? globalThis.fetch;\n if (typeof impl !== 'function') {\n throw new TypeError(\n 'No fetch available. Node >= 18 has one; otherwise pass `fetchImpl` in the config.',\n );\n }\n this.fetchImpl = impl;\n }\n\n // -------------------------------------------------------------------------\n // Free — no dependency, no signature, no credential\n // -------------------------------------------------------------------------\n\n /**\n * `GET /wallets/{wallet}/chains` — **free**. The happy path starts here.\n *\n * Gratis-primero is not politeness, it is the shape of the product: the 402\n * challenge of the metered route says it itself — *\"si ahí no hay nada, no\n * hay nada que comprar\"*. Ask for free whether there is anything, and only\n * then buy the decomposition.\n *\n * `wallet` goes through VERBATIM. EVM is normalised server-side, but Solana\n * base58 is case-SENSITIVE and lower-casing it here would silently ask about\n * a different wallet.\n *\n * @returns the reputation (whose `globalScore` may be `null` — that is an\n * answer), or `null` when describe.net could not be reached and `failOpen`\n * is on.\n */\n async wallet(address: string): Promise<WalletReputation | null> {\n const path = `/wallets/${encodeURIComponent(address)}/chains`;\n return this.guard(path, async () => parseWalletReputation(await this.getJson(path)));\n }\n\n /**\n * `GET /leaderboard` — **free**, first page.\n *\n * Takes NO parameters: `?limit=2` answers 422 `leaderboard_takes_no_params`\n * (verified live 2026-08-30). Paging is the metered `/leaderboard/page`.\n *\n * ⚠️ Ordered by `shrunkScore`, not by `finalScore`. Re-sorting client-side by\n * `finalScore` undoes the shrinkage and puts a single 100-point rating above\n * two hundred real ones.\n */\n async leaderboard(): Promise<LeaderboardRow[] | null> {\n const path = '/leaderboard';\n return this.guard(path, async () => parseLeaderboard(await this.getJson(path)));\n }\n\n /**\n * `GET /health` — **free**, and the authority on this index's totals.\n *\n * Also the live source for `readingPolicy` and `confidenceThresholds`: the\n * server publishes its own calibrable values so that no consumer re-types\n * them. Read them here rather than hardcoding a threshold that will drift.\n */\n async health(): Promise<IndexHealth | null> {\n const path = '/health';\n return this.guard(path, async () => parseHealth(await this.getJson(path)));\n }\n\n /**\n * The badge URL. **Builds a string, opens no socket, cannot fail.**\n *\n * `GET /badge/{wallet}.svg` is free and returns `image/svg+xml` (604 bytes,\n * verified 2026-08-30). Drop it in an `<img>` and a page shows a live score\n * with its distinct raters and the date of the data, with no JavaScript and\n * no dependency on this package at all.\n */\n badgeUrl(address: string): string {\n return `${this.baseUrl}/badge/${encodeURIComponent(address)}.svg`;\n }\n\n /** Where a human reads the same wallet. On surfaces without hover, THIS is the attribution. */\n profileUrl(address: string, siteUrl: string = DEFAULT_SITE_URL): string {\n return `${siteUrl.replace(/\\/+$/, '')}/agent.html?wallet=${encodeURIComponent(address)}`;\n }\n\n // -------------------------------------------------------------------------\n // Metered — a 402 is paid through uvd-x402-sdk, never by us\n // -------------------------------------------------------------------------\n\n /**\n * `GET /reputation/wallet/{wallet}` — **metered, $0.01** ($0.05 with a\n * citable snapshot). Who rated, how many times, how concentrated.\n *\n * The price above is documentation with a date on it, not a value this SDK\n * uses: what gets paid is what the live challenge says. We never type a\n * price into a code path.\n *\n * 🔴 **Not nullable, and never fail-open** — not even with `failOpen: true`.\n * There is money in flight here, and a swallowed failure is a spent\n * credential with no receipt. Every failure arrives as a typed throw, and one\n * that happened after the envelope left carries `error.payment`\n * (`failedAfterPaying()`). Note this includes a 404: it is still absence and\n * still costs nothing (it is checked before the challenge is read), but with\n * no `| null` left there is nowhere to degrade it to.\n *\n * Without a `payer`, throws `DescribePaymentRequired` with the challenge\n * attached — asking is free and is the intended first move, so you can read\n * the price without paying.\n */\n async walletBreakdown(address: string): Promise<WalletBreakdown> {\n const path = `/reputation/wallet/${encodeURIComponent(address)}`;\n const { body, payment, servedReceipt } = await this.getPaidJson(path);\n const result = parseWalletBreakdown(body, payment);\n this.announceMalformed(path, result, servedReceipt);\n return result;\n }\n\n /**\n * `GET /reputation/agent/{network}/{agentId}` — **metered, $0.02**. One\n * ERC-8004 identity, down to the individual ratings.\n *\n * 🔴 Same money rule as `walletBreakdown()`: not nullable, never fail-open,\n * throws on everything including a 404 for an agent id that does not exist.\n */\n async agent(network: string, agentId: string | number): Promise<AgentReputation> {\n const path = `/reputation/agent/${encodeURIComponent(network)}/${encodeURIComponent(String(agentId))}`;\n const { body, payment, servedReceipt } = await this.getPaidJson(path);\n const result = parseAgentReputation(body, payment);\n this.announceMalformed(path, result, servedReceipt);\n return result;\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n /**\n * The fail-open gate — **for the free routes, and only for them**.\n *\n * ⚠️ Corrected 2026-08-30. The old comment here read *\"every network method\n * goes through exactly one of these so the rule cannot drift between\n * methods\"*, and the intent was right while the scope was wrong: routing the\n * paid methods through it is what let a post-settlement timeout come back as\n * `null`. The rule that must not drift is R5, and R5 has a term this function\n * cannot see. So the paid methods do not call it — deliberately, and a test\n * named `MOUNTS THE BAD STATE` goes red if anyone puts them back.\n *\n * Whoever adds the sixth method: free ⇒ wrap it here; metered ⇒ do not.\n */\n private async guard<T>(path: string, run: () => Promise<T>): Promise<T | null> {\n try {\n return await run();\n } catch (error) {\n // A 404 is DATA — \"there is nothing here\" — so it never leaves as an\n // exception, `failOpen` or not (R4). It is still announced: a mistyped\n // `baseUrl` 404s every route, and a silent null forever would read as\n // \"nobody in this index has any reputation\".\n if (error instanceof DescribeNotFound) {\n this.onFailure?.({ path, error, kind: error.kind, transient: false });\n return null;\n }\n if (this.failOpen && failOpenCovers(error)) {\n // Announced BEFORE the null. If this ever moves below the return, a\n // failure becomes indistinguishable from an unrated wallet.\n this.onFailure?.({\n path,\n error,\n kind: error.kind,\n transient: error.transient,\n });\n return null;\n }\n throw error;\n }\n }\n\n /**\n * The pause that disperses a fleet. **Before EVERY request** — called from the\n * top of `request()` and from nowhere else, so a method that makes two\n * requests sleeps twice.\n *\n * ⚠️ **Corrected 2026-08-30, and the wrong version is left written because it\n * is the intuitive one and someone will want it back.** This first sat in\n * `getJson()` / `getPaidJson()`, i.e. *once per public call, before the FIRST\n * request*, on the theory that the metered flow should not sleep twice. That\n * is a hole: a call that fires N requests would disperse one of them and let\n * the other N−1 out in a pack, which is the exact problem this contribution\n * came to fix. KarmaKadabra's own call site settles it — their sleep lives\n * inside the function that performs the GET (`reputation_scan.py:123`), and\n * that function runs twice on their real path (`:242` for the EVM address,\n * `:245` for the Solana one). Their jitter is per REQUEST, and the reason they\n * wrote beside it (`:121-122`) is per-PROCESS: agents that wake together\n * against a shared ceiling.\n *\n * The paid replay sleeps too, and that was the hardest half of the correction\n * to accept. The argument for exempting it was that delaying a signed envelope\n * widens the window in which a crash loses a receipt — but the challenge this\n * client answers carries `maxTimeoutSeconds: 120`, so 400 ms is a third of a\n * percent of the envelope's own validity, while the herd argument applies to\n * the replay in full: 27 agents that get their 402 in the same second replay\n * in the same second.\n *\n * **Before the signature, and before the clock.** `request()` calls this\n * first, so an ERC-8128 signature is never left ageing against its 300 s\n * window while we sleep, and the sleep is not charged to `timeoutMs`.\n */\n private async jitter(): Promise<void> {\n const ms = jitterDelayMs(this.jitterMs);\n if (ms > 0) await sleep(ms);\n }\n\n /**\n * Announce a malformed hash field, if there is one — KarmaKadabra's *\"el 200\n * sin tx\"*, reaching the caller.\n *\n * ⚠️ **This is the second thing `onFailure` announces, and invariant 4 is\n * restated rather than broken.** It used to read *\"`onFailure` fires if and\n * only if a method hands back `null`\"*, and that wording was a description of\n * the only case that existed on 2026-08-30 at noon. The rule it was protecting\n * is bigger and now reads: **`onFailure` announces everything that was\n * silently swallowed — a `null` handed back instead of an answer, and a field\n * dropped because it was not what it claimed to be — and nothing that reaches\n * you as a throw.** A failure you are holding does not need announcing; a\n * field that vanished out of a 200 does, and it is exactly as invisible as a\n * silent fail-open.\n *\n * That is why it is not a second callback: the channel a consumer is already\n * watching is where KarmaKadabra asked for this to land, and a new one would\n * be a channel nobody wired. The notice is filterable in one line\n * (`f.kind === 'malformed_hash'`), carries `transient: false` and\n * `serviceFault: false`, and the error it carries is never thrown.\n *\n * 🔴 The callback is wrapped, and this call site is the reason: it fires after\n * a metered read that already SETTLED. An observer that throws would destroy a\n * response the caller paid for, which is the same class of bug as swallowing a\n * receipt — with the sign flipped. (The `guard()` call site is deliberately\n * left unwrapped: there the answer is already `null`, so a throwing observer\n * costs nothing that was bought.)\n */\n private announceMalformed(\n path: string,\n result: Parameters<typeof malformedHashReport>[0],\n servedReceipt: string | null,\n ): void {\n const fields = malformedHashReport(result);\n if (fields.length === 0) return;\n // The receipt is the ONE malformed value `raw` cannot preserve — `raw` is\n // the body and that arrived as a header — so it is quoted here or it is\n // lost. Truncated because a field that is not a hash can be anything: the\n // longest `tag1` in this index is 471 characters of prose.\n const quoted =\n fields.includes('payment.receipt') && servedReceipt !== null\n ? ` The receipt as served was ${JSON.stringify(servedReceipt.slice(0, 120))}.`\n : '';\n const error = new DescribeMalformedHash(\n `GET ${path} served ${fields.length} field(s) that are not hashes: ${fields.join(', ')}. ` +\n 'Each one was dropped to null; every other value as served is still in `raw`. ' +\n `Nothing was retried and nothing else in the answer was touched.${quoted}`,\n fields,\n );\n try {\n this.onFailure?.({ path, error, kind: error.kind, transient: false });\n } catch {\n // An observer that throws must not destroy a response that was paid for.\n }\n }\n\n /**\n * The partner headers for one request, or `{}` when there is no partner.\n *\n * 🔴 THIS RUNS OUTSIDE `request()`'s try/catch AND THAT IS THE WHOLE POINT.\n * Inside it, a signer that threw would be caught by the transport handler and\n * re-thrown as `DescribeUnreachable` — which is `serviceFault: true`, which\n * `failOpen` swallows, which turns \"my partner key is missing\" into a `null`\n * that reads as \"this wallet has no reputation\". The most expensive bug in\n * this file, one indentation level away.\n */\n private async partnerHeaders(path: string): Promise<Record<string, string>> {\n if (!this.partner) return {};\n try {\n return await this.partner.sign({ method: 'GET', url: `${this.baseUrl}${path}` });\n } catch (error) {\n throw new DescribePartnerUnsigned(path, this.partner.address, error);\n }\n }\n\n private async request(path: string, headers: Record<string, string> = {}): Promise<Response> {\n // Every request, not every call: see `jitter()` for the correction and for\n // the KarmaKadabra call site that settles it. It runs before the signature\n // (which would otherwise age against its 300 s window) and before the timer\n // (so the sleep is not charged to `timeoutMs`).\n await this.jitter();\n\n // Signed BEFORE the timer starts and before the try: see `partnerHeaders`.\n const signed = await this.partnerHeaders(path);\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: 'GET', // never HEAD: every route but /openapi.json answers 405 to it\n headers: { Accept: 'application/json', 'User-Agent': this.ua, ...signed, ...headers },\n signal: controller.signal,\n });\n } catch (error) {\n // An AbortError here is ours (the timer), not the caller's: this\n // controller is created in this function and handed to nobody.\n const name = (error as { name?: string } | null)?.name;\n if (name === 'AbortError' || name === 'TimeoutError') {\n throw new DescribeTimeout(`GET ${path} timed out after ${this.timeoutMs} ms`, error);\n }\n throw new DescribeUnreachable(`GET ${path} unreachable: ${String(error)}`, error);\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async readJson(response: Response, path: string): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new DescribeUnparseable(`GET ${path} body is not JSON`, error);\n }\n }\n\n /** A free route: any non-2xx is a typed HTTP error. */\n private async getJson(path: string): Promise<unknown> {\n const response = await this.request(path);\n if (response.status === 404) {\n throw new DescribeNotFound(`GET ${path} -> HTTP 404`);\n }\n if (!response.ok) {\n throw new DescribeHTTPError(response.status, `GET ${path} -> HTTP ${response.status}`);\n }\n return this.readJson(response, path);\n }\n\n /**\n * A metered route: ask free, read the challenge, verify WHO we are about to\n * pay, pay through the injected payer, replay the identical request.\n *\n * The order matters and the third step is the one people skip. The published\n * guide says it in the imperative — *\"verify who you are about to pay — do\n * this every time\"* — because the challenge arrives over the same network\n * that could be lying to you, and it names its own recipient.\n *\n * There is one line in this function that changes what a failure MEANS, and\n * it is marked: everything above `payer.pay()` returning is a failure that\n * cost nothing, everything below it may have cost real USDC. Failures below\n * it are stamped with a `PaymentAttempt` so the caller does not have to infer\n * which side of that line they landed on. Nothing above it is stamped, and\n * that asymmetry IS the signal — see `errors.ts::PaymentAttempt`.\n */\n private async getPaidJson(\n path: string,\n ): Promise<{ body: unknown; payment: PaymentEvidence | null; servedReceipt: string | null }> {\n const first = await this.request(path);\n\n if (first.ok) {\n // Free-tier or already-settled. No charge, so no evidence to report.\n return { body: await this.readJson(first, path), payment: null, servedReceipt: null };\n }\n\n if (first.status === 404) {\n // Absence, and free: nothing was paid to learn it. The metered route is\n // the one where a 404 is most likely (an agent id that does not exist),\n // and charging for it would be charging for \"there is nothing here\".\n throw new DescribeNotFound(`GET ${path} -> HTTP 404`);\n }\n\n if (first.status !== 402) {\n throw new DescribeHTTPError(first.status, `GET ${path} -> HTTP ${first.status}`);\n }\n\n const challenge = await this.readChallenge(first, path);\n\n // ── THE PARTNER RAIL FAILED, AND FAILING LOUDLY IS THE FEATURE ──────────\n // We signed this request (every request is signed in partner mode) and the\n // route charged anyway, so the gate did not exempt us. Falling through to\n // `payer.pay()` from here is the silent downgrade this whole rail exists to\n // prevent: identical answers, identical latency, USDC leaving a wallet that\n // budgeted none. Checked BEFORE the missing-payer branch because \"your free\n // rail is down\" is the more useful of the two messages when both are true.\n if (this.partner && !this.partnerFallsBackToPaying) {\n throw new DescribePartnerRejected(path, this.partner.address, challenge);\n }\n\n if (!this.payer) {\n throw new DescribePaymentRequired(\n `GET ${path} is metered (${challenge.amount ?? '?'} ${challenge.token ?? 'USDC'}) ` +\n 'and no `payer` is configured. Read `error.challenge` for the terms, or use the ' +\n 'free route: GET /wallets/{wallet}/chains.',\n challenge,\n );\n }\n\n this.assertPayableTo(challenge);\n\n // Nothing above this line has spent anything: the payer may still refuse,\n // and a signature that never leaves the payer moves no money — the seller\n // is what settles it. A throw from `pay()` is the caller's own payer\n // talking, so it is not annotated and not translated.\n const header = await this.payer.pay(challenge);\n\n // ─────────── BELOW THIS LINE A SIGNED ENVELOPE IS IN FLIGHT ───────────\n const terms = {\n amount: typeof challenge.amount === 'string' ? challenge.amount : undefined,\n token: typeof challenge.token === 'string' ? challenge.token : undefined,\n payTo: typeof challenge.recipient === 'string' ? challenge.recipient : undefined,\n };\n\n let second: Response;\n try {\n second = await this.request(path, { 'X-PAYMENT': header });\n } catch (error) {\n // No answer at all — timeout or dead socket. `fetch` rejects identically\n // whether the request bytes were written or not, so this is exactly the\n // case that CANNOT be narrowed: `unknown`, said out loud.\n throw attachPayment(error, { settlement: 'unknown', receipt: null, reused: null, ...terms });\n }\n\n const receipt = second.headers.get('X-Payment-Receipt');\n const reused = second.headers.get('X-Payment-Reused');\n const attempt: PaymentAttempt = {\n // A receipt is the settlement transaction hash, put there by the seller:\n // proof, not inference. Its absence proves nothing — an unhandled 500 is\n // rendered above the paywall middleware and never gets the header.\n //\n // ⚠️ Since 2026-08-30 the header must also LOOK like a settlement id (a\n // hash, or the `pending` the OpenAPI declares) before it may be called\n // proof. `'settled'` means *we hold the hash*, and a string that is not\n // one is not one. The value is still carried in `receipt` — on this path\n // it is forensic evidence, not a typed field — and `'unknown'` is the\n // honest verdict: ask the chain.\n settlement: receipt !== null && looksLikeSettlementReceipt(receipt) ? 'settled' : 'unknown',\n receipt,\n reused: reused === null ? null : reused.toLowerCase() === 'true',\n status: second.status,\n ...terms,\n };\n\n if (!second.ok) {\n // 🔴 Money may already be gone here: the authorization was signed and the\n // paywall settles BEFORE running the query. The status is preserved so a\n // caller can tell \"they refused the payment\" (4xx) from \"we paid and\n // their query blew up\" (5xx) — different conversations to have with them.\n throw attachPayment(\n new DescribeHTTPError(\n second.status,\n `GET ${path} -> HTTP ${second.status} AFTER paying (settlement: ${attempt.settlement}` +\n `${receipt ? `, receipt ${receipt}` : ''}). Read \\`error.payment\\` before retrying: ` +\n 'the same receipt unlocks only this byte-identical resource.',\n ),\n attempt,\n );\n }\n\n let body: unknown;\n try {\n body = await this.readJson(second, path);\n } catch (error) {\n // The worst of the set and the easiest to forget: a 200 whose body is\n // garbage. It settled — the receipt is right there — and the caller got\n // nothing for it. Swallowing THIS was the old behaviour.\n throw attachPayment(error, attempt);\n }\n\n // The receipt is a hash too, and it is the one hash the caller is most\n // likely to carry somewhere — to an explorer, to a support ticket, to a\n // reconciliation. So it gets the same shape check as every other hash field\n // (KarmaKadabra, 2026-08-30), with its own predicate: `pending` is a value\n // the seller's OpenAPI declares legitimate, and calling it garbage would\n // fire an alarm on the happy path of every freshly settled payment.\n //\n // 🔴 Only the SUCCESS path nulls a malformed receipt. On the failure path\n // (`attempt`, above) the served string is kept verbatim, because there it is\n // forensic evidence rather than a typed field — what changes there is that\n // `settlement` may not claim `'settled'` on the strength of a string that is\n // not a hash. `'settled'` means *we hold the hash*, and we do not.\n const receiptOk = receipt !== null && looksLikeSettlementReceipt(receipt);\n return {\n body,\n payment: {\n receipt: receiptOk ? receipt : null,\n reused: (reused ?? '').toLowerCase() === 'true',\n malformedHashes: receipt !== null && !receiptOk ? ['receipt'] : [],\n },\n servedReceipt: receipt,\n };\n }\n\n /**\n * Read the 402 challenge from wherever it is.\n *\n * The header FIRST, then the body — and that order is measured, not\n * defensive: of 40 live x402 resources probed on 2026-08-20, 36 of 36 that\n * answered 402 carried the challenge in the header and none in the body\n * (`uvd-x402-sdk-typescript/src/utils/x402.ts`). describe.net serves BOTH\n * (verified 2026-08-30: `Payment-Required` base64 header AND a JSON body), so\n * either path works here — the order is for the ecosystem, not for us.\n */\n private async readChallenge(response: Response, path: string): Promise<X402Challenge> {\n const raw = response.headers.get('Payment-Required') ?? response.headers.get('X-Payment-Required');\n if (raw) {\n const trimmed = raw.trim();\n for (const decode of [() => atob(trimmed), () => trimmed]) {\n try {\n const parsed = JSON.parse(decode());\n if (parsed && typeof parsed === 'object') return parsed as X402Challenge;\n } catch {\n // not this encoding; try the next\n }\n }\n }\n const body = await this.readJson(response, path);\n if (body && typeof body === 'object') return body as X402Challenge;\n throw new DescribeUnparseable(`GET ${path} answered 402 with no readable challenge`);\n }\n\n /**\n * `DO_NOT_PAY` unless every recipient in the challenge is the pinned\n * treasury.\n *\n * Checks the top-level `recipient` AND every `accepts[].payTo`, because a\n * challenge that names the right treasury up top and a stranger in one of six\n * `accepts` entries is exactly the shape an attack would take: the caller's\n * chain selection decides which one gets paid. Case-insensitive, since EVM\n * addresses travel in mixed checksum case (the live challenge serves\n * `0xe4dc963c56979E0260fc146b87eE24F18220e545` while the path parameter is\n * lowercase).\n */\n private assertPayableTo(challenge: X402Challenge): void {\n const expected = this.expectedPayTo.toLowerCase();\n const offered: Array<string | undefined> = [\n typeof challenge.recipient === 'string' ? challenge.recipient : undefined,\n ...Object.values(challenge.recipients ?? {}),\n ...(challenge.accepts ?? []).map((a) =>\n typeof a?.payTo === 'string' ? (a.payTo as string) : undefined,\n ),\n ];\n\n const seen = offered.filter((a): a is string => typeof a === 'string' && a.length > 0);\n if (seen.length === 0) {\n throw new DescribePaymentRefused(this.expectedPayTo, undefined, challenge);\n }\n for (const address of seen) {\n if (address.toLowerCase() !== expected) {\n throw new DescribePaymentRefused(this.expectedPayTo, address, challenge);\n }\n }\n }\n}\n","/**\n * How a score is written down. One rule, ecosystem-wide.\n *\n * **Two decimals, trailing zeros trimmed.** `86.65`, `84.7`, `87` — never `82.0`.\n *\n * Fixed on 2026-08-29 after the three consumers each rendered the SAME number\n * differently (`86.653045`, `86.7`, `86` — one field, three strings), and\n * decided by measurement rather than taste: over 47 real distinct scores,\n * rounding to 0 decimals merges 23 pairs of *different* agents into identical\n * strings, 1 decimal merges 4, and 2 decimals merges 1. Trimming matters as\n * much as the count — two surfaces both \"agreeing on 1 decimal\" still printed\n * `82.0` and `82` for the same agent.\n *\n * The canonical one-liner, byte-identical across the two languages\n * (`docs.describe.net`, §\"Displaying a score\"):\n *\n * ```js\n * String(parseFloat(x.toFixed(2))) // JavaScript\n * ```\n * ```python\n * f\"{round(x, 2):g}\" # Python\n * ```\n *\n * **Live witness case**: the agent scored `83.0` renders as `83` on all three\n * surfaces — where `toFixed(2)` alone prints `83.00` and `toFixed(1)` prints\n * `83.0`. It is the one value that tells the three candidate rules apart, which\n * is why `format.test.ts` tests it first.\n *\n * This is a DISPLAY convention. The API keeps serving the full-precision number\n * (six decimals) and what you compute with is the number, never the string —\n * which is why the two functions below are separate and why `formatScore`\n * returns a `string`. A helper that rounded the number in place would push a\n * lossy value back into arithmetic, and averaging rounded members is how an\n * aggregate ends up disagreeing with the members it aggregates.\n */\n\n/**\n * The canonical display string, or `null` when there is nothing to display.\n *\n * `null` in, `null` out — never `\"0\"`, never `\"—\"`. Choosing the placeholder\n * for absence is the surface's job and it is a different decision per surface;\n * inventing one here would put this package's taste into every consumer, and\n * `\"0\"` in particular would publish \"worst possible reputation\" for \"nobody has\n * rated this yet\" (invariante 7 of the index, and R1 of this SDK).\n *\n * A non-finite input (a `NaN` from a malformed payload) is also `null`: a\n * number we cannot name is not a number we may put describe.net's name on.\n */\nexport function formatScore(value: number | null | undefined): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n return String(parseFloat(value.toFixed(2)));\n}\n\n/**\n * The same rounding, kept as a `number`.\n *\n * For the one case where a number is what you need: MeshRelay rounds at the\n * boundary where the value ENTERS the system rather than at each surface,\n * because \"the bug this closes is one number rendering differently in two\n * places\" (`describenet.js:204-208`). If you do that, use this — and be aware\n * you have made the value lossy on purpose. Everything else should carry the\n * full-precision number and call `formatScore` at the pixel.\n */\nexport function roundScore(value: number | null | undefined): number | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n return parseFloat(value.toFixed(2));\n}\n","/**\n * How many distinct counterparties are behind a wallet's reputation — and the\n * two ways of reconstructing that number that are both WRONG.\n *\n * Contributed by **MeshRelay**, `#agents` on MeshRelay, **2026-08-30**. The\n * seven lines of the helper are not the contribution; the two measurements are,\n * and they are the reason this file has a docstring longer than its code.\n */\n\n/**\n * The distinct-rater count of a wallet, or `null` when there is none to give.\n *\n * ## 🔴 Read this before you use the number\n *\n * `distinct_raters` at the top level of `GET /wallets/{wallet}/chains` is\n * `COUNT(DISTINCT client)` across every chain AND every identity: one rater who\n * reviewed on two chains counts **once**. There is no way to rebuild that from\n * the per-chain rows, and MeshRelay measured both attempts on 2026-08-30:\n *\n * * **Summing the chains DOUBLE-COUNTS** whoever rated on more than one of\n * them. Measured case: the karma-hello wallet reads **9** distinct raters\n * globally while its per-chain figures add up to **11**.\n * * **Taking the maximum UNDERESTIMATES.** Measured case: 3 raters on base and\n * 4 *different* ones on avalanche is **7** real counterparties, and the\n * maximum answers **4**.\n *\n * So the per-chain maximum is a **LOWER BOUND — never the answer**, and summing\n * is not a second-best either: it is wrong in the opposite direction. That pair\n * of sentences is the contribution; without them this helper reads like a\n * one-liner and gets used as the truth.\n *\n * **One live vector proves all three branches at once.** Verified against\n * `api.describe.net` on 2026-08-30 (free route), wallet\n * `0xcc28…4821`: global `distinct_raters` **129**, per chain base **113** and\n * ethereum **21**. The maximum answers 113 (**16 short**), the sum answers 134\n * (**5 over**), and only the global figure is right. It is the fixture this\n * file's test pins, because a vector where two wrong answers land on opposite\n * sides of the true one cannot be passed by accident.\n *\n * ## 🔴 The fallback is a COMPATIBILITY path, not a normal one\n *\n * ⚠️ Corrected while writing this, and the correction matters more than the\n * line it replaces: an earlier draft called the per-chain maximum a \"fallback\n * for when the global figure is not there\", which invites a reader to treat the\n * global field as optional. It is not. describe.net has served wallet-level\n * `distinct_raters` since `b753c9c` — *\"el dato ya estaba y no lo leíamos\"*,\n * committed **2026-08-28**, which MeshRelay's own note dates 08-29 (the day they\n * read it; both are written here because a reader will find the other one and\n * think one of us is wrong) — and their comment says the maximum is kept *\"only\n * as a fallback for a cached response predating that deploy\"*\n * (`meshrelay/meshrelayserv/describenet.js:228-230`,\n * read 2026-08-30). Confirmed live the same day: the free route serves\n * `distinct_raters` at the top level on every wallet.\n *\n * So in a client written after that date the fallback branch is unreachable\n * unless you cache responses and outlive one of their deploys — which MeshRelay\n * does, and is why the branch exists at all. It is kept for them and for anyone\n * replaying a stored payload, not because the field might be missing today.\n *\n * ## What this function therefore does\n *\n * Prefers the global count whenever the object carries one; falls back to the\n * per-chain maximum only when it does not. What comes back is exact in the first\n * case and a lower bound in the second, and there is no third answer it could\n * give. **It never sums, and neither should you.**\n *\n * ## 🔴 Why this is not called `maxDistinctRaters`\n *\n * Because MeshRelay, who wrote it under that name, asked for the rename when\n * they handed it over (2026-08-30): *\"ese nombre invita a creer que el máximo es\n * la respuesta correcta, cuando es el último recurso. El mío está mal nombrado y\n * lo arrastro de cuando el nivel wallet no existía.\"*\n *\n * That is worth keeping written down, because the old name is what a reader will\n * search for and because it is the failure this whole file guards against\n * arriving through the API surface: a function named after its fallback\n * advertises the fallback, and the fallback is the wrong answer. Their name\n * survives here, in the provenance, which is where it belongs.\n *\n * ## Two `null`s that are not zero\n *\n * * A wallet with no eligible rating anywhere serves `distinct_raters: null`\n * with `chains: []` — verified live 2026-08-30 against `0xdEaD…BEEF`. The\n * answer is `null`, **never `0`**: \"nobody has rated this\" and \"zero people\n * rated this after we counted\" are the same sentence, but `0` is a number a\n * caller will divide by, average, or render as a bar of length zero next to\n * wallets whose bar means something. `Math.max(...[])` is `-Infinity`, which\n * is the concrete bug this branch exists to not have.\n * * A `null` INPUT (the fail-open value of `wallet()`, i.e. \"we could not ask\n * describe.net\") also gives `null`. Accepting it is deliberate: it lets a\n * caller write `resolveDistinctRaters(await describe.wallet(w))` without a\n * null-check that would only exist to satisfy the compiler, and it keeps the\n * three absences of this package from collapsing — an unreachable index and\n * an unrated wallet both mean \"no number\", and neither means zero.\n *\n * Structurally typed rather than tied to `WalletReputation` so it also works on\n * a payload you parsed yourself or pulled out of your own cache.\n */\nexport function resolveDistinctRaters(\n wallet:\n | {\n distinctRaters: number | null;\n chains: readonly { distinctRaters: number }[];\n }\n | null\n | undefined,\n): number | null {\n if (!wallet) return null;\n if (wallet.distinctRaters !== null && wallet.distinctRaters !== undefined) {\n return wallet.distinctRaters;\n }\n let best: number | null = null;\n for (const chain of wallet.chains ?? []) {\n const n = chain?.distinctRaters;\n if (typeof n === 'number' && Number.isFinite(n) && (best === null || n > best)) best = n;\n }\n return best;\n}\n"]}
|