agent402-model-provider 0.0.0-stage → 0.7.0-claim.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 +175 -2
- package/cli.js +224 -0
- package/index.d.ts +93 -0
- package/index.js +209 -0
- package/known-assets.js +358 -0
- package/models.d.ts +41 -0
- package/models.js +122 -0
- package/openclaw.plugin.json +64 -0
- package/package.json +92 -4
- package/provider.js +45 -0
- package/proxy.d.ts +48 -0
- package/proxy.js +311 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cardhavok LLC (doing business as Havok Holdings LLC)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent402-model-provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Part of [Agent402](https://agent402.tools), open source and self-hostable. Agent402 is the payment and trust layer for agentic commerce: agents find, pay for and verify paid calls to Agent402, across x402 and MPP, with signed receipts on successful direct calls. 500+ ready tools on the same rails.
|
|
4
|
+
|
|
5
|
+
Agent402 as a model provider for use with [OpenClaw](https://openclaw.ai): explicit models
|
|
6
|
+
**priced per request** from the body by default (metered), and the auto-routed
|
|
7
|
+
tier at a **flat per-call price**, paid in **USDC over x402** from a wallet or with a
|
|
8
|
+
prepaid credits key (agent402.tools/credits says whether packs are on sale). The
|
|
9
|
+
same key and gateway reach Agent402's 500+ pay-per-call tools; credits pay
|
|
10
|
+
Agent402's own services, so the routes that buy from an outside seller
|
|
11
|
+
(the route-execute tiers, `seller-payability`, `decide-execute` and the flight routes) need a wallet.
|
|
12
|
+
|
|
13
|
+
Works with OpenClaw. Agent402 is not affiliated with or endorsed by the OpenClaw project.
|
|
14
|
+
|
|
15
|
+
Formerly `agent402-openclaw`: the same plugin, provider id and CLI commands under a new name. Install `agent402-model-provider` and run `npx agent402-model-provider` where you ran `npx agent402-openclaw`.
|
|
16
|
+
|
|
17
|
+
Guide: https://agent402.tools/guides/openclaw-model-provider
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
openclaw plugins install agent402-model-provider
|
|
23
|
+
npx agent402-model-provider setup --write # no key? it mints a wallet and prints the address to fund
|
|
24
|
+
openclaw gateway restart
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
With no credits key and no `AGENT402_WALLET_KEY`, `setup` generates an EVM
|
|
28
|
+
wallet into `~/.openclaw/agent402/wallet.key` (0600, the only copy, never
|
|
29
|
+
printed) and prints its address: send it USDC on Base and every call is paid
|
|
30
|
+
from it over x402. `agent402-model-provider wallet` shows the address and balance;
|
|
31
|
+
`--no-wallet` skips the generation. Holding a credits key? Run
|
|
32
|
+
`AGENT402_CREDITS_KEY=a402_... npx agent402-model-provider setup --write` (key by env,
|
|
33
|
+
or `--credits-key -` on stdin).
|
|
34
|
+
|
|
35
|
+
(`openclaw plugins install` copies the plugin into `~/.openclaw/extensions` and
|
|
36
|
+
does not link its CLI, hence `npx`.) `setup` stores a credits key under
|
|
37
|
+
`~/.openclaw/agent402/credits.key` (0600) and prints the `openclaw.json` block;
|
|
38
|
+
add `--write` to merge it in. The primary model it writes is the cheapest
|
|
39
|
+
metered model that can hold OpenClaw's own prompt: OpenClaw sends roughly 70k
|
|
40
|
+
characters of system prompt and tool schemas before your first word, and the
|
|
41
|
+
routed `auto` tier caps input at 16k, so `auto` stays listed for short one-off
|
|
42
|
+
prompts but is never made primary (OpenClaw would refuse every turn as a
|
|
43
|
+
context overflow). The plugin starts a loopback proxy (`127.0.0.1:8412`) that
|
|
44
|
+
pays Agent402 and forwards; OpenClaw only ever sees a local OpenAI-compatible URL.
|
|
45
|
+
|
|
46
|
+
Each release is published to npm and ClawHub. OpenClaw 2026.11.5 and later
|
|
47
|
+
install a bare name from ClawHub, so the command above takes the ClawHub
|
|
48
|
+
listing there; `openclaw plugins install npm:agent402-model-provider` takes the npm
|
|
49
|
+
package. Earlier hosts install the bare name from npm, and
|
|
50
|
+
`openclaw plugins install clawhub:agent402-model-provider` takes the ClawHub listing
|
|
51
|
+
and shows its security audit first.
|
|
52
|
+
|
|
53
|
+
OpenClaw 2026.10.1 and later reserve the verified-source badge for plugins in
|
|
54
|
+
OpenClaw's own official inventory, so `openclaw plugins doctor` and `plugins
|
|
55
|
+
inspect` list agent402 with "OpenClaw can't verify where this plugin came from
|
|
56
|
+
... reason=provenance-invalid" whichever way it was installed (npm, ClawHub or a
|
|
57
|
+
local archive). That notice is OpenClaw's verdict on every community plugin. The
|
|
58
|
+
plugin loads, the gateway starts its proxy and turns are served as before: it
|
|
59
|
+
registers a model provider and a service, and uses no feature OpenClaw keeps for
|
|
60
|
+
trusted plugins.
|
|
61
|
+
|
|
62
|
+
Tested in CI against real OpenClaw installs (the newest proven release and the
|
|
63
|
+
one before it, plus a daily run against the newest published one): plugin
|
|
64
|
+
install from a packed archive, the npm registry and ClawHub, doctor, setup, model
|
|
65
|
+
listing, gateway boot and one agent turn (`test-real-install.js`).
|
|
66
|
+
|
|
67
|
+
No OpenClaw? `agent402-model-provider proxy` runs the proxy alone; point any OpenAI
|
|
68
|
+
client at `http://127.0.0.1:8412/v1`. An explicit model rides the metered route
|
|
69
|
+
by default (each request quoted from its body, and settlement never exceeds the
|
|
70
|
+
quote); model `auto` takes the flat routed tier.
|
|
71
|
+
|
|
72
|
+
**Claude Code and other Anthropic-wire clients** (0.5.0): the proxy also answers
|
|
73
|
+
`POST /v1/messages` and forwards it to the gateway's metered Messages route,
|
|
74
|
+
paid from the same wallet:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
export ANTHROPIC_BASE_URL=http://127.0.0.1:8412
|
|
78
|
+
export ANTHROPIC_AUTH_TOKEN=unused # the proxy pays; this value is ignored
|
|
79
|
+
claude --model claude-sonnet-5
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Pay from a wallet instead
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
npm i @x402/fetch @x402/evm viem
|
|
86
|
+
export AGENT402_WALLET_KEY=0x... # an EVM key holding USDC on Base
|
|
87
|
+
export AGENT402_MAX_PER_CALL_USD=5 # per-call ceiling checked before signing (default 5; 0 or off turns it off)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
With no credits key present the proxy signs an x402 payment per call from that
|
|
91
|
+
wallet. The key never leaves the machine. A $5 per-call ceiling protects the
|
|
92
|
+
wallet by default (it covers every fixed price in the catalog). The ceiling is
|
|
93
|
+
checked on the payment
|
|
94
|
+
option that is signed, priced from the known decimals of its asset (USDC or
|
|
95
|
+
USDG on a known network) and from the amount field that option's x402 version
|
|
96
|
+
signs; an option in any other asset is not signed while a ceiling is set. Once
|
|
97
|
+
the payment is built, the amount it actually signs is read back and checked
|
|
98
|
+
against the same price and ceiling before it is sent.
|
|
99
|
+
|
|
100
|
+
A signed payment also has a validity ceiling of 24 hours: a payment option
|
|
101
|
+
that asks to stay redeemable for longer (its `maxTimeoutSeconds`) is not
|
|
102
|
+
signed, and a built payment whose expiry (`validBefore` or the Permit2
|
|
103
|
+
`deadline`) lies more than 24 hours out is refused before it is sent. Any
|
|
104
|
+
refusal happens before the payment leaves the machine, and the call's error
|
|
105
|
+
names the reason.
|
|
106
|
+
|
|
107
|
+
`maxPerCallUsd` (or `AGENT402_MAX_PER_CALL_USD`) set to `0` or `"off"` turns
|
|
108
|
+
the ceiling off. A value that is not a USD amount (text, a negative number, an
|
|
109
|
+
empty string) keeps the $5 default and the proxy names the setting on stderr.
|
|
110
|
+
`allowUncappedPayments` is still accepted from earlier configurations and
|
|
111
|
+
changes nothing. A call the ceiling refuses names the price, the ceiling and
|
|
112
|
+
`maxPerCallUsd` / `AGENT402_MAX_PER_CALL_USD`.
|
|
113
|
+
|
|
114
|
+
Two ways the wallet can pay a metered call:
|
|
115
|
+
|
|
116
|
+
- **exact** (default): the 402 quotes the call from its body (input + your
|
|
117
|
+
`max_tokens`) and the wallet pays that quote.
|
|
118
|
+
- **upto, actual usage**: run `agent402-model-provider permit2-approve` once (one USDC
|
|
119
|
+
approval transaction on Base; the wallet needs a little ETH for gas). From
|
|
120
|
+
then on the proxy authorizes the quote as a CEILING and the gateway settles
|
|
121
|
+
what the call actually used, so a short answer costs a fraction of the
|
|
122
|
+
quote. `agent402-model-provider doctor` says which mode the wallet is in.
|
|
123
|
+
|
|
124
|
+
Credits-key buyers already pay actual usage on metered calls.
|
|
125
|
+
|
|
126
|
+
## Models and pricing
|
|
127
|
+
|
|
128
|
+
`auto` (routed per prompt, flat $0.01/call) plus every id from
|
|
129
|
+
`GET https://agent402.tools/v1/models`. Explicit models are **metered by default**:
|
|
130
|
+
the proxy sends them to the gateway's metered route, where each request is quoted
|
|
131
|
+
from its body (input plus your `max_tokens`, from $0.001, capped at $2 per
|
|
132
|
+
call), so a short call costs a fraction
|
|
133
|
+
of a cent and a long one pays for what it asks. `--flat` (or
|
|
134
|
+
`AGENT402_PRICING=flat`) keeps every model on its flat per-call tier instead.
|
|
135
|
+
Either way OpenClaw's per-token cost fields stay zero; the price is per call. A model sent to another flat
|
|
136
|
+
tier's route is priced at its home tier: the 402 quotes that tier's price, and the paid call is served under
|
|
137
|
+
that tier's caps (the answer says so in `agent402_tier`). The router, grounded and stealth tiers still answer a
|
|
138
|
+
400 naming the right route; nothing is charged on x402. A client-supplied `Idempotency-Key`
|
|
139
|
+
is passed through: on a credits key, a retry with the same key replays the paid
|
|
140
|
+
answer; on a wallet, each forwarded call signs a fresh payment, which the server
|
|
141
|
+
treats as a new purchase. Without a key, each call is its own payment.
|
|
142
|
+
|
|
143
|
+
The proxy answers native clients on loopback only: requests carrying a browser
|
|
144
|
+
`Origin` header or a non-loopback `Host` are refused, so a web page cannot spend
|
|
145
|
+
the key.
|
|
146
|
+
|
|
147
|
+
The credits key stays out of what the proxy prints: an upstream or network
|
|
148
|
+
error is logged and answered (the 502 body) with the key cut out as
|
|
149
|
+
`[redacted]`, and `agent402-model-provider doctor` reports the key as `present` or
|
|
150
|
+
`none`, never any part of it.
|
|
151
|
+
|
|
152
|
+
## Commands
|
|
153
|
+
|
|
154
|
+
- `agent402-model-provider setup [--credits-key K | --credits-key - (stdin) | AGENT402_CREDITS_KEY env] [--no-wallet] [--write] [--port N] [--flat]`
|
|
155
|
+
- `agent402-model-provider proxy [--port N] [--upstream URL]`
|
|
156
|
+
- `agent402-model-provider doctor`
|
|
157
|
+
- `agent402-model-provider wallet [--rpc URL]` (address + USDC balance of the wallet the proxy pays from)
|
|
158
|
+
- `agent402-model-provider permit2-approve [--rpc URL]` (one-time USDC approval so the wallet pays actual usage over upto)
|
|
159
|
+
|
|
160
|
+
## What else the same key buys
|
|
161
|
+
|
|
162
|
+
The key or wallet that pays for chat also pays for the rest of the gateway and
|
|
163
|
+
the catalog, with one 402 shape and one receipt shape: OpenAI Responses and
|
|
164
|
+
Anthropic Messages wires, embeddings, rerank, images, video, speech,
|
|
165
|
+
transcription, grounded answers with citations, 500+ tools over
|
|
166
|
+
MCP or HTTP, wallet-keyed memory, finished reports (dossiers, insider flow, 13F,
|
|
167
|
+
domain audits, token risk, deep research) and monitors, plus routing that buys
|
|
168
|
+
from external sellers and resells the result.
|
|
169
|
+
|
|
170
|
+
Why pay here, with every claim linked to its proof: https://agent402.tools/docs#why.
|
|
171
|
+
Usage is priced under a ceiling quoted before you pay, a failed call is not
|
|
172
|
+
charged and the receipt proves it, a keyed retry on a credits key is not
|
|
173
|
+
debited twice, and uptime and transactions are published from outside
|
|
174
|
+
production.
|
|
175
|
+
|
|
176
|
+
Zero dependencies. MIT. Maintained by Havok Holdings LLC.
|
package/cli.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// agent402-model-provider <command>
|
|
3
|
+
// setup [--credits-key a402_...] [--write] store the key, print (or merge) the openclaw.json block
|
|
4
|
+
// proxy [--port N] [--upstream URL] run the local proxy on its own (no OpenClaw needed;
|
|
5
|
+
// serves the OpenAI wire and Anthropic POST /v1/messages)
|
|
6
|
+
// doctor show what is configured and whether the gateway answers
|
|
7
|
+
import { mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync, statSync, realpathSync, renameSync } from "node:fs";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { STATE_DIR, CREDITS_KEY_FILE, WALLET_KEY_FILE, resolveCreditsKey, resolveWalletKey, resolvePayFetch, USDC_BASE, DEFAULT_BASE_RPC, uptoReady } from "./index.js";
|
|
12
|
+
import { startProxy, loadRoutes, DEFAULT_UPSTREAM } from "./proxy.js";
|
|
13
|
+
import { providerModelsConfig, stripTrailingSlashes, defaultPrimary, AUTO_ID, OPENCLAW_MIN_INPUT_CHARS } from "./models.js";
|
|
14
|
+
import { DEFAULT_PORT, PLUGIN_ID, PROVIDER_ID } from "./provider.js";
|
|
15
|
+
|
|
16
|
+
const args = process.argv.slice(2);
|
|
17
|
+
const cmd = args[0] || "help";
|
|
18
|
+
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
|
|
19
|
+
const has = (k) => args.includes(k);
|
|
20
|
+
const out = (s) => process.stdout.write(s + "\n");
|
|
21
|
+
|
|
22
|
+
/** The provider block for openclaw.json (JSON, so it can be merged; OpenClaw reads JSON5 which is a superset). */
|
|
23
|
+
export function configBlock({ port = DEFAULT_PORT, routes }) {
|
|
24
|
+
const primary = defaultPrimary(routes);
|
|
25
|
+
return {
|
|
26
|
+
agents: { defaults: { model: { primary: `${PROVIDER_ID}/${primary ? primary.id : AUTO_ID}` } } },
|
|
27
|
+
models: { providers: { [PROVIDER_ID]: { ...providerModelsConfig(`http://127.0.0.1:${port}`, routes), timeoutSeconds: 120 } } },
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function mergeInto(target, block, { port = DEFAULT_PORT } = {}) {
|
|
32
|
+
const t = target && typeof target === "object" ? target : {};
|
|
33
|
+
t.agents = t.agents || {}; t.agents.defaults = t.agents.defaults || {};
|
|
34
|
+
t.agents.defaults.model = { ...(t.agents.defaults.model || {}), primary: block.agents.defaults.model.primary };
|
|
35
|
+
t.models = t.models || {}; t.models.providers = t.models.providers || {};
|
|
36
|
+
t.models.providers[PROVIDER_ID] = block.models.providers[PROVIDER_ID];
|
|
37
|
+
// The plugin service reads ITS port from plugins.entries.<id>.config, not from
|
|
38
|
+
// the provider baseUrl - a --port that only moved the baseUrl left the proxy
|
|
39
|
+
// on 8412 and OpenClaw dialing a port nobody listened on (real-install test).
|
|
40
|
+
if (port !== DEFAULT_PORT) {
|
|
41
|
+
t.plugins = t.plugins || {}; t.plugins.entries = t.plugins.entries || {};
|
|
42
|
+
t.plugins.entries[PLUGIN_ID] = { ...(t.plugins.entries[PLUGIN_ID] || {}), config: { ...(t.plugins.entries[PLUGIN_ID]?.config || {}), port } };
|
|
43
|
+
}
|
|
44
|
+
return t;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Mint a fresh EVM wallet into WALLET_KEY_FILE (0600). Needs viem (an optional
|
|
48
|
+
// peer, same as x402 payment itself); returns null when it is not installed so
|
|
49
|
+
// setup can fall back to the card path instead of failing.
|
|
50
|
+
async function generateWallet() {
|
|
51
|
+
try {
|
|
52
|
+
const [{ generatePrivateKey, privateKeyToAccount }] = await Promise.all([import("viem/accounts")]);
|
|
53
|
+
const pk = generatePrivateKey();
|
|
54
|
+
const account = privateKeyToAccount(pk);
|
|
55
|
+
mkdirSync(STATE_DIR(), { recursive: true });
|
|
56
|
+
writeFileSync(WALLET_KEY_FILE(), pk + "\n", { mode: 0o600, flag: "wx" }); // never overwrite an existing key
|
|
57
|
+
try { chmodSync(WALLET_KEY_FILE(), 0o600); } catch { /* best effort */ }
|
|
58
|
+
return { address: account.address };
|
|
59
|
+
} catch (e) {
|
|
60
|
+
if (e?.code === "EEXIST") { try { return { address: (await import("viem/accounts")).privateKeyToAccount(readFileSync(WALLET_KEY_FILE(), "utf8").trim()).address }; } catch { return null; } }
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function main() {
|
|
66
|
+
if (cmd === "help" || has("--help")) {
|
|
67
|
+
out("agent402-model-provider setup [--credits-key a402_...|-] [--no-wallet] [--write] [--flat] | proxy [--port N] [--upstream URL] [--flat] | wallet [--rpc URL] | doctor | permit2-approve [--rpc URL]");
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
const upstream = stripTrailingSlashes(opt("--upstream") || process.env.AGENT402_UPSTREAM || DEFAULT_UPSTREAM);
|
|
71
|
+
const port = Number(opt("--port")) || DEFAULT_PORT;
|
|
72
|
+
// Pricing: metered by default (explicit models pay a per-request quote, from
|
|
73
|
+
// $0.001); --flat (or AGENT402_PRICING=flat) keeps every model on its flat tier.
|
|
74
|
+
const pricing = has("--flat") || String(process.env.AGENT402_PRICING || "").toLowerCase() === "flat" ? "flat" : "metered";
|
|
75
|
+
|
|
76
|
+
if (cmd === "setup") {
|
|
77
|
+
// The key may arrive on argv (lands in shell history), via AGENT402_CREDITS_KEY,
|
|
78
|
+
// or on stdin with `--credits-key -` (the form the docs recommend).
|
|
79
|
+
let key = (opt("--credits-key") || "").trim();
|
|
80
|
+
if (key === "-") key = readFileSync(0, "utf8").trim();
|
|
81
|
+
if (!key && process.env.AGENT402_CREDITS_KEY && !has("--no-env")) key = process.env.AGENT402_CREDITS_KEY.trim();
|
|
82
|
+
if (key) {
|
|
83
|
+
if (!/^a402_[A-Za-z0-9_-]{16,80}$/.test(key)) { console.error("that does not look like an Agent402 credits key (a402_...)"); return 2; }
|
|
84
|
+
mkdirSync(STATE_DIR(), { recursive: true });
|
|
85
|
+
writeFileSync(CREDITS_KEY_FILE(), key + "\n", { mode: 0o600 });
|
|
86
|
+
try { chmodSync(CREDITS_KEY_FILE(), 0o600); } catch { /* best effort */ }
|
|
87
|
+
out(`stored credits key at ${CREDITS_KEY_FILE()} (0600)`);
|
|
88
|
+
} else if (!resolveCreditsKey() && !resolveWalletKey()) {
|
|
89
|
+
// No payment method at all: mint a wallet right here, print the address,
|
|
90
|
+
// and the user funds it with USDC on Base. Same first-run shape as a
|
|
91
|
+
// per-token router that prints a wallet at install; the card path
|
|
92
|
+
// (credits key) stays available. --no-wallet keeps the old behaviour.
|
|
93
|
+
if (has("--no-wallet")) {
|
|
94
|
+
out(`no payment method yet: set AGENT402_WALLET_KEY, rerun without --no-wallet to generate a wallet, or rerun with --credits-key a402_... if you hold a credits key`);
|
|
95
|
+
} else {
|
|
96
|
+
const w = await generateWallet();
|
|
97
|
+
if (w) {
|
|
98
|
+
out(`no credits key found, so a wallet was generated for you:`);
|
|
99
|
+
out(` address: ${w.address}`);
|
|
100
|
+
out(` key: ${WALLET_KEY_FILE()} (0600; back it up, it is the only copy)`);
|
|
101
|
+
out(`fund it with USDC on Base (any amount; a call costs from $0.001), then every call is paid from it over x402.`);
|
|
102
|
+
out(`optional: \`agent402-model-provider permit2-approve\` once (needs a little ETH on Base for gas) to pay actual usage instead of the per-request quote.`);
|
|
103
|
+
out(`holding a credits key? rerun with --credits-key a402_... instead`);
|
|
104
|
+
} else {
|
|
105
|
+
out(`no payment method yet: install viem + @x402/fetch + @x402/evm and rerun to generate a wallet, set AGENT402_WALLET_KEY, or rerun with --credits-key a402_... if you hold a credits key`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let routes;
|
|
110
|
+
try { routes = await loadRoutes(upstream, fetch, { pricing }); } catch (e) { console.error(`could not read ${upstream}/v1/models: ${e?.message || e}`); return 2; }
|
|
111
|
+
const block = configBlock({ port, routes });
|
|
112
|
+
const primary = block.agents.defaults.model.primary;
|
|
113
|
+
if (primary === `${PROVIDER_ID}/${AUTO_ID}`) {
|
|
114
|
+
console.error(`WARNING: no model in this catalog (${pricing} pricing) accepts the ~${Math.round(OPENCLAW_MIN_INPUT_CHARS / 1000)}k chars OpenClaw sends before your first word; primary falls back to ${primary}, which will answer "Context overflow" on every turn. Rerun without --flat to use the metered route.`);
|
|
115
|
+
}
|
|
116
|
+
const cfgPath = join(process.env.AGENT402_OPENCLAW_HOME || join(homedir(), ".openclaw"), "openclaw.json");
|
|
117
|
+
if (has("--write")) {
|
|
118
|
+
let existing = {};
|
|
119
|
+
if (existsSync(cfgPath)) {
|
|
120
|
+
try { existing = JSON.parse(readFileSync(cfgPath, "utf8")); }
|
|
121
|
+
catch { console.error(`${cfgPath} is not plain JSON (JSON5 comments?); not touching it. Merge this block by hand:`); out(JSON.stringify(block, null, 2)); return 2; }
|
|
122
|
+
}
|
|
123
|
+
mkdirSync(join(cfgPath, ".."), { recursive: true });
|
|
124
|
+
// Preserve the file's mode (openclaw.json holds other providers' keys and
|
|
125
|
+
// is often 0600); a fresh file is created 0600. Never loosen it.
|
|
126
|
+
let mode = 0o600;
|
|
127
|
+
try { if (existsSync(cfgPath)) mode = statSync(cfgPath).mode & 0o777; } catch { /* keep 0600 */ }
|
|
128
|
+
const tmp = `${cfgPath}.${process.pid}.tmp`;
|
|
129
|
+
writeFileSync(tmp, JSON.stringify(mergeInto(existing, block, { port }), null, 2) + "\n", { mode });
|
|
130
|
+
try { chmodSync(tmp, mode); } catch { /* best effort */ }
|
|
131
|
+
renameSync(tmp, cfgPath);
|
|
132
|
+
out(`wrote provider "${PROVIDER_ID}" + primary model ${primary} into ${cfgPath}; run: openclaw gateway restart`);
|
|
133
|
+
} else {
|
|
134
|
+
out(`add to ${cfgPath} (or rerun with --write):`);
|
|
135
|
+
out(JSON.stringify(block, null, 2));
|
|
136
|
+
}
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (cmd === "proxy") {
|
|
141
|
+
const creditsKey = resolveCreditsKey();
|
|
142
|
+
const payFetch = creditsKey ? null : await resolvePayFetch({}, (m) => console.error(m));
|
|
143
|
+
const p = await startProxy({ upstream, creditsKey, payFetch, port, pricing, log: (m) => console.error(m) });
|
|
144
|
+
out(`${p.baseUrl}/v1 (${p.mode}, ${p.pricing} pricing)`);
|
|
145
|
+
await new Promise(() => {}); // run until killed
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// One-time USDC -> Permit2 approval on Base so the wallet can pay ACTUAL
|
|
149
|
+
// usage over `upto` instead of the per-request quote over `exact`.
|
|
150
|
+
if (cmd === "permit2-approve") {
|
|
151
|
+
const pk = resolveWalletKey();
|
|
152
|
+
if (!pk) { console.error("no wallet: set AGENT402_WALLET_KEY (0x + 64 hex) or run `agent402-model-provider setup` to generate one"); return 2; }
|
|
153
|
+
try {
|
|
154
|
+
const [{ createPermit2ApprovalTx, getPermit2AllowanceReadParams }, { createWalletClient, createPublicClient, http }, { privateKeyToAccount }, { base }] = await Promise.all([import("@x402/evm/upto/client"), import("viem"), import("viem/accounts"), import("viem/chains")]);
|
|
155
|
+
const account = privateKeyToAccount(pk);
|
|
156
|
+
const rpc = (opt("--rpc") || process.env.AGENT402_BASE_RPC || DEFAULT_BASE_RPC).trim();
|
|
157
|
+
const pub = createPublicClient({ chain: base, transport: http(rpc) });
|
|
158
|
+
const read = () => pub.readContract(getPermit2AllowanceReadParams({ tokenAddress: USDC_BASE, ownerAddress: account.address }));
|
|
159
|
+
if (uptoReady(await read())) { out(`already approved: ${account.address} has a Permit2 allowance on USDC (Base); the proxy pays actual usage (upto)`); return 0; }
|
|
160
|
+
const tx = createPermit2ApprovalTx(USDC_BASE);
|
|
161
|
+
const wallet = createWalletClient({ account, chain: base, transport: http(rpc) });
|
|
162
|
+
const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data });
|
|
163
|
+
out(`approval sent: ${hash} (waiting for confirmation)`);
|
|
164
|
+
await pub.waitForTransactionReceipt({ hash, timeout: 120_000 });
|
|
165
|
+
out(uptoReady(await read()) ? `approved: ${account.address} can now pay actual usage over upto. Restart the gateway.` : "transaction confirmed but the allowance still reads low - check the wallet on basescan");
|
|
166
|
+
return 0;
|
|
167
|
+
} catch (e) { console.error(`permit2-approve failed: ${String(e?.message || e).slice(0, 300)}`); return 1; }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Address + USDC balance of the wallet the proxy pays from. Read-only.
|
|
171
|
+
if (cmd === "wallet") {
|
|
172
|
+
const pk = resolveWalletKey();
|
|
173
|
+
if (!pk) { console.error("no wallet: run `agent402-model-provider setup` to generate one, or set AGENT402_WALLET_KEY"); return 2; }
|
|
174
|
+
try {
|
|
175
|
+
const [{ createPublicClient, http, erc20Abi, formatUnits }, { privateKeyToAccount }, { base }] = await Promise.all([import("viem"), import("viem/accounts"), import("viem/chains")]);
|
|
176
|
+
const account = privateKeyToAccount(pk);
|
|
177
|
+
const pub = createPublicClient({ chain: base, transport: http((opt("--rpc") || process.env.AGENT402_BASE_RPC || DEFAULT_BASE_RPC).trim()) });
|
|
178
|
+
const bal = await pub.readContract({ address: USDC_BASE, abi: erc20Abi, functionName: "balanceOf", args: [account.address] });
|
|
179
|
+
out(`address: ${account.address}`);
|
|
180
|
+
out(`USDC on Base: $${formatUnits(bal, 6)}`);
|
|
181
|
+
if (bal === 0n) out(`fund it: send USDC on Base (eip155:8453) to ${account.address}`);
|
|
182
|
+
return 0;
|
|
183
|
+
} catch (e) { console.error(`wallet: ${String(e?.message || e).slice(0, 200)}`); return 1; }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (cmd === "doctor") {
|
|
187
|
+
const key = resolveCreditsKey();
|
|
188
|
+
const walletPk = resolveWalletKey();
|
|
189
|
+
out(`upstream: ${upstream}`);
|
|
190
|
+
out(`credits key: ${key ? "present" : "none"}`);
|
|
191
|
+
out(`wallet key: ${walletPk ? "present" : "none"}`);
|
|
192
|
+
if (walletPk) {
|
|
193
|
+
try {
|
|
194
|
+
const [{ getPermit2AllowanceReadParams }, { createPublicClient, http }, { privateKeyToAccount }, { base }] = await Promise.all([import("@x402/evm/upto/client"), import("viem"), import("viem/accounts"), import("viem/chains")]);
|
|
195
|
+
const account = privateKeyToAccount(walletPk);
|
|
196
|
+
const pub = createPublicClient({ chain: base, transport: http((process.env.AGENT402_BASE_RPC || DEFAULT_BASE_RPC).trim()) });
|
|
197
|
+
const allowance = await pub.readContract(getPermit2AllowanceReadParams({ tokenAddress: USDC_BASE, ownerAddress: account.address }));
|
|
198
|
+
out(`wallet ${account.address}: ${uptoReady(allowance) ? "pays actual usage (upto; Permit2 approved)" : "pays the per-request quote (exact) - run permit2-approve once to pay actual usage"}`);
|
|
199
|
+
} catch (e) { out(`wallet: allowance unreadable (${String(e?.message || e).slice(0, 80)})`); }
|
|
200
|
+
}
|
|
201
|
+
try { const r = await loadRoutes(upstream, fetch, { pricing }); out(`gateway: ok, ${r.size} models (${pricing} pricing: ${[...r.values()].filter((x) => x.metered).length} metered)`); } catch (e) { out(`gateway: unreachable (${e?.message || e})`); return 1; }
|
|
202
|
+
if (key) {
|
|
203
|
+
try {
|
|
204
|
+
const r = await fetch(`${upstream}/api/credits/balance`, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) });
|
|
205
|
+
const j = await r.json().catch(() => ({}));
|
|
206
|
+
out(`balance: ${r.ok ? `$${j.balanceUsd ?? j.balance ?? "?"}` : `HTTP ${r.status} ${j.reason || j.error || ""}`}`);
|
|
207
|
+
} catch (e) { out(`balance: unreadable (${e?.message || e})`); }
|
|
208
|
+
}
|
|
209
|
+
return 0;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
console.error(`unknown command: ${cmd}`); return 2;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Entry guard that survives npm's bin SYMLINK and paths with spaces: Node
|
|
216
|
+
// resolves import.meta.url to the real path but leaves process.argv[1] as the
|
|
217
|
+
// symlink, so a plain string compare is false for every `npx`/global install
|
|
218
|
+
// and the CLI silently did nothing (0.1.0 and 0.1.1 shipped that way).
|
|
219
|
+
function invokedDirectly() {
|
|
220
|
+
try { return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; } catch { return false; }
|
|
221
|
+
}
|
|
222
|
+
if (invokedDirectly()) {
|
|
223
|
+
main().then((c) => process.exit(c ?? 0), (e) => { console.error(e?.message || e); process.exit(1); });
|
|
224
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Type declarations for agent402-model-provider, the OpenClaw model provider
|
|
2
|
+
// plugin. The runtime is index.js (plain ES modules); these declarations
|
|
3
|
+
// describe its public API. The x402 packages it can pay with are optional
|
|
4
|
+
// peers and are typed loosely here.
|
|
5
|
+
import type { ProxyOptions, RunningProxy } from "./proxy.js";
|
|
6
|
+
import type { OpenClawModel } from "./models.js";
|
|
7
|
+
|
|
8
|
+
export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
9
|
+
|
|
10
|
+
/** The plugin's config block in OpenClaw. */
|
|
11
|
+
export interface Agent402PluginConfig {
|
|
12
|
+
walletKey?: string;
|
|
13
|
+
creditsKey?: string;
|
|
14
|
+
/** Ceiling on one paid call in USD (default 5); 0 or "off" turns it off. */
|
|
15
|
+
maxPerCallUsd?: number | string;
|
|
16
|
+
allowUncappedPayments?: boolean | string;
|
|
17
|
+
baseRpc?: string;
|
|
18
|
+
port?: number;
|
|
19
|
+
upstream?: string;
|
|
20
|
+
pricing?: "metered" | "flat";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** One accept of an x402 402 answer. */
|
|
24
|
+
export interface PaymentAccept {
|
|
25
|
+
scheme?: string;
|
|
26
|
+
network?: string;
|
|
27
|
+
asset?: string;
|
|
28
|
+
amount?: string;
|
|
29
|
+
maxAmountRequired?: string;
|
|
30
|
+
maxTimeoutSeconds?: number;
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface KnownAsset { asset: string; decimals: number; symbol: string; name?: string; version?: string }
|
|
35
|
+
export const KNOWN_ASSETS: Readonly<Record<string, KnownAsset[]>>;
|
|
36
|
+
export const MAX_VALIDITY_SECONDS: number;
|
|
37
|
+
/** The base-unit amount the signer of `x402Version` signs for one accept, or null. */
|
|
38
|
+
export function acceptAmount(accept: PaymentAccept, x402Version?: number): string | null;
|
|
39
|
+
/** The USD value of one accept over the known decimals of its asset, or null. */
|
|
40
|
+
export function acceptUsd(accept: PaymentAccept, x402Version?: number): number | null;
|
|
41
|
+
/** Why a created payment payload stays redeemable too long, or null. */
|
|
42
|
+
export function signedValidityProblem(paymentPayload: unknown, opts?: { maxSeconds?: number; nowMs?: number }): string | null;
|
|
43
|
+
/** Why a signed payment does not match the priced option or the cap, or null. */
|
|
44
|
+
export function signedPaymentProblem(paymentPayload: unknown, requirements: PaymentAccept, x402Version: number, cap?: number): Promise<string | null>;
|
|
45
|
+
|
|
46
|
+
export const STATE_DIR: () => string;
|
|
47
|
+
export const CREDITS_KEY_FILE: () => string;
|
|
48
|
+
export const WALLET_KEY_FILE: () => string;
|
|
49
|
+
export function resolveWalletKey(pluginConfig?: Agent402PluginConfig): string | null;
|
|
50
|
+
export function resolveCreditsKey(pluginConfig?: Agent402PluginConfig): string | null;
|
|
51
|
+
|
|
52
|
+
export const USDC_BASE: string;
|
|
53
|
+
export const BASE_CAIP2: string;
|
|
54
|
+
export const DEFAULT_BASE_RPC: string;
|
|
55
|
+
export const PERMIT2_READY_MIN: bigint;
|
|
56
|
+
/** The default per-call ceiling in USD. */
|
|
57
|
+
export const DEFAULT_MAX_PER_CALL_USD: number;
|
|
58
|
+
export function uncappedAcknowledged(pluginConfig?: Agent402PluginConfig): boolean;
|
|
59
|
+
/** Kept for callers of earlier releases; always false. */
|
|
60
|
+
export const uncappedRefused: () => false;
|
|
61
|
+
/** The per-call ceiling in USD; Infinity when turned off. */
|
|
62
|
+
export function maxPerCallUsd(pluginConfig?: Agent402PluginConfig): number;
|
|
63
|
+
/** A one-line warning when the configured ceiling does not parse, else null. */
|
|
64
|
+
export function maxPerCallProblem(pluginConfig?: Agent402PluginConfig): string | null;
|
|
65
|
+
/** Which accept to pay; throws (nothing signed) when it is over the ceiling or cannot be priced. */
|
|
66
|
+
export function selectAccept(accepts: PaymentAccept[], opts?: { preferUpto?: boolean; maxUsd?: number; x402Version?: number }): PaymentAccept | undefined;
|
|
67
|
+
export function uptoReady(allowance: unknown): boolean;
|
|
68
|
+
/** An x402-paying fetch for the configured wallet key, or null (no key, or the optional x402 packages are missing). */
|
|
69
|
+
export function resolvePayFetch(pluginConfig?: Agent402PluginConfig, log?: (message: string) => void): Promise<FetchLike | null>;
|
|
70
|
+
|
|
71
|
+
/** The OpenClaw provider registration. */
|
|
72
|
+
export interface Agent402Provider {
|
|
73
|
+
id: string;
|
|
74
|
+
label: string;
|
|
75
|
+
docsPath: string;
|
|
76
|
+
aliases: string[];
|
|
77
|
+
envVars: string[];
|
|
78
|
+
readonly models: { baseUrl: string; api: "openai-completions"; models: OpenClawModel[] };
|
|
79
|
+
auth: unknown[];
|
|
80
|
+
}
|
|
81
|
+
export function buildProvider(opts?: { port?: number }): Agent402Provider;
|
|
82
|
+
export function startProxy(opts?: ProxyOptions): Promise<RunningProxy>;
|
|
83
|
+
|
|
84
|
+
/** The OpenClaw plugin object (its loader calls register). */
|
|
85
|
+
export interface Agent402Plugin {
|
|
86
|
+
id: string;
|
|
87
|
+
name: string;
|
|
88
|
+
description: string;
|
|
89
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
90
|
+
register(api: any): void;
|
|
91
|
+
}
|
|
92
|
+
export const plugin: Agent402Plugin;
|
|
93
|
+
export default plugin;
|