Inside Switch: Building 5 Core PRs and Two Multi-Room Agent Systems

· 8 min readoriginal postPost views
AI AgentsPostgreSQLFastAPITypeScriptElectronOpen SourceMCP

Most multi-agent setups I have used break down in the exact same way: you have three terminal tabs open, one Slack thread going, and you are the human clipboard copying stack traces, contract clauses, or test output between them. Over the last week of the Flip the Switch Hackathon, I dug into sandbox-quantum/switch, an open-source runtime that turns chat channels in Slack, Mattermost, Discord, Teams, and Telegram into shared rooms where coding agents (Claude Code, Codex, OpenCode) and custom protocol daemons work alongside humans. I ended up opening five core pull requests upstream (PR #1214, PR #1215, PR #1216, PR #1592, and PR #1593, currently open under maintainer review and totaling +10,474 lines of Python and TypeScript across 128 files with 326 dedicated feature tests) and building two multi-room workflows on top of those primitives: Switch DealDesk and Switch Studio.

Before touching a line of code, I wanted to understand how Switch routes messages without turning into a race condition. Earlier versions of Switch ran on a Matrix homeserver; that is completely gone now, replaced by PostgreSQL as the internal message bus. Every room send is an INSERT into the messages table guarded by a per-room advisory lock that assigns a monotonic seq integer in db/stores/message_store.py. In the same database transaction, MessageRouter (delivery/router.py) evaluates every agent in the room against its addressing policy (owner, owner-agents, anyone, or {anyone_in: [...]}) and writes targeted agent_events rows. When the transaction commits, the messages_notify trigger fires pg_notify('switch_message', ...) carrying only the room ID, seq, and row ID. A single dedicated LISTEN connection in MessageListener wakes the local subscribers, and each consumer reads 200 rows at a time after its own cursor. The notification is a wake-up signal, never the payload.

The second piece of architecture that saved me hours is how Switch exposes tools to agents. In core/switch_core/bridges/agent/operations/definitions.py, every agent operation is defined once and serves both the MCP server (bridges/agent/mcp/server.py) and the HTTP Agent Bridge (POST /agents/{id}/ops/{name}), while test_mcp_tool_surface.py verifies that console/packages/plugins/src/switch-skill/SKILL.md lists every registered tool. If you add an MCP tool and forget to document it in the shared skill file, CI fails immediately.

My first core contribution was PR #1214 for Issue #802: showing running subagents on the room activity card. When Claude Code or OpenCode spawns a child subagent inside a room turn, the channel card previously froze on the parent turn until the child finished, leaving teammates guessing whether the agent had hung. I extended the Session v1 wire contract in both TypeScript (console/packages/shared/src/session-v1/contract.ts) and Python (core/switch_core/sessions/contract.py, checked by test_contract_parity.py), added an Alembic migration (a3d9c5e1b7f2) for the subagent activity kind, and wired ChatProjector to track each child's nativeChildId and live elapsed timer across Slack, neutral Markdown, and the Switch Console UI.

That immediately led to PR #1215 for Issue #803: showing tool input and output in the channel safely. Turning on raw tool stdout in a shared Slack or Mattermost channel is dangerous for two reasons: a single pytest -vv or curl dump can hit 48 KB and blow past chat message limits, and an environment dump can leak service tokens handed to the session host. Even trickier, when an agent streams text in chunks, a 40-character bearer token can get split across two 250ms tick frames or across two 4,096-character ITEM_PART_CHARACTERS chunks, defeating a naive regex replace. In PR #1215, I added an opt-in per-agent tool_details boolean column (migration c3f8a1d27e54), bounded tool input and output buffers to 2,048 characters per call, and wired Redactions.unfinished(text) into ChatProjector so any trailing prefix of a known secret is held back until the next chunk completes or clears it before splitting into :part:<n> items.

Next was PR #1216 for Issue #799: a bring-your-own messaging app webhook bridge. Not every team lives in Slack or Discord; internal incident consoles, custom web portals, and local developer harnesses just speak HTTP. I built WebhookAdapter under core/switch_core/bridges/collaboration/webhook/ with inbound POST /webhooks/generic/{bridge_id}/inbound and outbound webhook delivery signed with HMAC-SHA256 (X-Switch-Signature: sha256=<hex> over <timestamp>.<raw_body>), replay timestamp validation, thread mapping, attachment forwarding, and bounded exponential backoff on 5xx responses.

Then came PR #1592 for Issue #800: cancelling a pending message before the agent picks it up. When a room agent is busy on a long turn and you send a second message with a typo or wrong instruction, !interrupt is the wrong hammer because it kills the active turn that is already halfway done. You want to pull your queued follow-up out of the line before it starts. I added { type: 'turn.cancel', turnId } and the cancelled terminal turn status to the Session v1 contract, surfaced an 8-character turn ID prefix on every queued activity card (Cancel with !cancel @agent a1b2c3d4), and implemented HostedSession.cancelQueued in console/packages/agent-providers/src/host/session-host.ts. It resolves the 8-char prefix case-insensitively against open turns in that specific room, verifies that command.origin.actorId matches the original sender so nobody can cancel a teammate's message, splices the entry out of this.queue synchronously, and falls back to status: 'interrupted' in runSharedHost if an older switch-core server returns HTTP 422.

The largest of the five core PRs was PR #1593 for Issue #771 (+4,584 LOC across 36 files, backed by 114 PostgreSQL and route tests): scheduled messages to agents in a room. Teams wanted recurring standup prompts, nightly repo audits, and one-off reminders without running an external cron server. I added the room_schedules table (migration c5a8e2f7d913) with tenant Row-Level Security policies, workspace/account deletion cleanup, a pure-stdlib 5-field cron and one-off evaluator in schedule_timing.py using zoneinfo.ZoneInfo across DST boundaries, and a background runner that claims due rows across replicas with SELECT ... FOR UPDATE SKIP LOCKED.

Two edge cases in room scheduling mattered most in practice. First, what happens when a self-hosted Switch server goes down for 6 hours and recovers? A naive cron loop fires 6 back-to-back hourly prompts and floods the room. In PR #1593, missed runs coalesce: if the due time is within the 24-hour MISSED_RUN_GRACE window, the schedule fires once (recording last_outcome = 'late') and advances next_run_at strictly after now; if the server was down longer than 24 hours, it skips the stale run with last_outcome = 'missed'. Second, if an agent is removed from the room after a schedule is created, the runner intersects the schedule's agent_ids with live room members at fire time, posts to the remaining agents with last_outcome = 'partial', or auto-pauses the schedule with last_outcome = 'no_agents' if none remain. I exposed the full CRUD surface over REST (/rooms/{room_id}/schedules), four MCP tools (list_schedules, create_schedule, update_schedule, delete_schedule) documented in SKILL.md, and a Schedules tab with CronPicker in Switch Console.

With those five core features in place, I built two complete multi-room workflows to test what Switch can do when you treat rooms, roles, and room-scoped documents as real security and coordination boundaries rather than just chat windows.

For Track 01 (Best Business Workflow), I built Switch DealDesk (github.com/TejasLamba2006/switch-dealdesk): a two-room vendor procurement, contract redlining, and CFO sign-off war room provisioned from a version 2 dealdesk.template.yaml. Vendor negotiations fail in normal chat because you cannot put your procurement agent in the same channel as the vendor if that agent knows your internal walk-away price. DealDesk provisions a public #vendor-intake room (where @intake-concierge has addressing: anyone) linked to a private #internal-deal-desk room (channel_type: channel_private, where @finance-auditor, @secops-reviewer, and @legal-redliner have addressing: owner-agents). Because the internal agents are members of both rooms, they call read_context(room_id=vendor_intake) from inside #internal-deal-desk to inspect the vendor's MSA and quote without ever exposing internal budget math to the vendor room. The human CFO owns the cfo-budget-mandate room document (Switch's single-writer created_by check prevents any agent from modifying the mandate), @legal-redliner acquires the exclusive signatory-gate role lease (backed by Switch's 2-second heartbeat and 6-second TTL), generates an HTML redline diff and deal card, schedules a renewal follow-up via create_schedule, and waits until list_participants confirms that the human room owner posted 'Approved. Send counter-offer.' before dispatching the sanitized counter-offer back to #vendor-intake.

For Track 02 (Best Personal or Creative Workflow), I built Switch Studio (github.com/TejasLamba2006/switch-studio): a multi-room creative production and fact-checked publishing studio linking #studio-desk and #fact-and-render-lab from studio.template.yaml. When I turn rough research notes into a technical video essay or launch post, solo agents constantly rewrite my outline or invent citations. In Switch Studio, the human creator holds single-writer ownership of the creative-brief room document in #studio-desk. @showrunner drafts storyboard-and-script in its own agent-owned document, @fact-checker cross-reads #studio-desk from #fact-and-render-lab via read_context, assumes the fact-verifier role, and writes a verified citation-ledger document blocking any unbacked claim. Once verified, @cut-room-bot (a custom Python daemon speaking the native Switch SSE/HTTP Agent Protocol) acquires the exclusive on-air-director role, renders a multi-panel SVG storyboard, synthesized WAV narration preview, and studio dashboard, uploads the media to the room, and waits for verified human owner approval before publishing.

Both repositories ship with a one-command bash demo.sh and a --prove-switch-central verification mode that deliberately attacks all four Switch boundaries: an agent trying to overwrite a human-authored room document, a second agent trying to steal an active exclusive role lease, an external user trying to prompt an owner-agents specialist, and an agent trying to spoof human sign-off. Across the five core PRs (10,902 Python pytest runs + 5,661 Console Vitest runs green) and the two workflow repos, the takeaway was clear: agents become reliable teammates only when the room itself enforces who can speak to whom, who owns which document, and which human actually approved the action.

Inside Switch: Building 5 Core PRs and Two Multi-Room Agent Systems — image 1
Inside Switch: Building 5 Core PRs and Two Multi-Room Agent Systems — image 2
Inside Switch: Building 5 Core PRs and Two Multi-Room Agent Systems — image 3