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.
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
wssfrom 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.
/** * 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); }
import { joinCouncil } from "./dist/council.js"; const council = await joinCouncil({ seed: "wss://127.0.0.1:7721/aspace", invite: "keeping-it-real-v1" }); council.watch("minutes", Minute, (entry) => console.log(entry.value.title, entry.value.winner));
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.
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).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.
| Seat | Class and annotation | Peer | Votes | Bio and rule |
|---|---|---|---|---|
| The Speaker | Speaker: @Propose, @OnDecision | speaker | no | Turns each Motion into a vote of eleven and writes the Verdict when the quorum is met. |
| Mr Never | Senators.Scripted: @Ballot | speaker | yes | Has voted nay since the committee was founded, on principle and on everything. |
| Ms Always | Senators.Scripted: @Ballot | speaker | yes | Believes every motion deserves a chance, and gives it one. |
| The Coin | Senators.Scripted: @Ballot | speaker | yes | Decides by a seeded coin; insists the coin is wise. |
| Senator Pork | Senators.Scripted: @Ballot | speaker | yes | Votes aye on any motion that mentions Nebraska, and on nothing else. |
| The Fence | Senators.Scripted: @Ballot | speaker | no | Has never come down on either side, and sees no reason to start now. It abstains and writes no ballot. |
| The Contrarian | Senators.Scripted: @Ballot | floor | yes | Votes against whatever is winning; when nothing is winning, against that too. |
| The Firebrand | Personas.Senator: @Ballot | floor | yes | A populist who hears the people in every motion and shouts back. Asks the model; votes aye by proxy if the call fails. |
| The Technocrat | Personas.Senator: @Ballot | floor | yes | A 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 Orator | Personas.Senator: @Ballot | floor | yes | An 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 Crusader | Personas.Senator: @Ballot | floor | yes | A 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-Flopper | Personas.Senator: @Ballot | floor | yes | Poll-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 Citizen | Citizen in resident-worker.ts: @ballot | resident tab | yes | Votes from the gallery: aye when the motion mentions people, snack, cat, weather, pizza, friday, coffee, nebraska, pun, nay on the rest. |
| two clerks | Clerks.Clerk: @OrderedTake | speaker, floor | no | Takes each Verdict through the ordered log and writes the Minute. |
| the Parliamentarian | Parliamentarian: @SpaceNotify | floor | no | Reads the precedent and records each minute in the Hansard. |
| the Node clerk | no agent: agentspaces-node run clerk.yaml | clerk | no | The third voter of the decisions log. |
| the Archive | no agent: a connector cell on a Durable Object | archive | no | Publishes 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.
/** * 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(); } }
public static final List<Rule> SCRIPTED = List.of( new Rule("Mr Never", "mr-never", "Has voted nay since the committee was founded, on principle and on everything.", CouncilFleet.SPEAKER, true, (floor, random) -> Vote.nay("No. Next.")), new Rule("Ms Always", "ms-always", "Believes every motion deserves a chance, and gives it one.", CouncilFleet.SPEAKER, true, (floor, random) -> Vote.aye("I am delighted to support this, as I support all things.")), new Rule("The Coin", "the-coin", "Decides by a seeded coin; insists the coin is wise.", CouncilFleet.SPEAKER, true, (floor, random) -> random.nextBoolean() ? Vote.aye("The coin says aye, and the coin has never been wrong.") : Vote.nay("The coin says nay. Take it up with the coin.")), new Rule("Senator Pork", "senator-pork", "Votes aye on any motion that mentions Nebraska, and on nothing else.", CouncilFleet.SPEAKER, true, (floor, random) -> floor.question().toLowerCase(Locale.ROOT).contains("nebraska") ? Vote.aye("At last, a motion for the good people of Nebraska. Aye, and proudly.") : Vote.nay("I see nothing in this for Nebraska. Nay.")), new Rule("The Fence", "the-fence", "Has never come down on either side, and sees no reason to start now.", CouncilFleet.SPEAKER, false, (floor, random) -> Vote.abstain("I can see merit on both sides, and I shall sit on neither.")), new Rule("The Contrarian", "the-contrarian", "Votes against whatever is winning; when nothing is winning, against that too.", CouncilFleet.FLOOR, true, (floor, random) -> { int aye = floor.ballotsSoFar().getOrDefault(Council.AYE, 0); int nay = floor.ballotsSoFar().getOrDefault(Council.NAY, 0); return aye > nay ? Vote.nay("The ayes are ahead, which is reason enough: nay.") : Vote.aye("The nays have it so far, so I shall not: aye."); }));
/** The Citizen: for the people, for snacks, for cats, and against the rest. */ @agent("citizen", { description: "The Citizen's seat: votes from a resident browser tab" }) class Citizen { cast = 0; @ballot("votes", { prefix: PREFIX, lease: "12h" }) vote(proposal: Proposal): string | null { const motionId = proposal.proposalId.slice(PREFIX.length); const q = proposal.question.toLowerCase(); const aye = ["people", "snack", "cat", "weather", "pizza", "friday", "coffee", "nebraska", "pun"].some((word) => q.includes(word)); const line = aye ? "From the gallery: this is the kind of thing a citizen can get behind." : "From the gallery: with respect, the people did not ask for this."; this.cast += 1; floor?.write(new FloorSpeech(motionId, "The Citizen", line, aye ? "aye" : "nay"), "12h"); return aye ? "aye" : "nay"; } }
What to watch for
- One class, several seats.
Senators.Scriptedtakes aRule. The launcher binds each one withgroup.bind(senator, rule.agentName()), so every seat has its own agent name and, underagent-keys: subordinate, its own signing key. - A null return abstains. The Fence's rule returns
Vote.abstain, the@Ballotmethod returnsnull, and the senator writes no ballot. Its speech still goes to the floor. - The Contrarian reads the ballots so far. It reads the
votesspace, so its choice depends on how many ballots have replicated to the Floor peer when its method runs.
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.
| Runtime | Peer | Listens | Dials | Joins with |
|---|---|---|---|---|
| Spring Boot | speaker | tcp 7711, ws 7712, wss 7721 | nothing: the seed | the founding in application.yml |
| Spring Boot | floor | tcp 7713 | 127.0.0.1:7711 and 127.0.0.1:7714 | the council.seeds property |
| agentspaces-node | clerk | tcp 7714 | 127.0.0.1:7711 | the founding in the generated clerk.yaml |
| workerd | archive | HTTP for the harness, not the group | ws://127.0.0.1:7712/aspace | AGENTSPACES_GROUP, the group id |
| Chromium | gallery, resident tab, two caucus pages | nothing | wss://127.0.0.1:7721/aspace | the 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.
# 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
spring: config: activate: on-profile: speaker agentspaces: roles: [RELAY] # forwards the browsers' RELAY_FRAMEs: the caucus signals, the clerks' Raft pipes springai: model-server: enabled: true models: ["${council.haiku-model}"] lease: 2m --- spring: config: activate: on-profile: haiku-live ai: model: chat: anthropic anthropic: api-key: ${ANTHROPIC_API_KEY} chat: options: model: ${council.haiku-model} max-tokens: 300 --- spring: config: activate: on-profile: floor agentspaces: springai: model-client: enabled: true model: ${council.haiku-model} timeout: 120s
/** * The properties of one peer. * * @param name speaker or floor * @param ports the session's ports * @param keys the session's keys * @param nodeClerk the Node clerk's PeerId * @param origins the browser origins the listeners admit */ public static Map<String, Object> properties(String name, Ports ports, Keys keys, PeerId nodeClerk, List<String> origins) { Map<String, Object> p = new HashMap<>(); p.put("council.peer-name", name); p.put("agentspaces.keystore", keys.root().resolve(name).toString()); // Every senator on the two Java peers and the Citizen's browser may vote; naming the Speaker // by agent puts VOTE at AGENT granularity, so each senator is its own counted voter. List<String> voters = List.of(keys.speaker().peerId().value(), keys.floor().peerId().value(), keys.citizen().peerId().value(), keys.speaker().peerId().value() + "/speaker"); for (int i = 0; i < voters.size(); i++) { p.put("agentspaces.security.grants.vote[" + i + "]", voters.get(i)); } p.put("agentspaces.security.grants.model-serve[0]", keys.speaker().peerId().value()); if (name.equals(SPEAKER)) { p.put("agentspaces.bind", ports.seedTcp()); p.put("agentspaces.transport.ws.enabled", "true"); p.put("agentspaces.transport.ws.bind", "127.0.0.1:" + ports.speakerWs()); p.put("agentspaces.transport.wss.enabled", "true"); p.put("agentspaces.transport.wss.bind", "127.0.0.1:" + ports.speakerWss()); for (int i = 0; i < origins.size(); i++) { p.put("agentspaces.transport.ws.allowed-origins[" + i + "]", origins.get(i)); p.put("agentspaces.transport.wss.allowed-origins[" + i + "]", origins.get(i)); } } else { p.put("agentspaces.bind", "127.0.0.1:" + ports.floorTcp()); // A list bound from a higher-priority source replaces the YAML's list wholesale, so the // seeds travel as one scalar the YAML's seeds entry expands. The Floor dials the Node // clerk as well as the Speaker: a direct link for its claims to the leader and for the // leader's rumors back, so the log's order and the claims' stamps agree (see README). p.put("council.seeds", ports.seedTcp() + ",127.0.0.1:" + ports.clerkTcp()); } return p; }
# The Node clerk: the third voter of the minutes' ordered log, generated per session. agentspaces: keystore: %s bind: 127.0.0.1:%d tick-millis: 250 groups: - name: %s founding: %s seeds: %s spaces: [ motions, floor, votes, decisions, minutes, data, model-requests ] ordered-logs: - { space: decisions, members: [ %s, %s ], log-dir: %s }
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.
visitor = await joinCouncil({ seed, invite }); const status = visitor.status(); text("status", `joined over ${status.scheme} as ${status.peerId.slice(0, 10)}…`); visitor.watch("motions", Motion, (e) => { row(e.value.motionId).motion = e.value; render(); }); visitor.watch("floor", FloorSpeech, (e) => { row(e.value.motionId).speeches.set(lineKey(e.value), { speech: e.value, at: e.expiresAtMillis }); render(); }); visitor.watch("decisions", Verdict, (e, kind) => { if (kind !== "EXPIRED") { row(e.value.motionId).verdict = e.value; // the clerks take the verdict away; the gavel stays on the board render(); } }); visitor.watch("minutes", Minute, (e) => { const r = row(e.value.motionId); r.minute = e.value; if (r.verdict === null) { r.verdict = new Verdict(e.value.motionId, e.value.title, e.value.winner, e.value.tally); } render(); }); visitor.watch("minutes", ArchiveReceipt, (e) => { row(e.value.motionId).receipt = e.value; render(); });
String config = "{\"seed\":\"" + ports.seedWss() + "\",\"invite\":\"" + Council.FOUNDING + "\"}";
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.
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-separatedcouncil.seedsvalue 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
wsslistener 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).
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.
| Space | Records and leases | Written by | Read by |
|---|---|---|---|
motions | Motion, 12 h | the launcher, through the speaker's peer | Speaker.open, the gallery |
votes | Proposal, Ballot (12 h), Decision | the Speaker, every senator | the vote capability, Speaker.gavel, the Contrarian |
floor | FloorSpeech, 12 h | the Speaker, every senator, the Citizen | the gallery, the resident page |
decisions | Verdict, 24 h | Speaker.gavel | the clerks, through the log; the gallery |
minutes | Minute, ArchiveReceipt, 24 h | the clerks, the Parliamentarian | the Parliamentarian, the gallery |
data | DataQuery, DataResult, AssetInvocation, AssetInvocationResult | the Parliamentarian, the Archive | the Archive, the Parliamentarian |
model-requests | ModelRequest, ModelResponse, chunks, server lease 2 m | the Floor's FleetChatModel, the speaker's ModelServer | the same two |
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 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) { }
@entry(PKG + "Minute#v1") export class Minute { constructor(public motionId = "", public title = "", public winner = "", public tally = "", public clerk = "", public commitIndex = 0) {} }
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.
- 1. The proposal. The launcher writes a
Motiontomotions.@ProposeonSpeaker.openopens aProposalwith the idmotion: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
@Ballotfires on the proposal, writes aFloorSpeechand 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,
@OnDecisiononSpeaker.gavelreturns aVerdict, which lands indecisionswith a 24 h lease. - 4. The minute. The clerks'
@OrderedTaketakes the verdict through the ordered log (chapter 8) and returns aMinuteintominutes. - 5 to 7. The Hansard. The Parliamentarian's
@SpaceNotifyfires on eachMinute. It waits up to 20 s for the Hansard card, reads the precedent for the motion's topic, and callsrecordDecisionunder the invocation idhansard:<motionId>(chapter 9). - 8 and 9. The receipt and the board. The
ArchiveReceiptgoes intominutes, and the gallery, which pulls the spaces once a second, draws the verdict, the minute and the receipt as they arrive.
@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(); }
@OnDecision(space = Council.VOTES, prefix = Council.PREFIX, resultSpace = Council.DECISIONS, resultLease = "24h") public Verdict gavel(VoteCapability.Decision decision) { String motionId = Council.motionIdOf(decision.proposalId()); String title = motions.read(Template.of(Motion.class).where("motionId", eq(motionId))) .map(Motion::title).orElse(motionId); Map<String, Integer> ordered = new TreeMap<>(decision.tally()); StringBuilder tally = new StringBuilder(); ordered.forEach((option, count) -> tally.append(tally.isEmpty() ? "" : ", ").append(option).append(' ').append(count)); floor.write(new FloorSpeech(motionId, "The Speaker", "The " + (Council.AYE.equals(decision.winner()) ? "ayes" : "nays") + " have it: " + tally + ".", ""), Lease.of(Duration.ofHours(12))); return new Verdict(motionId, title, decision.winner(), tally.toString()); }
@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(); }
@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()); }
@SpaceNotify(space = Council.MINUTES, resultSpace = Council.MINUTES, resultLease = "24h") public ArchiveReceipt archive(Minute minute) throws Exception { Optional<AssetCard> hansard = Optional.empty(); long deadline = System.nanoTime() + cardWait.toNanos(); while (hansard.isEmpty() && System.nanoTime() < deadline) { hansard = hansardCard(); if (hansard.isEmpty()) { Thread.sleep(200); } } if (hansard.isEmpty()) { return new ArchiveReceipt(minute.motionId(), invocationIdOf(minute.motionId()), "no Archive present", "", name); } String precedent = precedent(hansard.get(), Council.topicOf(minute.title())); LOG.log(System.Logger.Level.INFO, "{0}: recording {1} ({2}) in the Hansard under {3}; precedent: {4}", name, minute.motionId(), minute.winner(), invocationIdOf(minute.motionId()), precedent); Map<String, String> params = new LinkedHashMap<>(); params.put("object", ROLL); params.put("motionId", minute.motionId()); params.put("title", minute.title()); params.put("winner", minute.winner()); params.put("tally", minute.tally()); params.put("precedent", precedent); AssetInvocationResult result = AssetInvocations.retry(data, hansard.get(), new AssetInvocation(AssetInvocations.VERSION, HANSARD, RECORD, params, invocationIdOf(minute.motionId())), Duration.ofSeconds(30)).get(40, TimeUnit.SECONDS); if (!result.ok()) { throw new IllegalStateException("the Archive refused " + RECORD + ": " + result.error() + " " + result.result()); } LOG.log(System.Logger.Level.INFO, "{0}: {1} recorded as Hansard #{2}", name, minute.motionId(), result.result().getOrDefault("seq", "?")); return new ArchiveReceipt(minute.motionId(), result.invocationId(), precedent, result.result().getOrDefault("seq", ""), name); }
for (Motion motion : Council.slate()) { fleet.table(motion); System.out.println(" tabled " + motion.title()); Optional<Minute> minute = await(() -> first(fleet.space(Council.MINUTES), Minute.class, motion.motionId()), Duration.ofSeconds(haikuLive ? 180 : 90)); minute.ifPresent(m -> System.out.println(" minuted " + m.winner() + " (" + m.tally() + ") by " + m.clerk())); Optional<ArchiveReceipt> receipt = await(() -> first(fleet.space(Council.MINUTES), ArchiveReceipt.class, motion.motionId()), Duration.ofSeconds(30)); receipt.ifPresent(r -> System.out.println(" archived Hansard #" + r.hansardSeq() + ", precedent: " + r.precedent())); }
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.topicOfpicks 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.
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 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.
/** * 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;
// Every senator on the two Java peers and the Citizen's browser may vote; naming the Speaker // by agent puts VOTE at AGENT granularity, so each senator is its own counted voter. List<String> voters = List.of(keys.speaker().peerId().value(), keys.floor().peerId().value(), keys.citizen().peerId().value(), keys.speaker().peerId().value() + "/speaker"); for (int i = 0; i < voters.size(); i++) { p.put("agentspaces.security.grants.vote[" + i + "]", voters.get(i)); }
/** * Whether a request for the Citizen's key came from this machine: the socket's peer is a loopback * address and the {@code Host} header names a loopback host, so a page on another site that points * a name of its own at 127.0.0.1 cannot read the key either. */ static boolean fromThisMachine(HttpExchange exchange) { if (!exchange.getRemoteAddress().getAddress().isLoopbackAddress()) { return false; } String host = exchange.getRequestHeaders().getFirst("Host"); if (host == null) { return false; } int colon = host.lastIndexOf(':'); String name = colon > host.lastIndexOf(']') ? host.substring(0, colon) : host; return List.of("127.0.0.1", "localhost", "[::1]").contains(name); }
Map<String, Integer> votersPerMotion = new LinkedHashMap<>(); for (Motion motion : slate) { votersPerMotion.put(motion.motionId(), (int) votes.readAllIssued(Template.of(VoteCapability.Ballot.class) .where("proposalId", eq(Council.PREFIX + motion.motionId())), 10_000).stream() .map(issued -> issued.issuer().encoded()).distinct().count()); } assertThat(votersPerMotion.values()).as("every voter cast a ballot on every motion: " + votersPerMotion) .allMatch(count -> count == Council.QUORUM);
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.voteand 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.jsononly 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>/speakerexists 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.
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.
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.
@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; }
/** The Floor peer: a ChatClient over the fleet's model for the personas, and the Parliamentarian. */ @Configuration(proxyBeanMethods = false) static class FloorConfig { @Bean ChatClient personaChat(FleetChatModel fleetChatModel, FleetTaskScheduler scheduler) { return ChatClient.builder(fleetChatModel) .defaultAdvisors(new TakeLeaseAdvisor(scheduler.scheduler(), Duration.ofSeconds(30))) .build(); } @Bean Parliamentarian parliamentarian(AgentSpaces spaces, Environment env) { return new Parliamentarian(spaces, env.getProperty("council.peer-name", FLOOR), Duration.ofSeconds(Long.parseLong(env.getProperty("council.archive-wait-seconds", "20")))); } }
/** Claude Haiku's stand-in, unless the haiku-live profile brings the Anthropic auto-configuration. */ @Configuration(proxyBeanMethods = false) @Profile("!haiku-live") static class FixtureConfig { @Bean ChatModel haiku() { return new Personas.Fixture(); } }
spring: config: activate: on-profile: speaker agentspaces: roles: [RELAY] # forwards the browsers' RELAY_FRAMEs: the caucus signals, the clerks' Raft pipes springai: model-server: enabled: true models: ["${council.haiku-model}"] lease: 2m --- spring: config: activate: on-profile: haiku-live ai: model: chat: anthropic anthropic: api-key: ${ANTHROPIC_API_KEY} chat: options: model: ${council.haiku-model} max-tokens: 300 --- spring: config: activate: on-profile: floor agentspaces: springai: model-client: enabled: true model: ${council.haiku-model} timeout: 120s
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
catchinvotewrites 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.
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.
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.
/** 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()); } }
/** * Seats one Java clerk: registers the coordinator for the decisions space with the fixed * member list (the two Java clerks and the Node clerk), its Raft state durable under * {@code logDir}, taking under the clerk's own attested identity, and binds the clerk, which * is what lets {@code @OrderedTake} bind on that peer. The election seed is chosen so the * first timeout is the longest the log allows: the Node clerk, started earlier and already * canvassing, wins the first election, and the test knows whom to kill. * * @param context the peer's application context * @param members every voter's PeerId, the same list on every member * @param logDir where this member's Raft term, vote, and entries are kept * @param seed the election-timer seed; see {@link #slowSeed} * @return the seat */ public static Seat seat(ConfigurableApplicationContext context, List<PeerId> members, Path logDir, long seed) { AgentSpaces.GroupContext group = context.getBean(AgentSpaces.class).group(Council.GROUP); PeerIdentity identity = context.getBean(PeerIdentity.class); String name = context.getEnvironment().getProperty("council.peer-name", "clerk"); ReplicatedSpace decisions = (ReplicatedSpace) group.space(Council.DECISIONS); AgentIdentity clerk = context.getBean(AgentIdentityFactory.class).identityFor(CLERK); OrderedTakes desk = OrderedTakes.over(group.pipes(), CborCodec.defaultCodec(), identity, clerk, members, InstantSource.system(), seed, decisions, new FileLogStore(logDir)); List<TakeClaim> committed = new CopyOnWriteArrayList<>(); desk.onCommitted((entryId, claim) -> committed.add(claim)); group.ordered(Council.DECISIONS, desk); return new Seat(name, desk, group.bind(new Clerk(name, desk)), committed); }
/** * Seats the two Java clerks on the desk with the Node clerk: the Floor peer first, then, * once the Floor peer hears a leader (the Node clerk, already canvassing), the Speaker's * peer, so the seed never holds the gavel first and the test knows whom to kill. */ public void seatClerks(PeerId nodeClerk, Duration leaderWait) throws InterruptedException { List<PeerId> members = List.of(keys.speaker().peerId(), keys.floor().peerId(), nodeClerk); seats.put(FLOOR, Clerks.seat(peer(FLOOR), members, keys.root().resolve(FLOOR).resolve("minutes-log"), Clerks.slowSeed(4100L))); await(() -> seats.get(FLOOR).desk().raft().leader(), leaderWait); seats.put(SPEAKER, Clerks.seat(peer(SPEAKER), members, keys.root().resolve(SPEAKER).resolve("minutes-log"), Clerks.slowSeed(4200L))); }
# The Node clerk of the Compose recipe: the third voter of the minutes' ordered log, beside the # two Java clerks. `members` names the Java clerks' PeerIds (print them with # `agentspaces-node id keys/speaker` and `keys/floor`, or read them from the peers' logs); the # clerk's own PeerId is added by the host. The fleet test and the demo write their own copy of # this file with the session's ids and ports. agentspaces: keystore: keys bind: 0.0.0.0:7714 tick-millis: 250 groups: - name: keeping-it-real founding: keeping-it-real-v1 seeds: speaker:7711 spaces: [ motions, floor, votes, decisions, minutes, data, model-requests ] ordered-logs: - { space: decisions, members: [ "<speaker PeerId>", "<floor PeerId>" ], log-dir: log/decisions }
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.
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));
for (String peer : List.of(CouncilFleet.SPEAKER, CouncilFleet.FLOOR)) { Space view = fleet.group(peer).space(Council.MINUTES); for (Motion motion : slate) { assertThat(all(view, Minute.class, motion.motionId())).as(peer + " sees one minute of " + motion.motionId() + "; gavel lines: " + all(fleet.space(Council.FLOOR), FloorSpeech.class, motion.motionId()).stream() .filter(sp -> sp.senator().equals("The Speaker")).map(FloorSpeech::text).toList() + claims).hasSize(1); assertThat(all(view, ArchiveReceipt.class, motion.motionId())).as(peer + " sees one receipt of " + motion.motionId()).hasSize(1); } }
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
Minuteand oneArchiveReceiptper motion. - Restarting the Floor. When the Floor leads,
Fleet.restartcloses its context and starts a new one on the same keystore and durableFileLogStore, 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.
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 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 connector cell: one per deployment, named `connector`, publishing the Hansard and the precedents. */ export class Fleet extends AgentSpacesConnectorCell<Env> { protected manifest(_env: Env): AssetManifest { return { application: "archive", runtime: "workerd", freshness: "PT30S", durableObjects: [{ binding: "HANSARD", className: "Hansard", shape: "aspace:HansardRoll", description: "The roll of the committee's decisions", read: [{ name: "getRoll", params: [], description: "the roll in sequence order", resultShape: "seq,motionId,title,winner,tally,precedent" }], invoke: [{ name: "recordDecision", params: ["motionId", "title", "winner", "tally", "precedent"], description: "record a decision in the roll, once per invocation" }], objects: ["hansard"], }], kv: [{ binding: "PRECEDENTS", description: "The committee's precedents by topic", shape: "aspace:Precedent", prefixes: ["precedent/"], }], }; } }
{
"$schema": "https://developers.cloudflare.com/workers/wrangler/configuration/",
"name": "archive",
"main": "src/index.ts",
"compatibility_date": "2026-10-01",
"durable_objects": {
"bindings": [
{ "name": "HANSARD", "class_name": "Hansard" },
{ "name": "FLEET", "class_name": "Fleet" }
]
},
"migrations": [
{ "tag": "v1", "new_sqlite_classes": ["Hansard", "Fleet"] }
],
"kv_namespaces": [
{ "binding": "PRECEDENTS", "id": "<your precedents namespace id>" }
],
"triggers": { "crons": ["* * * * *"] },
"vars": {
"AGENTSPACES_GROUP": "z9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW",
"AGENTSPACES_SEEDS": "wss://council.example.com:7721/aspace",
"AGENTSPACES_INVITE": "",
"AGENTSPACES_PROFILE": "attested"
}
}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.
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.
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
wslistener and carries every query and invocation as an entry indata, so the deployment needs no inbound port. It joins by group id: in the test and the demo the launcher passesfleet.groupId()asAGENTSPACES_GROUP, andwrangler.jsoncarries 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 beforewrangler deploy. - Three cards. The class card
do/Hansard, the instance carddo/Hansard/hansardand the table cardkv/PRECEDENTS. The manifest is the whole allowlist: one read, one invoke operation, theprecedent/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.
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.
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; }
let target: string | null = null; while (target === null && Date.now() < deadline) { for (const [id, ad] of peer.members) { const endpoints = (ad["endpoints"] as { transport?: unknown }[] | undefined) ?? []; if (id !== peer.identity.peerId && endpoints.some((e) => e.transport === "webrtc")) { target = id; break; } } if (target === null) { await sleep(100); } } if (target === null) { window.caucus.reason = "the other citizen never appeared"; return; } const channel = await binding.connect(target); const echoes: string[] = []; channel.onFrame((frame) => { echoes.push(decoder.decode(frame)); window.caucus.received.push(echoes[echoes.length - 1]!); }); window.sendNotes = async (count: number) => { const before = echoes.length; for (let i = 0; i < count; i++) { channel.send(encoder.encode(`whip note ${window.caucus.sent + 1}: hold the line on the snack budget`)); window.caucus.sent += 1; } const until = Date.now() + 15_000; while (echoes.length < before + count && Date.now() < until) { await sleep(50); } text("notes", `${window.caucus.sent} whip notes sent, ${echoes.length} echoed`); return { sent: count, echoed: echoes.length - before }; };
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 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 ?? []; }
location = /config.json {
default_type application/json;
return 200 '{"seed":"wss://localhost:7721/aspace","invite":"keeping-it-real-v1","iceServers":[{"urls":["stun:localhost:3478","turn:localhost:3478"],"username":"caucus","credential":"whipnotes"}]}';
}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.
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:3478or?turn=turn:host:3478&turnUser=name&turnCredential=secretto 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=acceptorin one tab and?role=dialerin another.
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.
| Residency | In the council | What it carries here | What it may not carry |
|---|---|---|---|
| visitor | the gallery and the two caucus pages | watches four spaces, pulls them once a second, opens a webrtc channel | every duty in the table |
| resident | the Citizen's worker | a decorated agent whose @ballot signs with its own key | a Raft vote, a coordinator, a listener, a relay, a connector |
| service | the Node clerk | a Raft voter of the decisions log, a tcp listener | nothing |
| cell | the Archive's Fleet object | the connector runtime, the Hansard and the KV table as assets | a Raft vote, a coordinator, a listener, a relay |
/** 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", };
function start(): ResidentHost { const scope = globalThis as unknown as SharedScope & DedicatedScope; const shared = "onconnect" in scope && typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope === "function"; const host = new ResidentHost({ shared }); const citizen = new Citizen(); host.onResume(() => { // Bound again on every resume: the host closes its bindings on pause (JS-R-03). host.bind(citizen); const binder = host.binder(); floor = binder.space("floor"); for (const name of ["votes", "floor"]) { host.peer?.pullSpace(name); } }); setInterval(() => { host.peer?.pullSpace("votes"); }, 1500); const seeded = seedIdentity(); const attach = (port: PortLike): void => { void seeded.then(() => host.attach(port)); }; if (shared) { scope.onconnect = (event) => { for (const port of event.ports) { attach(port); } }; } else { const port: PortLike = { postMessage: (message) => scope.postMessage(message), get onmessage() { return scope.onmessage; }, set onmessage(handler) { scope.onmessage = handler; }, close: () => { void host.stop().finally(() => { globalThis.setTimeout(() => scope.close(), 250); }); }, }; attach(port); } return host; }
const worker = `/dist/resident-worker.js?${new URLSearchParams({ invite, key: citizen.key, pub: citizen.pub })}`; const host: BrowserHost = await connect({ founding: invite, seeds: [seed], worker, agentName: "citizen", tickMillis: 500 });
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.
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.
| 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 trip | The persona votes by proxy and says so. The quorum never waits. | the vote method of Personas.Senator, chapter 7 |
| A recording in flight | A 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 absent | The 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 candidates | Chromium 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 closed | The committee has no quorum and waits. The motion stays open until the Citizen returns. | the demo with COUNCIL_HEADLESS_CITIZEN set to false |
| The speaker | The 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.
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=trueCouncilSessionTest 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 desk | The Node clerk joins, the Floor and the speaker seat their clerks, and the log has a leader that is not the speaker. |
| 1: the gallery | The 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 Archive | The 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 caucus | The data channel opens, the acceptor echoes 25 notes, and the burst adds at most five relayed frames. |
| 2: the session | Five 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 Hansard | The forced retry answers the same record; one result exists per invocation id; durable and recorded both equal 10. |
| The Citizen | The resident tab cast 10 signed ballots; every motion has 11 distinct voters. |
| The personas | The 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.
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.
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.
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
clerk: build: context: ../.. dockerfile: agentspaces-example-apps/browser-council/docker/node.Dockerfile target: node command: ["node", "/workspace/agentspaces-typescript/packages/node/build/src/cli.js", "run", "/keys/clerk/clerk.yaml"] volumes: - keys:/keys depends_on: - speaker - floor archive: build: context: ../.. dockerfile: agentspaces-example-apps/browser-council/docker/node.Dockerfile target: node command: ["node", "/workspace/examples/browser-council/tools/run-archive.mjs", "${COUNCIL_GROUP_ID:-z9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW}", "ws://speaker:7712/aspace", "/archive", "31536000", "8788"] volumes: - archive:/archive depends_on: - speaker gallery: build: context: ../.. dockerfile: agentspaces-example-apps/browser-council/docker/node.Dockerfile target: gallery ports: - "8787:8787" depends_on: - speaker coturn: image: coturn/coturn:4.6 # The demo credential caucus:whipnotes is also in docker/gallery.conf, which hands it to the caucus pages. command: ["-n", "--log-file=stdout", "--listening-port=3478", "--min-port=49160", "--max-port=49200", "--realm=council.local", "--user=caucus:whipnotes", "--lt-cred-mech", "--no-tls", "--no-dtls"] ports: - "3478:3478/udp" - "3478:3478/tcp" - "49160-49200:49160-49200/udp"
# The Node image of the Compose recipe, shared by the clerk and the Archive, and the gallery's nginx # image: the agentspaces-typescript workspace, installed and built here, with this example's tools and # bundles on top. # # Build context: the AgentSpaces workspace root (compose.yaml sets `context: ../..`), because the image # needs two sibling directories, agentspaces-typescript and agentspaces-example-apps/browser-council, # and a context cannot reach above its own root. docker/node.Dockerfile.dockerignore keeps the rest of # the workspace out of the context. `docker compose build` from the example directory needs nothing # more than Docker. The layout under /workspace keeps tools/paths.mjs working: the example sits two # directories below /workspace, beside agentspaces-typescript. FROM node:22-bookworm-slim AS node WORKDIR /workspace COPY agentspaces-typescript /workspace/agentspaces-typescript # Installed and built in the image, so esbuild and workerd match this image's platform and not the # machine that checked the sources out. RUN cd /workspace/agentspaces-typescript && npm ci && npm run build && npm run build:packages COPY agentspaces-example-apps/browser-council /workspace/examples/browser-council RUN cd /workspace/examples/browser-council && node tools/build.mjs # The gallery: nginx over the pages the node stage bundled (site/dist) and docker/gallery.conf. FROM nginx:1.27-alpine AS gallery COPY --from=node /workspace/examples/browser-council/site /usr/share/nginx/html COPY agentspaces-example-apps/browser-council/docker/gallery.conf /etc/nginx/conf.d/default.conf
# The build context of node.Dockerfile is the AgentSpaces workspace root (compose.yaml: context ../..). # Send the TypeScript workspace and this example, and nothing else; the image installs and builds both. * !agentspaces-typescript !agentspaces-example-apps/browser-council # Host installs and builds: the image makes its own, for its own platform. **/node_modules **/build agentspaces-example-apps/browser-council/target agentspaces-example-apps/browser-council/site/dist agentspaces-example-apps/browser-council/archive/dist
#!/bin/sh # Starts one Java peer of the committee under Compose: the Spring application of CouncilPeer with # the properties the in-process launcher (CouncilFleet) would have set. COUNCIL_MEMBERS names the # three clerks' PeerIds once they are known (print them with `agentspaces-node id`); without it # the peer sits its senators and forms no desk. set -e ROLE="${1:-speaker}" KEYS="${COUNCIL_KEYS:-/keys}" mkdir -p "$KEYS/$ROLE" CP="/app/*:/app/lib/*" PROPS="-Dcouncil.peer-name=$ROLE -Dagentspaces.keystore=$KEYS/$ROLE" for G in $(echo "${COUNCIL_VOTE_GRANTS:-}" | tr ',' ' '); do I=${I:-0}; PROPS="$PROPS -Dagentspaces.security.grants.vote[$I]=$G"; I=$((I+1)) done if [ -n "${COUNCIL_MODEL_SERVER:-}" ]; then PROPS="$PROPS -Dagentspaces.security.grants.model-serve[0]=$COUNCIL_MODEL_SERVER" fi if [ "$ROLE" = "speaker" ]; then J=0 for O in $(echo "${COUNCIL_GALLERY_ORIGINS:-http://localhost:8787}" | tr ',' ' '); do PROPS="$PROPS -Dagentspaces.transport.ws.allowed-origins[$J]=$O -Dagentspaces.transport.wss.allowed-origins[$J]=$O" J=$((J+1)) done PROPS="$PROPS -Dagentspaces.bind=0.0.0.0:7711 -Dagentspaces.transport.ws.enabled=true -Dagentspaces.transport.ws.bind=0.0.0.0:7712" PROPS="$PROPS -Dagentspaces.transport.wss.enabled=true -Dagentspaces.transport.wss.bind=0.0.0.0:7721" else PROPS="$PROPS -Dagentspaces.bind=0.0.0.0:7713 -Dcouncil.seeds=${COUNCIL_SEED:-speaker:7711}" fi exec java $PROPS -cp "$CP" ai.badmonkey.agentspaces.examples.council.CouncilPeer "$ROLE"
- Peer ids come first.
clerk/clerk.yamlneeds the two Java clerks' PeerIds, and the Java peers take them back asCOUNCIL_MEMBERS. Print them withagentspaces-node idover thekeysvolume. - The Archive's group id has a default.
COUNCIL_GROUP_IDoverrides it. Unset,compose.yamlpassesz9QChLuUFY2vg9bSaB5tnAbJHFqscSpTPoh7uh9vg3AW, 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>/speakerfor agent granularity) andCOUNCIL_MODEL_SERVER(the speaker's peer id) once the ids are known. - Two things stay by hand. Only the in-process launcher writes
Motionentries intomotionsand 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.
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.
- Developer guide: the vote capability, the ordered log, connector cells, model access as a fleet service and JavaScript everywhere.
- TypeScript guide: the browser host, the Node host, Workers cells and the ordered log, joins and reduce.
- Other example guides: Superfriends (the vote and the ordered log across three model vendors), Ops Center (an ordered desk with a human gate) and Party Bus (every coordination type on one trip).