diff --git a/README.md b/README.md index ac39bdc..657a055 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Predge agent tools -Framework adapters for the [Predge API](https://predge.io/docs). They give an agent a signed settlement-risk check for any Polymarket market (free, no key), offline verification of Predge records, and x402-paid Polymarket data. +Dispute and refund verdicts for AI-agent payments, as framework tools for the [Predge API](https://predge.io/docs). An agent that paid for a call can ask for a signed verdict (`delivered` / `not_delivered` / `inconclusive`, with a refund recommendation) and re-read any verdict by id. Also: a signed settlement-risk check for any Polymarket market (free, no key), offline verification of Predge records, and x402-paid Polymarket data. | Package | Framework | |---|---| diff --git a/package-lock.json b/package-lock.json index 065c1c1..fc978f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2324,7 +2324,7 @@ }, "packages/ai-sdk": { "name": "@predge/ai-sdk", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "dependencies": { "zod": "^4.1.0" @@ -2338,7 +2338,7 @@ }, "packages/langchain": { "name": "@predge/langchain", - "version": "0.1.0", + "version": "0.2.0", "license": "MIT", "dependencies": { "zod": "^4.1.0" diff --git a/packages/ai-sdk/README.md b/packages/ai-sdk/README.md index 2d174e4..c38888f 100644 --- a/packages/ai-sdk/README.md +++ b/packages/ai-sdk/README.md @@ -1,8 +1,8 @@ # @predge/ai-sdk -[Predge](https://predge.io) tools for the [Vercel AI SDK](https://ai-sdk.dev). Before your agent trades, pays or settles on a Polymarket market, it can check whether that market's resolution is settled, disputed or at risk. Records are read live from UMA's Optimistic Oracle on Polygon and signed with ed25519. Every signature is verified against Predge's published key. +Dispute and refund verdicts for AI-agent payments, as [Vercel AI SDK](https://ai-sdk.dev) tools. When your agent pays for a call and the result looks wrong, it sends what was promised, what came back and what was paid, and gets a signed [Predge](https://predge.io) verdict: `delivered`, `not_delivered` or `inconclusive`, with reason codes and a refund recommendation. Every verdict is ed25519-signed and checked against Predge's published key. -The free tools need no API key and no wallet. +Also included: a free signed settlement-risk check for Polymarket markets (read live from UMA's Optimistic Oracle on Polygon) and x402-paid Polymarket data. ## Get a free key @@ -32,10 +32,40 @@ npm install @predge/ai-sdk ai zod ## Usage +### Verdicts with a pilot key + ```ts import { generateText, stepCountIs } from "ai"; import { predgeTools } from "@predge/ai-sdk"; +const { text } = await generateText({ + model: "openai/gpt-5-mini", + tools: predgeTools({ apiKey: process.env.PREDGE_KEY }), // free pilot key: https://predge.io/start + stopWhen: stepCountIs(3), + prompt: + "I paid $0.25 to https://api.example.com/v1/report for JSON with a `rows` field. " + + 'It answered 200 with body {"error":"timeout"}. Ask Predge for a verdict and tell me if I should get a refund.', +}); +``` + +Without `apiKey` the tool reads `PREDGE_KEY` from the environment. Or call the client directly: + +```ts +import { PredgeAPI } from "@predge/ai-sdk"; + +const verdict = await new PredgeAPI({ apiKey: process.env.PREDGE_KEY }).requestVerdict(undefined, { + job: { endpoint: "https://api.example.com/v1/report", expected_content_type: "application/json", required_fields: ["rows"] }, + delivery: { status: 200, headers: { "content-type": "application/json" }, body: '{"error":"timeout"}' }, + payment: { amount_usd: 0.25, payer: "0xBuyer", payee: "0xMerchant" }, +}); +// verdict.verdict === "not_delivered", verdict.refund.recommended === true, verdict.signature.valid === true +``` + +The refund is a recommendation the merchant executes. Predge does not move money. + +### Settlement risk (free, no key) + +```ts const { text } = await generateText({ model: "openai/gpt-5-mini", prompt: "Is Polymarket market 5608010 safe to settle against? Check its settlement risk first.", @@ -48,7 +78,7 @@ console.log(text); ### Paid tools (x402, USDC on Base) -Pass an account and the paid tools are added. Any viem account works, e.g. `privateKeyToAccount`. +Pass an account and the paid tools are added. Any viem account works, e.g. `privateKeyToAccount`. With an account and no key, `predgeRequestVerdict` pays per verdict over x402 ($0.05 when the paid call is under $1; $0.50 at $1 or more, which needs `maxPaymentUsd: 0.5`). ```ts import { privateKeyToAccount } from "viem/accounts"; @@ -66,6 +96,8 @@ Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The | Key | Tool name | Price | What it does | |---|---|---|---| +| `predgeRequestVerdict` | `predge_request_verdict` | free with a pilot key; else $0.05 (< $1) / $0.50 (>= $1) | Signed delivery verdict for a paid call: `delivered` / `not_delivered` / `inconclusive`, reason codes, per-check results, refund recommendation, `verify_url`. Returned when a key or an account is configured | +| `predgeGetVerdict` | `predge_get_verdict` | free | Reads a stored verdict by id (`vrd_...`) and checks its signature | | `predgeSettlementRisk` | `predge_get_settlement_risk` | free | Signed settlement-risk record for a market (condition id, numeric id or slug): `risk_level` (`ok`, `watch`, `caution`, `resolved`), UMA state, disputes, signature check | | `predgeVerifyRecord` | `predge_verify_record` | free | Verifies a Predge signed record offline against the pinned key | | `predgeSettlementEstimate` | `predge_get_settlement_estimate` | $0.02 | Same record plus `settlement_estimate`: for a disputed market, the calibrated probability that it settles differently from the disputed proposal. Failed requests are not charged | @@ -79,7 +111,7 @@ An error, or a record whose signature does not verify, is never a "no risk" answ import { verifyPredgeRecord } from "@predge/ai-sdk"; const res = await fetch("https://api.predge.io/v1/settlement-risk/5608010"); -console.log(verifyPredgeRecord(await res.json())); // { valid: true, kid: "13fa3d18a369e6c7", checks: {...} } +console.log(verifyPredgeRecord(await res.json())); // { valid: true, kid: "3b6551a6439b9bda", checks: {...} } ``` ## Links diff --git a/packages/ai-sdk/package.json b/packages/ai-sdk/package.json index f3a0ec9..b0df018 100644 --- a/packages/ai-sdk/package.json +++ b/packages/ai-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@predge/ai-sdk", - "version": "0.1.0", - "description": "Predge tools for the Vercel AI SDK: signed settlement-risk checks for Polymarket markets (free) and x402-paid Polymarket data", + "version": "0.2.0", + "description": "Dispute and refund verdicts for AI-agent payments: Predge tools for the Vercel AI SDK, plus signed Polymarket settlement-risk checks", "license": "MIT", "author": "Predge ", "homepage": "https://github.com/predgeAI/predge-agent-tools/tree/main/packages/ai-sdk#readme", @@ -11,7 +11,7 @@ "directory": "packages/ai-sdk" }, "bugs": "https://github.com/predgeAI/predge-agent-tools/issues", - "keywords": ["ai-sdk", "vercel-ai-sdk", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"], + "keywords": ["agent-payments", "disputes", "refunds", "verdicts", "ai-sdk", "vercel-ai-sdk", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"], "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.js", diff --git a/packages/ai-sdk/src/index.ts b/packages/ai-sdk/src/index.ts index 593dc28..8ec44fb 100644 --- a/packages/ai-sdk/src/index.ts +++ b/packages/ai-sdk/src/index.ts @@ -4,6 +4,8 @@ import { type PredgeToolsOptions, resolveTools } from "../../../shared/tools"; export * from "../../../shared/index"; const KEYS: Record = { + predge_request_verdict: "predgeRequestVerdict", + predge_get_verdict: "predgeGetVerdict", predge_get_settlement_risk: "predgeSettlementRisk", predge_verify_record: "predgeVerifyRecord", predge_get_settlement_estimate: "predgeSettlementEstimate", @@ -14,9 +16,10 @@ const KEYS: Record = { * Predge tools for the Vercel AI SDK. * * Free tools are always returned. Paid tools (x402, USDC on Base) are returned only when an `account` is given. + * The verdict tool is also returned with a Predge key (`apiKey` or env PREDGE_KEY; free pilot key at predge.io/start). * * @example - * const { text } = await generateText({ model, tools: predgeTools(), prompt: "Is market 5608010 safe to settle?" }); + * const { text } = await generateText({ model, tools: predgeTools({ apiKey: process.env.PREDGE_KEY }), prompt: "Was this paid call delivered?" }); */ export function predgeTools(options: PredgeToolsOptions = {}): ToolSet { const { api, signer, specs } = resolveTools(options); diff --git a/packages/langchain/README.md b/packages/langchain/README.md index 8c4f071..27c5a8c 100644 --- a/packages/langchain/README.md +++ b/packages/langchain/README.md @@ -1,8 +1,8 @@ # @predge/langchain -[Predge](https://predge.io) tools for [LangChain.js](https://js.langchain.com) and LangGraph.js. Before your agent trades, pays or settles on a Polymarket market, it can check whether that market's resolution is settled, disputed or at risk. Records are read live from UMA's Optimistic Oracle on Polygon and signed with ed25519. Every signature is verified against Predge's published key. +Dispute and refund verdicts for AI-agent payments, as [LangChain.js](https://js.langchain.com) and LangGraph.js tools. When your agent pays for a call and the result looks wrong, it sends what was promised, what came back and what was paid, and gets a signed [Predge](https://predge.io) verdict: `delivered`, `not_delivered` or `inconclusive`, with reason codes and a refund recommendation. Every verdict is ed25519-signed and checked against Predge's published key. -The free tools need no API key and no wallet. +Also included: a free signed settlement-risk check for Polymarket markets (read live from UMA's Optimistic Oracle on Polygon) and x402-paid Polymarket data. ## Get a free key @@ -39,14 +39,23 @@ import { createPredgeTools } from "@predge/langchain"; const agent = createReactAgent({ llm: new ChatOpenAI({ model: "gpt-5-mini" }), - tools: createPredgeTools(), + tools: createPredgeTools({ apiKey: process.env.PREDGE_KEY }), // free pilot key: https://predge.io/start }); const result = await agent.invoke({ - messages: [{ role: "user", content: "Check the settlement risk of Polymarket market 5608010." }], + messages: [ + { + role: "user", + content: + "I paid $0.25 to https://api.example.com/v1/report for JSON with a `rows` field. " + + 'It answered 200 with body {"error":"timeout"}. Ask Predge for a verdict and tell me if I should get a refund.', + }, + ], }); ``` +Without `apiKey` the tools read `PREDGE_KEY` from the environment. Without any key, `predge_request_verdict` is only returned when an account is configured (x402, below); the free tools need nothing. The refund is a recommendation the merchant executes. Predge does not move money. + Each tool returns a JSON string. ### Paid tools (x402, USDC on Base) @@ -60,12 +69,14 @@ const tools = createPredgeTools({ }); ``` -Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The tool pays only USDC on the account's chain and never more than `maxPaymentUsd` per call. +With an account and no key, `predge_request_verdict` pays per verdict ($0.05 when the paid call is under $1; $0.50 at $1 or more, which needs `maxPaymentUsd: 0.5`). Payments use x402 v2 (`exact` scheme, EIP-3009 USDC authorization on Base). The tool pays only USDC on the account's chain and never more than `maxPaymentUsd` per call. ## Tools | Tool | Price | What it does | |---|---|---| +| `predge_request_verdict` | free with a pilot key; else $0.05 (< $1) / $0.50 (>= $1) | Signed delivery verdict for a paid call: `delivered` / `not_delivered` / `inconclusive`, reason codes, per-check results, refund recommendation, `verify_url` | +| `predge_get_verdict` | free | Reads a stored verdict by id (`vrd_...`) and checks its signature | | `predge_get_settlement_risk` | free | Signed settlement-risk record for a market: `risk_level` (`ok`, `watch`, `caution`, `resolved`), UMA state, disputes, signature check | | `predge_verify_record` | free | Verifies a Predge signed record offline against the pinned key | | `predge_get_settlement_estimate` | $0.02 | Same record plus `settlement_estimate` for a disputed market. Failed requests are not charged | diff --git a/packages/langchain/package.json b/packages/langchain/package.json index cec4343..21754b0 100644 --- a/packages/langchain/package.json +++ b/packages/langchain/package.json @@ -1,7 +1,7 @@ { "name": "@predge/langchain", - "version": "0.1.0", - "description": "Predge tools for LangChain.js: signed settlement-risk checks for Polymarket markets (free) and x402-paid Polymarket data", + "version": "0.2.0", + "description": "Dispute and refund verdicts for AI-agent payments: Predge tools for LangChain.js, plus signed Polymarket settlement-risk checks", "license": "MIT", "author": "Predge ", "homepage": "https://github.com/predgeAI/predge-agent-tools/tree/main/packages/langchain#readme", @@ -11,7 +11,7 @@ "directory": "packages/langchain" }, "bugs": "https://github.com/predgeAI/predge-agent-tools/issues", - "keywords": ["langchain", "langgraph", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"], + "keywords": ["agent-payments", "disputes", "refunds", "verdicts", "langchain", "langgraph", "agents", "tools", "polymarket", "prediction-markets", "uma", "x402", "ed25519", "predge"], "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.js", diff --git a/packages/langchain/src/index.ts b/packages/langchain/src/index.ts index d5686c8..755d36b 100644 --- a/packages/langchain/src/index.ts +++ b/packages/langchain/src/index.ts @@ -7,6 +7,7 @@ export * from "../../../shared/index"; * Predge tools for LangChain.js / LangGraph.js. * * Free tools are always returned. Paid tools (x402, USDC on Base) are returned only when an `account` is given. + * The verdict tool is also returned with a Predge key (`apiKey` or env PREDGE_KEY; free pilot key at predge.io/start). * Each tool returns a JSON string. * * @example diff --git a/shared/client.ts b/shared/client.ts index bfe0967..d95202f 100644 --- a/shared/client.ts +++ b/shared/client.ts @@ -8,6 +8,27 @@ export type PredgePluginOptions = { maxPaymentUsd?: number; /** Trusted ed25519 public keys (hex). Defaults to Predge's published attestation key. */ trustedKeys?: string[]; + /** + * Predge API key, sent as the `x-predge-key` header on verdict requests. A free 30-day pilot key is at + * https://predge.io/start . Defaults to the PREDGE_KEY environment variable. Without a key, verdicts are paid over x402. + */ + apiKey?: string; +}; + +/** Header that carries a Predge API key (pilot / Desk key). */ +export const PREDGE_KEY_HEADER = "x-predge-key"; +/** A paid call of this many USD or more is a large-tier verdict (POST /v1/verdicts/large, $0.50). */ +export const LARGE_VERDICT_THRESHOLD_USD = 1; + +/** Body of POST /v1/verdicts: what was promised, what was delivered, and what was paid. */ +export type VerdictRequest = { + job: Json & { endpoint: string }; + delivery: Json; + payment: Json & { amount_usd: number }; + buyer_id?: string; + merchant_id?: string; + agent?: Json; + provider_agent?: Json; }; type Json = Record; @@ -53,6 +74,30 @@ export function summarizeSettlementRisk(record: Json): Json { }; } +/** The fields of a signed verdict an agent needs to act on it. */ +export function summarizeVerdict(record: Json): Json { + const refund = (record.refund ?? {}) as Json; + return { + id: record.id, + verdict: record.verdict, + method: record.method, + reason_codes: record.reason_codes, + checks: record.checks, + refund_recommended: record.refund_recommended, + refund: { + recommended: refund.recommended ?? record.refund_recommended, + amount_usd: refund.amount_usd ?? record.refund_amount_usd, + from: refund.from, + to: refund.to, + status: refund.status, + instructions: refund.instructions, + }, + issued_at: record.issued_at, + verify_url: record.verify_url, + fee: record.fee, + }; +} + function apiError(status: number, data: Json | null, url: string) { return { error: true, @@ -68,11 +113,96 @@ export class PredgeAPI { private readonly baseUrl: string; private readonly maxPaymentUsd: number; private readonly trustedKeys: string[]; + readonly apiKey: string | undefined; constructor(options: PredgePluginOptions = {}) { this.baseUrl = (options.baseUrl ?? "https://api.predge.io").replace(/\/+$/, ""); this.maxPaymentUsd = options.maxPaymentUsd ?? 0.05; this.trustedKeys = options.trustedKeys ?? [PREDGE_ATTESTATION_PUBLIC_KEY]; + const envKey = typeof process !== "undefined" ? process.env?.PREDGE_KEY : undefined; + this.apiKey = (options.apiKey ?? envKey)?.trim() || undefined; + } + + /** + * Ask Predge for a signed delivery verdict: was the paid work delivered as promised? + * Sends the key (x-predge-key) when one is configured; otherwise, or when the key has no free verdicts left + * (402), pays over x402 from the signer, never above maxPaymentUsd. Calls of $1 or more go to the large tier. + */ + async requestVerdict(signer: X402Signer | undefined, request: VerdictRequest) { + const amount = Number(request.payment?.amount_usd); + const large = Number.isFinite(amount) && amount >= LARGE_VERDICT_THRESHOLD_USD; + const url = `${this.baseUrl}/v1/verdicts${large ? "/large" : ""}`; + const body = JSON.stringify(request); + const headers: Record = { "Content-Type": "application/json", Accept: "application/json" }; + if (this.apiKey) headers[PREDGE_KEY_HEADER] = this.apiKey; + + let response: Response; + if (this.apiKey) { + response = await fetch(url, { method: "POST", headers, body }); + if (response.status === 402 && !(signer && this.maxPaymentUsd > 0)) { + return { + error: true, + status: 402, + message: + "This key has no free verdicts left (pilot window over). Pay per verdict over x402 by configuring an EVM account, " + + "or get a key at https://predge.io/start . Nothing was charged.", + url, + }; + } + } else { + if (this.maxPaymentUsd <= 0 || !signer) { + return { + error: true, + message: + "A verdict needs a Predge key (free pilot key at https://predge.io/start, option apiKey or env PREDGE_KEY) " + + "or an EVM account to pay over x402 ($0.05 under $1, $0.50 at $1 or more).", + }; + } + response = new Response(null, { status: 402 }); + } + if (response.status === 402 && signer) { + try { + ({ response } = await fetchWithX402( + url, + signer, + BigInt(Math.floor(this.maxPaymentUsd * 1_000_000)), + fetch, + { method: "POST", body, headers }, + )); + } catch (e) { + return { error: true, message: (e as Error).message, url }; + } + } + const text = await response.text(); + const data = parseJson(text); + if (!response.ok || !data) return apiError(response.status, data, url); + return { ...this.verdictResult(data, text, response), source: url }; + } + + /** Re-read a stored verdict by id (free, no key). Verifies its signature. */ + async getVerdict(id: string) { + const url = `${this.baseUrl}/v1/verdicts/${encodeURIComponent(id)}`; + const response = await fetch(url, { headers: { Accept: "application/json" } }); + const text = await response.text(); + const data = parseJson(text); + if (!response.ok || !data) return apiError(response.status, data, url); + return { ...this.verdictResult(data, text, response), source: url }; + } + + private verdictResult(data: Json, text: string, response: Response) { + const paymentHeader = response.headers.get("payment-response"); + let payment: unknown = null; + if (paymentHeader) { + payment = parseJson(Buffer.from(paymentHeader, "base64").toString("utf8")) ?? { raw: paymentHeader }; + } + return { + ...summarizeVerdict(data), + signature: { + ...verifyPredgeRecord(data, this.trustedKeys), + bodySignature: verifyBodySignature(text, response.headers.get("x-predge-body-signature"), this.trustedKeys), + }, + payment, + }; } async getSettlementRisk(market: string) { diff --git a/shared/index.ts b/shared/index.ts index 387baf6..d38b4e2 100644 --- a/shared/index.ts +++ b/shared/index.ts @@ -1,4 +1,12 @@ export * from "./verify"; export { fetchWithX402, PREDGE_USDC_BY_CHAIN, selectRequirement, type X402Signer } from "./x402"; -export { PredgeAPI, summarizeSettlementRisk } from "./client"; +export { + LARGE_VERDICT_THRESHOLD_USD, + PREDGE_KEY_HEADER, + PredgeAPI, + summarizeSettlementRisk, + summarizeVerdict, + type PredgePluginOptions, + type VerdictRequest, +} from "./client"; export { TOOL_SPECS, resolveTools, type PredgeAccount, type PredgeToolsOptions } from "./tools"; diff --git a/shared/tools.ts b/shared/tools.ts index 90bba7e..3ff959e 100644 --- a/shared/tools.ts +++ b/shared/tools.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { PredgeAPI, type PredgePluginOptions } from "./client"; +import { PredgeAPI, type PredgePluginOptions, type VerdictRequest } from "./client"; import type { X402Signer } from "./x402"; /** A viem-style account: anything with an address and EIP-712 signTypedData (e.g. privateKeyToAccount). */ @@ -20,15 +20,115 @@ const market = z .min(1) .describe("Polymarket market: a condition id (0x + 64 hex), a numeric market id, or a market slug"); +const optStr = (max: number, d: string) => z.string().min(1).max(max).optional().describe(d); + +const agentIdentity = (who: string) => + z + .object({ + id: z.string().min(1).max(256).describe("Stable agent id, e.g. an ERC-8004 id"), + version: z.string().min(1).max(64).describe("Agent version"), + operator: z.string().min(1).max(256).describe("Company or wallet accountable for the agent"), + authorization_ref: optStr(256, "Mandate or policy id the agent acted under"), + }) + .optional() + .describe(`Optional know-your-agent record of the ${who}; signed into the verdict as given, not verified by Predge`); + +const verdictSchema = z.object({ + job: z + .object({ + endpoint: z.string().min(1).max(2048).describe("The URL or path that was called and paid for"), + method: optStr(16, "HTTP method of the paid call, e.g. GET or POST"), + expected_content_type: optStr(128, "Content type that was promised, e.g. application/json"), + expect_json: z.boolean().optional().describe("True if the response had to be valid JSON"), + json_schema: z + .record(z.string(), z.unknown()) + .optional() + .describe("JSON Schema the response body had to match"), + required_fields: z.array(z.string().min(1).max(200)).max(50).optional().describe("Dot-paths that must exist"), + non_empty_fields: z + .array(z.string().min(1).max(200)) + .max(50) + .optional() + .describe("Dot-paths that must be non-empty"), + max_latency_ms: z.number().int().min(0).max(3_600_000).optional().describe("Promised maximum latency"), + expected_sha256: z + .string() + .regex(/^[0-9a-fA-F]{64}$/) + .optional() + .describe("sha256 (hex) the body had to have"), + }) + .describe("What was promised"), + delivery: z + .object({ + status: z.number().int().min(100).max(599).optional().describe("HTTP status of the delivery"), + headers: z.record(z.string(), z.string()).optional().describe("Response headers (at most 30)"), + body: z.string().max(200_000).optional().describe("Response body as text (or send body_sha256 instead)"), + body_sha256: z + .string() + .regex(/^[0-9a-fA-F]{64}$/) + .optional() + .describe("sha256 (hex) of the response body"), + requested_at: optStr(40, "ISO 8601 time the request was sent"), + responded_at: optStr(40, "ISO 8601 time the response arrived"), + latency_ms: z.number().int().min(0).max(86_400_000).optional().describe("Measured latency"), + }) + .describe("The delivery evidence"), + payment: z + .object({ + amount_usd: z.number().min(0).describe("USD paid for the job. Under $1: $0.05 verdict; $1 or more: $0.50"), + tx_hash: optStr(200, "Payment transaction hash"), + network: optStr(200, "Payment network, e.g. eip155:8453"), + asset: optStr(200, "Payment asset address or symbol"), + payer: optStr(200, "Buyer address or id"), + payee: optStr(200, "Merchant address or id"), + }) + .describe("The payment reference"), + buyer_id: optStr(128, "Your id for the buyer"), + merchant_id: optStr(128, "Your id for the merchant"), + agent: agentIdentity("buyer agent"), + provider_agent: agentIdentity("provider (merchant) agent"), +}); + export type ToolSpec = { name: string; description: string; schema: z.ZodObject; paid: boolean; + /** Also available without a wallet when a Predge API key is configured. */ + keyed?: boolean; run: (api: PredgeAPI, input: Record, signer: X402Signer | undefined) => Promise; }; export const TOOL_SPECS: ToolSpec[] = [ + { + name: "predge_request_verdict", + description: + "Get a signed delivery verdict for a paid AI-agent call: was the work delivered as promised, and should the payment be refunded? " + + "Input: job (what was promised: endpoint, expected content type, JSON Schema, required fields, max latency), delivery (the evidence: " + + "status, headers, body or its sha256, timing) and payment (amount_usd, payer, payee, tx hash). Returns verdict (delivered, " + + "not_delivered or inconclusive), reason codes, per-check results, a refund recommendation, a verify_url and the ed25519 signature " + + "check. Deterministic checks of the evidence you send. Free with a Predge pilot key inside its 30-day window; otherwise paid over " + + "x402: $0.05 when the paid call is under $1, $0.50 at $1 or more. The refund is a recommendation the merchant executes; Predge does " + + "not move money.", + schema: verdictSchema, + paid: true, + keyed: true, + run: (api, input, signer) => api.requestVerdict(signer, input as unknown as VerdictRequest), + }, + { + name: "predge_get_verdict", + description: + "Read a stored Predge delivery verdict by id (vrd_ followed by 24 characters). Free, no key. Returns the verdict, reason codes, " + + "refund recommendation and the ed25519 signature check, so a buyer, merchant or third party can confirm what was ruled.", + schema: z.object({ + id: z + .string() + .regex(/^vrd_[A-Za-z0-9_-]{24}$/) + .describe("Verdict id, e.g. vrd_ followed by 24 characters"), + }), + paid: false, + run: (api, input) => api.getVerdict(String(input.id)), + }, { name: "predge_get_settlement_risk", description: @@ -79,6 +179,6 @@ export function resolveTools(options: PredgeToolsOptions = {}) { } : undefined; const paidEnabled = signer !== undefined && (options.maxPaymentUsd ?? 0.05) > 0; - const specs = TOOL_SPECS.filter((s) => !s.paid || paidEnabled); + const specs = TOOL_SPECS.filter((s) => !s.paid || paidEnabled || (s.keyed === true && api.apiKey !== undefined)); return { api, signer, specs }; } diff --git a/shared/verify.ts b/shared/verify.ts index 2610e91..76e52e3 100644 --- a/shared/verify.ts +++ b/shared/verify.ts @@ -1,7 +1,20 @@ import { createHash, createPublicKey, verify as edVerify } from "node:crypto"; -/** Predge's published ed25519 attestation key (kid 13fa3d18a369e6c7). */ -export const PREDGE_ATTESTATION_PUBLIC_KEY = "13fa3d18a369e6c71bf941563ba47822b30182273d5106a0e8fb61c5016352d9"; +/** + * Predge's current ed25519 attestation key (kid 3b6551a6439b9bda), as published at + * https://api.predge.io/.well-known/predge-keys.json . + */ +export const PREDGE_ATTESTATION_PUBLIC_KEY = "3b6551a6439b9bda0de7e3b8dc89f276b2141fdfde310f762e663ab4ba2e9d1b"; + +/** + * Keys Predge has revoked. A record signed with one of these never verifies, even if a caller + * passes it in `trustedKeys`. kid 13fa3d18a369e6c7 was revoked on 2026-10-21. + */ +export const PREDGE_REVOKED_KEYS: readonly string[] = [ + "13fa3d18a369e6c71bf941563ba47822b30182273d5106a0e8fb61c5016352d9", +]; + +const isRevoked = (key: string) => PREDGE_REVOKED_KEYS.includes(key.toLowerCase()); const ED25519_SPKI_PREFIX = "302a300506032b6570032100"; const BODY_SIGNATURE_PREFIX = "predge-body-v1\n"; @@ -117,9 +130,12 @@ export function verifyPredgeRecord( if (!env) { return { valid: false, checks, error: "No signed envelope (canonical + signature) found" }; } - const trusted = trustedKeys.map((k) => k.toLowerCase()); + const trusted = trustedKeys.map((k) => k.toLowerCase()).filter((k) => !isRevoked(k)); const key = String(env.public_key ?? "").toLowerCase(); checks.trustedKey = trusted.includes(key); + if (isRevoked(key)) { + return { valid: false, kid: env.kid ?? key.slice(0, 16), checks, error: "Signed with a revoked Predge key" }; + } // Verify with the trusted key only; a record signed by any other key fails. checks.signature = checks.trustedKey && verifyEd25519(env.canonical, env.signature, key); if (env.payload !== undefined) { @@ -164,7 +180,7 @@ export function verifyBodySignature( }), ); if (parts.alg !== "ed25519" || !parts.kid || !parts.sig) return false; - const key = trustedKeys.find((k) => k.toLowerCase().startsWith(parts.kid.toLowerCase())); + const key = trustedKeys.find((k) => !isRevoked(k) && k.toLowerCase().startsWith(parts.kid.toLowerCase())); if (!key) return false; return verifyEd25519(BODY_SIGNATURE_PREFIX + rawBody, parts.sig, key.toLowerCase()); } diff --git a/shared/x402.ts b/shared/x402.ts index 13a70c7..72bb928 100644 --- a/shared/x402.ts +++ b/shared/x402.ts @@ -77,7 +77,7 @@ export function decodePaymentRequired(header: string | null): PaymentRequired | } /** - * GET a URL; on HTTP 402, pay with an EIP-3009 USDC authorization (x402 v2 `exact` scheme) and retry once. + * GET a URL (or send `init.method` with `init.body`); on HTTP 402, pay with an EIP-3009 USDC authorization (x402 v2 `exact` scheme) and retry once. * Never pays more than `maxAtomic` (USDC atomic units, 6 decimals). */ export async function fetchWithX402( @@ -85,9 +85,12 @@ export async function fetchWithX402( signer: X402Signer, maxAtomic: bigint, fetchImpl: typeof fetch = fetch, + init: { method?: string; body?: string; headers?: Record } = {}, ): Promise<{ response: Response; paid: boolean }> { - const headers = { Accept: "application/json" }; - const first = await fetchImpl(url, { headers }); + const headers: Record = { Accept: "application/json", ...(init.headers ?? {}) }; + const request = (h: Record) => + fetchImpl(url, init.method ? { method: init.method, headers: h, body: init.body } : { headers: h }); + const first = await request(headers); if (first.status !== 402) return { response: first, paid: false }; const required = decodePaymentRequired(first.headers.get("payment-required")); @@ -130,11 +133,9 @@ export async function fetchWithX402( accepted: req, payload: { authorization, signature }, }; - const paid = await fetchImpl(url, { - headers: { - ...headers, - "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(paymentPayload), "utf8").toString("base64"), - }, + const paid = await request({ + ...headers, + "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(paymentPayload), "utf8").toString("base64"), }); return { response: paid, paid: true }; } diff --git a/test/adapters.test.ts b/test/adapters.test.ts index 257a47d..a251818 100644 --- a/test/adapters.test.ts +++ b/test/adapters.test.ts @@ -1,25 +1,40 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createPredgeTools } from "../packages/langchain/src/index"; import { predgeTools } from "../packages/ai-sdk/src/index"; const record = { risk_level: "ok", market: { slug: "m" }, attestation: {} }; const account = { address: "0x1111111111111111111111111111111111111111", signTypedData: vi.fn() }; -afterEach(() => vi.restoreAllMocks()); +beforeEach(() => vi.stubEnv("PREDGE_KEY", "")); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); describe("AI SDK adapter", () => { it("returns only free tools without an account", () => { - expect(Object.keys(predgeTools())).toEqual(["predgeSettlementRisk", "predgeVerifyRecord"]); + expect(Object.keys(predgeTools())).toEqual(["predgeGetVerdict", "predgeSettlementRisk", "predgeVerifyRecord"]); + }); + + it("adds the verdict tool with a Predge key and no wallet", () => { + expect(Object.keys(predgeTools({ apiKey: "pdg_pilot_test" }))).toEqual([ + "predgeRequestVerdict", + "predgeGetVerdict", + "predgeSettlementRisk", + "predgeVerifyRecord", + ]); }); it("adds paid tools with an account unless payments are disabled", () => { expect(Object.keys(predgeTools({ account }))).toEqual([ + "predgeRequestVerdict", + "predgeGetVerdict", "predgeSettlementRisk", "predgeVerifyRecord", "predgeSettlementEstimate", "predgeWhaleTrades", ]); - expect(Object.keys(predgeTools({ account, maxPaymentUsd: 0 }))).toHaveLength(2); + expect(Object.keys(predgeTools({ account, maxPaymentUsd: 0 }))).toHaveLength(3); }); it("executes the settlement-risk tool", async () => { @@ -39,13 +54,31 @@ describe("LangChain adapter", () => { it("returns structured tools that answer with JSON strings", async () => { vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify(record))); const tools = createPredgeTools(); - expect(tools.map((t) => t.name)).toEqual(["predge_get_settlement_risk", "predge_verify_record"]); - const out = await tools[0].invoke({ market: "5608010" }); + expect(tools.map((t) => t.name)).toEqual(["predge_get_verdict", "predge_get_settlement_risk", "predge_verify_record"]); + const out = await tools[1].invoke({ market: "5608010" }); expect(JSON.parse(out as string).risk_level).toBe("ok"); }); it("validates input with the zod schema", async () => { const tools = createPredgeTools(); - await expect(tools[0].invoke({ market: "" })).rejects.toThrow(); + await expect(tools[1].invoke({ market: "" })).rejects.toThrow(); + await expect(tools[0].invoke({ id: "nope" })).rejects.toThrow(); + }); + + it("exposes predge_request_verdict with a key and sends it as x-predge-key", async () => { + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValue(new Response(JSON.stringify({ id: "vrd_x", verdict: "delivered", attestation: {} }))); + const tools = createPredgeTools({ apiKey: "pdg_pilot_test" }); + const t = tools.find((x) => x.name === "predge_request_verdict"); + const out = await t?.invoke({ + job: { endpoint: "https://api.example.com/v1/report" }, + delivery: { status: 200, body: "{}" }, + payment: { amount_usd: 0.1 }, + }); + expect(JSON.parse(out as string).verdict).toBe("delivered"); + const init = fetchMock.mock.calls[0][1] as { headers: Record }; + expect(init.headers["x-predge-key"]).toBe("pdg_pilot_test"); + await expect(t?.invoke({ job: {}, delivery: {}, payment: { amount_usd: 1 } })).rejects.toThrow(); }); }); diff --git a/test/verdicts.test.ts b/test/verdicts.test.ts new file mode 100644 index 0000000..7a39290 --- /dev/null +++ b/test/verdicts.test.ts @@ -0,0 +1,219 @@ +import { generateKeyPairSync, sign } from "node:crypto"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { PredgeAPI } from "../shared/client"; +import { + PREDGE_ATTESTATION_PUBLIC_KEY, + PREDGE_REVOKED_KEYS, + canonicalJson, + verifyBodySignature, + verifyPredgeRecord, +} from "../shared/verify"; + +const { privateKey, publicKey } = generateKeyPairSync("ed25519"); +const TEST_KEY = (publicKey.export({ format: "der", type: "spki" }) as Buffer).subarray(-32).toString("hex"); +const signHex = (m: string) => sign(null, Buffer.from(m, "utf8"), privateKey).toString("hex"); +// biome-ignore lint/suspicious/noExplicitAny: test assertions on loosely typed results +type Json = Record; +const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; +const ID = "vrd_abcdefghijklmnopqrstuvwx"; + +function envelope(payload: Record, key = TEST_KEY) { + const canonical = canonicalJson(payload); + const env: Record = { + version: "predge-attest-v1", + public_key: key, + canonical, + signature: signHex(canonical), + payload, + kid: key.slice(0, 16), + }; + env.envelope_signature = signHex(canonicalJson(env)); + return env; +} + +function verdictBody(verdict = "not_delivered") { + const refund = verdict === "not_delivered"; + return { + id: ID, + verdict, + method: "schema", + reason_codes: refund ? ["missing_required_field"] : [], + checks: [{ id: "required_fields", status: refund ? "fail" : "pass", reason_code: refund ? "missing_required_field" : null }], + refund_recommended: refund, + refund_amount_usd: refund ? "0.250000" : "0.000000", + refund: { + recommended: refund, + amount_usd: refund ? "0.250000" : "0.000000", + from: refund ? "0xMerchant" : null, + to: refund ? "0xBuyer" : null, + status: "recommendation_only", + instructions: "x", + onchain: null, + note: "n", + }, + issued_at: "2026-10-31T00:00:00.000Z", + verify_url: `https://api.predge.io/v1/verdicts/${ID}`, + fee: { tier: "standard", access: "pilot_key", price_usd: "0.000000" }, + attestation: envelope({ kind: "verdict", verdict_id: ID, verdict }), + }; +} + +const request = { + job: { endpoint: "https://api.example.com/v1/report", required_fields: ["rows"] }, + delivery: { status: 200, headers: { "content-type": "application/json" }, body: "{}" }, + payment: { amount_usd: 0.25, payer: "0xBuyer", payee: "0xMerchant" }, +}; + +const signed = (body: unknown, extra: Record = {}, status = 200) => { + const text = JSON.stringify(body); + const header = `kid=${TEST_KEY.slice(0, 16)}; alg=ed25519; sig=${signHex(`predge-body-v1\n${text}`)}`; + return new Response(text, { status, headers: { "x-predge-body-signature": header, ...extra } }); +}; + +const paymentRequired = (amount: string) => + Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "https://api.predge.io/v1/verdicts" }, + accepts: [ + { + scheme: "exact", + network: "eip155:8453", + asset: BASE_USDC, + amount, + payTo: "0x9084f5000e07c7133d6da5ee4f271ab6d1821144", + maxTimeoutSeconds: 60, + extra: { name: "USD Coin", version: "2" }, + }, + ], + }), + ).toString("base64"); + +const signer = () => ({ + address: "0x1111111111111111111111111111111111111111", + chainId: 8453, + signTypedData: vi.fn().mockResolvedValue("0xsig"), +}); + +beforeEach(() => vi.stubEnv("PREDGE_KEY", "")); +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +describe("requestVerdict", () => { + it("posts the request with x-predge-key and verifies the signed verdict", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(signed(verdictBody())); + const api = new PredgeAPI({ trustedKeys: [TEST_KEY], apiKey: "pdg_pilot_test" }); + const out = (await api.requestVerdict(undefined, request)) as Json; + const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit & { headers: Record }]; + expect(url).toBe("https://api.predge.io/v1/verdicts"); + expect(init.method).toBe("POST"); + expect(init.headers["x-predge-key"]).toBe("pdg_pilot_test"); + expect(JSON.parse(String(init.body))).toEqual(request); + expect(out).toMatchObject({ + id: ID, + verdict: "not_delivered", + refund_recommended: true, + refund: { recommended: true, amount_usd: "0.250000", to: "0xBuyer", status: "recommendation_only" }, + verify_url: `https://api.predge.io/v1/verdicts/${ID}`, + }); + expect(out.signature.valid).toBe(true); + expect(out.signature.bodySignature).toBe(true); + }); + + it("reads the key from PREDGE_KEY", async () => { + vi.stubEnv("PREDGE_KEY", "pdg_pilot_env"); + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(signed(verdictBody())); + await new PredgeAPI({ trustedKeys: [TEST_KEY] }).requestVerdict(undefined, request); + const init = fetchMock.mock.calls[0][1] as { headers: Record }; + expect(init.headers["x-predge-key"]).toBe("pdg_pilot_env"); + }); + + it("routes paid calls of $1 or more to the large tier", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(signed(verdictBody("delivered"))); + const api = new PredgeAPI({ trustedKeys: [TEST_KEY], apiKey: "pdg_pilot_test" }); + await api.requestVerdict(undefined, { ...request, payment: { amount_usd: 1 } }); + expect(fetchMock.mock.calls[0][0]).toBe("https://api.predge.io/v1/verdicts/large"); + }); + + it("refuses without a key or a wallet, and never as a verdict", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch"); + const out = (await new PredgeAPI().requestVerdict(undefined, request)) as Json; + expect(out.error).toBe(true); + expect(out.message).toContain("predge.io/start"); + expect(out.verdict).toBeUndefined(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("tells the caller when the key has no free verdicts left and no wallet is set", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}", { status: 402 })); + const out = (await new PredgeAPI({ apiKey: "pdg_pilot_old" }).requestVerdict(undefined, request)) as Json; + expect(out).toMatchObject({ error: true, status: 402 }); + }); + + it("pays $0.05 over x402 without a key, posting the same body", async () => { + const fetchMock = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(new Response("{}", { status: 402, headers: { "payment-required": paymentRequired("50000") } })) + .mockResolvedValueOnce( + signed(verdictBody(), { + "payment-response": Buffer.from(JSON.stringify({ success: true })).toString("base64"), + }), + ); + const s = signer(); + const out = (await new PredgeAPI({ trustedKeys: [TEST_KEY] }).requestVerdict(s, request)) as Json; + expect(out.verdict).toBe("not_delivered"); + expect(out.payment).toEqual({ success: true }); + const paidInit = fetchMock.mock.calls[1][1] as RequestInit & { headers: Record }; + expect(paidInit.method).toBe("POST"); + expect(JSON.parse(String(paidInit.body))).toEqual(request); + expect(paidInit.headers["PAYMENT-SIGNATURE"]).toBeTruthy(); + expect(paidInit.headers["x-predge-key"]).toBeUndefined(); + expect(s.signTypedData.mock.calls[0][0].message.value).toBe(50000n); + }); + + it("does not pay the $0.50 large tier above the default cap", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response("{}", { status: 402, headers: { "payment-required": paymentRequired("500000") } }), + ); + const s = signer(); + const out = (await new PredgeAPI().requestVerdict(s, { ...request, payment: { amount_usd: 5 } })) as Json; + expect(out.error).toBe(true); + expect(out.message).toContain("nothing was paid"); + expect(s.signTypedData).not.toHaveBeenCalled(); + }); + + it("passes API errors through", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(JSON.stringify({ error: "invalid_request", message: "job.endpoint is required" }), { status: 400 }), + ); + const out = (await new PredgeAPI({ apiKey: "k" }).requestVerdict(undefined, request)) as Json; + expect(out).toMatchObject({ error: true, status: 400, code: "invalid_request" }); + }); +}); + +describe("getVerdict", () => { + it("reads a stored verdict by id and verifies it", async () => { + const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(signed(verdictBody("delivered"))); + const out = (await new PredgeAPI({ trustedKeys: [TEST_KEY] }).getVerdict(ID)) as Json; + expect(fetchMock.mock.calls[0][0]).toBe(`https://api.predge.io/v1/verdicts/${ID}`); + expect(out.verdict).toBe("delivered"); + expect(out.signature.valid).toBe(true); + }); +}); + +describe("signing keys", () => { + it("pins the current published key and never trusts a revoked one", () => { + expect(PREDGE_ATTESTATION_PUBLIC_KEY.startsWith("3b6551a6439b9bda")).toBe(true); + expect(PREDGE_REVOKED_KEYS).not.toContain(PREDGE_ATTESTATION_PUBLIC_KEY); + const record = { attestation: envelope({ kind: "verdict" }) }; + // Pretend TEST_KEY were revoked by passing a record whose public_key is on the revoked list. + const revoked = PREDGE_REVOKED_KEYS[0]; + const forged = { attestation: { ...(record.attestation as Json), public_key: revoked } }; + const v = verifyPredgeRecord(forged, [revoked]); + expect(v.valid).toBe(false); + expect(v.error).toContain("revoked"); + expect(verifyBodySignature("{}", `kid=${revoked.slice(0, 16)}; alg=ed25519; sig=00`, [revoked])).toBe(false); + }); +});