Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 14 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Say what you want. The skill handles the rest:
/x402 generate an image of a mountain sunset
/x402 transcribe this audio file
/x402 search twitter for AI agent discussions
/x402 upload this file to NanoStore for a year
/x402 upload this file to bsv-storage for a year
```

Under the hood:
Expand All @@ -31,9 +31,9 @@ The skill discovers agents from [x402agency.com/.well-known/agents](https://x402
| **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 |
| **NanoStore** | File hosting with UHRP content addressing (Babbage) | ~$0.0004/MB/yr |
| **bsv-storage** | File hosting with UHRP content addressing (R2) | $0.05/GB-month; 1,000-sat minimum/upload |

Third-party services like NanoStore are listed in the directory with hosted manifests — clients connect directly, no proxy.
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

Expand All @@ -58,7 +58,7 @@ The `/x402` command is the entry point. You can use it conversationally or with
### Natural language
```
/x402 generate a photo of a cat in a top hat
/x402 upload report.pdf to NanoStore for 1 year
/x402 upload report.pdf to bsv-storage for 1 year
/x402 search twitter for "bitcoin scaling" from the last 24 hours
/x402 transcribe meeting.wav
```
Expand All @@ -67,8 +67,8 @@ The `/x402` command is the entry point. You can use it conversationally or with
```
/x402 list # List all agents in the directory
/x402 discover banana # Show endpoints, pricing, schemas for an agent
/x402 discover nanostore # Works for third-party services too
/x402 auth GET nanostore/list # Authenticated request (no payment)
/x402 discover bsv-storage # Registry-hosted storage discovery
/x402 auth GET bsv-storage/list # Authenticated request (no payment)
/x402 pay POST banana/generate {"prompt":"a sunset"} # Paid request
```

Expand All @@ -84,7 +84,7 @@ The `/x402` command is the entry point. You can use it conversationally or with
| `/x402 identity` | Show your wallet's identity key |
| `/x402 session <url>` | Inspect a cached BRC-31 session |

Agent names (`banana`, `nanostore`, `whisper`, etc.) resolve automatically. Full URLs work too.
Agent names (`banana`, `bsv-storage`, `whisper`, etc.) resolve automatically. Full URLs work too.

## Examples

Expand All @@ -95,9 +95,13 @@ Agent names (`banana`, `nanostore`, `whisper`, etc.) resolve automatically. Full
```

### Upload a file

The upload command defaults to `bsv-storage` at `storage.x402agency.com`.
Storage costs $0.05 per GB-month with a 1,000-sat minimum per upload.

```
/x402 upload report.pdf to NanoStore for 1 year
→ discovers NanoStore, pays ~730 sats for 1MB/year, returns presigned upload URL
/x402 upload report.pdf to bsv-storage for 1 year
→ discovers bsv-storage, requests the exact quote (1,000-sat minimum), pays, PUTs the bytes, and verifies the public URL
```

### Search Twitter
Expand Down Expand Up @@ -157,7 +161,7 @@ Then `session --clear-all` lists the filenames and deletes all wallets' sessions

## Agent Directory

The skill resolves short names (like `banana` or `nanostore`) to full URLs via the [x402agency.com](https://x402agency.com) registry. Any BRC-31/BRC-29 service can be listed — including third-party services that don't serve their own discovery manifest.
The skill resolves short names (like `banana` or `bsv-storage`) to full URLs via the [x402agency.com](https://x402agency.com) registry. Any BRC-31/BRC-29 service can be listed, including third-party services that don't serve their own discovery manifest.

The registry is cached locally for 5 minutes. Full URLs (`https://...`) bypass the registry entirely.

Expand Down
26 changes: 13 additions & 13 deletions skills/x402/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,23 @@ Handshake is automatic — never call it manually before `auth` or `pay`.

## File uploads (UHRP)

For UHRP storage servers (`nanostore`, or a protocol-compatible port like
`bsv-storage-cloudflare`), use the **`upload`** command. It does the whole
two-step flow in one shot: pays `POST /upload` (BRC-29), PUTs the file bytes
to the presigned storage URL with the required headers, derives the public
URL, and verifies it serves.
Use **`upload`** with the registry name `bsv-storage` (the default server).
It pays `POST /upload` at `https://storage.x402agency.com`, PUTs the file bytes
to the presigned R2 URL with required headers, and derives the public URL
from the registry-hosted manifest at
`https://x402agency.com/manifests/bsv-storage.json`. Downloads use
`https://files.x402agency.com/cdn/{id}`. Pricing is $0.05 per GB-month with a
1,000-sat minimum per upload to cover the overlay advertisement miner fee.

```bash
# nanostore: public URL is auto-derived from the discovery manifest
python3 ./scripts/brc31_helpers.py upload ./report.html nanostore 525600

# R2-backed server: its S3 upload endpoint is NOT the public domain, so pass
# the public base (the bucket's r2.dev URL or a custom domain)
python3 ./scripts/brc31_helpers.py upload ./report.html \
https://bsv-storage-cloudflare.dev-a3e.workers.dev 525600 \
--public-base https://pub-XXXX.r2.dev
python3 ./scripts/brc31_helpers.py upload ./report.html bsv-storage 525600
# Default server and one-year retention:
python3 ./scripts/brc31_helpers.py upload ./report.html
```

For another protocol-compatible server without a public URL manifest, pass
its full API URL and `--public-base https://your-public-files-domain`.

- `retention_min` is the hosting duration in minutes (default `525600` = 1 year).
- Content-Type is guessed from the file extension so the file renders in a browser.
- Returns JSON with `publicURL`, `objectKey`, `amountSats`, and `verified`.
Expand Down
3 changes: 2 additions & 1 deletion skills/x402/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,8 @@ def build_parser() -> argparse.ArgumentParser:
help="UHRP file upload (pay /upload + PUT bytes + derive public URL).",
)
p_up.add_argument("file", help="Path to the file to upload.")
p_up.add_argument("server", help="UHRP server name (e.g. nanostore) or full URL.")
p_up.add_argument("server", nargs="?", default="bsv-storage",
help="UHRP server registry name or full URL (default bsv-storage).")
p_up.add_argument(
"retention",
nargs="?",
Expand Down
46 changes: 16 additions & 30 deletions skills/x402/lib/upload.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,10 @@
"""End-to-end UHRP file upload over BRC-31 auth + BRC-29 payment.

UHRP storage servers (nanostore.babbage.systems and protocol-compatible
ports such as bsv-storage-cloudflare) split a file upload into two steps:

1. POST /upload {fileSize, retentionPeriod} -> paid (BRC-29). The server
replies with a *presigned* storage URL (GCS or R2 S3) plus the
``requiredHeaders`` that must accompany the PUT. The server never
proxies the file bytes.
2. PUT the raw bytes directly to that presigned URL.

The ``pay`` command only does step 1, so callers had to hand-roll the PUT
and then guess the public URL. ``do_upload`` does the whole thing and
returns the public, browsable URL.

Works against any protocol-compatible UHRP server:

* nanostore -> files served from a public GCS bucket; the public URL is the
presigned URL with its query stripped (and matches the discovery
manifest's ``publicUrlFormat``).
* bsv-storage-cloudflare (R2) -> the presigned PUT goes to the R2 *S3 API*
endpoint (``<acct>.r2.cloudflarestorage.com``), which is NOT the public
domain. R2's public domain (an ``r2.dev`` URL or a custom domain) is
separate, so it can't be derived from the upload URL. Pass it with
``public_base`` to get the browsable URL.
The default server is ``bsv-storage``, resolved through the x402agency registry.
POST /upload pays for a presigned R2 PUT URL; PUT sends the file bytes with
all required headers. The registry-hosted manifest supplies the public files
URL, separate from the R2 S3 endpoint. Protocol-compatible servers may use
an explicit ``public_base`` override instead.
"""

from __future__ import annotations
Expand All @@ -39,6 +21,7 @@

# A year, in minutes (UHRP retention is expressed in minutes; 525600 = 365d).
DEFAULT_RETENTION_MINUTES = 525_600
DEFAULT_STORAGE_SERVER = "bsv-storage"


class UploadError(Exception):
Expand Down Expand Up @@ -85,13 +68,16 @@ def _derive_public_url(
# 1. Explicit override always wins.
if public_base:
return public_base.rstrip("/") + "/" + object_key
# 2. Discovery manifest's publicUrlFormat (nanostore advertises this).
# 2. Discovery manifest's publicUrlFormat (the registry advertises this).
if manifest:
pattern = (manifest.get("publicUrlFormat") or {}).get("pattern")
if pattern and "{base58id}" in pattern:
return pattern.replace("{base58id}", object_key.rsplit("/", 1)[-1])
url_format = manifest.get("publicUrlFormat") or {}
pattern = url_format if isinstance(url_format, str) else url_format.get("pattern")
if pattern:
for placeholder in ("{id}", "{base58id}"):
if placeholder in pattern:
return pattern.replace(placeholder, object_key.rsplit("/", 1)[-1])
# 3. Strip the query off the presigned URL. Correct when the storage
# endpoint IS the public domain (GCS public buckets / nanostore).
# endpoint IS the public domain (public storage buckets).
parsed = urllib.parse.urlparse(upload_url)
if "r2.cloudflarestorage.com" in parsed.netloc:
# R2's S3 API host is never public — caller must supply public_base.
Expand All @@ -101,14 +87,14 @@ def _derive_public_url(

def do_upload(
file_path: str,
server: str,
server: str = DEFAULT_STORAGE_SERVER,
retention_minutes: int = DEFAULT_RETENTION_MINUTES,
public_base: str | None = None,
verify: bool = True,
) -> dict:
"""Upload ``file_path`` to a UHRP storage ``server`` and return its URL.

``server`` may be a registry name (e.g. ``nanostore``) or a full URL.
``server`` may be a registry name (e.g. ``bsv-storage``) or a full URL.
Returns a dict with ``publicURL`` (or ``None`` + a ``note`` when it can't
be derived), the ``objectKey``, sats paid, and a verify result.
"""
Expand Down
12 changes: 6 additions & 6 deletions skills/x402/scripts/brc31_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
brc31_helpers.py session --clear-all List and clear all stored sessions
brc31_helpers.py auth <METHOD> <url> [body] Authenticated request
brc31_helpers.py pay <METHOD> <url> [body] Auth + payment request
brc31_helpers.py upload <file> <server> [retention_min] [--public-base URL]
brc31_helpers.py upload <file> [server] [retention_min] [--public-base URL]
UHRP file upload (pay /upload + PUT + public URL)
brc31_helpers.py execute-action <json> Execute a pending action template (broadcasts tx)
"""
Expand All @@ -27,7 +27,7 @@
from lib.auth_request import authenticated_request
from lib.payment import paid_request
from lib.metanet import get_identity_key
from lib.upload import do_upload, DEFAULT_RETENTION_MINUTES
from lib.upload import do_upload, DEFAULT_RETENTION_MINUTES, DEFAULT_STORAGE_SERVER
from lib import registry


Expand Down Expand Up @@ -157,19 +157,19 @@ def main():
print(json.dumps(result, indent=2))

elif cmd == "upload":
# upload <file> <server> [retention_min] [--public-base URL]
# upload <file> [server] [retention_min] [--public-base URL]
rest = sys.argv[2:]
public_base = None
if "--public-base" in rest:
i = rest.index("--public-base")
public_base = rest[i + 1]
del rest[i : i + 2]
if len(rest) < 2:
if len(rest) < 1:
print(json.dumps({"error": "UsageError",
"message": "upload <file> <server> [retention_min] [--public-base URL]"}))
"message": "upload <file> [server] [retention_min] [--public-base URL]"}))
sys.exit(1)
file_path = rest[0]
server = rest[1]
server = rest[1] if len(rest) > 1 else DEFAULT_STORAGE_SERVER
retention = int(rest[2]) if len(rest) > 2 else DEFAULT_RETENTION_MINUTES
result = do_upload(file_path, server, retention_minutes=retention, public_base=public_base)
print(json.dumps(result, indent=2))
Expand Down
48 changes: 48 additions & 0 deletions tests/test_upload_registry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Registry discovery must separate R2 uploads from public downloads."""
import pytest
import cli
from lib.upload import _derive_public_url


@pytest.mark.parametrize("url_format", [
{"pattern": "https://files.example.com/cdn/{id}"},
{"pattern": "https://files.example.com/cdn/{base58id}"},
"https://files.example.com/cdn/{id}",
])
def test_public_download_uses_manifest_host(url_format):
assert _derive_public_url(
"https://example.r2.cloudflarestorage.com/bucket/cdn/sample?signature=private",
"cdn/sample", None, {"publicUrlFormat": url_format},
) == "https://files.example.com/cdn/sample"


def test_upload_defaults_to_registry_storage():
args = cli.build_parser().parse_args(["upload", "report.txt"])
assert args.server == "bsv-storage"
assert args.retention == 525600


def test_upload_keeps_explicit_server_and_retention():
args = cli.build_parser().parse_args(["upload", "report.txt", "https://other.example", "180"])
assert args.server == "https://other.example"
assert args.retention == 180


def test_skill_helper_defaults_to_registry_storage(monkeypatch, capsys):
import importlib.util
import sys
from pathlib import Path
path = Path(__file__).parents[1] / "skills/x402/scripts/brc31_helpers.py"
spec = importlib.util.spec_from_file_location("storage_helper", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
calls = []
def upload(file_path, server, **kwargs):
calls.append((file_path, server, kwargs))
return {"status": "success"}
monkeypatch.setattr(module, "do_upload", upload)
monkeypatch.setattr(sys, "argv", ["helper", "upload", "report.txt"])
module.main()
assert calls == [("report.txt", "bsv-storage", {
"retention_minutes": 525600, "public_base": None,
})]
Loading