FastATP

PeerApp — the framework people build tools, agents, and workloads with

PeerApp is a framework layer on top of FastATP's shipped primitives; it does not change any of them. It sits on top of the core API and conforms to the atproto vendored material (wire format).

Scope — read this first, it is the whole point

We are not building a market. We are building the Python package that developers take as a dependency to build the tools, agents, and workloads that could eventually constitute a market. The market is emergent; FastATP ships the primitives and one ergonomic framework, and demonstrates the pattern in an example. Nothing market-specific is shipped in the package.

The line, stated as a rule the framework must not cross:

What ships is PeerApp: a FastAPI-shaped framework that dispatches any user-defined Lexicon to a handler, and gives handlers ergonomic access to the already-shipped machinery (verify, repo write/broadcast, admit/evict). It is generic over the record type end to end.

The pattern PeerApp enables (context, not a shipped artifact)

A developer builds an agent and a tool as peers. The agent signs a request record (its own lexicon) into its repo; the tool, subscribed to the agent's firehose, sees it, does the work, and signs a response record (its own lexicon) into its repo; the agent, subscribed to the tool, correlates the response. No long-poll, no timeout-and-drop; the medium is durable signed records. This is the async, signed, provenance-carrying substrate that replaces MCP for long-running multi-party work — but PeerApp only provides the mechanism (dispatch + admission + emit); the developer provides the records and the meaning.

Why the mechanism is worth shipping as a framework rather than leaving people to hand-roll it on Peer.verify() + RepoMirror:

The resolved architecture decision (constrains the framework)

The DID/repo is the unit and the only enforceable listener boundary. Collections organize records within one identity; they are NOT a listener-isolation or security boundary. Forced by the shipped code:

  1. await Repo.create(did, signing_key) and await PeerServer.create(peer) bind 1 DID = 1 repo = 1 firehose (fastatp/server/peer_server.py, fastatp/repo/repo.py).
  2. The firehose is whole-repo broadcast: PeerServer._emit() pushes every #commit to every subscriber; _subscribe() neither authenticates the subscriber nor filters by collection. Everyone admitted receives every record in the repo.
  3. Verification is whole-commit: RepoMirror re-derives the signed MST root from all of a commit's ops; filtering ops to hide a collection breaks the proof. (This is why atproto's subscribeRepos is whole-repo.)
  4. WireGuard admission (WireGuardReconciler.grant) is per-DID network reachability — the kill switch's granularity.

Consequences the framework must honor:

The PeerApp API to build

Generic over the developer's own Lexicon subclasses. Handlers do not return HTTP; they write records into the app's repo (which broadcasts on the firehose).

# The developer defines their OWN records (their namespace, not ours):
class QuoteRequest(Lexicon):
    nsid = "com.acme.fx.quoteRequest"
    context_id: Tid
    pair: str
    notional: int


class Quote(Lexicon):
    nsid = "com.acme.fx.quote"
    context_id: Tid
    price: str


# The framework we ship:
app = PeerApp(peer, server, reconciler)  # one DID's peer + PeerServer + reconciler


@app.on(QuoteRequest)  # dispatch by $type — any Lexicon subclass
async def price_it(req: QuoteRequest, ctx: Envelope) -> None:
    # ctx: issuer_did, record_cid, received_at — the record is already
    # verified (commit signature, MST membership, rotation-key ban, authorize
    # hook) and parsed. The handler just does work.
    await app.emit(
        "com.acme.fx.quote", generate_tid(), Quote(context_id=req.context_id, price=quote(req))
    )

Required surface — all generic, nothing domain-specific:

Handler execution & concurrency

The topology (one RepoMirror per admitted producer -> dispatch) is fixed; this section is how invocations run in time. Model it on FastAPI: there is one handler per $type, many producers, so many concurrent invocations of that one handler — the multiplicity is calls, not handlers (a @app.on(X) handler is to records what a FastAPI route is to HTTP requests).

Rules:

Two residual design calls remain open: whether per-producer ordering is a decorator flag or an app default, and the queue-full policy's default.

Idempotency is a dial the app sets — the CID detects duplicates, it does not suppress them

A CID is a content hash: the same record always has the same CID, computed by anyone with no coordination, so a redelivered record (cursor-resume replays everything after your last cursor; the checkpoint #sync can re-send current state) carries the same CID. That makes the CID a perfect duplicate detector — but detecting is not suppressing: to skip reprocessing you must remember seen CIDs, which is state (in-memory = lost on restart; durable = a dedup log you maintain). The CID gives the key, not the mechanism.

The levels, cheapest first — most workloads never need durable state:

FastATP ships the two primitives that make every level buildable — the CID (a reliable detector) and the present-state repo (the output-keyed level for free) — and never a mandated dedup store (that would be stateful, opinionated, and wrong for half the workloads). Framework default: it re-dispatches on replay and the handler owns its idempotency. An optional in-memory seen-set may ship as a convenience, labelled "not durable, not exactly-once" — never as a guarantee.

Conveniences & composition patterns

Ergonomic sugar over the primitives above. Each stays optional and must not smuggle in an application schema or a required third party. See PHILOSOPHY.md "How the market gets built" for the model these serve.

# --- admit_issuer: reply-path bootstrapping -------------------------------
@tool_app.on(InspectionRequest, admit_issuer=True)
async def handle(req: InspectionRequest, ctx: Envelope) -> None:
    # admit_issuer=True auto-calls admit(ctx.issuer_did) when this handler runs,
    # so the sender can subscribe to THIS peer's firehose and hear the reply.
    # Without it a first-time sender isn't admitted to your firehose and your
    # response broadcasts where they can't reach it. Defaults False — admission
    # is a sovereign act, so opting in is explicit. It grants subscribe on your
    # WHOLE firehose (the DID/repo is the boundary); for reply-only exposure,
    # reply from a dedicated response DID/repo instead.
    ...

# --- advertise + publish_schemas: opt-in public discovery -----------------
@tool_app.on(InspectionRequest, advertise=True)    # this lexicon is public-facing
async def handle_public(...): ...

@tool_app.on(InternalReindex)                       # advertise defaults False -> NOT published
async def handle_private(...): ...

published = tool_app.publish_schemas()
# Writes a schema record (com.atproto.lexicon.schema-shaped) into this peer's
# repo for every advertise=True handler — and ONLY those. A tool routinely
# supports lexicons it does NOT want to advertise (internal/admin/privileged),
# so publication is per-lexicon opt-in, never "publish everything I handle".
# Returns the schema docs so you can also post them to a bulletin board.

# --- sovereign admission negotiation (edge business logic) ----------------
# A private worker, publicly discoverable, that decides its own admission policy.
# The front desk is a PUBLIC (ungated) peer; the worker firehose is admitted-only.
@frontdesk_app.on(AdmissionRequest)
async def consider(ask: AdmissionRequest, ctx: Envelope) -> None:
    if my_policy_accepts(ask, ctx.issuer_did):      # proof-of-need, payment, OAuth,
        worker_app.admit(ctx.issuer_did)            # human approval — the tool's choice.
    # admit() adds the WireGuard peer; the requester can now reach the private
    # worker firehose. admit()/evict() wrap reconciler.grant/revoke. Whatever
    # policy runs here is this tool's edge business logic, never the substrate —
    # an OAuth check here gates nothing for any other peer (PHILOSOPHY.md).

admit_issuer and advertise are decorator flags on @app.on; publish_schemas is an app method built on the shipped Lexicon.to_lexicon_json(). The bulletin board is example/user code, not library code — a peer whose one handler accepts signed listing records and re-hosts them (a pure relay; the listing's own signature carries authority, not the board's). The framework ships on / emit / admit / advertise / publish_schemas; the board, the Listing lexicon, and the admission policy are the developer's.

The private-response pattern (ephemeral channels, no encryption)

Private replies without encryption and without accounts. The firehose is a shared broadcast, so a service that answers many producers from one repo leaks each response to all admitted subscribers. Two honest answers:

Playbook (all built by the developer; FastATP ships the primitives + optional conveniences):

  1. The service publishes a public contract (its own lexicon, on the bulletin board / its DID document): "responses arrive on an ephemeral did:key repo, reachable as described in a signed attestation, lasting TTL T; here is how to verify it."
  2. A producer sends its request to the service's firehose.
  3. The handler spins up an ephemeral channel — a fresh did:key + repo + hosted firehose — and admits the issuer to that channel (channel.admit(ctx.issuer_did) on the NEW channel — distinct from the admit_issuer=True flag, which admits to the current app). It does the work and posts the response there.
  4. The service posts a chain-of-custody attestation to its PUBLIC repo, signed by its stable main DID, carrying: the request's context_id, the ephemeral DID, the ephemeral firehose's reachability, and the TTL. This signed binding is the entire anti-spoof mechanism — trust flows main DID -> attestation -> ephemeral DID -> response. Nobody can stand up a repo and claim to be the service's channel, because the binding is signed by the main key.
  5. The producer reads the attestation, verifies it against the (discovered, reputation-checked) main DID, connects to the ephemeral firehose (already admitted), reads its private response, and knows from the published TTL when the channel vanishes.

Two hinges that must be exact:

Candidate conveniences (ship as needed — none are application schemas): app.spawn_ephemeral_channel(issuer_did, ttl=…), app.attest(channel, context_id), and consumer-side await peer.follow_attested(attestation). Enablers to build underneath: multi-repo hosting and whole-repo TTL/expiry.

Status: shipping. These mechanics are implemented. The developer surface is two calls — the developer never touches did:key, WireGuard, or attestations:

# Producer — one call spins the channel, admits the issuer by key, writes the
# reply into it, and publishes the signed attestation:
@app.on(InspectionRequest)
async def handle(req, ctx):
    await app.reply_private(ctx, InspectionResult(...), ttl=120)


# Consumer — same call site as the public path:
reply = await agent.call(
    tool_did, request, reply_type=Result, private=True, self_attestation=my_coords
)

Seams underneath: app.open_private_channel(issuer_did, ...), app.attest( channel, context_id, to=board_url), app.follow_attested(attestation); the shipped Attestation record; the doorman enforces the isolation (a second subscriber to the channel is refused). End-to-end symmetric board rendezvous: examples/board_rendezvous.py. The design rests on several interlocking pieces:

WireGuard admission needs each end's WG public key, and WireGuardReconciler.grant gets it by resolving the grantee's DID document. An ephemeral did:key has no document, so a tunnel to/from it can't be set up by resolution — both ends' keys travel out-of-band instead: the requester's key in the request (so the channel can admit it), the channel's key + endpoint in the attestation (signed by the service's main DID — anti-spoof

Note a private reply is ALSO achievable with a dedicated did:web response repo per caller (resolution-based grant, no new code) — heavier but available. The ephemeral did:key flavor is the lightweight, self-cleaning alternative. The workorder example uses the public reply path only and does not depend on any of this.

First contact (board rendezvous — resolves the fully-private case). A fully private service can't receive a first request over pull (no tunnel to any requester yet), and it should NOT need a public intake endpoint of its own (that would give it a probeable public surface). The resolution is symmetric contact via the bulletin board (PHILOSOPHY.md "First contact"): the requester posts a signed want ad on the public board carrying its WG public key + reachability; the private service — whose only move is outbound (subscribe to the board) — sees it, answers with a signed engagement record (its channel's key + endpoint, same attestation shape as the private-response pattern), and both sides admit each other by key. The request architecture is the response architecture. Consequences for the framework:

Multi-repo hosting: the apartment building

One PeerServer hosting many repos, add/removed live at runtime (a registry routed by DID), is the shape ephemeral channels force: a channel's did:key does not exist until the request arrives, so no static configuration can describe it. It is also plain atproto — a PDS hosts thousands of repos in one service, subscribeRepos frames each carry their did, getRepo takes ?did=. FastATP's one-repo server was the degenerate case; the wire format needs zero changes.

Why not server-per-repo? Not philosophy — operations. Per-channel listeners mean birthing and killing network endpoints (ports, firewall/NAT rules, endpoint discovery in every attestation) at request rate: a Kubernetes-shaped infra project as the default path for "reply privately", which kills both "easy for anyone" and the RPi fleet story. In the shared building, spawning a channel is a dictionary insert.

Two guarantees silently lean on "one server = one repo" today and must be deliberately re-attached to the repo, or they evaporate:

Same lesson both times: multi-repo hosting splits server from repo, and every guarantee that secretly leaned on their identity must be re-attached to the repo on purpose.

Deployment remains composable — two independent axes: isolation model (shared building + doorman vs. server-per-repo) x enforcement plane (native WG reconciler vs. tailnet vs. firewall vs. open). Multi-repo hosting makes the shared building the cheap zero-dependency default; server-per-repo stays available for whoever would rather buy orchestration than run a doorman — e.g. one repo per port with tailnet ACLs gating each, keeping enforcement purely network-level. Note the trade: a tailnet's control plane is a reachability authority (a trusted third party for who-reaches-what — legitimate inside an org, exactly the dependency the native WG plane avoids across orgs), and capability<->ACL drift is manual unless someone writes a tailnet enforcement adapter against the injectable WireGuardInterface protocol — a welcome, on-philosophy contribution.

Execution semantics = routing topology (framework stays neutral)

The framework must NOT bake in at-most-once vs. race. Topology carries it, and that's the developer's choice: grant one tool DID (one tunnel = exactly-once, by construction) or grant N (fan-out / consensus, take first-or-best reply). PeerApp just makes admit/evict cheap so tool selection is as ephemeral as the developer wants.

What already exists vs. what to build

Reuse as-is (do not modify): Peer.verify() (fastatp/peer.py), PeerServer (fastatp/server/peer_server.py), RepoMirror (fastatp/repo/sync.py), WireGuardReconciler.grant/revoke/reconcile (fastatp/authz/reconciler.py), Capability/Revocation (fastatp/authz/capability.py), did:web + DIDServer, the full Lexicon palette (fastatp/lex/).

Build (this is the entire deliverable):

  1. PeerApp — per-producer RepoMirror fan-in, per-app $type dispatch, Envelope, emit, call, admit/evict. Generic over any Lexicon. Multiple instances per process. This is a framework module (propose fastatp/app.py or fastatp/peerapp/), exported from fastatp.__init__.
  2. Tests: dispatch to the right handler by $type; unknown $type ignored; emit broadcasts and round-trips; call correlates a reply (subscribe- before-emit; local timeout raises without affecting the peer); admit/evict toggle reachability (reuse the SimTunnel harness from test_integration_authz.py); idempotent redelivery (same record CID -> handler fires once); multi-app-per-process isolation.
  3. examples/workorder.py — a demonstration, defining its own request / status / result lexicons in a com.example.* namespace (mirroring how examples/two_peers.py defines com.example.agent.*). This is where the "workload market" pattern is shown; it is example code, not library code.

First slice — examples/workorder.py acceptance

Developer-defined lexicons in com.example.*, real DIDServers over localhost, real signed records both ways, all over PeerApp:

  1. An agent-app and a tool-app, each its own DID/repo/PeerServer, admit each other (real Capability records + SimTunnel/WG admission).
  2. Agent emits a request record addressed to the tool.
  3. Tool-app's handler fires, emits a "received" status record, does the work, emits a result record.
  4. Agent-app's handlers receive status then result and correlate by the app's correlation field.
  5. Liveness: assert status precedes result — silence vs. work is distinguishable.
  6. Kill switch: agent evicts the tool; a subsequent request never arrives, and the Revocation is visible on the agent's firehose as audit.
  7. Idempotency: replay the same request (reconnect with an old cursor); the handler fires once.

Suite/lint/types green, coverage held. Some framework design calls remain open (module layout; per-producer ordering flag vs. default; queue-full policy default). app.call ships in v1.

Deferred (do not build; do not let the framework assume it)