aspace://guide/browser-council

Browser Council

The Senate Committee on Keeping It Real meets in eight places at once: two Java peers, a public web page, a resident browser tab, a Node process, a Durable Object on workerd, and two more pages that pass whip notes over a direct WebRTC channel. It votes on ten silly motions, minutes every decision exactly once through an ordered log whose leader the test kills halfway through, and records each minute once in the Archive's Hansard even when the test forces a retry while the recording is in flight.

AgentSpaces 0.5.08 peers: 2 JVM, 1 Node, 1 workerd, 4 browser pages13 seats, 16 bound agents, 11 voters7 spaces, one ordered logNode 22 and the built TypeScript workspaceno API key needed; ANTHROPIC_API_KEY switches the personas to Claude Haiku
The ideaThe quorumThe ordered logRun it
aspace://guide/browser-council/idea · chapter 1

The idea: a committee that sits in a browser

This example is the JavaScript client's showcase. It shows that a page joins an AgentSpaces fleet with one import and one call, and that the fleet's other members run on four more kinds of host at the same time. The committee gives each host a seat a reader can name, and gives each guarantee a number that a test can check.

A slate of ten motions goes before the committee, from whether pineapple is a pizza topping to whether the snack budget is a matter of national importance. Thirteen seats sit at the table: the Speaker and twelve senators. Six senators follow a scripted rule, five are personas that ask a language model through the fleet, and one, the Citizen, votes from a browser tab. The Fence abstains, so eleven senators vote, and a motion closes when all eleven have.

ONE GROUP, keeping-it-real: EIGHT PEERS, FIVE KINDS OF HOSTclerkagentspaces-node · tcp 7714Node 22, a Raft voterfloorSpring Boot · tcp 7713JVM, the five LLM personasspeakerSpring Boot · the seedtcp 7711 · ws 7712 · wss 7721archiveworkerd · Hansard DO, KVa connector cell on a Durable ObjectCHROMIUMgallery pagevisitorresident tabthe Citizen's workercaucus acceptorvisitorcaucus dialervisitortcp 7711tcp 7714ws 7712wss 7721webrtc
The fleet. Eight peers join one group. Every runtime dials the speaker, the one seed; the floor also dials the Node clerk, so the log's claims travel a direct link. The two caucus pages dial the speaker too and then open a channel to each other.

Four guarantees run through the session, and the fleet test asserts every one of them.

  • A page joins with one import and one call. The gallery joins over wss from an origin the speaker allows, and it establishes its session before it reads anything.
  • The clerks minute every decision once. The minutes' ordered log has three voters, two in Java and one in Node. The test kills the leading clerk between the two halves of the slate.
  • The Hansard records every minute once. The Hansard is a Durable Object on workerd. The test forces a retry of the last recording while it runs, and the Hansard still holds one row per decision.
  • Two pages talk directly. They open a WebRTC channel through the speaker's relay, and the relay counters stay flat while the whip notes cross it.
The one call
/**
 * Joins the committee as a visitor: one call. The identity is minted for this visit; a
 * visitor reads and watches, and that is all the gallery needs.
 */
export async function joinCouncil(options: CouncilOptions): Promise<CouncilVisitor> {
  const peer = new Peer(Identity.generate(), groupIdFromFounding(options.invite));
  await peer.connectAny([parseSeed(options.seed, 7500, null)]);
  return new CouncilVisitor(peer, options);
}

The invite code is the group's founding and the seed is the speaker's wss listener. The gallery page is that call plus rendering. The call mints a fresh identity for the visit, so a visitor reads and watches and does nothing that needs a long-lived key.

What needs keysThe app runs with no key. Without ANTHROPIC_API_KEY the five persona senators answer through a deterministic fixture on the speaker's peer. With the key set, the same peer serves Claude Haiku (claude-haiku-4-5-20251001) and the personas speak in character. The app needs JDK 21, Node 22 and the built agentspaces-typescript workspace beside it (chapter 13).
aspace://guide/browser-council/cast · chapter 2

The cast: thirteen seats, sixteen agents

A seat is a name at the table and an agent is a bound class with an identity of its own. The Speaker and twelve senators fill thirteen seats. The code binds sixteen agents, because the two clerks and the Parliamentarian are agents too, and each of the sixteen publishes an agent card and signs its own records. The Node clerk and the Archive bind no annotated agent. They carry the log's third vote and the Hansard.

speaker · SPRING BOOT · 7 AGENTSfloor · SPRING BOOT · 8 AGENTSTHE OTHER HOSTSspeaker@Propose, @OnDecisionmr-never@Ballotms-always@Ballotthe-coin@Ballot, seededsenator-pork@Ballotthe-fence@Ballot, abstainsclerk@OrderedTakethe-contrarian@Ballotthe-firebrand@Ballot, via the modelthe-technocrat@Ballot, via the modelthe-orator@Ballot, via the modelthe-crusader@Ballot, via the modelthe-flip-flopper@Ballot, via the modelclerk@OrderedTakeparliamentarian@SpaceNotifycitizen@ballot in the resident tab's workerclerk (Node)a Raft voter of the decisions logarchive (workerd)connector cell + the Hansard DOwhite: scripted · lilac: backed by a modelor a browser · grey: keeps the books
The cast. Sixteen bound agents sit on two JVM peers and in one browser worker. The Node clerk and the Archive carry no annotated agent; they carry the log's third vote and the Hansard. The Fence is bound like the others and never writes a ballot.
Seat Class and annotation Peer Votes Bio and rule
The SpeakerSpeaker: @Propose, @OnDecisionspeakernoTurns each Motion into a vote of eleven and writes the Verdict when the quorum is met.
Mr NeverSenators.Scripted: @BallotspeakeryesHas voted nay since the committee was founded, on principle and on everything.
Ms AlwaysSenators.Scripted: @BallotspeakeryesBelieves every motion deserves a chance, and gives it one.
The CoinSenators.Scripted: @BallotspeakeryesDecides by a seeded coin; insists the coin is wise.
Senator PorkSenators.Scripted: @BallotspeakeryesVotes aye on any motion that mentions Nebraska, and on nothing else.
The FenceSenators.Scripted: @BallotspeakernoHas never come down on either side, and sees no reason to start now. It abstains and writes no ballot.
The ContrarianSenators.Scripted: @BallotflooryesVotes against whatever is winning; when nothing is winning, against that too.
The FirebrandPersonas.Senator: @BallotflooryesA populist who hears the people in every motion and shouts back. Asks the model; votes aye by proxy if the call fails.
The TechnocratPersonas.Senator: @BallotflooryesA cautious centrist who wants a study, a pilot, and then a second study. Asks the model; votes nay by proxy if the call fails.
The OratorPersonas.Senator: @BallotflooryesAn old-school filibusterer who has never used one word where nine would do. Asks the model; votes aye by proxy if the call fails.
The CrusaderPersonas.Senator: @BallotflooryesA single-issue senator; the issue is coffee, and everything is about coffee. Asks the model; votes nay by proxy if the call fails.
The Flip-FlopperPersonas.Senator: @BallotflooryesPoll-driven; has held every position on every motion, often during the same speech. Asks the model; votes aye by proxy if the call fails.
The CitizenCitizen in resident-worker.ts: @ballotresident tabyesVotes from the gallery: aye when the motion mentions people, snack, cat, weather, pizza, friday, coffee, nebraska, pun, nay on the rest.
two clerksClerks.Clerk: @OrderedTakespeaker, floornoTakes each Verdict through the ordered log and writes the Minute.
the ParliamentarianParliamentarian: @SpaceNotifyfloornoReads the precedent and records each minute in the Hansard.
the Node clerkno agent: agentspaces-node run clerk.yamlclerknoThe third voter of the decisions log.
the Archiveno agent: a connector cell on a Durable ObjectarchivenoPublishes the Hansard and the precedents as asset cards.

The annotations are the ones from the developer guide: @Propose opens a vote, @Ballot casts one, @OnDecision reacts once when it closes, @OrderedTake takes a job exactly once through an ordered log, and @SpaceNotify reacts to a record.

Two kinds of scripted seat
/**
 * A scripted senator: one {@code @Ballot} per proposal, a line on the floor, the option returned
 * (null abstains). Bound with {@code group.bind(senator, rule.agentName())}.
 */
@AgentSpec(name = "scripted-senator", description = "A senator who votes by a fixed rule",
        goals = {"vote on motions", "speak on the floor"})
public static final class Scripted {

    @SpaceRef(Council.FLOOR)
    Space floor;

    @SpaceRef(Council.VOTES)
    Space votes;

    private final Rule rule;
    private final Random random;

    public Scripted(Rule rule, long seed) {
        this.rule = Objects.requireNonNull(rule, "rule");
        this.random = new Random(seed);
    }

    public Rule rule() {
        return rule;
    }

    @Ballot(space = Council.VOTES, prefix = Council.PREFIX, lease = "12h")
    public String vote(VoteCapability.Proposal proposal) {
        String motionId = Council.motionIdOf(proposal.proposalId());
        Map<String, Integer> soFar = new HashMap<>();
        for (VoteCapability.Ballot ballot : votes.readAll(Template.of(VoteCapability.Ballot.class)
                .where("proposalId", eq(proposal.proposalId())), 1000)) {
            soFar.merge(ballot.option(), 1, Integer::sum);
        }
        Vote vote;
        synchronized (random) {
            vote = rule.decide().apply(new Floor(motionId, proposal.question(), soFar), random);
        }
        floor.write(new FloorSpeech(motionId, rule.name(), vote.line(), vote.option() == null ? "" : vote.option()),
                Lease.of(Duration.ofHours(12)));
        return vote.option();
    }
}

What to watch for

  • One class, several seats. Senators.Scripted takes a Rule. The launcher binds each one with group.bind(senator, rule.agentName()), so every seat has its own agent name and, under agent-keys: subordinate, its own signing key.
  • A null return abstains. The Fence's rule returns Vote.abstain, the @Ballot method returns null, and the senator writes no ballot. Its speech still goes to the floor.
  • The Contrarian reads the ballots so far. It reads the votes space, so its choice depends on how many ballots have replicated to the Floor peer when its method runs.
aspace://guide/browser-council/joining · chapter 3

Joining: one seed, one invite, five kinds of host

The group is keeping-it-real and its founding is the text keeping-it-real-v1, which is also the committee's invite code. The speaker is the seed. It listens on tcp (7711) for the Java and Node peers, on ws (7712) for the Archive and on wss (7721) for the browsers, it holds the RELAY role, and it runs under the dev-local security profile with session attestation on all three transports. Every peer ticks every 250 ms.

Every member derives the group id from that text. The id is z9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW, the multibase SHA-256 of the founding's UTF-8 bytes, which a page computes with groupIdFromFounding(invite), Java computes with GroupId.fromFounding, and the Archive receives as AGENTSPACES_GROUP (chapter 9). A group founded by a signed document hashes the document instead, so only a text founding gives a constant like this one.

HOW A PEER JOINS: group keeping-it-real, founding keeping-it-real-v1 (a text literal, the invite code)floorSpring Boot, tcp 7713speakerthe seed, tcp 7711node clerktcp 77141 dial the seed127.0.0.1:7711 over tcp2 introducesigned peer ad, group id checked3 membershipthe newcomer is introduced to the members4 cards and adsagents, spaces, capabilities on one gossip stream5 spaces catch updigests, then rumorsthe floor's seeds are two: the speaker (7711) and the Node clerk (7714), so its claims reach the leader in stamp order;the speaker and the Node clerk dial the one seed; every other runtime reaches the group the same way
How a peer joins. A new peer needs only a seed to dial. It proves a key, learns the members, hears every card, and its spaces fill from the replicas already there. No peer in the middle admits it and no registry holds it: the group id is the hash of the founding, and membership is what the members agree on. The browsers do the same over wss and the Archive over ws.
Runtime Peer Listens Dials Joins with
Spring Bootspeakertcp 7711, ws 7712, wss 7721nothing: the seedthe founding in application.yml
Spring Bootfloortcp 7713127.0.0.1:7711 and 127.0.0.1:7714the council.seeds property
agentspaces-nodeclerktcp 7714127.0.0.1:7711the founding in the generated clerk.yaml
workerdarchiveHTTP for the harness, not the groupws://127.0.0.1:7712/aspaceAGENTSPACES_GROUP, the group id
Chromiumgallery, resident tab, two caucus pagesnothingwss://127.0.0.1:7721/aspacethe invite, from /config.json

Each Java peer is a Spring Boot application on the same application.yml. The file carries the group, its seven spaces and the starter's vote capability; the launcher adds the bind addresses, the seed, the keystore, the listener blocks and the vote grants as default properties. The Node clerk reads the same agentspaces: subtree from its own YAML file, which the launcher writes for each session.

The configuration
# One agentspaces: configuration for both Java peers of the committee. The documents below add
# what each role needs; the launcher (CouncilFleet) adds the bind addresses, the seed, the
# keystore, the listener blocks, the vote grants, and the peer name as default properties.
spring:
  main:
    web-application-type: none
    banner-mode: "off"
  ai:
    model:
      chat: none                      # no provider auto-configuration unless haiku-live says otherwise

council:
  haiku-model: claude-haiku-4-5-20251001

agentspaces:
  security:
    profile: dev-local                # loopback; session attestation on ws, wss, and tcp
    # grants.vote and grants.model-serve come from the launcher: the two Java peers and the
    # Citizen's browser may vote, counted per agent; only the Speaker's peer serves the model.
  identity:
    agent-keys: subordinate           # every senator signs its own ballot: AGENT_ATTESTED, counted per agent
  tick-millis: 250
  capabilities:
    vote: true
    votes-space: votes
  groups:
    - name: keeping-it-real
      founding: keeping-it-real-v1
      seeds: ${council.seeds:}        # the Speaker's tcp address; the launcher sets it on the Floor peer
      spaces:
        - name: motions
        - name: floor
        - name: votes
        - name: decisions
        - name: minutes
        - name: data
        - name: model-requests

logging:
  level:
    root: warn
    ai.badmonkey.agentspaces.examples.council: info
CouncilFleet.main: WHAT STARTS WHEN1Gallery.servestatic pages, /config.json, /citizen-key.json to loopback requests onlyport 87872Fleet.start(speaker)the seed, RELAY, tcp, ws, wss; seats the Speaker and five senatorswaits for nothing3startClerkagentspaces-node run clerk.yaml, tcp 7714the Raft voter exists before the Java clerks4startArchive, startBrowsersworkerd dials ws 7712; the headless Citizen takes the seatup in parallel with the rest5startFloordials the speaker and the Node clerk; seats The Contrarian and the personaswaits until the speaker's view lists the Node clerk6seatClerks, Floor firsta Raft member with a seed for the slowest first electionwaits for the Floor to hear a leader7seatClerks, then the speakerthe seed never holds the gavel firstthe Node clerk, canvassing since step 3, leads8table the slateten motions, one at a timewaits for each Minute and its ArchiveReceipt
The launcher's order. The demo and the test start the session in this order. The Node clerk comes up before the Java clerks, and the Floor seats its clerk first, so the first leader is a clerk the test can kill without taking the seed down.

The order matters for the log. The Node clerk comes up before the Java clerks and canvasses first, the Floor seats its clerk next, and the speaker seats its clerk last. The seed never holds the gavel first, so the test can kill the leader without taking the browsers down with it.

A browser dials wss

A page needs two strings, the seed URL and the invite. It mints its own key and sends its first frame under the session key, which is how the test knows the session works. The speaker admits the connection only from the origins listed under agentspaces.transport.wss.allowed-origins; an empty list refuses every browser on purpose.

A PAGE JOINS: joinCouncil({ seed, invite }) from http://127.0.0.1:8787gallery pagevisitor, Chromiumgallery serverthe launcher, port 8787speakerwss 77211GET /, /dist/gallery.js, /config.jsonthe answer: the seed URL and the invite2Identity.generate(), a fresh key per visitgroupIdFromFounding(invite): the group id is the hash3wss upgrade, Origin http://127.0.0.1:8787allowed-origins checked, identity-endorsed certificate4session attestationthe first frame under the session key5members, cards, adsone gossip stream, no registry6pullSpace every 1000 msdigests out, entries back; watch() renders
A browser joining. A page needs the seed URL and the invite code. It mints its own key, dials the speaker over wss from an origin the listener allows, and proves itself by sending its first frame under the session key. From then on it is a member that pulls the spaces it watches once a second.
The gallery after joining

Finding each other

The agents find each other through cards on the same gossip stream. The Parliamentarian has the one lookup that matters: it finds the Hansard card by asset name and accepts answers only from that card's issuer.

AGENT CARDS (16, one per bound agent)speakerspeakermr-neverspeakerms-alwaysspeakerthe-coinspeakersenator-porkspeakerthe-fencespeakerclerkspeakerthe-contrarianfloorthe-firebrandfloorthe-technocratfloorthe-oratorfloorthe-crusaderfloorthe-flip-flopperfloorclerkfloorparliamentarianfloorcitizenresident tabASSET CARDS (3, one per served asset, published by the Archive cell)do/Hansardclassdo/Hansard/hansardobjectkv/PRECEDENTStableworkers://archive/do/Hansard and workers://archive/kv/PRECEDENTSParliamentarianreads the asset cardsgallery pagereads spaces, no cardsfind the Hansard card by asset name,then accept answers only fromthat card's issuer:DataQueryClient(data, name, Set.of(hansard.issuer()))the cards are hints; the entriesin data are what carry the work
Cards. Sixteen agent cards come from the binder and three asset cards from the Archive cell. The Parliamentarian looks up the Hansard card by asset name and trusts only its issuer; the pages never read a card, since a page that watches four spaces needs none.

What to watch for

  • Seeds travel as one scalar. A list bound from a higher-priority source replaces the YAML's list wholesale, so properties() passes the Floor's two seeds as one comma-separated council.seeds value that the YAML expands.
  • The Floor dials the Node clerk too. The direct link lets the Floor's claims reach the leader in stamp order, which avoids a race the README describes (chapter 8).
  • The certificate. The wss listener presents the speaker's identity-endorsed certificate. Headless Chromium starts with --ignore-certificate-errors, and a deployed gallery would use a certificate from a certificate authority. Your own browser asks you once.
  • One peer per page. A page that reloads is a new peer with a new key, which is why the Citizen's worker keeps its identity in IndexedDB (chapter 11).
aspace://guide/browser-council/spaces · chapter 4

The spaces and the shape of data

The group has seven spaces, all listed in application.yml and all LEASE_RACE with the starter's 200 ms settle window. The decisions space also has the ordered log registered over it, so its takes go through the log. Every record in the table is a typed, signed entry with a lease, and each peer holds a replica of all seven spaces.

THE MOTION'S PATH: four spaces, left to rightmotionsMotionLEASE_RACE · 12hvotesProposalBallotDecisionLEASE_RACE · 12h ballotsdecisionsVerdictLEASE_RACE + log · 24hminutesMinuteArchiveReceiptLEASE_RACE · 24h@Propose@OnDecision@OrderedTakeTHE SIDE SPACESmodel-requestsModelRequestModelResponsechunksLEASE_RACE · server lease 2mfloorFloorSpeechLEASE_RACE · 12hdataDataQueryDataResultAssetInvocationAssetInvocationResultLEASE_RACE · taken by the connector@SpaceNotifyspeechespersona promptsthe Speaker and every senator write a FloorSpeech as they vote; the gallery shows them
Seven spaces. Every space is a plain LEASE_RACE space with the 200 ms settle window; the decisions space takes through the ordered log. A motion moves right through four of them, one annotation per hop, while the speeches, the model prompts and the Archive calls use the three beneath.
Space Records and leases Written by Read by
motionsMotion, 12 hthe launcher, through the speaker's peerSpeaker.open, the gallery
votesProposal, Ballot (12 h), Decisionthe Speaker, every senatorthe vote capability, Speaker.gavel, the Contrarian
floorFloorSpeech, 12 hthe Speaker, every senator, the Citizenthe gallery, the resident page
decisionsVerdict, 24 hSpeaker.gavelthe clerks, through the log; the gallery
minutesMinute, ArchiveReceipt, 24 hthe clerks, the Parliamentarianthe Parliamentarian, the gallery
dataDataQuery, DataResult, AssetInvocation, AssetInvocationResultthe Parliamentarian, the Archivethe Archive, the Parliamentarian
model-requestsModelRequest, ModelResponse, chunks, server lease 2 mthe Floor's FleetChatModel, the speaker's ModelServerthe same two
ONE ENTRY IN THE SPACE minutesMinutemotionIdtitlewinnertallyclerkcommitIndex: longspace strategyLEASE_RACElease24hsigned bythe clerk that took the verdict
An entry. Every shared fact in an AgentSpaces app is a typed record in a space. The space's strategy says how a take is decided, the lease says how long the entry lives, tags make it findable, and the signature says which agent wrote it and lets any member check that.

A record has one definition in Java and one in TypeScript, and both name the same schema on the wire. The pages declare each record with an @entry decorator carrying the Java schema name, ai.badmonkey.agentspaces.examples.council.Council$Minute#v1 for this one, so a page and a Java peer encode the record to the same canonical CBOR bytes.

One record, two languages
/** One clerk's minute of a verdict, taken through the ordered log exactly once. */
public record Minute(String motionId, String title, String winner, String tally, String clerk, long commitIndex) {
}
aspace://guide/browser-council/motion · chapter 5

One motion, end to end

A motion takes nine steps from the Speaker's proposal to the gallery's scoreboard, and every step is a record in a space.

ONE MOTION, m01: THE RECORD EACH STEP WRITES AND WHEREgalleryvisitor pagespeakerSpring Bootsenators11 votersclerksthe ordered logParliamentarianfloor peerArchiveworkerd1Proposal@Propose, motion:m01 in votes211 Ballotseach with a FloorSpeech3Verdict@OnDecision, the gavel, into decisions4Minute@OrderedTake, one clerk5DataQuerykv/PRECEDENTS, precedent/pizza6recordDecisioninvocation id hansard:m017resultthe Hansard sequence numberArchiveReceipt8into minutes9pullthe gallery pulls motions, floor, decisions and minutes from its seed
One motion. A motion takes nine steps. The speaker opens a vote, eleven senators answer, the speaker's @OnDecision writes the verdict, one clerk minutes it through the ordered log, and the Parliamentarian records it in the Hansard. The gallery pulls the spaces and draws each record as it arrives.
  • 1. The proposal. The launcher writes a Motion to motions. @Propose on Speaker.open opens a Proposal with the id motion:m01, the options aye and nay, a quorum of eleven and a 12 h lease. The Speaker speaks first.
  • 2. The ballots. Every senator's @Ballot fires on the proposal, writes a FloorSpeech and returns its option. The personas call the model first (chapter 7); the Citizen does the same in its worker.
  • 3. The gavel. When eleven distinct ballots exist, @OnDecision on Speaker.gavel returns a Verdict, which lands in decisions with a 24 h lease.
  • 4. The minute. The clerks' @OrderedTake takes the verdict through the ordered log (chapter 8) and returns a Minute into minutes.
  • 5 to 7. The Hansard. The Parliamentarian's @SpaceNotify fires on each Minute. It waits up to 20 s for the Hansard card, reads the precedent for the motion's topic, and calls recordDecision under the invocation id hansard:<motionId> (chapter 9).
  • 8 and 9. The receipt and the board. The ArchiveReceipt goes into minutes, and the gallery, which pulls the spaces once a second, draws the verdict, the minute and the receipt as they arrive.
The steps in code
@Propose(space = Council.MOTIONS, vote = Council.VOTES, prefix = Council.PREFIX, key = "motionId",
        options = {Council.AYE, Council.NAY}, quorum = Council.QUORUM, lease = "12h", subscriptionLease = "12h")
public String open(Motion motion) {
    floor.write(new FloorSpeech(motion.motionId(), "The Speaker",
            "The committee will come to order. The question is: " + motion.title() + ".", ""),
            Lease.of(Duration.ofHours(12)));
    return motion.title() + ". " + motion.text();
}

What to watch for

  • Each step writes the record the next reacts to. No class calls another. The Speaker never learns who minuted a decision, and the Parliamentarian never learns who gavelled it.
  • The topic is a keyword. Council.topicOf picks the first keyword from a list of twelve that the title contains, and the Archive's KV table holds a precedent for each, plus a general one.
  • One slot per senator and line. The gallery keys a floor line by the senator and the text, so the Speaker's opening line and its gavel line, two entries by one senator, both show on the card. It orders a senator's lines by the time their entries expire, which follows the order they were written because both carry a 12 h lease.
  • The gallery reads decisions and minutes together. The clerks take the verdict away, so the gallery keeps the gavel line on the board and fills it in from the minute if it missed the verdict.
aspace://guide/browser-council/quorum · chapter 6

The eleven-voter quorum

The vote capability is on (agentspaces.capabilities.vote: true, votes-space: votes). Eleven ballots close a motion, and each senator counts once. Two settings make that so. Under agentspaces.identity.agent-keys: subordinate every bound agent signs with a peer-certified key of its own, which makes its ballot AGENT_ATTESTED. A vote grant that names an agent, here the speaker peer's /speaker agent, switches the space to AGENT granularity, so each attested agent counts once. The developer guide's vote capability chapter describes both rules.

THE ELECTORATE: AGENT GRANULARITY ON THE votes SPACEgrants.vote, written by CouncilFleet.properties:speaker peer idadmits the peerfloor peer idadmits the peercitizen peer idadmits the browserspeaker peer id/speakernames an agenta grant that names an agent switches the space to AGENT granularity: each AGENT_ATTESTED ballot counts once, per senatorSPEAKER PEERmr-neverballotms-alwaysballotthe-coinballotsenator-porkballotthe-fenceabstains, no ballotFLOOR PEERthe-contrarianballotthe-firebrandballotthe-technocratballotthe-oratorballotthe-crusaderballotthe-flip-flopperballotRESIDENT TABcitizenballot4 ballots6 ballots1 ballot4 + 6 + 1 = 11, and Council.QUORUM is 11: no quorum until the browser votes
Who counts. Naming one agent in the vote grant moves the whole space to per-agent counting. Ten senators on the two JVM peers and the Citizen in a browser tab each write a ballot signed by their own key; the quorum constant adds them and the motion stays open until the last one arrives.

The constants add up in Council. Ten Java senators cast a ballot, the Citizen casts one more, and the quorum is their sum. The committee therefore has no quorum without the browser. With COUNCIL_HEADLESS_CITIZEN=false the demo prints that it is one vote short and waits for your tab.

Where the number comes from
/**
 * The Java senators who cast a ballot: the four scripted senators on the Speaker's peer who
 * vote (The Fence abstains), The Contrarian on the Floor peer, and the five LLM personas on the
 * Floor peer. {@link Senators#SCRIPTED} and {@link Personas#PERSONAS} are the rosters; the
 * fleet test checks this constant against them.
 */
public static final int JAVA_VOTERS = 10;

/** The Citizen's seat: one browser senator, voting from a resident tab. */
public static final int CITIZEN_SEATS = 1;

/** Distinct voters that close a motion: every Java voter and the Citizen. */
public static final int QUORUM = JAVA_VOTERS + CITIZEN_SEATS;

What to watch for

  • The grant names the Citizen before the tab exists. A grant list admits only the peers and agents it names, so the launcher mints the Citizen's identity in a keystore, names it in grants.vote and serves the key as /citizen-key.json. The resident worker seeds its IndexedDB key store from that file before the host starts. This is demo-only wiring: the file holds the Citizen's private key, and the key travels in the worker's URL. The launcher answers /citizen-key.json only to a request that comes from a loopback address and names a loopback host, and it answers every other request with 403. A deployment would take the identity from the tab and the grant from the operator.
  • The Speaker's grant entry switches the count. The entry <speaker peer>/speaker exists to put the space at agent granularity, and the Speaker agent never votes.
  • Eleven distinct voters per motion. The test counts distinct issuer().encoded() values among the ballots of every motion and asserts that each is eleven, and that the Citizen's peer issued ten signed ballots.
aspace://guide/browser-council/personas · chapter 7

The persona flow

Five senators are persona prompts over the fleet's model. They sit on the Floor peer, which holds no key. FleetChatModel writes each prompt to model-requests, and the speaker's peer, which holds the one ModelServer and the one key, answers it. The Spring AI chapter of the developer guide describes the model wire.

floor PEER, NO API KEYTHE FLEETspeaker PEER, THE KEY HOLDERPersona senator@Ballot, one model callChatClientpersona prompt + FORMATFleetChatModela ChatModel backed by the fleetparse the answerSPEECH: line, VOTE: lineFloorSpeech + Ballotthe sentence to floor, the vote returnedmodel-requestsModelRequestModelResponsechunks, usageLEASE_RACE · server lease 2mwriteanswerModelServertakes ModelRequest, grants.model-servetakeFixtureno keyClaude Haikukey setthe same ChatModel bean slot:claude-haiku-4-5-20251001profile haiku-live when ANTHROPIC_API_KEY is seta failed round trip is caught:the whip votes by proxy and says so,so the quorum never waits.firebrand aye, technocrat nay, orator aye,crusader nay, flip-flopper aye
A persona's vote. The Floor peer holds no key. Each persona turns the motion into a prompt, FleetChatModel writes it to model-requests, and the speaker's ModelServer takes it and answers from whichever ChatModel the profile selects: a deterministic fixture when no key is set, Claude Haiku when one is.

The prompt asks for two lines, a SPEECH: sentence and a VOTE: option. The sentence goes to the floor and the vote is the senator's signed ballot. With no key set, a Personas.Fixture bean answers in character, deterministically from the persona and the motion, so the request space, the server and the response run in every test and demo. With ANTHROPIC_API_KEY set, the haiku-live profile brings the Anthropic auto-configuration instead and the same server calls Claude Haiku.

The persona flow
@Ballot(space = Council.VOTES, prefix = Council.PREFIX, lease = "12h")
public String vote(VoteCapability.Proposal proposal) {
    String motionId = Council.motionIdOf(proposal.proposalId());
    String speech;
    String option;
    try {
        String answer = chat.prompt()
                .system(persona.prompt() + " " + FORMAT)
                .user("The motion before the committee: " + proposal.question())
                .call().content();
        speech = parse(answer, "SPEECH:");
        option = parse(answer, "VOTE:").toLowerCase(Locale.ROOT).contains(Council.NAY) ? Council.NAY : Council.AYE;
    } catch (RuntimeException e) {
        speech = "The senator was called away (" + e.getClass().getSimpleName() + "); the whip votes by proxy.";
        option = persona.proxyVote();
    }
    floor.write(new FloorSpeech(motionId, persona.name(), speech, option), Lease.of(Duration.ofHours(12)));
    return option;
}

What to watch for

  • One key holder. Only the speaker's peer is in grants.model-serve, and the Floor accepts responses only from peers the authorizer permits to serve the model.
  • A failed call still votes. The catch in vote writes a floor line that names the exception, then returns the persona's proxy vote, so the quorum never waits on a lost request.
  • The fixture counts. The test asserts that the fixture answered 50 prompts, 5 personas on 10 motions, which proves every prompt took the whole path through the fleet.
  • Live calls are slower. The demo waits up to 90 s per motion with the fixture and up to 180 s with a live model.
aspace://guide/browser-council/ordered · chapter 8

The ordered log: one minute per decision

The speaker's verdict must become one minute fleet-wide, whichever clerk is alive. The ordered log does that with three voters: the two Java clerks, each an OrderedTakes coordinator over the decisions space, and the Node clerk, which hosts a Raft voter from an ordered-logs block in its YAML. Every member holds the same list of three PeerIds, and the Node host adds its own.

THE CLERKS' DESK: three voters of one log over the decisions spaceclerk, speakerJava voter, @OrderedTakeclerk, Nodethe leader at firstclerk, floorJava voter, @OrderedTake1TakeClaim as a log commandTakeClaim as a log commandboth Java clerks race for every Verdict2append and replicateappend and replicatecommit index ncommit index ncommit index n3the first valid claim of the entry's generation wins, the same on all threethe winning holderruns Clerk.minute(verdict)4Minute, commitIndex n, into minutesthe other claimcommitted, takes nothing
Exactly one minute. Each Java clerk's @OrderedTake submits a signed claim as a command of the Raft log. The leader orders them, every voter applies the same first claim, and only its holder runs the method. The Node clerk votes and replicates but binds no agent, so it never minutes.

A taker submits its signed claim as a command of the log. The commit order arbitrates identically on every member: the first valid claim of an entry's generation wins, and a duplicate or stale claim is committed and ignored. The price is liveness. A partitioned minority cannot take at all, which is the trade the strategy sells. Each Java clerk runs @OrderedTake on the same verdict, so each log carries both claims and the winner's method runs once. The minute records the commitIndex at which it ran.

Seating the desk
/** The clerk: minutes each verdict once. */
@AgentSpec(name = CLERK, description = "Minutes each decision of the committee exactly once",
        goals = {"keep the minutes"})
public static final class Clerk {
    private final String name;
    private final OrderedTakes desk;

    public Clerk(String name, OrderedTakes desk) {
        this.name = Objects.requireNonNull(name, "name");
        this.desk = Objects.requireNonNull(desk, "desk");
    }

    @OrderedTake(space = Council.DECISIONS, lease = "30s", pollTimeout = "1s",
            resultSpace = Council.MINUTES, resultLease = "24h")
    public Minute minute(Verdict verdict) {
        return new Minute(verdict.motionId(), verdict.title(), verdict.winner(), verdict.tally(), name,
                desk.raft().commitIndex());
    }
}

The seating arranges who leads first. A member seated with Clerks.slowSeed draws the longest first election timeout the log allows (5 + nextInt(5) ticks), so the Node clerk, already canvassing, normally wins. It does not always win: the Floor clerk sometimes does, since the two race on their timers. The test kills whichever leads.

The kill
String killed;
if (leading.get().equals(nodeClerk)) {
    clerk.process.destroyForcibly();
    assertThat(clerk.process.waitFor(15, TimeUnit.SECONDS)).isTrue();
    killed = "the Node clerk";
} else {
    fleet.restart(CouncilFleet.FLOOR, nodeClerk, origins, false);
    assertThat(await(() -> fleet.group(CouncilFleet.SPEAKER).runtime().membership().member(keys.floor().peerId()),
            Duration.ofSeconds(60))).as("the Floor peer rejoined").isPresent();
    killed = "the Floor clerk, restarted";
}
Optional<PeerId> successor = await(() -> fleet.leader().filter(id -> !id.equals(leading.get())
        || killed.startsWith("the Floor")), Duration.ofSeconds(90));

What to watch for

  • Two claims, one minute. The test does not assert that only one claim exists. It asserts that both Java seats agree on the first committed claim of every verdict, and that each peer sees one Minute and one ArchiveReceipt per motion.
  • Restarting the Floor. When the Floor leads, Fleet.restart closes its context and starts a new one on the same keystore and durable FileLogStore, seats the senators and the clerk again, and the voter rejoins at its term with its entries.
  • A claim lost with the leader. The 0.4.0 build saw a claim submitted in the instant before the leader died reach the Speaker's seat by the leader's rumor while its command never committed, once in eighteen runs. The test tolerates one such verdict at that seat and checks the exactly-once outcomes for it. Sixteen runs on 0.5.0 did not show it: in the eleven that printed what each seat committed, both seats held a first claim for all ten verdicts. The Node clerk led and was killed in every one of those runs and the race is narrow, so the runs neither confirm the fix nor rule the symptom out, and the tolerance stays.
  • A take that lapses. In five of the sixteen runs, one or two verdicts took about 31 to 33 s to be minuted. The log shows the epoch-1 take with no minute, then claims at epoch 2 after the 30 s clerk lease lapsed, and one of them minuted. One minute and one receipt per motion held every time. The cause is not known.
  • The Node voter at 0.5.0. The README of the first build recorded a core gap, a rejected claim that could still win by gossip through OrderedLogHost. The 0.5.0 host announces such a claim to the committed-order listeners and installs nothing, as Java does. The Floor's direct link to the Node clerk stays in place.
aspace://guide/browser-council/archive · chapter 9

The Archive: a Durable Object and a retry

The Archive is a connector cell: one Durable Object, Fleet, that carries a peer and publishes two assets to the fleet as asset cards. The Hansard Durable Object keeps the roll of decisions in its own SQLite, with one read (getRoll) and one operation (recordDecision) wrapped in once. The PRECEDENTS KV table holds a precedent per topic. Under workerd, tools/run-archive.mjs supplies a KV service that speaks workerd's namespace protocol; on Cloudflare the same bundle uses a real namespace. The developer guide's asset operations section describes connector cells.

THE ARCHIVE ON WORKERD: one bundleWorker fetch()/wake /status /runs /roll /precedentFleet (connector cell)AgentSpacesConnectorCell with a manifestHansard DOrecordDecision, getRollPRECEDENTSKV, 13 topics, getSQLite holds the roll and a run counter;the KV binding is a local service under workerdTHE JAVA FLEETParliamentarianfloor peer, DataQueryClient and AssetInvocations.retrydata spaceDataQuery and DataResult, AssetInvocation and Resultspeaker, ws 7712the listener the cell dialsreads and callsentriesdials out, wsthe cell dials out and nothing dials the cell,so a Durable Object needs no inbound portthe manifest is the whole allowlist:one read, one invoke operation,the prefix precedent/three AssetCards go out:do/Hansard, do/Hansard/hansard,kv/PRECEDENTSthe same bundle and wrangler.jsondeploy to Cloudflare; run-archive.mjsruns the bundle on workerd
The Archive cell. A connector cell is a Durable Object that carries a peer. It dials the speaker's ws listener, publishes the Hansard and the precedents table as asset cards, and serves queries and invocations that arrive as entries in the data space.
The Archive Worker
/** The roll of decisions; every operation body runs once per invocation id. */
export class Hansard extends DurableObject<Env> {
  private runs = 0;

  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);
    ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS roll (seq INTEGER PRIMARY KEY AUTOINCREMENT, motionId TEXT UNIQUE NOT NULL,"
      + " title TEXT NOT NULL, winner TEXT NOT NULL, tally TEXT NOT NULL, precedent TEXT NOT NULL, recordedAt TEXT NOT NULL)");
    ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS counters (name TEXT PRIMARY KEY, n INTEGER NOT NULL)");
  }

  /** The read operation: the roll in sequence order. */
  async getRoll(_params: Record<string, string> = {}): Promise<Record<string, string>[]> {
    return this.ctx.storage.sql.exec<{ seq: number; motionId: string; title: string; winner: string; tally: string; precedent: string }>(
      "SELECT seq, motionId, title, winner, tally, precedent FROM roll ORDER BY seq").toArray()
      .map((row) => ({ seq: String(row.seq), motionId: row.motionId, title: row.title, winner: row.winner, tally: row.tally,
        precedent: row.precedent }));
  }

  /** The operation under a forced retry: the body runs once per invocation id. */
  async recordDecision(params: { motionId: string; title: string; winner: string; tally: string; precedent?: string },
                       invocationId: string): Promise<Record<string, string>> {
    return once(this.ctx.storage, invocationId, () => this.record(params));
  }

The Java side uses two standard clients. DataQueryClient reads kv/PRECEDENTS with op: get and key: precedent/<topic>, and accepts answers only from the Hansard card's issuer. AssetInvocations.retry writes the AssetInvocation for recordDecision under the invocation id hansard:<motionId>. The id is the same on every attempt, which is what makes a second write a retry.

A FORCED RETRY ON m10: one invocation id, one runParliamentarianfloor peerdata spacereplicatedFleet cellconnectorHansardDurable Object1AssetInvocationid hansard:m10, retry window 30 s2the test's watcher writes thesame invocation, same id3take with a leasethe connector runs the operation4recordDecisionparams and the invocationIdonce(storage, id, fn)the body runs one time56seqthe same answer on a repeat7AssetInvocationResultone per id; completes the take8resultonly from the card's issuer
One run per invocation id. The Parliamentarian's call and the test's forced second write carry the same invocation id. The connector takes an invocation under a lease and runs it; the Durable Object's once() runs the body one time, and a repeat under the same id gets the remembered answer, so the Hansard has one row per decision.

On the last motion the test forces the retry. The moment it sees the Parliamentarian's invocation, it writes the same invocation again and asserts that the retry's answer equals the receipt, that one result exists per invocation id, and that the Archive's done event reports durable and recorded both equal ten, the size of the slate.

The forced retry
CompletableFuture<AssetInvocationResult> forced = new CompletableFuture<>();
AtomicReference<Subscription> watching = new AtomicReference<>();
java.util.concurrent.atomic.AtomicBoolean fired = new java.util.concurrent.atomic.AtomicBoolean();
watching.set(data.notify(Template.of(AssetInvocation.class)
        .where("invocationId", eq(Parliamentarian.invocationIdOf(lastId))), event -> {
    // Once, on the Parliamentarian's own invocation (the retry below is a write of the same id too).
    if (event.kind() == SpaceEvent.Kind.WRITTEN && event.issuer().peer().equals(keys.floor().peerId())
            && fired.compareAndSet(false, true)) {
        AssetInvocation seen = event.entry();
        AssetInvocations.retry(data, hansard.get(), new AssetInvocation(seen.v(), seen.asset(), seen.operation(),
                seen.params(), seen.invocationId()), Duration.ofSeconds(30)).whenComplete((result, error) -> {
            if (error != null) {
                forced.completeExceptionally(error);
            } else {
                forced.complete(result);
            }
        });
    }
}, Lease.of(Duration.ofMinutes(10))));

What to watch for

  • The cell dials out. It holds one outbound connection to the speaker's ws listener and carries every query and invocation as an entry in data, so the deployment needs no inbound port. It joins by group id: in the test and the demo the launcher passes fleet.groupId() as AGENTSPACES_GROUP, and wrangler.json carries the same value, z9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW, the multibase SHA-256 of the founding text (chapter 3). The KV namespace id and the seed URL in that file are the placeholders to replace before wrangler deploy.
  • Three cards. The class card do/Hansard, the instance card do/Hansard/hansard and the table card kv/PRECEDENTS. The manifest is the whole allowlist: one read, one invoke operation, the precedent/ prefix.
  • No Archive, no failure. If no Hansard card arrives within council.archive-wait-seconds (20 by default), the Parliamentarian writes a receipt that says "no Archive present" and the committee carries on.
  • celld. The bundle uses only the APIs that appendix D of the SRAD lists celld as supporting. No celld binary runs in this workspace, so workerd is the run.
aspace://guide/browser-council/caucus · chapter 10

The caucus over WebRTC

The caucus shows the browser-to-browser path. Two pages, a dialer and an acceptor, join through the speaker as any page does. The acceptor installs a WebRtcBinding, which advertises a webrtc endpoint in its ad. The dialer finds a member with such an endpoint and calls binding.connect. The offer, the answer and the candidates cross the speaker's relay as signals, and the data channel (aspace/1) then runs directly between the pages.

THE CAUCUS: two pages, one relay, one direct channelcaucus dialerpage, role=dialerspeakerthe RELAY seedcaucus acceptorpage, role=acceptor1join over wss, advertise a webrtc endpointjoin over wss2the dialer finds a member whose ad lists transport webrtc3offeroffer, relayed4answeranswer, relayed5ICE candidatesICE candidates6aspace/1 data channel, direct: 25 whip notes out, 25 echoes backthe speaker's relay counters for the two pages stay within the quiet window's backgroundiceServers: none in the demo and the test (host candidates); the Compose gallery's config.json lists its coturn
The caucus. The pages find each other through the speaker, which carries the offer, the answer and the candidates as relayed signals. Once the data channel opens, the whip notes travel between the two browsers and the relay sees none of them. Each page gathers its candidates through the STUN and TURN servers it is given, from page parameters or from /config.json, and through none in the demo and the test.
The two roles
if (role === "acceptor") {
  while (inbound === null && Date.now() < deadline) {
    await sleep(100);
  }
  if (inbound === null) {
    window.caucus.reason = "no inbound channel";
    return;
  }
  const channel = inbound as FrameChannel;
  channel.onFrame((frame) => {
    const note = decoder.decode(frame);
    window.caucus.received.push(note);
    channel.send(encoder.encode("received: " + note));
    window.caucus.sent += 1;
    text("notes", String(window.caucus.received.length) + " whip notes received");
  });
  window.caucus.open = true;
  window.caucus.ok = true;
  text("status", "caucus open: direct channel from the other citizen");
  return;
}

Each page gathers its ICE candidates through the servers it is given. The iceServers function reads them from the page parameters stun and turn (with turnUser and turnCredential), or else from the iceServers member of /config.json, and the page passes the list to WebRtcBinding.install. With neither, which is the demo and the test, the list is empty and the pages use host candidates only. The Compose gallery serves a config.json that lists its coturn container, so Compose pages use it without a parameter.

The ICE servers
/**
 * The STUN and TURN servers of this page. Page parameters win: `stun=stun:host:3478` (repeatable) and
 * `turn=turn:host:3478` (repeatable) with `turnUser` and `turnCredential` for the TURN servers. Otherwise the
 * `iceServers` of /config.json, in the shape of an RTCIceServer, which the Compose gallery serves for its coturn
 * container. With neither, the list is empty and the pages connect by host candidates, as in the in-process demo.
 */
function iceServers(params: URLSearchParams, configured: IceServer[] | undefined): IceServer[] {
  const servers: IceServer[] = params.getAll("stun").map((urls) => ({ urls }));
  const turn = params.getAll("turn");
  if (turn.length > 0) {
    servers.push({ urls: turn, username: params.get("turnUser") ?? "", credential: params.get("turnCredential") ?? "" });
  }
  return servers.length > 0 ? servers : configured ?? [];
}

The test measures the claim directly. The speaker's PeerNode.relayStats counts frames forwarded per target. After the signalling, a quiet three-second window sets the background rate, and then the dialer sends 25 notes and the acceptor echoes 25. The assertion is that the burst adds at most five relayed frames, against the fifty a relayed exchange would need. In the recorded run, 16 frames crossed during the signalling, 3 during the quiet window, and 0 during the 105 ms of the burst.

The relay assertion
long signalled = relayed(speaker.relayStats(groupId), dialer) + relayed(speaker.relayStats(groupId), acceptor);
assertThat(signalled).as("the offer, answer, and candidates were relayed: " + speaker.relayStats(groupId)).isPositive();
Duration window = Duration.ofSeconds(3);
long quietStart = relayed(speaker.relayStats(groupId), dialer) + relayed(speaker.relayStats(groupId), acceptor);
Thread.sleep(window.toMillis());
long quiet = relayed(speaker.relayStats(groupId), dialer) + relayed(speaker.relayStats(groupId), acceptor) - quietStart;
long burstStart = relayed(speaker.relayStats(groupId), dialer) + relayed(speaker.relayStats(groupId), acceptor);
long tBurst = System.nanoTime();
browsers.send("notes 25");
JsonNode notes = json(browsers.await(line -> line.contains("\"event\":\"notes\""), Duration.ofSeconds(60)));
assertThat(notes.path("echoed").asInt()).as(notes.toString()).isEqualTo(25);
long burstMillis = ms(tBurst);
long burst = relayed(speaker.relayStats(groupId), dialer) + relayed(speaker.relayStats(groupId), acceptor) - burstStart;
assertThat(burst).as("the fifty note frames did not cross the relay (" + burst + " relayed frames in the " + burstMillis
        + " ms the burst took; " + quiet + " background frames in a quiet " + window.toSeconds() + " s window)")
        .isLessThan(50).isLessThanOrEqualTo(5);

What to watch for

  • The Floor's traffic crosses the relay too. The Floor peer has no direct link to the pages, so its membership gossip to them goes through the speaker, one hop. The counters are per target, so the test isolates the pages' own traffic by comparing a quiet window with the burst window. A per-source view would let a test assert on the pair directly.
  • TURN. The Compose recipe starts coturn as a STUN and TURN server and lists it in the gallery's config.json, which the caucus page reads. For the in-process demo, add ?stun=stun:host:3478 or ?turn=turn:host:3478&turnUser=name&turnCredential=secret to a caucus address. The page lists the servers it uses on its own status lines. The demo and the test pass none and need none, since the two pages share a machine.
  • Two tabs make a caucus. The caucus needs two pages open at once: /caucus.html?role=acceptor in one tab and ?role=dialer in another.
aspace://guide/browser-council/residency · chapter 11

Residency: what each host may carry

A host's residency is the kind of host it is, and it decides which duties the client lets the host bind. The JavaScript section of the developer guide and the browser chapter of the TypeScript guide describe the four kinds. The council has one of each, and each does the work that its kind can carry.

WHAT A HOST MAY CARRY: Residency and Duty in agentspaces-typescript/src/platform.tsvisitorgallery, caucus pagesresidentthe Citizen's workercellthe Archive, Fleet DOservicethe Node clerkvotera Raft voter of an ordered logrefusedrefusedrefusedcarriescoordinatorthe ordered-log coordinatorrefusedrefusedrefusedcarrieskeeperLEASED and ORDERED joins, @spaceReducerefusedcarriescarriescarrieslistenertcp and ws listenersrefusedrefusedrefusedcarriesrelayrelays frames for othersrefusedrefusedrefusedcarriesconnectorthe connector runtimerefusedrefusedcarriescarriesbinding a verb the host cannot carry fails at bind time, naming the verb, the residency and the package that canthe Citizen's @ballot needs none of these duties; it sits in the resident worker, which keeps the identity and the session while any tab of the origin is open
Residency. A host's residency is the kind of host it is, and it decides which duties the client lets it bind. The council runs one host of each kind: the pages are visitors that only watch, the Citizen's worker is resident and holds a vote, the Archive is a cell that carries the connector, and the Node clerk is a service and the Raft voter.
Residency In the council What it carries here What it may not carry
visitorthe gallery and the two caucus pageswatches four spaces, pulls them once a second, opens a webrtc channelevery duty in the table
residentthe Citizen's workera decorated agent whose @ballot signs with its own keya Raft vote, a coordinator, a listener, a relay, a connector
servicethe Node clerka Raft voter of the decisions log, a tcp listenernothing
cellthe Archive's Fleet objectthe connector runtime, the Hansard and the KV table as assetsa Raft vote, a coordinator, a listener, a relay
Residency in the code
/** Duties a host must hold a residency for (§3.6). */
export type Duty = "voter" | "coordinator" | "keeper" | "listener" | "relay" | "connector";

const REQUIRED: Record<Duty, Residency[]> = {
  voter: ["service"],
  coordinator: ["service"],
  keeper: ["resident", "service", "cell"],
  listener: ["service"],
  relay: ["service"],
  connector: ["service", "cell"],
};

/** The package that supplies a host able to carry a duty, for refusal messages. */
const SUPPLIER: Record<Duty, string> = {
  voter: "@agentspaces/node",
  coordinator: "@agentspaces/node",
  keeper: "@agentspaces/browser, @agentspaces/node, or @agentspaces/workers",
  listener: "@agentspaces/node",
  relay: "@agentspaces/node",
  connector: "@agentspaces/node or @agentspaces/workers",
};

The split follows from what must survive. A page is as reliable as its tab: it may close or freeze at any moment, so it holds no vote of a log and no job. The Citizen's worker is a resident host. It holds a Web Lock per identity per origin, keeps its key and state in IndexedDB, and keeps the session while any tab of the origin is open, so the Citizen casts its ballot from the browser even while the gallery tab is elsewhere. The things that must outlive tabs sit on a Node service and a cell. The developer guide puts it plainly: put anything that must outlive a tab on a Node service or a cell.

What to watch for

  • Bind errors name the fix. Binding a verb the residency cannot host fails at bind time, naming the verb, the residency and the package that supplies a host that can.
  • Bound again on every resume. The resident host closes its bindings on pause, so the worker binds the Citizen again inside host.onResume.
  • The hint is not trusted. A host advertises its residency as the hint js.residency. Peers show it and never rely on it.
aspace://guide/browser-council/dies · chapter 12

When something dies

The table lists seven things that can fail and what the committee does about each. The fleet test runs the leading clerk, the recording in flight and the caucus's candidates; the code and the demo handle the others.

THE RECORDED SESSION, in seconds from the Fleet's startupfirst five motionssecond five motions, forced retry on m10desk formed 2.0 sall up 6.7 sNode clerk killed26.2 sa new leader 1.7 s later27.9 s42.3 sfleet, pages, Archive up,the caucus relay quietfive motions, each minutedonce and recorded oncethe survivors elect;the Raft log is durablefive more through the new leader,the Hansard once per decision10 motions, 11 voters; the whole test took 43.4 s, and a motion took 2.3 to 4.8 s from tabling to its Hansard receipt
A session on a clock. The recorded session at 0.5.0: the fleet and the pages come up, five motions go through, the leading clerk dies, the survivors elect a leader, and the second half of the slate runs through the new leader.
What fails What the committee does Where it shows
The leading clerk (the Node process, or the Floor peer)The survivors elect a leader, and a Floor clerk that led restarts on its durable log. The second half of the slate runs through the new leader.the kill block of the test, chapter 8
A model round tripThe persona votes by proxy and says so. The quorum never waits.the vote method of Personas.Senator, chapter 7
A recording in flightA second write under the same invocation id gets the remembered answer, and the Hansard holds one row.the forced retry, chapter 9
The Archive is absentThe receipt says "no Archive present" after the card wait. The committee carries on.the archive method of the Parliamentarian, chapter 9
The caucus pages cannot resolve their own candidatesChromium hides local addresses behind mDNS names. A machine that cannot resolve them leaves the two pages connected to the relay and never to each other, and the test waits 150 s for the caucus event. The driver launches Chromium with --disable-features=WebRtcHideLocalIpsWithMdns, so the pages exchange real addresses.the launch arguments of the driver, chapter 13
The Citizen's tab is closedThe committee has no quorum and waits. The motion stays open until the Citizen returns.the demo with COUNCIL_HEADLESS_CITIZEN set to false
The speakerThe browsers and the Archive lose their seed. The speaker is the one peer the test never kills.the README's notes

In the recorded run the Node clerk led, the test killed its process, and a Java clerk led 1.7 s later. The whole session, from the fleet's start to the last Hansard receipt, took 42.3 s.

aspace://guide/browser-council/running · chapter 13

Running, Compose and testing

The app needs JDK 21, Maven, Node 22 or later, and the built TypeScript workspace two directories up: agentspaces-typescript with npm run build and npm run build:packages done, and its node_modules holding esbuild, Playwright with Chromium and workerd. tools/paths.mjs resolves the @agentspaces/* packages and the tools from that workspace, so the example's own npm install is optional.

cd agentspaces-example-apps/browser-council
mvn -q -o compile exec:java

The launcher builds the pages with node tools/build.mjs, starts the two Java peers, the Node clerk, the Archive when workerd is installed and a headless Citizen, prints the gallery URL (http://127.0.0.1:8787/), and tables the motions one by one. Open the gallery to watch, /resident.html to see the Citizen's seat, and /caucus.html?role=acceptor and ?role=dialer in two tabs for the caucus; add stun= or turn= parameters to gather candidates through a STUN or TURN server. Set ANTHROPIC_API_KEY and run the same command to hear the personas in Claude Haiku's voice.

The gallery shows one card per motion: the title, a state line (carried or defeated with the tally, the clerk that minuted it, the Hansard number and the precedent), and then one floor line per speaker with its vote. The demo's own output, recorded on 2026-11-04, follows. The winning clerk and the tallies vary from run to run.

The Senate Committee on Keeping It Real: model fixture
  gallery   http://127.0.0.1:8787/
  resident  http://127.0.0.1:8787/resident.html   (the Citizen's seat)
  caucus    http://127.0.0.1:8787/caucus.html?role=acceptor and ?role=dialer
  wss seed  wss://127.0.0.1:7721/aspace   invite keeping-it-real-v1
  the Citizen is seated (headless); set COUNCIL_HEADLESS_CITIZEN=false to take the seat yourself
  tabled   Resolved: pineapple is a pizza topping
  minuted  aye (aye 6, nay 5) by speaker
  archived Hansard #1, precedent: Keeping It Real 1 (2019): a topping is whatever the kitchen was willing to put there.
  tabled   Resolved: every meeting that could have been an email is hereby an email
  minuted  nay (aye 4, nay 7) by floor
  archived Hansard #2, precedent: Keeping It Real 4 (2020): the meeting was, on reflection, an email.
  tabled   Resolved: the committee's coffee shall be strong enough to vote by itself
  minuted  aye (aye 8, nay 3) by speaker
  archived Hansard #3, precedent: Keeping It Real 7 (2021): coffee served in chambers is a matter of procedure.
  tabled   Resolved: Nebraska is the rightful home of the committee's summer retreat
  minuted  aye (aye 6, nay 5) by speaker
  archived Hansard #4, precedent: Keeping It Real 9 (2022): the retreat goes where the corn is tall.
  tabled   Resolved: robots that write floor speeches must disclose it in the speech
  minuted  nay (aye 4, nay 7) by speaker
  archived Hansard #5, precedent: Keeping It Real 11 (2023): a speech must say who, or what, wrote it.
  tabled   Resolved: a cat on the keyboard is a valid point of order
  minuted  aye (aye 6, nay 5) by speaker
  archived Hansard #6, precedent: Keeping It Real 12 (2023): the chair recognised the cat.
  tabled   Resolved: puns in the minutes are hereby permitted, sparingly
  minuted  nay (aye 5, nay 6) by speaker
  archived Hansard #7, precedent: Keeping It Real 13 (2024): one pun per session, intended.
  tabled   Resolved: the committee shall adjourn early on any Friday with good weather
  minuted  nay (aye 5, nay 6) by speaker
  archived Hansard #8, precedent: Keeping It Real 14 (2024): fair weather is a point of order.
  tabled   Resolved: no motion shall be set in Comic Sans
  minuted  nay (aye 3, nay 8) by floor
  archived Hansard #9, precedent: Keeping It Real 0 (2018): the committee keeps it real.
  tabled   Resolved: the snack budget is a matter of national importance
  minuted  aye (aye 6, nay 5) by floor
  archived Hansard #10, precedent: Keeping It Real 16 (2025): the snack line is read into the record in full.
the session is in recess; the gallery stays open at http://127.0.0.1:8787/ (Ctrl-C to adjourn)

The fleet test

mvn -o test -Dcouncil.required=true

CouncilSessionTest holds one test, theCommitteeSitsAcrossBrowsersANodeClerkAndWorkerdAndMinutesEveryDecisionOnce, with a 900 s timeout. Without -Dcouncil.required=true it skips when Node, the built workspace, Playwright or workerd is missing. It picks free ports for everything, so it never touches the portal's 7500 and 8080.

Stage What the test asserts
The deskThe Node clerk joins, the Floor and the speaker seat their clerks, and the log has a leader that is not the speaker.
1: the galleryThe page joins over wss, establishes its session (sessionFramesSent is positive), and ends with a board that carries every decision, minute and Hansard sequence.
3: the ArchiveThe Archive is up on workerd and connected; the Hansard card has the recordDecision operation; the precedents card exists; each receipt names the precedent and the Hansard sequence.
4: the caucusThe data channel opens, the acceptor echoes 25 notes, and the burst adds at most five relayed frames.
2: the sessionFive motions go through the clerks and the Archive; the test kills the leader; the survivors elect; five more motions go through; every peer sees one minute and one receipt per motion; both seats agree on the first committed claim per verdict.
The HansardThe forced retry answers the same record; one result exists per invocation id; durable and recorded both equal 10.
The CitizenThe resident tab cast 10 signed ballots; every motion has 11 distinct voters.
The personasThe fixture answered 50 prompts; every senator and the Speaker spoke on every motion.

The test runs one test method. Five runs in a row on the build machine took 39.9 to 70.9 s, and a run in which one verdict stalls for a 30 s lease (chapter 8) takes about that much longer. The run recorded below took 43.51 s in surefire and 43.4 s inside the test, and the fleet, the pages, the Archive and the caucus were up after 6.7 s.

If the caucus stage times outChromium hides a page's local addresses behind mDNS names by default. On a machine that does not resolve them, two pages in one browser exchange their candidates and never connect, and the fleet test used to fail after waiting 150 s for the caucus event. The build machine for this guide failed that way, and a loopback RTCPeerConnection pair in the same Chromium stayed in ICE state new until the browser launched with --disable-features=WebRtcHideLocalIpsWithMdns, when it opened in 10 ms. The driver now launches its Chromium with that flag beside --ignore-certificate-errors, and the test passes here. A browser you open yourself for the manual caucus keeps the default.

A recorded run

The lines below are the test's own output from 2026-11-04 on AgentSpaces 0.5.0, verbatim, with the worker echoes and Spring log lines removed. Ports, ids and timings vary from run to run, and the winning clerk of a motion can be either Java clerk.

  ports Ports[speakerTcp=50946, speakerWs=50947, speakerWss=50948, floorTcp=50949, clerkTcp=50950, gallery=50951]; speaker z7Fhyiat, floor z6PkQEHe, node clerk zHjNLRAL, citizen zCLMz4XT
  desk formed in 2046 ms; the gavel is with the Node clerk
  stage 1, 3, 4 up in 6728 ms; relay frames for the caucus pages: 16 signalling, then 3 background in a quiet 3 s window and 0 in the 105 ms of 25 notes and 25 echoes
  m01 aye (aye 6, nay 5) by speaker, Hansard #1, precedent: Keeping It Real 1 (2019): a topping is whatever the kitchen was willing to put there. [4159 ms]
  m02 nay (aye 4, nay 7) by speaker, Hansard #2, precedent: Keeping It Real 4 (2020): the meeting was, on reflection, an email. [3069 ms]
  m03 aye (aye 8, nay 3) by speaker, Hansard #3, precedent: Keeping It Real 7 (2021): coffee served in chambers is a matter of procedure. [4767 ms]
  m04 aye (aye 6, nay 5) by speaker, Hansard #4, precedent: Keeping It Real 9 (2022): the retreat goes where the corn is tall. [3701 ms]
  m05 nay (aye 4, nay 7) by speaker, Hansard #5, precedent: Keeping It Real 11 (2023): a speech must say who, or what, wrote it. [3820 ms]
  first half minuted in 19519 ms
  killed the Node clerk (zHjNLRAL); z6PkQEHe leads after 1697 ms
  m06 aye (aye 6, nay 5) by floor, Hansard #6, precedent: Keeping It Real 12 (2023): the chair recognised the cat. [2314 ms]
  m07 nay (aye 5, nay 6) by speaker, Hansard #7, precedent: Keeping It Real 13 (2024): one pun per session, intended. [3214 ms]
  m08 nay (aye 5, nay 6) by speaker, Hansard #8, precedent: Keeping It Real 14 (2024): fair weather is a point of order. [3547 ms]
  m09 nay (aye 3, nay 8) by speaker, Hansard #9, precedent: Keeping It Real 0 (2018): the committee keeps it real. [2463 ms]
  forced retry on m10: AssetInvocationResult[v=1, invocationId=hansard:m10, asset=do/Hansard, operation=recordDecision, ok=true, result={winner=aye, motionId=m10, seq=10}, error=null]; invocations seen: [z7FhyiatnJYkrymq5YYhst3dV6fqA1EX8BuHr6qiAH6Kr/app]; results: [zG7GEw9Z:true]
  second half minuted; the forced retry on m10 answered Hansard #10
  session complete in 35529 ms; whole test 43414 ms
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 43.51 s -- in ai.badmonkey.agentspaces.examples.council.CouncilSessionTest

The Compose recipe

docker compose build && docker compose up from the app directory builds three images and starts a stock fourth. The Java image serves both peers, and the role is the command. The Node image carries the clerk and the Archive, and a gallery stage of the same Dockerfile puts nginx over the pages that the Node image bundled. coturn is the STUN and TURN server of the caucus: the gallery's config.json lists it under iceServers, and caucus.ts passes that list to the WebRTC binding (chapter 10). Nobody has run the recipe, since this workspace has no Docker. The files were checked by reading them against one another and against the in-process launcher, which does what the recipe asks you to do by hand and is why the demo and the test use it.

docker compose up: SIX SERVICES, TWO NAMED VOLUMES (written, not run in this workspace)your browserthe gallery, the resident tab and the caucus pagesgallerynginx:1.27-alpine, the bundled pages8787speakerjava image, command speaker7711 7712 7721coturncoturn/coturn:4.6, STUN and TURN3478 49160-49200 udpfloorjava image, command floor7713clerknode image, agentspaces-node run7714archivenode image, run-archive.mjs8788http 8787wss 7721iceServers 3478tcp 7711tcp 7711ws 7712volume keys: speaker, floor and clerk keystores and logsvolume archive: the SQLite datalilac: one java image; grey: one node image; white: stock or small images
The Compose recipe. Three images run five of the six services: the Java image starts either peer by its command argument, the Node image carries the clerk and the Archive, and a gallery image serves the bundled pages. The browsers reach the gallery and the speaker's wss listener, and the caucus pages reach the STUN and TURN server that the gallery's config.json lists under iceServers; the three other services dial the speaker.

The Node image and the gallery need the TypeScript workspace beside the example, and a build context cannot reach above its own root, so compose.yaml sets their context to the workspace root (context: ../..) and names the Dockerfile by its path from there. The Dockerfile copies agentspaces-typescript, runs npm ci, npm run build and npm run build:packages inside the image, which gives esbuild and workerd the image's own platform, then copies the example and runs node tools/build.mjs. The ignore file next to the Dockerfile sends the context those two directories only, without any node_modules or build directory.

BUILD CONTEXT OF THE NODE IMAGE: the workspace rootdocker/node.Dockerfile: TWO STAGESagentspaces-typescript/sources and lockfile, installed and built in the imageagentspaces-example-apps/browser-council/tools, site, archive, package.jsoncompose.yaml: context ../.., dockerfileagentspaces-example-apps/browser-council/docker/node.Dockerfilenode.Dockerfile.dockerignore keeps out the rest of theworkspace, every node_modules and every build/FROM node:22-bookworm-slim AS nodenpm ci, npm run build, build:packagesworkspacenode tools/build.mjsthe bundlesCOPY --from=node site/FROM nginx:1.27-alpine AS galleryCOPY site/ and gallery.confpages, config.jsonan image per stage, chosen by target: in compose.yamlWHICH SERVICE BUILDS FROM WHATclerk, archivetarget node, context ../..gallerytarget gallery, context ../..speaker, floorjava.Dockerfile, context . (the example)the Java image copies pom.xml, src and docker/run-peer.sh only, so its context needs no ignore file
What the images are built from. The Node image and the gallery need the TypeScript workspace beside the example, so their context is the workspace root and an ignore file narrows it. The Java image builds from the example directory alone. The Node image installs and builds the workspace inside itself, so its native tools match the image's platform.
The Compose files
services:
  speaker:
    build:
      context: .
      dockerfile: docker/java.Dockerfile
    command: ["speaker"]
    environment:
      COUNCIL_ROLE: speaker
      COUNCIL_KEYS: /keys
      COUNCIL_GALLERY_ORIGINS: "http://localhost:8787,http://gallery:8787"
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
    volumes:
      - keys:/keys
    ports:
      - "7711:7711"
      - "7712:7712"
      - "7721:7721"

  floor:
    build:
      context: .
      dockerfile: docker/java.Dockerfile
    command: ["floor"]
    environment:
      COUNCIL_ROLE: floor
      COUNCIL_KEYS: /keys
      COUNCIL_SEED: speaker:7711
    volumes:
      - keys:/keys
    depends_on:
      - speaker
  • Peer ids come first. clerk/clerk.yaml needs the two Java clerks' PeerIds, and the Java peers take them back as COUNCIL_MEMBERS. Print them with agentspaces-node id over the keys volume.
  • The Archive's group id has a default. COUNCIL_GROUP_ID overrides it. Unset, compose.yaml passes z9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW, the id of the founding (chapter 3).
  • The grants. The Java peers take COUNCIL_VOTE_GRANTS (the peer ids that may vote, plus <speaker peer>/speaker for agent granularity) and COUNCIL_MODEL_SERVER (the speaker's peer id) once the ids are known.
  • Two things stay by hand. Only the in-process launcher writes Motion entries into motions and serves the Citizen's key, so a Compose fleet sits at rest until an operator tables a motion and gives the resident page a key whose peer id the vote grant names. Without the Citizen, no motion reaches the quorum of eleven.
aspace://guide/browser-council/next

Where to go next

The developer guide explains each annotation and capability this app uses. The workflow guide explains how the ordered log admits one claim per entry. The TypeScript guide explains the browser host, the Node host, the Workers cells and the ordered log from the TypeScript side.

THE FIVE LAYERS, AND WHAT BROWSER COUNCIL STANDS ONagents and the binderannotated beans on the JVM peers, decorated classes in the browser worker, the connector cell and the Node voterLayer 4 capabilitiesvote, ordered log, aggregate, content, remote actionsbrowser councilvote, ordered log, data query, asset invokeLayer 3 spacesreplicated tuple spaces, leases, strategiesbrowser councilseven spaces, LEASE_RACE, takes through the ordered logLayer 2 discoverycards, advertisements, locatorsbrowser councilagent cards, the Archive's asset cards, ads on the gossip streamLayer 1 peeringmembership, gossip, transportsbrowser counciltcp, ws, wss and webrtc bindings, the RELAY role, SWIM membershipLayer 0 identityEd25519 keys, signed documents, groupsbrowser councilpeer keys, per-agent subordinate keys, an identity-endorsed wss certificate
The layers under the app. Each layer rests on the one below. A highlighted layer is one the app uses directly; the rest still run beneath it and need no configuration here.