agent402-agent-loop-tools 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.
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/index.d.ts +40 -0
- package/index.js +236 -0
- 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,138 @@
|
|
|
1
|
-
#
|
|
1
|
+
# agent402-agent-loop-tools
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Agent402](https://agent402.tools) tools for use with [Strands Agents](https://strandsagents.com) (TypeScript):
|
|
4
|
+
turn 500+ pay-per-call web tools into
|
|
5
|
+
Strands `tool({...})` instances your agent can invoke. Payment is handled
|
|
6
|
+
underneath: proof-of-work for the compute-payable tools (no wallet), and the
|
|
7
|
+
payment-wrapped fetch you pass (x402 in USDC on 13 chains or USDG on Robinhood
|
|
8
|
+
Chain, or a stock `mppx` fetch) for wallet-only tools.
|
|
9
|
+
|
|
10
|
+
Works with Strands Agents (`@strands-agents/sdk`) wherever it runs, including on Amazon Bedrock AgentCore. Agent402 is not affiliated with or endorsed by Amazon Web Services.
|
|
11
|
+
|
|
12
|
+
Formerly `agent402-strands`: the same API under a new name. Change the dependency and the import specifier; nothing else changes.
|
|
13
|
+
|
|
14
|
+
> **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).
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install agent402-agent-loop-tools @strands-agents/sdk zod @x402/fetch @x402/core @x402/evm viem
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The `@x402/*` and `viem` packages pay wallet-only tools from your wallet; the free tier needs only the first three.
|
|
24
|
+
|
|
25
|
+
## Use
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { Agent } from "@strands-agents/sdk";
|
|
29
|
+
import { agent402Tools } from "agent402-agent-loop-tools";
|
|
30
|
+
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
31
|
+
import { x402Client } from "@x402/core/client";
|
|
32
|
+
import { registerExactEvmScheme } from "@x402/evm/exact/client";
|
|
33
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
34
|
+
|
|
35
|
+
const payClient = new x402Client();
|
|
36
|
+
registerExactEvmScheme(payClient, { signer: privateKeyToAccount(process.env.AGENT_KEY) });
|
|
37
|
+
const payFetch = wrapFetchWithPayment(fetch, payClient);
|
|
38
|
+
|
|
39
|
+
// Web search, then a cited answer: both wallet-only, paid per call through payFetch.
|
|
40
|
+
const { tools } = await agent402Tools({
|
|
41
|
+
slugs: ["search", "answer"], // pick what you need
|
|
42
|
+
freeOnly: false,
|
|
43
|
+
fetch: payFetch,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
const agent = new Agent({ tools });
|
|
47
|
+
const out = await agent.invoke("Search the web for x402 payment protocol adoption, then answer with citations: what is the x402 payment protocol?");
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**No wallet yet?** The pure-CPU tools (hash, uuid, base64, markdown, JSON and more) run free with proof-of-work and no wallet. Leave out `fetch`; the default (`freeOnly: true`) keeps only those tools:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const { tools } = await agent402Tools({
|
|
54
|
+
slugs: ["hash", "uuid", "json-to-csv"],
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
That's it. The agent now has those tools available; when it calls one, the
|
|
59
|
+
adapter signs an x402 payment (paid tier) or solves a proof-of-work (free
|
|
60
|
+
tier) under the hood and returns the result as a structured object.
|
|
61
|
+
|
|
62
|
+
## Spending caps
|
|
63
|
+
|
|
64
|
+
agent402-client 0.10.0 and later hold one ceiling by default: `maxPerCallUsd`
|
|
65
|
+
of $5, above every catalog price (`0` or `"off"` turns it off). The rolling
|
|
66
|
+
caps are opt-in. Pass agent402-client's caps through (since 0.2.0); a paid
|
|
67
|
+
call over one is refused before anything is signed, with a
|
|
68
|
+
`SpendingLimitError`:
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
const { tools, execute } = await agent402Tools({
|
|
72
|
+
slugs: ["search", "answer"], freeOnly: false, fetch: payFetch,
|
|
73
|
+
x402Client: client, // the @x402/core client payFetch wraps: caps hold at signing
|
|
74
|
+
maxPerCallUsd: 0.05, // per call
|
|
75
|
+
dailyLimitUsd: 5, // rolling 24 hours
|
|
76
|
+
maxPerHostUsd: 1, // rolling 24 hours, per seller host
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`agent402Execute` takes the same options.
|
|
81
|
+
|
|
82
|
+
## Using it with Amazon Bedrock AgentCore
|
|
83
|
+
|
|
84
|
+
Two ways in:
|
|
85
|
+
|
|
86
|
+
1. Add `https://agent402.tools/mcp` as a Gateway target to reach the catalog
|
|
87
|
+
over MCP, no adapter needed.
|
|
88
|
+
2. Or use this adapter to pull a *curated subset* of tools and embed them
|
|
89
|
+
directly in a Strands agent running on AgentCore.
|
|
90
|
+
|
|
91
|
+
See [Using Agent402 with Amazon Bedrock AgentCore](https://github.com/MikeyPetrillo/Agent402/wiki/AWS-Bedrock-AgentCore)
|
|
92
|
+
for the end-to-end recipe.
|
|
93
|
+
|
|
94
|
+
## API
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
agent402Tools(opts?: {
|
|
98
|
+
baseUrl?: string; // default "https://agent402.tools"
|
|
99
|
+
slugs?: string[]; // restrict to these tool slugs (recommended)
|
|
100
|
+
freeOnly?: boolean; // default true - only compute-payable tools (no wallet)
|
|
101
|
+
fetch?: typeof fetch; // an @x402/fetch-wrapped fetch (only for wallet-only tools)
|
|
102
|
+
maxPerCallUsd?: number | string; // per-call ceiling ($5 by default from agent402-client 0.10.0; 0 or "off" turns it off)
|
|
103
|
+
dailyLimitUsd?: number;
|
|
104
|
+
maxPerHostUsd?: number;
|
|
105
|
+
x402Client?: object; // the @x402/core client fetch wraps, so caps hold at signing
|
|
106
|
+
}): Promise<{
|
|
107
|
+
tools: StrandsTool[]; // pass to `new Agent({ tools })`
|
|
108
|
+
execute: (name, args) => Promise<unknown>; // pays under the hood
|
|
109
|
+
client: Agent402; // raw buyer SDK (find()/call()/clearCache())
|
|
110
|
+
}>;
|
|
111
|
+
|
|
112
|
+
agent402Execute(opts?: {
|
|
113
|
+
baseUrl?: string;
|
|
114
|
+
fetch?: typeof fetch;
|
|
115
|
+
maxPerCallUsd?: number; dailyLimitUsd?: number; maxPerHostUsd?: number; x402Client?: object;
|
|
116
|
+
}): (name, args) => Promise<unknown>;
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`freeOnly: true` (the default) filters to the compute-payable (pure-CPU)
|
|
120
|
+
tools - every one of them works with no wallet, paid in a fraction of a second
|
|
121
|
+
of CPU via proof-of-work. Set `freeOnly: false` and pass an
|
|
122
|
+
`@x402/fetch`-wrapped `fetch` to reach the wallet-only tools (the network- and
|
|
123
|
+
disk-touching ones, and most skill packs). The live split is on
|
|
124
|
+
`/api/pricing` (`computePayable` per entry).
|
|
125
|
+
|
|
126
|
+
## Sibling adapters
|
|
127
|
+
|
|
128
|
+
Same shape, different framework:
|
|
129
|
+
|
|
130
|
+
- [`agent402-function-calling`](https://www.npmjs.com/package/agent402-function-calling) - OpenAI function-calling
|
|
131
|
+
- [`agent402-messages-tools`](https://www.npmjs.com/package/agent402-messages-tools) - Anthropic Messages
|
|
132
|
+
- [`agent402-stream-tools`](https://www.npmjs.com/package/agent402-stream-tools) - Vercel AI SDK
|
|
133
|
+
- [`agent402-structured-tools`](https://www.npmjs.com/package/agent402-structured-tools) - LangChain JS / LangGraph
|
|
134
|
+
- [`agent402-function-tools`](https://www.npmjs.com/package/agent402-function-tools) - LlamaIndex TS
|
|
135
|
+
|
|
136
|
+
Source: [`adapters/strands/`](https://github.com/MikeyPetrillo/Agent402/tree/main/adapters/strands).
|
|
137
|
+
Issues + PRs welcome on the [main repo](https://github.com/MikeyPetrillo/Agent402).
|
|
138
|
+
MIT licensed.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Type declarations for agent402-agent-loop-tools. The runtime is index.js (plain ES modules on
|
|
2
|
+
// agent402-client); these declarations describe its public API.
|
|
3
|
+
import type { Agent402, FetchLike } from "agent402-client";
|
|
4
|
+
|
|
5
|
+
export interface Agent402ToolOptions {
|
|
6
|
+
/** Default "https://agent402.tools". */
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
/** Only these slugs (recommended: every tool is a definition the model reads). */
|
|
9
|
+
slugs?: string[];
|
|
10
|
+
/** Only the tools that run free with proof of work (default true). */
|
|
11
|
+
freeOnly?: boolean;
|
|
12
|
+
/** An x402- or MPP-wrapped fetch that pays wallet-only tools. */
|
|
13
|
+
fetch?: FetchLike;
|
|
14
|
+
/** Spending caps passed to agent402-client: one paid call (default 5; 0 or "off" turns it off). */
|
|
15
|
+
maxPerCallUsd?: number | string | null;
|
|
16
|
+
/** Rolling 24-hour total for paid calls (opt-in). */
|
|
17
|
+
dailyLimitUsd?: number | null;
|
|
18
|
+
/** Rolling 24-hour total per seller host (opt-in). */
|
|
19
|
+
maxPerHostUsd?: number | null;
|
|
20
|
+
/** The @x402/core x402Client the fetch wraps, so the caps hold on the payment that is signed. */
|
|
21
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
22
|
+
x402Client?: any;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type ExecuteOptions = Omit<Agent402ToolOptions, "slugs" | "freeOnly">;
|
|
26
|
+
|
|
27
|
+
/** Runs a tool by its tool name (or slug) and resolves to its JSON answer. */
|
|
28
|
+
export type Agent402Execute = (name: string, args?: Record<string, unknown>) => Promise<unknown>;
|
|
29
|
+
|
|
30
|
+
/** A Strands Agents tool, typed loosely (@strands-agents/sdk is a peer). */
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
32
|
+
export type StrandsTool = any;
|
|
33
|
+
|
|
34
|
+
/** Agent402 tools as Strands tools, the client, and an executor (needs @strands-agents/sdk and zod). */
|
|
35
|
+
export function agent402Tools(opts?: Agent402ToolOptions): Promise<{ client: Agent402; tools: StrandsTool[]; execute: Agent402Execute }>;
|
|
36
|
+
|
|
37
|
+
/** An executor for a tool list built another way. */
|
|
38
|
+
export function agent402Execute(opts?: ExecuteOptions): Agent402Execute;
|
|
39
|
+
|
|
40
|
+
export default agent402Tools;
|
package/index.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// agent402-agent-loop-tools: Agent402 tools for use with Strands Agents (TypeScript).
|
|
2
|
+
// Formerly agent402-strands.
|
|
3
|
+
//
|
|
4
|
+
// Turn the Agent402 catalog (500+ pay-per-call web tools) into Strands
|
|
5
|
+
// `tool({...})` instances the agent can invoke, with payment handled for you
|
|
6
|
+
// under the hood by agent402-client (proof-of-work for the free tier,
|
|
7
|
+
// x402+USDC for wallet-only tools when you pass a payFetch).
|
|
8
|
+
//
|
|
9
|
+
// import { Agent } from "@strands-agents/sdk";
|
|
10
|
+
// import { agent402Tools } from "agent402-agent-loop-tools";
|
|
11
|
+
//
|
|
12
|
+
// const { tools } = await agent402Tools({ slugs: ["extract","hash","render"] });
|
|
13
|
+
// const agent = new Agent({ tools });
|
|
14
|
+
// const out = await agent.invoke("Hash 'hello world' with sha256");
|
|
15
|
+
//
|
|
16
|
+
// Works with Strands Agents wherever it runs, including on Amazon Bedrock AgentCore.
|
|
17
|
+
|
|
18
|
+
import { Agent402 } from "agent402-client";
|
|
19
|
+
|
|
20
|
+
const DEFAULT_BASE = "https://agent402.tools";
|
|
21
|
+
// Keep in lockstep with package.json: the User-Agent product token that names
|
|
22
|
+
// this package on every call it sends.
|
|
23
|
+
const USER_AGENT = "agent402-agent-loop-tools/0.3.0";
|
|
24
|
+
|
|
25
|
+
// Discovery reads (catalog, find, route, manifest, a proof-of-work challenge)
|
|
26
|
+
// settle nothing, so a 503 the server sheds under load is safe to repeat. It
|
|
27
|
+
// is retried only when it names its own delay (a Retry-After header or a
|
|
28
|
+
// retryAfterSeconds body field), at most DISCOVERY_ATTEMPTS tries in all,
|
|
29
|
+
// each wait capped at DISCOVERY_MAX_WAIT_MS. A paid call never goes through
|
|
30
|
+
// here: a repeat of one could settle twice.
|
|
31
|
+
const DISCOVERY_ATTEMPTS = 3;
|
|
32
|
+
const DISCOVERY_MAX_WAIT_MS = 5000;
|
|
33
|
+
|
|
34
|
+
async function shedRetryWaitMs(r) {
|
|
35
|
+
if (!r || r.status !== 503) return null;
|
|
36
|
+
const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
|
|
37
|
+
let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
|
|
38
|
+
if (!Number.isFinite(seconds)) {
|
|
39
|
+
try {
|
|
40
|
+
const body = await (typeof r.clone === "function" ? r.clone() : r).json();
|
|
41
|
+
seconds = Number(body && body.retryAfterSeconds);
|
|
42
|
+
} catch { seconds = NaN; }
|
|
43
|
+
}
|
|
44
|
+
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
|
45
|
+
return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
|
|
49
|
+
// "after N attempts" when it retried, and the server's `error` text) with
|
|
50
|
+
// `.status`, `.body` and `.attempts` set.
|
|
51
|
+
// `init` may be a function, so each attempt gets its own timeout signal.
|
|
52
|
+
async function discoveryFetch(fetchImpl, label, url, init) {
|
|
53
|
+
let r;
|
|
54
|
+
let attempts = 0;
|
|
55
|
+
for (;;) {
|
|
56
|
+
attempts++;
|
|
57
|
+
const i = (typeof init === "function" ? init() : init) || {};
|
|
58
|
+
r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
|
|
59
|
+
if (r.ok) return r;
|
|
60
|
+
if (attempts >= DISCOVERY_ATTEMPTS) break;
|
|
61
|
+
const wait = await shedRetryWaitMs(r);
|
|
62
|
+
if (wait == null) break;
|
|
63
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
64
|
+
}
|
|
65
|
+
const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
|
|
66
|
+
err.attempts = attempts;
|
|
67
|
+
throw err;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// The server's own answer to a failed request, on the thrown error: its
|
|
71
|
+
// `error` text joins the message, and `.status` and `.body` (the parsed JSON,
|
|
72
|
+
// else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
|
|
73
|
+
// why the call failed (a refusal, a limit, a missing parameter).
|
|
74
|
+
const ERROR_BODY_MAX = 4000;
|
|
75
|
+
async function responseError(message, r) {
|
|
76
|
+
let text = "";
|
|
77
|
+
try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
|
|
78
|
+
text = text.slice(0, ERROR_BODY_MAX);
|
|
79
|
+
let body = null;
|
|
80
|
+
try { body = text ? JSON.parse(text) : null; } catch { body = null; }
|
|
81
|
+
const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
|
|
82
|
+
const err = new Error(said ? `${message}: ${said}` : message);
|
|
83
|
+
err.status = r?.status;
|
|
84
|
+
err.body = body ?? (text || null);
|
|
85
|
+
return err;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Strands tool names, function-name shape, conservative.
|
|
89
|
+
const sanitizeName = (s) => String(s).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Fetch the Agent402 catalog and return:
|
|
93
|
+
* - `tools`: Strands Tool[] ready to pass to `new Agent({ tools })`
|
|
94
|
+
* - `execute`: async (name, args) => result, pays under the hood
|
|
95
|
+
* - `client`: the underlying Agent402 client (use for find()/clearCache())
|
|
96
|
+
*
|
|
97
|
+
* @param {object} [opts]
|
|
98
|
+
* @param {string} [opts.baseUrl="https://agent402.tools"]
|
|
99
|
+
* @param {string[]} [opts.slugs] Restrict to these slugs (recommended; smaller tool list = better tool-selection)
|
|
100
|
+
* @param {boolean} [opts.freeOnly=true] Default: only include compute-payable tools (no wallet needed)
|
|
101
|
+
* @param {typeof fetch} [opts.fetch] An x402-wrapped fetch (only needed for wallet-only tools)
|
|
102
|
+
* @param {number} [opts.maxPerCallUsd] Spending caps passed to agent402-client ($5 per call by default from 0.10.0):
|
|
103
|
+
* @param {number} [opts.dailyLimitUsd] a paid call over one is refused before anything is signed
|
|
104
|
+
* @param {number} [opts.maxPerHostUsd]
|
|
105
|
+
* @param {object} [opts.x402Client] The @x402/core client your fetch wraps, so the caps hold at signing
|
|
106
|
+
*/
|
|
107
|
+
export async function agent402Tools({ baseUrl = DEFAULT_BASE, slugs, freeOnly = true, fetch: payFetch, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
108
|
+
const [strands, zodMod] = await Promise.all([loadStrands(), loadZod()]);
|
|
109
|
+
const z = zodMod.z || zodMod.default?.z || zodMod;
|
|
110
|
+
const client = new Agent402({ userAgent: USER_AGENT, baseUrl, fetch: payFetch, ...capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client }) });
|
|
111
|
+
// Bounded discovery fetch: caller picks baseUrl, so cap the wait. Node ≥18
|
|
112
|
+
// exposes AbortSignal.timeout() (declared in package.json engines).
|
|
113
|
+
const r = await discoveryFetch(globalThis.fetch, `Could not load ${baseUrl}/openapi.json`, `${baseUrl}/openapi.json`, () => ({ signal: AbortSignal.timeout(15000) }));
|
|
114
|
+
const spec = await r.json();
|
|
115
|
+
|
|
116
|
+
const wanted = slugs ? new Set(slugs) : null;
|
|
117
|
+
const meta = [];
|
|
118
|
+
|
|
119
|
+
for (const [, methods] of Object.entries(spec.paths || {})) {
|
|
120
|
+
for (const [method, op] of Object.entries(methods)) {
|
|
121
|
+
const slug = op.operationId?.replace(/Get$/, "");
|
|
122
|
+
if (!slug) continue;
|
|
123
|
+
if (wanted && !wanted.has(slug)) continue;
|
|
124
|
+
|
|
125
|
+
const schema = method.toLowerCase() === "get"
|
|
126
|
+
? {
|
|
127
|
+
type: "object",
|
|
128
|
+
properties: Object.fromEntries((op.parameters || []).map((p) => [p.name, { type: p.schema?.type || "string", description: p.description }])),
|
|
129
|
+
required: (op.parameters || []).filter((p) => p.required).map((p) => p.name),
|
|
130
|
+
}
|
|
131
|
+
: op.requestBody?.content?.["application/json"]?.schema || { type: "object", properties: {} };
|
|
132
|
+
if (schema && !schema.type) schema.type = "object";
|
|
133
|
+
|
|
134
|
+
meta.push({ name: sanitizeName(slug), slug, schema, description: shortDesc(op.summary, op.description) });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (freeOnly) {
|
|
139
|
+
const pr = await discoveryFetch(globalThis.fetch, `Could not load ${baseUrl}/api/pricing`, `${baseUrl}/api/pricing`, () => ({ signal: AbortSignal.timeout(15000) }));
|
|
140
|
+
const pricing = await pr.json();
|
|
141
|
+
const free = new Set((pricing.endpoints || []).filter((e) => e.computePayable).map((e) => e.slug));
|
|
142
|
+
for (let i = meta.length - 1; i >= 0; i--) if (!free.has(meta[i].slug)) meta.splice(i, 1);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Strands `tool({...})` accepts a Zod schema directly. Convert from the
|
|
146
|
+
// simple JSON Schema shapes Agent402 emits, keeps users off needing their
|
|
147
|
+
// own conversion step. Strands callbacks can return any JSON-serializable
|
|
148
|
+
// value directly, so no string-wrapping step is needed here.
|
|
149
|
+
const tools = meta.map((m) => strands.tool({
|
|
150
|
+
name: m.name,
|
|
151
|
+
description: m.description,
|
|
152
|
+
inputSchema: jsonSchemaToZod(m.schema, z),
|
|
153
|
+
callback: async (input) => client.call(m.slug, input ?? {}),
|
|
154
|
+
}));
|
|
155
|
+
|
|
156
|
+
return { client, tools, execute: makeExecute(client, meta) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function loadStrands() {
|
|
160
|
+
try {
|
|
161
|
+
return await import("@strands-agents/sdk");
|
|
162
|
+
} catch {
|
|
163
|
+
throw new Error("agent402-agent-loop-tools requires '@strands-agents/sdk'. Install it with: npm install @strands-agents/sdk");
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function loadZod() {
|
|
168
|
+
try {
|
|
169
|
+
return await import("zod");
|
|
170
|
+
} catch {
|
|
171
|
+
throw new Error("agent402-agent-loop-tools requires 'zod'. Install it with: npm install zod");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function makeExecute(client, meta) {
|
|
176
|
+
const nameToSlug = new Map(meta.map((m) => [m.name, m.slug]));
|
|
177
|
+
return async function execute(name, args) {
|
|
178
|
+
const slug = nameToSlug.get(name) || name;
|
|
179
|
+
return client.call(slug, args ?? {});
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Standalone executor for users who built their tool list a different way.
|
|
185
|
+
* Returns an `execute(name, args)` that calls Agent402 with PoW or x402 payment.
|
|
186
|
+
*/
|
|
187
|
+
export function agent402Execute({ baseUrl = DEFAULT_BASE, fetch: payFetch, maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
188
|
+
const client = new Agent402({ userAgent: USER_AGENT, baseUrl, fetch: payFetch, ...capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client }) });
|
|
189
|
+
return async function execute(name, args) {
|
|
190
|
+
return client.call(name, args ?? {});
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Minimal JSON Schema → Zod converter for the shapes Agent402 emits. Object
|
|
195
|
+
// schemas with primitive/array/object properties cover every tool in the
|
|
196
|
+
// catalog; anything we don't recognize falls back to z.any().
|
|
197
|
+
function jsonSchemaToZod(schema, z) {
|
|
198
|
+
if (!schema || schema.type !== "object" || !schema.properties) return z.object({}).passthrough();
|
|
199
|
+
const shape = {};
|
|
200
|
+
const required = new Set(schema.required || []);
|
|
201
|
+
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
202
|
+
let s;
|
|
203
|
+
switch (prop?.type) {
|
|
204
|
+
case "string": s = z.string(); break;
|
|
205
|
+
case "number": case "integer": s = z.number(); break;
|
|
206
|
+
case "boolean": s = z.boolean(); break;
|
|
207
|
+
case "array": s = z.array(z.any()); break;
|
|
208
|
+
case "object": s = z.record(z.any()); break;
|
|
209
|
+
default: s = z.any();
|
|
210
|
+
}
|
|
211
|
+
if (prop?.description) s = s.describe(prop.description);
|
|
212
|
+
if (!required.has(key)) s = s.optional();
|
|
213
|
+
shape[key] = s;
|
|
214
|
+
}
|
|
215
|
+
// passthrough() lets extra fields the model invents pass through to the
|
|
216
|
+
// tool: Agent402 ignores unknowns anyway, and over-strict schemas confuse
|
|
217
|
+
// agents.
|
|
218
|
+
return z.object(shape).passthrough();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function shortDesc(summary, description) {
|
|
222
|
+
const d = (description || summary || "").split("\n\n")[0].trim();
|
|
223
|
+
return d.length > 280 ? d.slice(0, 277) + "..." : d;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export default agent402Tools;
|
|
227
|
+
|
|
228
|
+
/** The opt-in spending caps a caller passed, as agent402-client options.
|
|
229
|
+
* None are set by default: a caller who sets none is never refused a
|
|
230
|
+
* purchase. */
|
|
231
|
+
function capOptions({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd, x402Client } = {}) {
|
|
232
|
+
const out = {};
|
|
233
|
+
for (const [k, v] of Object.entries({ maxPerCallUsd, dailyLimitUsd, maxPerHostUsd })) if (v != null) out[k] = v;
|
|
234
|
+
if (x402Client) out.x402Client = x402Client;
|
|
235
|
+
return out;
|
|
236
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent402-agent-loop-tools",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Agent402 tools for use with Strands Agents for TypeScript (Agentic Finance over x402 or MPP): turn tools from Agent402's catalog of 500+ pay-per-call tools and skill packs into tool() instances, one per catalog tool, with payment handled by agent402-client. 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-strands.",
|
|
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
|
+
"strands",
|
|
27
|
+
"strands-agents",
|
|
28
|
+
"x402",
|
|
29
|
+
"ai-agents",
|
|
30
|
+
"agent-tools",
|
|
31
|
+
"llm-tools",
|
|
32
|
+
"usdc",
|
|
33
|
+
"base",
|
|
34
|
+
"proof-of-work",
|
|
35
|
+
"http-402",
|
|
36
|
+
"micropayments",
|
|
37
|
+
"agent402",
|
|
38
|
+
"tool-discovery",
|
|
39
|
+
"smart-order-router",
|
|
40
|
+
"mcp",
|
|
41
|
+
"agentic-commerce",
|
|
42
|
+
"agentic-finance",
|
|
43
|
+
"aifi",
|
|
44
|
+
"mpp",
|
|
45
|
+
"machine-payments-protocol",
|
|
46
|
+
"agentic-payments"
|
|
47
|
+
],
|
|
48
|
+
"author": "Cardhavok LLC (doing business as Havok Holdings LLC) <mike@agent402.tools> (https://github.com/MikeyPetrillo/Agent402)",
|
|
49
|
+
"license": "MIT",
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/MikeyPetrillo/Agent402.git",
|
|
53
|
+
"directory": "adapters/strands"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://agent402.tools",
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"agent402-client": ">=0.8.21 <1.0.0"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"@strands-agents/sdk": ">=1 <2",
|
|
61
|
+
"zod": ">=3 <5"
|
|
62
|
+
},
|
|
63
|
+
"peerDependenciesMeta": {
|
|
64
|
+
"@strands-agents/sdk": {
|
|
65
|
+
"optional": true
|
|
66
|
+
},
|
|
67
|
+
"zod": {
|
|
68
|
+
"optional": true
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|