agentsla 2.0.3 → 2.2.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/README.md +193 -41
- package/index.js +313 -76
- package/package.json +12 -3
package/README.md
CHANGED
|
@@ -1,19 +1,11 @@
|
|
|
1
|
-
# AgentSLA (`agentsla` v2.0
|
|
1
|
+
# AgentSLA (`agentsla` v2.2.0)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
**Check an API before your agent pays it.** AgentSLA checks whether an API or MCP server answers within your
|
|
4
|
+
latency limit (HTTP 2xx/3xx), signs the result with its oracle (EIP-712), and offers refundable USDC escrow on Base.
|
|
5
5
|
|
|
6
|
-
- **Site:** [https://agentsla.io](https://agentsla.io)
|
|
7
|
-
- **MCP server (
|
|
8
|
-
- **
|
|
9
|
-
- **OpenAPI:** [https://agentsla.io/openapi.json](https://agentsla.io/openapi.json)
|
|
10
|
-
- **llms.txt:** [https://agentsla.io/llms.txt](https://agentsla.io/llms.txt)
|
|
11
|
-
- **Escrow contract (Base):** `0x5c8D11AB570D7384d01226bC80123D0dD103Fb57`
|
|
12
|
-
- **USDC (Base):** `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`
|
|
13
|
-
|
|
14
|
-
> **Upgrade from 2.0.2 or earlier.** Those versions pointed at a retired escrow contract
|
|
15
|
-
> (`0x6ca6cDDd…99Ba79CD`) and sent `jobId: 1` with every `verifyEndpoint` call. 2.0.3 uses the current contract
|
|
16
|
-
> and only sends `jobId` when you pass one.
|
|
6
|
+
- **Site:** [agentsla.io](https://agentsla.io) · **Docs:** [agentsla.io/docs](https://agentsla.io/docs)
|
|
7
|
+
- **MCP server (Streamable HTTP):** `https://agentsla.io/mcp` · **OpenAPI:** `https://agentsla.io/openapi.json`
|
|
8
|
+
- **Contract security:** [agentsla.io/docs#security](https://agentsla.io/docs#security)
|
|
17
9
|
|
|
18
10
|
## Install
|
|
19
11
|
|
|
@@ -21,55 +13,215 @@ EIP-712 signed SLA checks, and use refundable USDC escrow on **Base Mainnet (cha
|
|
|
21
13
|
npm install agentsla ethers
|
|
22
14
|
```
|
|
23
15
|
|
|
24
|
-
##
|
|
16
|
+
## Check before paying (free)
|
|
25
17
|
|
|
26
18
|
```javascript
|
|
27
19
|
import { AgentSLA } from "agentsla";
|
|
28
20
|
|
|
29
21
|
const sla = new AgentSLA();
|
|
30
|
-
const
|
|
31
|
-
|
|
22
|
+
const { ok, reason } = await sla.checkBeforePaying("https://api.example.com/v1/quote", { maxLatencyMs: 1500 });
|
|
23
|
+
if (!ok) throw new Error("Not paying: " + reason);
|
|
32
24
|
```
|
|
33
25
|
|
|
34
|
-
|
|
26
|
+
10 free checks per month per IP. With a 7-day pass on the agent's wallet they are unlimited.
|
|
27
|
+
|
|
28
|
+
## Signed checks, paid automatically
|
|
29
|
+
|
|
30
|
+
Give the SDK the agent's own Base wallet. A signed check uses the wallet's pass if it has one, otherwise it pays
|
|
31
|
+
**0.05 USDC per check with x402**: one USDC signature, no gas, no approval.
|
|
32
|
+
|
|
33
|
+
```javascript
|
|
34
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY }); // or { signer } (any ethers v6 Signer)
|
|
35
|
+
|
|
36
|
+
const signed = await sla.verifyEndpoint({ endpointUrl: "https://api.example.com/health" });
|
|
37
|
+
console.log(signed.slaMet, signed.httpStatus, signed.latencyMs, signed.eip712Signature, signed.oracleSigner);
|
|
38
|
+
```
|
|
35
39
|
|
|
36
|
-
|
|
40
|
+
Many checks? Buy a **7-day pass** (5 USDC, also one signature, no gas):
|
|
37
41
|
|
|
38
42
|
```javascript
|
|
39
|
-
|
|
40
|
-
console.log(check.httpStatus, check.edgeLatencyMs, check.meetsSla);
|
|
43
|
+
if (!(await sla.isSubscribed())) await sla.buyPass();
|
|
41
44
|
```
|
|
42
45
|
|
|
43
|
-
|
|
46
|
+
`pay: "pass" | "x402" | "none"` (constructor or per call) forces one payment method. Verify any signature yourself
|
|
47
|
+
with `ethers.verifyTypedData`, using the domain and types from `GET https://agentsla.io/v1/attestations?url=...`.
|
|
48
|
+
|
|
49
|
+
> **Pass access needs a wallet signature (since 2.1).** Pass purchases are public on-chain, so a bare `walletAddress`
|
|
50
|
+
> no longer unlocks a pass. The SDK signs a short message with the pass wallet automatically. Calling the API
|
|
51
|
+
> directly? See [Pass access without the SDK](#pass-access-without-the-sdk).
|
|
44
52
|
|
|
45
|
-
|
|
46
|
-
|
|
53
|
+
## x402 guard: check every payment automatically
|
|
54
|
+
|
|
55
|
+
Put the guard **under** your x402 client, and every x402 payment your agent makes is checked with AgentSLA first.
|
|
56
|
+
The payment is stopped (and never sent) when the API is down or too slow, when it asks to be paid at a different
|
|
57
|
+
address than it shows AgentSLA, or when the price is above your limit.
|
|
47
58
|
|
|
48
59
|
```javascript
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
60
|
+
import { AgentSLA, withAgentSLAGuard } from "agentsla";
|
|
61
|
+
|
|
62
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY }); // a pass on this wallet = unlimited checks
|
|
63
|
+
const guardedFetch = withAgentSLAGuard(fetch, { client: sla, maxLatencyMs: 1500, maxPaymentUsdc: 2 });
|
|
64
|
+
|
|
65
|
+
// with any x402 client that takes a fetch, e.g. x402-fetch:
|
|
66
|
+
const payFetch = wrapFetchWithPayment(guardedFetch, wallet);
|
|
67
|
+
const res = await payFetch("https://api.example.com/paid-endpoint"); // throws AgentSLAGuardError if blocked
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
No x402 library yet? The SDK pays x402 APIs on Base itself, with the guard built in:
|
|
71
|
+
|
|
72
|
+
```javascript
|
|
73
|
+
const res = await sla.payX402("https://api.example.com/paid-endpoint", {}, { maxPaymentUsdc: 1 });
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
| Option | Default | Meaning |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| `maxLatencyMs` | `1000` | The API must answer within this time. An x402 API answering 402 with a valid offer counts as up. |
|
|
79
|
+
| `maxPaymentUsdc` | no limit (`payX402`: 1) | Refuse payments above this price. |
|
|
80
|
+
| `signedAboveUsdc` | `1` | Payments of this size or more get an oracle-signed check (pass or 0.05 USDC). |
|
|
81
|
+
| `cacheSeconds` | `60` | Reuse a passing check for the same URL this long. |
|
|
82
|
+
| `onCheckError` | `"allow"` | If AgentSLA can't answer: `"allow"` (an AgentSLA outage never stops your agent) or `"block"`. |
|
|
83
|
+
| `allowHosts` / `denyHosts` | `[]` | Hosts that skip the check / are always refused. |
|
|
84
|
+
| `onBlock(details)` / `onWarn(details)` | none | Called when a payment is blocked / goes ahead unchecked. |
|
|
85
|
+
|
|
86
|
+
A blocked payment throws `AgentSLAGuardError` (`err.url`, `err.reason`, `err.check`) before the signed payment
|
|
87
|
+
leaves the agent, so the seller never receives it and nothing is charged. Checks use the agent wallet's 7-day pass
|
|
88
|
+
when it has one (unlimited); otherwise the 10 free checks a month, then x402.
|
|
89
|
+
|
|
90
|
+
## Use it in your agent framework
|
|
91
|
+
|
|
92
|
+
The MCP server gives any framework the free tools (directory search, live checks, pass status, escrow quotes). For
|
|
93
|
+
signed checks paid from the agent's wallet, add the SDK tools.
|
|
94
|
+
|
|
95
|
+
### Any framework: `agentslaTools()`
|
|
96
|
+
|
|
97
|
+
Three tools with JSON Schema parameters and an `execute` function: `check_before_paying` (free), `signed_check`
|
|
98
|
+
(pass or 0.05 USDC) and `find_apis`.
|
|
99
|
+
|
|
100
|
+
```javascript
|
|
101
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
102
|
+
const tools = agentslaTools(new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY }));
|
|
103
|
+
// each: { name, description, parameters (JSON Schema), execute(args) }
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### OpenAI Agents SDK (TypeScript)
|
|
107
|
+
|
|
108
|
+
```javascript
|
|
109
|
+
import { Agent, run, tool, MCPServerStreamableHttp } from "@openai/agents";
|
|
110
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
111
|
+
|
|
112
|
+
const mcp = new MCPServerStreamableHttp({ name: "agentsla", url: "https://agentsla.io/mcp" });
|
|
113
|
+
await mcp.connect();
|
|
114
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY });
|
|
115
|
+
const paid = agentslaTools(sla).map((t) => tool({ name: t.name, description: t.description, parameters: t.parameters, strict: false, execute: t.execute }));
|
|
116
|
+
|
|
117
|
+
const agent = new Agent({
|
|
118
|
+
name: "Buyer",
|
|
119
|
+
instructions: "Before paying or relying on any external API, call check_before_paying and stop if ok is false.",
|
|
120
|
+
mcpServers: [mcp],
|
|
121
|
+
tools: paid
|
|
122
|
+
});
|
|
123
|
+
console.log((await run(agent, "Is https://api.example.com/v1/quote safe to pay right now?")).finalOutput);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### OpenAI Agents SDK (Python)
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from agents import Agent, Runner
|
|
130
|
+
from agents.mcp import MCPServerStreamableHttp
|
|
131
|
+
|
|
132
|
+
async with MCPServerStreamableHttp(name="agentsla", params={"url": "https://agentsla.io/mcp"}) as agentsla:
|
|
133
|
+
agent = Agent(name="Buyer", mcp_servers=[agentsla],
|
|
134
|
+
instructions="Before paying or relying on any external API, call check_endpoint and stop if meetsSla is false.")
|
|
135
|
+
print((await Runner.run(agent, "Check https://api.example.com/v1/quote before I pay it.")).final_output)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### LangChain / LangGraph (Python)
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
from langchain_mcp_adapters.client import MultiServerMCPClient
|
|
142
|
+
from langgraph.prebuilt import create_react_agent
|
|
143
|
+
|
|
144
|
+
client = MultiServerMCPClient({"agentsla": {"url": "https://agentsla.io/mcp", "transport": "streamable_http"}})
|
|
145
|
+
tools = await client.get_tools()
|
|
146
|
+
agent = create_react_agent("openai:gpt-4.1", tools)
|
|
147
|
+
await agent.ainvoke({"messages": "Find a weather API on AgentSLA and check it before I pay it."})
|
|
53
148
|
```
|
|
54
149
|
|
|
55
|
-
|
|
56
|
-
`ethers.verifyTypedData` using the domain and types from `GET https://agentsla.io/v1/attestations?url=...`.
|
|
150
|
+
### CrewAI (Python)
|
|
57
151
|
|
|
58
|
-
|
|
152
|
+
```python
|
|
153
|
+
from crewai import Agent
|
|
154
|
+
from crewai_tools import MCPServerAdapter
|
|
155
|
+
|
|
156
|
+
with MCPServerAdapter({"url": "https://agentsla.io/mcp", "transport": "streamable-http"}) as tools:
|
|
157
|
+
buyer = Agent(role="API buyer", goal="Only pay APIs that pass a live AgentSLA check",
|
|
158
|
+
backstory="Careful with money.", tools=tools)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### Vercel AI SDK
|
|
59
162
|
|
|
60
163
|
```javascript
|
|
61
|
-
|
|
164
|
+
import { generateText, tool, jsonSchema, stepCountIs } from "ai";
|
|
165
|
+
import { openai } from "@ai-sdk/openai";
|
|
166
|
+
import { AgentSLA, agentslaTools } from "agentsla";
|
|
167
|
+
|
|
168
|
+
const sla = new AgentSLA({ privateKey: process.env.AGENT_PRIVATE_KEY });
|
|
169
|
+
const tools = Object.fromEntries(agentslaTools(sla).map((t) => [t.name, tool({ description: t.description, inputSchema: jsonSchema(t.parameters), execute: t.execute })]));
|
|
170
|
+
|
|
171
|
+
const { text } = await generateText({ model: openai("gpt-4.1"), tools, stopWhen: stepCountIs(5),
|
|
172
|
+
prompt: "Check https://api.example.com/v1/quote before paying it." });
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Framework APIs move quickly: if a snippet doesn't match your version, the parts that stay the same are the MCP URL
|
|
176
|
+
(`https://agentsla.io/mcp`, Streamable HTTP) and `agentslaTools()` (JSON Schema + `execute`).
|
|
177
|
+
|
|
178
|
+
## Pass access without the SDK
|
|
179
|
+
|
|
180
|
+
Sign this message with the pass wallet (EIP-191 `personal_sign`, no gas), within 5 minutes of the request:
|
|
181
|
+
|
|
182
|
+
```
|
|
183
|
+
AgentSLA pass access
|
|
184
|
+
Wallet: <checksummed wallet address>
|
|
185
|
+
Signed at: <unix seconds>
|
|
62
186
|
```
|
|
63
187
|
|
|
64
|
-
|
|
65
|
-
`
|
|
188
|
+
Then send `walletAddress`, `walletSignedAt` and `walletSignature` in the JSON body of `POST /v1/verify` (or as MCP
|
|
189
|
+
arguments to `verify_endpoint_sla`), or the header `X-AgentSLA-Wallet-Auth: <signedAt>.<signature>`.
|
|
66
190
|
|
|
67
|
-
|
|
191
|
+
Python (`eth-account`):
|
|
68
192
|
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
193
|
+
```python
|
|
194
|
+
import os, time, requests
|
|
195
|
+
from eth_account import Account
|
|
196
|
+
from eth_account.messages import encode_defunct
|
|
197
|
+
|
|
198
|
+
acct = Account.from_key(os.environ["AGENT_PRIVATE_KEY"])
|
|
199
|
+
ts = int(time.time())
|
|
200
|
+
sig = acct.sign_message(encode_defunct(text=f"AgentSLA pass access\nWallet: {acct.address}\nSigned at: {ts}")).signature.hex()
|
|
201
|
+
r = requests.post("https://agentsla.io/v1/verify", json={
|
|
202
|
+
"targetApiUrl": "https://api.example.com/health",
|
|
203
|
+
"walletAddress": acct.address, "walletSignedAt": ts, "walletSignature": sig if sig.startswith("0x") else "0x" + sig,
|
|
204
|
+
})
|
|
205
|
+
print(r.json())
|
|
75
206
|
```
|
|
207
|
+
|
|
208
|
+
## Escrow (beta)
|
|
209
|
+
|
|
210
|
+
`escrowTransactions({ apiId, providerAddress, priceUsdc })` returns the unsigned Base transactions that lock USDC for a
|
|
211
|
+
listing; the oracle pays the provider if the SLA is met and refunds you otherwise. See
|
|
212
|
+
[agentsla.io/docs#escrow](https://agentsla.io/docs#escrow).
|
|
213
|
+
|
|
214
|
+
## Changes in 2.2.0
|
|
215
|
+
|
|
216
|
+
- **x402 guard:** `withAgentSLAGuard(fetch)` checks every outgoing x402 payment with AgentSLA and blocks it when the API is down, too slow, priced above your limit, or asking to be paid at a different address than it shows AgentSLA.
|
|
217
|
+
- `payX402(url)`: a built-in x402 client for Base (v1 and v2), with the guard in front of every payment.
|
|
218
|
+
- `createX402Guard()`, `AgentSLAGuardError`, `signExact()`.
|
|
219
|
+
- Checks now treat an x402 paywall (HTTP 402 with a valid payment request) as up, and report its offer.
|
|
220
|
+
|
|
221
|
+
## Changes in 2.1.0
|
|
222
|
+
|
|
223
|
+
- `verifyEndpoint()` pays automatically: the wallet's pass (with a wallet signature), else 0.05 USDC by x402.
|
|
224
|
+
- New: `checkBeforePaying()`, `buyPass()` (x402, no gas), `passStatus()`, `passAuth()`, `x402Post()`, `agentslaTools()`,
|
|
225
|
+
`escrowTransactions()`.
|
|
226
|
+
- `subscribeSevenDays()` now buys the pass with `buyPass()` (no approval). `isSubscribed()` counts passes bought either way.
|
|
227
|
+
- `discoverApis()` and every call use `https://agentsla.io`.
|
package/index.js
CHANGED
|
@@ -2,132 +2,369 @@
|
|
|
2
2
|
|
|
3
3
|
export const AGENTSLA_CONFIG = {
|
|
4
4
|
API_URL: "https://agentsla.io",
|
|
5
|
-
ORACLE_URL: "https://agentsla-oracle.agentsla-dev.workers.dev",
|
|
6
5
|
MCP_URL: "https://agentsla.io/mcp",
|
|
7
6
|
CHAIN_ID: 8453,
|
|
7
|
+
NETWORK: "eip155:8453",
|
|
8
8
|
RPC_URL: "https://mainnet.base.org",
|
|
9
|
-
// Current escrow contract (the one the oracle settles). 2.0.2 and earlier pointed at the retired 0x6ca6cDDd... contract.
|
|
10
9
|
ESCROW_CONTRACT: "0x5c8D11AB570D7384d01226bC80123D0dD103Fb57",
|
|
11
10
|
USDC_TOKEN: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
12
11
|
TREASURY_WALLET: "0x9A0d2dD2402991eC8095fE2Be0d96A59d9DCF13C"
|
|
13
12
|
};
|
|
14
13
|
|
|
15
|
-
const ESCROW_ABI = [
|
|
16
|
-
"function createJob(address _agent, uint256 _apiId, uint256 _lockedAmount) external returns (uint256)",
|
|
17
|
-
"function paySubscription() external"
|
|
18
|
-
];
|
|
19
|
-
|
|
20
14
|
const USDC_ABI = [
|
|
21
15
|
"function approve(address spender, uint256 amount) external returns (bool)",
|
|
22
16
|
"function allowance(address owner, address spender) view returns (uint256)",
|
|
23
|
-
"function balanceOf(address account) view returns (uint256)"
|
|
24
|
-
"function transfer(address to, uint256 amount) external returns (bool)"
|
|
17
|
+
"function balanceOf(address account) view returns (uint256)"
|
|
25
18
|
];
|
|
19
|
+
const TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
20
|
+
TransferWithAuthorization: [
|
|
21
|
+
{ name: "from", type: "address" }, { name: "to", type: "address" }, { name: "value", type: "uint256" },
|
|
22
|
+
{ name: "validAfter", type: "uint256" }, { name: "validBefore", type: "uint256" }, { name: "nonce", type: "bytes32" }
|
|
23
|
+
]
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const b64 = (s) => Buffer.from(s, "utf8").toString("base64");
|
|
27
|
+
const unb64 = (s) => Buffer.from(String(s), "base64").toString("utf8");
|
|
28
|
+
|
|
29
|
+
/** The message a pass wallet signs (personal_sign) to prove it is the caller. Valid for 5 minutes. */
|
|
30
|
+
export function passAuthMessage(wallet, signedAt) {
|
|
31
|
+
return "AgentSLA pass access\nWallet: " + ethers.getAddress(wallet) + "\nSigned at: " + Math.floor(Number(signedAt));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class AgentSLAError extends Error {
|
|
35
|
+
constructor(message, status, body) { super(message); this.name = "AgentSLAError"; this.status = status; this.body = body; }
|
|
36
|
+
}
|
|
37
|
+
/** Thrown by the x402 guard when it stops a payment. The payment was never sent, so nothing was charged. */
|
|
38
|
+
export class AgentSLAGuardError extends AgentSLAError {
|
|
39
|
+
constructor(message, details) { super(message, 0, details); this.name = "AgentSLAGuardError"; this.url = details && details.url; this.reason = details && details.reason; this.check = details && details.check; }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---- x402 helpers ----
|
|
43
|
+
// Reads the x402 offer from a 402 response: v2 PAYMENT-REQUIRED header, else the v1 JSON body. { version, resource, accepts } | null
|
|
44
|
+
async function readOffer(res) {
|
|
45
|
+
let pr = null;
|
|
46
|
+
const h = res.headers.get("payment-required");
|
|
47
|
+
if (h) { try { pr = JSON.parse(unb64(h)); } catch {} }
|
|
48
|
+
if (!pr) { try { pr = JSON.parse(await res.clone().text()); } catch {} }
|
|
49
|
+
return pr && Array.isArray(pr.accepts) && pr.accepts.length ? pr : null;
|
|
50
|
+
}
|
|
51
|
+
// What an outgoing x402 payment header pays: { amountUsdc, payTo, network } (best effort; v1 X-PAYMENT or v2 PAYMENT-SIGNATURE)
|
|
52
|
+
function readPayment(headerValue) {
|
|
53
|
+
let p; try { p = JSON.parse(unb64(headerValue)); } catch { return null; }
|
|
54
|
+
const acc = p.accepted || {}, auth = (p.payload && p.payload.authorization) || {};
|
|
55
|
+
const atomic = acc.amount ?? auth.value ?? null;
|
|
56
|
+
return { amountUsdc: atomic != null ? Number(atomic) / 1e6 : null, payTo: acc.payTo || auth.to || null, network: acc.network || p.network || null, version: Number(p.x402Version) || null };
|
|
57
|
+
}
|
|
58
|
+
const sameAddress = (a, b) => (String(a).startsWith("0x") ? String(a).toLowerCase() === String(b).toLowerCase() : String(a) === String(b));
|
|
59
|
+
const BASE_NETWORKS = new Set(["eip155:8453", "base"]);
|
|
26
60
|
|
|
27
61
|
export class AgentSLA {
|
|
62
|
+
/**
|
|
63
|
+
* @param {object} [options]
|
|
64
|
+
* @param {string} [options.privateKey] the agent's own Base wallet key (needed only to pay or use a pass)
|
|
65
|
+
* @param {import("ethers").Signer} [options.signer] or any ethers v6 Signer (wallet, KMS, smart account adapter)
|
|
66
|
+
* @param {"auto"|"pass"|"x402"|"none"} [options.pay="auto"] how signed checks are paid: an active pass first, else 0.05 USDC by x402
|
|
67
|
+
*/
|
|
28
68
|
constructor(options = {}) {
|
|
29
69
|
this.apiUrl = (options.apiUrl || AGENTSLA_CONFIG.API_URL).replace(/\/+$/, "");
|
|
30
|
-
this.oracleUrl = options.oracleUrl || AGENTSLA_CONFIG.ORACLE_URL;
|
|
31
70
|
this.mcpUrl = options.mcpUrl || AGENTSLA_CONFIG.MCP_URL;
|
|
32
|
-
this.
|
|
33
|
-
this.
|
|
34
|
-
this.
|
|
71
|
+
this.provider = new ethers.JsonRpcProvider(options.rpcUrl || AGENTSLA_CONFIG.RPC_URL, AGENTSLA_CONFIG.CHAIN_ID, { staticNetwork: true });
|
|
72
|
+
this.signer = options.signer || (options.privateKey ? new ethers.Wallet(options.privateKey, this.provider) : null);
|
|
73
|
+
this.pay = options.pay || "auto";
|
|
35
74
|
}
|
|
36
75
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
76
|
+
async address() { return this.signer ? await this.signer.getAddress() : null; }
|
|
77
|
+
#needSigner() { if (!this.signer) throw new AgentSLAError("This needs the agent's wallet: construct AgentSLA with { privateKey } or { signer }.", 0); }
|
|
78
|
+
|
|
79
|
+
async #json(path, init = {}) {
|
|
80
|
+
const res = await fetch(this.apiUrl + path, init);
|
|
81
|
+
const text = await res.text();
|
|
82
|
+
let body; try { body = JSON.parse(text); } catch { body = { raw: text.slice(0, 500) }; }
|
|
83
|
+
return { res, body };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------- free ----------------
|
|
87
|
+
|
|
88
|
+
/** Search the directory of APIs and MCP servers (indexed and probed, not audited). */
|
|
41
89
|
async discoverApis(filter = {}) {
|
|
42
90
|
const params = new URLSearchParams();
|
|
43
|
-
if (typeof filter === "string") {
|
|
44
|
-
|
|
45
|
-
} else if (filter && typeof filter === "object") {
|
|
91
|
+
if (typeof filter === "string") { if (filter && filter !== "all") params.set("category", filter); }
|
|
92
|
+
else {
|
|
46
93
|
if (filter.category && filter.category !== "all") params.set("category", filter.category);
|
|
47
|
-
if (filter.search) params.set("
|
|
94
|
+
if (filter.search || filter.q) params.set("q", filter.search || filter.q);
|
|
48
95
|
if (filter.limit) params.set("limit", String(filter.limit));
|
|
49
96
|
if (filter.offset) params.set("offset", String(filter.offset));
|
|
50
97
|
}
|
|
51
98
|
const qs = params.toString();
|
|
52
|
-
|
|
53
|
-
return await res.json();
|
|
99
|
+
return (await this.#json("/v1/directory" + (qs ? "?" + qs : ""))).body;
|
|
54
100
|
}
|
|
55
101
|
|
|
56
|
-
/**
|
|
57
|
-
* Call the remote Streamable HTTP MCP server at https://agentsla.io/mcp
|
|
58
|
-
*/
|
|
102
|
+
/** Call a tool on the MCP server (https://agentsla.io/mcp). Returns the parsed tool result. */
|
|
59
103
|
async callMcpTool(name, args = {}) {
|
|
60
104
|
const res = await fetch(this.mcpUrl, {
|
|
61
105
|
method: "POST",
|
|
62
106
|
headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
63
|
-
body: JSON.stringify({
|
|
64
|
-
jsonrpc: "2.0",
|
|
65
|
-
id: Date.now(),
|
|
66
|
-
method: "tools/call",
|
|
67
|
-
params: { name, arguments: args }
|
|
68
|
-
})
|
|
107
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: Date.now(), method: "tools/call", params: { name, arguments: args } })
|
|
69
108
|
});
|
|
70
|
-
|
|
109
|
+
const j = await res.json();
|
|
110
|
+
const text = j && j.result && j.result.content && j.result.content[0] && j.result.content[0].text;
|
|
111
|
+
let data = text; try { data = JSON.parse(text); } catch {}
|
|
112
|
+
return { isError: !!(j.result && j.result.isError), data, raw: j };
|
|
71
113
|
}
|
|
72
114
|
|
|
73
115
|
/**
|
|
74
|
-
*
|
|
116
|
+
* Unsigned live check: HTTP status, latency and the SLA rule (2xx/3xx within maxLatencyMs).
|
|
117
|
+
* 10 free per month per IP; with an active pass on the agent's wallet it is unlimited (signed automatically).
|
|
75
118
|
*/
|
|
76
|
-
async checkEndpoint({ endpointUrl, maxLatencyMs = 1000 }) {
|
|
119
|
+
async checkEndpoint({ endpointUrl, maxLatencyMs = 1000 } = {}) {
|
|
77
120
|
const qs = new URLSearchParams({ url: endpointUrl, max_latency_ms: String(maxLatencyMs) });
|
|
78
|
-
const
|
|
79
|
-
|
|
121
|
+
const headers = {};
|
|
122
|
+
if (this.signer && this.pay !== "none" && (await this.#hasPass())) {
|
|
123
|
+
const a = await this.passAuth();
|
|
124
|
+
qs.set("wallet", a.walletAddress);
|
|
125
|
+
headers["X-AgentSLA-Wallet-Auth"] = a.walletSignedAt + "." + a.walletSignature;
|
|
126
|
+
}
|
|
127
|
+
const { res, body } = await this.#json("/v1/verify?" + qs, { headers });
|
|
128
|
+
if (res.status === 402) body.paymentRequired = true;
|
|
129
|
+
return body;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Pass status for a wallet (default: the agent's wallet). Counts passes bought on-chain or at /v1/pass. */
|
|
133
|
+
async passStatus(address) {
|
|
134
|
+
const who = address || (await this.address());
|
|
135
|
+
if (!who) throw new AgentSLAError("Pass an address or construct AgentSLA with a wallet.", 0);
|
|
136
|
+
return (await this.#json("/v1/pass?wallet=" + encodeURIComponent(who))).body;
|
|
80
137
|
}
|
|
138
|
+
async isSubscribed(address) { return !!(await this.passStatus(address)).active; }
|
|
139
|
+
|
|
140
|
+
// ---------------- wallet proof ----------------
|
|
141
|
+
|
|
142
|
+
/** Fresh proof that the agent controls its pass wallet: { walletAddress, walletSignedAt, walletSignature }. */
|
|
143
|
+
async passAuth() {
|
|
144
|
+
this.#needSigner();
|
|
145
|
+
const walletAddress = ethers.getAddress(await this.signer.getAddress());
|
|
146
|
+
const walletSignedAt = Math.floor(Date.now() / 1000);
|
|
147
|
+
const walletSignature = await this.signer.signMessage(passAuthMessage(walletAddress, walletSignedAt));
|
|
148
|
+
return { walletAddress, walletSignedAt, walletSignature };
|
|
149
|
+
}
|
|
150
|
+
async #hasPass() { try { return await this.isSubscribed(); } catch { return false; } }
|
|
151
|
+
|
|
152
|
+
// ---------------- paid ----------------
|
|
81
153
|
|
|
82
154
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* (that probes the job's registered endpoint and settles the job). Without either, the response is HTTP 402 and
|
|
86
|
-
* explains how to pay (pass, escrow job, or x402 at 0.05 USDC per check).
|
|
87
|
-
* 2.0.2 and earlier sent jobId 1 by default, which tried to settle escrow job #1 instead of checking endpointUrl.
|
|
155
|
+
* x402 v2 payment on Base: POST path, read the 402 offer, sign a USDC transferWithAuthorization (no gas, no approval),
|
|
156
|
+
* retry with PAYMENT-SIGNATURE. Returns { body, receipt } (receipt = the settlement from PAYMENT-RESPONSE).
|
|
88
157
|
*/
|
|
89
|
-
async
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
if (
|
|
102
|
-
|
|
158
|
+
async x402Post(path, body = {}, { maxAmountUsdc } = {}) {
|
|
159
|
+
this.#needSigner();
|
|
160
|
+
const init = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
|
|
161
|
+
const first = await this.#json(path, init);
|
|
162
|
+
if (first.res.status !== 402) {
|
|
163
|
+
if (first.res.ok) return { body: first.body, receipt: null };
|
|
164
|
+
throw new AgentSLAError(first.body.error || "HTTP " + first.res.status, first.res.status, first.body);
|
|
165
|
+
}
|
|
166
|
+
const hdr = first.res.headers.get("payment-required");
|
|
167
|
+
if (!hdr) throw new AgentSLAError("402 without a PAYMENT-REQUIRED header", 402, first.body);
|
|
168
|
+
const pr = JSON.parse(unb64(hdr));
|
|
169
|
+
const acc = (pr.accepts || []).find((a) => a.network === AGENTSLA_CONFIG.NETWORK && a.scheme === "exact");
|
|
170
|
+
if (!acc) throw new AgentSLAError("No Base payment option offered", 402, pr);
|
|
171
|
+
if (maxAmountUsdc != null && BigInt(acc.amount) > ethers.parseUnits(String(maxAmountUsdc), 6)) {
|
|
172
|
+
throw new AgentSLAError("Price " + ethers.formatUnits(acc.amount, 6) + " USDC is above maxAmountUsdc " + maxAmountUsdc, 402, pr);
|
|
173
|
+
}
|
|
174
|
+
const payment = b64(JSON.stringify({ x402Version: 2, resource: pr.resource, accepted: acc, payload: await this.signExact(acc) }));
|
|
175
|
+
const second = await this.#json(path, { ...init, headers: { ...init.headers, "PAYMENT-SIGNATURE": payment } });
|
|
176
|
+
const rh = second.res.headers.get("payment-response");
|
|
177
|
+
const receipt = rh ? JSON.parse(unb64(rh)) : null;
|
|
178
|
+
if (!second.res.ok) throw new AgentSLAError(second.body.error || "Payment not accepted (HTTP " + second.res.status + ")", second.res.status, second.body);
|
|
179
|
+
return { body: second.body, receipt };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Signs a USDC transferWithAuthorization for an x402 "exact" offer on Base. Returns the payload { signature, authorization }. */
|
|
183
|
+
async signExact(acc) {
|
|
184
|
+
this.#needSigner();
|
|
185
|
+
const from = ethers.getAddress(await this.signer.getAddress());
|
|
186
|
+
const now = Math.floor(Date.now() / 1000);
|
|
187
|
+
const authorization = { from, to: ethers.getAddress(acc.payTo), value: String(acc.amount ?? acc.maxAmountRequired), validAfter: String(now - 600), validBefore: String(now + Number(acc.maxTimeoutSeconds || 300)), nonce: ethers.hexlify(ethers.randomBytes(32)) };
|
|
188
|
+
const signature = await this.signer.signTypedData(
|
|
189
|
+
{ name: acc.extra && acc.extra.name ? acc.extra.name : "USD Coin", version: acc.extra && acc.extra.version ? acc.extra.version : "2", chainId: AGENTSLA_CONFIG.CHAIN_ID, verifyingContract: acc.asset },
|
|
190
|
+
TRANSFER_WITH_AUTHORIZATION_TYPES, authorization
|
|
191
|
+
);
|
|
192
|
+
return { signature, authorization };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Calls any x402 API and pays it in USDC on Base if it answers 402, with the AgentSLA guard in front of the payment.
|
|
197
|
+
* opts: { maxPaymentUsdc (default 1), guard: guard options (see withAgentSLAGuard) or false to skip the check }.
|
|
198
|
+
* Returns the API's Response; res.x402Payment holds the settlement receipt when one was returned.
|
|
199
|
+
*/
|
|
200
|
+
async payX402(url, init = {}, opts = {}) {
|
|
201
|
+
const first = await fetch(url, init);
|
|
202
|
+
if (first.status !== 402) return first;
|
|
203
|
+
const pr = await readOffer(first);
|
|
204
|
+
if (!pr) throw new AgentSLAError("HTTP 402 without an x402 payment request", 402);
|
|
205
|
+
const acc = pr.accepts.find((a) => BASE_NETWORKS.has(String(a.network)) && (a.scheme || "exact") === "exact");
|
|
206
|
+
if (!acc) throw new AgentSLAError("No x402 payment option on Base was offered", 402, pr);
|
|
207
|
+
const amountUsdc = Number(acc.amount ?? acc.maxAmountRequired) / 1e6;
|
|
208
|
+
const max = opts.maxPaymentUsdc ?? 1;
|
|
209
|
+
if (amountUsdc > max) throw new AgentSLAGuardError("Price " + amountUsdc + " USDC is above maxPaymentUsdc " + max + "; not paid.", { url, reason: "price above limit" });
|
|
210
|
+
if (opts.guard !== false) await createX402Guard({ client: this, ...(opts.guard || {}) }).assertSafe(url, { amountUsdc, payTo: acc.payTo, network: acc.network });
|
|
211
|
+
const payload = await this.signExact(acc);
|
|
212
|
+
const v2 = Number(pr.x402Version) >= 2;
|
|
213
|
+
const header = v2 ? b64(JSON.stringify({ x402Version: 2, resource: pr.resource, accepted: acc, payload }))
|
|
214
|
+
: b64(JSON.stringify({ x402Version: 1, scheme: acc.scheme || "exact", network: acc.network, payload }));
|
|
215
|
+
const headers = new Headers(init.headers || {});
|
|
216
|
+
headers.set(v2 ? "PAYMENT-SIGNATURE" : "X-PAYMENT", header);
|
|
217
|
+
const res = await fetch(url, { ...init, headers });
|
|
218
|
+
const rh = res.headers.get(v2 ? "payment-response" : "x-payment-response");
|
|
219
|
+
try { res.x402Payment = rh ? JSON.parse(unb64(rh)) : null; } catch { res.x402Payment = null; }
|
|
220
|
+
return res;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Buy a 7-day pass: 5 USDC on Base with one signature (x402 at /v1/pass), no gas, no approval. */
|
|
224
|
+
async buyPass() {
|
|
225
|
+
const { body, receipt } = await this.x402Post("/v1/pass", {});
|
|
226
|
+
return { ...body, receipt };
|
|
103
227
|
}
|
|
228
|
+
/** @deprecated since 2.1: use buyPass() (no approval, no gas). Kept so existing code keeps working. */
|
|
229
|
+
async subscribeSevenDays() { return this.buyPass(); }
|
|
104
230
|
|
|
105
|
-
/**
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Signed check: probes the endpoint and returns an EIP-712 SLA attestation from the oracle.
|
|
233
|
+
* Payment (pay option): "auto" uses the wallet's pass if active (with a fresh wallet signature), else pays 0.05 USDC by x402;
|
|
234
|
+
* "pass" only uses the pass; "x402" always pays per check. jobId settles that escrow job instead (no payment).
|
|
235
|
+
*/
|
|
236
|
+
async verifyEndpoint({ endpointUrl, maxLatencyMs, payload, jobId, pay } = {}) {
|
|
237
|
+
const mode = pay || this.pay;
|
|
238
|
+
const body = { targetApiUrl: endpointUrl };
|
|
239
|
+
if (maxLatencyMs) body.maxLatencyMs = maxLatencyMs;
|
|
240
|
+
if (payload && Object.keys(payload).length) body.targetApiPayload = payload;
|
|
241
|
+
if (jobId) {
|
|
242
|
+
body.jobId = jobId;
|
|
243
|
+
return (await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })).body;
|
|
244
|
+
}
|
|
245
|
+
if (mode !== "x402" && this.signer && (mode === "pass" || (await this.#hasPass()))) {
|
|
246
|
+
Object.assign(body, await this.passAuth());
|
|
247
|
+
const { res, body: out } = await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
248
|
+
if (res.ok || mode === "pass") { if (res.status === 402 || res.status === 401) out.paymentRequired = true; return out; }
|
|
249
|
+
}
|
|
250
|
+
if (mode === "none" || mode === "pass" || !this.signer) {
|
|
251
|
+
const { res, body: out } = await this.#json("/v1/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
252
|
+
if (res.status === 402) out.paymentRequired = true;
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
const { body: out, receipt } = await this.x402Post("/v1/verify", body, { maxAmountUsdc: "0.05" });
|
|
256
|
+
return { ...out, payment: out.payment || receipt };
|
|
111
257
|
}
|
|
112
258
|
|
|
113
259
|
/**
|
|
114
|
-
*
|
|
260
|
+
* One call before your agent pays or depends on an API: live check against the SLA rule.
|
|
261
|
+
* Returns { ok, reason, check }. signed: true returns the oracle-signed result (pass or 0.05 USDC).
|
|
115
262
|
*/
|
|
116
|
-
async
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
263
|
+
async checkBeforePaying(endpointUrl, { maxLatencyMs = 1000, signed = false } = {}) {
|
|
264
|
+
const check = signed ? await this.verifyEndpoint({ endpointUrl, maxLatencyMs }) : await this.checkEndpoint({ endpointUrl, maxLatencyMs });
|
|
265
|
+
if (check.paymentRequired || check.error) return { ok: false, reason: check.error || "payment required", check };
|
|
266
|
+
const met = signed ? check.slaMet === true : check.meetsSla === true;
|
|
267
|
+
const status = check.httpStatus, ms = signed ? check.latencyMs : check.edgeLatencyMs;
|
|
268
|
+
return { ok: met, reason: met ? "HTTP " + status + " in " + ms + " ms (limit " + maxLatencyMs + ")" : "SLA not met: HTTP " + status + " in " + ms + " ms (limit " + maxLatencyMs + ")", check };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ---------------- escrow ----------------
|
|
272
|
+
|
|
273
|
+
/** The unsigned Base transactions that lock USDC in escrow for a listing (via the MCP tool create_escrow_job). */
|
|
274
|
+
async escrowTransactions({ apiId, providerAddress, priceUsdc }) {
|
|
275
|
+
const walletAddress = await this.address();
|
|
276
|
+
if (!walletAddress) this.#needSigner();
|
|
277
|
+
return (await this.callMcpTool("create_escrow_job", { walletAddress, apiId, providerAddress, priceUsdc })).data;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* The x402 guard. Checks an endpoint with AgentSLA right before a payment to it, and refuses to pay when:
|
|
283
|
+
* - the endpoint is down or slower than maxLatencyMs (an x402 paywall, HTTP 402 with a valid offer, counts as up),
|
|
284
|
+
* - the payment goes to a different address than the endpoint advertises to AgentSLA's own probe (swapped recipient),
|
|
285
|
+
* - the price is above maxPaymentUsdc, or the host is on denyHosts.
|
|
286
|
+
* Payments of signedAboveUsdc or more get an oracle-signed check (pass or 0.05 USDC); smaller ones the free/pass check.
|
|
287
|
+
* Passing results are cached per URL for cacheSeconds. If AgentSLA itself can't answer, onCheckError decides
|
|
288
|
+
* ("allow" by default, so an AgentSLA outage never stops an agent; "block" for strict setups).
|
|
289
|
+
*/
|
|
290
|
+
export function createX402Guard(opts = {}) {
|
|
291
|
+
const o = { maxLatencyMs: 1000, signedAboveUsdc: 1, maxPaymentUsdc: Infinity, cacheSeconds: 60, onCheckError: "allow", allowHosts: [], denyHosts: [], ...opts };
|
|
292
|
+
const client = o.client || new AgentSLA();
|
|
293
|
+
const cache = new Map();
|
|
294
|
+
const host = (u) => { try { return new URL(u).hostname.toLowerCase(); } catch { return ""; } };
|
|
295
|
+
async function assertSafe(url, payment = {}) {
|
|
296
|
+
const h = host(url), amount = payment.amountUsdc;
|
|
297
|
+
const block = (reason, check) => { const d = { url, reason, check, payment }; if (o.onBlock) { try { o.onBlock(d); } catch {} } throw new AgentSLAGuardError("AgentSLA guard stopped the payment to " + url + ": " + reason + ". Nothing was paid.", d); };
|
|
298
|
+
if (o.denyHosts.includes(h)) block("host is on denyHosts");
|
|
299
|
+
if (o.allowHosts.includes(h)) return { allowed: true, reason: "host is on allowHosts" };
|
|
300
|
+
if (amount != null && amount > o.maxPaymentUsdc) block("price " + amount + " USDC is above maxPaymentUsdc " + o.maxPaymentUsdc);
|
|
301
|
+
const signed = amount != null && amount >= o.signedAboveUsdc;
|
|
302
|
+
const key = url + "|" + (signed ? "s" : "f") + "|" + o.maxLatencyMs;
|
|
303
|
+
const hit = cache.get(key);
|
|
304
|
+
let check;
|
|
305
|
+
if (hit && Date.now() - hit.at < o.cacheSeconds * 1000) check = hit.check;
|
|
306
|
+
else {
|
|
307
|
+
try { check = signed ? await client.verifyEndpoint({ endpointUrl: url, maxLatencyMs: o.maxLatencyMs }) : await client.checkEndpoint({ endpointUrl: url, maxLatencyMs: o.maxLatencyMs }); }
|
|
308
|
+
catch (e) { check = { error: e.message || String(e) }; }
|
|
309
|
+
}
|
|
310
|
+
if (!check || check.error || check.paymentRequired) {
|
|
311
|
+
const why = (check && (check.error || (check.paymentRequired && "AgentSLA check needs payment (free checks used up)"))) || "no answer";
|
|
312
|
+
if (o.onCheckError === "block") block("AgentSLA could not check the endpoint (" + why + ")", check);
|
|
313
|
+
if (o.onWarn) { try { o.onWarn({ url, reason: why }); } catch {} }
|
|
314
|
+
return { allowed: true, unchecked: true, reason: why };
|
|
127
315
|
}
|
|
128
|
-
const
|
|
129
|
-
|
|
316
|
+
const met = signed ? check.slaMet === true : check.meetsSla === true;
|
|
317
|
+
if (!met) block("endpoint failed the check (HTTP " + check.httpStatus + " in " + (check.latencyMs ?? check.edgeLatencyMs) + " ms, limit " + o.maxLatencyMs + " ms)", check);
|
|
318
|
+
const advertised = check.x402 && check.x402.offers ? check.x402.offers.map((x) => x.payTo) : [];
|
|
319
|
+
if (payment.payTo && advertised.length && !advertised.some((a) => sameAddress(a, payment.payTo))) {
|
|
320
|
+
block("payment goes to " + payment.payTo + ", but the endpoint advertises " + advertised.join(", ") + " to AgentSLA", check);
|
|
321
|
+
}
|
|
322
|
+
cache.set(key, { at: Date.now(), check });
|
|
323
|
+
return { allowed: true, check, signed };
|
|
130
324
|
}
|
|
325
|
+
return { assertSafe, options: o };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Wraps fetch so every outgoing x402 payment is checked with AgentSLA first. Put it UNDER your x402 client:
|
|
330
|
+
* const payFetch = wrapFetchWithPayment(withAgentSLAGuard(fetch, { client }), wallet);
|
|
331
|
+
* Requests without a payment header pass through untouched. A blocked payment throws AgentSLAGuardError before the
|
|
332
|
+
* request (and its signed payment) leaves the agent, so the seller never receives it and nothing is charged.
|
|
333
|
+
*/
|
|
334
|
+
export function withAgentSLAGuard(fetchImpl = globalThis.fetch, opts = {}) {
|
|
335
|
+
const guard = createX402Guard(opts);
|
|
336
|
+
const wrapped = async (input, init = {}) => {
|
|
337
|
+
const req = input instanceof Request ? input : null;
|
|
338
|
+
const headers = new Headers(init.headers || (req ? req.headers : undefined));
|
|
339
|
+
const pay = headers.get("payment-signature") || headers.get("x-payment");
|
|
340
|
+
if (pay) {
|
|
341
|
+
const url = typeof input === "string" ? input : (input && (input.url || input.href)) || String(input);
|
|
342
|
+
await guard.assertSafe(url, readPayment(pay) || {});
|
|
343
|
+
}
|
|
344
|
+
return fetchImpl(input, init);
|
|
345
|
+
};
|
|
346
|
+
wrapped.guard = guard;
|
|
347
|
+
return wrapped;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Framework-neutral tool definitions (JSON Schema + execute) for agent frameworks: OpenAI function calling, Vercel AI SDK,
|
|
352
|
+
* LangChain JS tool(), Mastra, etc. check_before_paying is free; signed_check pays with the wallet's pass or 0.05 USDC.
|
|
353
|
+
*/
|
|
354
|
+
export function agentslaTools(client = new AgentSLA()) {
|
|
355
|
+
const url = { type: "string", description: "Full http(s) URL of the API or MCP endpoint" };
|
|
356
|
+
const max = { type: "integer", minimum: 50, maximum: 30000, description: "Maximum response time in ms (default 1000)" };
|
|
357
|
+
return [
|
|
358
|
+
{ name: "check_before_paying", description: "Check an API or MCP endpoint right now before paying or relying on it: returns ok (HTTP 2xx/3xx within the latency limit), the status and latency.",
|
|
359
|
+
parameters: { type: "object", properties: { endpointUrl: url, maxLatencyMs: max }, required: ["endpointUrl"], additionalProperties: false },
|
|
360
|
+
execute: ({ endpointUrl, maxLatencyMs }) => client.checkBeforePaying(endpointUrl, { maxLatencyMs }) },
|
|
361
|
+
{ name: "signed_check", description: "Oracle-signed (EIP-712) check of an endpoint, as verifiable proof of its status and latency. Paid with the agent wallet's 7-day pass, else 0.05 USDC on Base.",
|
|
362
|
+
parameters: { type: "object", properties: { endpointUrl: url, maxLatencyMs: max }, required: ["endpointUrl"], additionalProperties: false },
|
|
363
|
+
execute: ({ endpointUrl, maxLatencyMs }) => client.verifyEndpoint({ endpointUrl, maxLatencyMs }) },
|
|
364
|
+
{ name: "find_apis", description: "Search the AgentSLA directory of APIs and MCP servers by keyword or category (indexed, not audited).",
|
|
365
|
+
parameters: { type: "object", properties: { search: { type: "string" }, category: { type: "string" }, limit: { type: "integer", minimum: 1, maximum: 50 } }, additionalProperties: false },
|
|
366
|
+
execute: (args) => client.discoverApis({ limit: 10, ...args }) }
|
|
367
|
+
];
|
|
131
368
|
}
|
|
132
369
|
|
|
133
370
|
export default AgentSLA;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentsla",
|
|
3
|
-
"version": "2.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.2.0",
|
|
4
|
+
"description": "Check an API before your agent pays it. x402 guard for every agent payment, live and oracle-signed (EIP-712) endpoint checks paid automatically with x402 or a 7-day pass, and refundable USDC escrow on Base.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"scripts": {
|
|
@@ -18,7 +18,16 @@
|
|
|
18
18
|
"x402",
|
|
19
19
|
"eip-712",
|
|
20
20
|
"llmstxt",
|
|
21
|
-
"glama"
|
|
21
|
+
"glama",
|
|
22
|
+
"agent-payments",
|
|
23
|
+
"openai-agents",
|
|
24
|
+
"langchain",
|
|
25
|
+
"crewai",
|
|
26
|
+
"vercel-ai-sdk",
|
|
27
|
+
"check-before-paying",
|
|
28
|
+
"x402-guard",
|
|
29
|
+
"payment-guard",
|
|
30
|
+
"agent-safety"
|
|
22
31
|
],
|
|
23
32
|
"author": "AgentSLA (https://agentsla.io)",
|
|
24
33
|
"license": "MIT",
|