agent402-action-provider 0.0.0-stage → 0.3.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/index.d.ts +54 -0
  4. package/index.js +279 -0
  5. package/package.json +69 -4
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,101 @@
1
- # Temporary Holding Version
1
+ # agent402-action-provider
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Agent402](https://agent402.tools) as an **action provider** for use with
4
+ [AgentKit](https://github.com/coinbase/agentkit): give an agent with a CDP, Privy, ZeroDev or viem-backed
5
+ wallet 500+ pay-per-call web tools through three actions, paying under the
6
+ hood over x402 in USDC from the agent's own wallet; the pure-CPU tools are
7
+ free via proof-of-work.
8
+
9
+ Works with AgentKit (`@coinbase/agentkit`). Agent402 is not affiliated with or endorsed by Coinbase.
10
+
11
+ Formerly `agent402-agentkit`: the same API under a new name. Change the dependency and the import specifier; nothing else changes.
12
+
13
+ > **Agent402 is the applied layer of [Agentic Finance](https://agent402.tools/agentic-finance)** - agents that pay and get paid on their own over the two open wires, [x402](https://x402.org) and MPP.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install agent402-action-provider @coinbase/agentkit @x402/fetch @x402/evm zod
19
+ ```
20
+
21
+ ## Use
22
+
23
+ ```ts
24
+ import { AgentKit, CdpEvmWalletProvider } from "@coinbase/agentkit";
25
+ import { agent402ActionProvider } from "agent402-action-provider";
26
+
27
+ const walletProvider = await CdpEvmWalletProvider.configureWithWallet({
28
+ apiKeyId: process.env.CDP_API_KEY_ID,
29
+ apiKeySecret: process.env.CDP_API_KEY_SECRET,
30
+ walletSecret: process.env.CDP_WALLET_SECRET,
31
+ networkId: "base-mainnet",
32
+ });
33
+
34
+ const agentKit = await AgentKit.from({
35
+ walletProvider,
36
+ actionProviders: [await agent402ActionProvider()],
37
+ });
38
+ // hand agentKit.getActions() to your framework (LangChain, Vercel AI SDK, ...)
39
+ ```
40
+
41
+ The agent now has:
42
+
43
+ | Action | Wallet | What it does |
44
+ |---|---|---|
45
+ | `agent402_find` | no | Resolve a task to the best-matching tools: slug, price, whether a wallet is needed, a ready example. Free. |
46
+ | `agent402_call` | yes | Call a tool by slug with its input. Free-tier tools are paid with a few seconds of proof-of-work; wallet-only tools are paid over x402 in USDC on Base, signed by the wallet provider. Returns the tool's JSON. |
47
+ | `agent402_about` | no | What Agent402 is, how it is paid, live tool counts. Free. |
48
+
49
+ The x402 signer is derived from the wallet provider the same way AgentKit's own
50
+ x402 action provider derives it (`toSigner()` plus `readContract`), so CDP,
51
+ Privy, ZeroDev and viem-backed wallets all work (proven live with viem).
52
+ Live-proven 2026-08-27 against production: a `ViemWalletProvider` over a
53
+ funded Base wallet ran `agent402_find` then `agent402_call` on a wallet-only
54
+ tool and paid $0.002 over x402 ([transaction](https://basescan.org/tx/0x1c0592f73d1f9182ee9bd40eb34d9b6c70b3196814b111589b82df4e79e7fb59)).
55
+
56
+ Hosts that wrap actions themselves can take the raw list:
57
+
58
+ ```js
59
+ import { agent402Actions } from "agent402-action-provider";
60
+ const actions = await agent402Actions(); // [{ name, description, schema, invoke }]
61
+ ```
62
+
63
+ ## Example: buy data, ship it to Base
64
+
65
+ [`examples/agentkit-data-to-deploy`](https://github.com/MikeyPetrillo/Agent402/tree/main/examples/agentkit-data-to-deploy)
66
+ is one script on one wallet: `agent402_call` buys the live ETH price over x402
67
+ (`crypto-price`), then `walletProvider.sendTransaction` deploys a contract to Base
68
+ mainnet that stores the price and the payment transaction hash. Proven from CI
69
+ against production.
70
+
71
+ ## Options and spend bounds
72
+
73
+ `agent402ActionProvider({ baseUrl, fetchImpl, zod, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, payees })`
74
+
75
+ - `maxPerCallUsd` (default `5`, which covers every fixed price in the
76
+ catalog): a paid call above this is refused before any signature, and the
77
+ error names the price, the ceiling and how to raise it. `0` or `"off"` turns
78
+ it off; a value that is not a USD amount keeps the default and is named on
79
+ stderr. `dailyLimitUsd` and `maxPerHostUsd` are opt-in and bound rolling
80
+ 24-hour spend.
81
+ The caps are enforced on the payment that is signed, priced from the known
82
+ decimals of its asset, so a 402 that changes between the preflight and the
83
+ paid request is held to them too.
84
+ - `payees`: an allowlist of `payTo` addresses; a 402 naming any other address
85
+ is refused before signing, so a mis-set `baseUrl` cannot spend the wallet.
86
+ - `baseUrl` for a self-hosted Agent402, `fetchImpl` to inject a fetch, `zod` to
87
+ pass the host's zod module.
88
+
89
+ ## What Agent402 serves
90
+
91
+ Web search, news and cited answers, browser render and screenshots, PDFs and
92
+ OCR, live market and crypto data, SEC filings, DNS and TLS checks, a code
93
+ sandbox, wallet-keyed memory, finished reports, and an OpenAI-compatible model
94
+ gateway. Most tools are deterministic code; the model gateway, the reports and
95
+ the media, embedding and answer tools are model-backed (`modelBacked` on
96
+ `/api/pricing`). Prices are per call; the live list is `/api/pricing`. Catalog:
97
+ https://agent402.tools/tools · agent-readable docs: https://agent402.tools/llms.txt
98
+
99
+ MIT. Maintained by Havok Holdings LLC.
100
+
101
+ Spend ceilings (`maxPerCallUsd`, `dailyLimitUsd`, `maxPerHostUsd`) are measured against one client per wallet provider for the life of the actions, so the daily ceiling holds across calls. `creditsKey` (a prepaid `a402_...` key) pays wallet-only tools without a wallet.
package/index.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ // Type declarations for agent402-action-provider. The runtime is index.js (plain ES
2
+ // modules on agent402-client); these declarations describe its public API.
3
+ // AgentKit, zod and the wallet provider are typed loosely, so the
4
+ // declarations import nothing from those peers.
5
+
6
+ /** An AgentKit wallet provider (an EVM one that can sign typed data), typed loosely. */
7
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
8
+ export type WalletProviderLike = any;
9
+
10
+ export interface Agent402ActionOptions {
11
+ /** Default "https://agent402.tools". */
12
+ baseUrl?: string;
13
+ /** Fetch used for free discovery and as the base of the paying fetch (default: the global fetch). */
14
+ fetchImpl?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
15
+ /** A zod module (loaded from the host when omitted). */
16
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ zod?: any;
18
+ /** Ceiling on one paid call in USD (default 5); 0 or "off" turns it off; a value that does not parse keeps the default. */
19
+ maxPerCallUsd?: number | string | null;
20
+ /** Ceiling on rolling 24-hour paid spend in USD (opt-in). */
21
+ dailyLimitUsd?: number | null;
22
+ /** Ceiling on rolling 24-hour paid spend to one seller host in USD (opt-in). */
23
+ maxPerHostUsd?: number | null;
24
+ /** Only pay these payTo addresses (lowercased EVM); anything else is refused before signing. */
25
+ payees?: string[] | null;
26
+ /** A prepaid credits key (a402_...). */
27
+ creditsKey?: string | null;
28
+ }
29
+
30
+ /** One AgentKit action: its zod schema and an invoke that resolves to text. */
31
+ export interface Agent402Action {
32
+ name: "agent402_find" | "agent402_call" | "agent402_about";
33
+ description: string;
34
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
+ schema: any;
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ invoke(...args: any[]): Promise<string>;
38
+ }
39
+
40
+ /** The default per-call ceiling in USD. */
41
+ export const DEFAULT_MAX_PER_CALL_USD: number;
42
+ /** The ceiling agent402-client gets for a setting: the default when unset, null for 0 or "off". */
43
+ export function resolveMaxPerCallUsd(v: unknown, warn?: (message: string) => void): number | null;
44
+ /** The three actions as plain objects. */
45
+ export function agent402Actions(opts?: Agent402ActionOptions): Promise<Agent402Action[]>;
46
+ /** An AgentKit action provider holding the three actions (needs @coinbase/agentkit). */
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ export function agent402ActionProvider(opts?: Agent402ActionOptions): Promise<any>;
49
+ /** An x402-paying fetch for an AgentKit wallet provider, or undefined when the provider cannot sign. */
50
+ export function payFetchFor(
51
+ walletProvider: WalletProviderLike,
52
+ fetchImpl?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>,
53
+ opts?: { payees?: string[] | null },
54
+ ): Promise<((input: string | URL | Request, init?: RequestInit) => Promise<Response>) | undefined>;
package/index.js ADDED
@@ -0,0 +1,279 @@
1
+ // agent402-action-provider (formerly agent402-agentkit): Agent402 as an action
2
+ // provider for use with AgentKit.
3
+ //
4
+ // Gives an AgentKit agent (a CDP, Privy, ZeroDev or viem-backed wallet
5
+ // provider) three actions over the Agent402 catalog: find a tool for a
6
+ // task, call it (paying under the hood), and read what Agent402 is. Payment
7
+ // is handled by agent402-client: a few seconds of proof-of-work for the free
8
+ // tier, or an x402 USDC payment on Base signed by the agent's own wallet
9
+ // provider for wallet-only tools. The signer is derived the same way
10
+ // AgentKit's own x402 action provider derives it (toSigner + readContract).
11
+ //
12
+ // import { AgentKit, CdpEvmWalletProvider } from "@coinbase/agentkit";
13
+ // import { agent402ActionProvider } from "agent402-action-provider";
14
+ //
15
+ // const walletProvider = await CdpEvmWalletProvider.configureWithWallet({ networkId: "base-mainnet" });
16
+ // const agentKit = await AgentKit.from({ walletProvider, actionProviders: [await agent402ActionProvider()] });
17
+ //
18
+ // `agent402Actions()` returns the raw { name, description, schema, invoke }
19
+ // list for hosts that wrap actions themselves; `agent402ActionProvider()`
20
+ // wraps them with AgentKit's customActionProvider.
21
+
22
+ import { Agent402 } from "agent402-client";
23
+
24
+ const DEFAULT_BASE = "https://agent402.tools";
25
+ // Keep in lockstep with package.json: the User-Agent product token that names
26
+ // this package on every call it sends.
27
+ const USER_AGENT = "agent402-action-provider/0.3.0";
28
+
29
+ // Discovery reads (catalog, find, route, manifest, a proof-of-work challenge)
30
+ // settle nothing, so a 503 the server sheds under load is safe to repeat. It
31
+ // is retried only when it names its own delay (a Retry-After header or a
32
+ // retryAfterSeconds body field), at most DISCOVERY_ATTEMPTS tries in all,
33
+ // each wait capped at DISCOVERY_MAX_WAIT_MS. A paid call never goes through
34
+ // here: a repeat of one could settle twice.
35
+ const DISCOVERY_ATTEMPTS = 3;
36
+ const DISCOVERY_MAX_WAIT_MS = 5000;
37
+
38
+ async function shedRetryWaitMs(r) {
39
+ if (!r || r.status !== 503) return null;
40
+ const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
41
+ let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
42
+ if (!Number.isFinite(seconds)) {
43
+ try {
44
+ const body = await (typeof r.clone === "function" ? r.clone() : r).json();
45
+ seconds = Number(body && body.retryAfterSeconds);
46
+ } catch { seconds = NaN; }
47
+ }
48
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
49
+ return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
50
+ }
51
+
52
+ // Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
53
+ // "after N attempts" when it retried, and the server's `error` text) with
54
+ // `.status`, `.body` and `.attempts` set.
55
+ // `init` may be a function, so each attempt gets its own timeout signal.
56
+ async function discoveryFetch(fetchImpl, label, url, init) {
57
+ let r;
58
+ let attempts = 0;
59
+ for (;;) {
60
+ attempts++;
61
+ const i = (typeof init === "function" ? init() : init) || {};
62
+ r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
63
+ if (r.ok) return r;
64
+ if (attempts >= DISCOVERY_ATTEMPTS) break;
65
+ const wait = await shedRetryWaitMs(r);
66
+ if (wait == null) break;
67
+ await new Promise((resolve) => setTimeout(resolve, wait));
68
+ }
69
+ const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
70
+ err.attempts = attempts;
71
+ throw err;
72
+ }
73
+
74
+ // The server's own answer to a failed request, on the thrown error: its
75
+ // `error` text joins the message, and `.status` and `.body` (the parsed JSON,
76
+ // else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
77
+ // why the call failed (a refusal, a limit, a missing parameter).
78
+ const ERROR_BODY_MAX = 4000;
79
+ async function responseError(message, r) {
80
+ let text = "";
81
+ try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
82
+ text = text.slice(0, ERROR_BODY_MAX);
83
+ let body = null;
84
+ try { body = text ? JSON.parse(text) : null; } catch { body = null; }
85
+ const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
86
+ const err = new Error(said ? `${message}: ${said}` : message);
87
+ err.status = r?.status;
88
+ err.body = body ?? (text || null);
89
+ return err;
90
+ }
91
+
92
+ /** Default per-call ceiling in USD: it covers every fixed price in the Agent402
93
+ * catalog, so it protects the wallet without refusing a listed tool. */
94
+ export const DEFAULT_MAX_PER_CALL_USD = 5;
95
+ /** The per-call ceiling agent402-client gets: the default when unset, null (no
96
+ * ceiling) for 0 or "off", the amount for a USD number. A value that does not
97
+ * parse (text, negative, NaN, empty) keeps the default and is named once on
98
+ * stderr, so a typo never removes the ceiling. */
99
+ export function resolveMaxPerCallUsd(v, warn = (m) => console.error(m)) {
100
+ if (v === undefined || v === null) return DEFAULT_MAX_PER_CALL_USD;
101
+ const raw = String(v).trim().toLowerCase();
102
+ if (raw === "off") return null;
103
+ const n = raw === "" ? NaN : Number(raw);
104
+ if (Number.isFinite(n) && n >= 0) return n === 0 ? null : n;
105
+ const shown = String(v).length <= 16 ? JSON.stringify(String(v)) : "(a long value, not shown)";
106
+ warn(`[agent402-action-provider] maxPerCallUsd=${shown} is not a USD amount, 0 or "off"; keeping the default $${DEFAULT_MAX_PER_CALL_USD} per-call ceiling`);
107
+ return DEFAULT_MAX_PER_CALL_USD;
108
+ }
109
+
110
+ /**
111
+ * The three actions, as plain AgentKit custom-action definitions.
112
+ * @param {object} [opts]
113
+ * @param {string} [opts.baseUrl="https://agent402.tools"]
114
+ * @param {typeof fetch} [opts.fetchImpl] fetch used for free discovery and as the base of the paying fetch
115
+ * @param {object} [opts.zod] a zod module (loaded from the host when omitted)
116
+ * @param {number|string} [opts.maxPerCallUsd=5] ceiling on one paid call (USD); over it the call is refused before paying. 0 or "off" turns it off; a value that does not parse keeps the default and is named on stderr
117
+ * @param {number} [opts.dailyLimitUsd] ceiling on rolling-24h paid spend (USD)
118
+ * @param {number} [opts.maxPerHostUsd] ceiling on rolling-24h paid spend to one seller host (USD)
119
+ * @param {string[]} [opts.payees] only pay these payTo addresses (lowercased EVM); anything else is refused before signing
120
+ * @param {string} [opts.creditsKey] prepaid credits key (a402_...); pays wallet-only tools on Agent402's own services without a wallet
121
+ */
122
+ export async function agent402Actions({ baseUrl = DEFAULT_BASE, fetchImpl = globalThis.fetch, zod, maxPerCallUsd: maxPerCallSetting, dailyLimitUsd = null, maxPerHostUsd = null, payees = null, creditsKey = null } = {}) {
123
+ const maxPerCallUsd = resolveMaxPerCallUsd(maxPerCallSetting);
124
+ const z = zod || (await loadZod());
125
+ // ONE client per wallet provider for the life of these actions. The rolling
126
+ // daily and per-host ceilings live in the client's ledger, so a client built
127
+ // per invoke (as 0.1.1 did) measured every call against an empty ledger and
128
+ // the daily ceiling bounded each call alone (found in the elizaOS plugin's
129
+ // registry review, 2026-09-14; the same shape was here).
130
+ const clients = new WeakMap();
131
+ const NO_WALLET = {};
132
+ const clientFor = async (walletProvider) => {
133
+ const key = walletProvider && typeof walletProvider === "object" ? walletProvider : NO_WALLET;
134
+ if (clients.has(key)) return clients.get(key);
135
+ // The x402 client is handed to agent402-client too, which holds every
136
+ // payment it signs to the ceilings below (guardX402Client).
137
+ const paying = creditsKey ? null : await x402For(walletProvider, fetchImpl, { payees, guarded: true });
138
+ const client = new Agent402({ userAgent: USER_AGENT, baseUrl: base, fetch: paying?.payFetch, x402Client: paying?.client, fetchImpl, creditsKey, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd });
139
+ clients.set(key, client);
140
+ return client;
141
+ };
142
+ // Linear trailing-slash strip (a /\/+$/ regex on caller input is the
143
+ // polynomial-ReDoS shape CodeQL flags; same fix as openclaw/models.js).
144
+ let base = String(baseUrl);
145
+ while (base.endsWith("/")) base = base.slice(0, -1);
146
+
147
+ const find = {
148
+ name: "agent402_find",
149
+ description:
150
+ "Find an Agent402 tool for a task (web search, page render, PDFs, OCR, market and crypto data, SEC filings, DNS/TLS " +
151
+ "checks), payable over x402 in USDC or free via proof-of-work. Returns the best-matching tools with slug, price, " +
152
+ "whether a wallet is needed, and a ready example. Free: no payment is made.",
153
+ schema: z.object({
154
+ task: z.string().min(1).describe("What you need done, in your own words, e.g. 'extract the article at a URL'"),
155
+ k: z.number().int().min(1).max(10).optional().describe("How many matches to return (default 5)"),
156
+ }),
157
+ invoke: async ({ task, k = 5 }) => {
158
+ const r = await discoveryFetch(fetchImpl, "agent402_find failed (GET /api/find)", `${base}/api/find?q=${encodeURIComponent(task)}&k=${k}`);
159
+ const j = await r.json();
160
+ const rows = (j.results || []).map((t) => ({
161
+ slug: t.slug, name: t.name, price: t.price, route: t.route, walletRequired: t.computePayable === false || t.walletOnly === true,
162
+ description: t.description, example: t.example ?? t.input ?? null,
163
+ }));
164
+ return JSON.stringify({ query: task, results: rows });
165
+ },
166
+ };
167
+
168
+ const call = {
169
+ name: "agent402_call",
170
+ description:
171
+ "Call an Agent402 tool by slug (from agent402_find) with its input and return the result. Pays for the call: " +
172
+ "proof-of-work for free-tier tools, or an x402 USDC micropayment on Base signed by this wallet for wallet-only tools " +
173
+ "(prices are typically $0.001 to $0.05). The result is the tool's JSON.",
174
+ schema: z.object({
175
+ slug: z.string().min(1).describe("Tool slug, e.g. 'hash', 'extract', 'render'"),
176
+ params: z.record(z.any()).optional().describe("Input matching the tool's example from agent402_find"),
177
+ }),
178
+ invoke: async (walletProvider, { slug, params = {} }) => {
179
+ // Spend bounds ride with every paid call and are checked on the payment
180
+ // that is signed: a per-call ceiling (default $5; 0 or "off" turns it
181
+ // off), optional rolling daily and per-host ceilings and an optional
182
+ // payee allowlist. With a per-call ceiling (the default), no single
183
+ // payment is signed above it, whatever baseUrl is set to; set
184
+ // dailyLimitUsd to bound the total too.
185
+ const client = await clientFor(walletProvider);
186
+ let out;
187
+ try {
188
+ out = await client.call(slug, params);
189
+ } catch (e) {
190
+ // A per-call refusal says how to allow it; the error keeps its type
191
+ // and fields (SpendingLimitError, atSigning, priceUsd, cap).
192
+ if (e?.name === "SpendingLimitError" && (e.limit === "maxPerCallUsd" || e.details?.limit === "maxPerCallUsd") && typeof e.message === "string" && !/set it to 0 or "off"/.test(e.message)) {
193
+ e.message += `; nothing was signed. Raise maxPerCallUsd (default $${DEFAULT_MAX_PER_CALL_USD}), or set it to 0 or "off", to allow it`;
194
+ }
195
+ throw e;
196
+ }
197
+ return typeof out === "string" ? out : JSON.stringify(out);
198
+ },
199
+ };
200
+
201
+ const about = {
202
+ name: "agent402_about",
203
+ description: "What Agent402 is, how it is paid, and how many tools it serves right now. Free.",
204
+ schema: z.object({}),
205
+ invoke: async () => {
206
+ const r = await discoveryFetch(fetchImpl, "agent402_about failed (GET /api/pricing)", `${base}/api/pricing`);
207
+ const p = await r.json();
208
+ const endpoints = p.endpoints || [];
209
+ return JSON.stringify({
210
+ name: "Agent402",
211
+ baseUrl: base,
212
+ tools: endpoints.length,
213
+ freeTier: endpoints.filter((e) => e.computePayable).length,
214
+ pay: "x402 (USDC on Base and other chains) from this wallet, or proof-of-work for free-tier tools; a prepaid credits key, where sold or already issued, also pays on Agent402's own services",
215
+ discover: `${base}/api/find?q=<task>`,
216
+ docs: `${base}/llms.txt`,
217
+ });
218
+ },
219
+ };
220
+
221
+ return [find, call, about];
222
+ }
223
+
224
+ /**
225
+ * An AgentKit ActionProvider carrying the three actions. Requires
226
+ * @coinbase/agentkit in the host project (it is a peer, never bundled).
227
+ */
228
+ export async function agent402ActionProvider(opts = {}) {
229
+ const actions = await agent402Actions(opts);
230
+ let mod;
231
+ try { mod = await import("@coinbase/agentkit"); }
232
+ catch { throw new Error("agent402-action-provider requires '@coinbase/agentkit' - install it with: npm install @coinbase/agentkit"); }
233
+ if (typeof mod.customActionProvider === "function") return mod.customActionProvider(actions);
234
+ if (typeof mod.CustomActionProvider === "function") return new mod.CustomActionProvider(actions);
235
+ throw new Error("@coinbase/agentkit does not expose customActionProvider - upgrade @coinbase/agentkit");
236
+ }
237
+
238
+ /**
239
+ * Build the paying fetch from an AgentKit wallet provider. EVM providers
240
+ * expose toSigner() (a viem account) and readContract(); the exact-EVM x402
241
+ * scheme is registered on it exactly as AgentKit's x402 provider does. A
242
+ * provider without toSigner() (or no provider at all) yields undefined, and
243
+ * agent402-client then pays free-tier tools with proof-of-work only.
244
+ */
245
+ export async function payFetchFor(walletProvider, fetchImpl = globalThis.fetch, { payees = null } = {}) {
246
+ return (await x402For(walletProvider, fetchImpl, { payees, guarded: false }))?.payFetch;
247
+ }
248
+
249
+ /** The x402 client and its paying fetch. `guarded`: agent402-client registers
250
+ * its own signing guard on the client (the caller does that), which replaces
251
+ * the library's default spend control; unguarded (payFetchFor on its own),
252
+ * that default control stays on. */
253
+ async function x402For(walletProvider, fetchImpl, { payees = null, guarded = false } = {}) {
254
+ if (!walletProvider || typeof walletProvider.toSigner !== "function") return null;
255
+ const account = await walletProvider.toSigner();
256
+ if (!account || typeof account.signTypedData !== "function") return null;
257
+ const signer = typeof walletProvider.readContract === "function"
258
+ ? { ...account, readContract: (args) => walletProvider.readContract(args) }
259
+ : account;
260
+ const [{ x402Client, wrapFetchWithPayment }, { registerExactEvmScheme }] = await Promise.all([
261
+ import("@x402/fetch"), import("@x402/evm/exact/client"),
262
+ ]);
263
+ const client = new x402Client();
264
+ // Guarded, agent402-client's signing guard holds each payment to this
265
+ // package's ceilings and prices it from known assets, so the library's
266
+ // default control (its own default assets only, a fixed $1) is replaced.
267
+ if (guarded) client.setSpendControls?.(false);
268
+ registerExactEvmScheme(client, { signer });
269
+ if (Array.isArray(payees) && payees.length) {
270
+ const { withPayeeAllowlist } = await import("agent402-client");
271
+ withPayeeAllowlist(client, payees);
272
+ }
273
+ return { client, payFetch: wrapFetchWithPayment(fetchImpl, client) };
274
+ }
275
+
276
+ async function loadZod() {
277
+ try { const m = await import("zod"); return m.z || m.default?.z || m; }
278
+ catch { throw new Error("agent402-action-provider requires 'zod' - install it with: npm install zod"); }
279
+ }
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "agent402-action-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Agent402 action provider for use with AgentKit: find, call and about actions over Agent402's 500+ pay-per-call web tools and skill packs (x402 or MPP; Agentic Finance) for agents with CDP, Privy, ZeroDev or viem wallets. Pays over x402 in USDC on Base from the agent's wallet, or with a prepaid credits key for Agent402's own services; the pure-CPU tools are free via proof-of-work. Formerly agent402-agentkit.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "README.md"
18
+ ],
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "scripts": {
23
+ "test": "node test.js"
24
+ },
25
+ "keywords": [
26
+ "agentkit",
27
+ "x402",
28
+ "ai-agents",
29
+ "agent-tools",
30
+ "llm-tools",
31
+ "usdc",
32
+ "base",
33
+ "proof-of-work",
34
+ "http-402",
35
+ "micropayments",
36
+ "agent402",
37
+ "tool-discovery",
38
+ "agentic-commerce",
39
+ "agentic-finance",
40
+ "aifi",
41
+ "mpp"
42
+ ],
43
+ "author": "Cardhavok LLC (doing business as Havok Holdings LLC)",
44
+ "license": "MIT",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/MikeyPetrillo/Agent402.git",
48
+ "directory": "adapters/agentkit"
49
+ },
50
+ "homepage": "https://agent402.tools",
51
+ "dependencies": {
52
+ "agent402-client": ">=0.8.21 <1.0.0"
53
+ },
54
+ "peerDependencies": {
55
+ "@coinbase/agentkit": ">=0.10.0 <1",
56
+ "@x402/evm": ">=2.0.0 <3",
57
+ "@x402/fetch": ">=2.0.0 <3",
58
+ "zod": ">=3.23.0 <5"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@coinbase/agentkit": {
62
+ "optional": true
63
+ },
64
+ "@x402/evm": {
65
+ "optional": true
66
+ },
67
+ "@x402/fetch": {
68
+ "optional": true
69
+ }
70
+ }
71
+ }