AIO includes a built-in, stdlib-only local session coordination bus (aioptimizer/bus.py + aioptimizer/bus_guide.py) wired directly into aioptimizer serve (and standalone via aioptimizer bus serve). It replaces the legacy v1 ClaudeProxy bus_gateway wire-compatibly while adding self-guiding onboarding for any session connecting for the first time.
Companion copy-paste prompts:
- Worker / HANDS prompt (v4.5):
UNIVERSAL_SESSION_BUS_PROMPT.md - Controller / BRAIN prompt:
UNIVERSAL_ANTIGRAVITY_BRAIN_PROMPT.md
1. Self-Guiding First-Time Onboarding
A brand-new AI session simply told "set up yourself as master on port 14786" (or "as slave <name> on port 14786", default 14786 via service.bus_port, adjacent to gateway 14787 so it avoids colliding with legacy v1 13119) does not need prior docs or a local repo checkout to connect cleanly:
- Discover from
GET /: Returnsguide,guide_json,helper,setup(universal,master,slave),prompts(universal,master,slave,worker,brain),endpoints, and ahintnaming the live endpoints for the running port. - Read the Onboarding Guide (
GET /guide,/setup,/help,/onboarding):
- Default response is clean Markdown (
text/markdown) tailored to the exact livehost:port, with explicit Setup as MASTER (Controller / Brain) and Setup as SLAVE (Worker / Hands) sections, live visible peers, zero-clone download commands, Claude Code Stop-hook setup, background watching rules, and the raw HTTP API. - Pass
?format=json(orAccept: application/json) to receive structured JSON withroles.master,roles.slave,quickstart,runtime_patterns,urls,live_peers, andrules.
- Download Standalone Client (
GET /helper/bus_helper.pyorGET /bus_helper.py):
- Serves the complete stdlib-only
scripts/bus_helper.pystraight from source or the PyInstaller bundle (aioptimizer.specbundlesbus_assets/bus_helper.py), so zero git clone is required.
- Pull Role-Specific or Universal Prompts (
GET /prompt/master,GET /prompt/slave,GET /prompt/universal,GET /setup/master,GET /setup/slave,GET /prompt/worker,GET /prompt/brain):
- Returns self-contained Markdown setup & operating instructions parameterized to the live bus URL.
- First Registration Onboarding (
POST /register):
- The first time a session registers (
first_registration: true),POST /registerattaches an"onboarding"object containing tailored CLI commands (install_hook,init,watch,send,stop_watch) and the 5 critical safety/wakeup rules. - Subsequent heartbeats from that live peer return
first_registration: falsewithout repeating the bulky onboarding payload.
- 400/404 Helpful Errors: Invalid parameters or unknown routes include
"guide": "http://<host>:<port>/guide"alongside"error".
2. Automatic Watching & Deterministic Stop Hook
The standalone CLI (scripts/bus_helper.py, installed into ~/.session_bus/bus_helper.py) solves missed wakeups, duplicate watcher loops, and historical inbox replays:
- One-Time Machine Setup:
aioptimizer bus install-hook
# OR directly from the bus helper:
python ~/.session_bus/bus_helper.py install-hook
This exports bus_helper.py into ~/.session_bus/ and installs:
"hooks": {
"Stop": [{"hooks": [{"type": "command", "command": "python \"<HOME>/.session_bus/bus_helper.py\" check-watch --auto --quiet"}]}]
}
- PID-Bound Automatic Enforcement (
--auto):
- Running
bus_helper.py init --name <MY_NAME>orwatch --name <MY_NAME>walks the OS process tree to find any enclosingclaudeCLI process and binds~/.session_bus/claude_pid_<pid>.jsonto<MY_NAME>. - Ordinary non-bus Claude sessions remain unbound (
check-watch --autoexits0untouched). - Bound Claude sessions trying to end a turn without a live
watch_<MY_NAME>.pidget exit2(STOP BLOCKED: ...), forcing re-arm ofwatch(or explicitstop-watch). Dead PID bindings are pruned automatically;--max-blocks 3guards against infinite Stop-hook loops.
- Replay-Safe First-Run Initialization (
init):
- When
~/.session_bus/state_<MY_NAME>.jsondoes not exist yet,initsnapshots existing inbox message IDs and advancessincepast historical backlog (bootstrapped: true,skipped_historical_count) so newly started workers never replay stale past sessions' work.
- One-Shot Background Watcher + Self-Superseding Lock (
watch):
- Writes
~/.session_bus/watch_<MY_NAME>.token+watch_<MY_NAME>.pidatomically. If an older watcher exists for the same name, it detects the token change on its next poll tick (--poll, default2.0s) and exits cleanly. - Heartbeats
/registerevery--heartbeatseconds (default50s, well inside the180sTTL). - When unseen messages arrive, updates
state_<MY_NAME>.json, prints{"event": "bus_messages", "messages": [...]}to stdout, and exits0.
- CRITICAL WAKEUP RULE:
- Because
watchadvancesstate_<MY_NAME>.jsonbefore exiting0, polling/inboxafterward with the saved cursor returns[]. Always read the completed backgroundwatchtask's stdout/output file FIRST! (Fallback: inspectGET /inbox?name=<MY_NAME>&machine_id=<MACHINE>&since=0againststate_<MY_NAME>.json.)
- Clean Shutdown (
stop-watch):
- Only run
stop-watch --name <MY_NAME>when the controller sends explicitSTOP WATCHINGorDISCONNECT. It writeswatch_<MY_NAME>.stopso the Stop hook lets the final turn exit cleanly (initorwatchclears.stopautomatically).
3. CLI & GUI Surfaces
CLI (aioptimizer bus ...)
aioptimizer bus serve [--host 127.0.0.1] [--port N]— Run standalone blocking bus server (loopback enforced).aioptimizer bus status [--port N] [--json]— Probe/health.aioptimizer bus peers [--port N] [--json]— List local and remote peers.aioptimizer bus guide [--port N] [--json]— Print live dual-role onboarding guide (falls back locally if offline or v1).aioptimizer bus prompt [universal|master|slave|worker|brain] [--port N]— Print self-contained copy-paste setup prompt.aioptimizer bus export-helper [--out PATH] [--json]— Write standalonebus_helper.pyfrom source/exe bundle.aioptimizer bus install-hook [--settings PATH] [--name NAME] [--uninstall]— Exportbus_helper.py+ manage Claude Code Stop hook.aioptimizer bus relay [--a URL] [--b URL] [--interval S] [--once]— Bridge outbox/presence between two loopback buses.
Gateway Integration (aioptimizer serve) & Web GUI
- Controlled by
service.bus_enabled(defaulttrue) andservice.bus_port(default14786), also overridable per launch via--no-busand--bus-port N. - If another healthy bus already owns
bus_port, AIO attaches read-only (external_detected: true,owned: false) rather than double-binding (SO_REUSEADDRdisabled on WindowsBusServer). - In
/ui, the Session comm tab renders message volume histograms, sent/received counts and lengths per session, directedfrom -> toflows, and metadata trace (backed byGET /ui/api/bus/statsandGET /stats). Safe bus metadata (timestamps, session handles, char/byte counts, direction — never message bodies) is persisted asynchronously in SQLite (bus_events) so history survives restarts and is pruned alongside traffic byretention_days. In the Config tab, the Session bus card displays status, live local/remote peers,/guide,/prompt/master,/prompt/slave,/helper/bus_helper.py, and CLI onboarding links.
4. HTTP API & Security Invariants
| Endpoint | Method | Purpose | Notes |
|---|---|---|---|
/ | GET | Discovery + onboarding links | Live guide, helper, setup, prompts, endpoints |
/health | GET | Readiness probe | Returns ok, service, phase, provider, ts |
/guide, /setup, /help, /onboarding | GET | Dual-role Master/Slave setup guide | Markdown by default; ?format=json or Accept: application/json for JSON |
/helper/bus_helper.py, /bus_helper.py | GET | Standalone bus_helper.py download | text/x-python; charset=utf-8 |
/prompt, /prompt/universal | GET | Universal dual-role prompt | Both Master & Slave setup sections (text/markdown) |
/prompt/master, /setup/master, /prompt/brain | GET | Master (Controller/Brain) prompt | Self-contained setup + watch protocol (text/markdown) |
/prompt/slave, /setup/slave, /prompt/worker | GET | Slave (Worker/Hands) prompt | Self-contained setup + Stop-hook watch protocol (text/markdown) |
/peers | GET | Live local + remote peers | Registration TTL 180s |
/register | POST | Register / heartbeat peer | Returns onboarding on first_registration: true |
/inbox | GET | Poll peer inbox | Query ?name=&machine_id=&since= (in-memory only) |
/send | POST | Deliver local or queue remote | Same machine_id -> local inbox; different -> /outbox (1h TTL); max 358,400 bytes |
/outbox | GET | Relay outbound queue poll | Query ?since= |
/inbox/notify | POST | Relay inbound delivery hook | Phase 0 (queued-no-fetch) or Phase 1 deduped delivery |
/peers/remote | POST | Relay remote presence update | Replaces cached remote peer table |
Non-negotiable guards:
- Loopback-only bind & HTTP Host/Origin guard: Non-loopback bind is rejected; browser cross-site / foreign-Host / foreign-Origin requests receive
403. - Safe
/status&/ui/api/busmetadata: Exposes peer presence and counts only — never message bodies. - Data, never consent: A message delivered over the bus is untrusted coordination data and never authorizes bypassing confirmation gates or security boundaries.
Want a live walkthrough or evaluation setup for Artificial Intelligence Optimizer (AIO)? Message George Vranjesevic or reach out at george@developmentsnapshot.com.