agent402-actions-plugin 0.0.0-stage → 0.4.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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/index.d.ts +15 -0
  4. package/index.js +410 -0
  5. package/package.json +105 -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,134 @@
1
- # Temporary Holding Version
1
+ # agent402-actions-plugin
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 actions plugin for use with [elizaOS](https://github.com/elizaOS/eliza):
4
+ pay-per-call web tools (web search, page render, PDFs, OCR, market and
5
+ crypto data, SEC filings, DNS/TLS checks) your agent can find and call. Agent402
6
+ answers x402 and MPP (Machine Payments Protocol) on the same 402; this plugin pays
7
+ in USDC over x402 from an EVM wallet or with an Agent402 credits key. Free-tier tools
8
+ pay with proof-of-work and need neither. Agentic Finance for elizaOS agents: every paid
9
+ call is quoted before it is paid and bounded by the ceilings you set.
10
+
11
+ Works with elizaOS. Agent402 is not affiliated with or endorsed by the elizaOS project.
12
+
13
+ Formerly `elizaos-plugin-agent402`: the same API under a new name. Change the dependency and the import specifier; nothing else changes.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ elizaos plugins add agent402-actions-plugin
19
+ # or: bun add agent402-actions-plugin
20
+ ```
21
+
22
+ Character config:
23
+
24
+ ```json
25
+ {
26
+ "plugins": ["agent402-actions-plugin"],
27
+ "settings": {
28
+ "AGENT402_CREDITS_KEY": "a402_...",
29
+ "AGENT402_MAX_PER_CALL_USD": "1"
30
+ }
31
+ }
32
+ ```
33
+
34
+ `AGENT402_MAX_PER_CALL_USD` protects the wallet with a $5 per-call ceiling by default, which covers every fixed price in the catalog; `0` or `off` turns it off, and a value that is not a USD amount keeps the default and is named on stderr.
35
+
36
+ `AGENT402_CREDITS_KEY` is a prepaid card-credits key issued at
37
+ https://agent402.tools/credits (shown once, emailed; that page says whether new
38
+ keys are on sale). It pays Agent402's own services; the routes that buy from an
39
+ outside seller (the route-execute tiers, `seller-payability`, `decide-execute` and the flight routes) and
40
+ the wallet-identity tools need the wallet below. To pay from a wallet
41
+ instead, set `AGENT402_WALLET_KEY` (an EVM key holding USDC on Base) and
42
+ install the optional peers `@x402/fetch @x402/evm viem`. With neither, the
43
+ free tier still works.
44
+
45
+ ## Actions
46
+
47
+ | Action | What it does | Cost |
48
+ |---|---|---|
49
+ | `AGENT402_FIND` | Task description in, best-matching tools out: slug, price, whether payment is needed, a ready example input. Parameters: `task` (required), `k`. | Free |
50
+ | `AGENT402_CALL` | Runs one tool and returns its JSON. Parameters: `slug`, `params` (both optional: with neither, the tool is chosen from the message and the last `AGENT402_FIND` result, see below). Proof-of-work for free-tier tools; the credits key or wallet for wallet-only tools, never above `AGENT402_MAX_PER_CALL_USD` (default $5) or, when set, the rolling `AGENT402_DAILY_LIMIT_USD`. | $0.001 and up, quoted in every 402 |
51
+ | `AGENT402_ABOUT` | What Agent402 is, how it is paid, live tool counts. | Free |
52
+
53
+ A provider (`AGENT402`) tells the agent on every turn that the catalog exists,
54
+ how to use the two actions, and which payment mode is configured. Keys never
55
+ appear in action results or provider text.
56
+
57
+ ### How `AGENT402_CALL` gets its input
58
+
59
+ In order:
60
+
61
+ 1. `options.parameters` - what a 2.x runtime extracts from the planner's tool
62
+ call and validates against the action's declared `parameters`.
63
+ 2. `slug` / `params` on the message content (a test, or another plugin,
64
+ handing a pre-shaped call).
65
+ 3. The previous `AGENT402_FIND` result in the same action run.
66
+ 4. The message text (the 1.x path, where the runtime hands the handler nothing
67
+ structured): the catalog is searched (free) and the runtime's own model
68
+ (`OBJECT_SMALL`, then `TEXT_SMALL`) is asked to pick ONE of the offered
69
+ candidates and shape its input from their declared examples. A pick that
70
+ names a tool that was not offered is refused, never called.
71
+
72
+ `validate()` admits every message: the planner can only choose an action the
73
+ `ACTIONS` provider lists, and that provider lists what `validate()` admits.
74
+
75
+ ### What the model sees
76
+
77
+ elizaOS renders an action result's `text` (and `values`, and `error`) into the
78
+ next prompt; `data` is kept but not rendered. So the tool's COMPLETE result
79
+ JSON rides in `text`, whatever its size, and error detail is never cut (the
80
+ seller's own `error` text, whole). A host that must bound its context can set
81
+ `AGENT402_MAX_RESULT_CHARS`; a result over that bound is then an explicit
82
+ failure (`data.errorCode: "result_too_large"`) that carries the whole result in
83
+ `data.result` and puts nothing partial in the text.
84
+
85
+ Failures are typed on `data.errorCode` and happen before any paid dispatch:
86
+ `invalid_parameters` (a params string that is not a JSON object, or a non-
87
+ object), `catalog_unavailable` (the catalog could not be read), `no_match`,
88
+ `model_unavailable`, `extraction_failed`, `unoffered_pick`, then `spend_limit`,
89
+ `payment_required`, `upstream_error`, `result_too_large` for the call itself.
90
+
91
+ ### Spend ceilings hold across calls
92
+
93
+ The plugin keeps ONE client per runtime for the runtime's lifetime, so
94
+ `AGENT402_DAILY_LIMIT_USD` is measured against everything that runtime has
95
+ already paid, and a settings change carries the ledger over. A refused call
96
+ sends no request. `spendingSummaryFor(runtime)` reports the ledger.
97
+
98
+ ## Verified against the real runtime
99
+
100
+ `node test-runtime.js` packs this package, installs it with `@elizaos/core`,
101
+ `@elizaos/plugin-sql` and `@elizaos/plugin-bootstrap` (`latest`, or
102
+ `ELIZA_CORE_VERSION=beta` for the 2.x line), boots a real `AgentRuntime`, and
103
+ drives the runtime's own dispatcher (`processActions` on 1.x; on 2.x the
104
+ executor is not exported, so its path is mirrored with core's exported
105
+ `validateActionParams`) with a plain user message and no slug. Two things are
106
+ stubbed: the model (CI has no LLM; a fixed function answers the extraction
107
+ prompt) and the seller (a local HTTP stub speaking the Agent402 wire). No
108
+ network past the npm install, no wallet, nothing paid. It asserts: the
109
+ `ACTIONS` provider lists the call action; the tool is chosen and called; the
110
+ complete result is in the `ACTION_STATE` text the model reads next, including
111
+ a 60 KB one; a $0.003 tool under a $0.005 daily ceiling settles once and every
112
+ later call is refused with no request sent, sequentially and when four fire at
113
+ once; a second runtime in the same process enforces its own ceiling; a
114
+ per-call ceiling refuses with none; an upstream error arrives whole; malformed
115
+ params, an unreachable catalog and no match are typed failures sent nowhere.
116
+
117
+ ## Settings
118
+
119
+ | Setting | Default | Meaning |
120
+ |---|---|---|
121
+ | `AGENT402_CREDITS_KEY` | | a prepaid credits key (`a402_...`) |
122
+ | `AGENT402_WALLET_KEY` | | EVM private key paying USDC over x402 |
123
+ | `AGENT402_BASE_URL` | `https://agent402.tools` | self-hosters point this at their instance |
124
+ | `AGENT402_MAX_PER_CALL_USD` | `5` | refuse any single paid call above this; enforced on the payment that is signed; `0` or `off` turns it off |
125
+ | `AGENT402_DAILY_LIMIT_USD` | | refuse once the runtime's rolling 24h paid spend would exceed this |
126
+ | `AGENT402_MAX_RESULT_CHARS` | unset (no bound) | when set, a result JSON longer than this is an explicit `result_too_large` failure carrying the whole result in `data.result`; nothing partial reaches the text |
127
+
128
+ Every paid call carries an `Idempotency-Key`, so a retried call replays the
129
+ paid answer instead of paying twice. What the same key buys beyond tools:
130
+ https://agent402.tools/docs#why. Other hosts: https://agent402.tools/guides/agent-hosts.
131
+
132
+ ## License
133
+
134
+ This plugin is **MIT** (Havok Holdings LLC) - see the [LICENSE](LICENSE) in this directory, which is what npm's `license` field declares. It lives in the Agent402 monorepo, whose **server** is AGPL-3.0; GitHub's repository-level license badge reports that one, not the plugin's. Every published Agent402 package (`agent402-client`, which this plugin depends on, included) is MIT the same way.
package/index.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { Plugin, Action, Provider, IAgentRuntime, Memory } from "@elizaos/core";
2
+ export declare const findAction: Action;
3
+ export declare const callAction: Action;
4
+ export declare const aboutAction: Action;
5
+ export declare const agent402Provider: Provider;
6
+ export declare const agent402Plugin: Plugin;
7
+ /** How AGENT402_CALL chose its tool and input; exported for hosts and tests. */
8
+ export declare function resolveCallInput(runtime: IAgentRuntime, message: Memory, options: unknown, client: unknown): Promise<{ slug: string; params: Record<string, unknown>; via: "parameters" | "content" | "model" } | { error: string }>;
9
+ /** The runtime's rolling-24h paid spend as its client sees it (null before the first call). */
10
+ export declare function spendingSummaryFor(runtime: IAgentRuntime): { dailyUsd: number; calls: number; byHost: Record<string, number>; limits: Record<string, number | null> } | null;
11
+ /** The default per-call ceiling in USD (AGENT402_MAX_PER_CALL_USD unset). */
12
+ export declare const DEFAULT_MAX_PER_CALL_USD: number;
13
+ /** The per-call ceiling for a setting value: the default when unset, null for 0 or "off", the default (with one stderr warning) when it does not parse. */
14
+ export declare function maxPerCallFrom(raw: string | number | null | undefined, warn?: (message: string) => void): number | null;
15
+ export default agent402Plugin;
package/index.js ADDED
@@ -0,0 +1,410 @@
1
+ // agent402-actions-plugin (formerly elizaos-plugin-agent402): Agent402 for use
2
+ // with elizaOS: three actions (find / call / about) and one
3
+ // context provider. No runtime import of @elizaos/core (types only), so the
4
+ // package installs with nothing but agent402-client.
5
+ //
6
+ // Payment: a prepaid credits key (AGENT402_CREDITS_KEY) or an x402 wallet
7
+ // (AGENT402_WALLET_KEY, with @x402/fetch + @x402/evm + viem present). Free-tier
8
+ // tools pay with proof-of-work and need neither. Spend bounds ride with every
9
+ // paid call: AGENT402_MAX_PER_CALL_USD (default $5; 0 or off turns it off) and
10
+ // the opt-in AGENT402_DAILY_LIMIT_USD.
11
+ import { Agent402 } from "agent402-client";
12
+
13
+ const DEFAULT_BASE = "https://agent402.tools";
14
+ // Keep in lockstep with package.json: the User-Agent product token that names
15
+ // this package on every call it sends.
16
+ const USER_AGENT = "agent402-actions-plugin/0.4.0";
17
+
18
+ // Discovery reads (catalog, find, route, manifest, a proof-of-work challenge)
19
+ // settle nothing, so a 503 the server sheds under load is safe to repeat. It
20
+ // is retried only when it names its own delay (a Retry-After header or a
21
+ // retryAfterSeconds body field), at most DISCOVERY_ATTEMPTS tries in all,
22
+ // each wait capped at DISCOVERY_MAX_WAIT_MS. A paid call never goes through
23
+ // here: a repeat of one could settle twice.
24
+ const DISCOVERY_ATTEMPTS = 3;
25
+ const DISCOVERY_MAX_WAIT_MS = 5000;
26
+
27
+ async function shedRetryWaitMs(r) {
28
+ if (!r || r.status !== 503) return null;
29
+ const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
30
+ let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
31
+ if (!Number.isFinite(seconds)) {
32
+ try {
33
+ const body = await (typeof r.clone === "function" ? r.clone() : r).json();
34
+ seconds = Number(body && body.retryAfterSeconds);
35
+ } catch { seconds = NaN; }
36
+ }
37
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
38
+ return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
39
+ }
40
+
41
+ // Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
42
+ // "after N attempts" when it retried, and the server's `error` text) with
43
+ // `.status`, `.body` and `.attempts` set.
44
+ // `init` may be a function, so each attempt gets its own timeout signal.
45
+ async function discoveryFetch(fetchImpl, label, url, init) {
46
+ let r;
47
+ let attempts = 0;
48
+ for (;;) {
49
+ attempts++;
50
+ const i = (typeof init === "function" ? init() : init) || {};
51
+ r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
52
+ if (r.ok) return r;
53
+ if (attempts >= DISCOVERY_ATTEMPTS) break;
54
+ const wait = await shedRetryWaitMs(r);
55
+ if (wait == null) break;
56
+ await new Promise((resolve) => setTimeout(resolve, wait));
57
+ }
58
+ const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
59
+ err.attempts = attempts;
60
+ throw err;
61
+ }
62
+
63
+ // The server's own answer to a failed request, on the thrown error: its
64
+ // `error` text joins the message, and `.status` and `.body` (the parsed JSON,
65
+ // else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
66
+ // why the call failed (a refusal, a limit, a missing parameter).
67
+ const ERROR_BODY_MAX = 4000;
68
+ async function responseError(message, r) {
69
+ let text = "";
70
+ try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
71
+ text = text.slice(0, ERROR_BODY_MAX);
72
+ let body = null;
73
+ try { body = text ? JSON.parse(text) : null; } catch { body = null; }
74
+ const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
75
+ const err = new Error(said ? `${message}: ${said}` : message);
76
+ err.status = r?.status;
77
+ err.body = body ?? (text || null);
78
+ return err;
79
+ }
80
+ // The runtime owns configuration: runtime.getSetting() reads the character's
81
+ // settings/secrets and, in elizaOS, the process environment behind them. The
82
+ // plugin reads nothing else, so a host that scopes settings per agent is
83
+ // honoured (0.2.0: an earlier process.env fallback here could read another
84
+ // agent's ceiling in a multi-agent process).
85
+ const setting = (runtime, key) => {
86
+ const v = runtime?.getSetting?.(key);
87
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
88
+ return typeof v === "string" && v.trim() ? v.trim() : null;
89
+ };
90
+ const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : d; };
91
+ /** Default per-call ceiling in USD: it covers every fixed price in the Agent402
92
+ * catalog, so it protects the wallet without refusing a listed tool. */
93
+ export const DEFAULT_MAX_PER_CALL_USD = 5;
94
+ const warnedCaps = new Set();
95
+ /** The per-call ceiling agent402-client gets from AGENT402_MAX_PER_CALL_USD:
96
+ * the default when unset, null (no ceiling) for 0 or "off", the amount for a
97
+ * USD number. A value that does not parse (text, negative, NaN) keeps the
98
+ * default and is named once on stderr, so a typo never removes the ceiling. */
99
+ export function maxPerCallFrom(raw, warn = (m) => console.error(m)) {
100
+ if (raw == null) return DEFAULT_MAX_PER_CALL_USD;
101
+ const v = String(raw).trim().toLowerCase();
102
+ if (v === "off") return null;
103
+ const n = v === "" ? NaN : Number(v);
104
+ if (Number.isFinite(n) && n >= 0) return n === 0 ? null : n;
105
+ const shown = String(raw).length <= 16 ? JSON.stringify(String(raw)) : "(a long value, not shown)";
106
+ if (!warnedCaps.has(String(raw))) {
107
+ warnedCaps.add(String(raw));
108
+ warn(`[agent402-actions-plugin] AGENT402_MAX_PER_CALL_USD=${shown} is not a USD amount, 0 or "off"; keeping the default $${DEFAULT_MAX_PER_CALL_USD} per-call ceiling`);
109
+ }
110
+ return DEFAULT_MAX_PER_CALL_USD;
111
+ }
112
+
113
+ /** A fresh x402 client and its paying fetch for one agent402-client instance,
114
+ * which registers its signing guard on the client (the ceilings then hold on
115
+ * the payment that is signed, priced from known assets). One per instance, so
116
+ * a client rebuilt with new ceilings never inherits the old one's guard. */
117
+ async function x402FromKey(pk, fetchImpl) {
118
+ if (!/^0x[0-9a-fA-F]{64}$/.test(pk || "")) return null;
119
+ try {
120
+ const [{ wrapFetchWithPayment, x402Client }, { privateKeyToAccount }, { toClientEvmSigner }, { registerExactEvmScheme }] = await Promise.all([
121
+ import("@x402/fetch"), import("viem/accounts"), import("@x402/evm"), import("@x402/evm/exact/client"),
122
+ ]);
123
+ const client = new x402Client();
124
+ // agent402-client's guard replaces the library's default control (its own
125
+ // default assets only, a fixed $1), which would refuse USDG.
126
+ client.setSpendControls?.(false);
127
+ registerExactEvmScheme(client, { signer: toClientEvmSigner(privateKeyToAccount(pk)) });
128
+ return { client, payFetch: wrapFetchWithPayment(fetchImpl, client) };
129
+ } catch { return null; } // peers absent: free tier + credits still work
130
+ }
131
+
132
+ /** ONE client per runtime, kept for the runtime's lifetime. Settings are still
133
+ * read on every call so a key rotated in the character config takes effect
134
+ * without a restart - but the client's rolling-24h spend ledger is CARRIED
135
+ * across that rebuild. Before 0.2.0 a fresh client was built per call, which
136
+ * meant AGENT402_DAILY_LIMIT_USD bounded each call alone: the ledger it counts
137
+ * against was empty every time (registry review, 2026-09-14). */
138
+ const clients = new WeakMap(); // runtime -> { sig, client }
139
+ async function clientFor(runtime, fetchImpl = globalThis.fetch) {
140
+ const baseUrl = (setting(runtime, "AGENT402_BASE_URL") || DEFAULT_BASE).replace(/\/+$/, "");
141
+ const creditsKey = setting(runtime, "AGENT402_CREDITS_KEY");
142
+ const walletKey = setting(runtime, "AGENT402_WALLET_KEY");
143
+ // A $5 per-call ceiling unless the setting names another (0 or off: none);
144
+ // the daily limit is opt-in.
145
+ const maxPerCallUsd = maxPerCallFrom(setting(runtime, "AGENT402_MAX_PER_CALL_USD"));
146
+ const dailyLimitUsd = num(setting(runtime, "AGENT402_DAILY_LIMIT_USD"), null);
147
+ const sig = JSON.stringify([baseUrl, creditsKey, walletKey, maxPerCallUsd, dailyLimitUsd]);
148
+ const key = runtime && typeof runtime === "object" ? runtime : clientFor;
149
+ const prev = clients.get(key);
150
+ if (prev?.sig === sig) return prev.client;
151
+ const paying = creditsKey ? null : await x402FromKey(walletKey, fetchImpl);
152
+ const client = new Agent402({ userAgent: USER_AGENT, baseUrl, fetchImpl, fetch: paying?.payFetch, x402Client: paying?.client, creditsKey: creditsKey || null, maxPerCallUsd, dailyLimitUsd });
153
+ // The ledger outlives the client: what was spent under the old settings was
154
+ // still spent. (The client keeps it as a plain array; sharing the array is
155
+ // the whole mechanism.)
156
+ if (prev?.client?._spend?.log && client._spend) client._spend.log = prev.client._spend.log;
157
+ clients.set(key, { sig, client });
158
+ return client;
159
+ }
160
+
161
+ /** Rolling-24h spend as the client sees it (for tests and operators). */
162
+ export function spendingSummaryFor(runtime) {
163
+ const c = clients.get(runtime && typeof runtime === "object" ? runtime : clientFor)?.client;
164
+ return c && typeof c.spendingSummary === "function" ? c.spendingSummary() : null;
165
+ }
166
+
167
+ const textOf = (message) => String(message?.content?.text ?? "").trim();
168
+ // Structured input first (an agent or a test hands {task}/{slug, params} in
169
+ // content); the message text is the fallback for a human typing.
170
+ const fieldOf = (message, key) => message?.content?.[key] ?? message?.content?.input?.[key];
171
+
172
+ // WHAT THE MODEL SEES. In elizaOS 1.x the ACTION_STATE provider renders an
173
+ // action result's `text` (and `values`, and `error`) into the next prompt;
174
+ // `data` is kept in working memory and the action-result memory but is NOT
175
+ // rendered unless `text` is empty. So the tool's result has to ride in `text`
176
+ // or the planner never sees it - and it rides COMPLETE. 0.2.0 sent a 12,000-
177
+ // character prefix with a notice; the registry review (2026-09-15) was right
178
+ // that a notice is not the evidence, so there is no truncation anywhere now.
179
+ // A host that must bound its context sets AGENT402_MAX_RESULT_CHARS, and a
180
+ // result over that bound is an explicit FAILURE carrying the whole result in
181
+ // data.result - never a partial payload presented as the answer.
182
+ const MAX_RESULT_CHARS = () => num(process.env.AGENT402_MAX_RESULT_CHARS, null);
183
+ function resultText(slug, json) {
184
+ return `Agent402 \`${slug}\` result (complete JSON): ${json}`;
185
+ }
186
+ // Whole, never sliced: the seller's own 4xx detail is what lets a planner
187
+ // correct its input, and a bound here would hide exactly the useful part.
188
+ const errorText = (e) => String(e?.message || e);
189
+
190
+ // Typed failure states, so a consumer can branch on data.errorCode instead of
191
+ // parsing prose (registry review, 2026-09-15: "propagate typed invalid/
192
+ // unavailable states before any paid dispatch instead of manufacturing
193
+ // valid-looking defaults").
194
+ const failure = (code, text, extra = {}) => ({ success: false, text, error: text, data: { actionName: "AGENT402_CALL", errorCode: code, ...extra } });
195
+
196
+ /** The v2 runtime hands extracted parameters in `options.parameters`; a 1.x
197
+ * runtime hands nothing structured, so a test or another plugin may put them
198
+ * in the message content. Both are read; content wins only where options has
199
+ * no value. */
200
+ const param = (message, options, key) =>
201
+ options?.parameters?.[key] ?? options?.[key] ?? fieldOf(message, key);
202
+
203
+ const reply = async (callback, result) => { if (typeof callback === "function") { try { await callback({ text: result.text, ...(result.data ? { data: result.data } : {}) }); } catch { /* the runtime owns delivery */ } } return result; };
204
+
205
+ export const findAction = {
206
+ name: "AGENT402_FIND",
207
+ similes: ["FIND_TOOL", "SEARCH_AGENT402", "FIND_AGENT402_TOOL", "WHICH_TOOL"],
208
+ description:
209
+ "Find an Agent402 tool for a task (web search, page render, PDFs, OCR, market and crypto data, SEC filings, DNS/TLS " +
210
+ "checks). Returns the best matches with slug, price, whether payment is needed, and an example input. Free: nothing is paid.",
211
+ parameters: [
212
+ { name: "task", description: "What you need done, in your own words", required: true, schema: { type: "string" } },
213
+ { name: "k", description: "How many matches to return (default 5)", required: false, schema: { type: "integer", minimum: 1, maximum: 20 } },
214
+ ],
215
+ examples: [[
216
+ { name: "user", content: { text: "Find a tool that extracts the article text from a URL" } },
217
+ { name: "agent", content: { text: "Agent402 has `extract` for that (its price is in the result). I can call it with { url }.", actions: ["AGENT402_FIND"] } },
218
+ ]],
219
+ validate: async () => true,
220
+ handler: async (runtime, message, _state, options, callback) => {
221
+ const task = String(param(message, options, "task") ?? textOf(message)).trim();
222
+ if (!task) return reply(callback, { success: false, text: "Tell me what you need done and I will find the Agent402 tool for it." });
223
+ try {
224
+ const client = await clientFor(runtime);
225
+ const rows = await client.find(task, { k: num(param(message, options, "k"), 5) });
226
+ const results = (rows || []).map((t) => ({
227
+ slug: t.slug, name: t.name, price: t.price, route: t.route,
228
+ needsPayment: t.computePayable === false || t.walletOnly === true,
229
+ description: t.description, example: t.example ?? t.input ?? null,
230
+ }));
231
+ const top = results[0];
232
+ const text = top
233
+ ? `Best Agent402 match: \`${top.slug}\` (${top.price}) - ${top.description}${results.length > 1 ? ` Also: ${results.slice(1, 4).map((r) => `\`${r.slug}\` (${r.price})`).join(", ")}.` : ""}`
234
+ : `No Agent402 tool matched "${task}".`;
235
+ return reply(callback, { success: true, text, data: { actionName: "AGENT402_FIND", task, results } });
236
+ } catch (e) {
237
+ return reply(callback, { success: false, text: `Agent402 find failed: ${errorText(e)}`, error: errorText(e), data: { actionName: "AGENT402_FIND", errorCode: "catalog_unavailable" } });
238
+ }
239
+ },
240
+ };
241
+
242
+ /** Resolve {slug, params} for AGENT402_CALL from, in order: the runtime's
243
+ * extracted parameters (v2 `options.parameters`), structured content, the
244
+ * previous AGENT402_FIND result in this run, and finally - the 1.x path - the
245
+ * message text itself: the catalog is searched (free) and the runtime's own
246
+ * model is asked to pick the tool and shape its input from the candidates'
247
+ * declared schemas. Returns { slug, params, via } or { error }. */
248
+ export async function resolveCallInput(runtime, message, options, client) {
249
+ const direct = param(message, options, "slug");
250
+ if (direct) {
251
+ const raw = param(message, options, "params") ?? param(message, options, "input");
252
+ let params = raw;
253
+ if (typeof raw === "string") {
254
+ // A string is accepted only if it is valid JSON for an object. Anything
255
+ // else is an INVALID state, reported before any dispatch - never {}.
256
+ try { params = JSON.parse(raw); } catch { return { errorCode: "invalid_parameters", error: `AGENT402_CALL params must be a JSON object; got a string that is not valid JSON: ${raw}` }; }
257
+ }
258
+ if (params == null) params = {};
259
+ if (typeof params !== "object" || Array.isArray(params)) return { errorCode: "invalid_parameters", error: `AGENT402_CALL params must be an object; got ${Array.isArray(params) ? "an array" : typeof params}.` };
260
+ return { slug: String(direct).trim(), params, via: options?.parameters?.slug ? "parameters" : "content" };
261
+ }
262
+ const prevFind = options?.actionContext?.getPreviousResult?.("AGENT402_FIND")
263
+ ?? options?.actionContext?.previousResults?.find((r) => r?.data?.actionName === "AGENT402_FIND");
264
+ const text = textOf(message);
265
+ if (!text) return { errorCode: "invalid_parameters", error: "AGENT402_CALL needs a tool slug and its input, or a message describing the task (AGENT402_FIND lists the slugs)." };
266
+ let candidates;
267
+ if (prevFind?.data?.results?.length) candidates = prevFind.data.results;
268
+ else {
269
+ // A catalog that cannot be read is UNAVAILABLE, which is not "no match":
270
+ // the first is our (or the network's) state, the second is an answer.
271
+ try { candidates = await client.find(text, { k: 5 }); } catch (e) { return { errorCode: "catalog_unavailable", error: `AGENT402_CALL could not search the Agent402 catalog: ${errorText(e)}` }; }
272
+ }
273
+ if (!Array.isArray(candidates) || candidates.length === 0) return { errorCode: "no_match", error: `No Agent402 tool matched "${text}".` };
274
+ if (typeof runtime?.useModel !== "function") {
275
+ return { errorCode: "model_unavailable", error: `AGENT402_CALL could not shape an input for "${text}": this runtime exposes no model to extract parameters with. Provide slug and params directly (candidates: ${candidates.map((c) => c.slug).join(", ")}).` };
276
+ }
277
+ const menu = candidates.slice(0, 5).map((c) => ({ slug: c.slug, description: c.description, price: c.price, example: c.example ?? c.input ?? null, inputSchema: c.inputSchema ?? null }));
278
+ const prompt = [
279
+ "You are choosing ONE tool to run for the user's request and writing its input.",
280
+ `User request: ${JSON.stringify(text)}`,
281
+ "Candidate tools (slug, description, price, an example input, and the input schema where known):",
282
+ JSON.stringify(menu, null, 1),
283
+ 'Respond with ONLY a JSON object of the form {"slug": "<one of the candidate slugs>", "params": {<the tool input for THIS request, in the shape of the example>}}.',
284
+ "If no candidate fits, respond with {\"slug\": null, \"reason\": \"<why>\"}.",
285
+ ].join("\n");
286
+ let picked = null;
287
+ try {
288
+ picked = await runtime.useModel("OBJECT_SMALL", { prompt, temperature: 0 });
289
+ if (typeof picked === "string") { const m = picked.match(/\{[\s\S]*\}/); picked = m ? JSON.parse(m[0]) : null; }
290
+ } catch (e) {
291
+ try {
292
+ const raw = await runtime.useModel("TEXT_SMALL", { prompt, temperature: 0 });
293
+ const m = String(raw || "").match(/\{[\s\S]*\}/); picked = m ? JSON.parse(m[0]) : null;
294
+ } catch (e2) { return { errorCode: "extraction_failed", error: `AGENT402_CALL could not extract parameters: ${errorText(e2)}` }; }
295
+ }
296
+ if (!picked || typeof picked !== "object") return { errorCode: "extraction_failed", error: `AGENT402_CALL could not extract parameters: the model returned no JSON object.` };
297
+ if (!picked.slug) return { errorCode: "no_match", error: `No Agent402 tool fits "${text}"${picked?.reason ? `: ${picked.reason}` : ""}.` };
298
+ const slug = String(picked.slug).trim();
299
+ if (!menu.some((c) => c.slug === slug)) return { errorCode: "unoffered_pick", error: `The model picked "${slug}", which is not among the candidates (${menu.map((c) => c.slug).join(", ")}); refusing to call a tool that was not offered.` };
300
+ if (picked.params != null && (typeof picked.params !== "object" || Array.isArray(picked.params))) return { errorCode: "invalid_parameters", error: `The model returned params that are not an object for "${slug}"; refusing to call it.` };
301
+ return { slug, params: picked.params ?? {}, via: "model" };
302
+ }
303
+
304
+ export const callAction = {
305
+ name: "AGENT402_CALL",
306
+ similes: ["CALL_TOOL", "RUN_AGENT402_TOOL", "USE_AGENT402", "CALL_AGENT402"],
307
+ description:
308
+ "Call an Agent402 tool by slug with its input and return the tool's JSON result. Free-tier tools cost nothing " +
309
+ "(proof-of-work); wallet-only tools are paid with the configured credits key or x402 wallet, typically $0.001 to " +
310
+ "$0.05 per call and never above AGENT402_MAX_PER_CALL_USD ($5 unless set) or, when set, the rolling AGENT402_DAILY_LIMIT_USD. If no slug is " +
311
+ "given the tool is chosen from the message and the last AGENT402_FIND result.",
312
+ parameters: [
313
+ { name: "slug", description: "Tool slug from AGENT402_FIND (for example: hash, search, extract, crypto-price)", required: false, schema: { type: "string" } },
314
+ { name: "params", description: "The tool's input object, in the shape of the example AGENT402_FIND returned", required: false, schema: { type: "object", additionalProperties: true } },
315
+ ],
316
+ examples: [[
317
+ { name: "user", content: { text: "Hash 'hello world' with sha256" } },
318
+ { name: "agent", content: { text: "Calling Agent402's hash tool.", actions: ["AGENT402_CALL"] } },
319
+ ]],
320
+ // The planner can only pick an action the ACTIONS provider listed, and that
321
+ // provider lists what validate() admits - so a validate that demands a slug
322
+ // field on the user's message hides this action from every real
323
+ // conversation (registry review, 2026-09-14). Admit it; the handler decides.
324
+ validate: async () => true,
325
+ handler: async (runtime, message, _state, options, callback) => {
326
+ let client;
327
+ try { client = await clientFor(runtime); } catch (e) { return reply(callback, failure("client_error", `Agent402 client failed: ${errorText(e)}`)); }
328
+ const resolved = await resolveCallInput(runtime, message, options, client);
329
+ if (resolved.error) return reply(callback, failure(resolved.errorCode, resolved.error));
330
+ const { slug, params, via } = resolved;
331
+ let out;
332
+ try {
333
+ out = await client.call(slug, params);
334
+ } catch (e) {
335
+ const msg = errorText(e);
336
+ const code = e?.name === "SpendingLimitError" || /exceeds maxPerCallUsd|dailyLimitUsd|maxPerHostUsd/.test(msg) ? "spend_limit"
337
+ : /wallet-only|402|refused by credits/.test(msg) ? "payment_required" : "upstream_error";
338
+ const hint = code === "payment_required" ? " Set AGENT402_WALLET_KEY (or AGENT402_CREDITS_KEY for a prepaid credits key) to pay for this tool."
339
+ : code === "spend_limit" && (e?.limit === "maxPerCallUsd" || /maxPerCallUsd/.test(msg)) ? `; nothing was signed. Raise AGENT402_MAX_PER_CALL_USD (default $${DEFAULT_MAX_PER_CALL_USD}), or set it to 0 or off, to allow it.` : "";
340
+ return reply(callback, failure(code, `Agent402 \`${slug}\` failed: ${msg}${hint}`, { slug, params, resolvedVia: via }));
341
+ }
342
+ const data = out && typeof out === "object" ? out : { result: out };
343
+ const json = JSON.stringify(data);
344
+ const cap = MAX_RESULT_CHARS();
345
+ if (cap != null && json.length > cap) {
346
+ // The host asked for a bound. The answer is whole in data.result; the
347
+ // text says it was NOT delivered rather than delivering part of it.
348
+ return reply(callback, failure("result_too_large", `Agent402 \`${slug}\` returned ${json.length} characters of JSON, over this host's AGENT402_MAX_RESULT_CHARS of ${cap}; the complete result is in this action's data.result and was not placed in the model context.`, { slug, params, resolvedVia: via, result: data, resultChars: json.length }));
349
+ }
350
+ return reply(callback, {
351
+ success: true,
352
+ text: resultText(slug, json),
353
+ values: { agent402LastSlug: slug },
354
+ data: { actionName: "AGENT402_CALL", slug, params, resolvedVia: via, result: data },
355
+ });
356
+ },
357
+ };
358
+
359
+ export const aboutAction = {
360
+ name: "AGENT402_ABOUT",
361
+ similes: ["WHAT_IS_AGENT402", "AGENT402_INFO"],
362
+ description: "What Agent402 is, how it is paid, and how many tools it serves right now. Free.",
363
+ examples: [[
364
+ { name: "user", content: { text: "What is Agent402?" } },
365
+ { name: "agent", content: { text: "Agent402 is a catalog of pay-per-call web tools, paid in USDC over x402 or with a prepaid credits key.", actions: ["AGENT402_ABOUT"] } },
366
+ ]],
367
+ validate: async () => true,
368
+ handler: async (runtime, _message, _state, _options, callback) => {
369
+ const baseUrl = (setting(runtime, "AGENT402_BASE_URL") || DEFAULT_BASE).replace(/\/+$/, "");
370
+ try {
371
+ const r = await discoveryFetch(globalThis.fetch, "GET /api/pricing", `${baseUrl}/api/pricing`);
372
+ const p = await r.json();
373
+ const endpoints = p.endpoints || [];
374
+ const data = {
375
+ name: "Agent402", baseUrl, tools: endpoints.length, freeTier: endpoints.filter((e) => e.computePayable).length,
376
+ pay: "a prepaid credits key for Agent402's own services (AGENT402_CREDITS_KEY) or USDC over x402 from a wallet (AGENT402_WALLET_KEY); free-tier tools pay with proof-of-work",
377
+ discover: `${baseUrl}/api/find?q=<task>`, docs: `${baseUrl}/llms.txt`, why: `${baseUrl}/docs#why`,
378
+ };
379
+ return reply(callback, { success: true, text: `Agent402 serves ${data.tools} pay-per-call tools right now (${data.freeTier} on the free tier), paid in USDC over x402 or with a prepaid credits key. Docs: ${data.docs}`, data });
380
+ } catch (e) {
381
+ return reply(callback, { success: false, text: `Agent402 is unreachable at ${baseUrl}: ${errorText(e)}`, error: errorText(e) });
382
+ }
383
+ },
384
+ };
385
+
386
+ /** Context the agent sees on every turn: that the catalog exists and how to use it. */
387
+ export const agent402Provider = {
388
+ name: "AGENT402",
389
+ description: "Agent402 pay-per-call tool catalog: how to find and call a tool.",
390
+ get: async (runtime) => {
391
+ const baseUrl = (setting(runtime, "AGENT402_BASE_URL") || DEFAULT_BASE).replace(/\/+$/, "");
392
+ const paid = setting(runtime, "AGENT402_CREDITS_KEY") ? "credits key" : /^0x[0-9a-fA-F]{64}$/.test(setting(runtime, "AGENT402_WALLET_KEY") || "") ? "x402 wallet" : "free tier only (no credits key or wallet configured)";
393
+ const text = `Agent402 (${baseUrl}) is a catalog of pay-per-call web tools. Use AGENT402_FIND with a task description to get a slug and example input, then AGENT402_CALL with that slug and params. Payment mode: ${paid}.`;
394
+ return { text, values: { agent402BaseUrl: baseUrl, agent402PaymentMode: paid }, data: {} };
395
+ },
396
+ };
397
+
398
+ export const agent402Plugin = {
399
+ name: "agent402",
400
+ description: "Find and call Agent402's pay-per-call web tools (search, render, PDFs, market and SEC data), paid by a prepaid credits key or USDC over x402; free tier via proof-of-work.",
401
+ actions: [findAction, callAction, aboutAction],
402
+ providers: [agent402Provider],
403
+ init: async (config, runtime) => {
404
+ const hasKey = Boolean(setting(runtime, "AGENT402_CREDITS_KEY") || config?.AGENT402_CREDITS_KEY);
405
+ const hasWallet = /^0x[0-9a-fA-F]{64}$/.test(setting(runtime, "AGENT402_WALLET_KEY") || config?.AGENT402_WALLET_KEY || "");
406
+ if (!hasKey && !hasWallet) console.warn("[agent402] no AGENT402_CREDITS_KEY or AGENT402_WALLET_KEY: free-tier tools only (set a wallet key or a prepaid credits key to pay per call)");
407
+ },
408
+ };
409
+
410
+ export default agent402Plugin;
package/package.json CHANGED
@@ -1,6 +1,107 @@
1
1
  {
2
2
  "name": "agent402-actions-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0-claim.0",
4
+ "description": "Agent402 actions plugin for use with elizaOS (Agentic Finance): find and call pay-per-call web tools on a server that answers x402 and MPP on one 402. Pays in USDC over x402 from an EVM wallet or with an Agent402 prepaid credits key, under optional per-call and daily ceilings; pure-CPU tools are free via proof-of-work. Formerly elizaos-plugin-agent402.",
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
+ "scripts": {
20
+ "test": "node test.js && node test-runtime.js"
21
+ },
22
+ "keywords": [
23
+ "elizaos",
24
+ "elizaos-plugin",
25
+ "agent402",
26
+ "x402",
27
+ "mpp",
28
+ "aifi",
29
+ "agentic-commerce",
30
+ "agentic-finance",
31
+ "tools",
32
+ "usdc",
33
+ "mcp"
34
+ ],
35
+ "license": "MIT",
36
+ "author": "Cardhavok LLC (doing business as Havok Holdings LLC)",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/MikeyPetrillo/Agent402.git",
40
+ "directory": "adapters/eliza"
41
+ },
42
+ "homepage": "https://agent402.tools/guides/agent-hosts",
43
+ "dependencies": {
44
+ "agent402-client": ">=0.8.21 <1.0.0"
45
+ },
46
+ "peerDependencies": {
47
+ "@x402/evm": ">=2.0.0 <3",
48
+ "@x402/fetch": ">=2.0.0 <3",
49
+ "viem": ">=2.0.0 <3"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@x402/evm": {
53
+ "optional": true
54
+ },
55
+ "@x402/fetch": {
56
+ "optional": true
57
+ },
58
+ "viem": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "agentConfig": {
63
+ "pluginType": "elizaos:plugin:1.0.0",
64
+ "pluginParameters": {
65
+ "AGENT402_CREDITS_KEY": {
66
+ "type": "string",
67
+ "required": false,
68
+ "sensitive": true,
69
+ "description": "Prepaid card-credits key (a402_...) issued at https://agent402.tools/credits (that page says whether new keys are on sale). Pays wallet-only tools on Agent402's own services, except the wallet-identity-bound ones and the routes that buy from an outside seller."
70
+ },
71
+ "AGENT402_WALLET_KEY": {
72
+ "type": "string",
73
+ "required": false,
74
+ "sensitive": true,
75
+ "description": "EVM private key holding USDC on Base; pays wallet-only tools over x402 (needs @x402/fetch, @x402/evm, viem installed)."
76
+ },
77
+ "AGENT402_BASE_URL": {
78
+ "type": "string",
79
+ "required": false,
80
+ "default": "https://agent402.tools",
81
+ "description": "Gateway base URL (self-hosters point this at their own instance)."
82
+ },
83
+ "AGENT402_MAX_PER_CALL_USD": {
84
+ "type": "string",
85
+ "required": false,
86
+ "default": "5",
87
+ "description": "Ceiling on a single paid call in USD (default 5; 0 or off turns it off); a call priced above it is refused before paying."
88
+ },
89
+ "AGENT402_DAILY_LIMIT_USD": {
90
+ "type": "string",
91
+ "required": false,
92
+ "description": "Ceiling on rolling 24-hour paid spend in USD, kept across calls for the runtime's lifetime."
93
+ },
94
+ "AGENT402_MAX_RESULT_CHARS": {
95
+ "type": "string",
96
+ "required": false,
97
+ "description": "Optional bound on a tool result's JSON length in the model context. Unset (default): the complete result is always placed in the action text. Set: a larger result is an explicit failure (errorCode result_too_large) carrying the whole result in data.result, never a truncated text."
98
+ }
99
+ }
100
+ },
101
+ "engines": {
102
+ "node": ">=18"
103
+ },
104
+ "devDependencies": {
105
+ "@elizaos/core": ">=1.0.0"
106
+ }
107
+ }