agent402-model-provider 0.0.0-stage → 0.7.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/index.js ADDED
@@ -0,0 +1,209 @@
1
+ // OpenClaw plugin entry (listed in package.json "openclaw.extensions").
2
+ // register() is what OpenClaw's loader calls - several times per gateway start
3
+ // (discovery, activation, per session), so registration is idempotent and the
4
+ // proxy is started once as a plugin service.
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { buildProvider, setActiveProxy, setCachedRoutes, DEFAULT_PORT, PLUGIN_ID } from "./provider.js";
9
+ import { startProxy, loadRoutes, DEFAULT_UPSTREAM } from "./proxy.js";
10
+ import { stripTrailingSlashes } from "./models.js";
11
+ import { acceptUsd, acceptAmount, guardSignedAmount, acceptValidityTooLong, MAX_VALIDITY_SECONDS } from "./known-assets.js";
12
+ export { acceptUsd, acceptAmount, signedPaymentProblem, signedValidityProblem, KNOWN_ASSETS, MAX_VALIDITY_SECONDS } from "./known-assets.js";
13
+
14
+ export const STATE_DIR = () => join(process.env.AGENT402_OPENCLAW_HOME || join(homedir(), ".openclaw"), "agent402");
15
+ export const CREDITS_KEY_FILE = () => join(STATE_DIR(), "credits.key");
16
+ export const WALLET_KEY_FILE = () => join(STATE_DIR(), "wallet.key");
17
+
18
+ /** Wallet key precedence: plugin config > env > ~/.openclaw/agent402/wallet.key
19
+ * (the wallet `setup` generates when no payment method exists yet). Only a
20
+ * well-formed 0x + 64 hex key counts; anything else is "no wallet". */
21
+ export function resolveWalletKey(pluginConfig = {}) {
22
+ const cands = [
23
+ typeof pluginConfig.walletKey === "string" ? pluginConfig.walletKey.trim() : "",
24
+ (process.env.AGENT402_WALLET_KEY || "").trim(),
25
+ ];
26
+ try { if (existsSync(WALLET_KEY_FILE())) cands.push(readFileSync(WALLET_KEY_FILE(), "utf8").trim()); } catch { /* unreadable */ }
27
+ return cands.find((k) => /^0x[0-9a-fA-F]{64}$/.test(k)) || null;
28
+ }
29
+
30
+ /** Credits key precedence: plugin config > env > ~/.openclaw/agent402/credits.key. */
31
+ export function resolveCreditsKey(pluginConfig = {}) {
32
+ const fromCfg = typeof pluginConfig.creditsKey === "string" ? pluginConfig.creditsKey.trim() : "";
33
+ if (fromCfg) return fromCfg;
34
+ const fromEnv = (process.env.AGENT402_CREDITS_KEY || "").trim();
35
+ if (fromEnv) return fromEnv;
36
+ try { if (existsSync(CREDITS_KEY_FILE())) return readFileSync(CREDITS_KEY_FILE(), "utf8").trim(); } catch { /* unreadable */ }
37
+ return null;
38
+ }
39
+
40
+ // x402 wallet payment - optional (peer deps) and, when the wallet has a
41
+ // Permit2 allowance, METERED: the `upto` scheme authorizes a CEILING (the
42
+ // per-request quote) and the gateway settles actual usage plus a markup, the way a
43
+ // per-token router bills. Without the allowance it pays `exact` (the quote).
44
+ export const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
45
+ export const BASE_CAIP2 = "eip155:8453";
46
+ export const DEFAULT_BASE_RPC = "https://mainnet.base.org";
47
+ // Permit2 approvals are max-uint by convention; anything this large is "approved".
48
+ export const PERMIT2_READY_MIN = 10n ** 12n; // 1,000,000 USDC (6 decimals): a real approval, not dust
49
+
50
+ /** Which 402 accept to pay: upto on Base when the client can (settle-actual),
51
+ * else exact on Base, else the first the client supports. Pure. */
52
+ /** Per-call ceiling in USD, enforced in the accept selector so an over-cap quote
53
+ * is refused BEFORE anything is signed. @x402/core 2.23+ ships a $1
54
+ * pegged-assets default on every client; this package turns that off (it would
55
+ * refuse USDG and gave an opaque vendor error on any metered turn over $1) and
56
+ * carries its own ceiling under its own name. The default is $5, which covers
57
+ * every fixed price in the Agent402 catalog and the gateway's metered quote
58
+ * cap, so no call the gateway would serve is refused here while a runaway
59
+ * quote still stops before the wallet signs. `maxPerCallUsd`
60
+ * in the plugin config or AGENT402_MAX_PER_CALL_USD sets another; `0` or
61
+ * `off` turns it off. A value that does not read as a USD amount (text, a
62
+ * negative number, an empty string) keeps the default, and
63
+ * maxPerCallProblem names the setting so the proxy says so on stderr: a typo
64
+ * never removes the ceiling. allowUncappedPayments is still read (it once had
65
+ * to stand beside `off`) and changes nothing. */
66
+ export const DEFAULT_MAX_PER_CALL_USD = 5;
67
+ export function uncappedAcknowledged(pluginConfig = {}) {
68
+ if (pluginConfig.allowUncappedPayments != null) return pluginConfig.allowUncappedPayments === true || String(pluginConfig.allowUncappedPayments).trim().toLowerCase() === "true";
69
+ return String(process.env.AGENT402_ALLOW_UNCAPPED_PAYMENTS ?? "").trim().toLowerCase() === "true";
70
+ }
71
+ /** Kept for callers of earlier releases: `off` needs no acknowledgment now. */
72
+ export const uncappedRefused = () => false;
73
+ /** The configured per-call value and where it came from, or null when unset. */
74
+ function capSetting(pluginConfig = {}) {
75
+ if (pluginConfig.maxPerCallUsd != null) return { name: "maxPerCallUsd", raw: pluginConfig.maxPerCallUsd };
76
+ if (Object.prototype.hasOwnProperty.call(process.env, "AGENT402_MAX_PER_CALL_USD")) return { name: "AGENT402_MAX_PER_CALL_USD", raw: process.env.AGENT402_MAX_PER_CALL_USD };
77
+ return null;
78
+ }
79
+ /** Infinity for 0 / off, the amount for a USD number, null when it does not parse. */
80
+ function readCap(raw) {
81
+ const v = String(raw).trim().toLowerCase();
82
+ if (v === "off") return Infinity;
83
+ const n = v === "" ? NaN : Number(v);
84
+ if (!Number.isFinite(n) || n < 0) return null;
85
+ return n === 0 ? Infinity : n;
86
+ }
87
+ export function maxPerCallUsd(pluginConfig = {}) {
88
+ const set = capSetting(pluginConfig);
89
+ if (!set) return DEFAULT_MAX_PER_CALL_USD;
90
+ return readCap(set.raw) ?? DEFAULT_MAX_PER_CALL_USD;
91
+ }
92
+ /** A one-line warning when the configured ceiling does not parse (the default
93
+ * then applies), else null. The value is quoted only when short. */
94
+ export function maxPerCallProblem(pluginConfig = {}) {
95
+ const set = capSetting(pluginConfig);
96
+ if (!set || readCap(set.raw) != null) return null;
97
+ const shown = String(set.raw).length <= 16 ? JSON.stringify(String(set.raw)) : "(a long value, not shown)";
98
+ return `[agent402-model-provider] ${set.name}=${shown} is not a USD amount, 0 or "off"; keeping the default $${DEFAULT_MAX_PER_CALL_USD} per-call ceiling`;
99
+ }
100
+ // The dollar value of an accept's quote is acceptUsd (./known-assets.js):
101
+ // the field the challenge's version signs (`amount` in v2, `maxAmountRequired`
102
+ // in v1) in base units over the KNOWN decimals of its asset, never a decimals
103
+ // value the seller sends, since the signer signs the raw amount. An accept in
104
+ // an asset outside the table, with no whole-number amount, or with both fields
105
+ // at different values, reads as null, and null is REFUSED under a finite
106
+ // ceiling: a quote we cannot price is not one we sign. After the payload is
107
+ // built, guardSignedAmount checks the amount actually signed against the same
108
+ // figure and the ceiling before anything is sent. An accept that asks to stay
109
+ // valid past MAX_VALIDITY_SECONDS (a day) is never a candidate, ceiling or no
110
+ // ceiling: the signed authorization would be a bearer claim for that long.
111
+ export function selectAccept(accepts, { preferUpto = true, maxUsd = Infinity, x402Version = undefined } = {}) {
112
+ const offered = Array.isArray(accepts) ? accepts : [];
113
+ const list = offered.filter((a) => !acceptValidityTooLong(a));
114
+ if (offered.length && !list.length) throw new Error(`agent402-model-provider: every payment option asks to stay valid for more than ${MAX_VALIDITY_SECONDS} seconds; nothing was signed`);
115
+ const pick = (preferUpto && list.find((a) => a?.scheme === "upto" && a?.network === BASE_CAIP2))
116
+ || list.find((a) => a?.scheme === "exact" && a?.network === BASE_CAIP2) || list[0];
117
+ // An accept with no amount its version signs cannot be paid at all (this is
118
+ // a malformed offer, not a ceiling), so it is refused before the signer runs.
119
+ if (pick && x402Version != null && acceptAmount(pick, x402Version) == null) {
120
+ throw new Error("agent402-model-provider: the payment option names no amount its x402 version signs; nothing was signed");
121
+ }
122
+ if (pick && Number.isFinite(maxUsd)) {
123
+ const usd = acceptUsd(pick, x402Version);
124
+ if (usd == null || usd > maxUsd) {
125
+ throw new Error(`agent402-model-provider: quote ${usd == null ? "unreadable" : `$${usd}`} exceeds the per-call ceiling $${maxUsd}; nothing was signed (raise maxPerCallUsd / AGENT402_MAX_PER_CALL_USD, or set it to 0 or \"off\", to allow it)`);
126
+ }
127
+ }
128
+ return pick;
129
+ }
130
+ export const uptoReady = (allowance) => { try { return BigInt(allowance ?? 0) >= PERMIT2_READY_MIN; } catch { return false; } };
131
+
132
+ export async function resolvePayFetch(pluginConfig = {}, log = () => {}) {
133
+ const pk = resolveWalletKey(pluginConfig);
134
+ if (!pk) return null;
135
+ const capProblem = maxPerCallProblem(pluginConfig);
136
+ if (capProblem) console.error(capProblem);
137
+ const maxUsd = maxPerCallUsd(pluginConfig);
138
+ try {
139
+ const [{ wrapFetchWithPayment, x402Client }, { privateKeyToAccount }, { toClientEvmSigner }, { registerExactEvmScheme }] = await Promise.all([
140
+ import("@x402/fetch"), import("viem/accounts"), import("@x402/evm"), import("@x402/evm/exact/client"),
141
+ ]);
142
+ const account = privateKeyToAccount(pk);
143
+ const signer = toClientEvmSigner(account);
144
+ // Upto needs a Permit2 allowance on USDC (one approval transaction, ever).
145
+ let upto = false;
146
+ try {
147
+ const [{ UptoEvmScheme, getPermit2AllowanceReadParams }, { createPublicClient, http }, { base }] = await Promise.all([import("@x402/evm/upto/client"), import("viem"), import("viem/chains")]);
148
+ const pub = createPublicClient({ chain: base, transport: http((pluginConfig.baseRpc || process.env.AGENT402_BASE_RPC || DEFAULT_BASE_RPC).trim()) });
149
+ const allowance = await pub.readContract(getPermit2AllowanceReadParams({ tokenAddress: USDC_BASE, ownerAddress: account.address }));
150
+ upto = uptoReady(allowance);
151
+ const client = new x402Client((v, accepts) => selectAccept(accepts, { preferUpto: upto, maxUsd, x402Version: v }));
152
+ client.setSpendControls?.(false); // the vendor default ($1, its own default assets only) would refuse USDG and any quote over $1; selectAccept holds the accept that is signed to our own maxPerCallUsd instead
153
+ guardSignedAmount(client, { allowance: () => maxUsd });
154
+ registerExactEvmScheme(client, { signer });
155
+ if (upto) client.register(BASE_CAIP2, new UptoEvmScheme(signer));
156
+ log(upto
157
+ ? `[agent402-model-provider] x402 wallet ${account.address}: paying actual usage (upto, Permit2 allowance present) on Base; exact elsewhere`
158
+ : `[agent402-model-provider] x402 wallet ${account.address}: paying the per-request quote (exact). To pay actual usage instead, run \`agent402-model-provider permit2-approve\` once (one USDC approval transaction on Base; needs a little ETH for gas)`);
159
+ return wrapFetchWithPayment(fetch, client);
160
+ } catch (e) {
161
+ // The allowance read or the upto scheme failed: exact still works.
162
+ log(`[agent402-model-provider] upto unavailable (${String(e?.message || e).slice(0, 120)}) - paying exact`);
163
+ const client = new x402Client((v, accepts) => selectAccept(accepts, { preferUpto: false, maxUsd, x402Version: v }));
164
+ client.setSpendControls?.(false); // the vendor default ($1, its own default assets only) would refuse USDG and any quote over $1; selectAccept holds the accept that is signed to our own maxPerCallUsd instead
165
+ guardSignedAmount(client, { allowance: () => maxUsd });
166
+ registerExactEvmScheme(client, { signer });
167
+ return wrapFetchWithPayment(fetch, client);
168
+ }
169
+ } catch (e) {
170
+ log(`[agent402-model-provider] x402 wallet payment unavailable (${e?.message || e}); install @x402/fetch @x402/evm viem, or use a credits key`);
171
+ return null;
172
+ }
173
+ }
174
+
175
+ let started = null;
176
+ let registeredOnce = false;
177
+
178
+ const plugin = {
179
+ id: PLUGIN_ID,
180
+ name: "Agent402",
181
+ description: "Agent402 model provider: routed + explicit models at a flat per-call price, paid in USDC from a wallet, or with a credits key already issued.",
182
+ register(api) {
183
+ const cfg = api.pluginConfig || {};
184
+ const port = Number(cfg.port) || DEFAULT_PORT;
185
+ const upstream = stripTrailingSlashes(cfg.upstream || process.env.AGENT402_UPSTREAM || DEFAULT_UPSTREAM);
186
+ const pricing = String(cfg.pricing || process.env.AGENT402_PRICING || "metered").toLowerCase() === "flat" ? "flat" : "metered";
187
+ const log = (m) => api.logger?.info?.(m);
188
+ api.registerProvider(buildProvider({ port }));
189
+ if (!registeredOnce) {
190
+ registeredOnce = true;
191
+ api.registerService({
192
+ id: "agent402-proxy",
193
+ start: async () => {
194
+ if (started) return;
195
+ const creditsKey = resolveCreditsKey(cfg);
196
+ const payFetch = creditsKey ? null : await resolvePayFetch(cfg, log);
197
+ try { setCachedRoutes(await loadRoutes(upstream, fetch, { pricing })); } catch (e) { log(`[agent402-model-provider] could not read ${upstream}/v1/models yet: ${e?.message || e}`); }
198
+ started = await startProxy({ upstream, creditsKey, payFetch, port, pricing, log });
199
+ setActiveProxy(started);
200
+ if (started.mode === "unpaid") log("[agent402-model-provider] no payment configured: run `agent402-model-provider setup` (a wallet key, or a credits key already issued) - paid calls will answer 402 until then");
201
+ },
202
+ stop: async () => { if (started) { await started.close(); started = null; setActiveProxy(null); } },
203
+ });
204
+ }
205
+ },
206
+ };
207
+
208
+ export default plugin;
209
+ export { plugin, buildProvider, startProxy };
@@ -0,0 +1,358 @@
1
+ // Known payment assets, and the USD value of an x402 accept priced from them.
2
+ //
3
+ // An x402 "exact" signer signs the accept's raw base-unit amount for the
4
+ // accept's `asset`: `amount` under x402 v2, `maxAmountRequired` under v1. A
5
+ // spending cap therefore has to price the field the signer of that version
6
+ // reads, with the asset's real decimals, and a decimals hint the seller sends
7
+ // beside it (for example `extra.decimals`) is not evidence of anything. So the
8
+ // price of an accept comes from its challenge's version and this table alone:
9
+ // the stablecoins each network settles on the Agent402 rails, with their
10
+ // on-chain decimals. An accept whose (network, asset) pair is not in the table,
11
+ // or that carries both amount fields with different values, cannot be priced,
12
+ // and a buyer with a cap does not sign it. The table is keyed by CAIP-2 ids
13
+ // only: a bare v1 network name (for example "base") is not priced.
14
+ //
15
+ // An entry may also name its token's EIP-712 domain (`name` and `version`,
16
+ // read from the token's own name() and version()). An EVM "exact" signer
17
+ // signs under the domain the accept's `extra` carries, so for such an entry
18
+ // an accept whose `extra.name` or `extra.version` is not exactly the token's
19
+ // cannot be priced either, and a buyer with a cap does not sign it.
20
+ //
21
+ // The same file ships in agent402-client, agent402-mcp and agent402-model-provider;
22
+ // the parent repo's scripts/test-known-assets.js keeps the copies identical and
23
+ // checks the table against the assets the server offers.
24
+
25
+ /** network (CAIP-2) -> the assets a buyer may price there. */
26
+ export const KNOWN_ASSETS = Object.freeze({
27
+ // EVM: USDC (native Circle) unless named otherwise.
28
+ "eip155:8453": [{ asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6, symbol: "USDC" }], // Base
29
+ "eip155:84532": [{ asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals: 6, symbol: "USDC" }], // Base Sepolia
30
+ "eip155:137": [{ asset: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", decimals: 6, symbol: "USDC" }], // Polygon
31
+ "eip155:42161": [{ asset: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", decimals: 6, symbol: "USDC" }], // Arbitrum
32
+ "eip155:143": [{ asset: "0x754704Bc059F8C67012fEd69BC8A327a5aafb603", decimals: 6, symbol: "USDC" }], // Monad
33
+ "eip155:42220": [{ asset: "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", decimals: 6, symbol: "USDC" }], // Celo
34
+ "eip155:43114": [{ asset: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", decimals: 6, symbol: "USDC" }], // Avalanche
35
+ "eip155:1329": [{ asset: "0xe15fC38F6D8c56aF07bbCBe3BAf5708A2Bf42392", decimals: 6, symbol: "USDC" }], // Sei
36
+ "eip155:10": [{ asset: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85", decimals: 6, symbol: "USDC" }], // Optimism
37
+ "eip155:5042": [{ asset: "0x3600000000000000000000000000000000000000", decimals: 6, symbol: "USDC" }], // Arc
38
+ "eip155:57073": [{ asset: "0x2D270e6886d130D724215A266106e6832161EAEd", decimals: 6, symbol: "USDC", name: "USDC", version: "2" }], // Ink
39
+ "eip155:4663": [{ asset: "0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168", decimals: 6, symbol: "USDG" }], // Robinhood Chain
40
+ // Solana: the USDC mint.
41
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": [{ asset: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", decimals: 6, symbol: "USDC" }],
42
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": [{ asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", decimals: 6, symbol: "USDC" }], // devnet
43
+ // Stellar: the USDC Stellar Asset Contract (7 decimals on Stellar).
44
+ "stellar:pubnet": [{ asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", decimals: 7, symbol: "USDC" }],
45
+ // Algorand: USDC is ASA 31566704. Mainnet is named by its CAIP-2 id (the
46
+ // first 32 characters of the base64 genesis hash) and, by sellers that
47
+ // predate it, by the full hash.
48
+ "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k": [{ asset: "31566704", decimals: 6, symbol: "USDC" }],
49
+ "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=": [{ asset: "31566704", decimals: 6, symbol: "USDC" }],
50
+ });
51
+
52
+ /** Chain name -> every network id in the table that names that chain. A
53
+ * chain spelled two ways on the wire lists both, so a buyer's preference by
54
+ * name, or by either spelling, matches a seller's accept in the other. */
55
+ export const NETWORK_NAMES = Object.freeze({
56
+ base: ["eip155:8453"],
57
+ "base-sepolia": ["eip155:84532"],
58
+ polygon: ["eip155:137"],
59
+ arbitrum: ["eip155:42161"],
60
+ monad: ["eip155:143"],
61
+ celo: ["eip155:42220"],
62
+ avalanche: ["eip155:43114"],
63
+ sei: ["eip155:1329"],
64
+ optimism: ["eip155:10"],
65
+ arc: ["eip155:5042"],
66
+ ink: ["eip155:57073"],
67
+ robinhood: ["eip155:4663"],
68
+ solana: ["solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"],
69
+ "solana-devnet": ["solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"],
70
+ stellar: ["stellar:pubnet"],
71
+ algorand: ["algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k", "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8="],
72
+ });
73
+
74
+ /** A chain's official name, as the server's rails and pages print it, read
75
+ * as the short name the table keys it by ("Arbitrum One" is arbitrum). */
76
+ export const NETWORK_NAME_ALIASES = Object.freeze({
77
+ "arbitrum one": "arbitrum",
78
+ "avalanche c-chain": "avalanche",
79
+ "op mainnet": "optimism",
80
+ "robinhood chain": "robinhood",
81
+ });
82
+
83
+ /** The network ids a preference names: a chain name's ids (its short or its
84
+ * official name); for an id, every id of the chain it belongs to (so either
85
+ * spelling matches the other); an id the table does not know passes through
86
+ * as itself. */
87
+ export function networkIdsOf(pref) {
88
+ const p = String(pref || "").trim();
89
+ if (!p) return [];
90
+ const low = p.toLowerCase().replace(/\s+/g, " ");
91
+ const byName = NETWORK_NAMES[NETWORK_NAME_ALIASES[low] || low];
92
+ if (byName) return [...byName];
93
+ for (const ids of Object.values(NETWORK_NAMES)) if (ids.some((id) => id.toLowerCase() === p.toLowerCase())) return [...ids];
94
+ return [p];
95
+ }
96
+
97
+ const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
98
+ // EVM addresses compare without case (checksum casing is presentation);
99
+ // base58, Stellar and Algorand identifiers compare exactly.
100
+ const sameAsset = (a, b) => (EVM_ADDRESS.test(a) && EVM_ADDRESS.test(b) ? a.toLowerCase() === b.toLowerCase() : a === b);
101
+
102
+ /** The table entry for (network, asset), or null when it is not a known asset. */
103
+ export function knownAsset(network, asset) {
104
+ if (typeof network !== "string" || typeof asset !== "string" || !asset) return null;
105
+ const list = KNOWN_ASSETS[network];
106
+ if (!list) return null;
107
+ return list.find((e) => sameAsset(e.asset, asset)) || null;
108
+ }
109
+
110
+ /** True when the accept carries the EIP-712 domain the table names for its
111
+ * asset (`extra.name` and `extra.version`, exactly), or when the entry names
112
+ * none. */
113
+ export function acceptDomainMatches(entry, accept) {
114
+ if (!entry || (entry.name == null && entry.version == null)) return true;
115
+ const extra = accept && typeof accept.extra === "object" && accept.extra ? accept.extra : {};
116
+ return extra.name === entry.name && extra.version === entry.version;
117
+ }
118
+
119
+ /** The base-unit amount the signer of `x402Version` signs for one accept, as
120
+ * a string of digits: `maxAmountRequired` under v1, `amount` under v2. With
121
+ * no version, the one field present (or both, when they agree). null when
122
+ * the field that version signs is missing or not a whole number, when the
123
+ * version is neither 1 nor 2, and whenever the accept carries both fields
124
+ * with different values: such an accept means one price to one reader and
125
+ * another to the next, so it is not priced at all. */
126
+ export function acceptAmount(accept, x402Version = undefined) {
127
+ if (!accept || typeof accept !== "object") return null;
128
+ const has = (x) => x != null && x !== "";
129
+ const v2 = accept.amount, v1 = accept.maxAmountRequired;
130
+ if (has(v2) && has(v1) && String(v2) !== String(v1)) return null;
131
+ let raw;
132
+ if (x402Version === 1) raw = v1;
133
+ else if (x402Version === 2) raw = v2;
134
+ else if (x402Version == null) raw = has(v2) ? v2 : v1;
135
+ else return null;
136
+ if (!has(raw) || !/^\d+$/.test(String(raw))) return null;
137
+ return String(raw);
138
+ }
139
+
140
+ /** The USD value of one accept: the base-unit amount its version's signer
141
+ * signs (acceptAmount) over the KNOWN decimals of its asset. null when the
142
+ * asset is not known, when the accept names a different EIP-712 domain than
143
+ * the table's for that asset, or when the amount cannot be read. */
144
+ export function acceptUsd(accept, x402Version = undefined) {
145
+ const raw = acceptAmount(accept, x402Version);
146
+ if (raw == null) return null;
147
+ const entry = knownAsset(accept.network, accept.asset);
148
+ if (!entry || !acceptDomainMatches(entry, accept)) return null;
149
+ return Number(raw) / 10 ** entry.decimals;
150
+ }
151
+
152
+ /** The USD values of a 402's accepts: `max` and `min` over the accepts that can
153
+ * be priced, and `unknown`, the count that cannot. null when there are none. */
154
+ export function quoteOf(accepts, x402Version = undefined) {
155
+ if (!Array.isArray(accepts) || !accepts.length) return null;
156
+ let max = null, min = null, unknown = 0;
157
+ for (const a of accepts) {
158
+ const usd = acceptUsd(a, x402Version);
159
+ if (usd == null) { unknown++; continue; }
160
+ if (max == null || usd > max) max = usd;
161
+ if (min == null || usd < min) min = usd;
162
+ }
163
+ return { max, min, unknown, total: accepts.length };
164
+ }
165
+
166
+ // The longest a signed payment may stay redeemable. An EVM "exact" signer
167
+ // sets validBefore (EIP-3009) or deadline (Permit2) to the moment of signing
168
+ // plus the accept's maxTimeoutSeconds, and the signed payload is a bearer
169
+ // claim until then, so a seller that quotes years gets an authorization it
170
+ // could redeem for years and a held amount that never stops counting. Honest
171
+ // accepts ask for minutes (Agent402's own ask 300 s); a day admits every
172
+ // one of them. An accept that asks for longer is dropped before selection,
173
+ // and a payload signed past it is refused before it is sent.
174
+ export const MAX_VALIDITY_SECONDS = 24 * 3600;
175
+ // Signing reads the clock a moment before the check after it does.
176
+ const VALIDITY_CLOCK_SLACK_SECONDS = 60;
177
+
178
+ /** True when an accept asks for a validity window past MAX_VALIDITY_SECONDS.
179
+ * An accept with no readable maxTimeoutSeconds is left to the check of what
180
+ * was signed (signedValidityProblem). */
181
+ export function acceptValidityTooLong(accept, maxSeconds = MAX_VALIDITY_SECONDS) {
182
+ const raw = accept?.maxTimeoutSeconds;
183
+ if (raw == null || raw === "") return false;
184
+ const n = Number(raw);
185
+ return !Number.isFinite(n) || n > maxSeconds;
186
+ }
187
+
188
+ /** The expiry a signed payload carries, in unix seconds: an EIP-3009
189
+ * `authorization.validBefore` or a Permit2 `deadline`. null when the payload
190
+ * names none (a Solana transaction, an unknown scheme). NaN when it names
191
+ * one that is not a whole number of seconds. */
192
+ export function signedExpirySeconds(paymentPayload) {
193
+ const p = paymentPayload?.payload;
194
+ const v = p?.authorization?.validBefore ?? p?.permit2Authorization?.deadline;
195
+ if (v == null) return null;
196
+ return /^\d{1,15}$/.test(String(v)) ? Number(v) : NaN;
197
+ }
198
+
199
+ /** Why a created payment payload stays redeemable for too long, or null: its
200
+ * expiry is past `nowMs` plus `maxSeconds` (and a minute of clock slack), or
201
+ * it names an expiry that cannot be read. */
202
+ export function signedValidityProblem(paymentPayload, { maxSeconds = MAX_VALIDITY_SECONDS, nowMs = Date.now() } = {}) {
203
+ const exp = signedExpirySeconds(paymentPayload);
204
+ if (exp == null) return null;
205
+ if (!Number.isFinite(exp)) return "the signed authorization's expiry cannot be read";
206
+ const left = exp - Math.floor(nowMs / 1000);
207
+ if (left > maxSeconds + VALIDITY_CLOCK_SLACK_SECONDS) return `the signed authorization stays valid for ${left} seconds, past the ${maxSeconds}-second ceiling`;
208
+ return null;
209
+ }
210
+
211
+ /** Enforce a USD allowance at signing on an @x402/core x402Client.
212
+ *
213
+ * `allowance()` is the most this buyer may sign for the payment being built
214
+ * (a per-call cap, a remaining budget, or the smaller of the two; Infinity
215
+ * for none). A registered policy drops every accept that cannot be priced or
216
+ * is over the allowance, so the client selects among the ones that fit, and a
217
+ * hook before payload creation checks the selected accept again and passes
218
+ * its USD value to `onSign`. An accept asking for a validity window past
219
+ * MAX_VALIDITY_SECONDS is dropped and refused the same way. A refusal throws
220
+ * (from the policy) or aborts (from the hook) before any signature exists;
221
+ * `onRefuse` hears why first. */
222
+ export function guardSigning(client, { allowance, onSign = null, onRefuse = null }) {
223
+ if (!client || typeof client.registerPolicy !== "function" || typeof client.onBeforePaymentCreation !== "function") {
224
+ throw new TypeError("guardSigning needs an @x402/core x402Client (registerPolicy and onBeforePaymentCreation)");
225
+ }
226
+ if (typeof allowance !== "function") throw new TypeError("guardSigning needs an allowance() function");
227
+ const refuse = (detail) => { try { onRefuse?.(detail); } catch { /* the refusal stands */ } return detail; };
228
+ client.registerPolicy((version, accepts) => {
229
+ const cap = allowance();
230
+ const priced = accepts.filter((a) => { const usd = acceptUsd(a, version); return usd != null && usd <= cap; });
231
+ const kept = priced.filter((a) => !acceptValidityTooLong(a));
232
+ if (!kept.length && priced.length) {
233
+ const d = refuse({ reason: "validity", priceUsd: null, allowanceUsd: cap, detail: `every payment option it may sign asks to stay valid for more than ${MAX_VALIDITY_SECONDS} seconds` });
234
+ throw new Error(`spending guard: ${d.detail}; nothing was signed`);
235
+ }
236
+ if (!kept.length) {
237
+ const q = quoteOf(accepts, version);
238
+ const d = refuse({ reason: q && q.min != null ? "over-allowance" : "unknown-asset", priceUsd: q ? q.min : null, allowanceUsd: cap });
239
+ throw new Error(d.reason === "unknown-asset"
240
+ ? "spending guard: no payment option is in a known asset, so none can be priced; nothing was signed"
241
+ : `spending guard: the cheapest payment option asks $${d.priceUsd}, above the $${cap} this buyer may sign; nothing was signed`);
242
+ }
243
+ return kept;
244
+ });
245
+ client.onBeforePaymentCreation(async ({ paymentRequired, selectedRequirements: r }) => {
246
+ const usd = acceptUsd(r, paymentRequired?.x402Version);
247
+ const cap = allowance();
248
+ if (usd == null) {
249
+ refuse({ reason: "unknown-asset", priceUsd: null, allowanceUsd: cap });
250
+ return { abort: true, reason: "spending guard: the selected payment option is not in a known asset; nothing was signed" };
251
+ }
252
+ if (usd > cap) {
253
+ refuse({ reason: "over-allowance", priceUsd: usd, allowanceUsd: cap });
254
+ return { abort: true, reason: `spending guard: the selected payment option asks $${usd}, above the $${cap} this buyer may sign; nothing was signed` };
255
+ }
256
+ if (acceptValidityTooLong(r)) {
257
+ const d = refuse({ reason: "validity", priceUsd: usd, allowanceUsd: cap, detail: `the selected payment option asks to stay valid for ${r.maxTimeoutSeconds} seconds, past the ${MAX_VALIDITY_SECONDS}-second ceiling` });
258
+ return { abort: true, reason: `spending guard: ${d.detail}; nothing was signed` };
259
+ }
260
+ onSign?.(usd, r);
261
+ return undefined;
262
+ });
263
+ guardSignedAmount(client, { allowance, onRefuse: refuse });
264
+ return client;
265
+ }
266
+
267
+ // The token programs a Solana "exact" payment moves its asset through, and
268
+ // the TransferChecked instruction's tag.
269
+ const SOLANA_TOKEN_PROGRAMS = new Set(["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);
270
+ const TRANSFER_CHECKED = 12;
271
+
272
+ /** The amount a Solana payment transaction moves: its one token-program
273
+ * instruction, which must be a TransferChecked, read as base units and
274
+ * decimals. Decoded with @solana/kit, the peer every Solana x402 signer
275
+ * already loads. null when the transaction cannot be read or does not hold
276
+ * exactly that one transfer. */
277
+ async function solanaTransferOf(transaction) {
278
+ if (typeof transaction !== "string" || !transaction) return null;
279
+ try {
280
+ const kit = await import("@solana/kit");
281
+ const tx = kit.getTransactionDecoder().decode(kit.getBase64Encoder().encode(transaction));
282
+ const msg = kit.getCompiledTransactionMessageDecoder().decode(tx.messageBytes);
283
+ const keys = msg.staticAccounts || [];
284
+ const ixs = msg.version === 1
285
+ ? (msg.instructionHeaders || []).map((h, i) => ({ program: keys[h.programAccountIndex], data: msg.instructionPayloads?.[i]?.instructionData }))
286
+ : (msg.instructions || []).map((ix) => ({ program: keys[ix.programAddressIndex], data: ix.data }));
287
+ const token = ixs.filter((ix) => SOLANA_TOKEN_PROGRAMS.has(String(ix.program)));
288
+ if (token.length !== 1) return null;
289
+ const d = token[0].data;
290
+ if (!d || d.length !== 10 || d[0] !== TRANSFER_CHECKED) return null;
291
+ let amount = 0n;
292
+ for (let i = 8; i >= 1; i--) amount = (amount << 8n) | BigInt(d[i]);
293
+ return { amount: amount.toString(), decimals: d[9] };
294
+ } catch {
295
+ return null;
296
+ }
297
+ }
298
+
299
+ /** The base-unit amount a created x402 payment payload commits the buyer to,
300
+ * read from what was signed: an EVM EIP-3009 `authorization.value`, an EVM
301
+ * Permit2 `permitted.amount`, or a Solana transaction's transfer. Returns
302
+ * `{ amount, decimals? }`, `{ unchecked: true }` for a network whose payload
303
+ * this reader does not decode (neither EVM nor Solana), or null when an EVM or
304
+ * Solana payload holds no amount it can read. */
305
+ export async function signedAmountOf(paymentPayload, network) {
306
+ const p = paymentPayload?.payload;
307
+ const net = String(network || "");
308
+ if (net.startsWith("eip155:")) {
309
+ const vals = [p?.authorization?.value, p?.permit2Authorization?.permitted?.amount].filter((x) => x != null);
310
+ if (vals.length !== 1 || !/^\d+$/.test(String(vals[0]))) return null;
311
+ return { amount: BigInt(String(vals[0])).toString() };
312
+ }
313
+ if (net.startsWith("solana:")) return solanaTransferOf(p?.transaction);
314
+ return { unchecked: true };
315
+ }
316
+
317
+ /** Check a created payment payload against the accept it was built for,
318
+ * before it is sent: the amount that was signed must be the amount the
319
+ * allowance was checked against (acceptAmount under the challenge's
320
+ * version), in the known asset's decimals, and within `cap`. Returns null
321
+ * when it holds, else why not. */
322
+ export async function signedPaymentProblem(paymentPayload, requirements, x402Version, cap = Infinity) {
323
+ const expected = acceptAmount(requirements, x402Version);
324
+ const entry = knownAsset(requirements?.network, requirements?.asset);
325
+ if (expected == null) return "the selected payment option's amount cannot be read";
326
+ const signed = await signedAmountOf(paymentPayload, requirements?.network);
327
+ if (signed == null) return "the signed payment's amount cannot be read";
328
+ if (signed.unchecked) return null;
329
+ if (signed.amount !== BigInt(expected).toString()) return `the signed amount (${signed.amount}) differs from the priced amount (${expected})`;
330
+ if (signed.decimals != null && entry && signed.decimals !== entry.decimals) return "the signed transfer's decimals differ from the known asset's";
331
+ if (Number.isFinite(cap)) {
332
+ if (!entry) return "the selected payment option is not in a known asset";
333
+ const usd = Number(signed.amount) / 10 ** entry.decimals;
334
+ if (usd > cap) return `the signed amount asks ${usd}, above the ${cap} this buyer may sign`;
335
+ }
336
+ return null;
337
+ }
338
+
339
+ /** Refuse to send a payment payload whose signed amount is not the one the
340
+ * allowance passed, or whose expiry is past MAX_VALIDITY_SECONDS from now
341
+ * (signedValidityProblem): registered after payload creation, so the check
342
+ * reads what was actually signed, and a throw here stops the payment-aware
343
+ * fetch before the payload leaves the process. guardSigning registers it; a
344
+ * client with its own selector (and no guardSigning) can register it alone. */
345
+ export function guardSignedAmount(client, { allowance = () => Infinity, onRefuse = null } = {}) {
346
+ if (!client || typeof client.onAfterPaymentCreation !== "function") {
347
+ throw new TypeError("guardSignedAmount needs an @x402/core x402Client (onAfterPaymentCreation)");
348
+ }
349
+ client.onAfterPaymentCreation(async ({ paymentRequired, selectedRequirements: r, paymentPayload }) => {
350
+ const cap = allowance();
351
+ const amountProblem = await signedPaymentProblem(paymentPayload, r, paymentRequired?.x402Version, cap);
352
+ const problem = amountProblem || signedValidityProblem(paymentPayload);
353
+ if (!problem) return;
354
+ try { onRefuse?.({ reason: amountProblem ? "signed-amount" : "signed-validity", priceUsd: null, allowanceUsd: cap, detail: problem }); } catch { /* the refusal stands */ }
355
+ throw new Error(`spending guard: ${problem}; the payment was not sent`);
356
+ });
357
+ return client;
358
+ }
package/models.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ // Type declarations for agent402-model-provider/models: the route table read from
2
+ // the gateway's /v1/models and the OpenClaw provider config built from it.
3
+
4
+ /** One model the local proxy can serve, and the gateway route it pays. */
5
+ export interface Agent402Route {
6
+ id: string;
7
+ endpoint: string;
8
+ tier: string | null;
9
+ priceUsd: number;
10
+ metered?: boolean;
11
+ maxTokens: number;
12
+ maxInputChars: number;
13
+ stealth: boolean;
14
+ }
15
+ export type RouteTable = Map<string, Agent402Route>;
16
+
17
+ /** An OpenClaw `models[]` entry. */
18
+ export interface OpenClawModel {
19
+ id: string;
20
+ name: string;
21
+ reasoning: boolean;
22
+ input: string[];
23
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
24
+ contextWindow: number;
25
+ maxTokens: number;
26
+ }
27
+
28
+ export const AUTO_ID: "auto";
29
+ export const METERED_MAX_INPUT_CHARS: number;
30
+ export const METERED_MAX_TOKENS: number;
31
+ export const OPENCLAW_MIN_INPUT_CHARS: number;
32
+ export const PRIMARY_PREFERENCE: string[];
33
+
34
+ export function stripTrailingSlashes(s: string): string;
35
+ /** The route table from a /v1/models document; "metered" (the default) pays explicit models per request. */
36
+ export function routesFromCatalog(catalog: unknown, opts?: { pricing?: "metered" | "flat" }): RouteTable;
37
+ /** The route OpenClaw should make its primary model, or null when none fits its prompt. */
38
+ export function defaultPrimary(routes: RouteTable, opts?: { minInputChars?: number }): Agent402Route | null;
39
+ export function openclawModels(routes: RouteTable): OpenClawModel[];
40
+ /** An OpenClaw ModelProviderConfig pointing at the local proxy. */
41
+ export function providerModelsConfig(baseUrl: string, routes: RouteTable): { baseUrl: string; api: "openai-completions"; models: OpenClawModel[] };