diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f1865f7..291eda5 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -4,18 +4,18 @@ "name": "Calgooon" }, "metadata": { - "description": "BSV micropayment skill for Claude Code — BRC-31 auth + BRC-29 payment via MetaNet Client", - "version": "1.1.1" + "description": "BSV micropayment skill for Claude Code - BRC-31 auth + BRC-29 payment via a BRC-100 wallet", + "version": "1.1.2" }, "plugins": [ { "name": "x402", - "description": "Make BSV-authenticated or paid API requests using BRC-31 auth and BRC-29 micropayments with MetaNet Client wallet", + "description": "Make BSV-authenticated or paid API requests using BRC-31 auth and BRC-29 micropayments with a BRC-100 wallet", "source": "./", "skills": [ "./skills/x402" ], - "version": "1.1.1" + "version": "1.1.2" } ] } diff --git a/README.md b/README.md index a3056f3..daddffc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # x402 -Claude Code skill for BSV micropayments. Discover, authenticate, and pay AI services with Bitcoin SV — all from natural language. +Claude Code skill for BSV micropayments. Discover, authenticate, and pay AI services with Bitcoin SV - all from natural language. ## What It Does @@ -18,26 +18,38 @@ Under the hood: 1. **Discovers** available services from the [x402agency.com](https://x402agency.com) agent directory 2. **Authenticates** with [BRC-31](https://brc.dev/31) mutual auth (automatic handshake + session caching) 3. **Pays** with [BRC-29](https://brc.dev/29) micropayments (automatic 402 handling, transaction creation) -4. **Refunds** automatically — both service-failure refunds (a paid request fails) and excess refunds (you overpaid a token-priced agent) are detected and internalized to your wallet with no manual steps +4. **Refunds** automatically - both service-failure refunds (a paid request fails) and excess refunds (you overpaid a token-priced agent) are detected and internalized to your wallet with no manual steps ## Available Services The skill discovers agents from [x402agency.com/.well-known/agents](https://x402agency.com/.well-known/agents): -| Agent | What it does | Cost | -|:------|:-------------|:-----| -| **Banana Agent** | AI image generation (Google Nano Banana Pro) | ~$0.19/image | -| **Veo Agent** | AI video generation with audio (Google Veo 3.1 Fast) | ~$0.75–$1.50/clip | -| **Whisper Agent** | Speech-to-text transcription (Whisper Large v3 Turbo) | ~$0.0006/min | -| **X Research Agent** | Twitter/X search, profiles, threads, trending | ~$0.005–$0.06/req | -| **1Sat Agent** | 1Sat Ordinals inscriptions (any file type) | 200–256,000 sats | -| **bsv-storage** | File hosting with UHRP content addressing (R2) | $0.05/GB-month; 1,000-sat minimum/upload | + +| Agent | What it does | Price range | Delivery | +|:------|:-------------|:------------|:---------| +| Nano Banana 2.1 | New - launched 2026-10-06 · AI Image Generation with Search Grounding | $0.042-$0.14175 USD (per-resolution; 1K to 4K) | async | +| Nano Banana 2 | AI Image Generation with Search Grounding | $0.08375-$0.18875 USD (per-resolution; 1K to 4K) | async | +| Nano Banana Pro | AI Image Generation with Safety Controls | $0.1875-$0.375 USD (per-resolution; 1K to 4K) | async | +| Veo Agent | AI Video Generation | $0.5-$1.5 USD (per-second; 4s silent to 8s + audio) | async | +| Whisper Agent | Speech-to-Text | $0.0006375-$0.019125 USD (per-minute; 1 min to 30 min) | sync | +| X Research Agent | Twitter/X Research API | $0.00625-$3.125 USD (per-resource; Counts: 1 page, mode recent to Search: limit 100, 5 pages (maximum)) | sync | +| Kling Agent | AI Video Generation (Kling) | $0.175-$1.155 USD (per-second; v1 Standard 5s to v3 Standard 3s + audio + voice) | async | +| 1Sat Agent | 1Sat Ordinals Inscriptions | $0.0001-$0.032 USD (per-byte (mining fee + 25%); 1 KB (200 sats min) to 500 KB max (64,000 sats)) | sync | +| OpenAI Agent | AI Chat Completions (GPT-5.x) | $0.002079-$0.94035 USD (per-token; gpt-5-nano (4K out) to gpt-5.5-pro (4K out)) | sync | +| Claude Agent | AI Chat Completions (Claude) | $0.02685-$0.2685 USD (per-token; claude-haiku-4-5 (4K out) to claude-fable-5 (4K out)) | sync | +| PolyMirror Agent | Polymarket Whale Tracking | $0.005-$0.01 USD (per-request; /leaderboard to /trader) | sync | +| BSV Storage | File Hosting (UHRP) | $0.0006083333333333333-$0.6083333333333334 USD (per-GB-month; 1 MB / 1 year (1,000-sat minimum) to 1 GB / 1 year (1,000-sat minimum)) | sync | +| MessageBox | P2P Message Relay | $0 USD (recipient-controlled; Free delivery) | sync | +| Web Reader Agent | URL → Clean Markdown | $0.003-$0.005 USD (per-request; Read URL to Web search) | sync | + + +Ranges use the minimum and maximum USD tier examples exactly as listed by the registry, with their labels and pricing model. They are not universal per-request quotes; use `discover` for endpoint pricing. Our `bsv-storage` server uses Cloudflare R2 for bytes and on-chain UHRP advertisements; the registry hosts its discovery manifest, and the helper derives downloads on `files.x402agency.com` automatically. ## Install -Requires [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and [MetaNet Client](https://getmetanet.com). +Requires [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and either wallet path below. ``` /plugin marketplace add calgooon/x402 @@ -48,8 +60,30 @@ Requires [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and [Meta ### Prerequisites -- **MetaNet Client** running at `localhost:3321` (download from [getmetanet.com](https://getmetanet.com)), or any BRC-100 wallet at the URL in `X402_WALLET_URL` -- **Python 3** with `requests` (`pip install requests`) +Install **Python 3** with `requests` (`pip install requests`), then choose a wallet. Both paths speak BRC-100 over HTTP; the helper sends every wallet call to `X402_WALLET_URL`. + +1. **For a person: MetaNet Client.** Download [MetaNet Client](https://getmetanet.com) and run it at `localhost:3321`, the helper's default wallet URL. +2. **For an agent with no human: bsv-wallet-cli.** Use the self-hosted headless daemon from the [public wallet README](https://github.com/Calhooon/bsv-wallet-cli#readme). Its current installation and inspection commands are: + + ```sh + cargo install bsv-wallet-cli --version 0.7.4 --locked --root ./wallet-tools + ./wallet-tools/bin/bsv-wallet --help + ./wallet-tools/bin/bsv-wallet respend --help + ``` + + The wallet README names `daemon` for the monitor plus HTTP server and `serve` for the HTTP server alone. It directs readers to command help for arguments and to source for configuration defaults. It does not provide complete initialization/start commands, an identity command, funding commands, or the HTTP port. Follow that README and the installed command help to initialize, start, identify, and fund the wallet; those missing commands are not assumed here. + + Once it is running, set the helper's URL to its configured loopback HTTP port, replacing ``: + + ```sh + export X402_WALLET_URL="http://127.0.0.1:" + ``` + + Check the identity through the x402 helper: + + ```sh + python3 skills/x402/scripts/brc31_helpers.py identity + ``` ## Usage @@ -77,7 +111,7 @@ The `/x402` command is the entry point. You can use it conversationally or with | Command | What it does | |:--------|:-------------| | `/x402 list` | List all registered agents with capabilities and pricing | -| `/x402 discover ` | Fetch the x402-info manifest — endpoints, schemas, pricing, error codes | +| `/x402 discover ` | Fetch the x402-info manifest - endpoints, schemas, pricing, error codes | | `/x402 auth ` | Make a BRC-31 authenticated request (no payment) | | `/x402 pay [body]` | Make an authenticated + paid request (auto-handles 402 flow, auto-internalizes refunds) | | `/x402 execute-action ` | Broadcast a pending action template (e.g. a 1Sat inscription) returned by `pay`, after you confirm | @@ -137,7 +171,7 @@ Storage costs $0.05 per GB-month with a 1,000-sat minimum per upload. → skill presents result to user ``` -All payment is automatic — no confirmation prompts for typical micropayments (1–100,000 sats). +All payment is automatic - no confirmation prompts for typical micropayments (1–100,000 sats). ## Wallet selection and sessions @@ -155,9 +189,15 @@ python3 skills/x402/scripts/brc31_helpers.py session --clear-all --dry-run Then `session --clear-all` lists the filenames and deletes all wallets' sessions without confirmation. The registry cache is preserved. These flags also work with `skills/x402/cli.py`. +## Development + +Run checks with `python3 -m pytest -q`. Regenerate the Available Services table from the live registry with `python3 scripts/gen_services.py`; do not edit the generated table by hand. + ## Changelog -- **1.1.1** — Sessions keyed by (server URL, client identity key); a session opened by one wallet is never reused by another (a wallet switch on the same server previously made the server derive the BRC-29 payee key from the wrong identity). Wallet URL configurable via `X402_WALLET_URL`. `createAction` accepts `tx` returned as an index-keyed object. Added `tests/` (`python3 -m pytest -q`). +- **1.1.2** - Document the MetaNet Client and headless wallet paths, including gaps in the wallet README. Generate all service rows, exact registry tier ranges, and sync/async delivery from the public registry. + +- **1.1.1** - Sessions keyed by (server URL, client identity key); a session opened by one wallet is never reused by another (a wallet switch on the same server previously made the server derive the BRC-29 payee key from the wrong identity). Wallet URL configurable via `X402_WALLET_URL`. `createAction` accepts `tx` returned as an index-keyed object. Added `tests/` (`python3 -m pytest -q`). ## Agent Directory diff --git a/scripts/gen_services.py b/scripts/gen_services.py new file mode 100644 index 0000000..e5e5e3c --- /dev/null +++ b/scripts/gen_services.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Regenerate the README service table from the public agent registry.""" + +import argparse +import json +from decimal import Decimal +from html import escape +from pathlib import Path +from urllib.request import Request, urlopen + + +REGISTRY_URL = "https://x402agency.com/.well-known/agents" +README = Path(__file__).resolve().parents[1] / "README.md" +START = "" +END = "" + + +def cell(value): + """Keep registry text inside one Markdown table cell with plain punctuation.""" + return " ".join(escape(str(value).replace("\u2014", "-"), quote=False).split()).replace("|", "|") + + +def price_range(pricing): + tiers = pricing["tiers"] + if not tiers: + raise ValueError("Registry pricing has no tiers") + low = min(tiers, key=lambda tier: tier["usd"]) + high = max(tiers, key=lambda tier: tier["usd"]) + if pricing["currency"] != "USD": + raise ValueError("Registry tier currency is not USD") + amount = f"${low['usd']}" + if high["usd"] != low["usd"]: + amount += f"-${high['usd']}" + labels = low["label"] + if high["label"] != low["label"]: + labels += f" to {high['label']}" + return f"{amount} USD ({pricing['model']}; {labels})" + + +def render_table(agents): + if not agents: + raise ValueError("Registry has no agents") + rows = [ + "| Agent | What it does | Price range | Delivery |", + "|:------|:-------------|:------------|:---------|", + ] + for agent in agents: + delivery = agent["delivery"] + if delivery not in ("sync", "async"): + raise ValueError(f"Unknown delivery mode: {delivery}") + values = (agent["displayName"], agent["tagline"], price_range(agent["pricing"]), delivery) + rows.append("| " + " | ".join(cell(value) for value in values) + " |") + return "\n".join(rows) + + +def update_readme(readme, table): + if readme.count(START) != 1 or readme.count(END) != 1: + raise ValueError("README must contain exactly one pair of services markers") + before, rest = readme.split(START) + _, after = rest.split(END) + return before + START + "\n" + table + "\n" + END + after + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", default=REGISTRY_URL, help="Registry URL or local JSON file") + parser.add_argument("--readme", type=Path, default=README, help="README to update") + args = parser.parse_args() + if args.registry.startswith(("https://", "http://")): + request = Request(args.registry, headers={ + "User-Agent": "x402-services-generator/1.0", + "Accept": "application/json", + }) + with urlopen(request, timeout=30) as response: + raw = response.read() + else: + raw = Path(args.registry).read_bytes() + agents = json.loads(raw, parse_float=Decimal)["agents"] + updated = update_readme(args.readme.read_text(encoding="utf-8"), render_table(agents)) + args.readme.write_text(updated, encoding="utf-8") + print(f"Updated service table: {len(agents)} agents") + + +if __name__ == "__main__": + main() diff --git a/skills/x402/SKILL.md b/skills/x402/SKILL.md index f40e0f1..1892460 100644 --- a/skills/x402/SKILL.md +++ b/skills/x402/SKILL.md @@ -6,13 +6,18 @@ argument-hint: [URL or description of API to call] ## Prerequisites -**MetaNet Client** must be running. Check with: +Run a BRC-100 HTTP wallet: **MetaNet Client** for a person, or the headless +**bsv-wallet-cli** daemon for an agent with no human. See the repository +[README prerequisites](../../README.md#prerequisites) for installation and +the wallet README's setup gaps. Set `X402_WALLET_URL` to the headless daemon's +configured loopback URL. For MetaNet Client at the default URL, check with: ```bash curl -s -H "Origin: http://localhost" http://localhost:3321/isAuthenticated ``` -If not running, tell the user to start it (macOS: `/Applications/Metanet Client.app`, or download from https://getmetanet.com). +If the selected wallet is not running, start that wallet. MetaNet Client is +available from https://getmetanet.com; headless setup follows the public wallet README. -**Choosing the wallet:** every wallet call (identity, signatures, `createAction`, `internalizeAction`, `upload`, `execute-action`) goes to `X402_WALLET_URL` (default `http://localhost:3321`). To pay from a second wallet daemon, prefix the command: `X402_WALLET_URL=http://localhost:3322 python3 ./scripts/brc31_helpers.py pay ...`. BRC-31 sessions are cached per (server, wallet identity key), so switching wallets always gets a fresh handshake for the new identity — never the other wallet's session. +**Choosing the wallet:** every wallet call (identity, signatures, `createAction`, `internalizeAction`, `upload`, `execute-action`) goes to `X402_WALLET_URL` (default `http://localhost:3321`). To pay from a second wallet daemon, prefix the command: `X402_WALLET_URL=http://localhost:3322 python3 ./scripts/brc31_helpers.py pay ...`. BRC-31 sessions are cached per (server, wallet identity key), so switching wallets always gets a fresh handshake for the new identity - never the other wallet's session. ## Task @@ -20,9 +25,9 @@ $ARGUMENTS ## Agent Registry -A directory of available agents lives at `x402agency.com`. Run `list` to see all registered agents — their names, capabilities, and URLs. Agent names resolve automatically anywhere a URL is expected. +A directory of available agents lives at `x402agency.com`. Run `list` to see all registered agents - their names, capabilities, and URLs. Agent names resolve automatically anywhere a URL is expected. -**Always start with `list`** when the user's request could match any registered agent. Use the agent descriptions, capabilities, and taglines to match the user's natural language intent to the right agent. Don't assume which agent to use — check the registry. +**Always start with `list`** when the user's request could match any registered agent. Use the agent descriptions, capabilities, and taglines to match the user's natural language intent to the right agent. Don't assume which agent to use - check the registry. The registry is cached locally for 5 minutes at `~/.local/share/brc31-sessions/registry.json`. Full URLs (`https://...`) still work directly and bypass the registry. @@ -41,27 +46,27 @@ All operations use the helper script bundled with this skill. All commands outpu | `python3 ./scripts/brc31_helpers.py execute-action ` | Execute a pending action template (broadcasts inscription tx after user confirms) | | `python3 ./scripts/brc31_helpers.py session ` | Inspect the current wallet's cached session | -Handshake is automatic — never call it manually before `auth` or `pay`. +Handshake is automatic - never call it manually before `auth` or `pay`. ## Decision Tree -1. **List** — Run `list` to see all registered agents. Match the user's intent to an agent by reading the name, tagline, and capabilities from the registry. There may be many agents — pick the best match. +1. **List** - Run `list` to see all registered agents. Match the user's intent to an agent by reading the name, tagline, and capabilities from the registry. There may be many agents - pick the best match. -2. **Discover** — Run `discover ` on the matched agent to get its full manifest: endpoints, pricing, input schemas. Present a summary to yourself (or the user if they're exploring). +2. **Discover** - Run `discover ` on the matched agent to get its full manifest: endpoints, pricing, input schemas. Present a summary to yourself (or the user if they're exploring). -3. **Route** — Match user intent to an endpoint: +3. **Route** - Match user intent to an endpoint: - `auth: true`, no payment → use **`auth`** - - `payment` with satoshis → use **`pay`** (do NOT ask user to confirm — consent is implicit by invoking this skill; typical costs are 1-100 sats) + - `payment` with satoshis → use **`pay`** (do NOT ask user to confirm - consent is implicit by invoking this skill; typical costs are 1-100 sats) - `auth: false` → plain curl, no skill needed -4. **Call** — Run the appropriate command. For requests with a JSON body, pass it as the 4th argument: +4. **Call** - Run the appropriate command. For requests with a JSON body, pass it as the 4th argument: ```bash python3 ./scripts/brc31_helpers.py pay POST / '{"key":"value"}' ``` -5. **Present** — Parse the JSON response (`{status, headers, body}`). The `body` is a string that may contain nested JSON — parse it before presenting. +5. **Present** - Parse the JSON response (`{status, headers, body}`). The `body` is a string that may contain nested JSON - parse it before presenting. -6. **Action** — If the `pay` response contains `pending_action` (e.g. from 1sat-agent), +6. **Action** - If the `pay` response contains `pending_action` (e.g. from 1sat-agent), present the cost breakdown to the user and ask for confirmation before calling `execute-action`. Do NOT broadcast automatically. The `pending_action` includes costs (service fee, estimated mining fee, estimated total) and the action template. @@ -136,7 +141,7 @@ python3 ./scripts/brc31_helpers.py pay POST "https://some-server.example.com/pai ## Refunds -Servers that support BRC-29 refunds will automatically return refund data when a paid request fails after payment. The client **auto-detects and internalizes refunds** — no manual action needed. +Servers that support BRC-29 refunds will automatically return refund data when a paid request fails after payment. The client **auto-detects and internalizes refunds** - no manual action needed. - **Inline refunds**: Returned in the same response as the error (e.g., `/paid` fails immediately) - **Deferred refunds**: Returned later when polling `/status/{id}` for async operations that failed @@ -147,7 +152,7 @@ The `discover` command shows which endpoints support refunds. The `pay` command Payment is sent via `x-bsv-payment` header as JSON: `{"derivationPrefix":"...","derivationSuffix":"...","transaction":""}`. The client handles this automatically. -**Transport:** Payment normally rides in the `x-bsv-payment` header. For payments larger than 8KB, the client uses BRC-105 multipart/form-data transport **when the server advertises it** (`x-bsv-payment-transports: multipart` on the 402); otherwise it keeps the payment in the header. Typical payments are ~2KB — well under the threshold — so header transport is what's used in practice. (No live x402agency.com agent currently advertises multipart.) +**Transport:** Payment normally rides in the `x-bsv-payment` header. For payments larger than 8KB, the client uses BRC-105 multipart/form-data transport **when the server advertises it** (`x-bsv-payment-transports: multipart` on the 402); otherwise it keeps the payment in the header. Typical payments are ~2KB - well under the threshold - so header transport is what's used in practice. (No live x402agency.com agent currently advertises multipart.) ## Default Test Server @@ -158,7 +163,7 @@ Payment is sent via `x-bsv-payment` header as JSON: `{"derivationPrefix":"..."," - Regular HTTP APIs without BSV authentication - APIs using OAuth, API keys, or JWT (unless specifically BRC-31) -- Coinbase x402 protocol (EVM/Solana only — this skill is BSV-only) +- Coinbase x402 protocol (EVM/Solana only - this skill is BSV-only) ## Troubleshooting @@ -170,7 +175,7 @@ Only consult this section if something goes wrong. | Discovery returns 404 | Server may not have `/.well-known/x402-info`; proceed with known endpoint info or ask user | | Connection error | Server may be down or wallet not running | | Payment error | Tell user to check MetaNet Client for approval prompt; may also be insufficient funds | -| HTTP 401 | Handled automatically — the client clears the stale session, re-handshakes, and retries once. If a 401 still surfaces, the server genuinely rejected auth (not a stale session). | +| HTTP 401 | Handled automatically - the client clears the stale session, re-handshakes, and retries once. If a 401 still surfaces, the server genuinely rejected auth (not a stale session). | | `Signature is not valid` on POST | Session may be stale. Clear: `python3 ./cli.py session --clear ` | | Persistent auth failures | Clear session: `python3 ./cli.py session --clear ` | | Need verbose output | Use full CLI: `python3 ./cli.py -v auth POST ""` | diff --git a/tests/test_gen_services.py b/tests/test_gen_services.py new file mode 100644 index 0000000..1fde763 --- /dev/null +++ b/tests/test_gen_services.py @@ -0,0 +1,63 @@ +"""Service generation preserves registry values and README boundaries.""" + +import runpy +from decimal import Decimal +from pathlib import Path + +import pytest + + +GEN = runpy.run_path(str(Path(__file__).resolve().parents[1] / "scripts/gen_services.py")) + + +def agent(name, delivery="sync"): + return { + "displayName": name, + "tagline": "Text | with\nmarkup and a long dash \u2014", + "delivery": delivery, + "pricing": { + "model": "per-resolution", + "currency": "USD", + "tiers": [ + {"label": "4K", "usd": Decimal("0.375")}, + {"label": "1K", "usd": Decimal("0.1875")}, + ], + }, + } + + +def test_all_agents_exact_bounds_and_safe_cells(): + table = GEN["render_table"]([agent("First"), agent("Second", "async")]) + assert len(table.splitlines()) == 4 + assert "$0.1875-$0.375 USD (per-resolution; 1K to 4K)" in table + assert "| sync |" in table and "| async |" in table + assert "Text | with markup <tag> and a long dash -" in table + assert all(line.count("|") == 5 for line in table.splitlines()) + + +def test_only_generated_region_changes_and_regeneration_is_stable(): + before = "Keep this\n\nstale\n\nAnd this\n" + table = GEN["render_table"]([agent("First")]) + after = GEN["update_readme"](before, table) + assert after == "Keep this\n\n" + table + "\n\nAnd this\n" + assert GEN["update_readme"](after, table) == after + + +@pytest.mark.parametrize("text", [ + "No markers", "", "\n", + "", +]) +def test_bad_markers_are_rejected(text): + with pytest.raises(ValueError): + GEN["update_readme"](text, "table") + + +def test_incomplete_registry_is_rejected(): + with pytest.raises(ValueError): + GEN["render_table"]([]) + with pytest.raises(ValueError): + GEN["render_table"]([agent("First", "unknown")]) + item = agent("First") + item["pricing"]["tiers"] = [] + with pytest.raises(ValueError): + GEN["render_table"]([item])