agent402-stream-tools 0.0.0-stage → 0.3.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 +111 -2
  3. package/index.d.ts +55 -0
  4. package/index.js +387 -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,112 @@
1
- # Temporary Holding Version
1
+ # agent402-stream-tools
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) tools for use with the AI SDK by Vercel (`streamText`, `generateText`). Agent402 is the open-source
4
+ x402 + MCP server with 500+ pay-per-call web tools (browser, web search,
5
+ OCR, PDFs, durable memory, pure-CPU utilities) **and** the cross-seller
6
+ [Smart Order Router](https://agent402.tools/marketplace) that ranks tools across
7
+ the x402 sellers Agent402 indexes.
8
+
9
+ Works with the AI SDK (`ai`). Agent402 is not affiliated with or endorsed by Vercel.
10
+
11
+ Formerly `agent402-ai-sdk`: 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://agent402.tools/what-is-x402) and [MPP](https://agent402.tools/what-is-mpp) (Machine Payments Protocol). Every paid endpoint answers both on the same 402; wallet-only tools take any payment-wrapped fetch (`@x402/fetch`, or a stock `mppx` fetch).
14
+
15
+ ```bash
16
+ npm install agent402-stream-tools ai zod
17
+ # the quickstart's model provider:
18
+ npm install @ai-sdk/openai
19
+ ```
20
+
21
+ ## Quickstart
22
+
23
+ ```js
24
+ import { agent402Tools } from "agent402-stream-tools";
25
+ import { generateText } from "ai";
26
+ import { openai } from "@ai-sdk/openai";
27
+
28
+ // Free tier (proof-of-work auto-pay, no wallet)
29
+ const tools = await agent402Tools();
30
+
31
+ // Or, for wallet-required tools (browser, search, memory), supply an
32
+ // x402-wrapped fetch (e.g. @x402/fetch with your funded Base wallet):
33
+ // const tools = await agent402Tools({ fetch: payFetch });
34
+
35
+ const { text } = await generateText({
36
+ model: openai("gpt-6-luna"),
37
+ tools,
38
+ prompt: "Hash 'hello world' with sha256",
39
+ });
40
+ ```
41
+
42
+ ## What you get - four meta tools
43
+
44
+ The LLM picks tasks; the router ranks sellers; the caller handles payment.
45
+
46
+ | Tool | Purpose |
47
+ |---|---|
48
+ | `agent402_find` | Resolve a task description to the best **local** Agent402 tool - slug, route, price, input schema, and a ready example. |
49
+ | `agent402_route` | **Cross-seller x402 router**: rank tools across the x402 sellers Agent402 indexes (its own catalog plus the other sellers it discovers and crawls). `include: "external"` excludes Agent402 itself - neutral discovery API over the rest of the ecosystem. |
50
+ | `agent402_call` | Call a tool by slug. Pays automatically: pure-CPU tools via proof-of-work; wallet-only via your x402 fetch. |
51
+ | `agent402_about` | The Agent402 service manifest - payment options, capability map, MCP connector, trust signals. |
52
+
53
+ Why four meta tools and not one tool per slug? Registering 500+ individual
54
+ tools blows past most agents' tool-budget and the LLM can't reason over
55
+ hundreds of entries. Routing-as-discovery scales - the LLM describes the
56
+ task, the router ranks the sellers that can serve it, the caller handles
57
+ payment.
58
+
59
+ ## Migration from 0.1.x
60
+
61
+ `agent402-stream-tools@0.2.0` replaces the per-slug tool generator with the four-
62
+ meta-tool pattern. If you were using `agent402Tools({ slugs: [...] })`, the
63
+ new entry point is just `agent402Tools()` - the LLM picks slugs at runtime
64
+ via `agent402_find` and `agent402_route`.
65
+
66
+ ## Framework-agnostic specs
67
+
68
+ If you'd rather not pull in `ai` (or you want to wrap the tools with your own
69
+ factory), use the framework-agnostic export:
70
+
71
+ ```js
72
+ import { agent402ToolSpecs } from "agent402-stream-tools";
73
+
74
+ const specs = agent402ToolSpecs();
75
+ // specs = [{ name, description, parametersJsonSchema, execute }, ...]
76
+ const result = await specs.find((s) => s.name === "agent402_route").execute({
77
+ query: "ocr image",
78
+ top: 3,
79
+ include: "external",
80
+ });
81
+ ```
82
+
83
+ ## Options
84
+
85
+ ```ts
86
+ agent402Tools({
87
+ baseUrl?: string, // default: "https://agent402.tools"
88
+ fetch?: typeof fetch, // x402-wrapped fetch for wallet-required tools
89
+ fetchImpl?: typeof fetch, // base fetch for unpaid lookups (default: global fetch)
90
+ maxPerCallUsd?: number | "off", // ceiling on one paid call, checked on its list price (default 5; 0 or "off" turns it off)
91
+ dailyLimitUsd?: number, // opt-in rolling 24-hour total for paid calls
92
+ })
93
+ ```
94
+
95
+ ### Spending caps
96
+
97
+ A paid call is checked before your payment `fetch` runs: a tool whose listed
98
+ price is above `maxPerCallUsd` (default $5, agent402-client's default, which
99
+ covers every fixed price in the catalog; `0` or `"off"` turns it off) is
100
+ refused, and so is a call that would bring the rolling 24-hour total above
101
+ `dailyLimitUsd` (opt-in). Every call sent through the payment `fetch` counts
102
+ its list price against that total, whatever its outcome. A refusal throws an
103
+ error with `code: "SPENDING_LIMIT"` and `limit` naming the cap; nothing is
104
+ paid. These caps read the list price; to hold them on the payment that is
105
+ signed, use agent402-client with its `x402Client` option.
106
+
107
+ A proof-of-work challenge above 28 bits (`MAX_POW_DIFFICULTY`) is refused
108
+ before any work, and the search yields to the event loop while it runs.
109
+
110
+ ## License
111
+
112
+ MIT - part of [Agent402](https://github.com/MikeyPetrillo/Agent402).
package/index.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ // Type declarations for agent402-stream-tools. The runtime is index.js (plain ES modules,
2
+ // no dependencies); these declarations describe its public API. The
3
+ // framework objects it returns are typed loosely, so the declarations import
4
+ // nothing from the framework (an optional peer).
5
+
6
+ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
7
+
8
+ export interface Agent402ToolOptions {
9
+ /** Default "https://agent402.tools". */
10
+ baseUrl?: string;
11
+ /** An x402-wrapped fetch that pays wallet-only tools. */
12
+ fetch?: FetchLike;
13
+ /** Plain fetch for unpaid lookups (default: the global fetch). */
14
+ fetchImpl?: FetchLike;
15
+ /** Ceiling on one paid call in USD, checked on the tool's listed price before the payment fetch runs (default 5; 0, "off" or null turns it off). */
16
+ maxPerCallUsd?: number | string | null;
17
+ /** Opt-in rolling 24-hour total for paid calls, in USD. */
18
+ dailyLimitUsd?: number | null;
19
+ }
20
+
21
+ /** A framework-agnostic tool: a JSON Schema and a plain async execute. */
22
+ export interface Agent402ToolSpec {
23
+ name: "agent402_find" | "agent402_route" | "agent402_call" | "agent402_about";
24
+ description: string;
25
+ parametersJsonSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
26
+ execute(input: Record<string, unknown>): Promise<unknown>;
27
+ }
28
+
29
+ /** Thrown before anything is paid when a spending cap refuses a call. */
30
+ export interface SpendingLimitError extends Error {
31
+ name: "SpendingLimitError";
32
+ code: "SPENDING_LIMIT";
33
+ limit: "maxPerCallUsd" | "dailyLimitUsd";
34
+ slug: string;
35
+ priceUsd?: number;
36
+ cap?: number;
37
+ spent?: number;
38
+ }
39
+
40
+ /** The default per-call ceiling in USD (agent402-client's default). */
41
+ export const DEFAULT_MAX_PER_CALL_USD: number;
42
+ /** The largest proof-of-work difficulty, in bits, this package solves. */
43
+ export const MAX_POW_DIFFICULTY: number;
44
+
45
+ /** The four meta tools as framework-agnostic specs. */
46
+ export function agent402ToolSpecs(opts?: Agent402ToolOptions): Agent402ToolSpec[];
47
+
48
+ /** An AI SDK tool (from `tool()` in "ai"), typed loosely. */
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
+ export type AiSdkTool = any;
51
+
52
+ /** The four meta tools keyed by name, the shape `generateText({ tools })` takes (needs ai and zod). */
53
+ export function agent402Tools(opts?: Agent402ToolOptions): Promise<Record<Agent402ToolSpec["name"], AiSdkTool>>;
54
+
55
+ export default agent402Tools;
package/index.js ADDED
@@ -0,0 +1,387 @@
1
+ // agent402-stream-tools (formerly agent402-ai-sdk): Agent402 tools for use with
2
+ // the AI SDK by Vercel, which the agent can pick up directly. Four meta tools, all free to discover:
3
+ //
4
+ // agent402_find: local catalog resolver (GET /api/find)
5
+ // agent402_route: cross-seller x402 router (POST /api/route)
6
+ // agent402_call: call a tool by slug, auto-pays (PoW free / x402 paid)
7
+ // agent402_about: service manifest (GET /.well-known/x402)
8
+ //
9
+ // Why four and not "one tool per slug"? Frameworks balk at registering 500+
10
+ // tools at once and the LLM can't reason over that many entries. Routing-as-
11
+ // discovery means the LLM picks a task, the router picks the seller, and the
12
+ // caller handles payment.
13
+ //
14
+ // import { agent402Tools } from "agent402-stream-tools";
15
+ // const tools = await agent402Tools(); // free tier (PoW)
16
+ // // or, for wallet-required tools, supply an x402 fetch:
17
+ // const tools = await agent402Tools({ fetch: payFetch });
18
+ //
19
+ // const { text } = await generateText({ model, tools, prompt: "..." });
20
+ //
21
+ // `agent402ToolSpecs()` returns the same four entries as framework-agnostic
22
+ // specs (plain JSON Schemas, plain async `execute`). Useful if you don't want
23
+ // the `ai` dep, or if you're wrapping the tools yourself.
24
+ //
25
+ // Implementation note: we inline the proof-of-work solver + call orchestration
26
+ // (~30 LoC) instead of depending on agent402-client at runtime, so this package
27
+ // stays zero-dep beyond its (optional) framework peers.
28
+ import { createHash } from "node:crypto";
29
+
30
+ const DEFAULT_BASE = "https://agent402.tools";
31
+ // Keep in lockstep with package.json: the User-Agent product token that names
32
+ // this package on every call it sends.
33
+ const USER_AGENT = "agent402-stream-tools/0.3.0";
34
+
35
+ // Discovery reads (catalog, find, route, manifest, a proof-of-work challenge)
36
+ // settle nothing, so a 503 the server sheds under load is safe to repeat. It
37
+ // is retried only when it names its own delay (a Retry-After header or a
38
+ // retryAfterSeconds body field), at most DISCOVERY_ATTEMPTS tries in all,
39
+ // each wait capped at DISCOVERY_MAX_WAIT_MS. A paid call never goes through
40
+ // here: a repeat of one could settle twice.
41
+ const DISCOVERY_ATTEMPTS = 3;
42
+ const DISCOVERY_MAX_WAIT_MS = 5000;
43
+
44
+ async function shedRetryWaitMs(r) {
45
+ if (!r || r.status !== 503) return null;
46
+ const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
47
+ let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
48
+ if (!Number.isFinite(seconds)) {
49
+ try {
50
+ const body = await (typeof r.clone === "function" ? r.clone() : r).json();
51
+ seconds = Number(body && body.retryAfterSeconds);
52
+ } catch { seconds = NaN; }
53
+ }
54
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
55
+ return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
56
+ }
57
+
58
+ // Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
59
+ // "after N attempts" when it retried, and the server's `error` text) with
60
+ // `.status`, `.body` and `.attempts` set.
61
+ // `init` may be a function, so each attempt gets its own timeout signal.
62
+ async function discoveryFetch(fetchImpl, label, url, init) {
63
+ let r;
64
+ let attempts = 0;
65
+ for (;;) {
66
+ attempts++;
67
+ const i = (typeof init === "function" ? init() : init) || {};
68
+ r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
69
+ if (r.ok) return r;
70
+ if (attempts >= DISCOVERY_ATTEMPTS) break;
71
+ const wait = await shedRetryWaitMs(r);
72
+ if (wait == null) break;
73
+ await new Promise((resolve) => setTimeout(resolve, wait));
74
+ }
75
+ const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
76
+ err.attempts = attempts;
77
+ throw err;
78
+ }
79
+
80
+ // The server's own answer to a failed request, on the thrown error: its
81
+ // `error` text joins the message, and `.status` and `.body` (the parsed JSON,
82
+ // else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
83
+ // why the call failed (a refusal, a limit, a missing parameter).
84
+ const ERROR_BODY_MAX = 4000;
85
+ async function responseError(message, r) {
86
+ let text = "";
87
+ try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
88
+ text = text.slice(0, ERROR_BODY_MAX);
89
+ let body = null;
90
+ try { body = text ? JSON.parse(text) : null; } catch { body = null; }
91
+ const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
92
+ const err = new Error(said ? `${message}: ${said}` : message);
93
+ err.status = r?.status;
94
+ err.body = body ?? (text || null);
95
+ return err;
96
+ }
97
+
98
+ const leadingZeroBits = (buf) => {
99
+ let n = 0;
100
+ for (const b of buf) {
101
+ if (b === 0) { n += 8; continue; }
102
+ n += Math.clz32(b) - 24;
103
+ break;
104
+ }
105
+ return n;
106
+ };
107
+
108
+ // A challenge the server sends is checked before any work: a difficulty above
109
+ // MAX_POW_DIFFICULTY bits (the most an Agent402 server asks, and what
110
+ // agent402-client accepts) is refused, so a server cannot hold this process
111
+ // in a search with no end, and the search stops after MAX_POW_TRIES_FACTOR
112
+ // times the expected count of hashes. It yields to the event loop between
113
+ // slices, so the host process keeps answering while it solves.
114
+ export const MAX_POW_DIFFICULTY = 28;
115
+ const MAX_POW_TRIES_FACTOR = 64;
116
+ const POW_SLICE = 4096;
117
+
118
+ // Solve a proof-of-work challenge (from /api/pow/challenge) into the
119
+ // X-Pow-Solution header value the paywall expects.
120
+ async function solvePow(pow) {
121
+ const { challenge, difficulty, token } = pow || {};
122
+ if (typeof challenge !== "string" || challenge.length === 0 || challenge.length > 512) throw new Error("proof-of-work challenge must be a string of 1 to 512 characters");
123
+ if (typeof difficulty !== "number" || !Number.isInteger(difficulty) || difficulty < 0 || difficulty > MAX_POW_DIFFICULTY) {
124
+ throw new Error(`proof-of-work difficulty ${JSON.stringify(difficulty)} is refused: this package solves a whole number of bits from 0 to ${MAX_POW_DIFFICULTY}`);
125
+ }
126
+ if (typeof token !== "string" || token.length === 0 || token.length > 4096) throw new Error("proof-of-work token must be a string of 1 to 4096 characters");
127
+ const maxTries = MAX_POW_TRIES_FACTOR * 2 ** difficulty;
128
+ for (let nonce = 0; nonce < maxTries; nonce++) {
129
+ if (leadingZeroBits(createHash("sha256").update(`${challenge}:${nonce}`).digest()) >= difficulty) return `${token}:${nonce}`;
130
+ if (nonce % POW_SLICE === POW_SLICE - 1) await new Promise((resolve) => setImmediate(resolve));
131
+ }
132
+ throw new Error(`proof-of-work search stopped after ${maxTries} hashes without a ${difficulty}-bit solution: the challenge is not solvable as stated`);
133
+ }
134
+
135
+ // Spending caps for the payment fetch. The per-call ceiling is on by default
136
+ // at DEFAULT_MAX_PER_CALL_USD (agent402-client's default, which covers every
137
+ // fixed price in the catalog); 0, "off" or null turns it off. dailyLimitUsd
138
+ // is opt-in: a rolling 24-hour total for this set of tools. Both are checked
139
+ // before the payment fetch is used, against the price the catalog lists for
140
+ // the tool, and a call sent through the payment fetch counts its list price
141
+ // against dailyLimitUsd whatever its outcome (this package cannot see what
142
+ // the payment fetch signed). To hold the caps on the payment that is signed,
143
+ // use agent402-client with its x402Client option.
144
+ export const DEFAULT_MAX_PER_CALL_USD = 5;
145
+ const DAY_MS = 24 * 60 * 60 * 1000;
146
+
147
+ function perCallCeilingOf(value, warn = (m) => console.warn(m)) {
148
+ if (value === undefined) return DEFAULT_MAX_PER_CALL_USD;
149
+ if (value === null) return null;
150
+ const raw = typeof value === "string" ? value.trim().toLowerCase() : value;
151
+ if (raw === "off" || raw === 0 || raw === "0") return null;
152
+ const n = typeof raw === "number" ? raw : (typeof raw === "string" && raw !== "" ? Number(raw) : NaN);
153
+ if (Number.isFinite(n) && n >= 0) return n;
154
+ const shown = typeof value === "string" && value.length <= 16 ? JSON.stringify(value) : typeof value;
155
+ warn(`[agent402-stream-tools] maxPerCallUsd ${shown} is not a USD amount, 0 or "off"; keeping the default ($${DEFAULT_MAX_PER_CALL_USD} per call)`);
156
+ return DEFAULT_MAX_PER_CALL_USD;
157
+ }
158
+
159
+ function dailyLimitOf(value) {
160
+ if (value === undefined || value === null || value === "off") return null;
161
+ const n = typeof value === "number" ? value : Number(String(value).trim());
162
+ if (Number.isFinite(n) && n >= 0) return n;
163
+ // A typo never removes a limit the caller meant to set: nothing is paid
164
+ // until it is fixed.
165
+ return 0;
166
+ }
167
+
168
+ /** The USD amount of a listed price ("$0.005"), or null. */
169
+ const listedUsd = (price) => {
170
+ const m = /^\$(\d+(?:\.\d+)?)$/.exec(String(price ?? "").trim());
171
+ return m ? Number(m[1]) : null;
172
+ };
173
+
174
+ /** A refusal made before anything is paid, with the limit it hit. */
175
+ function spendingLimitError(message, fields) {
176
+ const err = new Error(message);
177
+ err.name = "SpendingLimitError";
178
+ err.code = "SPENDING_LIMIT";
179
+ Object.assign(err, fields);
180
+ return err;
181
+ }
182
+
183
+ /**
184
+ * Framework-agnostic tool specs. `execute(input)` returns the JSON result
185
+ * (or throws on HTTP error).
186
+ */
187
+ export function agent402ToolSpecs({ baseUrl = DEFAULT_BASE, fetch: payFetch, fetchImpl = globalThis.fetch, maxPerCallUsd, dailyLimitUsd } = {}) {
188
+ if (typeof fetchImpl !== "function") throw new Error("No fetch available: pass { fetchImpl } on Node < 18");
189
+ // One ledger per set of tools: what its paid calls have committed in the
190
+ // last 24 hours.
191
+ const spend = { maxPerCall: perCallCeilingOf(maxPerCallUsd), daily: dailyLimitOf(dailyLimitUsd), paid: [] };
192
+ const base = String(baseUrl).replace(/\/$/, "");
193
+ const getJSON = async (path) => {
194
+ const r = await discoveryFetch(fetchImpl, `GET ${path}`, `${base}${path}`);
195
+ return r.json();
196
+ };
197
+ const postJSON = async (path, body) => {
198
+ const r = await discoveryFetch(fetchImpl, `POST ${path}`, `${base}${path}`, {
199
+ method: "POST",
200
+ headers: { "content-type": "application/json" },
201
+ body: JSON.stringify(body),
202
+ });
203
+ return r.json();
204
+ };
205
+ return [
206
+ {
207
+ name: "agent402_find",
208
+ description:
209
+ "Resolve a task description to the best Agent402 tool: returns slug, route, price, input schema, and a ready example so you skip the explore step. Local catalog only; for cross-seller use agent402_route.",
210
+ parametersJsonSchema: {
211
+ type: "object",
212
+ properties: {
213
+ task: { type: "string", description: 'What you want to do, e.g. "extract the article from this URL"' },
214
+ limit: { type: "number", description: "Max results (default 5)" },
215
+ },
216
+ required: ["task"],
217
+ },
218
+ execute: ({ task, limit }) => getJSON(`/api/find?q=${encodeURIComponent(task)}&k=${limit || 5}`),
219
+ },
220
+ {
221
+ name: "agent402_route",
222
+ description:
223
+ "Cross-seller x402 router: rank matching tools across every x402 seller (Agent402's catalog + other sellers auto-discovered from the Coinbase CDP Bazaar). Filters out unhealthy sellers, tiebreaks on health then price. include='external' excludes Agent402 itself. Use it as a neutral discovery API over the rest of the ecosystem.",
224
+ parametersJsonSchema: {
225
+ type: "object",
226
+ properties: {
227
+ query: { type: "string", description: 'Task description, e.g. "ocr image to text"' },
228
+ top: { type: "number", description: "Max results (default 5)" },
229
+ include: { type: "string", enum: ["all", "external", "local"], description: "all (default) | external (exclude Agent402) | local (Agent402 only)" },
230
+ },
231
+ required: ["query"],
232
+ },
233
+ execute: ({ query, top, include }) => postJSON(`/api/route`, { query, top: top || 5, include: include || "all" }),
234
+ },
235
+ {
236
+ name: "agent402_call",
237
+ description:
238
+ "Call an Agent402 tool by slug. Pays automatically: pure-CPU tools settle via built-in proof-of-work (no wallet), wallet-only tools settle via the payment-wrapped fetch you configured, on whichever chain its signer pays. Returns the parsed JSON result.",
239
+ parametersJsonSchema: {
240
+ type: "object",
241
+ properties: {
242
+ slug: { type: "string", description: 'Tool slug, e.g. "hash" or "extract"' },
243
+ params: { type: "object", description: "Tool input, matching the tool's inputSchema (use agent402_find to discover)" },
244
+ },
245
+ required: ["slug"],
246
+ },
247
+ execute: async ({ slug, params }) => callTool({ base, slug, params: params || {}, payFetch, fetchImpl, spend }),
248
+ },
249
+ {
250
+ name: "agent402_about",
251
+ description:
252
+ "Return the Agent402 service manifest (/.well-known/x402): identity, payment options (x402 networks + proof-of-work), capability map, MCP connector, the neutral cross-seller discovery surface, and trust signals.",
253
+ parametersJsonSchema: { type: "object", properties: {} },
254
+ execute: () => getJSON(`/.well-known/x402`),
255
+ },
256
+ ];
257
+ }
258
+
259
+ /** Refuse a paid call the caps do not allow, before the payment fetch is
260
+ * used; otherwise count its list price against the rolling 24 hours. */
261
+ function checkSpend(spend, slug, price) {
262
+ if (spend.maxPerCall == null && spend.daily == null) return;
263
+ const usd = listedUsd(price);
264
+ if (usd == null) {
265
+ throw spendingLimitError(`refusing to pay for "${slug}": its listed price ${JSON.stringify(price ?? null)} does not read as a USD amount, and a spending cap is set (maxPerCallUsd${spend.daily != null ? " or dailyLimitUsd" : ""})`, { limit: spend.maxPerCall != null ? "maxPerCallUsd" : "dailyLimitUsd", slug });
266
+ }
267
+ if (spend.maxPerCall != null && usd > spend.maxPerCall + 1e-9) {
268
+ throw spendingLimitError(`refusing to pay $${usd} for "${slug}": over maxPerCallUsd $${spend.maxPerCall}. Nothing was paid; raise maxPerCallUsd (0 or "off" turns it off) to allow it.`, { limit: "maxPerCallUsd", slug, priceUsd: usd, cap: spend.maxPerCall });
269
+ }
270
+ const now = Date.now();
271
+ spend.paid = spend.paid.filter((p) => now - p.at < DAY_MS);
272
+ const spent = spend.paid.reduce((a, p) => a + p.usd, 0);
273
+ if (spend.daily != null && spent + usd > spend.daily + 1e-9) {
274
+ throw spendingLimitError(`refusing to pay $${usd} for "${slug}": would bring 24h spend to $${(spent + usd).toFixed(6)}, over dailyLimitUsd $${spend.daily}. Nothing was paid.`, { limit: "dailyLimitUsd", slug, priceUsd: usd, spent: Number(spent.toFixed(6)), cap: spend.daily });
275
+ }
276
+ spend.paid.push({ at: now, usd });
277
+ }
278
+
279
+ // One-shot tool invocation: resolve the slug → call the route, auto-paying via
280
+ // proof-of-work (free tier) or the user's x402 fetch (wallet-required tools).
281
+ // Mirrors agent402-client.call() behavior so this package stays zero-dep.
282
+ async function callTool({ base, slug, params, payFetch, fetchImpl, spend }) {
283
+ const pricingRes = await discoveryFetch(fetchImpl, "could not load catalog (GET /api/pricing)", `${base}/api/pricing`);
284
+ const pricing = await pricingRes.json();
285
+ const entry = (pricing.endpoints || []).find((e) => e.slug === slug);
286
+ if (!entry) throw new Error(`unknown tool "${slug}": use agent402_find or agent402_route to discover one`);
287
+
288
+ const idem = `a402aisdk-${createHash("sha256").update(`${slug}:${JSON.stringify(params)}:${Date.now()}:${Math.random()}`).digest("hex").slice(0, 24)}`;
289
+ const send = async (extraHeaders = {}, useFetch = fetchImpl) => {
290
+ const headers = { "User-Agent": USER_AGENT, "Idempotency-Key": idem, ...extraHeaders };
291
+ let url = `${base}${entry.path}`;
292
+ // A request through the payment fetch never follows a redirect: followed,
293
+ // it would pay another origin's 402 or carry a signature to another host.
294
+ const paid = Boolean(payFetch) && useFetch === payFetch;
295
+ const init = paid ? { method: entry.method, headers, redirect: "manual" } : { method: entry.method, headers };
296
+ if (entry.method === "GET") {
297
+ const qs = new URLSearchParams(Object.entries(params).map(([k, v]) => [k, typeof v === "object" ? JSON.stringify(v) : String(v)])).toString();
298
+ if (qs) url += `?${qs}`;
299
+ } else {
300
+ headers["Content-Type"] = "application/json";
301
+ init.body = JSON.stringify(params);
302
+ }
303
+ const r = await useFetch(url, init);
304
+ if (paid && (r?.type === "opaqueredirect" || (r?.status >= 300 && r?.status < 400))) {
305
+ const loc = r.headers?.get?.("location");
306
+ const to = loc ? new URL(loc, url).href : null;
307
+ throw new Error(`refusing to follow a redirect on a paid call to "${slug}": ${url} answered HTTP ${r.status || "redirect"}${to ? ` pointing to ${to}` : ""}. Paid requests never follow redirects${to ? `; if that is the address you meant, use ${new URL(to).origin} as the base URL` : ""}.`);
308
+ }
309
+ return r;
310
+ };
311
+
312
+ // Wallet-only tool: route through the user's x402 fetch, inside the caps.
313
+ if (!entry.computePayable) {
314
+ if (payFetch) checkSpend(spend, slug, entry.price);
315
+ const r = payFetch ? await send({}, payFetch) : await send();
316
+ if (!r.ok) {
317
+ if (payFetch) throw await responseError(`call "${slug}" failed: HTTP ${r.status}`, r);
318
+ throw new Error(`call "${slug}" needs a wallet: construct with { fetch: payFetch } (an @x402/fetch-wrapped fetch)`);
319
+ }
320
+ return r.json();
321
+ }
322
+
323
+ // Compute-payable tool: try unpaywalled first (FREE_MODE instance), fall back
324
+ // to proof-of-work using the server-issued challenge.
325
+ let r = await send();
326
+ if (!r.ok) {
327
+ const challengeRes = await discoveryFetch(fetchImpl, `proof-of-work challenge for "${slug}" failed (GET /api/pow/challenge)`, `${base}/api/pow/challenge?slug=${encodeURIComponent(slug)}`);
328
+ const chal = await challengeRes.json();
329
+ r = await send({ "X-Pow-Solution": await solvePow(chal) });
330
+ }
331
+ if (!r.ok) throw await responseError(`call "${slug}" failed after proof-of-work: HTTP ${r.status}`, r);
332
+ return r.json();
333
+ }
334
+
335
+ /**
336
+ * Framework-native Vercel AI SDK tools. Dynamically imports `ai` and `zod`
337
+ * (both peer dependencies) so the spec path works without them.
338
+ *
339
+ * Returns an object keyed by tool name, the shape `generateText({ tools })`
340
+ * expects.
341
+ */
342
+ export async function agent402Tools(opts) {
343
+ const [{ tool }, { z }] = await Promise.all([
344
+ import("ai"),
345
+ import("zod"),
346
+ ]);
347
+ const specs = agent402ToolSpecs(opts);
348
+ const out = {};
349
+ for (const s of specs) {
350
+ // AI SDK 5 renamed `parameters` to `inputSchema` and reads nothing else;
351
+ // 3 and 4 read `parameters`. Both are passed, so the model gets the schema
352
+ // on every major (on ai 5-7 a `parameters`-only tool has NO schema: found
353
+ // 2026-09-15 by constructing against ai@7.0.100).
354
+ const schema = jsonSchemaToZod(s.parametersJsonSchema, z);
355
+ out[s.name] = tool({
356
+ description: s.description,
357
+ inputSchema: schema,
358
+ parameters: schema,
359
+ execute: s.execute,
360
+ });
361
+ }
362
+ return out;
363
+ }
364
+
365
+ // Minimal JSON-Schema → Zod converter for the shapes we emit. Not a general
366
+ // solution: it covers `object` with primitive/enum/object properties and the
367
+ // `required` list. Keeps a zero-fat dep on zod's surface.
368
+ function jsonSchemaToZod(schema, z) {
369
+ if (!schema || schema.type !== "object") return z.object({});
370
+ const shape = {};
371
+ const required = new Set(schema.required || []);
372
+ for (const [k, prop] of Object.entries(schema.properties || {})) {
373
+ let s;
374
+ if (prop.enum) s = z.enum(prop.enum);
375
+ else if (prop.type === "string") s = z.string();
376
+ else if (prop.type === "number") s = z.number();
377
+ else if (prop.type === "boolean") s = z.boolean();
378
+ else if (prop.type === "object") s = z.record(z.any());
379
+ else s = z.any();
380
+ if (prop.description) s = s.describe(prop.description);
381
+ if (!required.has(k)) s = s.optional();
382
+ shape[k] = s;
383
+ }
384
+ return z.object(shape);
385
+ }
386
+
387
+ export default agent402Tools;
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "agent402-stream-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0-claim.0",
4
+ "description": "Agent402 tools for use with the AI SDK by Vercel (Agentic Finance over x402 or MPP): turn Agent402's catalog of 500+ pay-per-call tools and skill packs into streamText and generateText tools via four meta-tools (find/route/call/about), including the cross-seller x402 router. Free via proof-of-work for the pure-CPU tools, or pay per call in USDC on 13 chains or USDG on Robinhood Chain. Formerly agent402-ai-sdk.",
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
+ "ai-sdk",
27
+ "vercel",
28
+ "ai",
29
+ "tools",
30
+ "streamText",
31
+ "generateText",
32
+ "x402",
33
+ "ai-agents",
34
+ "agent-tools",
35
+ "llm-tools",
36
+ "usdc",
37
+ "base",
38
+ "proof-of-work",
39
+ "http-402",
40
+ "micropayments",
41
+ "agent402",
42
+ "tool-discovery",
43
+ "smart-order-router",
44
+ "agentic-commerce",
45
+ "agentic-finance",
46
+ "aifi",
47
+ "mpp",
48
+ "machine-payments-protocol",
49
+ "agentic-payments"
50
+ ],
51
+ "author": "Cardhavok LLC (doing business as Havok Holdings LLC) <mike@agent402.tools> (https://github.com/MikeyPetrillo/Agent402)",
52
+ "license": "MIT",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/MikeyPetrillo/Agent402.git",
56
+ "directory": "adapters/ai-sdk"
57
+ },
58
+ "homepage": "https://agent402.tools",
59
+ "peerDependencies": {
60
+ "ai": ">=3 <8",
61
+ "zod": ">=3 <5"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "ai": {
65
+ "optional": true
66
+ },
67
+ "zod": {
68
+ "optional": true
69
+ }
70
+ }
71
+ }