agentsla 2.1.0 → 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 +45 -1
- package/index.js +133 -7
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# AgentSLA (`agentsla` v2.
|
|
1
|
+
# AgentSLA (`agentsla` v2.2.0)
|
|
2
2
|
|
|
3
3
|
**Check an API before your agent pays it.** AgentSLA checks whether an API or MCP server answers within your
|
|
4
4
|
latency limit (HTTP 2xx/3xx), signs the result with its oracle (EIP-712), and offers refundable USDC escrow on Base.
|
|
@@ -50,6 +50,43 @@ with `ethers.verifyTypedData`, using the domain and types from `GET https://agen
|
|
|
50
50
|
> no longer unlocks a pass. The SDK signs a short message with the pass wallet automatically. Calling the API
|
|
51
51
|
> directly? See [Pass access without the SDK](#pass-access-without-the-sdk).
|
|
52
52
|
|
|
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.
|
|
58
|
+
|
|
59
|
+
```javascript
|
|
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
|
+
|
|
53
90
|
## Use it in your agent framework
|
|
54
91
|
|
|
55
92
|
The MCP server gives any framework the free tools (directory search, live checks, pass status, escrow quotes). For
|
|
@@ -174,6 +211,13 @@ print(r.json())
|
|
|
174
211
|
listing; the oracle pays the provider if the SLA is met and refunds you otherwise. See
|
|
175
212
|
[agentsla.io/docs#escrow](https://agentsla.io/docs#escrow).
|
|
176
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
|
+
|
|
177
221
|
## Changes in 2.1.0
|
|
178
222
|
|
|
179
223
|
- `verifyEndpoint()` pays automatically: the wallet's pass (with a wallet signature), else 0.05 USDC by x402.
|
package/index.js
CHANGED
|
@@ -34,6 +34,29 @@ export function passAuthMessage(wallet, signedAt) {
|
|
|
34
34
|
export class AgentSLAError extends Error {
|
|
35
35
|
constructor(message, status, body) { super(message); this.name = "AgentSLAError"; this.status = status; this.body = body; }
|
|
36
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"]);
|
|
37
60
|
|
|
38
61
|
export class AgentSLA {
|
|
39
62
|
/**
|
|
@@ -148,19 +171,53 @@ export class AgentSLA {
|
|
|
148
171
|
if (maxAmountUsdc != null && BigInt(acc.amount) > ethers.parseUnits(String(maxAmountUsdc), 6)) {
|
|
149
172
|
throw new AgentSLAError("Price " + ethers.formatUnits(acc.amount, 6) + " USDC is above maxAmountUsdc " + maxAmountUsdc, 402, pr);
|
|
150
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();
|
|
151
185
|
const from = ethers.getAddress(await this.signer.getAddress());
|
|
152
186
|
const now = Math.floor(Date.now() / 1000);
|
|
153
|
-
const authorization = { from, to: ethers.getAddress(acc.payTo), value: String(acc.amount), validAfter: String(now - 600), validBefore: String(now + Number(acc.maxTimeoutSeconds || 300)), nonce: ethers.hexlify(ethers.randomBytes(32)) };
|
|
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)) };
|
|
154
188
|
const signature = await this.signer.signTypedData(
|
|
155
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 },
|
|
156
190
|
TRANSFER_WITH_AUTHORIZATION_TYPES, authorization
|
|
157
191
|
);
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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;
|
|
164
221
|
}
|
|
165
222
|
|
|
166
223
|
/** Buy a 7-day pass: 5 USDC on Base with one signature (x402 at /v1/pass), no gas, no approval. */
|
|
@@ -221,6 +278,75 @@ export class AgentSLA {
|
|
|
221
278
|
}
|
|
222
279
|
}
|
|
223
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 };
|
|
315
|
+
}
|
|
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 };
|
|
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
|
+
|
|
224
350
|
/**
|
|
225
351
|
* Framework-neutral tool definitions (JSON Schema + execute) for agent frameworks: OpenAI function calling, Vercel AI SDK,
|
|
226
352
|
* LangChain JS tool(), Mastra, etc. check_before_paying is free; signed_check pays with the wallet's pass or 0.05 USDC.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentsla",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "Check an API before your agent pays it
|
|
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": {
|
|
@@ -24,7 +24,10 @@
|
|
|
24
24
|
"langchain",
|
|
25
25
|
"crewai",
|
|
26
26
|
"vercel-ai-sdk",
|
|
27
|
-
"check-before-paying"
|
|
27
|
+
"check-before-paying",
|
|
28
|
+
"x402-guard",
|
|
29
|
+
"payment-guard",
|
|
30
|
+
"agent-safety"
|
|
28
31
|
],
|
|
29
32
|
"author": "AgentSLA (https://agentsla.io)",
|
|
30
33
|
"license": "MIT",
|