Plan: agent messaging over the pivot relay - the box side
Closes: #562 (U1), #563 (U2), #564 (U3), #565 (U4), #566 (U5), each by its unit’s MR (Closes #N in the commit). Relates to: #559 (shipped 0.135.1), #561 (shipped 0.135.2), pi-pivot #153 (ADR-008), #154 (relay), #155 (pivot-wire), #156 (client). Branches: fix/hub-attach-token, feat/messaging-spaces, feat/messaging-delivery, feat/messaging-tools, feat/messaging-wakes, in that order. Status: Done (2026-10-31) — U1-U5 shipped (#562-#566; 0.135.4, 0.136.0, and U5 in the next release); live use waits on pivot’s relay 0.3.2 and its phone’s space page (pi-pivot #156)
Erratum (2026-10-30): U2-U5 bind to pivot-wire 0.6.0 as built (pi-pivot #155; recorded on #563). Channel.derive(secret, name) returns a handle whose addr() is a method; seal(senderBoxId, messageJson) returns nonce, ciphertext and tag together, and open(stampBoxId, ct) returns the record as a JSON string. open throws one code, msg_sealed, both for a record that does not open and for one that opens malformed or past a limit (ADR-008: a failure says nothing about which check failed); seal throws msg_limit, msg_name or malformed. The record type is types/Message.ts, with these limits: subject one line of at most 200 characters, at most 32 tags of at most 64 characters each, the sealed form at most 262,144 bytes. Only maxSealedBytes() and channelNameOk(name) are exported. replay’s `epoch is absent when there is no cursor; the relay’s err gains too_large. U3’s contract test opens vectors.json’s `msg fixture with open(sender, ct) and expects exactly its message_json: there is no API to supply a nonce.
Erratum (2026-10-30): U2’s space secret is hex, as pivot-wire 0.6.0’s SpaceSecret carries it on the Noise wire, and spaces.json keeps it so; spaceId and Channel.derive take its 32 bytes. U2 also builds no member path for the grant records: every Peer is the hub’s (link.ts makes each one, and members hold none), so space_grant, space_revoke and space_export always reach the hub’s onControl. Nothing is added to MEMBER_CONTROLS, and there is no export refusal for a member; a member’s /remote-control status reads spaces.json for the labels.
Erratum (2026-10-30): gadhs-pi-remote.json’s loader never refused unknown keys, contrary to U2’s "as it does today"; U2 validates its `spaces key and leaves the rest as they were.
Erratum (2026-10-30): pivot-wire 0.6.0 refuses an agent over 64 characters (Unicode code points; seal throws msg_limit), and a canonical path often is longer. U3’s agentName keeps a name of 64 or fewer as it is, and shortens a longer one to an 8-hex SHA-256 digest of the whole name, a ~, and its last 55 characters; a configured agent must be one line of 1-64 characters.
Erratum (2026-10-30): U3’s store files are <state dir>/msg/<space_id>/ch-<channel>.jsonl; the prefix keeps a channel named like a Windows device (con) a plain file there. Reading is an appended read line naming the agent, not a read field rewritten in place, so marking a message read never rewrites a 20 MiB file, and unread counts are per agent, as the plan’s start-of-session count needs.
Erratum (2026-10-30): a member tells the hub its agent name, at attach and when its subscriptions change, as a new ToHub { t: "agent", agent }, and a delivered record goes down as a new ToMember { t: "message", where, message }; MEMBER_CONTROLS are the records broadcast to the phones, so a subscription sent there would have gone out to every device. Both are additive: an older hub or member logs and drops a line it does not know. A session’s own delivery is published on pi’s bus as gadhs:msg, for U5 to wake on. The listen set is sent only while non-empty, so a box not using messaging never puts a new verb before a relay that predates it.
Erratum (2026-10-31): U4 seals only at the hub, the one holder of the link: a member’s msg_post goes up as a new ToHub { t: "post", ref, where, record } and is answered { t: "posted", ref, error? }, the hub stamping the member’s named agent. The hub keeps its own posts in the store (seq 0, empty epoch) and fans them out, since the relay never returns a box’s own publish. The tools' tests are in extension.test.ts, whose harness builds a real session state, and the permission test is in pi-modes' mode-policy.test.ts; pi-remote declares typebox as a peer, as pi-modes does.
Erratum (2026-10-31): U5’s event carries this session’s agent and its subscription’s wake and collect tags, so pi-modes never reads pi-remote’s subscriptions.json. A second event, gadhs-msg:read { id }, which msg_read emits, lets the status count drop once a message is read. U3’s interim gadhs:msg is replaced by gadhs-msg:received. The Messages tab is one list sorted by channel and then newest first, with each row naming its channel and marking an unread collected one; the hub’s digit keys gain 6. The status line counts collected messages not yet read; a wake already reached the agent.
Why
What ntfy costs, from every agent in the thread (XI8U5hGEy3gK and its replies): every message wakes every subscriber, the sender’s own echoes included; whole bodies land in context when a headline would do; a subscription is a shell process that dies with the session, and its cursor sits in /tmp; the Title proves nothing; a post is a curl the judge weighs each time, and on Windows the shell halves backslashes (#450) and Git’s curl re-encodes non-ASCII argv. The operator chose ADR-008’s design and asked pi to build its side; ntfy stays for non-pi participants until a later standalone client.
ADR-008 fixes the wire, and this plan restates what it binds to so a reader needs no other document. Derivation: space_id = BLAKE2s-256(key = S, "pivot-space-id"); a channel name n (1-64 bytes of [a-z0-9._-]) gives addr = BLAKE2s-256(key = S, "pivot-channel-addr" ‖ n) and K = BLAKE2s-256(key = S, "pivot-channel-key" ‖ n). Record: { id (16 random bytes hex), re?, agent (1-64 chars), subject (one line), tags: [..], body (UTF-8), sent (unix s) }, sealed with XChaCha20-Poly1305 under K, a 24-byte random nonce prefixed, AAD "pivot-msg-v1" ‖ addr ‖ sender_box_id; the sealed form at most 256 KiB. Relay verbs, box connection only: listen { channels: [addr] } (replaces the set), publish { channel, ct }, replay { channel, epoch, after }; message { channel, epoch, seq, from, ct, sent_at } to every other listener, replayed { channel, epoch, head, gap }; epoch is minted per relay process, and a cursor (epoch, seq) from another epoch is a gap whatever head says. Grant records, session 0 over Noise: space_grant { space_id, label, secret }, space_revoke { space_id }, space_export { space_id } from the device; spaces { spaces: [{ space_id, label }] } and space_secret { space_id, secret } from the box. pivot-wire’s next release (pi-pivot #155) exports the derivation, seal and open, and the new Envelope and control variants; U2-U5 pin it and bind to its actual export names (an erratum if they differ from the ADR’s prose; the formats above do not move).
Design
U1 - a member authenticates its attach (#562; packages/pi-remote/hub.ts, member.ts, identity.ts, lifecycle.ts)
Since #559 the hub on Windows is a named pipe whose default ACL lets every account open it, and a hub treats a connection whose attach parses as a session of this box. Messages will fan out through the hub, so the attach is authenticated first, on every platform.
Token. hubToken(agentDir) in identity.ts: 32 random bytes, hex, in <state dir>/hub.token, mode 0600, created by the first hub that needs it and kept; the lock holder reads it when it listens, a member reads it before it attaches. The same user owns both files; another account cannot read the token, which is the whole check. ToHub’s `attach gains token: string and HUB_PROTOCOL becomes 2; attachProblem (hub.ts) requires the field, and onAttach compares it with timingSafeEqual before a session id is assigned: a wrong token is refused with reason not this box’s token and the connection closed, as a bad attach is today. A member so refused stops with attach failed, and its notice names the reason. No tokenless fallback: both ends ship together in one pi-remote version.
Tests (hub.test.ts, member.test.ts, hub-e2e.test.ts): an attach without the token or with a wrong one is refused and sent nothing else; with the right one it is session 2 as before; the token file is 0600 on POSIX (skipIf(win32)); the end-to-end member path still attaches, reading the file the hub wrote. A mutation check on the comparison and on `attachProblem’s new field. Failure class: fail-closed - a member that cannot read the token does not attach, and says so.
U2 - spaces and the standing link (#563; packages/pi-remote/spaces.ts new, peer.ts, hub.ts, member.ts, lifecycle.ts, commands.ts, config.ts, index.ts)
The secrets. spaces.ts keeps <state dir>/spaces.json: [{ space_id, label, secret, granted_at }], mode 0600, written atomically as saveDevices writes devices.json (identity.ts). loadSpaces, rememberSpace, forgetSpace. The secret is 32 bytes base64. space_id is checked against pivot-wire’s derivation on load, and an entry that does not match is dropped with a log line (pi_remote.space_dropped). On Windows the agent dir’s ACL is the guard (ADR-008); DPAPI is a later hardening, noted on #563, not built here.
The grant records. A device’s control records reach Peer.onControl (peer.ts) only after its Noise handshake was admitted (admission(): a pairing token, or a static on the trusted list), so every onControl caller is an authenticated device. The guard this unit adds is trust: Peer.pairing is true for a device that came in through a pairing window and has not finished introducing itself. space_grant and space_revoke are accepted from any admitted device (the operator holds it, and a grant is their act); space_export answers space_secret only when pairing is false, else refused { what: "space_export", reason: "not yet a trusted device" } - a device must be on the trust list before it can carry a secret out. Unknown record types keep today’s frame_dropped path. A grant remembers the space and broadcasts spaces; a revoke forgets it (U3 drops its cursors, subscriptions and store). spaces is sent after hello and on every change, to every ready device. A member’s peer has no secrets: a device talking to a member’s session sends its grant to that member, which forwards it up the hub socket as { t: "control", json } (HubClient.write, as idle goes today) with the record’s t added to MEMBER_CONTROLS; the hub does the grant and broadcasts spaces itself. An export asked of a member is refused there with reason: "ask the hub’s session", since the hub holds the file and the answer carries a secret.
The standing link. Today the relay link is up only under /remote-control, restored by the per-directory wish (link.wanted.d). A box that holds a space wants its link whenever pi runs: restoreLink (lifecycle.ts) also starts it when loadSpaces is non-empty and a trusted device exists, in whichever role the lock gives it, saying pivot: remote link up for messaging (N space(s)) once per session. /remote-control stop still stops it for this session and says it returns with the next session while this box holds a space; forgetting the spaces (a revoke from the phone) is the way out. /remote-control status (index.ts statusLines) lists the spaces by label.
Config (config.ts). gadhs-pi-remote.json lives at <agentDir>/gadhs-pi-remote.json: one file per agent dir, not per project. It gains spaces?: { allow?: string[] } (labels): absent, every space the box holds; present, only the named ones are listened to by this agent dir’s sessions. A convenience, not a boundary (the ADR’s words), documented so. The validator refuses an unknown key as it does today.
Tests (spaces.test.ts new, link.test.ts, hub-e2e.test.ts, extension.test.ts): grant, revoke and export round-trip through a trusted FakeDevice; export from a pairing-window device is refused by reason; spaces follows hello and each change; a grant to a member reaches the hub and is remembered once; a box with a space and no wish starts its link at session start; a stop says the link returns; status names the labels; the file’s mode and the space_id check; spaces.allow narrows the listen set. Property test: space_id of a random secret matches pivot-wire’s derivation (the contract with the wire). Failure class: fail-closed - a record that does not validate is refused by reason; a secret that does not derive its space_id is dropped and logged, never used.
U3 - delivery: listen, replay, the cursor, the store, agent names, fan-out (#564; packages/pi-remote/messaging.ts new, msg-store.ts new, agent-name.ts new, link.ts, hub.ts, member.ts, session-link.ts, config.ts, index.ts)
Agent name. agentName(cwd, ws) in agent-name.ts: the project’s canonical path (realpath.native), case-folded on win32 (#535, #538 and #567 were all this class), the remote path when the session’s workspace is remote; the per-agent-dir config may override it (agent?: string, so one box’s agent dir names itself pi-dev across its projects). Fixed at session start, shown in the hub’s Session tab (U5), sent as the record’s agent.
Listen. When the link is up and the box holds a space, messaging.ts derives the addresses of every channel any session on the box has subscribed to (U4), filtered by spaces.allow, and the hub’s Link sends listen { channels } as a new envelope (link.ts send); the set is re-sent on every reconnect (onWelcome) and whenever a subscription changes. A member’s subscriptions reach the hub as { t: "control", json: { t: "subscribe", … } } (added to MEMBER_CONTROLS); the hub keeps the union and listens once.
Replay and the cursor. Per channel the box keeps cursor = (epoch, seq) in <state dir>/msg/cursors.json, written after each delivered message (debounced to one write per second). On every (re)connect the hub sends replay { channel, epoch, after } per listened channel (a box with no cursor sends after: 0 and an empty epoch); a replayed with gap: true is written to the store as a missed record and the hub says pivot: messages were missed on <channel> (the relay restarted, or the window passed) once per gap.
Open. Each message is opened with the channel’s K and the ADR’s AAD, with the relay’s from as the stamp; one that does not open is logged (pi_remote.msg_rejected { channel, from }) and dropped, never surfaced to a session. The opened record is checked for shape (the fields and limits in Why) before anything reads it.
The store. msg-store.ts: <state dir>/msg/<space_id>/<channel>.jsonl, one line per record ({ id, re, agent, from, subject, tags, body, sent, seq, epoch, received, read }) plus missed lines; bounded per channel at 16 MiB, oldest lines dropped by rewriting when it passes 20 MiB. find(id) across channels; markRead(id). The store is the box’s; every session reads it.
Fan-out. The hub delivers each opened record to every session whose subscription matches its channel: to a member as a new ToMember { t: "message", channel, record, from }, to its own session directly; each session then applies its own tags (U5). A record for an agent whose name is in subscriptions.json but has no running session waits in the store, and the next session with that name is told at start how many it has unread per channel. Own posts: the relay never returns the sender’s own publish, and the hub never delivers a record whose from is this box and whose agent is the receiving session’s; a second agent on the same box does receive it.
Tests (messaging.test.ts, msg-store.test.ts, agent-name.test.ts new; hub-e2e.test.ts, link.test.ts with the FakeRelay grown the new verbs): listen is sent on connect, re-sent on reconnect and on a change; the cursor advances per delivered message and survives a new harness on the same dir; a replayed with the cursor’s epoch different from the relay’s writes missed and says so once, even when head is past the cursor (the ADR’s pinned rule); a record sealed under another space, another channel name or another stamp does not open and is logged (pivot-wire’s vectors); the store bounds and rewrites; a message for an agent with no session is in the store and counted at the next start; the sender’s own session never receives its post, a second agent on the box does; agent names fold case on win32 and are the remote path over SSH. A concurrency test: two members subscribing while a replay is in flight leave one listen set and no duplicate delivery. Failure class: fail-closed for a record that does not open (dropped and logged); silent-made-visible for a gap (a missed line and one notice, never swallowed).
U4 - the tools (#565; packages/pi-remote/msg-tools.ts new, index.ts; packages/pi-modes/modes.json; packages/pi-workflow/index.ts)
Four tools, registered by pi-remote: msg_channels, msg_subscribe, msg_post, msg_read (the msg_ prefix because pi’s own tool is read). Each takes a space by label when the box holds more than one, else the one.
-
msg_channels: the channels this box has subscribed to, per space, with the unread count per channel. The relay lists nothing (ADR-008): a channel exists by use, so the list is the box’s own. -
msg_subscribe { channel, wake?: string[], collect?: string[], off?: boolean }: subscribes this agent (by its name) to a channel with wake tags and collect tags;to:<agent name>always wakes;offunsubscribes. Persisted in<state dir>/msg/subscriptions.jsonper agent name, so a reload keeps it. -
msg_post { channel, subject, body, tags?, re? }: seals and publishes; a body whose sealed form would pass 256 KiB is refused with the limit named and "put it in git and reference it". A file attachment by path is not in this round; the issue says so. -
msg_read { id }: the record from the store, marked read;{ channel, missed: true }lists the channel’smissedlines.
Permissions. The tools are typed calls, never a shell; a space the operator granted from the phone is the authorization. In modes.json each mode’s permission block gains the four with "*": "allow" in auto and manual, as monitor has (modes[0], modes[2]); plan mode’s permission gains msg_channels, msg_read and msg_subscribe as allow and msg_post as deny (plan changes nothing outside the plan file, and a post is an outside effect), and plan mode’s tools list, which is what offers tools there, gains the three; yolo has no rules and allows all four. No judge call per post. pi-workflow’s tool_call pause (index.ts, where write is paused today) gains a msg_post case: subject and body go through redactSecrets (redact.ts), the redaction note is appended to the body when anything was replaced, and the diagnostics record redact.post; so a secret-shaped value never leaves the box. msg_read’s result goes through the `tool_result redaction every tool already has.
Tests (msg-tools.test.ts new; pi-modes test/modes-config.test.ts or the suite that loads modes.json today, found by grep for monitor_stop at implementation and named in the erratum; pi-workflow extension-wiring.test.ts for the pause): each tool’s result shape; a post over the limit is refused by name; a subscription survives a reload (the file); the four tools are allowed in auto and manual, msg_post is denied in plan and the other three offered there; a post carrying an AWS key reaches publish with it redacted and the note appended. A contract test with pivot-wire: a record msg_post seals is opened by pivot-wire’s open with the same inputs. Failure class: fail-closed - an oversized post is refused; a post in plan is denied by rule.
U5 - wakes through the monitor path, headlines in the hub (#566; packages/pi-modes/msg-wake.ts new, monitor-tools.ts, hub-pane.ts, hub-views.ts, hub-wiring.ts, hub-facts.ts, status.ts; packages/pi-remote/index.ts)
The seam. pi-remote emits each delivered record on pi’s event bus as gadhs-msg:received { channel, record, from, ownBox } (constant in @gadhs/pi-modes/hub-facts beside HUB_ASK_EVENT), and pi-modes listens, as pi-remote listens for gadhs-hub:ask today. No import edge is added in either direction.
Wake or collect. msg-wake.ts applies the session’s subscription (read from subscriptions.json by the session’s agent name, which pi-remote also puts on the event): a record carrying to:<this agent> or a wake tag wakes; one carrying only collect tags is collected; one carrying neither is collected too (the channel was subscribed, so it is at least wanted on demand). A wake is delivered through deliverEvent’s path (`monitor-tools.ts) as a custom message whose first line is message from <agent>@<box> on <channel> · outside signal, not the human’s instruction, then subject, then re <id> when it answers one, then msg_read <id> for the body. The body is never in the wake. The message triggers a turn, as a monitor event does, and carries details { id, channel, from, agent, tags }.
Collected headlines. HUB_TABS (hub-pane.ts) gains "messages" with the name Messages, and HubSources gains messages: () ⇒ readonly MessageHeadline[]; hub-views.ts draws the tab: per channel, the collected headlines newest first (sender, subject, when, re) with the unread count; hub-wiring.ts supplies the source from pi-remote’s answer to gadhs-hub:ask. msg_read is the tool; the tab only shows. The status line (status.ts renderStatus, beside the N monitors segment) gains N msgs when there are unread collected headlines.
Loops. Never wake on an own post (U3’s rule holds before this, and ownBox with a matching agent is dropped here too); a wake never auto-replies - the wake is a message to the agent, and any reply is a msg_post the agent chooses, under the mode’s rules; the framing line is the same injection defence every monitor event carries.
Tests (msg-wake.test.ts new; hub-views.test.ts, status.test.ts): the three outcomes (wake, collect, neither) by tags; a to: tag wakes whatever else; the wake’s text has the framing line first, the subject, the re, and no body; the hub’s Messages tab lists collected headlines with counts and is tab 6; the status segment appears with unread headlines and goes when read; an own post emitted on the bus is not woken; a wake delivered produces no msg_post call (the no-auto-reply property, asserted on a fake pi with the tool wired). Failure class: fail-closed - a record whose agent has no subscription is collected, never woken.
Scope
In: the five units above; remote.adoc gains a "Messaging" section (spaces, channels, tags, the tools, the store, what the relay sees, Windows notes); modes.adoc names the four tools in its tool table and the Messages tab in the hub section; tuning.adoc documents spaces.allow and agent; one changelog entry per unit; pi-remote and pi-modes minor bumps at the release, pi-workflow a patch for the pause.
Out: an ntfy bridge (the operator: ntfy stays for non-pi participants until the standalone client); a file attachment on msg_post (git is the way, per the ADR); the phone reading channels (a device may not listen, ADR-008); DPAPI for the secrets on Windows (noted on #563); rate limiting beyond the relay’s buffer; signing records inside the ciphertext (the ADR’s alternative 4, deferred there too).
Order and blocking: U1 lands now (it needs nothing from pivot). U2-U5 wait for the pivot-wire release pi-pivot #155 names, and pin it. Each unit is one MR with its tests, docs and changelog entry, and closes its issue; a unit’s live check on Windows is pi-win’s (the hub token, the pipe), and over SSH is pivot’s (the agent name is the remote path).
Risks, each with its failure class:
-
pivot-wire’s export names differ from the ADR’s prose: fail-closed - the build does not compile until bound; an erratum names the exports, the formats do not move.
-
The hub socket gains record types (
subscribe, the grants,message): fail-closed -MEMBER_CONTROLSis extended by name and the hub still refuses anything that speaks for the box; a test assertshello,pairedandsession_endedfrom a member are still refused. -
A chatty channel fills the store’s bound: silent-made-visible - the rewrite keeps the newest 16 MiB, and anything missed on the relay side is a
missedline and a notice, never a quiet loss. -
The PowerShell start-time query (#570) and the token file on Windows: fail-open on the token only if the agent dir’s ACL is wrong, which is the same guard the identity key has today; documented in `remote.adoc’s Windows notes.