Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(codex): Codex joins Switch via a connector plugin — drops the bespoke MCP setup path (CHOO-1436) (#79)

Christian McDermott60bffd5b01bb
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index ae5569bb2..62f8e2cba 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -1,7 +1,7 @@
{
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
"name": "switch-plugins",
- "description": "Switch platform plugins for Claude Code",
+ "description": "Switch platform connector plugins for Claude Code and Codex",
"owner": {
"name": "SandboxAQ"
},
@@ -11,6 +11,12 @@
"description": "Connect Claude Code to a Switch platform instance as a participating agent",
"category": "integrations",
"source": "./connectors/claude-code-plugin"
+ },
+ {
+ "name": "switch-connector-codex",
+ "description": "Connect Codex to a Switch platform instance as a participating agent",
+ "category": "integrations",
+ "source": "./connectors/codex-plugin"
}
]
}
diff --git a/CLAUDE.md b/CLAUDE.md
index c6061cd53..3307c67b6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -74,24 +74,42 @@ just test -k "test_name" # run specific test
- Session management: API endpoints use middleware-provided sessions; background work creates sessions explicitly
- All participants in rooms are Matrix clients (matrix-nio) connecting to Tuwunel
-## Claude Code connector plugin
-
-The `switch-connector` Claude Code plugin lives in `connectors/claude-code-plugin/`
-— skills, hooks, and an `.mcp.json`. It contains **no runtime code**: the MCP
-server is `@sandbox-quantum/switch-agent-runtime`, fetched with `npx` and built
-from `dash/packages/switch-agent-runtime/`. switchdash imports the same package
-for its protocol client, so there is one implementation of the agent protocol
-rather than a copy per consumer.
+## Connector plugins
+
+There are **two** connector plugins under `connectors/`, one per agent host, and
+each ships its own copy of the Switch room-workflow skill at
+`skills/switch/SKILL.md`:
+
+- `connectors/claude-code-plugin/` — manifest `.claude-plugin/plugin.json`.
+ Ships the skill plus an MCP config (`.mcp.json`) and hooks. It contains **no
+ runtime code**: the MCP server is `@sandbox-quantum/switch-agent-runtime`,
+ fetched with `npx` and built from `dash/packages/switch-agent-runtime/`.
+ switchdash imports the same package for its protocol client, so there is one
+ implementation of the agent protocol rather than a copy per consumer.
+- `connectors/codex-plugin/` — manifest `.codex-plugin/plugin.json`. Ships
+ **only** the skill. Codex does not expand `${VAR}` in a plugin-bundled
+ `.mcp.json` and has no `${CLAUDE_PLUGIN_ROOT}` equivalent, so switchdash
+ registers the same local `switch-agent-runtime` MCP server itself when it
+ launches the session — through a per-agent Codex profile
+ (`$CODEX_HOME/<slug>.config.toml`, launched with `--profile <slug>`), since a
+ stdio server cannot be expressed on argv the way an HTTP one can.
When you change how agents interact with Switch — new/changed MCP tools, in-room
commands, room workflow, or anything an agent-facing client needs to know:
-- **Update the skill** (`connectors/claude-code-plugin/skills/switch/SKILL.md`)
- so the documented workflow matches the actual behavior.
+- **Update both skills.** A room-workflow change must land in
+ `connectors/claude-code-plugin/skills/switch/SKILL.md` *and*
+ `connectors/codex-plugin/skills/switch/SKILL.md` so the documented workflow
+ matches actual behavior on both hosts.
- **Bump the versions of whatever you changed, in the same commit.** Not at
release time — it gets forgotten, and then a version number is a claim nobody
- can trust. `dash/AGENTS.md` has the table (plugin, runtime package, sidecar)
- and the rules for which digit moves.
+ can trust. `dash/AGENTS.md` has the table (both plugins, runtime package,
+ sidecar) and the rules for which digit moves.
+- **Diff the two skills after editing.** They are deliberately not identical
+ (host-specific wording for tool namespacing, event delivery and task
+ notifications, attachments, and MCP registration), so diff them to confirm
+ every remaining difference is intentional rather than a fix that only landed
+ on one side.
- **Publishing the runtime is a tag**, not a merge:
`git tag switch-agent-runtime-v<version> && git push origin <tag>`. It works
from a branch, so a version can be tested before it lands. The tag must match
@@ -133,11 +151,21 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pyt
## Reference Documentation
-The target architecture docs are in `docs/`:
-- `docs/ARCHITECTURE.md` — system overview
-- `docs/switch-core/CODEBASE.md` — module structure and interfaces
-- `docs/switch-core/DATA_MODEL.md` — database schema
-- `docs/switch-core/ROOM_DESIGN.md` — room design and client types
-- `docs/api/API.md` — HTTP API spec
-- `docs/api/MCP.md` — MCP server spec
-- `docs/bridges/` — bridge specifications
+Everything under `docs/` is listed here; if it is not in this list, it does not
+exist:
+- `docs/ARCHITECTURE.md` — system overview: components, domain model, key flows,
+ entry points, and a code map from area to module
+- `docs/api/AGENT_PROTOCOL.md` — the agent↔Switch protocol (connections, the
+ event stream, room slots, failure handling). Authoritative where it and
+ `ARCHITECTURE.md` overlap
+- `docs/bridges/` — collaboration bridge setup: `README.md` plus one page each
+ for Slack, Mattermost, Discord, and Teams
+
+There is no separate schema, room-design, HTTP-API or MCP-surface document. Read
+those from the code: `core/switch_core/db/models.py` for the schema,
+`core/switch_core/room_service.py` for room provisioning and lifecycle,
+`core/switch_core/bridges/agent/api/handlers.py` for the HTTP surface, and
+`core/switch_core/bridges/agent/operations/definitions.py` for the agent tool
+surface — one definition serves both the MCP server
+(`bridges/agent/mcp/server.py`) and the HTTP front door
+(`bridges/agent/api/operations.py`), so the two cannot drift.
diff --git a/README.md b/README.md
index b7feeaf53..985790794 100644
--- a/README.md
+++ b/README.md
@@ -82,13 +82,19 @@ Once it's up, open:
| Mattermost (chat with agents) | <http://localhost:8065> | `user` / `user1234` |
**First run — connect your own agent.** Switch ships no bundled agents; the
-point is to plug in yours. The quickest path is the **Claude Code connector**
-in [`connectors/claude-code-plugin/`](connectors/claude-code-plugin/):
+point is to plug in yours. The quickest path is a bundled connector — the
+**Claude Code connector** in
+[`connectors/claude-code-plugin/`](connectors/claude-code-plugin/), or the
+**Codex connector** in [`connectors/codex-plugin/`](connectors/codex-plugin/):
1. In the gateway, create a room (and note its id).
-2. Install and configure the connector so Claude Code registers as a Switch
- agent and joins the room — the plugin's `configure` skill walks you through
- registering with this Switch instance and writing the credentials.
+2. Install and configure the connector so your agent registers as a Switch
+ agent and joins the room. For Claude Code, the plugin's `configure` skill
+ walks you through registering with this Switch instance and writing the
+ credentials. The Codex plugin ships the room-workflow skill only — its
+ Switch MCP server is registered by the [switchdash desktop app](dash/) when
+ it launches the session, so set the agent up there; see
+ [`connectors/codex-plugin/README.md`](connectors/codex-plugin/README.md).
3. Talk to the agent from Mattermost, and watch the interaction in the gateway.
Stop the stack with `just standalone-down`, or `just standalone-reset` to also
@@ -172,7 +178,7 @@ The operator dashboard frontend lives in [`gateway/`](gateway/)
| `core/tests/` | Test suite, mirroring the `switch_core/` module structure |
| `gateway/` | Operator dashboard frontend (Node/Vite) |
| `dash/` | The switchdash desktop app |
-| `connectors/` | Agent connectors (`claude-code-plugin`) |
+| `connectors/` | Agent connectors (`claude-code-plugin`, `codex-plugin`) |
| `deploy/` | Deployment assets — Docker Compose stacks (`local/`) and shared resources |
| `justfile` | Repo-root task runner (drives all three code trees) |
diff --git a/connection_model b/connection_model
deleted file mode 100644
index e69de29bb..000000000
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.json
index 219f078e2..4a9d2b4c7 100644
--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json
+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json
@@ -1,5 +1,5 @@
{
"name": "switch-connector",
- "version": "0.7.4",
+ "version": "0.7.5",
"description": "Connect Claude Code to a Switch platform instance as a participating agent"
}
diff --git a/connectors/claude-code-plugin/hooks/switch_hook.py b/connectors/claude-code-plugin/hooks/switch_hook.py
index 01e3ec3b0..19d080d63 100644
--- a/connectors/claude-code-plugin/hooks/switch_hook.py
+++ b/connectors/claude-code-plugin/hooks/switch_hook.py
@@ -6,7 +6,7 @@ Switch Agent Bridge HTTP API for pre/post tool mediation and event reporting.
Config is read from environment variables set in the user's
`.claude/settings.local.json` env block (the same values consumed by the MCP
-servers in `.mcp.json`):
+server in `.mcp.json`):
SWITCH_API_ENDPOINT — Switch server URL
SWITCH_API_TOKEN — Agent API key
CLAUDE_PLUGIN_DATA — Persistent plugin data directory (auto-injected)
@@ -78,13 +78,13 @@ def _parse_response(raw: object) -> dict:
def _channel_port_path() -> str:
- # The bun channel writes its port to ~/.switch/sessions/<ppid>/port,
+ # The Switch agent runtime writes its port to ~/.switch/sessions/<ppid>/port,
# where ppid is the Claude Code session PID. This hook is also a direct
# child of that same Claude Code process, so getppid() returns the same
# value, and both sides resolve to the same path independently.
#
# NOTE: if hooks.json ever wraps this in a shell (e.g. `bash -c "python …"`),
- # the shell becomes the parent and getppid() will not match the channel's
+ # the shell becomes the parent and getppid() will not match the runtime's
# ppid. Keep the hook invocation a direct `python <script>` call.
return os.path.join(
os.path.expanduser("~"), ".switch", "sessions", str(os.getppid()), "port"
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 06caa80ab..8700774b0 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -1,6 +1,6 @@
---
name: switch
-description: REQUIRED before calling ANY `mcp__plugin_switch-connector_switch__*` tool (list_rooms, connect_to_room, read_context, post_message, send_targeted_message, list_participants, delegate_task, accept_task, update_task, finalise_task, cancel_task, list_tasks, create_room, invite_agent_to_room, list_all_rooms, get_room_detail, list_bridges, list_reference_types, create_reference, attach_reference_to_room, link_rooms, unlink_rooms, list_room_groups, create_room_group, get_room_group_detail, list_agents, get_agent_detail, update_agent_detail). Load this skill the moment the user mentions Switch, a Switch room, joining/connecting to a room, listing rooms, posting in a room, creating a room, creating a room group, creating a reference, linking rooms, inspecting or updating an agent, or interacting with other Switch agents — BEFORE you call any tool. The skill explains the room workflow, interaction modes, the task-protocol lifecycle, the moderation tools (room creation, invites, references, links), and the rules you must follow to participate correctly.
+description: REQUIRED before calling ANY `mcp__plugin_switch-connector_switch__*` tool (list_rooms, connect_to_room, read_context, post_message, send_targeted_message, list_participants, list_roles, get_role_detail, assume_role, release_role, define_role, edit_role, delete_role, delegate_task, accept_task, update_task, finalise_task, cancel_task, list_tasks, create_room, invite_agent_to_room, list_all_rooms, get_room_detail, list_bridges, list_reference_types, create_reference, attach_reference_to_room, link_rooms, unlink_rooms, list_room_groups, create_room_group, get_room_group_detail, list_agents, get_agent_detail, update_agent_detail). Load this skill the moment the user mentions Switch, a Switch room, joining/connecting to a room, listing rooms, posting in a room, creating a room, creating a room group, creating a reference, linking rooms, inspecting or updating an agent, or interacting with other Switch agents — BEFORE you call any tool. The skill explains the room workflow, interaction modes, the task-protocol lifecycle, the moderation tools (room creation, invites, references, links), and the rules you must follow to participate correctly.
---
# Switch Room Workflow
@@ -27,21 +27,23 @@ the same connection — you never talk to the Switch server directly.
package carries its own `instructions` field — read those carefully,
they tell you how to use that specific resource. The `linked_rooms`
array advertises related rooms — see "Linked rooms" below.
-3. **Delivery starts automatically.** Once `connect_to_room` succeeds, a
- plugin hook tells the channel process which room you are in, and it
- claims that room on its push connection to Switch. Events arrive as
- `<channel>` notifications as they happen — no separate tool call is
- needed. Switching rooms (calling `connect_to_room` with a new
- `room_id`) re-targets delivery automatically.
+3. **Delivery starts automatically.** `connect_to_room` claims the room on
+ the connection your tool calls travel over — the same one that delivers
+ your events — so events arrive as `<channel>` notifications as they
+ happen, with no separate tool call. Switching rooms (calling
+ `connect_to_room` with a new `room_id`) re-targets delivery
+ automatically.
4. **Read context** — call `read_context` to see the conversation history.
Always read before contributing. It returns the timeline **grouped into
threads**: a list of `{root, replies: [...]}` ordered by latest activity
(freshest last). Top-level messages are roots with an empty `replies`
list. Every message carries an `id` — use it as `thread_id` to reply into
that thread (see "Threads" below).
-5. **Check participants** — call `list_participants` to see who else is in
- the room, the room role each currently holds (if any), their `agent_type`,
- and their task capabilities.
+5. **Check participants** — call `list_participants` for the current roster
+ (`id`, `name`, `type`, `status`, `alias`). Each participant's
+ `agent_type`, task capabilities and room role come from the
+ `participants` array in the `connect_to_room` payload, or from
+ `get_room_detail`.
6. **Act** — see the interaction modes below.
## Interaction modes
@@ -106,10 +108,10 @@ bridge as a real platform file upload (Slack, Mattermost).
retrieved. Say so rather than pretending you saw them.
For an attachment seen in `read_context` history (its `attachments` field)
- that did not arrive with a path, pass its `mxc` to the channel's
- `download_attachment` tool, then Read the returned path. It works for any
- file type.
-- **Sending:** call the channel's **`send_attachment`** tool with either
+ that did not arrive with a path, pass its `mxc` to the
+ **`download_attachment`** tool, then Read the returned path. It works for
+ any file type.
+- **Sending:** call the **`send_attachment`** tool with either
`path` (one file) or `paths` (several — they arrive as **one** message
carrying all of them), plus an optional `caption` and `thread_id` (same
threading semantics as `post_message`). Any file type works. The files
@@ -118,12 +120,17 @@ bridge as a real platform file upload (Slack, Mattermost).
several attachments. Note on Slack the upload renders under the Switch app
identity (Slack file uploads can't carry the per-agent name/icon); your
name is bolded in the file's comment instead.
-- **No channel tool available?** (e.g. a switchdash-managed session where the
- channel process is not running): upload directly to the bridge API —
- `curl -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media"
+- **No Switch MCP server registered?** Then you have no `send_attachment` /
+ `download_attachment` — and no Switch tools at all, so say so. If the
+ session's credentials are nevertheless in your environment, the bridge
+ media endpoint takes the same work directly:
+ `curl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media"
-H "Authorization: Bearer $SWITCH_API_TOKEN" -F "files=@/path/to/report.md"
-F "caption=..."` (optional `-F "thread_id=..."`; repeat `-F "files=@..."`
- for several files in one message). Returns the posted `event_id`.
+ for several files in one message). Returns the posted `event_id`. Download
+ with `-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same
+ URL. If those variables are absent too, do not fabricate an upload or
+ claim an attachment was sent.
- Attachments are capped (20MB by default, server-configurable); oversize
uploads are rejected loudly rather than truncated. A multi-file send is
validated as a whole — if any one file is oversize or unreadable the entire
@@ -170,13 +177,13 @@ outstanding work.
## Reactive event handling
After `connect_to_room` succeeds, events arrive as `<channel>`
-notifications automatically — the channel process holds a push connection
-to Switch and a plugin hook points it at your room, so you don't need to
-call any extra tool. If the connection drops it reconnects and resumes
-from where it stopped, so a brief network blip costs nothing. If events
-were dropped and cannot be replayed, the notification you receive next
-carries a **gap warning** — a line saying earlier events were dropped, plus
-a `gap` entry in its meta. A gap never arrives as a notification of its own
+notifications automatically — the runtime beside you holds a push
+connection to Switch and `connect_to_room` claims your room on it, so you
+don't need to call any extra tool. If the connection drops it reconnects
+and resumes from where it stopped, so a brief network blip costs nothing.
+If events were dropped and cannot be replayed, the notification you receive
+next carries a **gap warning** — a line saying earlier events were dropped,
+plus a `gap` entry in its meta. A gap never arrives as a notification of its own
and never wakes you on its own; it rides along on your next real event. When
you see one, call `read_context` before responding rather than assuming you
have the full picture. **Only messages addressed to you,
@@ -194,6 +201,19 @@ or the gateway create-room / room-detail pages. When you do receive one,
react if relevant (e.g. greet a new arrival and explain the room). Your
own join never produces one.
+**Under a supervisor, the same events arrive as text instead.** A session
+switchdash launched shares its connection: switchdash reads the stream and
+delivers each event into your session as a `[Switch] …` line rather than a
+`<channel>` notification, so you are not told twice. What is delivered, what
+is filtered out, the unread count and the gap warning are all the same
+either way; only the shape differs. Attachments come as a parenthetical
+naming local paths rather than as `image_path` / `file_path`, and a
+`[Switch] Task delegated to you …` line carries the summary and description
+but **not** the task id — get that from
+`list_tasks(role='assigned', status='pending')`. Handle whichever form you
+get; if neither has ever arrived, nothing is delivering events to you and
+`read_context` is your only source.
+
**Always `read_context` to catch up on unaddressed messages:**
- **Right after `connect_to_room`** — pull recent history so you know
@@ -205,6 +225,8 @@ own join never produces one.
up any unaddressed messages that landed between the previous one you
saw and the current one. Do not rely on the notification body alone;
it is one line of context out of a possibly busy conversation.
+- **Before posting anything substantive**, if it has been a while since
+ your last `read_context` — the room may have moved on.
When you receive an event:
@@ -284,9 +306,9 @@ applies.
- **`list_agents`** — list every agent on the instance (vs
`list_participants`, which is scoped to the connected room). Optional
filters, ANDed: `name_contains` (case-insensitive substring),
- `owner_name` (exact), `known_agent_type` (e.g. `"claude-code"`).
- Returns agent summaries sorted by name; use `get_agent_detail` for one
- agent's full detail.
+ `owner_name` (exact), `known_agent_type` (e.g. `"codex"`,
+ `"claude-code"`). Returns agent summaries sorted by name; use
+ `get_agent_detail` for one agent's full detail.
- **`list_room_groups`** / **`get_room_group_detail`** — room groups are a
navigation/organization layer: a room belongs to at most one group, and
groups nest under a parent group to form a tree. `list_room_groups`
@@ -305,9 +327,12 @@ applies.
- **`update_agent_detail`** — change an agent's editable settings.
**Owner-only**: you may only update an agent whose owner matches your own
owner. `options` is a PARTIAL map of known-agent options merged over the
- current ones (for a claude-code agent: `repo_dir` (working directory),
- `channels_enabled`, `notify_user`, `subagent_name`) — only the keys you
- pass change. `parent_agent_id` sets the agent's parent (validated against
+ current ones — the keys differ per known-agent type. For `codex`:
+ `repo_dir` (working directory), `notify_user`, `auto_session`. For
+ `claude-code`: those plus `channels_enabled` and `subagent_name`. Only the
+ keys you pass change, and a key the type does not define is ignored rather
+ than rejected — so check the returned detail rather than assuming a write
+ landed. `parent_agent_id` sets the agent's parent (validated against
self-parenting and cycles); `clear_parent=true` detaches it to top-level.
- **`list_reference_types`** — discover the Reference sub-types this
instance supports, including the per-type `value_schema`. Call this
@@ -317,7 +342,9 @@ applies.
Drive, Confluence, GitHub — call `list_reference_types` for the full
list).
Required: `type`, `name`, `description`, `instructions`, `value`.
- Optional: `visibility` (defaults to `"private"`). The reference is
+ Optional: `read_visibility` / `write_visibility` (both default
+ `"private"`; `write_visibility` must not be `"public"` while
+ `read_visibility` is `"private"`). The reference is
owned by your agent's user. Use the `instructions` field to tell
other agents how to USE the reference — what's in it, when to consult
it, any caveats.
@@ -462,7 +489,7 @@ an alias only resolves in the room it was set in.
- **Read before responding.** Always call `read_context` (with `since`
when handling events) to understand what has been discussed.
- **One room at a time.** Calling `connect_to_room` with a different room
- disconnects from the current one. Polling automatically re-targets to
+ disconnects from the current one. Delivery automatically re-targets to
the new room.
- **Governance is enforced.** Your tool calls (Bash, Edit, Write, etc.)
are submitted to Switch for mediation before execution. If Switch denies
@@ -486,7 +513,7 @@ an alias only resolves in the room it was set in.
## Formatting messages for bridged channels
Your messages render on whatever external platform the room is bridged to
-(check `bridge_display_name` in the `connect_to_room` / `get_room_detail`
+(check `bridge_display_name` in the `get_room_detail`
payload). The platforms do **not** render Markdown identically, so adapt:
- **Slack** renders only a *subset* of Markdown (mrkdwn). **Bold**,
@@ -542,6 +569,23 @@ are listed in the `connect_to_room` payload (`roles`) and via `list_roles`.
- **`release_role()`** — drop the role you hold (idempotent). Ending your
session also releases it automatically.
+**Creating and editing roles.** The three tools above consume roles someone
+else defined; these author them. All three act on the **connected room** and
+require write access to it, so they are moderation tools — use them when you
+are setting a room up, not in passing.
+
+- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`
+ must be unique within the room. `instructions` is the bundle `assume_role`
+ hands whoever takes it, so write it as instructions *to that agent*, not as
+ a description of the role. Set `exclusive` when at most one live agent may
+ hold it at a time.
+- **`edit_role(name, instructions=None, exclusive=None)`** — change a role's
+ instructions and/or its exclusivity; omit a field to leave it as is. Edits
+ apply on the **next** `assume_role` — an agent already holding the role
+ keeps the instructions it was given, so ask it to release and re-assume if
+ the change is meant to reach it now.
+- **`delete_role(name)`** — remove the role and any lease on it.
+
**Exclusive vs shared.** An `exclusive` role admits at most one live holder:
it is leased to you with a fast heartbeat while your session stays alive and
**auto-releases shortly after you disconnect**, so another agent can take
@@ -566,8 +610,8 @@ tell whether a holder is reachable in this room right now.
- `connect_to_room` — when entering a room. Pass
`include_general_instructions=False` since this skill already covers the
general Switch workflow. Read every resource's `instructions` field in
- the response (references, documents, packages). Polling for the room
- starts automatically via a plugin hook — no separate step.
+ the response (references, documents, packages). Delivery of the room's
+ events follows automatically — no separate step.
- `read_context` — to understand history before contributing. Use `since`
when responding to events to avoid re-reading.
- `list_linked_rooms` — to refresh the current room's outbound pointers
@@ -584,6 +628,9 @@ tell whether a holder is reachable in this room right now.
- `assume_role` / `release_role` — take on (and later drop) a room-scoped
role and its instruction bundle. One role at a time; exclusive roles are
leased with auto-release on disconnect.
+- `define_role` / `edit_role` / `delete_role` — author the roles others
+ assume. Moderation tools: they need write access to the connected room, and
+ an edit only reaches a holder on its next `assume_role`.
- `delegate_task` / `accept_task` / `update_task` / `finalise_task` /
`cancel_task` / `list_tasks` — for tracked, formal work.
- `list_bridges` — before creating a room, to discover the available
@@ -596,7 +643,7 @@ tell whether a holder is reachable in this room right now.
- `list_all_rooms` / `get_room_detail` — enumerate every room on the
instance, and inspect a room's members and configuration.
- `list_agents` — list every agent on the instance (optionally filtered
- by name, owner, known-agent type, or role).
+ by name, owner, or known-agent type).
- `list_room_groups` / `get_room_group_detail` — see how rooms are
organized into groups, and inspect one group's members + subgroups.
- `create_room_group` — provision a new room group (optionally nested
diff --git a/connectors/codex-plugin/.codex-plugin/plugin.json b/connectors/codex-plugin/.codex-plugin/plugin.json
new file mode 100644
index 000000000..e9e15348e
--- /dev/null
+++ b/connectors/codex-plugin/.codex-plugin/plugin.json
@@ -0,0 +1,6 @@
+{
+ "name": "switch-connector-codex",
+ "version": "0.1.4",
+ "description": "Connect Codex to a Switch platform instance as a participating agent",
+ "skills": "./skills/"
+}
diff --git a/connectors/codex-plugin/README.md b/connectors/codex-plugin/README.md
new file mode 100644
index 000000000..888e2bb47
--- /dev/null
+++ b/connectors/codex-plugin/README.md
@@ -0,0 +1,77 @@
+# switch-connector (Codex)
+
+The Codex build of the Switch connector plugin. It ships the **Switch
+room-workflow skill** (`skills/switch/SKILL.md`) — the room workflow,
+interaction modes, thread semantics, task protocol, room roles, and
+moderation tools an agent needs in order to participate in a Switch room
+correctly.
+
+Manifest: `.codex-plugin/plugin.json`. Registered in the repo marketplace
+(`.claude-plugin/marketplace.json`) as `switch-connector-codex`.
+
+This is the sibling of `connectors/claude-code-plugin/`, which additionally
+ships an MCP config and hooks. Those pieces are Claude Code-specific and are
+deliberately **not** part of this plugin.
+
+## The Switch MCP server is not registered by this plugin
+
+Codex does **not** expand `${VAR}` inside a plugin-bundled `.mcp.json`, and
+there is no `${CLAUDE_PLUGIN_ROOT}` equivalent for a plugin to reference its
+own install path. A bundled MCP config would therefore be shipped with
+unresolvable placeholders — it would either fail loudly or, worse, connect
+with literal `${SWITCH_API_TOKEN}` text. So this plugin ships no `.mcp.json`
+and never references its own path.
+
+Instead, **switchdash registers the Switch MCP server when it launches the
+Codex session** — as a per-agent Codex *profile*. It writes
+`$CODEX_HOME/<agent-slug>.config.toml` (under `~/.codex`) declaring the local
+`@sandbox-quantum/switch-agent-runtime` over stdio and launches Codex with
+`--profile <agent-slug>`. The profile is static and holds no secret: it lists
+the variables the runtime needs — `SWITCH_API_ENDPOINT` / `SWITCH_API_TOKEN` /
+`SWITCH_AGENT_ID` (and `SWITCH_CONNECTION_ID`) — under `env_vars`, and Codex
+forwards those by name from its own environment, which switchdash populates
+from the agent's `.switch/agents/<slug>.json`. Naming them is not optional:
+Codex hands an MCP server a fixed allowlist (`HOME`, `PATH`, `SHELL`, `USER`,
+`TMPDIR`, …) rather than a copy of its own environment, so a server that names
+nothing starts with no credentials and dies before the MCP handshake — which
+the session reports only as `connection closed: initialize response`. The
+`env_vars` list also carries the npm settings `npx` needs to fetch the runtime
+from its private registry.
+
+A profile does *not* replace a same-named server in the user's base
+`~/.codex/config.toml` — the two tables are merged. A base `switch` entry from
+the pre-profile design declares a `url`, which merges with this profile's
+`command` into a server that is both, and Codex then refuses to load the config
+at all. switchdash removes such an entry when it writes the profile. The skill
+assumes the Switch tools are present under the `switch` server; if they are
+missing, the session was launched without the profile.
+
+A stdio server is used rather than the argument-vector overrides Codex also
+accepts (`-c mcp_servers.switch.*`) because the profile is the single unit
+that also carries per-agent model, reasoning effort, and instructions.
+
+## What the registered runtime gives a Codex session
+
+The runtime is the same package the Claude Code connector registers, so a
+Codex session gets the same tool surface: every Switch operation the agent
+bridge advertises, plus the runtime's own `send_attachment` and
+`download_attachment`. Neither is gated on which process owns the
+connection, so the skill documents the tools rather than `curl` against the
+bridge media endpoint — that is now only the fallback for a session with no
+Switch MCP server at all.
+
+Events are the part that differs from Claude Code. Codex has no channel of
+its own to receive MCP notifications, so switchdash opens the session's
+event connection itself, hands the id over as `SWITCH_CONNECTION_ID`, and
+delivers what arrives into the session's pane as `[Switch] …` lines. The
+runtime borrows that connection rather than opening a second one: the
+session's `connect_to_room` therefore claims the room on the connection
+switchdash is reading, which is how switchdash learns which room the session
+is in — no tool-response scraping, and no per-session room-tracking hook.
+
+One caveat on remote hosts: room tracking depends on that connection, which
+switchdash opens only for a session it can keep attached — i.e. a tmux session.
+A remote session started with tmux disabled gets the Switch MCP tools (the
+profile is still written) but no `SWITCH_CONNECTION_ID`, so it never claims a
+room server-side and receives no `[Switch]` events. Run remote Codex agents
+with tmux (the default) for room participation.
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
new file mode 100644
index 000000000..68f38961d
--- /dev/null
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -0,0 +1,680 @@
+---
+name: "switch"
+description: "REQUIRED before calling ANY tool on the `switch` MCP server (list_rooms, connect_to_room, read_context, post_message, send_targeted_message, list_participants, list_roles, get_role_detail, assume_role, release_role, define_role, edit_role, delete_role, delegate_task, accept_task, update_task, finalise_task, cancel_task, list_tasks, create_room, invite_agent_to_room, list_all_rooms, get_room_detail, list_bridges, list_reference_types, create_reference, attach_reference_to_room, link_rooms, unlink_rooms, list_room_groups, create_room_group, get_room_group_detail, list_agents, get_agent_detail, update_agent_detail). Load this skill the moment the user mentions Switch, a Switch room, joining/connecting to a room, listing rooms, posting in a room, creating a room, creating a room group, creating a reference, linking rooms, inspecting or updating an agent, or interacting with other Switch agents — BEFORE you call any tool. The skill explains the room workflow, interaction modes, the task-protocol lifecycle, the moderation tools (room creation, invites, references, links), and the rules you must follow to participate correctly."
+---
+
+# Switch Room Workflow
+
+You are connected to a **Switch** platform instance. Switch orchestrates AI
+agents in collaborative rooms using the Matrix protocol as the internal
+message bus.
+
+## How to participate
+
+All Switch tools are served by a local runtime running beside you,
+registered as the `switch` MCP server. This plugin does **not** bundle it:
+switchdash registers it when it launches your session, through a per-agent
+Codex profile (`--profile <name>`). Tool calls travel that runtime's
+connection to Switch, so you never talk to the Switch server directly. If
+the Switch tools are missing, the session was launched without the profile;
+say so rather than guessing.
+
+1. **List your rooms** — call `list_rooms` to see which rooms you are
+ assigned to.
+2. **Connect to a room** — call
+ `connect_to_room(room_id, include_general_instructions=False)`. **You
+ already have the general Switch usage instructions from this skill**, so
+ pass `include_general_instructions=False` to skip the room-onboarding
+ text and avoid duplicating it. You still receive room-specific resources
+ in the response: `participants`, `references`, `documents`, `packages`,
+ `reference_types`, and `linked_rooms`. Each reference, document, and
+ package carries its own `instructions` field — read those carefully,
+ they tell you how to use that specific resource. The `linked_rooms`
+ array advertises related rooms — see "Linked rooms" below.
+3. **Delivery starts automatically.** `connect_to_room` claims the room on
+ the connection your session was launched with, and switchdash — which
+ holds that connection — delivers the room's events into your session as
+ `[Switch] …` lines. No separate tool call is needed, and calling
+ `connect_to_room` with a new `room_id` re-targets delivery. See
+ "Receiving room events" below for what does and does not arrive.
+4. **Read context** — call `read_context` to see the conversation history.
+ Always read before contributing, and read again whenever a `[Switch]`
+ line hands you a room event: unaddressed room chatter is never delivered,
+ so `read_context` is your only complete view of the room. It returns the
+ timeline **grouped into threads**: a list of `{root, replies: [...]}`
+ ordered by latest activity (freshest last). Top-level messages are roots
+ with an empty `replies` list. Every message carries an `id` — use it as
+ `thread_id` to reply into that thread (see "Threads" below).
+5. **Check participants** — call `list_participants` for the current roster
+ (`id`, `name`, `type`, `status`, `alias`). Each participant's
+ `agent_type`, task capabilities and room role come from the
+ `participants` array in the `connect_to_room` payload, or from
+ `get_room_detail`.
+6. **Act** — see the interaction modes below.
+
+## Interaction modes
+
+You have three ways to participate. Pick the one that fits the situation:
+
+- **`post_message`** — broadcast to the room. Everyone sees it; other
+ agents receive it as *unaddressed* context (no expected action). Use for
+ discussion, results, status updates, replying to messages addressed to
+ you. **Do not write `@agent-name` mentions in the body** — see the
+ "No stray @-mentions" rule below. If you need a specific agent to act,
+ use `send_targeted_message` (which prepends the mentions for you) instead.
+- **`send_targeted_message`** — broadcast with `@mentions` prepended for
+ specific agents or users. They receive it as an *addressed* event and
+ will respond; others see it as context. Use when you need a specific
+ participant to act, but the request is informal (a question, a nudge, a
+ handoff) and doesn't need lifecycle tracking. Pass
+ `target_names=["agent_a", "user_b"]` and a `body`. You can also address
+ **roles** with `target_roles=["manager"]` to reach whoever currently
+ holds a role without naming the agent — it fans out to every live holder
+ (see "Room roles" below). At least one of `target_names` / `target_roles`
+ is required.
+- **Task protocol** (`delegate_task`, `accept_task`, `update_task`,
+ `finalise_task`, `cancel_task`, `list_tasks`) — formal tracked work with
+ a persistent lifecycle (`pending` → `ongoing` → `finalised` /
+ `cancelled`). Use when the work is concrete, the outcome matters, and
+ you may want to check on it later.
+
+**Rule of thumb:** message → conversation; targeted message → request a
+synchronous response; task → request tracked work.
+
+## Threads
+
+Both `post_message` and `send_targeted_message` accept an optional
+`thread_id` to post a **threaded reply** instead of a top-level message:
+
+- `thread_id` is the `id` of any message in the thread (a root or a reply) —
+ it is normalised to the thread root, so you can pass whatever id you have.
+- Omit `thread_id` for a normal top-level message (default).
+- Get ids from `read_context` (each message has an `id`) or from the
+ `message_id` / `thread_id` in the `[Switch]` line that handed you the
+ message — a `thread_id` appears there only when the message is already in
+ a thread. When a message you receive carries a `thread_id`, **reply with
+ that same `thread_id`** so the conversation stays in its thread rather
+ than fragmenting to the top level.
+- Threads bridge to/from Mattermost natively. You are only *delivered*
+ threaded replies that address you; pull unaddressed thread activity with
+ `read_context` as usual.
+
+## Sending and receiving attachments
+
+Messages can carry file attachments of **any type** — images, `.md`, `.csv`,
+`.pdf`, logs, code — and a single message can carry **several**. Both
+directions work in any room; on bridged rooms the attachment crosses the
+bridge as a real platform file upload (Slack, Mattermost).
+
+- **Receiving:** an addressed message with attachments is delivered with the
+ files already downloaded for you. The `[Switch]` line is followed by a
+ parenthetical naming the local paths — images and other files listed
+ separately — plus any attachment that could **not** be retrieved. Read the
+ paths; say so rather than pretending you saw an attachment reported as
+ failed.
+
+ For an attachment seen in `read_context` history (its `attachments` field)
+ that did not arrive with a path, pass its `mxc` to the
+ **`download_attachment`** tool, then read the returned path. It works for
+ any file type.
+- **Sending:** call the **`send_attachment`** tool with either `path` (one
+ file) or `paths` (several — they arrive as **one** message carrying all of
+ them), plus an optional `caption` and `thread_id` (same threading
+ semantics as `post_message`). Any file type works. The files enter the
+ room as native image/file events; bridges relay them out as platform file
+ uploads, and a multi-file send lands as a single post with several
+ attachments. Note on Slack the upload renders under the Switch app
+ identity (Slack file uploads can't carry the per-agent name/icon); your
+ name is bolded in the file's comment instead.
+- **No Switch MCP server registered?** Then you have no `send_attachment` /
+ `download_attachment` — and no Switch tools at all, so say so. If the
+ session's credentials are nevertheless in your environment, the bridge
+ media endpoint takes the same work directly:
+ `curl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media"
+ -H "Authorization: Bearer $SWITCH_API_TOKEN" -F "files=@/path/to/report.md"
+ -F "caption=..."` (optional `-F "thread_id=..."`; repeat `-F "files=@..."`
+ for several files in one message). Returns the posted `event_id`. Download
+ with `-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same
+ URL. If those variables are absent too, do not fabricate an upload or
+ claim an attachment was sent.
+- Attachments are capped (20MB by default, server-configurable); oversize
+ uploads are rejected loudly rather than truncated. A multi-file send is
+ validated as a whole — if any one file is oversize or unreadable the entire
+ call fails and **nothing** is posted, rather than quietly dropping it.
+
+**Match the mode to the recipient's `agent_type`:**
+- `always_on` — safe to use targeted messages; prompt response expected.
+- `session_addressable` — targeted messages work when the agent is in an
+ active session; otherwise delivery is deferred.
+- `session_passive` — **do not** expect a synchronous response. Prefer
+ `delegate_task` so the work is queued and picked up when the agent next
+ reads room context.
+
+## Task protocol
+
+If your `instructions` indicate you have task capabilities:
+
+- **Delegating** (`can_delegate=true`):
+ 1. Call `delegate_task(performer_agent_id, summary, description)`. Task
+ starts in `pending` until the performer accepts.
+ 2. Progress is delivered to you as `[Switch] Task …` lines — acceptance,
+ each `update`, and the final `outcome`, each naming the `task_id`.
+ `list_tasks(role='delegated')` enumerates the same state on demand.
+ 3. Call `cancel_task(task_id, reason)` to abandon a task that is no
+ longer needed.
+
+ Note: a performer may have a **scoped addressing policy** restricting who can
+ address it. If you are not permitted, `delegate_task` fails with a permission
+ error (delegating is a form of addressing). This is expected — do not retry;
+ reach the performer another way or ask an operator. The same policy silently
+ drops disallowed `@name` / targeted messages (you'll get a one-line "not
+ permitted to address me here" reply instead of a response).
+
+- **Accepting** (`can_accept=true`):
+ 1. A delegation is delivered as `[Switch] Task delegated to you in room …`.
+ That line carries the summary and description but **not** the task id —
+ call `list_tasks(role='assigned', status='pending')` to find it, then
+ `accept_task(task_id)` to move the task to `ongoing`.
+ 2. Optionally call `update_task(task_id, update)` with progress messages
+ while you work — these are persisted to the task record.
+ 3. Call `finalise_task(task_id, outcome)` when done. The `outcome` is a
+ single string describing what happened (success or failure).
+
+Call `list_tasks(role='delegated'|'assigned', status=...)` to enumerate
+outstanding work.
+
+## Receiving room events
+
+Room events reach you as **`[Switch] …` lines delivered into this session**
+by switchdash, which holds your session's connection to Switch. They are not
+MCP notifications: they arrive in your input the way a message from the
+operator does. If your session was not started by switchdash, nothing
+delivers events to you at all and `read_context` is your only source — say
+so rather than waiting for a line that will never come.
+
+**What is delivered:**
+
+- **Messages addressed to you** — `[Switch] <sender> addressed you in room
+ <room> (message_id …[, thread_id …]): <body>`, followed by a parenthetical
+ naming any downloaded attachments.
+- **Task events** — delegation, acceptance, each update, finalisation and
+ cancellation, as `[Switch] Task …` lines. A delegation line omits the task
+ id; see "Task protocol" above.
+- **`room_join`** — `[Switch] <name> joined room <room>`, but only in rooms
+ where an operator opted you in to join events (per-room, per-agent, off by
+ default — set via the `join_event_listeners` argument on `create_room` /
+ `update_room`, or the gateway create-room / room-detail pages). New
+ arrivals also show up in `list_participants`. Your own join never produces
+ one. When you do learn of one, react if relevant (e.g. greet the new
+ arrival and explain the room).
+
+**What is not:** unaddressed room chatter — other agents talking to each
+other, broadcast updates, the user discussing things without `@`-mentioning
+you — is filtered out and never delivered. You must pull it yourself. A
+delivered line tells you how far behind you have fallen: when unaddressed
+messages were filtered out since your last `read_context`, the line ends
+with `(N unread room messages since your last read_context — call
+read_context to catch up.)`.
+
+**Gap warnings.** If the connection drops it reconnects and resumes from
+where it stopped, so a brief network blip costs nothing. If room events were
+dropped and cannot be replayed, the next line you receive ends with `(Some
+earlier room events were dropped and cannot be replayed: <reason> — call
+read_context before responding.)`. A gap never arrives on its own and never
+interrupts you on its own; it rides along on the next real event. When you
+see one, call `read_context` before responding rather than assuming you have
+the full picture.
+
+**Always `read_context` to catch up on unaddressed messages:**
+
+- **Right after `connect_to_room`** — pull recent history so you know what
+ is going on in the room, even if nothing has been delivered yet. Delivery
+ carries what arrives from the moment your session's connection opened; it
+ is not a substitute for history.
+- **Every time a `[Switch]` line hands you an event** — call `read_context`
+ with `since` set to a few minutes ago (lines are delivered as the event
+ happens, so they carry no timestamp of their own), and you pick up the
+ unaddressed messages that landed between the previous event you saw and
+ this one. Do not rely on the delivered line alone; it is one line of
+ context out of a possibly busy conversation.
+- **Before posting anything substantive**, if it has been a while since
+ your last `read_context` — the room may have moved on.
+
+When you receive an event:
+
+1. **Read recent context** — call `read_context` with `since` set to a few
+ minutes before the event reached you. This gives you the recent
+ conversation, including the unaddressed messages delivery did not carry.
+2. **Understand what is being asked** — review the context and the event
+ content.
+3. **Act and respond** — do the work, then use the appropriate interaction
+ mode (message, targeted message, or task) to share results or progress.
+
+## Linked rooms
+
+Rooms can advertise **directed pointers** to other Switch rooms — typically
+a hub room pointing at its support / feature / workstream rooms, or
+parallel workstream rooms cross-referencing each other. These pointers are
+metadata only: they tell you that *another* room exists and is related to
+the one you are in. They do **not** grant you access to that other room.
+
+The `connect_to_room` response includes a `linked_rooms` array, and you
+can refresh it any time by calling `list_linked_rooms`. Each entry has:
+
+- `target_room_id` — the linked room's id (use it for `connect_to_room`).
+- `target_room_name` / `target_room_description` — what the target room is.
+- `label` — a free-text relationship hint set by the operator (e.g.
+ `"support"`, `"parent project"`, `"depends on"`). Read it; it tells you
+ *why* the rooms are connected.
+- `access` — explicit string:
+ - `"member"` — you are assigned to the target room and may call
+ `connect_to_room(target_room_id)` directly.
+ - `"not_member"` — you are NOT assigned. The connect call will fail.
+ Do not try it; ask the room's operator (the human user, typically) to
+ add you first. A `not_member` entry also carries an `access_note`
+ spelling this out.
+
+**Following a link** means calling `connect_to_room(target_room_id)`. Note
+this disconnects you from the current room (one room at a time). If you
+need to compare or move work between two linked rooms, treat the hop
+explicitly — read context, do the work, then connect back.
+
+**The link is one-way.** A pointer from A → B does NOT imply a pointer
+from B → A. If you connect to B, its own `linked_rooms` may be empty or
+point at entirely different rooms.
+
+## Moderation: creating rooms and inviting agents
+
+You can create new rooms and invite agents into them. These tools are
+available to any agent — the responsibility for using them well still
+applies.
+
+- **`list_bridges`** — discover the collaboration bridges configured on
+ this Switch instance. Returns `{id, type, display_name, status,
+ is_default}` per bridge. Only `status == "active"` bridges are usable
+ for new rooms. `is_default` marks the bridge `create_room` uses when no
+ `bridge_id` is given (at most one per instance).
+- **`create_room`** — provision a new room. Required: `name`,
+ `description`, `agent_names`. Optional but commonly used: `bridge_id`,
+ `internal_only` (opt out of the default bridge — see "Prefer bridged
+ rooms" below), `channel_type` (`"channel_public"`, `"channel_private"`,
+ or `"direct"` for a 1:1 DM — see "DM rooms" below), `user_names`,
+ `instructions`,
+ `reference_ids`, `package_ids`, `linked_rooms`, `join_event_listeners`
+ (subset of `agent_names` that should receive `room_join` events in the
+ room — off by default). Returns
+ `{id, name, matrix_room_id, failed_attachments}`.
+- **`invite_agent_to_room`** — add an existing agent to an existing room
+ by name. Humans (and agents) can do the same from inside a room with the
+ `!invite-agent @agent-name` in-room command (also exposed as the
+ `/invite-agent` Slack slash command on bridged Slack channels).
+- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on
+ the instance (not just rooms you are in), and fetch a room's members /
+ channel type / admin mode. `get_room_detail` also returns the room's
+ assumable `roles` (same shape as `list_roles`: each with `name`,
+ `exclusive`, `instructions_preview`, `held_by` holders with presence, and
+ `assumable_by_me`).
+- **`list_agents`** — list every agent on the instance (vs
+ `list_participants`, which is scoped to the connected room). Optional
+ filters, ANDed: `name_contains` (case-insensitive substring),
+ `owner_name` (exact), `known_agent_type` (e.g. `"codex"`,
+ `"claude-code"`). Returns agent summaries sorted by name; use
+ `get_agent_detail` for one agent's full detail.
+- **`list_room_groups`** / **`get_room_group_detail`** — room groups are a
+ navigation/organization layer: a room belongs to at most one group, and
+ groups nest under a parent group to form a tree. `list_room_groups`
+ enumerates every group with its room count and root-first `path`;
+ `get_room_group_detail` returns one group plus the rooms directly in it
+ (`member_rooms`) and its immediate `child_groups`.
+- **`create_room_group`** — provision a new room group. Required: `name`.
+ Optional: `description`, `color`, `parent_group_name` (resolved by name,
+ must be unique — nest under it; omit for a top-level group). Creating a
+ group does not move any rooms into it. File rooms under it later by
+ passing `group_name` to `create_room`.
+- **`get_agent_detail`** — fetch full detail for any agent on the instance:
+ its config, capabilities, `known_agent_type` / `known_agent_options`,
+ `integration_profile`, room memberships, live sessions, and child
+ subagents. Readable by any agent.
+- **`update_agent_detail`** — change an agent's editable settings.
+ **Owner-only**: you may only update an agent whose owner matches your own
+ owner. `options` is a PARTIAL map of known-agent options merged over the
+ current ones — the keys differ per known-agent type. For `codex`:
+ `repo_dir` (working directory), `notify_user`, `auto_session`. For
+ `claude-code`: those plus `channels_enabled` and `subagent_name`. Only the
+ keys you pass change, and a key the type does not define is ignored rather
+ than rejected — so check the returned detail rather than assuming a write
+ landed. `parent_agent_id` sets the agent's parent (validated against
+ self-parenting and cycles); `clear_parent=true` detaches it to top-level.
+- **`list_reference_types`** — discover the Reference sub-types this
+ instance supports, including the per-type `value_schema`. Call this
+ before `create_reference` if you don't already know what `type` and
+ `value` shape to use.
+- **`create_reference`** — create a new external Reference (e.g. Google
+ Drive, Confluence, GitHub — call `list_reference_types` for the full
+ list).
+ Required: `type`, `name`, `description`, `instructions`, `value`.
+ Optional: `read_visibility` / `write_visibility` (both default
+ `"private"`; `write_visibility` must not be `"public"` while
+ `read_visibility` is `"private"`). The reference is
+ owned by your agent's user. Use the `instructions` field to tell
+ other agents how to USE the reference — what's in it, when to consult
+ it, any caveats.
+- **`attach_reference_to_room`** — attach an existing Reference to an
+ existing room. Standalone version of the `reference_ids` field on
+ `create_room`. Authorization: your agent's owner must be able to
+ access the reference (public, owned, or admin).
+- **`link_rooms`** — create a directed link from one room to another
+ with a free-text `label` describing the relationship (e.g.
+ `"support"`, `"parent project"`, `"depends on"`). Links are one-way;
+ call again with source/target swapped to make it bidirectional.
+- **`unlink_rooms`** — the inverse of `link_rooms`: remove the directed
+ link from one room to another so it no longer appears in the source
+ room's `linked_rooms`. Links are one-way, so this removes only the
+ `source → target` direction; call again with source/target swapped to
+ remove the reverse link too. Errors if no such link exists.
+
+### Prefer bridged rooms — and let the user pick the bridge
+
+The point of Switch is collaboration between agents and humans, so
+**rooms are bridged by default**. Omitting `bridge_id` no longer makes an
+isolated room — it uses the instance's **default bridge** (on a standalone
+deployment, the bundled Mattermost). That means a room is readable by
+humans without you having to know the deployment's topology.
+
+To create a room with **no** external channel, pass `internal_only=True`.
+Do that only when the user has explicitly said the room should not bridge
+anywhere — e.g. "just a scratch room for agents to coordinate."
+
+**Do not guess a `bridge_id`.** Workflow when the user asks you to
+create a room:
+
+1. Call `list_bridges`.
+2. Show the user the active bridges (display name + type), noting which is
+ `is_default`, and ask which to use (or whether to skip bridging).
+3. Pass their chosen `bridge_id` (and `channel_type`, usually
+ `"channel_public"` or `"channel_private"`) to `create_room`. Omit
+ `bridge_id` to accept the default; pass `internal_only=True` if they
+ want no channel at all.
+
+If the instance has a default bridge and the room is clearly for
+collaboration, it is reasonable to just accept the default without
+enumerating — but still confirm the room itself before creating.
+
+If the instance has **no** default configured and you omit `bridge_id`,
+the room is created internal-only.
+
+### DM rooms (1:1 with a user)
+
+To open a private 1:1 conversation between a single agent and a single
+human, create a room with `channel_type="direct"` — exactly one entry in
+`agent_names` and one in `user_names`, on a bridge. In a `direct` room the
+agent is addressed by *every* message (no `@`-mention needed), so it feels
+like a real DM.
+
+- **Slack**: there is no app-creatable native DM, so the room is
+ provisioned as a *private channel* named `dm-<user>-<agent>` with that
+ user invited.
+- **Mattermost**: DMs are user-initiated from the client, so creating a
+ `direct` room here fails — the user starts the DM with the agent's bot
+ and Switch picks it up automatically.
+
+The user must already be known to Switch on the bridge (they have messaged
+the workspace before). If they are not, creation fails loudly with
+`no user '<name>' is known on this bridge` — there is no way to invite a
+never-seen user by name. Surface that error to the user rather than
+retrying. As with any room, confirm the agent + user before creating.
+
+### Attachments at creation
+
+`create_room` accepts `reference_ids`, `package_ids`, and `linked_rooms`
+to seed the new room with content at creation time. Authorization for
+references and packages is checked against the *owner of your agent
+account* — you can only attach resources that owner can access. Bad ids
+or access denials abort creation before the room is provisioned.
+
+Race-time attachment failures (rare) do not abort the room. They show
+up in `failed_attachments` on the response as
+`[{kind, id, error}, ...]`. If that list is non-empty, surface it to
+the user and decide whether to retry the attach via the per-resource
+endpoints or accept the partial state.
+
+### Confirm before creating
+
+Room creation is a real side effect: a Matrix room is provisioned, an
+external channel may be created on the bridge, and agents are auto-joined.
+Always propose the room (name, description, bridge choice, member list)
+to the user and get explicit confirmation before calling `create_room`.
+
+## Per-room agent aliases
+
+A room can give an agent a short **alias** — a room-scoped handle so
+`@<alias>` addresses that agent in that room exactly like its full name
+(same routing and addressed-event semantics). Aliases are scoped to one
+room: the same agent can have a different alias (or none) in each room, and
+an alias only resolves in the room it was set in.
+
+- **Where aliases show up.** `connect_to_room`, `list_participants`, and
+ `get_room_detail` include each agent's alias — on participants as an
+ `alias` field, and on room detail as an `aliases` map (agent name →
+ alias). Read them so you know which handles are live in the room.
+- **In-room commands** (handled by the Switch admin client, like
+ `!list-agents`):
+ - `!list-aliases` — list the room's aliases (`@alias` → agent).
+ - `!set-alias @agent-name @alias` — give an agent an alias (agent first,
+ then the alias).
+ - `!remove-alias @alias` (or `@agent-name`) — clear an alias.
+- **At room creation / update (MCP).** `create_room` accepts an `aliases`
+ map (agent name → alias) to seed aliases; `update_room` accepts the same
+ map to set or change them, with an empty string (`""`) clearing an
+ agent's alias.
+- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` (so
+ it tokenises as one `@`-mention), must be unique within the room, and
+ must not clash with any agent's real name or a room role name
+ (case-insensitive) — Switch rejects a colliding alias. An alias is
+ dropped automatically if the agent leaves the room.
+
+## Important rules
+
+- **No stray `@-mentions` in free-text fields.** Switch re-parses these
+ strings as room messages and any `@agent-name` becomes an *addressed*
+ event for that agent — they will respond, even though you only meant to
+ describe them. This applies to **every** free-text field you author:
+ - `post_message(body)`
+ - `delegate_task(summary, description)`
+ - `update_task(update)`
+ - `finalise_task(outcome)`
+ - `cancel_task(reason)`
+
+ If you need to refer to an agent in text, write the bare name without
+ `@` (e.g. "codex.test-codex posted the greeting", not
+ "@codex.test-codex posted the greeting"). To genuinely address
+ agents, use `send_targeted_message` (for messages) or the task tools
+ (for tracked work) — they handle addressing for you.
+- **Always connect before reading.** `read_context`, `list_participants`,
+ `post_message`, `send_targeted_message`, and the task tools all require
+ an active room connection.
+- **Read each resource's `instructions`.** Every reference, document, and
+ package in the `connect_to_room` response carries its own `instructions`
+ field. Read them — they may override or specialise the defaults in this
+ skill for that particular resource.
+- **Read before responding.** Always call `read_context` (with `since`
+ when catching up) to understand what has been discussed.
+- **One room at a time.** Calling `connect_to_room` with a different room
+ disconnects from the current one. Delivery automatically re-targets to
+ the new room.
+- **Switch does not mediate your local tool calls.** Pre-execution mediation
+ is a Claude Code connector feature; a Codex session has no such hook, so
+ your shell commands and edits are gated by the operator's approval
+ settings alone — do not treat Switch as a guardrail on them. Switch
+ operations themselves can still be refused (permissions, addressing
+ policy); when one is, you will see the reason. Do not try to circumvent a
+ denial.
+- **You are a participant, not the controller.** Other agents and users
+ are in the room. Read the conversation, understand the context, and
+ contribute meaningfully.
+- **Reply in the room, not just in the terminal.** When a message in the
+ room asks you something or requests work, your substantive answer
+ belongs in the room — via `post_message` (or `send_targeted_message`
+ if directed at a specific participant). Other participants, including
+ human users on a bridged external channel (Slack, Mattermost), cannot
+ see your terminal output; only room events reach them. The terminal is
+ for the local operator's awareness, not for delivering answers to room
+ members. Default behavior: when responding to a room message, post the
+ answer to the room first, then optionally summarise locally. The only
+ times it is fine to stay terminal-only are when the local operator is
+ explicitly steering you outside the room conversation (e.g. asking you
+ to investigate something privately before replying).
+
+## Formatting messages for bridged channels
+
+Your messages render on whatever external platform the room is bridged to
+(check `bridge_display_name` in the `get_room_detail`
+payload). The platforms do **not** render Markdown identically, so adapt:
+
+- **Slack** renders only a *subset* of Markdown (mrkdwn). **Bold**,
+ `inline code`, ```code blocks```, `>` quotes, bullet lists, and
+ `[label](url)` links all convert and render. But Slack does **NOT** render
+ **Markdown tables** — pipe-and-dash tables show up as raw `| … |` text. So
+ in a Slack-bridged room, **never use Markdown tables**: for any multi-item
+ list with attributes (status digests, backlogs, queues), use **one short
+ line/bullet per item with bold field labels** instead — e.g.
+ `- **CHOO-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with
+ the bold identifier; separate fields with `·` or `—`.
+- **Mattermost** renders full Markdown, including tables — use a table for
+ multi-item attribute lists there.
+
+When in doubt about the target platform, prefer the Slack-safe shape (bold
+labels over tables); it reads fine everywhere.
+
+## Agent capabilities
+
+Agents have no global role: room creation, invites, and other moderation
+tools are available to any agent (including Codex). Task-delegation
+capability is declared per agent in their integration profile
+(`can_delegate`, `can_accept`). Check each participant's capabilities in
+the `connect_to_room` response.
+
+## Room roles (assumable)
+
+A room can define **room-scoped roles** — named, assumable instruction
+bundles (e.g.
+`manager`, `worker`, `reviewer`). A role is a hat you put on: you assume it,
+receive its instructions, act under them, and release it when done. Roles
+are listed in the `connect_to_room` payload (`roles`) and via `list_roles`.
+
+- **`list_roles`** — see the room's roles. Each entry has `name`,
+ `exclusive`, `instructions_preview`, `assumable_by_me`, and `held_by`.
+ `held_by` is a list of holder objects `{name, present_here, session_room}`:
+ `present_here` is true when that holder's session is connected to this room
+ right now; otherwise `session_room` names the room its session is currently
+ attending (a role lease survives room hops, so a holder can be live but
+ looking elsewhere), or is null if no live session is found. The
+ `instructions_preview` is truncated (first 200 chars) — use
+ `get_role_detail` for the full text.
+- **`get_role_detail(room_id, role_name)`** — fetch ONE role's **full
+ untruncated** `instructions` (plus `name`, `exclusive`, `held_by` with the
+ same presence shape as `list_roles`, and `assumable_by_me`). Use this when
+ the preview is cut off and you need the complete instruction bundle — e.g.
+ to read what a role entails before assuming it. Requires room membership;
+ the room need not be the one your session is currently connected to.
+- **`assume_role(role)`** — take the role and receive its full instruction
+ bundle. Layer those instructions on top of your existing context. You may
+ hold only one role at a time — release the current one first. Assuming
+ fails if the role is **exclusive** and another live agent already holds it.
+- **`release_role()`** — drop the role you hold (idempotent). Ending your
+ session also releases it automatically.
+
+**Creating and editing roles.** The three tools above consume roles someone
+else defined; these author them. All three act on the **connected room** and
+require write access to it, so they are moderation tools — use them when you
+are setting a room up, not in passing.
+
+- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`
+ must be unique within the room. `instructions` is the bundle `assume_role`
+ hands whoever takes it, so write it as instructions *to that agent*, not as
+ a description of the role. Set `exclusive` when at most one live agent may
+ hold it at a time.
+- **`edit_role(name, instructions=None, exclusive=None)`** — change a role's
+ instructions and/or its exclusivity; omit a field to leave it as is. Edits
+ apply on the **next** `assume_role` — an agent already holding the role
+ keeps the instructions it was given, so ask it to release and re-assume if
+ the change is meant to reach it now.
+- **`delete_role(name)`** — remove the role and any lease on it.
+
+**Exclusive vs shared.** An `exclusive` role admits at most one live holder:
+it is leased to you with a fast heartbeat while your session stays alive and
+**auto-releases shortly after you disconnect**, so another agent can take
+over — no manual handoff needed. A non-exclusive (shared) role may be held
+by many agents at once.
+
+**Addressing roles.** Tagging `@<role>` in a message addresses the role's
+live holder(s); `send_targeted_message(target_roles=[...])` does this for
+you and fans out to **every** live holder of a shared role (the single
+holder for an exclusive one). This is how you reach "whoever is currently
+the manager" without knowing which agent it is.
+
+**Presence = availability.** Because a role lease is kept alive across room
+hops, an agent can hold a role here while its session is attending another
+room. Use the `present_here` / `session_room` fields (and the addressed-but-
+unavailable auto-reply, which names where the agent's session actually is) to
+tell whether a holder is reachable in this room right now.
+
+## When to use these tools
+
+- `list_rooms` — when starting a session or asked which rooms exist.
+- `connect_to_room` — when entering a room. Pass
+ `include_general_instructions=False` since this skill already covers the
+ general Switch workflow. Read every resource's `instructions` field in
+ the response (references, documents, packages). Delivery of the room's
+ events follows automatically — no separate step.
+- `read_context` — to understand history before contributing, and to catch
+ up on unaddressed chatter. Use `since` when catching up to avoid
+ re-reading.
+- `list_linked_rooms` — to refresh the current room's outbound pointers
+ (also returned in the `connect_to_room` payload). Check the `access`
+ field before trying to `connect_to_room` on a linked room.
+- `post_message` — broadcast to everyone.
+- `send_targeted_message` — request a synchronous response from specific
+ agents or roles (informal handoff, question, nudge). Use `target_roles`
+ to address a role's live holder(s).
+- `list_roles` — see the room's assumable roles, who holds them, and where
+ those holders' sessions currently are.
+- `get_role_detail` — read ONE role's full untruncated instructions (the
+ `list_roles` / `get_room_detail` preview is capped at 200 chars).
+- `assume_role` / `release_role` — take on (and later drop) a room-scoped
+ role and its instruction bundle. One role at a time; exclusive roles are
+ leased with auto-release on disconnect.
+- `define_role` / `edit_role` / `delete_role` — author the roles others
+ assume. Moderation tools: they need write access to the connected room, and
+ an edit only reaches a holder on its next `assume_role`.
+- `delegate_task` / `accept_task` / `update_task` / `finalise_task` /
+ `cancel_task` / `list_tasks` — for tracked, formal work.
+- `list_bridges` — before creating a room, to discover the available
+ collaboration bridges and ask the user which one to use.
+- `create_room` — provision a new room. Confirm name, members, and
+ bridge choice with the user before calling. Rooms use the default
+ bridge unless you pass `bridge_id` or `internal_only`.
+- `invite_agent_to_room` — add another agent to an existing room by
+ name.
+- `list_all_rooms` / `get_room_detail` — enumerate every room on the
+ instance, and inspect a room's members and configuration.
+- `list_agents` — list every agent on the instance (optionally filtered
+ by name, owner, or known-agent type).
+- `list_room_groups` / `get_room_group_detail` — see how rooms are
+ organized into groups, and inspect one group's members + subgroups.
+- `create_room_group` — provision a new room group (optionally nested
+ under a parent group by name) to organize rooms.
+- `get_agent_detail` — inspect any agent's configuration, capabilities,
+ room memberships, and sessions.
+- `update_agent_detail` — change an agent you own (partial known-agent
+ options, e.g. working directory, and/or its parent agent).
+- `list_reference_types` — discover supported Reference types + their
+ value schemas before calling `create_reference`.
+- `create_reference` — register a new external Reference (Drive,
+ Confluence, GitHub, …) so it can be attached to rooms.
+- `attach_reference_to_room` — attach an existing Reference to an
+ existing room, standalone (vs at room creation).
+- `link_rooms` — create a directed pointer from one room to another
+ with a `label`.
+- `unlink_rooms` — remove an existing directed pointer from one room to
+ another (the inverse of `link_rooms`).
diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index 124432870..d0f7b2b0f 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -495,8 +495,8 @@ async def read_context(
`attachments` is a (usually empty) list of files on the message, each
{"filename", "mimetype", "size", "mxc", "msgtype"}. Any file type can
appear, and a message may carry several. To actually view one, pass its
- `mxc` to the channel's `download_attachment` tool, which fetches it to a
- local file you can read.
+ `mxc` to the `download_attachment` tool, which fetches it to a local file
+ you can read.
Args:
limit: Maximum number of messages to scan (default 50), grouped into
@@ -533,7 +533,8 @@ async def list_participants() -> list[dict[str, Any]]:
connect_to_room first.
Returns:
- List of {id, name, type} dicts for each participant.
+ List of {id, name, type, status, alias} dicts for each participant.
+ `status` and `alias` are null when unset.
"""
get_agent_id()
room_id = await require_connected_room()
@@ -759,6 +760,26 @@ async def finalise_task(task_id: str, outcome: str) -> dict[str, Any]:
}
+@operation
+async def cancel_task(task_id: str, reason: str) -> dict[str, str]:
+ """Abandon a task you delegated. Only the requester can cancel.
+
+ Args:
+ task_id: The id of a task this agent delegated.
+ reason: Why the task is no longer needed. Recorded on the task and
+ posted to the room so the performer learns it has been dropped.
+
+ Returns:
+ {"status": "cancelled", "reason": "<reason>"}.
+ """
+ agent_id = get_agent_id()
+ await require_connected_room()
+
+ protocol = get_protocol()
+ await protocol.cancel_task(agent_id, task_id, reason)
+ return {"status": "cancelled", "reason": reason}
+
+
@operation
async def list_tasks(
role: str | None = None, status: str | None = None
diff --git a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
new file mode 100644
index 000000000..1c42f18d7
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
@@ -0,0 +1,130 @@
+"""The MCP tool surface agents are told about must be the surface that exists.
+
+The connector skills and `protocol/instructions.py` name specific tools and
+tell agents to call them, and neither is checked against the server's actual
+registrations at build time. These tests pin the tool names so a rename, a
+removal, or a name that only ever existed in the documentation fails here
+rather than surfacing as an agent calling into nothing.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+from switch_core.bridges.agent.mcp.server import mcp
+
+TASK_PROTOCOL_TOOLS = {
+ "delegate_task",
+ "accept_task",
+ "update_task",
+ "finalise_task",
+ "cancel_task",
+ "list_tasks",
+}
+
+
+async def tool_names() -> set[str]:
+ return {tool.name for tool in await mcp.list_tools()}
+
+
+async def test_task_protocol_is_fully_exposed(tool_names: set[str]) -> None:
+ """Every stage of the documented task lifecycle is callable over MCP.
+
+ `cancel_task` is the requester's abort path: without it the lifecycle the
+ skills describe has no exit for the agent that opened it.
+ """
+ assert TASK_PROTOCOL_TOOLS <= tool_names
+
+
+async def test_documented_tools_exist(tool_names: set[str]) -> None:
+ """Every tool the connector skills advertise is registered.
+
+ Mirrors the tool names used across `connectors/*/skills/switch/SKILL.md`,
+ including those named only in the body. Maintained by hand: add a name here
+ when a skill starts advertising one.
+ """
+ documented = TASK_PROTOCOL_TOOLS | {
+ "list_rooms",
+ "connect_to_room",
+ "read_context",
+ "post_message",
+ "send_targeted_message",
+ "list_participants",
+ "list_roles",
+ "get_role_detail",
+ "assume_role",
+ "release_role",
+ "define_role",
+ "edit_role",
+ "delete_role",
+ "list_linked_rooms",
+ "update_room",
+ "create_room",
+ "invite_agent_to_room",
+ "list_all_rooms",
+ "get_room_detail",
+ "list_bridges",
+ "list_reference_types",
+ "create_reference",
+ "attach_reference_to_room",
+ "link_rooms",
+ "unlink_rooms",
+ "list_room_groups",
+ "create_room_group",
+ "get_room_group_detail",
+ "list_agents",
+ "get_agent_detail",
+ "update_agent_detail",
+ }
+
+ assert documented <= tool_names, (
+ f"documented but not registered: {sorted(documented - tool_names)}"
+ )
+
+
+SKILLS = sorted(
+ (Path(__file__).parents[5] / "connectors").glob("*/skills/switch/SKILL.md")
+)
+
+
+def _frontmatter_tools(skill: Path) -> list[str]:
+ """The tool names listed in a skill's frontmatter `description:` trigger.
+
+ Both skills carry them as one parenthesised, comma-separated run — the
+ first parenthetical in the file. Read rather than YAML-parsed so the
+ unquoted (Claude) and quoted (Codex) forms are handled the same way.
+ """
+ match = re.search(
+ r"^description:.*?\(([a-z_, ]+)\)", skill.read_text(), re.MULTILINE
+ )
+ assert match is not None, f"no parenthesised tool list in {skill}"
+ return [name.strip() for name in match.group(1).split(",") if name.strip()]
+
+
+def test_both_skills_advertise_the_same_tools() -> None:
+ """The two connectors' trigger lists must not drift apart.
+
+ They are host-specific documents but the tool surface behind them is one
+ surface, and a tool added to one skill's trigger is silently absent from
+ the other's.
+ """
+ assert len(SKILLS) == 2, f"expected two connector skills, found {SKILLS}"
+ first, second = (_frontmatter_tools(skill) for skill in SKILLS)
+ assert first == second
+
+
+async def test_skill_frontmatter_tools_are_registered(tool_names: set[str]) -> None:
+ """Every tool named in a skill's trigger list actually exists.
+
+ Derived from the files rather than restated here, so this half cannot go
+ stale the way the hand-maintained set above can. It does not replace that
+ set: the skills also name tools in their bodies (`list_linked_rooms`,
+ `update_room`) that never appear in the trigger.
+ """
+ for skill in SKILLS:
+ advertised = set(_frontmatter_tools(skill))
+ assert advertised <= tool_names, (
+ f"{skill} advertises unregistered tools: {sorted(advertised - tool_names)}"
+ )
diff --git a/core/uv.lock b/core/uv.lock
index 862b7f2f5..33a3bede3 100644
--- a/core/uv.lock
+++ b/core/uv.lock
@@ -2433,7 +2433,7 @@ wheels = [
[[package]]
name = "switch-core"
-version = "0.10.0"
+version = "0.11.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
diff --git a/dash/AGENTS.md b/dash/AGENTS.md
index 7fc446880..eebdb00de 100644
--- a/dash/AGENTS.md
+++ b/dash/AGENTS.md
@@ -346,6 +346,7 @@ The pairs that must stay in step:
| Desktop | Sidecar | Shared by |
|---|---|---|
| `agent-runtime/impl/local-agent-runtime.ts` (spawn env) | `sidecar/session-spawner.ts` + `sidecar/index.ts` | nothing — **the usual place to forget** |
+| `agent-hooks/hook-config-service.ts` + `ssh-agent-runtime.installRemoteHooks` | `sidecar/session-spawner.installHooks` | nothing — same failure mode: one side quietly installs fewer hooks |
| `switch-rooms/auto-session-watcher.ts` | `sidecar/notification-watcher.ts` | nothing — two implementations of one watcher |
| `switch-rooms/room-connection.ts` | — | shared: the sidecar constructs the same class |
| protocol client (stream, heartbeat, cursor) | — | shared: `@sandbox-quantum/switch-agent-runtime` |
@@ -361,7 +362,7 @@ too.
## Versioned Artifacts — Bump Them
-Three things here ship independently of the app and carry their own version.
+Four things here ship independently of the app and carry their own version.
**If you make a non-trivial change to one, bump its version in the same commit.**
Not at release time, not "later" — in the commit that changes it, or it will be
forgotten and someone will debug a build they think is newer than it is.
@@ -370,16 +371,34 @@ forgotten and someone will debug a build they think is newer than it is.
|---|---|---|
| Remote sidecar | `src/sidecar/sidecar-version.ts` | any behaviour change; **major only** on a client↔sidecar wire break (ready line, endpoint shapes, shared on-disk layout) |
| Claude Code plugin | `connectors/claude-code-plugin/.claude-plugin/plugin.json` | any change to the plugin — installs will not pick it up otherwise |
-| Agent runtime package | `packages/switch-agent-runtime/package.json` | any change; it is published, and `.mcp.json` pins an exact version that must move with it |
+| Codex plugin | `connectors/codex-plugin/.codex-plugin/plugin.json` | any change to the plugin (it ships only the skill) — installs will not pick it up otherwise |
+| Agent runtime package | `packages/switch-agent-runtime/package.json` | any change; it is published, and two pins name the version sessions actually run — the Claude connector `.mcp.json`, and `SWITCH_AGENT_RUNTIME_VERSION` in `src/shared/core/switch-rooms/switch-agent-runtime.ts` (which the Codex profile uses) |
"Non-trivial" means anything a user could observe: behaviour, protocol, wiring,
dependencies. A comment or a rename that changes nothing does not need one.
+**The runtime's version and its two pins move at different times, in this
+order.** Bump `package.json` with the change; the pins must keep naming a
+version that is *published*, so they stay behind until the tag exists
+(`git tag switch-agent-runtime-v<version> && git push origin <tag>`), and only
+then move to it. Pinning ahead points every session at something the registry
+does not have. `switch-agent-runtime.test.ts` enforces exactly this: the two
+pins must agree with each other, and neither may run ahead of `package.json`.
+The cost of the lag is real and worth stating in the PR — a change to `bin.ts`
+reaches no session until the tag is pushed and the pins follow.
+
Two traps worth knowing rather than rediscovering:
- **A sidecar major replaces every sidecar on sight, live sessions included.**
It is judged on the contract *switchdash* speaks to, not on how much changed
inside. Changing how the sidecar talks to Switch is not a major.
+- **A *new* sidecar endpoint is a minor, not a major.** A major only achieves
+ anything if `MIN_SUPPORTED_SIDECAR_MAJOR` moves with it, and that kills every
+ older sidecar on sight — including one an older switchdash on the same host
+ then kills right back, each replacing the other forever. The client owns the
+ detection instead: call the endpoint, and when an older sidecar 404s it, fail
+ the operation with a message naming the upgrade rather than continuing
+ without whatever the endpoint was for.
- **Redeploy is decided by the bundle's content hash, not by the version.** So a
forgotten bump does not strand a VM on old code — but it does make the version
a lie, which is worse in its own way, because it is the number people reason
@@ -427,7 +446,11 @@ pnpm run test
## Extensibility Hooks
-- Agent providers are defined in `src/shared/core/agents/agent-provider-registry.ts`.
+- Agent providers are defined in `packages/plugins/src/agents/impl/<id>/index.ts`.
+ `src/shared/core/providers/agent-provider-registry.ts` holds the id list, per-provider
+ display metadata, and a mirror of each provider's argv shape. The mirror is
+ descriptive: nothing reads it at spawn time, so change the plugin first and update the
+ mirror to match. `provider-argv-parity.test.ts` pins Codex's.
- Provider detection lives in `src/main/core/dependencies/dependency-manager.ts`.
- Provider PTY behavior and env passthrough live under `src/main/core/pty/`.
- Provider event hooks and plugins live under `src/main/core/agent-hooks/`.
@@ -444,6 +467,21 @@ pnpm run test
`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,
`SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`, and
`SWITCHDASH_FAKE_UPDATE`.
+- An auto-approving Codex session launches with `-c approval_policy="never"` and
+ nothing else. The sandbox is deliberately **not** overridden: "Bypass
+ permissions" promises unattended approvals, not unattended filesystem and
+ network access, so the user's own `sandbox_mode` from `~/.codex/config.toml`
+ stands. Measured against codex-cli 0.146.0, Codex runs hooks **outside** the
+ sandbox, so switchdash's `curl http://127.0.0.1:$SWITCHDASH_HOOK_PORT/hook`
+ hooks return 200 under `workspace-write` — the loopback block applies to
+ model-generated commands only. See
+ `packages/plugins/src/agents/impl/codex/index.ts`.
+- Every switchdash-launched Codex session — not only auto-approving ones — carries
+ `--dangerously-bypass-hook-trust`. Codex skips any hook it has no persisted
+ `trusted_hash` for, which would take switchdash's own hooks with it; the flag is
+ per-invocation and also un-gates hooks the user added to `~/.codex/hooks.json`
+ themselves. Rationale and the rejected alternative are on `CODEX_HOOK_TRUST_FLAG` in
+ `packages/plugins/src/agents/impl/codex/hooks.ts`.
- App updates in dev: the update service is inert outside packaged builds, so the
"update available" UI cannot be exercised by `pnpm run dev` alone. Set
`SWITCHDASH_FAKE_UPDATE` to replay the lifecycle against a simulated release —
diff --git a/dash/agents/architecture/shared.md b/dash/agents/architecture/shared.md
index 534a0e46a..e1393e53c 100644
--- a/dash/agents/architecture/shared.md
+++ b/dash/agents/architecture/shared.md
@@ -2,8 +2,9 @@
## Main Shared Areas
-- Agent provider registry:
- - `src/shared/core/agents/agent-provider-registry.ts`
+- Agent provider registry (ids, display metadata, and a descriptive argv mirror; behavior
+ lives in `packages/plugins/src/agents/impl/<id>/index.ts`):
+ - `src/shared/core/providers/agent-provider-registry.ts`
- IPC primitives:
- `src/shared/ipc/rpc.ts` — typed RPC router, controller, and client
- `src/shared/ipc/events.ts` — typed event emitter
@@ -36,9 +37,11 @@ Aliases are resolved at build time by electron-vite. No runtime monkey-patching
When adding a provider:
-1. update `src/shared/core/agents/agent-provider-registry.ts`
-2. add any required env passthrough in `src/main/core/pty/pty-env.ts`
-3. add or update hook/plugin installation in `src/main/core/agent-hooks/` if the provider
- supports explicit events
-4. update renderer surfaces that assume provider metadata
-5. add tests for non-standard spawn or detection behavior
+1. add the plugin under `packages/plugins/src/agents/impl/<id>/index.ts`
+2. add the id to `AGENT_PROVIDER_IDS` and a display entry to `AGENT_PROVIDERS` in
+ `src/shared/core/providers/agent-provider-registry.ts`
+3. add any required env passthrough in `src/main/core/pty/pty-env.ts`
+4. declare the provider's `hooks` capability in the plugin if it supports explicit events;
+ `src/main/core/agent-hooks/` writes the config files from that declaration
+5. update renderer surfaces that assume provider metadata
+6. add tests for non-standard spawn or detection behavior
diff --git a/dash/agents/integrations/providers.md b/dash/agents/integrations/providers.md
index 841623ad0..580866c1b 100644
--- a/dash/agents/integrations/providers.md
+++ b/dash/agents/integrations/providers.md
@@ -2,7 +2,10 @@
## Source Of Truth
-- `src/shared/core/agents/agent-provider-registry.ts`
+- `packages/plugins/src/agents/impl/<id>/index.ts` — the provider plugin. Authoritative for
+ everything behavioral.
+- `src/shared/core/providers/agent-provider-registry.ts` — ids, display metadata, and a
+ descriptive mirror of the plugin's argv. Never authoritative.
- `src/main/core/dependencies/registry.ts`
- `src/main/core/pty/`
@@ -10,16 +13,24 @@
codex, claude, grok, devin, cursor, gemini, antigravity, qwen, droid, amp, commandcode, opencode, hermes, copilot, charm, auggie, goose, kimi, kilocode, kiro, rovo, cline, continue, codebuff, freebuff, mistral, jules, junie, pi, letta, autohand
-## Provider Metadata Includes
+## Where Provider Metadata Lives
-- CLI and detection commands
-- version args
-- install command and docs URL
-- auto-approve flags
-- initial prompt handling
-- keystroke injection behavior
-- resume and session flags
-- optional plan activation and auto-start commands
+The plugin (`packages/plugins/src/agents/impl/<id>/index.ts`) owns everything that affects
+behavior:
+
+- argv shaping — auto-approve flags, initial prompt handling, resume and session flags,
+ default args — via the `buildStandardCommand` spec in `behavior.prompt.buildCommand`
+- CLI name, detection commands, and version args — via `hostDependency`
+- prompt delivery mode, including keystroke injection — via `capabilities.prompt.kind`
+- hook support — via `capabilities.hooks`
+- the provider icon — via the plugin's `icon` asset
+
+`agent-provider-registry.ts` holds the `AGENT_PROVIDER_IDS` list, per-provider display
+metadata (name, one-line description, docs URL, icon, install command), and a mirror of the
+argv fields above. It builds no commands and nothing reads the mirror at spawn time — it
+exists so the provider table can be read in one place. Change the plugin first, then the
+mirror. `src/main/core/providers/provider-argv-parity.test.ts` fails if Codex's two drift
+apart; the other providers' mirrors are unguarded, so treat them as hints, not facts.
## Agent Hooks And Notifications
@@ -38,9 +49,11 @@ or notify an inferred status for that event.
## Adding Or Changing A Provider
-1. update `src/shared/core/agents/agent-provider-registry.ts`
-2. update allowlisted agent env vars in `src/main/core/pty/pty-env.ts` if needed
-3. add or update hook/plugin installation in `src/main/core/agent-hooks/` if the provider
- supports explicit events
+1. add or update the plugin in `packages/plugins/src/agents/impl/<id>/index.ts` — this is where
+ argv, dependencies, capabilities, and hooks are defined
+2. for a new provider only, add the id to `AGENT_PROVIDER_IDS` and a display entry to
+ `AGENT_PROVIDERS` in `src/shared/core/providers/agent-provider-registry.ts`
+ (`plugin-registry.ts` fails at load if the id list and the plugins disagree)
+3. update allowlisted agent env vars in `src/main/core/pty/pty-env.ts` if needed
4. validate detection behavior in `src/main/core/dependencies/`
5. add or update tests for any non-standard behavior
diff --git a/dash/apps/switchdash-desktop/drizzle/0045_magenta_otto_octavius.sql b/dash/apps/switchdash-desktop/drizzle/0045_magenta_otto_octavius.sql
new file mode 100644
index 000000000..cb11ddc45
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/0045_magenta_otto_octavius.sql
@@ -0,0 +1 @@
+ALTER TABLE `agents` ADD `provider_config` text;
\ No newline at end of file
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0045_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0045_snapshot.json
new file mode 100644
index 000000000..34038daf5
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/meta/0045_snapshot.json
@@ -0,0 +1,836 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "9e33859d-6f5a-4fe3-b926-f902c4cb0863",
+ "prevId": "0accfa68-741f-4f75-9b40-7a47c434091e",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "switch_agent_id": {
+ "name": "switch_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "api_endpoint": {
+ "name": "api_endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "auto_approve": {
+ "name": "auto_approve",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "provider_config": {
+ "name": "provider_config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_agents_location_id": {
+ "name": "idx_agents_location_id",
+ "columns": ["location_id"],
+ "isUnique": false
+ },
+ "idx_agents_server_id": {
+ "name": "idx_agents_server_id",
+ "columns": ["server_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "agents_location_id_locations_id_fk": {
+ "name": "agents_location_id_locations_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agents_server_id_switch_servers_id_fk": {
+ "name": "agents_server_id_switch_servers_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "switch_servers",
+ "columnsFrom": ["server_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "app_secrets": {
+ "name": "app_secrets",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_app_secrets_key": {
+ "name": "idx_app_secrets_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "app_settings": {
+ "name": "app_settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_app_settings_key": {
+ "name": "idx_app_settings_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "kv": {
+ "name": "kv",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_kv_key": {
+ "name": "idx_kv_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "location_settings": {
+ "name": "location_settings",
+ "columns": {
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "base_settings_json": {
+ "name": "base_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "shareable_settings_json": {
+ "name": "shareable_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "legacy_config_migrated_at": {
+ "name": "legacy_config_migrated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "location_settings_location_id_locations_id_fk": {
+ "name": "location_settings_location_id_locations_id_fk",
+ "tableFrom": "location_settings",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "locations": {
+ "name": "locations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "dir": {
+ "name": "dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_locations_host_dir": {
+ "name": "idx_locations_host_dir",
+ "columns": ["ssh_host", "dir"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender": {
+ "name": "sender",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_messages_session_id": {
+ "name": "idx_messages_session_id",
+ "columns": ["session_id"],
+ "isUnique": false
+ },
+ "idx_messages_timestamp": {
+ "name": "idx_messages_timestamp",
+ "columns": ["timestamp"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "remote_host_reachability": {
+ "name": "remote_host_reachability",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_reachable_at": {
+ "name": "last_reachable_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "consecutive_failures": {
+ "name": "consecutive_failures",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "remote_hosts": {
+ "name": "remote_hosts",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "session_room_connections": {
+ "name": "session_room_connections",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "room_id": {
+ "name": "room_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "room_name": {
+ "name": "room_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "switch_agent_id": {
+ "name": "switch_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_room_connections_session_id_sessions_id_fk": {
+ "name": "session_room_connections_session_id_sessions_id_fk",
+ "tableFrom": "session_room_connections",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config": {
+ "name": "config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shell_id": {
+ "name": "shell_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_session_id": {
+ "name": "agent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status": {
+ "name": "agent_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status_seen": {
+ "name": "agent_status_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "is_initial_session": {
+ "name": "is_initial_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_pinned": {
+ "name": "is_pinned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_interacted_at": {
+ "name": "last_interacted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status_changed_at": {
+ "name": "status_changed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_sessions_agent_id": {
+ "name": "idx_sessions_agent_id",
+ "columns": ["agent_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "switch_servers": {
+ "name": "switch_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gateway_url": {
+ "name": "gateway_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "api_url": {
+ "name": "api_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "managed": {
+ "name": "managed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "management_kind": {
+ "name": "management_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_switch_servers_gateway_url": {
+ "name": "idx_switch_servers_gateway_url",
+ "columns": ["gateway_url"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
index 5ce5ca53e..8d7c9ff4b 100644
--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
@@ -316,6 +316,13 @@
"when": 1785224671278,
"tag": "0044_session_room_connections",
"breakpoints": true
+ },
+ {
+ "idx": 45,
+ "version": "6",
+ "when": 1785783917371,
+ "tag": "0045_magenta_otto_octavius",
+ "breakpoints": true
}
]
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
index 0d9edee30..573d293d2 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
@@ -82,7 +82,7 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
async handleRawHook(raw: RawHookRequest, opts: { startLocalPoller: boolean }): Promise<void> {
let parsed;
try {
- parsed = await parseHookEvent(raw, dbContextResolver);
+ parsed = await parseHookEvent(raw, dbContextResolver, log);
} catch (error) {
log.warn('AgentHookService: failed to parse hook event', {
ptyId: raw.ptyId,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
index 922dc4139..d63b7a7cf 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ContextResolver, type AgentHookContext, parseHookEvent } from './event-enricher';
import type { RawHookRequest } from './hook-server';
@@ -10,117 +10,244 @@ const ctx: AgentHookContext = {
const fixedResolver: ContextResolver = async () => ctx;
+const log = { warn: vi.fn() };
+
function raw(type: string, body: Record<string, unknown>): RawHookRequest {
return { ptyId: ctx.ptyId, type, body: JSON.stringify(body) } as RawHookRequest;
}
+/** The Switch `connect_to_room` result as the tool itself returns it. */
+const roomResult = { room_id: 'room-1', agent_id: 'agent-1', name: 'Room One' };
+
+const expectedRoom = {
+ kind: 'switch-room',
+ ctx,
+ roomId: 'room-1',
+ agentId: 'agent-1',
+ roomName: 'Room One',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
describe('parseHookEvent', () => {
it('parses a switch_room_connect event using the injected context', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', { tool_response: roomResult }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ });
+
+ it('unwraps the CallToolResult Codex actually forwards', async () => {
+ // Verbatim `tool_response` captured from Codex CLI 0.146.0 via
+ // `scripts/codex-hook-probe/run.sh`, calling a FastMCP tool declared like
+ // the real `connect_to_room` (async, returning `dict[str, Any]`). Codex
+ // forwards the envelope rather than unwrapping it the way Claude Code does,
+ // so reading `tool_response.room_id` finds nothing — kept literal so a
+ // future Codex change fails here rather than silently stranding the poller
+ // on the room the session spawned in.
const parsed = await parseHookEvent(
raw('switch_room_connect', {
- tool_response: { room_id: 'room-1', agent_id: 'agent-1', name: 'Room One' },
+ tool_name: 'mcp__switch__connect_to_room',
+ tool_response: {
+ content: [
+ {
+ type: 'text',
+ text: '{"room_id":"room-1","agent_id":"agent-1","name":"Room One","participants":[]}',
+ },
+ ],
+ structuredContent: { ...roomResult, participants: [] },
+ isError: false,
+ },
}),
- fixedResolver
+ fixedResolver,
+ log
);
- expect(parsed).toEqual({
- kind: 'switch-room',
- ctx,
- roomId: 'room-1',
- agentId: 'agent-1',
- roomName: 'Room One',
- });
+ expect(parsed).toEqual({ ...expectedRoom, ctx });
+ expect(log.warn).not.toHaveBeenCalled();
});
- it('ignores a switch_room_connect event missing room/agent ids', async () => {
+ it('unwraps structuredContent on its own', async () => {
const parsed = await parseHookEvent(
- raw('switch_room_connect', { tool_response: { room_id: 'room-1' } }),
- fixedResolver
+ raw('switch_room_connect', { tool_response: { structuredContent: roomResult } }),
+ fixedResolver,
+ log
);
- expect(parsed).toEqual({ kind: 'ignore' });
+
+ expect(parsed).toEqual(expectedRoom);
+ });
+
+ it('falls through to the text block when structuredContent is missing agent_id', async () => {
+ // structuredContent is tried before the text block and the first match wins,
+ // so a probe satisfied by room_id alone would take this partial envelope and
+ // then drop the event for a missing agent_id the text block was carrying.
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: {
+ structuredContent: { room_id: 'room-1' },
+ content: [{ type: 'text', text: JSON.stringify(roomResult) }],
+ },
+ }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
+ it('unwraps a structuredContent re-serialised as a JSON string', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: { structuredContent: JSON.stringify(roomResult) },
+ }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
+ it('unwraps structuredContent.result when the tool return was wrapped', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: { structuredContent: { result: roomResult } },
+ }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ });
+
+ it('unwraps the first text content block on its own', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: {
+ content: [
+ { type: 'image', data: 'ignored' },
+ { type: 'text', text: JSON.stringify(roomResult) },
+ ],
+ },
+ }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ });
+
+ it('keeps scanning past a text block that is not the result', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: {
+ content: [
+ { type: 'text', text: 'Connected to Room One.' },
+ { type: 'text', text: JSON.stringify(roomResult) },
+ ],
+ },
+ }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual(expectedRoom);
+ expect(log.warn).not.toHaveBeenCalled();
});
/**
- * A local MCP runtime that returns only text content — no structuredContent —
- * surfaces the tool result as an envelope, with the fields one level down.
- * Reading only the top level meant the hook was silently ignored: the session
- * was never bound to its room, so the sidebar showed no room AND the room
- * poller was never started, which looked like "messages stopped arriving".
+ * A CLI that unwraps the outer `CallToolResult` but not the content list hands
+ * the hook the bare array. The fields are in there, one level down. Failing to
+ * look means the session is never bound to its room: no room in the sidebar,
+ * and no room poller started either.
*/
- describe('tool responses that arrive as an MCP content envelope', () => {
- const payload = { room_id: 'room-1', agent_id: 'agent-1', name: 'Room One' };
- const expected = {
- kind: 'switch-room',
- ctx,
- roomId: 'room-1',
- agentId: 'agent-1',
- roomName: 'Room One',
- };
-
- it('reads structuredContent when the server provides it', async () => {
- const parsed = await parseHookEvent(
- raw('switch_room_connect', {
- tool_response: {
- content: [{ type: 'text', text: JSON.stringify(payload) }],
- structuredContent: payload,
- },
- }),
- fixedResolver
- );
- expect(parsed).toEqual(expected);
- });
+ it('handles a bare content array', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: [{ type: 'text', text: JSON.stringify(roomResult) }],
+ }),
+ fixedResolver,
+ log
+ );
- it('falls back to parsing the text block when it does not', async () => {
- const parsed = await parseHookEvent(
- raw('switch_room_connect', {
- tool_response: { content: [{ type: 'text', text: JSON.stringify(payload) }] },
- }),
- fixedResolver
- );
- expect(parsed).toEqual(expected);
- });
+ expect(parsed).toEqual(expectedRoom);
+ expect(log.warn).not.toHaveBeenCalled();
+ });
- it('handles a bare content array', async () => {
- const parsed = await parseHookEvent(
- raw('switch_room_connect', {
- tool_response: [{ type: 'text', text: JSON.stringify(payload) }],
- }),
- fixedResolver
- );
- expect(parsed).toEqual(expected);
- });
+ it('parses a tool_response delivered as a JSON string', async () => {
+ const asPayload = await parseHookEvent(
+ raw('switch_room_connect', { tool_response: JSON.stringify(roomResult) }),
+ fixedResolver,
+ log
+ );
+ expect(asPayload).toEqual(expectedRoom);
- it('still ignores an envelope carrying no room', async () => {
- const parsed = await parseHookEvent(
- raw('switch_room_connect', {
- tool_response: { content: [{ type: 'text', text: '{"ok":true}' }] },
- }),
- fixedResolver
- );
- expect(parsed).toEqual({ kind: 'ignore' });
- });
+ const asEnvelope = await parseHookEvent(
+ raw('switch_room_connect', {
+ tool_response: JSON.stringify({ structuredContent: roomResult }),
+ }),
+ fixedResolver,
+ log
+ );
+ expect(asEnvelope).toEqual(expectedRoom);
+ });
+
+ it('ignores a switch_room_connect event missing room/agent ids', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', { tool_response: { room_id: 'room-1' } }),
+ fixedResolver,
+ log
+ );
+ expect(parsed).toEqual({ kind: 'ignore' });
+ });
+
+ it('warns and ignores when the tool result shape is unrecognisable', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', { tool_response: { isError: true, content: 'nope' } }),
+ fixedResolver,
+ log
+ );
- it('prefers a direct top-level result over the envelope', async () => {
- const parsed = await parseHookEvent(
- raw('switch_room_connect', {
- ...{ tool_response: { ...payload, content: [{ type: 'text', text: '{}' }] } },
- }),
- fixedResolver
- );
- expect(parsed).toEqual(expected);
+ expect(parsed).toEqual({ kind: 'ignore' });
+ expect(log.warn).toHaveBeenCalledTimes(1);
+ expect(log.warn).toHaveBeenCalledWith(expect.any(String), {
+ providerId: ctx.providerId,
+ ptyId: ctx.ptyId,
+ toolResponseType: 'object',
+ toolResponseKeys: ['isError', 'content'],
});
});
+ it('warns without keys when the tool result is not an object', async () => {
+ const parsed = await parseHookEvent(
+ raw('switch_room_connect', { tool_response: 'not json' }),
+ fixedResolver,
+ log
+ );
+
+ expect(parsed).toEqual({ kind: 'ignore' });
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ toolResponseType: 'string', toolResponseKeys: undefined })
+ );
+ });
+
it('throws when the context resolver cannot resolve the ptyId', async () => {
const nullResolver: ContextResolver = async () => null;
- await expect(parseHookEvent(raw('Stop', {}), nullResolver)).rejects.toThrow(
+ await expect(parseHookEvent(raw('Stop', {}), nullResolver, log)).rejects.toThrow(
'Unrecognised ptyId'
);
});
it('does not consult the database — the resolver is the only context source', async () => {
const resolver = vi.fn(fixedResolver);
- await parseHookEvent(raw('switch_room_connect', { tool_response: {} }), resolver);
+ await parseHookEvent(raw('switch_room_connect', { tool_response: {} }), resolver, log);
expect(resolver).toHaveBeenCalledWith(ctx.ptyId);
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
index 70d10e73f..ee5d4b28d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
@@ -31,52 +31,100 @@ export type ParsedHookEvent =
| { kind: 'ignore' };
/**
- * Event type emitted by the Claude `connect_to_room` PostToolUse hook (see the
- * claude plugin hook config). The hook fires for the Switch MCP tool only, via
- * its `mcp__.*__connect_to_room` matcher.
+ * Minimal logger the parser needs. Injected rather than imported so the parser
+ * can run in the remote sidecar bundle, which must not pull in the
+ * Electron-bound main-process file logger.
*/
-const SWITCH_ROOM_CONNECT_EVENT = 'switch_room_connect';
+export interface HookEventLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
/**
- * Claude reports the tool result under `tool_response`, which may arrive as an
- * already-parsed object, a JSON string, or an MCP content envelope. The Switch
- * `connect_to_room` result carries `room_id` and `agent_id`.
+ * Event type emitted by the `connect_to_room` PostToolUse hook that
+ * `buildClaudeHookConfig` in `@switchdash/plugins` registers, scoped to the
+ * Switch MCP tool by an `mcp__.*__connect_to_room` matcher.
*
- * The envelope case matters: a server that returns only text content — no
- * `structuredContent` — surfaces as `{content: [{type: 'text', text: '<json>'}]}`
- * or as the bare content array. The fields are in there, one level down. Failing
- * to look meant the hook was silently ignored and the session was never bound to
- * its room: no room in the sidebar, and no room poller started either.
+ * Claude only. A session switchdash launched learns its room from the server
+ * instead: it carries a `SWITCH_CONNECTION_ID` and its `connect_to_room` claims
+ * the room on that connection. The hook covers what that path misses — a Claude
+ * session started outside switchdash and adopted afterwards, which joined a room
+ * on a connection of its own. Codex has no equivalent case, so
+ * `buildCodexHookConfig` registers no room hook: its Switch MCP server exists
+ * only in the per-agent profile switchdash writes and launches it with, so a
+ * Codex session switchdash did not start has no `connect_to_room` to call.
*/
-function parseToolResponse(body: Record<string, unknown>): Record<string, unknown> | null {
- const direct = coerceObject(body.tool_response);
- if (direct && ('room_id' in direct || 'agent_id' in direct)) return direct;
- return unwrapContentEnvelope(body.tool_response) ?? direct;
+const SWITCH_ROOM_CONNECT_EVENT = 'switch_room_connect';
+
+/** The value as a plain object, or null for anything else. */
+function asRecord(value: unknown): Record<string, unknown> | null {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return null;
+ return value as Record<string, unknown>;
}
-function coerceObject(raw: unknown): Record<string, unknown> | null {
- if (raw && typeof raw === 'object') return raw as Record<string, unknown>;
- if (typeof raw === 'string') {
- try {
- const value: unknown = JSON.parse(raw);
- if (value && typeof value === 'object') return value as Record<string, unknown>;
- } catch {}
+/**
+ * A string is decoded as JSON; anything else passes through untouched. Applied
+ * at each level of the response because an agent CLI that re-serialises a nested
+ * field hands it over as a string rather than as the object it stands for.
+ */
+function decodeJson(value: unknown): unknown {
+ if (typeof value !== 'string') return value;
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return null;
}
- return null;
}
-/** Pull the first JSON object out of an MCP text-content envelope. */
-function unwrapContentEnvelope(raw: unknown): Record<string, unknown> | null {
- const container = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null;
- const structured = coerceObject(container?.structuredContent);
- if (structured) return structured;
+/**
+ * The value as a Switch `connect_to_room` result — a plain object carrying both
+ * a string `room_id` and a string `agent_id` — or null. Those two fields are
+ * what tell the payload apart from an MCP envelope wrapping it, since both are
+ * plain objects.
+ *
+ * Both are required because the caller returns on the first match: a partial
+ * `structuredContent` that satisfied a `room_id`-only probe would win over the
+ * text block that carries the whole result, and the event would then be dropped
+ * for a missing `agent_id` that was available all along.
+ */
+function asRoomResult(value: unknown): Record<string, unknown> | null {
+ const record = asRecord(value);
+ if (!record) return null;
+ return typeof record.room_id === 'string' && typeof record.agent_id === 'string' ? record : null;
+}
+
+/**
+ * Extract the Switch `connect_to_room` result — which carries `room_id`,
+ * `agent_id` and `name` — from the hook's `tool_response`.
+ *
+ * How deeply it is wrapped depends on how far the agent CLI unwraps the MCP
+ * `CallToolResult` before handing it to the hook. Claude reports the payload
+ * itself (as an object or a JSON string); an envelope-aware CLI such as Codex
+ * may pass the `CallToolResult` through, which puts the payload under
+ * `structuredContent` (or `structuredContent.result` when the tool returned a
+ * non-dict) and repeats it as JSON in a `text` content block; a CLI that unwraps
+ * the result but not its content list hands over the bare content array.
+ *
+ * Every content block is tried, so a server that narrates before returning its
+ * JSON still parses. Malformed input yields null rather than throwing.
+ */
+function parseToolResponse(body: Record<string, unknown>): Record<string, unknown> | null {
+ const value = decodeJson(body.tool_response);
+
+ const direct = asRoomResult(value);
+ if (direct) return direct;
- const blocks = Array.isArray(raw) ? raw : container?.content;
+ const envelope = asRecord(value);
+ const structured = asRecord(decodeJson(envelope?.structuredContent));
+ const fromStructured = asRoomResult(structured) ?? asRoomResult(decodeJson(structured?.result));
+ if (fromStructured) return fromStructured;
+
+ const blocks = Array.isArray(value) ? value : envelope?.content;
if (!Array.isArray(blocks)) return null;
for (const block of blocks) {
- const text = (block as Record<string, unknown> | null)?.text;
- const parsed = typeof text === 'string' ? coerceObject(text) : null;
- if (parsed) return parsed;
+ const text = asRecord(block)?.text;
+ if (typeof text !== 'string') continue;
+ const fromText = asRoomResult(decodeJson(text));
+ if (fromText) return fromText;
}
return null;
}
@@ -112,7 +160,8 @@ function canonicalToAgentEvent(
export async function parseHookEvent(
raw: RawHookRequest,
- resolveContext: ContextResolver
+ resolveContext: ContextResolver,
+ log: HookEventLogger
): Promise<ParsedHookEvent> {
const ctx = await resolveContext(raw.ptyId);
if (!ctx) {
@@ -126,7 +175,19 @@ export async function parseHookEvent(
const roomId = typeof response?.room_id === 'string' ? response.room_id : null;
const agentId = typeof response?.agent_id === 'string' ? response.agent_id : null;
const roomName = typeof response?.name === 'string' ? response.name : null;
- if (!roomId || !agentId) return { kind: 'ignore' };
+ if (!roomId || !agentId) {
+ const toolResponse = body.tool_response;
+ log.warn('event-enricher: switch_room_connect carried no usable connect_to_room result', {
+ providerId: ctx.providerId,
+ ptyId: ctx.ptyId,
+ toolResponseType: typeof toolResponse,
+ toolResponseKeys:
+ toolResponse !== null && typeof toolResponse === 'object'
+ ? Object.keys(toolResponse)
+ : undefined,
+ });
+ return { kind: 'ignore' };
+ }
return { kind: 'switch-room', ctx, roomId, agentId, roomName };
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
index 7cf7f893d..642df880b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
@@ -202,4 +202,63 @@ describe('HookServer /events endpoint', () => {
);
expect(res.status).toBe(404);
});
+
+ // The id is the whole point of the call: the session is launched carrying it,
+ // and its room is claimed on that connection. A reply that loses it leaves the
+ // remote session addressable by nobody.
+ it('answers /connection with the id the handler opened', async () => {
+ const connectionHandler = vi.fn(() => 'conn-abc');
+ server = new HookServer(noopLog);
+ await server.start(async () => {}, { connectionHandler });
+
+ const ok = await post(
+ server.getPort(),
+ '/connection',
+ server.getToken(),
+ JSON.stringify({ sessionId: 'session-1', providerId: 'codex' })
+ );
+
+ expect(ok.status).toBe(200);
+ expect(JSON.parse(ok.body)).toEqual({ connectionId: 'conn-abc' });
+ expect(connectionHandler).toHaveBeenCalledWith('session-1', 'codex');
+
+ const forbidden = await post(
+ server.getPort(),
+ '/connection',
+ 'wrong',
+ JSON.stringify({ sessionId: 'session-1', providerId: 'codex' })
+ );
+ expect(forbidden.status).toBe(403);
+ });
+
+ it('rejects /connection without a sessionId and providerId', async () => {
+ const connectionHandler = vi.fn(() => 'conn-abc');
+ server = new HookServer(noopLog);
+ await server.start(async () => {}, { connectionHandler });
+
+ const res = await post(
+ server.getPort(),
+ '/connection',
+ server.getToken(),
+ JSON.stringify({ sessionId: 'session-1' })
+ );
+
+ expect(res.status).toBe(400);
+ expect(connectionHandler).not.toHaveBeenCalled();
+ });
+
+ // The 404 a client sees from a sidecar too old to have the endpoint. It must
+ // stay a 404 rather than any success shape, because that is what the client
+ // keys its "restart the sidecar" error on.
+ it('does not serve /connection when no handler is configured', async () => {
+ server = new HookServer(noopLog);
+ await server.start(async () => {});
+ const res = await post(
+ server.getPort(),
+ '/connection',
+ server.getToken(),
+ JSON.stringify({ sessionId: 'session-1', providerId: 'codex' })
+ );
+ expect(res.status).toBe(404);
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
index 371e6c01c..eb64a7bd9 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
@@ -129,6 +129,18 @@ export type SidecarSessionsProvider = () => SidecarSessionInfo[] | Promise<Sidec
*/
export type SidecarDisconnectHandler = (sessionId: string, terminated: boolean) => void;
+/**
+ * Open (or return) the Switch connection a VM session's tool calls ride on, and
+ * answer with its id.
+ *
+ * A session's room is claimed on the connection whose id it is handed as
+ * `SWITCH_CONNECTION_ID`, and only the process reading that connection sees the
+ * room's events. The sidecar mints one itself for every session its own watcher
+ * starts; this is the same hand-off for a session switchdash starts over SSH,
+ * which would otherwise own a connection nobody on the VM reads.
+ */
+export type SidecarConnectionHandler = (sessionId: string, providerId: string) => string;
+
export class HookServer {
private server: http.Server | null = null;
private port = 0;
@@ -136,6 +148,7 @@ export class HookServer {
private eventLog: HookEventLog | null = null;
private sessionsProvider: SidecarSessionsProvider | null = null;
private disconnectHandler: SidecarDisconnectHandler | null = null;
+ private connectionHandler: SidecarConnectionHandler | null = null;
constructor(private readonly log: HookServerLogger) {}
@@ -146,7 +159,10 @@ export class HookServer {
* `sessionsProvider` is provided it also exposes a token-gated `GET /sessions`
* snapshot so switchdash can reconcile VM-spawned sessions into its UI. When
* `disconnectHandler` is provided it exposes a token-gated `POST /disconnect`
- * so switchdash can drop a session's room connection when it deletes it.
+ * so switchdash can drop a session's room connection when it deletes it. When
+ * `connectionHandler` is provided it exposes a token-gated `POST /connection`
+ * so switchdash can open a room connection here for a session it is about to
+ * start over SSH.
*/
async start(
handler: HookHandler,
@@ -154,6 +170,7 @@ export class HookServer {
eventLog?: HookEventLog;
sessionsProvider?: SidecarSessionsProvider;
disconnectHandler?: SidecarDisconnectHandler;
+ connectionHandler?: SidecarConnectionHandler;
}
): Promise<void> {
if (this.server) return;
@@ -161,6 +178,7 @@ export class HookServer {
this.eventLog = options?.eventLog ?? null;
this.sessionsProvider = options?.sessionsProvider ?? null;
this.disconnectHandler = options?.disconnectHandler ?? null;
+ this.connectionHandler = options?.connectionHandler ?? null;
this.server = http.createServer((req, res) => {
if (req.headers['x-switchdash-token'] !== this.token) {
@@ -193,6 +211,15 @@ export class HookServer {
return;
}
+ if (
+ req.method === 'POST' &&
+ this.connectionHandler &&
+ (req.url ?? '').startsWith('/connection')
+ ) {
+ this.serveConnection(req, res, this.connectionHandler);
+ return;
+ }
+
if (req.method !== 'POST' || req.url !== '/hook') {
res.writeHead(404);
res.end();
@@ -334,6 +361,52 @@ export class HookServer {
});
}
+ private serveConnection(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ handler: SidecarConnectionHandler
+ ): void {
+ let body = '';
+ req.on('data', (chunk: Buffer) => {
+ body += chunk.toString();
+ if (body.length > 1_000_000) req.destroy();
+ });
+ req.on('end', () => {
+ let sessionId = '';
+ let providerId = '';
+ try {
+ const parsed = JSON.parse(body) as { sessionId?: unknown; providerId?: unknown };
+ if (typeof parsed.sessionId === 'string') sessionId = parsed.sessionId;
+ if (typeof parsed.providerId === 'string') providerId = parsed.providerId;
+ } catch {
+ sessionId = '';
+ }
+ if (!sessionId || !providerId) {
+ this.log.warn('HookServer: /connection missing sessionId or providerId');
+ res.writeHead(400);
+ res.end();
+ return;
+ }
+ let connectionId: string;
+ try {
+ connectionId = handler(sessionId, providerId);
+ } catch (err) {
+ this.log.warn('HookServer: /connection handler error', { error: String(err) });
+ res.writeHead(500);
+ res.end();
+ return;
+ }
+ const payload = Buffer.from(JSON.stringify({ connectionId }), 'utf8');
+ // Explicit Content-Length (not chunked) so the caller reading the raw HTTP
+ // response off an SSH-forwarded socket gets the body verbatim.
+ res.writeHead(200, {
+ 'content-type': 'application/json',
+ 'content-length': payload.byteLength,
+ });
+ res.end(payload);
+ });
+ }
+
stop(): void {
if (this.server) {
this.server.close();
@@ -342,6 +415,7 @@ export class HookServer {
this.eventLog = null;
this.sessionsProvider = null;
this.disconnectHandler = null;
+ this.connectionHandler = null;
}
}
getPort(): number {
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
index ab2795036..c67f54010 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
@@ -1,3 +1,4 @@
+import type { SwitchLaunchSpecialization } from '@switchdash/core/agents/plugins';
import { generateAgentLaunchSpec } from '@main/core/agents/generate-agent-launch-spec';
import type { IExecutionContext } from '@main/core/execution-context/types';
import { log } from '@main/lib/logger';
@@ -27,6 +28,9 @@ export interface AgentSidecarParams {
/** The agent's name — so auto-started sessions launch as it with its own
* identity (a definitions-capable provider passes it as `--agent <name>`). */
agentName: string | null;
+ /** Per-agent model / effort / instructions folded into auto-started sessions'
+ * launch profile. */
+ specialization?: SwitchLaunchSpecialization;
ctx: IExecutionContext;
connectionId: string;
host: SidecarHost;
@@ -39,6 +43,8 @@ async function buildLauncher(params: AgentSidecarParams): Promise<RemoteSidecarL
deeplinkScheme: params.deeplinkScheme,
autoApprove: params.autoApprove,
agentName: params.agentName,
+ credsSlug: params.credsSlug,
+ specialization: params.specialization,
ctx: params.ctx,
connectionId: params.connectionId,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
index 6f4147976..f1cddb9b6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
@@ -1,3 +1,5 @@
+import { pluginRegistry } from '@switchdash/plugins/agents';
+import { parse as parseTOML } from 'smol-toml';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AGENT_FRESH_RECOVERY_GRACE_MS } from '@main/core/agent-runtime/agent-runtime-supervisor';
import type { Pty, PtyExitInfo } from '@main/core/pty/pty';
@@ -62,6 +64,12 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({
readAgentSwitchEnvFromFs: vi.fn(async () => ({})),
}));
+// Loading the agent record to fold in per-agent Codex config would pull in the
+// DB client, which has no database in this unit test.
+vi.mock('@main/core/agents/getAgentById', () => ({
+ getAgentById: vi.fn(async () => null),
+}));
+
// Reads the app's userData path and shells out to `gh`; neither exists here,
// and these tests are about the spawn, not the registry.
vi.mock('@main/core/switch-rooms/npm-registry-auth', () => ({
@@ -94,18 +102,20 @@ vi.mock('@main/core/providers/plugin-registry', () => ({
getPluginVersion: vi.fn(),
getPluginPath: vi.fn(),
},
+ // The real builder, not a stand-in: these tests exist to check what the
+ // profile actually tells Codex, which a fake profile cannot show.
+ mcp:
+ id === 'codex'
+ ? (pluginRegistry.get('codex')!.behavior as { mcp?: unknown }).mcp
+ : undefined,
},
})),
}));
+// Keyed by root because the runtime opens two: the workspace (creds) and the
+// home dir (the Codex profile). A single shared fake cannot tell them apart.
vi.mock('@main/core/providers/plugin-fs', () => ({
- createPluginFs: vi.fn(() => ({
- read: vi.fn(async () => null),
- write: vi.fn(async () => {}),
- delete: vi.fn(async () => {}),
- exists: vi.fn(async () => false),
- list: vi.fn(async () => []),
- })),
+ createPluginFs: vi.fn((root: string) => pluginFsFor(root)),
}));
vi.mock('@main/core/pty/local-pty', () => ({
@@ -220,6 +230,35 @@ function session(): Session {
};
}
+/** One in-memory PluginFs per root, so a test can read what was written where. */
+const pluginFsRoots = new Map<string, Map<string, string>>();
+
+function pluginFsFor(root: string) {
+ const files = pluginFsRoots.get(root) ?? new Map<string, string>();
+ pluginFsRoots.set(root, files);
+ return {
+ read: vi.fn(async (p: string) => files.get(p) ?? null),
+ write: vi.fn(async (p: string, content: string) => {
+ files.set(p, content);
+ }),
+ delete: vi.fn(async (p: string) => {
+ files.delete(p);
+ }),
+ exists: vi.fn(async (p: string) => files.has(p)),
+ list: vi.fn(async () => []),
+ };
+}
+
+/** The Codex profile written to the agent's home, whichever root that was. */
+function writtenCodexProfile(): string {
+ for (const files of pluginFsRoots.values()) {
+ for (const [path, content] of files) {
+ if (path.endsWith('.config.toml')) return content;
+ }
+ }
+ throw new Error('no Codex profile was written');
+}
+
function fakePty(exitHandlers: Array<(info: PtyExitInfo) => void>): Pty {
return {
write: vi.fn(),
@@ -258,6 +297,58 @@ describe('local agent runtime respawn state', () => {
vi.mocked(agentHookService.getPort).mockReturnValue(0);
vi.mocked(agentHookService.getToken).mockReturnValue('token');
ptySessionRegistry.unregister('location-1:session-1');
+ pluginFsRoots.clear();
+ });
+
+ it('writes the Codex profile to the home dir and loads it on argv', async () => {
+ const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
+ spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
+ vi.mocked(readAgentSwitchEnvFromFs).mockResolvedValueOnce({
+ SWITCH_API_ENDPOINT: 'https://switch.example.com',
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'sw-1',
+ });
+
+ await localProvider().start(session());
+
+ expect(writtenCodexProfile()).toContain('[mcp_servers.switch]');
+ // Profile name is digest-suffixed on (dir, slug) so same-named agents in
+ // different dirs don't collide.
+ expect(buildCommandMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ agentArgs: ['--profile', expect.stringMatching(/^codex-hoot-[a-z0-9]+$/)],
+ })
+ );
+ });
+
+ it('puts every variable the profile forwards onto the session it spawns', async () => {
+ // Codex forwards these by name out of its own environment, so a name the
+ // profile lists but the session lacks reaches the runtime as nothing at
+ // all — and a missing credential kills the handshake, not just one tool.
+ const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
+ spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
+ vi.mocked(readAgentSwitchEnvFromFs).mockResolvedValueOnce({
+ SWITCH_API_ENDPOINT: 'https://switch.example.com',
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'sw-1',
+ });
+
+ await localProvider().start(session());
+
+ const server = (
+ parseTOML(writtenCodexProfile()) as {
+ mcp_servers: Record<string, { env_vars?: string[] }>;
+ }
+ ).mcp_servers.switch;
+ const spawned = (spawnLocalPty.mock.calls[0][0] as { env: Record<string, string> }).env;
+
+ expect(server.env_vars?.length).toBeGreaterThan(0);
+ for (const name of server.env_vars ?? []) {
+ // SWITCH_CONNECTION_ID and the npm settings come from services stubbed
+ // out here; the credentials are the ones this path is responsible for.
+ if (!name.startsWith('SWITCH_API') && name !== 'SWITCH_AGENT_ID') continue;
+ expect(spawned).toHaveProperty(name);
+ }
});
it('reads the identity file keyed by the agent row name, not the session id', async () => {
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
index 2a2e630b3..f7efbbc15 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
@@ -4,8 +4,10 @@ import { dirTrustService } from '@main/core/agent-hooks/dir-trust-service';
import { ensureHooksInstalled } from '@main/core/agent-hooks/hook-config-service';
import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';
import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';
+import { prepareSwitchMcpLaunch } from '@main/core/agent-runtime/switch-mcp-launch-args';
import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';
+import { getAgentById } from '@main/core/agents/getAgentById';
import { localDependencyManager } from '@main/core/dependencies/dependency-managers';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
@@ -28,6 +30,7 @@ import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
import { events } from '@main/lib/events';
import { runWithLogContext } from '@main/lib/log-context';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makePtyId } from '@shared/core/pty/ptyId';
import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
@@ -156,14 +159,47 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
cachedStatePath,
});
+ // A session talks to Switch as its own agent, not whatever identity happens
+ // to sit in `.claude/settings.local.json`. Real env vars outrank every
+ // settings file and reach the spawned MCP server, so inject the agent's
+ // identity last (highest precedence): a subagent from its definition creds,
+ // and a plain agent from its provider-neutral `.switch/agents/<slug>.json`
+ // (empty when absent — the session then falls back to settings.local.json,
+ // which Claude reads natively).
+ // Resolved before the command is built because a provider that registers
+ // the Switch server at launch keys it on this identity (see below).
+ const workspaceFs = createPluginFs(this.sessionPath);
+ const identityVars =
+ session.agentName && repoAgents
+ ? await repoAgents.readLaunchEnv(workspaceFs, session.agentName)
+ : await readAgentSwitchEnvFromFs(workspaceFs, agentCredsSlug(session), log);
+
+ // Register the Switch MCP server for providers that cannot resolve it from
+ // a bundled config (Codex): writes a per-agent profile under `~/.codex` and
+ // returns `--profile <slug>`, folding in the agent's per-agent model /
+ // effort / instructions. A no-op for Claude, whose plugin expands its own
+ // `.mcp.json`.
+ const agentRecord = await getAgentById(session.agentId);
+ const switchMcpArgs = await prepareSwitchMcpLaunch(plugin, {
+ homeFs: createPluginFs(homedir()),
+ slug: agentCredsSlug(session),
+ workingDir: this.sessionPath,
+ hasSwitchIdentity: !!identityVars.SWITCH_API_ENDPOINT,
+ specialization: toSwitchSpecialization(agentRecord?.providerConfig),
+ });
+
const agentCommand = plugin.behavior.prompt!.buildCommand({
cli: executableCli,
extraArgs: parseExtraArgs(providerConfig?.extraArgs),
- // The provider owns how to run as the named agent (CHOO-1440).
- agentArgs:
- session.agentName && repoAgents
+ // The provider owns how to run as the named agent (CHOO-1440), and how to
+ // receive a per-session Switch MCP server when it cannot read one from a
+ // config file.
+ agentArgs: [
+ ...(session.agentName && repoAgents
? repoAgents.launchArgs(this.sessionPath, session.agentName)
- : [],
+ : []),
+ ...switchMcpArgs,
+ ],
autoApprove: session.autoApprove ?? false,
initialPrompt: agentSession.isResuming ? undefined : initialPrompt,
sessionId: agentSession.sessionId,
@@ -181,18 +217,6 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
const port = agentHookService.getPort();
const token = agentHookService.getToken();
const colorEnv = await getTerminalColorEnv();
- // A session talks to Switch as its own agent, not whatever identity happens
- // to sit in `.claude/settings.local.json`. Real env vars outrank every
- // settings file and reach the spawned MCP server, so inject the agent's
- // identity last (highest precedence): a subagent from its definition creds,
- // and a plain agent from its provider-neutral `.switch/agents/<slug>.json`
- // (empty when absent — only Claude then recovers, by reading
- // settings.local.json natively; any other provider launches unidentified).
- const workspaceFs = createPluginFs(this.sessionPath);
- const identityVars =
- session.agentName && repoAgents
- ? await repoAgents.readLaunchEnv(workspaceFs, session.agentName)
- : await readAgentSwitchEnvFromFs(workspaceFs, agentCredsSlug(session), log);
// Open this session's Switch connection before the session exists, and
// hand it the id. Its tool calls then arrive on the connection switchdash
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts
new file mode 100644
index 000000000..58c160b8c
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { IExecutionContext } from '@main/core/execution-context/types';
+import { createRemoteHomePluginFs } from './remote-home-plugin-fs';
+
+function makeCtx(exec: (command: string, args: string[]) => Promise<{ stdout: string }>) {
+ const spy = vi.fn(async (command: string, args?: string[]) => ({
+ ...(await exec(command, args ?? [])),
+ stderr: '',
+ }));
+ return { ctx: { exec: spy } as unknown as IExecutionContext, exec: spy };
+}
+
+describe('createRemoteHomePluginFs', () => {
+ it('sends the path and the content as positional arguments, never inline', async () => {
+ const { ctx, exec } = makeCtx(async () => ({ stdout: '' }));
+
+ await createRemoteHomePluginFs(ctx).write('.codex/hooks.json', '{"hooks":{}}');
+
+ const [command, args] = exec.mock.calls[0]!;
+ expect(command).toBe('sh');
+ expect(args).toContain('.codex/hooks.json');
+ expect(Buffer.from(args!.at(-1)!, 'base64').toString('utf8')).toBe('{"hooks":{}}');
+ // The script itself must name neither, or a quote in either breaks out of it.
+ expect(args![1]).not.toContain('.codex/hooks.json');
+ expect(args![1]).not.toContain('hooks":{}');
+ });
+
+ it('decodes the file content the far side base64-encoded', async () => {
+ const content = 'a = "b"\n# ünicode\n';
+ const { ctx } = makeCtx(async () => ({
+ stdout: `1${Buffer.from(content, 'utf8').toString('base64')}\n`,
+ }));
+
+ expect(await createRemoteHomePluginFs(ctx).read('.codex/config.toml')).toBe(content);
+ });
+
+ it('reads a missing file as null', async () => {
+ const { ctx } = makeCtx(async () => ({ stdout: '0' }));
+
+ expect(await createRemoteHomePluginFs(ctx).read('.codex/config.toml')).toBeNull();
+ });
+
+ // Hook writers read-modify-write these files. A transport failure reported as
+ // "missing" makes them rewrite from scratch, discarding whatever was there —
+ // for `.claude/settings.local.json`, the agent's Switch credentials.
+ it('propagates a failed read instead of reporting the file as absent', async () => {
+ const { ctx } = makeCtx(async () => {
+ throw new Error('ssh: channel exhausted');
+ });
+
+ await expect(createRemoteHomePluginFs(ctx).read('.codex/config.toml')).rejects.toThrow(
+ 'channel exhausted'
+ );
+ });
+
+ it('rejects an unrecognised read response rather than guessing', async () => {
+ const { ctx } = makeCtx(async () => ({ stdout: '-bash: base64: command not found\n' }));
+
+ await expect(createRemoteHomePluginFs(ctx).read('.codex/config.toml')).rejects.toThrow(
+ /unreadable response/
+ );
+ });
+
+ it('refuses a path that would escape the home directory', async () => {
+ const { ctx, exec } = makeCtx(async () => ({ stdout: '0' }));
+
+ await expect(createRemoteHomePluginFs(ctx).read('../../etc/passwd')).rejects.toThrow(
+ /outside the home directory/
+ );
+ await expect(createRemoteHomePluginFs(ctx).write('/etc/passwd', 'x')).rejects.toThrow(
+ /outside the home directory/
+ );
+ expect(exec).not.toHaveBeenCalled();
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts
new file mode 100644
index 000000000..00a4a4e0a
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-home-plugin-fs.ts
@@ -0,0 +1,81 @@
+import type { PluginFs } from '@switchdash/core/agents/plugins';
+import type { IExecutionContext } from '@main/core/execution-context/types';
+
+/**
+ * Adapt a remote host to the `PluginFs` shape, rooted at the VM's `$HOME`.
+ *
+ * The SSH `FileSystemProvider` is rooted at the agent's repo dir, so a provider
+ * whose config lives in the home directory — Codex writes its hooks to
+ * `~/.codex/hooks.json` and its Switch profile beside them — cannot be reached
+ * through it at all. Everything here therefore runs as a shell command: the far
+ * side expands `$HOME`, and paths and file contents travel as positional
+ * arguments (contents base64-encoded) so neither can break out of the command.
+ */
+export function createRemoteHomePluginFs(ctx: IExecutionContext): PluginFs {
+ const checked = (path: string): string => {
+ const segments = path.split('/');
+ if (path.startsWith('/') || segments.includes('..') || segments.includes('')) {
+ throw new Error(`remote home fs: refusing a path outside the home directory: ${path}`);
+ }
+ return path;
+ };
+
+ return {
+ /**
+ * The first byte of stdout says whether the file was there: `1` followed by
+ * its base64 content, or `0`. Distinguishing "absent" from "unreadable" is
+ * load-bearing — hook writers read-modify-write these files, and a transport
+ * failure reported as "missing" makes them rewrite from scratch.
+ */
+ async read(path: string): Promise<string | null> {
+ const { stdout } = await ctx.exec('sh', [
+ '-c',
+ 'f="$HOME/$1"; if [ -f "$f" ]; then printf 1; base64 < "$f"; else printf 0; fi',
+ 'sh',
+ checked(path),
+ ]);
+ if (stdout.startsWith('0')) return null;
+ if (!stdout.startsWith('1')) {
+ throw new Error(`remote home fs: unreadable response while reading ${path}`);
+ }
+ return Buffer.from(stdout.slice(1), 'base64').toString('utf8');
+ },
+
+ async write(path: string, content: string): Promise<void> {
+ await ctx.exec('sh', [
+ '-c',
+ 'set -e; mkdir -p "$HOME/$(dirname "$1")"; printf %s "$2" | base64 -d > "$HOME/$1"',
+ 'sh',
+ checked(path),
+ Buffer.from(content, 'utf8').toString('base64'),
+ ]);
+ },
+
+ async delete(path: string): Promise<void> {
+ await ctx.exec('sh', ['-c', 'rm -f "$HOME/$1"', 'sh', checked(path)]);
+ },
+
+ async exists(path: string): Promise<boolean> {
+ const { stdout } = await ctx.exec('sh', [
+ '-c',
+ 'if [ -e "$HOME/$1" ]; then printf 1; else printf 0; fi',
+ 'sh',
+ checked(path),
+ ]);
+ return stdout.trim() === '1';
+ },
+
+ async list(path: string): Promise<string[]> {
+ const { stdout } = await ctx.exec('sh', [
+ '-c',
+ 'if [ -d "$HOME/$1" ]; then ls -1A "$HOME/$1"; fi',
+ 'sh',
+ checked(path),
+ ]);
+ return stdout
+ .split('\n')
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0);
+ },
+ };
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts
index 719b9e84f..996a266fd 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts
@@ -1,5 +1,6 @@
import { dirname } from 'node:path/posix';
import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { assertRemoved } from '@main/core/fs/assert-removed';
import {
FileSystemError,
FileSystemErrorCodes,
@@ -47,7 +48,7 @@ export function createRemotePluginFs(fs: FileSystemProvider): PluginFs {
},
async delete(path: string): Promise<void> {
- await fs.remove(path);
+ assertRemoved(path, await fs.remove(path));
},
async exists(path: string): Promise<boolean> {
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts
index 2eb668b9a..70a264893 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts
@@ -6,7 +6,24 @@ export interface SidecarChannelOpener {
}
/**
- * Speak HTTP/1.1 GET directly over the provided duplex and parse the JSON body.
+ * A response the sidecar answered with that was not a success. Carries the
+ * status because callers act on it: a 404 means the running sidecar predates
+ * the endpoint, which is a different problem from an unreachable host and has a
+ * different remedy.
+ */
+export class SidecarHttpStatusError extends Error {
+ constructor(
+ readonly status: number,
+ message: string
+ ) {
+ super(message);
+ this.name = 'SidecarHttpStatusError';
+ }
+}
+
+/**
+ * Speak one HTTP/1.1 request directly over the provided duplex and read the
+ * reply.
*
* We can't use `http.request` here: the sidecar listens on the REMOTE host's
* loopback, reachable only through the SSH-forwarded channel, but `http.request`
@@ -15,17 +32,20 @@ export interface SidecarChannelOpener {
* `Connection: close` makes the server end the socket after the response, so we
* read to EOF; the sidecar always sends an explicit `Content-Length`, so we
* finish as soon as that many body bytes have arrived without de-chunking.
+ *
+ * `wantBody` false resolves the moment the status line has arrived, for an
+ * endpoint whose reply carries nothing worth waiting for.
*/
-export function httpGetJsonOverChannel<T>(
+function exchangeOverChannel(
channel: Duplex,
- opts: { port: number; token: string; path: string; timeoutMs: number }
-): Promise<T> {
- const { port, token, path, timeoutMs } = opts;
- return new Promise<T>((resolve, reject) => {
+ opts: { method: string; path: string; timeoutMs: number; wantBody: boolean; request: Buffer[] }
+): Promise<{ status: number; body: string }> {
+ const { method, path, timeoutMs, wantBody, request } = opts;
+ return new Promise((resolve, reject) => {
let settled = false;
const chunks: Buffer[] = [];
- const finish = (err: Error | null, value?: T): void => {
+ const finish = (err: Error | null, value?: { status: number; body: string }): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
@@ -33,10 +53,10 @@ export function httpGetJsonOverChannel<T>(
else resolve(value!);
};
- const timer = setTimeout(() => finish(new Error(`GET ${path} timed out`)), timeoutMs);
+ const timer = setTimeout(() => finish(new Error(`${method} ${path} timed out`)), timeoutMs);
/**
- * Try to parse the accumulated bytes as a complete HTTP response. `atEof` is
+ * Try to read the accumulated bytes as a complete HTTP response. `atEof` is
* true when the readable side has ended and no more bytes will arrive — only
* then is an incomplete buffer an error. While still streaming we return
* quietly and wait for the next chunk.
@@ -52,26 +72,24 @@ export function httpGetJsonOverChannel<T>(
const head = raw.slice(0, sep);
const statusLine = head.slice(0, head.indexOf('\r\n'));
const status = Number.parseInt(statusLine.split(' ')[1] ?? '', 10);
- if (status !== 200) {
- finish(new Error(`GET ${path} returned status ${status || statusLine}`));
+ if (!Number.isFinite(status) || status === 0) {
+ finish(new Error(`${method} ${path} returned an unparseable status: ${statusLine}`));
return;
}
const body = raw.slice(sep + 4);
- const contentLength = /content-length:\s*(\d+)/i.exec(head);
- if (contentLength) {
- if (Buffer.byteLength(body, 'utf8') < Number.parseInt(contentLength[1]!, 10)) {
- if (atEof) finish(new Error(`truncated HTTP response from sidecar ${path}`));
+ if (wantBody) {
+ const contentLength = /content-length:\s*(\d+)/i.exec(head);
+ if (contentLength) {
+ if (Buffer.byteLength(body, 'utf8') < Number.parseInt(contentLength[1]!, 10)) {
+ if (atEof) finish(new Error(`truncated HTTP response from sidecar ${path}`));
+ return;
+ }
+ } else if (!atEof) {
+ // No Content-Length: the body runs to EOF, so wait for end/close.
return;
}
- } else if (!atEof) {
- // No Content-Length: the body runs to EOF, so wait for end/close.
- return;
- }
- try {
- finish(null, JSON.parse(body) as T);
- } catch (error) {
- finish(error instanceof Error ? error : new Error(String(error)));
}
+ finish(null, { status, body });
};
channel.on('data', (chunk: Buffer) => {
@@ -82,71 +100,94 @@ export function httpGetJsonOverChannel<T>(
channel.on('end', () => tryParse(true));
channel.on('close', () => tryParse(true));
- channel.write(
- `GET ${path} HTTP/1.1\r\n` +
- `Host: 127.0.0.1:${port}\r\n` +
- `x-switchdash-token: ${token}\r\n` +
- `Connection: close\r\n\r\n`
- );
+ for (const part of request) channel.write(part);
});
}
+function requestHead(
+ method: string,
+ opts: { port: number; token: string; path: string },
+ contentLength: number | null
+): Buffer {
+ const { port, token, path } = opts;
+ return Buffer.from(
+ `${method} ${path} HTTP/1.1\r\n` +
+ `Host: 127.0.0.1:${port}\r\n` +
+ `x-switchdash-token: ${token}\r\n` +
+ (contentLength === null
+ ? ''
+ : `Content-Type: application/json\r\nContent-Length: ${contentLength}\r\n`) +
+ `Connection: close\r\n\r\n`,
+ 'utf8'
+ );
+}
+
+function parseJsonBody<T>(path: string, body: string): T {
+ try {
+ return JSON.parse(body) as T;
+ } catch (error) {
+ throw new Error(`malformed JSON body from sidecar ${path}: ${String(error)}`);
+ }
+}
+
+/** GET a JSON document from the sidecar over an SSH-forwarded channel. */
+export async function httpGetJsonOverChannel<T>(
+ channel: Duplex,
+ opts: { port: number; token: string; path: string; timeoutMs: number }
+): Promise<T> {
+ const { status, body } = await exchangeOverChannel(channel, {
+ method: 'GET',
+ path: opts.path,
+ timeoutMs: opts.timeoutMs,
+ wantBody: true,
+ request: [requestHead('GET', opts, null)],
+ });
+ if (status !== 200) {
+ throw new SidecarHttpStatusError(status, `GET ${opts.path} returned status ${status}`);
+ }
+ return parseJsonBody<T>(opts.path, body);
+}
+
/**
- * Speak HTTP/1.1 POST directly over the provided duplex, sending a JSON body,
- * and resolve once a 2xx response is received. Same transport constraints as
- * `httpGetJsonOverChannel` (the sidecar is on the remote loopback), but we only
- * need the status — the sidecar's `/disconnect` replies with an empty 200 body.
+ * POST a JSON body to the sidecar and resolve once a 2xx comes back. For an
+ * endpoint whose reply is empty — `/disconnect` answers with a bare 200.
*/
-export function httpPostJsonOverChannel(
+export async function httpPostJsonOverChannel(
channel: Duplex,
opts: { port: number; token: string; path: string; body: unknown; timeoutMs: number }
): Promise<void> {
- const { port, token, path, body, timeoutMs } = opts;
- return new Promise<void>((resolve, reject) => {
- let settled = false;
- const chunks: Buffer[] = [];
-
- const finish = (err: Error | null): void => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- if (err) reject(err);
- else resolve();
- };
-
- const timer = setTimeout(() => finish(new Error(`POST ${path} timed out`)), timeoutMs);
-
- const tryParse = (atEof: boolean): void => {
- if (settled) return;
- const raw = Buffer.concat(chunks).toString('utf8');
- const sep = raw.indexOf('\r\n\r\n');
- if (sep === -1) {
- if (atEof) finish(new Error(`malformed HTTP response from sidecar ${path}`));
- return;
- }
- const statusLine = raw.slice(0, raw.indexOf('\r\n'));
- const status = Number.parseInt(statusLine.split(' ')[1] ?? '', 10);
- if (status >= 200 && status < 300) finish(null);
- else finish(new Error(`POST ${path} returned status ${status || statusLine}`));
- };
-
- channel.on('data', (chunk: Buffer) => {
- chunks.push(chunk);
- tryParse(false);
- });
- channel.on('error', (err: Error) => finish(err));
- channel.on('end', () => tryParse(true));
- channel.on('close', () => tryParse(true));
+ const payload = Buffer.from(JSON.stringify(opts.body), 'utf8');
+ const { status } = await exchangeOverChannel(channel, {
+ method: 'POST',
+ path: opts.path,
+ timeoutMs: opts.timeoutMs,
+ wantBody: false,
+ request: [requestHead('POST', opts, payload.byteLength), payload],
+ });
+ if (status < 200 || status >= 300) {
+ throw new SidecarHttpStatusError(status, `POST ${opts.path} returned status ${status}`);
+ }
+}
- const payload = Buffer.from(JSON.stringify(body), 'utf8');
- channel.write(
- `POST ${path} HTTP/1.1\r\n` +
- `Host: 127.0.0.1:${port}\r\n` +
- `x-switchdash-token: ${token}\r\n` +
- `Content-Type: application/json\r\n` +
- `Content-Length: ${payload.byteLength}\r\n` +
- `Connection: close\r\n\r\n`
- );
- channel.write(payload);
+/**
+ * POST a JSON body to the sidecar and parse the JSON document it answers with.
+ * For an endpoint whose reply is the point of the call — `/connection` returns
+ * the id the session must be launched with.
+ */
+export async function httpPostForJsonOverChannel<T>(
+ channel: Duplex,
+ opts: { port: number; token: string; path: string; body: unknown; timeoutMs: number }
+): Promise<T> {
+ const payload = Buffer.from(JSON.stringify(opts.body), 'utf8');
+ const { status, body } = await exchangeOverChannel(channel, {
+ method: 'POST',
+ path: opts.path,
+ timeoutMs: opts.timeoutMs,
+ wantBody: true,
+ request: [requestHead('POST', opts, payload.byteLength), payload],
});
+ if (status < 200 || status >= 300) {
+ throw new SidecarHttpStatusError(status, `POST ${opts.path} returned status ${status}`);
+ }
+ return parseJsonBody<T>(opts.path, body);
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
index 494ed84d2..4b97c72a0 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
@@ -1,3 +1,5 @@
+import { pluginRegistry } from '@switchdash/plugins/agents';
+import { parse as parseTOML } from 'smol-toml';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';
import type { Pty, PtyExitInfo } from '@main/core/pty/pty';
@@ -6,6 +8,7 @@ import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
import type { Session } from '@shared/core/sessions/sessions';
+import { SidecarHttpStatusError } from './sidecar-http';
import { SshAgentRuntime } from './ssh-agent-runtime';
const openSsh2Pty = vi.hoisted(() => vi.fn());
@@ -16,6 +19,12 @@ const buildCommandMock = vi.hoisted(() =>
env: {} as Record<string, string>,
}))
);
+/** A provider with no `mcp` behavior — it resolves MCP servers from config. */
+const defaultGetPlugin = vi.hoisted(() => (id: string) => ({
+ metadata: { id },
+ capabilities: { hostDependency: { binaryNames: [id] }, hooks: { kind: 'none' } },
+ behavior: { prompt: { buildCommand: buildCommandMock } },
+}));
const resolveSshCommand = vi.hoisted(() => vi.fn(() => 'remote-cmd'));
const deployAndLaunch = vi.hoisted(() => vi.fn(async () => ({ port: 9999, token: 'sidecar-tok' })));
const sidecarStop = vi.hoisted(() => vi.fn(async () => {}));
@@ -37,11 +46,18 @@ vi.mock('./remote-sidecar-launcher', () => ({
}));
const httpPostJsonOverChannel = vi.hoisted(() => vi.fn(async () => {}));
+const httpPostForJsonOverChannel = vi.hoisted(() =>
+ vi.fn(async () => ({ connectionId: 'conn-remote-1' }))
+);
-// POST is spied so disconnect can be asserted; GET is parked so the hook-event
-// relay's poll loop doesn't spin in tests that don't exercise relaying.
-vi.mock('./sidecar-http', () => ({
+// POST is spied so disconnect and the connection hand-off can be asserted; GET
+// is parked so the hook-event relay's poll loop doesn't spin in tests that
+// don't exercise relaying. The real status error is kept: the runtime narrows
+// on it to tell an out-of-date sidecar from an unreachable one.
+vi.mock('./sidecar-http', async () => ({
+ ...(await vi.importActual<Record<string, unknown>>('./sidecar-http')),
httpPostJsonOverChannel,
+ httpPostForJsonOverChannel,
httpGetJsonOverChannel: vi.fn(() => new Promise(() => {})),
}));
@@ -76,11 +92,7 @@ vi.mock('@main/core/agents/getAgentById', () => ({
}));
vi.mock('@main/core/providers/plugin-registry', () => ({
- getPlugin: vi.fn((id: string) => ({
- metadata: { id },
- capabilities: { hostDependency: { binaryNames: [id] }, hooks: { kind: 'none' } },
- behavior: { prompt: { buildCommand: buildCommandMock } },
- })),
+ getPlugin: vi.fn(defaultGetPlugin),
}));
vi.mock('./keystroke-injection', () => ({
@@ -127,6 +139,8 @@ function emitReconnected(connectionId: string): void {
}
const { events } = await import('@main/lib/events');
+const { getAgentById } = await import('@main/core/agents/getAgentById');
+const { getPlugin } = await import('@main/core/providers/plugin-registry');
type ProviderState = {
known: boolean;
@@ -138,15 +152,19 @@ function makeProxy(overrides: Partial<SshClientProxy> = {}): SshClientProxy {
connectionId: 'ssh-1',
getRemoteShellProfile: vi.fn(async () => ({ shell: '/bin/bash', env: {} })),
refreshRemoteShellProfile: vi.fn(async () => ({ shell: '/bin/bash', env: {} })),
- // Never resolves: parks the hook-event relay's poll loop so it does not spin
- // in tests that don't exercise event relaying.
- forwardOut: vi.fn(() => new Promise<never>(() => {})),
+ // A channel opens, but the mocked GET on it never resolves — which parks the
+ // hook-event relay's poll loop so it does not spin in tests that don't
+ // exercise event relaying, while still letting the connection hand-off (a
+ // POST) complete.
+ forwardOut: vi.fn(async () => ({ destroy: vi.fn() }) as never),
...overrides,
} as unknown as SshClientProxy;
}
+/** A remote host with an empty home: the home-rooted read probe answers `0`
+ * ("no such file") and every other command exits quietly. */
function makeCtx(): ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'] {
- return { exec: vi.fn(async () => ({ stdout: '', stderr: '' })) } as never;
+ return { exec: vi.fn(async () => ({ stdout: '0', stderr: '' })) } as never;
}
/** A remote filesystem holding `files` (keyed by repo-relative path); anything
@@ -231,11 +249,14 @@ describe('SshAgentRuntime', () => {
openSsh2Pty.mockReset();
buildCommandMock.mockReset();
buildCommandMock.mockReturnValue({ command: 'agent', args: [], env: {} });
+ vi.mocked(getPlugin).mockImplementation(defaultGetPlugin as never);
resolveSshCommand.mockClear();
deployAndLaunch.mockClear();
remoteNpmRegistryAuthEnv.mockClear();
sidecarStop.mockClear();
httpPostJsonOverChannel.mockClear();
+ httpPostForJsonOverChannel.mockReset();
+ httpPostForJsonOverChannel.mockResolvedValue({ connectionId: 'conn-remote-1' });
vi.mocked(events.emit).mockClear();
connectionListeners.length = 0;
ptySessionRegistry.unregister('location-1:session-1');
@@ -290,6 +311,146 @@ describe('SshAgentRuntime', () => {
);
});
+ it('registers the Switch MCP server via a profile written to the VM home', async () => {
+ // The endpoint and token reach the session as env vars, but Codex only learns
+ // the server exists from a profile loaded with `--profile`. Without this a
+ // remote Codex session comes up authenticated and with no `switch` tools.
+ const ctx = makeCtx();
+ vi.mocked(getPlugin).mockImplementation(
+ (id: string) =>
+ ({
+ metadata: { id },
+ capabilities: { hostDependency: { binaryNames: [id] }, hooks: { kind: 'none' } },
+ behavior: {
+ prompt: { buildCommand: buildCommandMock },
+ // The real builder, so the payload written to the VM is the profile
+ // Codex will actually read rather than a stand-in string.
+ mcp: (pluginRegistry.get('codex')!.behavior as { mcp?: unknown }).mcp,
+ },
+ }) as never
+ );
+ vi.mocked(getAgentById).mockResolvedValueOnce({
+ autoApprove: false,
+ name: 'codex-hoot',
+ } as never);
+ mockSpawn([]);
+
+ await sshProvider({
+ ctx,
+ fs: makeRemoteFs({
+ '.switch/agents/codex-hoot.json': JSON.stringify({
+ env: {
+ SWITCH_API_ENDPOINT: 'https://switch.example.com/',
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'sw-1',
+ },
+ }),
+ }),
+ }).start(session());
+
+ // Profile name is digest-suffixed on (dir, slug); the argv and the written
+ // path must carry the same name.
+ expect(buildCommandMock).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ agentArgs: ['--profile', expect.stringMatching(/^codex-hoot-[a-z0-9]+$/)],
+ })
+ );
+ // The profile is written to the VM home over ctx.exec (base64), not the
+ // repo-dir filesystem.
+ expect(ctx.exec).toHaveBeenCalledWith(
+ 'sh',
+ expect.arrayContaining([
+ expect.stringMatching(/^\.codex\/codex-hoot-[a-z0-9]+\.config\.toml$/),
+ ])
+ );
+
+ // Every credential the profile tells Codex to forward must be on the remote
+ // session, or the runtime starts blind and never answers the handshake.
+ const written = (vi.mocked(ctx.exec).mock.calls as unknown[][])
+ .flatMap((call) => (call[1] as string[]) ?? [])
+ .map((arg) => {
+ try {
+ return Buffer.from(arg, 'base64').toString('utf8');
+ } catch {
+ return '';
+ }
+ })
+ .find((decoded) => decoded.includes('[mcp_servers.switch]'));
+ const server = (parseTOML(written!) as { mcp_servers: Record<string, { env_vars?: string[] }> })
+ .mcp_servers.switch;
+ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;
+
+ expect(server.env_vars?.length).toBeGreaterThan(0);
+ for (const name of server.env_vars ?? []) {
+ // Only the identity tier here: this session runs without tmux, so it has
+ // no sidecar and therefore no connection id or registry config. The tmux
+ // path below covers the rest of what the profile forwards.
+ if (!name.startsWith('SWITCH_API') && name !== 'SWITCH_AGENT_ID') continue;
+ expect(env).toHaveProperty(name);
+ }
+ });
+
+ // Codex keeps its hooks in `~/.codex/hooks.json`, which the repo-rooted SFTP
+ // filesystem cannot reach. Skipped, the VM has nothing that posts to the
+ // sidecar: SessionStart never fires so no provider session id is captured and
+ // every resume silently starts a new conversation, and Stop never fires so the
+ // room's "working on it" never clears.
+ it('installs a global-scope provider hooks under the VM home', async () => {
+ const ctx = makeCtx();
+ vi.mocked(getPlugin).mockImplementation(
+ (id: string) =>
+ ({
+ metadata: { id },
+ capabilities: {
+ hostDependency: { binaryNames: [id] },
+ hooks: { kind: 'config', scope: 'global', supportedEvents: ['stop'] },
+ },
+ behavior: {
+ prompt: { buildCommand: buildCommandMock },
+ hooks: pluginRegistry.get('codex')!.behavior.hooks,
+ },
+ }) as never
+ );
+ mockSpawn([]);
+
+ await sshProvider({ ctx, tmux: true }).start(session());
+
+ const written = (vi.mocked(ctx.exec).mock.calls as unknown[][])
+ .map((call) => (call[1] as string[]) ?? [])
+ .find((args) => args.includes('.codex/hooks.json') && args[1]?.includes('base64 -d'));
+ expect(written).toBeDefined();
+ const config = JSON.parse(Buffer.from(written!.at(-1)!, 'base64').toString('utf8')) as {
+ hooks: Record<string, unknown[]>;
+ };
+ expect(Object.keys(config.hooks).sort()).toEqual(['PermissionRequest', 'SessionStart', 'Stop']);
+ });
+
+ // Neither root fits a scope nobody has taught the remote path about, and the
+ // session would come up with no hooks at all — which looks fine until someone
+ // notices resume has been starting fresh conversations for a month.
+ it('refuses to start a session whose hook scope has no remote root', async () => {
+ vi.mocked(getPlugin).mockImplementation(
+ (id: string) =>
+ ({
+ metadata: { id },
+ capabilities: {
+ hostDependency: { binaryNames: [id] },
+ hooks: { kind: 'config', scope: 'user-profile', supportedEvents: ['stop'] },
+ },
+ behavior: {
+ prompt: { buildCommand: buildCommandMock },
+ hooks: pluginRegistry.get('codex')!.behavior.hooks,
+ },
+ }) as never
+ );
+ mockSpawn([]);
+
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(
+ /no remote hook root for scope 'user-profile'/
+ );
+ expect(openSsh2Pty).not.toHaveBeenCalled();
+ });
+
it('propagates a failed SSH channel open as an error', async () => {
openSsh2Pty.mockResolvedValue({ success: false, error: new Error('channel refused') });
@@ -384,6 +545,79 @@ describe('SshAgentRuntime', () => {
expect(env.SWITCH_CHANNEL_DISABLE_POLL).toBe('1');
});
+ // A session's room is claimed on the connection whose id it carries, and on a
+ // remote host only the sidecar reads that connection. Left to mint its own,
+ // the session is addressable by nobody: an @-mention reaches silence and the
+ // session shows no room, while the identical local session works.
+ it('opens a connection on the sidecar and hands its id to the remote session', async () => {
+ mockSpawn([]);
+
+ await sshProvider({ tmux: true }).start(session());
+
+ expect(httpPostForJsonOverChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ path: '/connection',
+ body: { sessionId: 'session-1', providerId: 'codex' },
+ })
+ );
+ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;
+ expect(env.SWITCH_CONNECTION_ID).toBe('conn-remote-1');
+ });
+
+ // A sidecar predating the endpoint 404s. Starting anyway would put the session
+ // back in exactly the silence the hand-off exists to prevent, so the start has
+ // to fail and say which upgrade fixes it.
+ it('fails the start when the sidecar has no /connection endpoint', async () => {
+ mockSpawn([]);
+ httpPostForJsonOverChannel.mockRejectedValue(
+ new SidecarHttpStatusError(404, 'POST /connection returned status 404')
+ );
+
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(
+ /did not open a Switch connection.*restart it to upgrade/s
+ );
+ expect(openSsh2Pty).not.toHaveBeenCalled();
+ });
+
+ // An unreachable host is a different fault with a different fix, so it must
+ // not be reported as an out-of-date sidecar.
+ it('does not blame the sidecar version when the connection call simply fails', async () => {
+ mockSpawn([]);
+ httpPostForJsonOverChannel.mockRejectedValue(new Error('POST /connection timed out'));
+
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(
+ /did not open a Switch connection/
+ );
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.not.toThrow(
+ /restart it to upgrade/
+ );
+ });
+
+ // Left open the connection keeps renewing, so the agent shows `live` in its
+ // room with no session behind it — the CHOO-1106 ghost, now reachable through
+ // a launch that dies between opening the connection and starting the pane.
+ it('hands the connection back when the launch fails after opening it', async () => {
+ openSsh2Pty.mockResolvedValue({ success: false, error: new Error('channel refused') });
+
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow('channel refused');
+
+ expect(httpPostJsonOverChannel).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ path: '/disconnect',
+ body: { sessionId: 'session-1', terminated: false },
+ })
+ );
+ });
+
+ it('rejects a /connection reply carrying no id rather than launching without one', async () => {
+ mockSpawn([]);
+ httpPostForJsonOverChannel.mockResolvedValue({} as never);
+
+ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(/no connection id/);
+ });
+
// The runtime is fetched with `npx` from a private registry, so without this
// the remote session comes up with no MCP server and npm reports a 404 that
// names neither the registry nor the missing credential.
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index 0ce86ae51..d9b06ad9f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -1,7 +1,9 @@
+import type { PluginFs, SwitchLaunchSpecialization } from '@switchdash/core/agents/plugins';
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';
import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';
import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';
+import { resolveSwitchLaunchProfile } from '@main/core/agent-runtime/switch-mcp-launch-args';
import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';
import { getAgentById } from '@main/core/agents/getAgentById';
@@ -26,25 +28,33 @@ import { readAgentSwitchEnvFromFs } from '@main/core/switch-rooms/switch-credent
import { events } from '@main/lib/events';
import { runWithLogContext } from '@main/lib/log-context';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import type { AgentSessionConfig } from '@shared/core/providers/agent-session';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';
import { makePtyId } from '@shared/core/pty/ptyId';
import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
import type { Session } from '@shared/core/sessions/sessions';
+import { SIDECAR_VERSION } from '../../../../sidecar/sidecar-version';
import { ensureAgentSidecar, probeAgentSidecar } from './ensure-agent-sidecar';
import { scheduleInitialPromptInjection } from './keystroke-injection';
+import { createRemoteHomePluginFs } from './remote-home-plugin-fs';
import { RemoteHookEventRelay } from './remote-hook-event-relay';
import { createRemotePluginFs } from './remote-plugin-fs';
import type { SidecarEndpoint, SidecarHost } from './remote-sidecar-launcher';
import { resolveAgentExecutable } from './resolve-agent-executable';
-import { httpPostJsonOverChannel } from './sidecar-http';
+import {
+ httpPostForJsonOverChannel,
+ httpPostJsonOverChannel,
+ SidecarHttpStatusError,
+} from './sidecar-http';
const DEFAULT_COLS = 80;
const DEFAULT_ROWS = 24;
const RESPAWN_DELAY_MS = 500;
const SHELL_NOT_FOUND_EXIT_CODE = 127;
const SIDECAR_DISCONNECT_TIMEOUT_MS = 5_000;
+const SIDECAR_CONNECTION_TIMEOUT_MS = 10_000;
function parseExtraArgs(value: string | undefined): string[] {
if (!value?.trim()) return [];
@@ -174,35 +184,83 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
}
/**
- * Install the provider's agent hooks into the remote workspace's
- * `.claude/settings.local.json` (or equivalent) over SFTP, mirroring what
+ * Where a provider's hook config lives on the VM. A workspace-scoped provider
+ * (Claude's `.claude/settings.local.json`) writes under the repo dir over
+ * SFTP; a global-scoped one (Codex's `~/.codex/hooks.json`) writes under the
+ * VM's home, which `this.fs` cannot reach at all.
+ */
+ private remoteHookFs(scope: 'global' | 'workspace'): PluginFs {
+ if (scope === 'global') return createRemoteHomePluginFs(this.ctx);
+ if (scope === 'workspace') return createRemotePluginFs(this.fs);
+ throw new Error(
+ `SshAgentRuntime: no remote hook root for scope '${String(scope)}' — the session would ` +
+ 'run with no hooks, reporting neither its provider session id nor when it stops'
+ );
+ }
+
+ /**
+ * Install the provider's agent hooks onto the VM, mirroring what
* `ensureHooksInstalled` does for local sessions. The remote agent is spawned
- * with the `SWITCHDASH_HOOK_*` env vars, but those only matter if the settings
- * actually register the hook commands — otherwise the agent posts no room/
- * status events to the sidecar. Best-effort: a failure is logged, not fatal.
+ * with the `SWITCHDASH_HOOK_*` env vars, but those only matter if its config
+ * actually registers the hook commands — otherwise the agent posts no
+ * lifecycle events to the sidecar, so its provider session id is never
+ * captured (every resume silently starts a new conversation) and the room's
+ * "working on it" never clears. Writing is best-effort: a failure is logged,
+ * not fatal.
*/
private async installRemoteHooks(providerId: string): Promise<void> {
const plugin = getPlugin(providerId);
const hooks = plugin.capabilities.hooks;
- if (hooks.kind !== 'config' || !plugin.behavior.hooks) return;
- if (hooks.scope !== 'workspace') {
- log.warn('SshAgentRuntime: skipping non-workspace-scoped remote hooks', {
+ if (hooks.kind === 'none') return;
+ if (hooks.kind !== 'config' || !plugin.behavior.hooks) {
+ log.error('SshAgentRuntime: provider hooks cannot be installed on a remote host', {
providerId,
- scope: hooks.scope,
+ kind: hooks.kind,
});
return;
}
+ const fs = this.remoteHookFs(hooks.scope);
try {
- await plugin.behavior.hooks.writeHooks(createRemotePluginFs(this.fs), []);
- log.info('SshAgentRuntime: installed remote agent hooks', { providerId });
+ await plugin.behavior.hooks.writeHooks(fs, []);
+ log.info('SshAgentRuntime: installed remote agent hooks', {
+ providerId,
+ scope: hooks.scope,
+ });
} catch (error) {
- log.warn('SshAgentRuntime: failed to install remote agent hooks', {
+ log.error('SshAgentRuntime: failed to install remote agent hooks', {
providerId,
+ scope: hooks.scope,
error: String(error),
});
}
}
+ /**
+ * Register the Switch MCP server for a provider that writes per-agent launch
+ * files under the VM's home (Codex: a profile). Returns the argv that loads
+ * the profile, or `[]` when there is nothing to write.
+ */
+ private async registerRemoteSwitchMcp(
+ plugin: ReturnType<typeof getPlugin>,
+ slug: string,
+ hasSwitchIdentity: boolean,
+ specialization: SwitchLaunchSpecialization | undefined
+ ): Promise<string[]> {
+ const profile = resolveSwitchLaunchProfile(plugin, {
+ slug,
+ workingDir: this.sessionPath,
+ hasSwitchIdentity,
+ specialization,
+ });
+ if (!profile) return [];
+
+ const homeFs = createRemoteHomePluginFs(this.ctx);
+ for (const file of profile.files) {
+ await homeFs.write(file.relativePath, file.content);
+ }
+ return profile.args;
+ }
+
private async launchSidecar(session: Session): Promise<SidecarEndpoint> {
// One agent-scoped sidecar serves every session on the VM (this one and any
// the sidecar's own watcher auto-starts) — ensure it is running and point
@@ -217,7 +275,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
deeplinkScheme: DEEPLINK_SCHEME,
autoApprove: agent?.autoApprove ?? false,
credsSlug: agentCredsSlug(session),
- agentName: session.agentName ?? null,
+ agentName: agent?.name ?? session.agentName ?? null,
+ specialization: toSwitchSpecialization(agent?.providerConfig),
ctx: this.ctx,
connectionId: this.connectionId,
host,
@@ -262,6 +321,55 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
}
}
+ /**
+ * Open this session's Switch connection on the VM's sidecar and return the id
+ * to hand it in its environment.
+ *
+ * The session's room is claimed on the connection whose id it carries, and
+ * only whoever reads that connection sees the room's events. On a remote host
+ * that reader is the sidecar — switchdash's own poller stands down for remote
+ * sessions and the in-session runtime's poll is disabled — so a session left
+ * to mint its own connection is addressable by nobody and never learns its
+ * room. Opened before the launch because the server refuses a call naming a
+ * connection that is not open, and the agent may call connect_to_room at once.
+ */
+ private async openSidecarConnection(
+ endpoint: SidecarEndpoint,
+ providerId: string
+ ): Promise<string> {
+ const channel = await this.proxy.forwardOut(endpoint.port);
+ let response: { connectionId?: unknown };
+ try {
+ response = await httpPostForJsonOverChannel<{ connectionId?: unknown }>(channel, {
+ port: endpoint.port,
+ token: endpoint.token,
+ path: '/connection',
+ body: { sessionId: this.sessionId, providerId },
+ timeoutMs: SIDECAR_CONNECTION_TIMEOUT_MS,
+ });
+ } catch (error) {
+ // Starting anyway would reproduce exactly the silence this exists to
+ // prevent, so refuse either way — but a 404 is its own diagnosis: the
+ // sidecar on this host predates the endpoint, and restarting it from the
+ // agent's sidecar panel upgrades it (an idle one upgrades itself).
+ const stale =
+ error instanceof SidecarHttpStatusError && error.status === 404
+ ? ` The sidecar on this host is older than ${SIDECAR_VERSION} and has no /connection endpoint; restart it to upgrade.`
+ : '';
+ throw new Error(
+ `SshAgentRuntime: the sidecar did not open a Switch connection for this session ` +
+ `(${String(error)}).${stale}`
+ );
+ } finally {
+ channel.destroy();
+ }
+ const connectionId = response.connectionId;
+ if (typeof connectionId !== 'string' || !connectionId) {
+ throw new Error('SshAgentRuntime: sidecar /connection returned no connection id');
+ }
+ return connectionId;
+ }
+
private async postDisconnect(
endpoint: { port: number; token: string },
sessionId: string,
@@ -307,7 +415,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
deeplinkScheme: DEEPLINK_SCHEME,
autoApprove: agent?.autoApprove ?? false,
credsSlug: agentCredsSlug(session),
- agentName: session.agentName ?? null,
+ agentName: agent?.name ?? session.agentName ?? null,
+ specialization: toSwitchSpecialization(agent?.providerConfig),
ctx: this.ctx,
connectionId: this.connectionId,
host: this.createSidecarHost(),
@@ -409,6 +518,11 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
this.known = true;
this.session = session;
+ // Declared out here so a launch that fails after the sidecar opened this
+ // session's connection can hand it back. Left open it keeps renewing, and
+ // the agent shows `live` in its room with no session behind it (CHOO-1106).
+ let switchEnv: Record<string, string> = {};
+
const spawnSize = ptySessionRegistry.getLastSize(ptySessionId) ?? initialSize;
const spawnToken = this.supervisor.beginStart({
requireDesired,
@@ -431,17 +545,42 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
connectionId: this.connectionId,
});
+ // The agent's Switch identity as real env vars (highest precedence): read
+ // from its neutral `.switch/agents/<slug>.json` on the VM. A `--settings`
+ // file's env block is not reliably propagated to the spawned MCP server, so
+ // inject it directly, matching the local runtime.
+ // Resolved before the command is built because a provider that registers the
+ // Switch server at launch keys it on this identity (see below).
+ const remoteFs = createRemotePluginFs(this.fs);
+ const identityVars =
+ session.agentName && repoAgents
+ ? await repoAgents.readLaunchEnv(remoteFs, session.agentName)
+ : await readAgentSwitchEnvFromFs(remoteFs, agentCredsSlug(session), log);
+
+ // Register the Switch MCP server (Codex writes a profile under the VM's
+ // ~/.codex), folding in the agent's per-agent model / effort / instructions.
+ const agentRecord = await getAgentById(session.agentId);
+ const switchMcpArgs = await this.registerRemoteSwitchMcp(
+ plugin,
+ agentCredsSlug(session),
+ !!identityVars.SWITCH_API_ENDPOINT,
+ toSwitchSpecialization(agentRecord?.providerConfig)
+ );
+
const agentCommand = plugin.behavior.prompt!.buildCommand({
cli: executableCli,
extraArgs: parseExtraArgs(providerConfig?.extraArgs),
// A remote agent runs as its own definition: the provider produces the
// run-as-name args (Claude → `--agent <name> --settings <neutral creds>`),
// resolved on the VM (sessionPath is remote). Distinct from user extra
- // args (CHOO-1440).
- agentArgs:
- session.agentName && repoAgents
+ // args (CHOO-1440). The provider also owns how it receives a per-session
+ // Switch MCP server when it cannot read one from a config file.
+ agentArgs: [
+ ...(session.agentName && repoAgents
? repoAgents.launchArgs(this.sessionPath, session.agentName)
- : [],
+ : []),
+ ...switchMcpArgs,
+ ],
autoApprove: session.autoApprove ?? false,
initialPrompt: agentSession.isResuming ? undefined : initialPrompt,
sessionId: agentSession.sessionId,
@@ -453,16 +592,6 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
const customEnv = providerConfig?.env ?? {};
const providerEnv: Record<string, string> = { ...agentCommand.env, ...customEnv };
- // The agent's Switch identity as real env vars (highest precedence): read
- // from its neutral `.switch/agents/<slug>.json` on the VM. A `--settings`
- // file's env block is not reliably propagated to the spawned MCP server, so
- // inject it directly, matching the local runtime.
- const remoteFs = createRemotePluginFs(this.fs);
- const identityVars =
- session.agentName && repoAgents
- ? await repoAgents.readLaunchEnv(remoteFs, session.agentName)
- : await readAgentSwitchEnvFromFs(remoteFs, agentCredsSlug(session), log);
-
const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;
const cfg: AgentSessionConfig = {
@@ -510,6 +639,9 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
token: endpoint.token,
endpointFile: endpoint.endpointFile,
});
+ switchEnv = {
+ SWITCH_CONNECTION_ID: await this.openSidecarConnection(endpoint, session.providerId),
+ };
} else {
log.warn(
'SshAgentRuntime: tmux disabled — remote agent will not stay connected to Switch while detached',
@@ -538,6 +670,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
...hookEnv,
...npmAuthEnv,
...identityVars,
+ ...switchEnv,
},
profile
);
@@ -618,6 +751,9 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
});
} catch (error) {
this.supervisor.failSpawn(spawnToken);
+ if (switchEnv.SWITCH_CONNECTION_ID) {
+ await this.disconnectSidecarSession(this.sessionId, false);
+ }
throw error;
}
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
index 865298aff..0bd8ce2b3 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
@@ -115,6 +115,11 @@ describe('resolveAgentSessionCommandArgs', () => {
});
expect(result.command).toBe('codex');
- expect(result.args).toEqual(['resume', 'provider-session-1']);
+ // Hook trust leads every Codex invocation, before the subcommand.
+ expect(result.args).toEqual([
+ '--dangerously-bypass-hook-trust',
+ 'resume',
+ 'provider-session-1',
+ ]);
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.test.ts
new file mode 100644
index 000000000..aa4d75656
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.test.ts
@@ -0,0 +1,218 @@
+import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { pluginRegistry } from '@switchdash/plugins/agents';
+import { parse as parseTOML } from 'smol-toml';
+import { describe, expect, it } from 'vitest';
+import type { getPlugin } from '@main/core/providers/plugin-registry';
+import { switchAgentRuntimeCommand } from '@shared/core/switch-rooms/switch-agent-runtime';
+import { prepareSwitchMcpLaunch, resolveSwitchLaunchProfile } from './switch-mcp-launch-args';
+
+type Plugin = ReturnType<typeof getPlugin>;
+
+/** The real Codex plugin — it registers the Switch server via a profile. */
+const codexPlugin = pluginRegistry.get('codex')! as unknown as Plugin;
+
+/** A provider whose connector resolves MCP servers itself, as Claude's does. */
+const claudeLikePlugin = { behavior: { mcp: {} } } as unknown as Plugin;
+
+/** An agent working directory; folded into the profile name for uniqueness. */
+const WD = '/home/agent/repo';
+
+/** The profile filename stem is the `--profile` value; assert they agree. */
+const PROFILE_STEM = /^codex-hoot-[a-z0-9]+$/;
+
+function memoryFs(): PluginFs & { files: Map<string, string> } {
+ const files = new Map<string, string>();
+ return {
+ files,
+ async read(p) {
+ return files.get(p) ?? null;
+ },
+ async write(p, c) {
+ files.set(p, c);
+ },
+ async delete(p) {
+ files.delete(p);
+ },
+ async exists(p) {
+ return files.has(p);
+ },
+ async list() {
+ return [];
+ },
+ };
+}
+
+describe('resolveSwitchLaunchProfile', () => {
+ it('returns a Codex profile registering the local stdio runtime, keyed on the (dir, slug)', () => {
+ const profile = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ });
+ expect(profile).not.toBeNull();
+ // The --profile value and the file stem are the same digest-suffixed name.
+ expect(profile!.args[0]).toBe('--profile');
+ expect(profile!.args[1]).toMatch(PROFILE_STEM);
+ expect(profile!.files[0].relativePath).toBe(`.codex/${profile!.args[1]}.config.toml`);
+ expect(profile!.files[0].content).toContain('[mcp_servers.switch]');
+ expect(profile!.files[0].content).toContain('command = "npx"');
+ expect(profile!.files[0].content).toContain('@sandbox-quantum/switch-agent-runtime@');
+ });
+
+ it('gives two agents that share a name in different dirs distinct profiles', () => {
+ const a = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: '/dir/one',
+ hasSwitchIdentity: true,
+ })!;
+ const b = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: '/dir/two',
+ hasSwitchIdentity: true,
+ })!;
+ expect(a.args).not.toEqual(b.args);
+ expect(a.files[0].relativePath).not.toBe(b.files[0].relativePath);
+ });
+
+ it('folds per-agent specialization into the one profile file', () => {
+ const profile = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ specialization: { model: 'gpt-5.6-terra', reasoningEffort: 'high', instructions: 'be terse' },
+ })!;
+ expect(profile.files).toHaveLength(1);
+ expect(profile.files[0].content).toContain('model = "gpt-5.6-terra"');
+ expect(profile.files[0].content).toContain('model_reasoning_effort = "high"');
+ // Additive: an instructions *file* would replace Codex's own operating
+ // manual, leaving the agent without the protocol it needs to act.
+ expect(profile.files[0].content).toContain('developer_instructions = "be terse"');
+ expect(profile.files[0].content).not.toContain('model_instructions_file');
+ });
+
+ it('keeps the system prompt out of the argv the SSH and tmux paths re-quote', () => {
+ const profile = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ specialization: { instructions: 'be terse\n$(whoami) "quoted"' },
+ })!;
+
+ expect(profile.args[0]).toBe('--profile');
+ expect(profile.args[1]).toMatch(PROFILE_STEM);
+ expect(profile.args.join(' ')).not.toContain('whoami');
+ });
+
+ it('tells Codex which variables to route into the server it spawns', () => {
+ // Codex gives an MCP child a fixed allowlist and nothing else, so a profile
+ // that names none of these produces a runtime with no credentials — which
+ // surfaces only as a closed connection during the handshake.
+ const profile = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ })!;
+ const server = (
+ parseTOML(profile.files[0].content) as {
+ mcp_servers: Record<string, { env_vars?: string[] }>;
+ }
+ ).mcp_servers.switch;
+
+ expect(server.env_vars).toEqual(switchAgentRuntimeCommand().envVars);
+ });
+
+ it('names the credentials without carrying them, so the profile is safe to bake and ship', () => {
+ const profile = resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'a',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ })!;
+ const server = (
+ parseTOML(profile.files[0].content) as {
+ mcp_servers: Record<string, { env?: unknown; bearer_token?: unknown; env_vars?: string[] }>;
+ }
+ ).mcp_servers.switch;
+
+ expect(server.env).toBeUndefined();
+ expect(server.bearer_token).toBeUndefined();
+ for (const name of server.env_vars ?? []) {
+ expect(name).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/);
+ }
+ expect(profile.files[0].content).not.toMatch(/Bearer /);
+ });
+
+ it('returns null when the provider resolves MCP servers some other way', () => {
+ expect(
+ resolveSwitchLaunchProfile(claudeLikePlugin, {
+ slug: 'x',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ })
+ ).toBeNull();
+ });
+
+ it('returns null when the session has no Switch identity', () => {
+ expect(
+ resolveSwitchLaunchProfile(codexPlugin, {
+ slug: 'x',
+ workingDir: WD,
+ hasSwitchIdentity: false,
+ })
+ ).toBeNull();
+ });
+});
+
+describe('prepareSwitchMcpLaunch', () => {
+ it('writes the profile under ~/.codex and returns the --profile argv', async () => {
+ const fs = memoryFs();
+ const args = await prepareSwitchMcpLaunch(codexPlugin, {
+ homeFs: fs,
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ });
+ expect(args[1]).toMatch(PROFILE_STEM);
+ expect(fs.files.get(`.codex/${args[1]}.config.toml`)).toContain('[mcp_servers.switch]');
+ });
+
+ it('writes the system prompt into the profile and no companion file', async () => {
+ const fs = memoryFs();
+ const args = await prepareSwitchMcpLaunch(codexPlugin, {
+ homeFs: fs,
+ slug: 'codex-hoot',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ specialization: { instructions: 'be terse' },
+ });
+
+ expect([...fs.files.keys()]).toEqual([`.codex/${args[1]}.config.toml`]);
+ expect(fs.files.get(`.codex/${args[1]}.config.toml`)).toContain(
+ 'developer_instructions = "be terse"'
+ );
+ });
+
+ it('writes nothing and returns [] when the session has no Switch identity', async () => {
+ const fs = memoryFs();
+ const args = await prepareSwitchMcpLaunch(codexPlugin, {
+ homeFs: fs,
+ slug: 'x',
+ workingDir: WD,
+ hasSwitchIdentity: false,
+ });
+ expect(args).toEqual([]);
+ expect(fs.files.size).toBe(0);
+ });
+
+ it('emits nothing for a provider that resolves MCP servers itself', async () => {
+ const fs = memoryFs();
+ expect(
+ await prepareSwitchMcpLaunch(claudeLikePlugin, {
+ homeFs: fs,
+ slug: 'x',
+ workingDir: WD,
+ hasSwitchIdentity: true,
+ })
+ ).toEqual([]);
+ expect(fs.files.size).toBe(0);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.ts
new file mode 100644
index 000000000..3a6f6182f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/switch-mcp-launch-args.ts
@@ -0,0 +1,67 @@
+import type {
+ PluginFs,
+ SwitchLaunchProfile,
+ SwitchLaunchSpecialization,
+} from '@switchdash/core/agents/plugins';
+import type { getPlugin } from '@main/core/providers/plugin-registry';
+import { switchAgentRuntimeCommand } from '@shared/core/switch-rooms/switch-agent-runtime';
+
+/**
+ * The launch profile that registers the Switch MCP server for a session and
+ * folds in any per-agent specialization (model / effort / instructions), or null
+ * when the provider resolves the server another way (Claude's bundled `.mcp.json`)
+ * and there is nothing to specialize.
+ *
+ * Pure — no write — so the caller decides where the files land: a direct write
+ * for local/SSH sessions, or a baked launch spec the VM sidecar writes for remote
+ * auto-sessions. The runtime it registers is static and secret-free: the profile
+ * names the variables the provider must route into the server's process rather
+ * than carrying their values, so the same profile is safe to bake and ship.
+ */
+export function resolveSwitchLaunchProfile(
+ plugin: ReturnType<typeof getPlugin>,
+ params: {
+ slug: string;
+ workingDir: string;
+ hasSwitchIdentity: boolean;
+ specialization?: SwitchLaunchSpecialization;
+ }
+): SwitchLaunchProfile | null {
+ const launchProfile = plugin.behavior.mcp?.launchProfile;
+ if (!launchProfile) return null;
+
+ return launchProfile({
+ slug: params.slug,
+ workingDir: params.workingDir,
+ switchServer: params.hasSwitchIdentity ? switchAgentRuntimeCommand() : null,
+ ...params.specialization,
+ });
+}
+
+/**
+ * Register the Switch MCP server for a launching session by writing its launch
+ * profile files into `homeFs` (rooted at the agent's home dir) and returning the
+ * argv that loads them. Returns `[]` when there is nothing to write.
+ *
+ * Used by the local and SSH runtimes, which write at launch. Remote auto-sessions
+ * instead bake the files into their launch spec (see {@link
+ * resolveSwitchLaunchProfile}) and the sidecar writes them.
+ */
+export async function prepareSwitchMcpLaunch(
+ plugin: ReturnType<typeof getPlugin>,
+ params: {
+ homeFs: PluginFs;
+ slug: string;
+ workingDir: string;
+ hasSwitchIdentity: boolean;
+ specialization?: SwitchLaunchSpecialization;
+ }
+): Promise<string[]> {
+ const profile = resolveSwitchLaunchProfile(plugin, params);
+ if (!profile) return [];
+
+ for (const file of profile.files) {
+ await params.homeFs.write(file.relativePath, file.content);
+ }
+ return profile.args;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts
index 4608b1225..8440b1b41 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts
@@ -24,13 +24,19 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {
// simulate a provider without repo-agent definitions (e.g. Codex).
const h = vi.hoisted(() => {
const writeDefinition = vi.fn(async () => {});
- const state: { workspace: PluginFs | null; repoAgents: object | null } = {
+ const state: {
+ workspace: PluginFs | null;
+ repoAgents: object | null;
+ nameTaken: boolean;
+ } = {
workspace: null,
repoAgents: { writeDefinition },
+ nameTaken: false,
};
return {
state,
writeDefinition,
+ agentNameTaken: vi.fn(async () => state.nameTaken),
registerAgentIdentity: vi.fn(async () => ({
kind: 'created' as const,
id: 'sw-1',
@@ -56,7 +62,9 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({
}));
vi.mock('@main/core/locations/store', () => ({
ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),
+ getLocationByHostDir: vi.fn(async () => ({ id: 'loc-1' })),
}));
+vi.mock('./agent-name-taken', () => ({ agentNameTaken: h.agentNameTaken }));
vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));
vi.mock('@main/core/locations/location-manager', () => ({
locationManager: { openLocation: vi.fn(async () => {}) },
@@ -93,6 +101,7 @@ function credsOf(fs: PluginFs, slug: string): Promise<Record<string, string>> {
describe('addAgent', () => {
beforeEach(() => {
vi.clearAllMocks();
+ h.state.nameTaken = false;
h.state.repoAgents = { writeDefinition: h.writeDefinition };
h.state.workspace = fakeFs();
h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });
@@ -156,4 +165,15 @@ describe('addAgent', () => {
expect(await fs.read(agentSettingsRelativePath('codex-hoot'))).toBeNull();
expect(h.createAgent).not.toHaveBeenCalled();
});
+
+ it('refuses a name already taken in the location, without minting an identity', async () => {
+ // The gateway's 409 is scoped to the Switch server, so it cannot see a name
+ // that is free there and taken in this directory — where both agents would
+ // then share one `.switch/agents/<name>.json`.
+ h.state.nameTaken = true;
+
+ expect((await addAgent(params())).kind).toBe('name-conflict');
+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();
+ expect(h.createAgent).not.toHaveBeenCalled();
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts
index 1d033e24a..f1970368e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts
@@ -2,14 +2,16 @@ import { randomUUID } from 'node:crypto';
import type { RepoAgentAttributes } from '@switchdash/core/agents/plugins';
import { locationManager } from '@main/core/locations/location-manager';
import { checkIsValidDirectory } from '@main/core/locations/path-utils';
-import { ensureLocation } from '@main/core/locations/store';
+import { ensureLocation, getLocationByHostDir } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { basenameFromAnyPath } from '@shared/path-name';
import { agentEvents } from './agent-events';
+import { agentNameTaken } from './agent-name-taken';
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
import { createAgent } from './createAgent';
import { knownAgentTypeForProvider } from './known-agent-type';
@@ -38,6 +40,10 @@ export type AddAgentParams = {
* keyed by the provider's attribute fields. `name`/`description` are set from
* the params above. */
definitionAttributes: RepoAgentAttributes;
+ /** Per-agent provider config folded into the agent's launch (Codex model /
+ * effort / instructions). Distinct from `definitionAttributes`, which is the
+ * repo-agent definition surface Codex does not use. */
+ providerConfig?: AgentProviderConfig | null;
};
export type AddAgentResult =
@@ -68,6 +74,14 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>
const server = await getServer(params.serverId);
if (!server) return { kind: 'error', message: `No Switch server with id ${params.serverId}` };
+ // Before minting an identity: the gateway's uniqueness check is scoped to the
+ // Switch server, so it cannot see a name already taken in this directory. Two
+ // same-named agents here would share one `.switch/agents/<name>.json`.
+ const existingLocation = await getLocationByHostDir(params.sshHost, params.dir);
+ if (existingLocation && (await agentNameTaken(existingLocation.id, params.name, null))) {
+ return { kind: 'name-conflict' };
+ }
+
const registered = await registerAgentIdentity(server, {
name: params.name,
description: params.description,
@@ -117,6 +131,7 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>
apiEndpoint: server.apiUrl,
serverId: params.serverId,
autoApprove: params.autoApprove,
+ providerConfig: params.providerConfig ?? null,
});
// Seed the local auto_session mirror + watcher from the gateway profile so an
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-name-taken.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-name-taken.ts
new file mode 100644
index 000000000..387933bc4
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-name-taken.ts
@@ -0,0 +1,30 @@
+import { and, eq, ne } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { agents } from '@main/db/schema';
+
+/**
+ * Whether another agent in the same location already answers to `name`.
+ *
+ * Everything switchdash provisions per agent is keyed by the name rather than the
+ * id — `.switch/agents/<name>.json` carries the Switch token, `.claude/agents/<name>.md`
+ * the definition — so two agents sharing a name in one directory share one
+ * credentials file, and whoever writes last decides which identity both of them
+ * present. The gateway's own uniqueness check cannot stand in for this one: it is
+ * scoped to a Switch server, and a name can be free there while taken here.
+ *
+ * `exceptAgentId` is the agent being renamed, so it does not conflict with itself;
+ * pass null when the agent does not exist yet.
+ */
+export async function agentNameTaken(
+ locationId: string,
+ name: string,
+ exceptAgentId: string | null
+): Promise<boolean> {
+ const matchesName = and(eq(agents.locationId, locationId), eq(agents.name, name));
+ const [row] = await db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(exceptAgentId === null ? matchesName : and(matchesName, ne(agents.id, exceptAgentId)))
+ .limit(1);
+ return row !== undefined;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts
index d80e27a6b..52f875245 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/createAgent.ts
@@ -16,6 +16,7 @@ export async function createAgent(params: CreateAgentParams): Promise<Agent> {
apiEndpoint: params.apiEndpoint,
serverId: params.serverId,
autoApprove: params.autoApprove,
+ providerConfig: params.providerConfig ?? null,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.returning();
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.test.ts
new file mode 100644
index 000000000..e6002ccf7
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.test.ts
@@ -0,0 +1,123 @@
+import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { agentSettingsRelativePath } from './switch-settings-paths';
+
+function fakeFs(seed: Record<string, string> = {}): PluginFs {
+ const files = new Map(Object.entries(seed));
+ return {
+ read: async (p) => files.get(p) ?? null,
+ write: async (p, c) => void files.set(p, c),
+ delete: async (p) => void files.delete(p),
+ exists: async (p) => files.has(p),
+ list: async () => [...files.keys()],
+ };
+}
+
+const h = vi.hoisted(() => {
+ const removeLocal = vi.fn(async (fs: PluginFs, name: string) => {
+ await fs.delete(`.claude/agents/${name}.md`);
+ });
+ const state: { fs: PluginFs; repoAgents: object | null; agent: Record<string, unknown> | null } =
+ {
+ fs: fakeFs(),
+ repoAgents: { removeLocal },
+ agent: null,
+ };
+ return { state, removeLocal, removeSwitchCredentials: vi.fn(async () => {}) };
+});
+
+vi.mock('@main/core/providers/plugin-registry', () => ({
+ getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),
+}));
+vi.mock('./agent-workspace-fs', () => ({
+ resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),
+}));
+vi.mock('./agent-location', () => ({
+ getAgentLocation: vi.fn(async () => ({ sshHost: null, dir: '/repo' })),
+}));
+vi.mock('./getAgentById', () => ({ getAgentById: vi.fn(async () => h.state.agent) }));
+vi.mock('./remove-switch-settings', () => ({
+ removeSwitchCredentials: h.removeSwitchCredentials,
+}));
+vi.mock('./agent-events', () => ({ agentEvents: { _emit: vi.fn() } }));
+vi.mock('./remote-watcher', () => ({ stopRemoteWatcher: vi.fn(async () => {}) }));
+vi.mock('./connect-remote-agent', () => ({ connectRemoteAgent: vi.fn() }));
+vi.mock('@main/core/agent-runtime/impl/remote-sidecar-launcher', () => ({
+ agentSidecarTmuxName: vi.fn(() => 'tmux'),
+ killSidecarSession: vi.fn(async () => {}),
+}));
+vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
+ setAutoSessionAgent: vi.fn(async () => {}),
+}));
+vi.mock('@main/core/switch-rooms/auto-session-watcher', () => ({
+ autoSessionWatcher: { stopForAgent: vi.fn() },
+}));
+vi.mock('@main/core/switch-servers/gateway-client', () => ({ deleteAgent: vi.fn() }));
+vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));
+vi.mock('@main/core/view-state/view-state-service', () => ({
+ viewStateService: { del: vi.fn(async () => {}) },
+}));
+vi.mock('../sessions/session-runtime-manager', () => ({
+ sessionRuntimeManager: { teardownSession: vi.fn(async () => {}) },
+}));
+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('@main/db/schema', () => ({ agents: {}, sessions: {} }));
+vi.mock('@main/db/client', () => ({
+ db: {
+ select: () => ({ from: () => ({ where: async () => [] }) }),
+ delete: () => ({ where: async () => undefined }),
+ },
+}));
+
+const { deleteAgent } = await import('./deleteAgent');
+
+const CREDS = JSON.stringify({
+ env: { SWITCH_API_ENDPOINT: 'https://s', SWITCH_API_TOKEN: 'tok-123', SWITCH_AGENT_ID: 'sw-1' },
+});
+
+describe('deleteAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ h.state.repoAgents = { removeLocal: h.removeLocal };
+ h.state.agent = { id: 'agent-1', name: 'cc-hoot', providerId: 'claude', locationId: 'loc' };
+ });
+
+ it('removes the per-agent credentials for a provider with no repo-agent definitions', async () => {
+ // The write is unconditional for every provider, so the teardown must be too:
+ // a provider without `removeLocal` would otherwise leave a live token on disk
+ // with no UI path left to revoke it.
+ h.state.repoAgents = null;
+ h.state.agent = { id: 'agent-1', name: 'codex-hoot', providerId: 'codex', locationId: 'loc' };
+ const fs = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: CREDS });
+ h.state.fs = fs;
+
+ await deleteAgent('agent-1', { deleteInSwitch: false });
+
+ expect(await fs.exists(agentSettingsRelativePath('codex-hoot'))).toBe(false);
+ });
+
+ it('removes both the credentials and the definition for a repo-agents provider', async () => {
+ const fs = fakeFs({
+ [agentSettingsRelativePath('cc-hoot')]: CREDS,
+ '.claude/agents/cc-hoot.md': '# cc-hoot',
+ });
+ h.state.fs = fs;
+
+ await deleteAgent('agent-1', { deleteInSwitch: false });
+
+ expect(await fs.exists(agentSettingsRelativePath('cc-hoot'))).toBe(false);
+ expect(await fs.exists('.claude/agents/cc-hoot.md')).toBe(false);
+ });
+
+ it('leaves a sibling agent sharing the directory untouched', async () => {
+ const fs = fakeFs({
+ [agentSettingsRelativePath('cc-hoot')]: CREDS,
+ [agentSettingsRelativePath('cc-sibling')]: CREDS,
+ });
+ h.state.fs = fs;
+
+ await deleteAgent('agent-1', { deleteInSwitch: false });
+
+ expect(await fs.exists(agentSettingsRelativePath('cc-sibling'))).toBe(true);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
index 7271289f4..cc334743d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
@@ -21,7 +21,9 @@ import { resolveWorkspaceFsFor } from './agent-workspace-fs';
import { connectRemoteAgent } from './connect-remote-agent';
import { getAgentById } from './getAgentById';
import { stopRemoteWatcher } from './remote-watcher';
+import { removeAgentLaunchProfile } from './remove-launch-profile';
import { removeSwitchCredentials } from './remove-switch-settings';
+import { agentSettingsRelativePath } from './switch-settings-paths';
export type DeleteAgentOptions = {
/**
@@ -80,7 +82,25 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promise
});
});
}
+ // The per-agent credentials are written for every provider, so they are
+ // removed for every provider — a provider without repo-agent definitions has
+ // no `removeLocal` to carry the token file out with it.
+ //
+ // Isolated like `removeLocal` above: each teardown step must run even if an
+ // earlier one fails, or one unwritable file leaves the rest of the agent's
+ // credentials behind.
+ await ctx.fs.delete(agentSettingsRelativePath(agent.name ?? agent.id)).catch((error) => {
+ log.warn('deleteAgent: failed to remove the per-agent Switch credentials', {
+ agentId: agent.id,
+ name: agent.name,
+ error: String(error),
+ });
+ });
await removeSwitchCredentials(agent.providerId, ctx.fs);
+ // A provider that registers the Switch server itself (Codex) leaves a
+ // per-agent launch profile under the user's home — a different scope than
+ // ctx.fs, reached through its own home filesystem (local or remote).
+ await removeAgentLaunchProfile(agent, location, agent.name ?? agent.id);
} finally {
ctx.close();
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
index 9e5a288b4..2137b6a1c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
@@ -1,4 +1,7 @@
+import { pluginRegistry } from '@switchdash/plugins/agents';
+import { parse as parseTOML } from 'smol-toml';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { switchAgentRuntimeCommand } from '@shared/core/switch-rooms/switch-agent-runtime';
const buildCommand = vi.fn(() => ({ command: 'claude', args: ['--x'], env: { E: '1' } }));
const launchArgs = vi.fn((dir: string, name: string) => [
@@ -8,9 +11,20 @@ const launchArgs = vi.fn((dir: string, name: string) => [
`${dir}/.switch/agents/${name}.json`,
]);
+const launchProfile = vi.fn((params: { slug: string; switchServer: unknown | null }) =>
+ params.switchServer
+ ? {
+ files: [{ relativePath: `.codex/${params.slug}.config.toml`, content: 'PROFILE' }],
+ args: ['--profile', params.slug],
+ }
+ : null
+);
+/** Set per test: whether the mocked provider registers the Switch server itself. */
+let mcpBehavior: { launchProfile?: typeof launchProfile } | undefined;
+
vi.mock('@main/core/providers/plugin-registry', () => ({
getPlugin: () => ({
- behavior: { prompt: { buildCommand }, repoAgents: { launchArgs } },
+ behavior: { prompt: { buildCommand }, repoAgents: { launchArgs }, mcp: mcpBehavior },
capabilities: { hostDependency: { binaryNames: ['claude'] } },
}),
}));
@@ -22,6 +36,12 @@ vi.mock('@main/core/settings/provider-settings-service', () => ({
}));
vi.mock('@main/core/dependencies/host-dependency-store', () => ({ hostDependencyStore: {} }));
+import { buildStandardCommand } from '@switchdash/core/agents/plugins/helpers';
+import {
+ INITIAL_PROMPT_PLACEHOLDER,
+ materializeAgentCommand,
+ SESSION_ID_PLACEHOLDER,
+} from '../../../sidecar/agent-launch-spec';
import { generateAgentLaunchSpec } from './generate-agent-launch-spec';
const baseParams = {
@@ -29,6 +49,7 @@ const baseParams = {
remoteRepoDir: '/home/agent/repo',
deeplinkScheme: 'switchdash',
agentName: null,
+ credsSlug: 'hoot',
ctx: {} as never,
connectionId: 'conn-1',
};
@@ -37,6 +58,8 @@ describe('generateAgentLaunchSpec', () => {
beforeEach(() => {
buildCommand.mockClear();
launchArgs.mockClear();
+ launchProfile.mockClear();
+ mcpBehavior = undefined;
});
// The bug (CHOO-1664): autoApprove was hardcoded true, so the remote watcher's
@@ -71,4 +94,158 @@ describe('generateAgentLaunchSpec', () => {
expect(launchArgs).not.toHaveBeenCalled();
expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ agentArgs: [] }));
});
+
+ it('bakes the profile args and launch file for a provider that registers the server itself', async () => {
+ // The endpoint and credentials reach the runtime through the env, so the spec
+ // carries the profile file the sidecar writes on the VM plus `--profile <slug>`
+ // to load it — no argv endpoint token any more.
+ mcpBehavior = { launchProfile };
+
+ const spec = await generateAgentLaunchSpec({ ...baseParams, autoApprove: false });
+
+ expect(launchProfile).toHaveBeenCalledWith(expect.objectContaining({ slug: 'hoot' }));
+ expect(buildCommand).toHaveBeenCalledWith(
+ expect.objectContaining({ agentArgs: ['--profile', 'hoot'] })
+ );
+ expect(spec.launchFiles).toEqual([
+ { homeRelativePath: '.codex/hoot.config.toml', content: 'PROFILE' },
+ ]);
+ });
+
+ it('bakes a profile that names the credentials and carries none of them', async () => {
+ // The sidecar writes this file verbatim on the VM, so whatever is baked here
+ // is what a remote session runs with — and a value baked in would be a secret
+ // shipped to the box and re-read on every poll.
+ mcpBehavior = (pluginRegistry.get('codex')!.behavior as { mcp?: typeof mcpBehavior }).mcp;
+
+ const spec = await generateAgentLaunchSpec({ ...baseParams, autoApprove: false });
+
+ const content = spec.launchFiles![0].content;
+ const server = (parseTOML(content) as { mcp_servers: Record<string, { env_vars?: string[] }> })
+ .mcp_servers.switch;
+
+ expect(server.env_vars).toEqual(switchAgentRuntimeCommand().envVars);
+ expect(content).not.toMatch(/Bearer |tok-/);
+ });
+
+ it('bakes a system prompt into the profile file rather than the argv', async () => {
+ // The sidecar re-renders these args as a shell command line for the tmux
+ // pane, so a free-form body there would be flattened or executed. It also
+ // has to survive `resume`, which only inherits what the profile carries.
+ mcpBehavior = (pluginRegistry.get('codex')!.behavior as { mcp?: typeof mcpBehavior }).mcp;
+ const instructions = 'be terse\n$(whoami) and "quotes"';
+
+ const spec = await generateAgentLaunchSpec({
+ ...baseParams,
+ autoApprove: false,
+ specialization: { instructions },
+ });
+
+ const parsed = parseTOML(spec.launchFiles![0].content) as Record<string, unknown>;
+ expect(spec.launchFiles).toHaveLength(1);
+ expect(parsed.developer_instructions).toBe(instructions);
+ expect(spec.launchFiles![0].homeRelativePath).not.toContain('instructions.md');
+ // The profile name is digest-suffixed on (dir, slug); the file stem and the
+ // --profile value must agree.
+ const profileName = spec.launchFiles![0].homeRelativePath.replace(
+ /^\.codex\/(.+)\.config\.toml$/,
+ '$1'
+ );
+ expect(profileName).toMatch(/^hoot-[a-z0-9]+$/);
+ expect(buildCommand).toHaveBeenCalledWith(
+ expect.objectContaining({ agentArgs: ['--profile', profileName] })
+ );
+ });
+
+ it('bakes no MCP args or launch files for a provider that resolves servers from config', async () => {
+ const spec = await generateAgentLaunchSpec({ ...baseParams, autoApprove: false });
+
+ expect(launchProfile).not.toHaveBeenCalled();
+ expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ agentArgs: [] }));
+ expect(spec.launchFiles).toBeUndefined();
+ });
+});
+
+/**
+ * The suite above mocks `buildCommand`, so it cannot see provider-specific argv
+ * constraints. Codex sets `sessionIdOnResumeOnly`: its fresh-session argv carries
+ * no session-id token at all, and a watcher that requires one rejects every spec
+ * it produces. These drive the real provider spec instead.
+ */
+describe('generateAgentLaunchSpec against real provider command builders', () => {
+ const CODEX_SPEC = {
+ defaultArgs: ['--dangerously-bypass-hook-trust'],
+ autoApproveFlag: '-c approval_policy="never"',
+ initialPromptFlag: '',
+ resumeFlag: 'resume',
+ sessionIdFlag: ' ',
+ sessionIdOnResumeOnly: true,
+ resumeWithoutSessionFlag: 'resume --last',
+ };
+
+ /** What `generateAgentLaunchSpec` asks a provider to build. */
+ function buildSpecArgs(providerSpec: Parameters<typeof buildStandardCommand>[1]): string[] {
+ return buildStandardCommand(
+ {
+ cli: '/usr/bin/agent',
+ extraArgs: [],
+ agentArgs: ['--profile', 'hoot'],
+ autoApprove: true,
+ initialPrompt: INITIAL_PROMPT_PLACEHOLDER,
+ sessionId: SESSION_ID_PLACEHOLDER,
+ providerSessionId: undefined,
+ isResuming: false,
+ model: '',
+ },
+ providerSpec
+ ).args;
+ }
+
+ it('produces a Codex spec the watcher can materialize', () => {
+ const args = buildSpecArgs(CODEX_SPEC);
+ expect(args).not.toContain(SESSION_ID_PLACEHOLDER);
+ expect(args).toContain('--profile');
+
+ const cmd = materializeAgentCommand(
+ {
+ command: '/usr/bin/codex',
+ args,
+ env: {},
+ cwd: '/home/agent/repo',
+ providerId: 'codex',
+ deeplinkScheme: 'switchdash',
+ },
+ {
+ sessionId: 's1',
+ initialPrompt: 'connect to switch room room-x',
+ extraEnv: {},
+ }
+ );
+
+ expect(cmd.args).toContain('hoot');
+ expect(cmd.args).toContain('connect to switch room room-x');
+ });
+
+ it('still carries the session id for a provider that takes one when fresh', () => {
+ const args = buildSpecArgs({ initialPromptFlag: '', sessionIdFlag: '--session-id' });
+ expect(args).toContain(SESSION_ID_PLACEHOLDER);
+
+ const cmd = materializeAgentCommand(
+ {
+ command: '/usr/bin/claude',
+ args,
+ env: {},
+ cwd: '/home/agent/repo',
+ providerId: 'claude',
+ deeplinkScheme: 'switchdash',
+ },
+ {
+ sessionId: 's1',
+ initialPrompt: 'p',
+ extraEnv: {},
+ }
+ );
+
+ expect(cmd.args).toContain('s1');
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
index c1d8f5efd..2b41ea2b1 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
@@ -1,4 +1,6 @@
+import type { SwitchLaunchSpecialization } from '@switchdash/core/agents/plugins';
import { resolveAgentExecutable } from '@main/core/agent-runtime/impl/resolve-agent-executable';
+import { resolveSwitchLaunchProfile } from '@main/core/agent-runtime/switch-mcp-launch-args';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
import { getPlugin } from '@main/core/providers/plugin-registry';
@@ -37,11 +39,25 @@ export async function generateAgentLaunchSpec(params: {
* prompt, tools, and Switch identity. Null for a provider/agent with no
* on-disk definition (CHOO-1440). */
agentName: string | null;
+ /** Per-agent creds slug (the agent's name) — keys the Switch launch profile a
+ * provider that registers the server itself writes (Codex). */
+ credsSlug: string;
+ /** Per-agent model / effort / instructions folded into the launch profile. */
+ specialization?: SwitchLaunchSpecialization;
ctx: IExecutionContext;
connectionId: string;
}): Promise<AgentLaunchSpec> {
- const { providerId, remoteRepoDir, deeplinkScheme, autoApprove, agentName, ctx, connectionId } =
- params;
+ const {
+ providerId,
+ remoteRepoDir,
+ deeplinkScheme,
+ autoApprove,
+ agentName,
+ credsSlug,
+ specialization,
+ ctx,
+ connectionId,
+ } = params;
const plugin = getPlugin(providerId);
if (!plugin.behavior.prompt) {
throw new Error(
@@ -59,13 +75,28 @@ export async function generateAgentLaunchSpec(params: {
connectionId,
});
+ // Auto-started sessions always run as the agent, so they have a Switch
+ // identity. A provider that registers the server itself (Codex) returns the
+ // profile file to bake into the spec and the `--profile <slug>` argv; the
+ // sidecar writes the file on the VM. Null for providers whose plugin resolves
+ // the server from a bundled config (Claude).
+ const switchProfile = resolveSwitchLaunchProfile(plugin, {
+ slug: credsSlug,
+ workingDir: remoteRepoDir,
+ hasSwitchIdentity: true,
+ specialization,
+ });
+
const repoAgents = plugin.behavior.repoAgents;
const agentCommand = plugin.behavior.prompt.buildCommand({
cli,
extraArgs: parseExtraArgs(providerConfig?.extraArgs),
// The provider owns how to run as the named agent (CHOO-1440); kept distinct
// from user extra args.
- agentArgs: agentName && repoAgents ? repoAgents.launchArgs(remoteRepoDir, agentName) : [],
+ agentArgs: [
+ ...(agentName && repoAgents ? repoAgents.launchArgs(remoteRepoDir, agentName) : []),
+ ...(switchProfile?.args ?? []),
+ ],
autoApprove,
initialPrompt: INITIAL_PROMPT_PLACEHOLDER,
sessionId: SESSION_ID_PLACEHOLDER,
@@ -79,6 +110,10 @@ export async function generateAgentLaunchSpec(params: {
args: agentCommand.args,
env: { ...agentCommand.env, ...(providerConfig?.env ?? {}) },
cwd: remoteRepoDir,
+ launchFiles: switchProfile?.files.map((file) => ({
+ homeRelativePath: file.relativePath,
+ content: file.content,
+ })),
providerId,
deeplinkScheme,
};
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
index 09e35036f..51a0cf465 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts
@@ -109,6 +109,7 @@ vi.mock('./agent-storage-migration-marker', () => ({
markAgentStorageMigrationComplete: h.markComplete,
}));
+import { log } from '@main/lib/logger';
import { migrateAgentStorage } from './migrate-agent-storage';
const baseAgent = {
@@ -166,7 +167,7 @@ describe('migrateAgentStorage', () => {
expect(h.writeDefinition).not.toHaveBeenCalled();
});
- it('falls back to .claude/settings.local.json when no neutral file exists', async () => {
+ it('falls back to .claude/settings.local.json when its identity matches the Claude row', async () => {
const ws = fakeFs({
'.claude/settings.local.json': credsJson('sw-1'),
'.claude/agents/cc-hoot-main.md': '# def',
@@ -177,6 +178,86 @@ describe('migrateAgentStorage', () => {
const written = JSON.parse((await ws.read('.switch/agents/cc-hoot-main.json')) as string);
expect(written.env.SWITCH_AGENT_ID).toBe('sw-1');
+ expect(written.env.SWITCH_API_TOKEN).toBe('tok-123');
+ expect(written.env.SWITCH_API_ENDPOINT).toBe('http://switch.example');
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
+ it('never reads .claude/settings.local.json for a provider without repo-agents', async () => {
+ // The shared settings file is written only by provisionAgent /
+ // provisionRemoteAgent, always as the Claude "main" agent, so for any other
+ // provider it is a different agent's identity and token. Adopting it would
+ // make the session launch AS that agent — a silent success where launching
+ // unidentified is a visible failure.
+ h.state.agents = [
+ { ...baseAgent, providerId: 'codex', name: 'codex-hoot', switchAgentId: 'sw-codex' },
+ ];
+ h.state.repoAgents = null;
+ const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });
+ const read = vi.spyOn(ws, 'read');
+ h.state.workspace = ws;
+
+ await migrateAgentStorage();
+
+ expect(read).not.toHaveBeenCalledWith('.claude/settings.local.json');
+ expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(false);
+ });
+
+ it('does not adopt .claude/settings.local.json for a provider without repo-agents when the row has no identity to compare', async () => {
+ // A row with no `switchAgentId` has nothing to compare against, so the
+ // behavior gate — not the identity cross-check — is what keeps the Claude
+ // main agent's credentials out of this agent's file.
+ h.state.agents = [
+ { ...baseAgent, providerId: 'codex', name: 'codex-hoot', switchAgentId: null },
+ ];
+ h.state.repoAgents = null;
+ const ws = fakeFs({ '.claude/settings.local.json': credsJson('sw-CLAUDE-MAIN') });
+ h.state.workspace = ws;
+
+ await migrateAgentStorage();
+
+ expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(false);
+ });
+
+ it('skips visibly when .claude/settings.local.json names a different agent than the Claude row', async () => {
+ // Multiple Claude agents can share a location; only one of them owns the
+ // shared settings file. Adopting a mismatched identity is never right.
+ const ws = fakeFs({
+ '.claude/settings.local.json': credsJson('sw-other'),
+ '.claude/agents/cc-hoot-main.md': '# def',
+ });
+ h.state.workspace = ws;
+
+ await migrateAgentStorage();
+
+ expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining('different Switch agent'),
+ expect.objectContaining({
+ agentId: 'agent-id-1',
+ agentName: 'cc-hoot-main',
+ expectedSwitchAgentId: 'sw-1',
+ foundSwitchAgentId: 'sw-other',
+ })
+ );
+ });
+
+ it('keeps a mismatched id-keyed neutral file instead of adopting or deleting it', async () => {
+ // The token exists nowhere else, so a skip must not take the only copy with
+ // it: without a name-keyed file the stale-file cleanup has to stay its hand.
+ h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];
+ h.state.repoAgents = null;
+ const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-other') });
+ h.state.workspace = ws;
+
+ await migrateAgentStorage();
+
+ expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(false);
+ expect(await ws.read('.switch/agents/agent-id-1.json')).toBe(credsJson('sw-other'));
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.stringContaining('different Switch agent'),
+ expect.objectContaining({ foundSwitchAgentId: 'sw-other', providerId: 'codex' })
+ );
});
it('does nothing when the name-keyed file already exists and the definition is present', async () => {
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
index 0f580d454..18c07062d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts
@@ -1,6 +1,9 @@
import { getLocationById } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
-import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';
+import {
+ parseSwitchAgentCredentials,
+ type SwitchAgentCredentials,
+} from '@main/core/switch-rooms/switch-credentials';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
import {
@@ -69,8 +72,8 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo
// A provider may have no repo-agent behavior (e.g. Codex): it has no on-disk
// definition and no `readLaunchEnv` hook, but its provider-neutral credentials
// still need collapsing onto the one name-keyed key-space. So the credential
- // migration runs for every provider; only the definition step (2) is
- // behavior-gated.
+ // migration runs for every provider; its Claude-specific sources, and the
+ // definition step (2), are behavior-gated.
const behavior = getPlugin(agent.providerId).behavior.repoAgents;
// Generation 2 only broadened step 1 to providers WITHOUT a behavior; for one
@@ -92,30 +95,44 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo
let changed = false;
// 1. Credentials: if the name-keyed neutral file is absent, adopt whatever
- // complete credentials already exist on disk, in priority order:
+ // complete credentials already exist on disk *for this agent*, in priority
+ // order:
// a. a stale ID-keyed neutral file `.switch/agents/<agentId>.json` — an
// earlier layout keyed the neutral file by agent id, not name (this
// includes Codex agents added on the pre-rework id-keyed scheme);
// b. the legacy per-agent file (via readLaunchEnv: name-keyed neutral
- // then `.claude/switch-subagents/<name>.settings.json`) — behavior
- // providers only;
+ // then `.claude/switch-subagents/<name>.settings.json`);
// c. the shared `.claude/settings.local.json` (legacy "main" agent).
+ // (b) and (c) are Claude-only sources, hence behavior-gated: the shared
+ // settings file is written solely by `provisionAgent`/`provisionRemoteAgent`,
+ // always as the Claude "main" agent, so for any other provider it holds a
+ // *different* agent's identity and token.
// The token is minted once and lives only on disk, so this is the only way
// to recover it — nothing can reconstruct it from the gateway.
const idKeyedRelPath = agentSettingsRelativePath(agent.id);
const namedRelPath = agentSettingsRelativePath(name);
const neutral = name === agent.id ? null : await workspace.fs.read(namedRelPath);
if (neutral === null) {
- const creds =
+ const recovered =
parseSwitchAgentCredentials(await workspace.fs.read(idKeyedRelPath), log) ??
(behavior ? toCreds(await behavior.readLaunchEnv(workspace.fs, name)) : null) ??
- parseSwitchAgentCredentials(await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log);
- if (creds) {
+ (behavior
+ ? parseSwitchAgentCredentials(await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log)
+ : null);
+ if (recovered && !belongsToAgent(agent, recovered)) {
+ log.warn('migrateAgentStorage: recovered credentials name a different Switch agent', {
+ agentId: agent.id,
+ agentName: name,
+ providerId: agent.providerId,
+ expectedSwitchAgentId: agent.switchAgentId,
+ foundSwitchAgentId: recovered.agentId,
+ });
+ } else if (recovered) {
await writeNeutralAgentSettingsFs(workspace.fs, {
slug: name,
- apiEndpoint: creds.apiEndpoint,
- apiToken: creds.token,
- agentId: creds.agentId,
+ apiEndpoint: recovered.apiEndpoint,
+ apiToken: recovered.token,
+ agentId: recovered.agentId,
});
changed = true;
}
@@ -145,10 +162,19 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo
}
}
+/**
+ * Whether recovered credentials are this agent's own. The row's `switchAgentId`
+ * is the authority on which Switch identity the agent has, so a file naming a
+ * different one belongs to a different agent — adopting it would launch this
+ * agent under that agent's identity and token, which looks like it worked. A row
+ * with no recorded identity has nothing to contradict.
+ */
+function belongsToAgent(agent: Agent, creds: SwitchAgentCredentials): boolean {
+ return agent.switchAgentId === null || agent.switchAgentId === creds.agentId;
+}
+
/** Build credentials from a launch-env map, or null when any value is missing. */
-function toCreds(
- env: Record<string, string>
-): { apiEndpoint: string; token: string; agentId: string } | null {
+function toCreds(env: Record<string, string>): SwitchAgentCredentials | null {
const apiEndpoint = env.SWITCH_API_ENDPOINT;
const token = env.SWITCH_API_TOKEN;
const agentId = env.SWITCH_AGENT_ID;
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts
index 87c6103eb..24857d790 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts
@@ -108,7 +108,7 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA
dir: params.dir,
message:
sshHost === null
- ? 'This directory is not configured as a Switch agent. Configure the agent first (run the switch-connector configure skill) before adding it.'
+ ? "This directory is not configured as a Switch agent. Configure it first — from Settings → Agents, or with the Claude Code connector's `configure` skill — before adding it."
: `The remote directory ${params.dir} on ${sshHost} is not configured as a Switch agent.`,
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
index ce3925e5d..6f2a9173d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
@@ -15,6 +15,7 @@ import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import { makePtyId } from '@shared/core/pty/ptyId';
import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';
@@ -427,6 +428,7 @@ class RemoteSessionReconciler {
autoApprove: agent.autoApprove,
credsSlug: agent.name ?? agent.id,
agentName: agent.name ?? null,
+ specialization: toSwitchSpecialization(agent.providerConfig),
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
index 278a1675b..0b70ff1dc 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
@@ -3,6 +3,7 @@ import { ensureAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-s
import { writeWatchEnabled } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import { getRemoteAgentLocation } from './agent-location';
import { connectRemoteAgent } from './connect-remote-agent';
import { getAgentById } from './getAgentById';
@@ -117,6 +118,7 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {
autoApprove: agent.autoApprove,
credsSlug: agent.name ?? agent.id,
agentName: agent.name ?? null,
+ specialization: toSwitchSpecialization(agent.providerConfig),
ctx,
connectionId,
host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.test.ts
new file mode 100644
index 000000000..ea2fb707f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ launchProfilePaths: vi.fn((p: { slug: string; workingDir: string }) => [
+ `.codex/${p.slug}-digest.config.toml`,
+ ]),
+ mcp: undefined as { launchProfilePaths?: unknown } | undefined,
+ localDelete: vi.fn(async () => undefined),
+ remoteDelete: vi.fn(async () => undefined),
+ connectRemoteAgent: vi.fn(async () => ({ ctx: { exec: vi.fn() } })),
+}));
+
+vi.mock('@main/core/providers/plugin-registry', () => ({
+ getPlugin: () => ({ behavior: { mcp: h.mcp } }),
+}));
+vi.mock('@main/core/providers/plugin-fs', () => ({
+ createPluginFs: () => ({ delete: h.localDelete }),
+}));
+vi.mock('@main/core/agent-runtime/impl/remote-home-plugin-fs', () => ({
+ createRemoteHomePluginFs: () => ({ delete: h.remoteDelete }),
+}));
+vi.mock('./connect-remote-agent', () => ({ connectRemoteAgent: h.connectRemoteAgent }));
+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }));
+
+import { removeAgentLaunchProfile } from './remove-launch-profile';
+
+const agent = { id: 'a1', providerId: 'codex', name: 'codex-hoot' } as never;
+const localLocation = { sshHost: null, dir: '/repo' } as never;
+const remoteLocation = { sshHost: 'vm', dir: '/home/agent/repo' } as never;
+
+describe('removeAgentLaunchProfile', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ h.mcp = { launchProfilePaths: h.launchProfilePaths };
+ });
+
+ it('deletes the profile from the local home for a local agent', async () => {
+ await removeAgentLaunchProfile(agent, localLocation, 'codex-hoot');
+
+ expect(h.launchProfilePaths).toHaveBeenCalledWith({
+ slug: 'codex-hoot',
+ workingDir: '/repo',
+ });
+ expect(h.localDelete).toHaveBeenCalledWith('.codex/codex-hoot-digest.config.toml');
+ expect(h.connectRemoteAgent).not.toHaveBeenCalled();
+ });
+
+ it('deletes the profile from the VM home for a remote agent', async () => {
+ await removeAgentLaunchProfile(agent, remoteLocation, 'codex-hoot');
+
+ // Reaches the VM home over the exec-backed remote FS, not the no-op stub.
+ expect(h.connectRemoteAgent).toHaveBeenCalledWith(agent);
+ expect(h.remoteDelete).toHaveBeenCalledWith('.codex/codex-hoot-digest.config.toml');
+ expect(h.localDelete).not.toHaveBeenCalled();
+ });
+
+ it('uses the passed slug (the old name on rename), not the agent name', async () => {
+ await removeAgentLaunchProfile(agent, localLocation, 'old-name');
+ expect(h.localDelete).toHaveBeenCalledWith('.codex/old-name-digest.config.toml');
+ });
+
+ it('does nothing for a provider that writes no launch profile', async () => {
+ h.mcp = {};
+ await removeAgentLaunchProfile(agent, remoteLocation, 'codex-hoot');
+ expect(h.connectRemoteAgent).not.toHaveBeenCalled();
+ expect(h.localDelete).not.toHaveBeenCalled();
+ expect(h.remoteDelete).not.toHaveBeenCalled();
+ });
+
+ it('logs and returns without throwing when the remote home cannot be reached', async () => {
+ h.connectRemoteAgent.mockRejectedValueOnce(new Error('vm unreachable'));
+ await expect(
+ removeAgentLaunchProfile(agent, remoteLocation, 'codex-hoot')
+ ).resolves.toBeUndefined();
+ expect(h.remoteDelete).not.toHaveBeenCalled();
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.ts
new file mode 100644
index 000000000..0c01b8c9a
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-launch-profile.ts
@@ -0,0 +1,57 @@
+import { homedir } from 'node:os';
+import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { createRemoteHomePluginFs } from '@main/core/agent-runtime/impl/remote-home-plugin-fs';
+import { createPluginFs } from '@main/core/providers/plugin-fs';
+import { getPlugin } from '@main/core/providers/plugin-registry';
+import { log } from '@main/lib/logger';
+import type { Agent } from '@shared/core/agents/agents';
+import type { Location } from '@shared/core/locations/locations';
+import { connectRemoteAgent } from './connect-remote-agent';
+
+/**
+ * Remove the per-agent launch profile a provider writes under the user's home
+ * (Codex: `~/.codex/<name>.config.toml`), for the given `slug` — the agent's
+ * current name on delete, its old name on rename.
+ *
+ * The profile lives in the home scope, not the working dir, so it is reached
+ * through the same home filesystem that wrote it: local disk for a local agent,
+ * and the exec-backed remote home for a remote one (the repo-dir `WorkspaceFs`
+ * used elsewhere in teardown deliberately has no writable home for remote
+ * agents). Best-effort and isolated: a filesystem or connection failure is
+ * logged, not thrown, so the rest of the agent's teardown still runs — but it is
+ * a real attempt, so a genuine failure is visible rather than a silent no-op.
+ */
+export async function removeAgentLaunchProfile(
+ agent: Agent,
+ location: Location,
+ slug: string
+): Promise<void> {
+ const mcp = getPlugin(agent.providerId).behavior.mcp;
+ const paths = mcp?.launchProfilePaths?.({ slug, workingDir: location.dir }) ?? [];
+ if (paths.length === 0) return;
+
+ let homeFs: PluginFs;
+ try {
+ homeFs =
+ location.sshHost === null
+ ? createPluginFs(homedir())
+ : createRemoteHomePluginFs((await connectRemoteAgent(agent)).ctx);
+ } catch (error) {
+ log.warn('removeAgentLaunchProfile: could not reach the agent home to remove its profile', {
+ agentId: agent.id,
+ sshHost: location.sshHost,
+ error: String(error),
+ });
+ return;
+ }
+
+ for (const path of paths) {
+ await homeFs.delete(path).catch((error) => {
+ log.warn('removeAgentLaunchProfile: failed to remove the per-agent launch profile', {
+ agentId: agent.id,
+ path,
+ error: String(error),
+ });
+ });
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.test.ts
new file mode 100644
index 000000000..d8b14b39e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.test.ts
@@ -0,0 +1,208 @@
+import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { agentSettingsRelativePath } from './switch-settings-paths';
+
+function fakeFs(seed: Record<string, string> = {}): PluginFs {
+ const files = new Map(Object.entries(seed));
+ return {
+ read: async (p) => files.get(p) ?? null,
+ write: async (p, c) => void files.set(p, c),
+ delete: async (p) => void files.delete(p),
+ exists: async (p) => files.has(p),
+ list: async () => [...files.keys()],
+ };
+}
+
+const h = vi.hoisted(() => {
+ const readDefinition = vi.fn(async (fs: PluginFs, name: string) =>
+ (await fs.read(`.claude/agents/${name}.md`)) === null ? null : { name, description: 'd' }
+ );
+ const writeDefinition = vi.fn(async (fs: PluginFs, attrs: { name: string }) => {
+ await fs.write(`.claude/agents/${attrs.name}.md`, `# ${attrs.name}`);
+ });
+ const removeLocal = vi.fn(async (fs: PluginFs, name: string) => {
+ await fs.delete(`.claude/agents/${name}.md`);
+ });
+ const state: {
+ row: Record<string, unknown> | undefined;
+ fs: PluginFs;
+ repoAgents: object | null;
+ nameTaken: boolean;
+ } = {
+ row: undefined,
+ fs: fakeFs(),
+ repoAgents: { readDefinition, writeDefinition, removeLocal },
+ nameTaken: false,
+ };
+ return { state, readDefinition, writeDefinition, removeLocal };
+});
+
+vi.mock('@main/core/providers/plugin-registry', () => ({
+ getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),
+}));
+vi.mock('./agent-location', () => ({
+ getAgentLocation: vi.fn(async () => ({ sshHost: null, dir: '/repo' })),
+ getRemoteAgentLocation: vi.fn(async () => null),
+}));
+vi.mock('./agent-workspace-fs', () => ({
+ resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),
+}));
+vi.mock('./getAgentById', () => ({
+ getAgentById: vi.fn(async () => ({
+ id: 'agent-1',
+ name: 'old-name',
+ providerId: 'claude',
+ locationId: 'loc-1',
+ })),
+}));
+vi.mock('./agent-name-taken', () => ({
+ agentNameTaken: vi.fn(async () => h.state.nameTaken),
+}));
+vi.mock('./connect-remote-agent', () => ({ connectRemoteAgent: vi.fn() }));
+vi.mock('./remote-watcher', () => ({ ensureRemoteWatcher: vi.fn(async () => {}) }));
+vi.mock('@main/core/agent-runtime/impl/remote-sidecar-launcher', () => ({
+ agentSidecarTmuxName: vi.fn(() => 'tmux'),
+ killSidecarSession: vi.fn(async () => {}),
+}));
+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock('@main/db/client', () => ({
+ db: {
+ update: () => ({
+ set: () => ({ where: () => ({ returning: async () => (h.state.row ? [h.state.row] : []) }) }),
+ }),
+ },
+}));
+vi.mock('@main/db/schema', () => ({ agents: {} }));
+vi.mock('./utils', () => ({
+ mapAgentRowToAgent: (row: Record<string, unknown>) => row,
+}));
+
+const { renameAgent } = await import('./renameAgent');
+
+const CREDS = JSON.stringify({
+ env: { SWITCH_API_ENDPOINT: 'https://s', SWITCH_API_TOKEN: 'tok-123', SWITCH_AGENT_ID: 'sw-1' },
+});
+
+describe('renameAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ h.state.nameTaken = false;
+ h.state.row = { id: 'agent-1', name: 'new-name', providerId: 'claude' };
+ h.state.repoAgents = {
+ readDefinition: h.readDefinition,
+ writeDefinition: h.writeDefinition,
+ removeLocal: h.removeLocal,
+ };
+ });
+
+ it('moves the credentials onto the new name so the minted token is not lost', async () => {
+ // The token is minted once and lives only in this file; every reader resolves
+ // it from the agent's current name.
+ const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });
+ h.state.fs = fs;
+
+ await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(CREDS);
+ expect(await fs.exists(agentSettingsRelativePath('old-name'))).toBe(false);
+ });
+
+ it('moves the credentials for a provider with no repo-agent definitions', async () => {
+ h.state.repoAgents = null;
+ const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });
+ h.state.fs = fs;
+
+ await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(CREDS);
+ expect(await fs.exists(agentSettingsRelativePath('old-name'))).toBe(false);
+ });
+
+ it('moves the definition too, so the CLI can still launch as --agent <new name>', async () => {
+ const fs = fakeFs({
+ [agentSettingsRelativePath('old-name')]: CREDS,
+ '.claude/agents/old-name.md': '# old-name',
+ });
+ h.state.fs = fs;
+
+ await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ expect(await fs.exists('.claude/agents/new-name.md')).toBe(true);
+ expect(await fs.exists('.claude/agents/old-name.md')).toBe(false);
+ });
+
+ it('writes the new files before removing the old ones', async () => {
+ const order: string[] = [];
+ const fs = fakeFs({
+ [agentSettingsRelativePath('old-name')]: CREDS,
+ '.claude/agents/old-name.md': '# old-name',
+ });
+ const write = fs.write.bind(fs);
+ const del = fs.delete.bind(fs);
+ fs.write = async (p, c) => {
+ order.push(`write ${p}`);
+ return write(p, c);
+ };
+ fs.delete = async (p) => {
+ order.push(`delete ${p}`);
+ return del(p);
+ };
+ h.state.fs = fs;
+
+ await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ // An interruption must leave a recoverable duplicate, never nothing.
+ const firstDelete = order.findIndex((o) => o.startsWith('delete'));
+ const lastWrite = order.map((o) => o.startsWith('write')).lastIndexOf(true);
+ expect(firstDelete).toBeGreaterThan(lastWrite);
+ });
+
+ it('does not touch the filesystem when the name is unchanged', async () => {
+ h.state.row = { id: 'agent-1', name: 'old-name', providerId: 'claude' };
+ const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });
+ h.state.fs = fs;
+
+ await renameAgent({ agentId: 'agent-1', newName: 'old-name' });
+
+ expect(await fs.read(agentSettingsRelativePath('old-name'))).toBe(CREDS);
+ expect(h.removeLocal).not.toHaveBeenCalled();
+ });
+
+ it('refuses a name a sibling in the same location already holds', async () => {
+ // Nothing keys agent state by id: the credentials live at
+ // `.switch/agents/<name>.json`. Renaming onto a sibling would overwrite that
+ // sibling's token with this agent's and then delete the original, leaving the
+ // sibling authenticating to Switch as somebody else.
+ const SIBLING = JSON.stringify({
+ env: {
+ SWITCH_API_ENDPOINT: 'https://s',
+ SWITCH_API_TOKEN: 'tok-sib',
+ SWITCH_AGENT_ID: 'sw-2',
+ },
+ });
+ h.state.nameTaken = true;
+ const fs = fakeFs({
+ [agentSettingsRelativePath('old-name')]: CREDS,
+ [agentSettingsRelativePath('new-name')]: SIBLING,
+ });
+ h.state.fs = fs;
+
+ const result = await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ expect(result).toEqual({
+ success: false,
+ error: { type: 'name-taken', name: 'new-name' },
+ });
+ expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(SIBLING);
+ expect(await fs.read(agentSettingsRelativePath('old-name'))).toBe(CREDS);
+ expect(h.writeDefinition).not.toHaveBeenCalled();
+ });
+
+ it('returns the renamed agent on success', async () => {
+ h.state.fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });
+
+ const result = await renameAgent({ agentId: 'agent-1', newName: 'new-name' });
+
+ expect(result.success).toBe(true);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
index f14360005..2623c354e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
@@ -1,16 +1,22 @@
+import { type Result, err, ok } from '@switchdash/shared';
import { eq, sql } from 'drizzle-orm';
import {
agentSidecarTmuxName,
killSidecarSession,
} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
+import { getPlugin } from '@main/core/providers/plugin-registry';
import { db } from '@main/db/client';
import { agents } from '@main/db/schema';
import { log } from '@main/lib/logger';
import type { Agent, RenameAgentParams } from '@shared/core/agents/agents';
-import { getRemoteAgentLocation } from './agent-location';
+import { getAgentLocation, getRemoteAgentLocation } from './agent-location';
+import { agentNameTaken } from './agent-name-taken';
+import { resolveWorkspaceFsFor } from './agent-workspace-fs';
import { connectRemoteAgent } from './connect-remote-agent';
import { getAgentById } from './getAgentById';
import { ensureRemoteWatcher } from './remote-watcher';
+import { removeAgentLaunchProfile } from './remove-launch-profile';
+import { agentSettingsRelativePath } from './switch-settings-paths';
import { mapAgentRowToAgent } from './utils';
/**
@@ -44,17 +50,94 @@ async function moveSidecarToNewName(previous: Agent, renamed: Agent): Promise<vo
}
}
-export async function renameAgent(params: RenameAgentParams): Promise<Agent | undefined> {
+/**
+ * Move the agent's on-disk state to its new name.
+ *
+ * Everything switchdash writes per agent is keyed by the agent's `name` — the
+ * Switch credentials at `.switch/agents/<name>.json` and, for a provider with
+ * repo-agent definitions, the definition the CLI is launched against
+ * (`--agent <name>`). A rename that only updates the row leaves both behind
+ * under the old key, and the credentials are unrecoverable: the token is minted
+ * once and lives nowhere else, so the agent would silently fall back to the
+ * shared `.claude/settings.local.json` identity — possibly another agent's.
+ *
+ * The new files are written before the old ones are removed, so an interruption
+ * leaves a recoverable duplicate rather than nothing.
+ *
+ * Best-effort — a rename must not fail because the VM is unreachable. A failure
+ * here leaves the agent on its old key, which the next launch reports as missing
+ * credentials rather than silently mis-authenticating.
+ */
+async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<void> {
+ const from = previous.name ?? previous.id;
+ const to = renamed.name ?? renamed.id;
+ if (from === to) return;
+
+ try {
+ const location = await getAgentLocation(previous);
+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);
+ try {
+ const creds = await ctx.fs.read(agentSettingsRelativePath(from));
+ if (creds !== null) await ctx.fs.write(agentSettingsRelativePath(to), creds);
+
+ const behavior = getPlugin(previous.providerId).behavior.repoAgents;
+ const definition = behavior ? await behavior.readDefinition(ctx.fs, from) : null;
+ if (behavior && definition) {
+ await behavior.writeDefinition(ctx.fs, { ...definition, name: to });
+ }
+
+ if (creds !== null) await ctx.fs.delete(agentSettingsRelativePath(from));
+ if (behavior && definition) await behavior.removeLocal(ctx.fs, from);
+ } finally {
+ ctx.close();
+ }
+
+ // A launch profile (Codex) is keyed on the agent name, so the rename orphans
+ // the old-named one; it is rewritten under the new name on the next launch,
+ // so just drop the stale file. Reached through its own home filesystem (the
+ // repo-dir workspace fs above has no writable home for a remote agent).
+ await removeAgentLaunchProfile(previous, location, from);
+ } catch (error) {
+ log.warn('renameAgent: failed to move the agent files to the new name', {
+ agentId: previous.id,
+ from,
+ to,
+ error: String(error),
+ });
+ }
+}
+
+export type RenameAgentError = { type: 'agent-not-found' } | { type: 'name-taken'; name: string };
+
+/**
+ * Rename an agent and move the on-disk state keyed by its old name.
+ *
+ * The name must be free in the agent's location before anything is written:
+ * {@link moveProvisionedFiles} writes the credentials to the destination
+ * unconditionally, so renaming onto a sibling would hand that sibling this
+ * agent's Switch token and then delete the original.
+ */
+export async function renameAgent(
+ params: RenameAgentParams
+): Promise<Result<Agent, RenameAgentError>> {
const previous = await getAgentById(params.agentId);
+ if (!previous) return err({ type: 'agent-not-found' });
+
+ if (await agentNameTaken(previous.locationId, params.newName, previous.id)) {
+ return err({ type: 'name-taken', name: params.newName });
+ }
+
const [row] = await db
.update(agents)
.set({ name: params.newName, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(agents.id, params.agentId))
.returning();
- if (!row) return undefined;
+ if (!row) return err({ type: 'agent-not-found' });
+
const renamed = mapAgentRowToAgent(row);
- if (previous && previous.name !== renamed.name) {
+ if (previous.name !== renamed.name) {
+ await moveProvisionedFiles(previous, renamed);
await moveSidecarToNewName(previous, renamed);
}
- return renamed;
+ return ok(renamed);
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
index a908206fe..d0f6407d5 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
@@ -14,6 +14,7 @@ import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';
import { getRemoteAgentLocation } from './agent-location';
@@ -48,6 +49,7 @@ async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<s
autoApprove: agent.autoApprove,
credsSlug: agent.name ?? agent.id,
agentName: agent.name ?? null,
+ specialization: toSwitchSpecialization(agent.providerConfig),
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
index 9fd84ef9b..f3a542541 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/utils.ts
@@ -17,6 +17,7 @@ export function mapAgentRowToAgent(row: AgentRow): Agent {
serverId: row.serverId ?? null,
status: row.status ?? null,
autoApprove: row.autoApprove,
+ providerConfig: row.providerConfig ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts
index c1d2441a5..cb573d725 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts
@@ -50,7 +50,7 @@ describe('writeSwitchSettings', () => {
});
// The Switch connector tools are auto-approved ("don't ask").
expect(settings.permissions).toEqual({
- allow: ['mcp__plugin_switch-connector_switch', 'mcp__plugin_switch-connector_switch-channel'],
+ allow: ['mcp__plugin_switch-connector_switch'],
});
// The detector should now recognise the directory as a configured agent.
@@ -84,11 +84,7 @@ describe('writeSwitchSettings', () => {
const settings = await readSettings();
// Existing allow rules are preserved; the Switch rules are unioned in.
expect(settings.permissions).toEqual({
- allow: [
- 'Bash',
- 'mcp__plugin_switch-connector_switch',
- 'mcp__plugin_switch-connector_switch-channel',
- ],
+ allow: ['Bash', 'mcp__plugin_switch-connector_switch'],
});
expect(settings.env).toEqual({
EXISTING_KEY: 'keep-me',
@@ -153,11 +149,7 @@ describe('writeNeutralAgentSettingsFs', () => {
// The connector's MCP tools are auto-approved on top of whatever the agent
// already allowed, so a Switch agent never has to ask to reach its room.
expect(settings.permissions).toEqual({
- allow: [
- 'Bash',
- 'mcp__plugin_switch-connector_switch',
- 'mcp__plugin_switch-connector_switch-channel',
- ],
+ allow: ['Bash', 'mcp__plugin_switch-connector_switch'],
});
});
@@ -302,7 +294,8 @@ describe('removeSwitchSettings', () => {
expect(result.kind).toBe('write');
const parsed = JSON.parse((result as { content: string }).content) as Record<string, unknown>;
- // Both blocks held only our contributions, so both are dropped entirely.
+ // Both blocks held only our contributions — including the retired
+ // switch-channel rule an older switchdash wrote — so both are dropped.
expect(parsed).toEqual({ hooks: { PostToolUse: [{ command: 'x' }] } });
expect('env' in parsed).toBe(false);
expect('permissions' in parsed).toBe(false);
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts
index 090e85968..45767d070 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts
@@ -1,6 +1,9 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
-import { SWITCH_CONNECTOR_TOOL_RULES } from '@switchdash/core/agents/plugins';
+import {
+ RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES,
+ SWITCH_CONNECTOR_TOOL_RULES,
+} from '@switchdash/core/agents/plugins';
import type { PluginFs } from '@switchdash/core/agents/plugins';
import { createPluginFs } from '@main/core/providers/plugin-fs';
import {
@@ -194,10 +197,9 @@ export function removeSwitchSettings(existingRaw: string | null): RemoveSwitchSe
? { ...(existing.permissions as Record<string, unknown>) }
: null;
if (perms && Array.isArray(perms.allow)) {
- const connectorRules = SWITCH_CONNECTOR_TOOL_RULES as readonly string[];
const allow = (perms.allow as unknown[])
.map(String)
- .filter((rule) => !connectorRules.includes(rule));
+ .filter((rule) => !RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES.includes(rule));
if (allow.length > 0) {
perms.allow = allow;
} else {
diff --git a/dash/apps/switchdash-desktop/src/main/core/fs/assert-removed.ts b/dash/apps/switchdash-desktop/src/main/core/fs/assert-removed.ts
new file mode 100644
index 000000000..046e3e504
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/fs/assert-removed.ts
@@ -0,0 +1,21 @@
+/**
+ * Turn a {@link FileSystemProvider.remove} result into the `PluginFs.delete`
+ * contract: absent is success, everything else throws.
+ *
+ * `remove` never throws — it reports through `{ success, error }` — so a caller
+ * that ignores the result swallows permission denied, a non-recursive directory,
+ * a failed `rm -rf`, and a dropped connection alike. `delete` is how an agent's
+ * Switch token is revoked from disk, so a silent no-op there reports a credential
+ * as destroyed while it is still readable on the host.
+ *
+ * The not-found case is matched on the message because the result carries no
+ * error code; the literal is the one produced by `SshFileSystem.remove` when its
+ * `stat` finds nothing. Prefer a structured code on the result if one is ever
+ * added — message matching is the weakest part of this check.
+ */
+export function assertRemoved(path: string, result: { success: boolean; error?: string }): void {
+ if (result.success) return;
+ const error = result.error ?? 'unknown error';
+ if (error.startsWith('File not found')) return;
+ throw new Error(`remote plugin fs: failed to delete ${path}: ${error}`);
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.test.ts
new file mode 100644
index 000000000..aa66b7966
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.test.ts
@@ -0,0 +1,63 @@
+import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createPluginFs } from './plugin-fs';
+
+/**
+ * Against a real temp directory rather than a mocked `node:fs`: the behaviour
+ * under test is which errno values are treated as "already absent", and a mock
+ * would just restate the implementation's own answer.
+ */
+describe('createPluginFs delete', () => {
+ let root: string;
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(tmpdir(), 'plugin-fs-'));
+ });
+
+ afterEach(async () => {
+ await chmod(root, 0o755).catch(() => {});
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('removes an existing file', async () => {
+ const fs = createPluginFs(root);
+ await writeFile(path.join(root, 'creds.json'), '{}');
+
+ await fs.delete('creds.json');
+
+ expect(await fs.exists('creds.json')).toBe(false);
+ });
+
+ it('resolves when the file is already gone', async () => {
+ const fs = createPluginFs(root);
+ await expect(fs.delete('never-existed.json')).resolves.toBeUndefined();
+ });
+
+ it('resolves when a parent path segment is not a directory', async () => {
+ // ENOTDIR: the file equally does not exist, same reasoning as read().
+ const fs = createPluginFs(root);
+ await writeFile(path.join(root, 'afile'), 'x');
+ await expect(fs.delete('afile/nested.json')).resolves.toBeUndefined();
+ });
+
+ it('throws (fails loud) when the file exists but cannot be removed', async () => {
+ // A silently-swallowed failure here reports an agent's Switch token as
+ // revoked while it is still readable on disk.
+ const fs = createPluginFs(root);
+ const locked = path.join(root, 'locked');
+ await mkdir(locked);
+ await writeFile(path.join(locked, 'token.json'), 'secret');
+ await chmod(locked, 0o500); // r-x: the entry cannot be unlinked
+
+ await expect(fs.delete('locked/token.json')).rejects.toThrow();
+
+ await chmod(locked, 0o700);
+ });
+
+ it('throws on a path escape instead of silently doing nothing', async () => {
+ const fs = createPluginFs(root);
+ await expect(fs.delete('../outside.json')).rejects.toThrow(/path escape/);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.ts
index 2ace3d710..f8de3fe9d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/plugin-fs.ts
@@ -44,10 +44,18 @@ export function createPluginFs(root: string): PluginFs {
},
async delete(path: string): Promise<void> {
+ const abs = resolveSafe(path);
try {
- await fs.unlink(resolveSafe(path));
- } catch {
- // Silently ignore if file doesn't exist
+ await fs.unlink(abs);
+ } catch (error) {
+ // Only "already absent" is success, on the same reasoning as read().
+ // A permission error or an I/O failure must propagate: delete is how an
+ // agent's Switch token is revoked from disk, and a silent no-op there
+ // reports a credential as destroyed while it is still readable.
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') {
+ throw error;
+ }
}
},
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/provider-argv-parity.test.ts b/dash/apps/switchdash-desktop/src/main/core/providers/provider-argv-parity.test.ts
new file mode 100644
index 000000000..146e9a21d
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/provider-argv-parity.test.ts
@@ -0,0 +1,62 @@
+import { pluginRegistry } from '@switchdash/plugins/agents';
+import { describe, expect, it } from 'vitest';
+import { getProvider } from '@shared/core/providers/agent-provider-registry';
+
+/** `splitFlag` in standard-command.ts is not exported; this mirrors it. */
+function splitFlag(flag: string): string[] {
+ return flag.split(/\s+/).filter(Boolean);
+}
+
+/** Whether `needle` appears in `haystack` as a contiguous run. */
+function containsSequence(haystack: string[], needle: string[]): boolean {
+ if (needle.length === 0) return true;
+ return haystack.some((_, i) => needle.every((token, offset) => haystack[i + offset] === token));
+}
+
+function buildCodexArgs(autoApprove: boolean): string[] {
+ return pluginRegistry.get('codex')!.behavior.prompt!.buildCommand({
+ cli: 'codex',
+ autoApprove,
+ model: '',
+ isResuming: false,
+ }).args;
+}
+
+/**
+ * The registry's argv fields describe the plugin rather than driving it, so
+ * nothing at runtime notices when the two disagree. Codex is the entry worth
+ * pinning: its flags suppress approval prompts and bypass hook trust, so a
+ * stale mirror misrepresents how much access a session is launched with.
+ */
+describe('codex registry metadata matches the argv the plugin builds', () => {
+ it('emits the mirrored defaultArgs and autoApproveFlag', () => {
+ const def = getProvider('codex')!;
+ const args = buildCodexArgs(true);
+
+ expect(def.defaultArgs).toBeDefined();
+ expect(def.autoApproveFlag).toBeDefined();
+ expect(containsSequence(args, def.defaultArgs!)).toBe(true);
+ expect(containsSequence(args, splitFlag(def.autoApproveFlag!))).toBe(true);
+ });
+
+ it('leaves the sandbox to the user config on both sides of the mirror', () => {
+ // Auto-approve means unattended approvals, not unattended filesystem and
+ // network access. Codex runs hooks outside the sandbox, so switchdash's
+ // loopback hook curls do not need one relaxed on their behalf.
+ const def = getProvider('codex')!;
+
+ expect(def.autoApproveFlag).not.toContain('sandbox_mode');
+ expect(buildCodexArgs(true).join(' ')).not.toContain('sandbox_mode');
+ });
+
+ it('emits defaultArgs on a session that does not auto-approve', () => {
+ // Hook trust belongs in defaultArgs, not autoApproveFlag: Codex silently
+ // skips hooks it has no trust entry for, so gating it on auto-approve
+ // leaves a default session running none of switchdash's hooks.
+ const def = getProvider('codex')!;
+ const args = buildCodexArgs(false);
+
+ expect(containsSequence(args, def.defaultArgs!)).toBe(true);
+ expect(args).not.toContain('-c');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.test.ts
index 7b7c67651..6b3ef8f4f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.test.ts
@@ -58,12 +58,28 @@ describe('createRemotePluginFs', () => {
});
it('delete removes the path and ignores a missing file', async () => {
- const remove = vi.fn(async () => ({ success: false, error: 'File not found' }));
+ // The literal SshFileSystem.remove produces when its stat finds nothing.
+ const remove = vi.fn(async () => ({ success: false, error: 'File not found: gone' }));
const fs = adapter({ remove });
await expect(fs.delete('gone')).resolves.toBeUndefined();
expect(remove).toHaveBeenCalledWith('gone');
});
+ it('delete resolves when the remove succeeds', async () => {
+ const fs = adapter({ remove: vi.fn(async () => ({ success: true })) });
+ await expect(fs.delete('x')).resolves.toBeUndefined();
+ });
+
+ it('delete throws (fails loud) when the file is there but cannot be removed', async () => {
+ // `remove` reports failure through its result rather than throwing, so a
+ // caller that ignores the result reports an undeletable Switch token as
+ // revoked.
+ const fs = adapter({
+ remove: vi.fn(async () => ({ success: false, error: 'Permission denied' })),
+ });
+ await expect(fs.delete('.switch/agents/a.json')).rejects.toThrow(/Permission denied/);
+ });
+
it('exists passes through', async () => {
const fs = adapter({ exists: vi.fn(async () => true) });
expect(await fs.exists('x')).toBe(true);
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.ts
index b97ccfd67..f7729f815 100644
--- a/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/remote-plugin-fs.ts
@@ -1,5 +1,6 @@
import { posix as pathPosix } from 'node:path';
import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { assertRemoved } from '@main/core/fs/assert-removed';
import type { SshFileSystem } from '@main/core/fs/impl/ssh-fs';
import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';
@@ -46,8 +47,7 @@ export function createRemotePluginFs(fs: SshFileSystem): PluginFs {
},
async delete(path: string): Promise<void> {
- // Match the local fs: a missing file is not an error, so ignore the result.
- await fs.remove(path);
+ assertRemoved(path, await fs.remove(path));
},
async exists(path: string): Promise<boolean> {
diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
index bf8301450..bf28d455e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
@@ -13,6 +13,7 @@ import { getAgentById } from '@main/core/agents/getAgentById';
import { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import { type AgentSidecarStatus, sidecarStatusChannel } from '@shared/events/sidecarEvents';
import { createRPCController } from '@shared/lib/ipc/rpc';
@@ -46,6 +47,7 @@ async function paramsForAgent(agent: Agent): Promise<AgentSidecarParams> {
autoApprove: agent.autoApprove,
credsSlug: agent.name ?? agent.id,
agentName: agent.name ?? null,
+ specialization: toSwitchSpecialization(agent.providerConfig),
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts
index 764ca2acb..5a38a6000 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/sidecar-diagnostics.ts
@@ -5,6 +5,7 @@ import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
import { getAgents } from '@main/core/agents/getAgents';
import { registerDiagnosticSection } from '@main/lib/file-logger';
import { log } from '@main/lib/logger';
+import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
const DIAGNOSTIC_TAIL_LINES = 200;
@@ -54,6 +55,7 @@ async function collectForAgent(agent: Agent): Promise<string> {
autoApprove: agent.autoApprove,
credsSlug: agent.name ?? agent.id,
agentName: agent.name ?? null,
+ specialization: toSwitchSpecialization(agent.providerConfig),
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/plugin-prompt-injector.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/plugin-prompt-injector.ts
index 809d2a143..5e35aee56 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/plugin-prompt-injector.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/plugin-prompt-injector.ts
@@ -10,8 +10,8 @@ const DEFAULT_SUBMIT_DELAY_MS = 150;
/**
* Resolves a provider's keystroke-injection behavior from the plugin registry.
- * Used by the local main process; the remote sidecar supplies its own
- * `PromptInjector` since the plugin registry is not available there.
+ * Shared: the local main process and the remote sidecar both construct this, so
+ * a provider's submit sequence and delay are defined once.
*/
export class PluginPromptInjector implements PromptInjector {
constructor(private readonly providerId: string) {}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
index eb76f1c19..f4f6e8a02 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -222,50 +222,6 @@ function bodyOf(call: unknown[]): Record<string, unknown> {
return JSON.parse(init.body) as Record<string, unknown>;
}
-describe('registerKnownAgent', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.stubGlobal('fetch', fetchMock);
- getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
- fetchMock.mockImplementation(
- async () =>
- ({
- status: 200,
- ok: true,
- json: async () => ({ id: 'sw-1', api_key: 'tok-123' }),
- headers: { getSetCookie: () => [] },
- text: async () => '',
- }) as unknown as Response
- );
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it('sends the caller-supplied agent_type rather than a hardcoded default', async () => {
- // The type governs the connector label and the hand-onboarding command the
- // gateway shows, so a default here would silently mislabel every non-Claude
- // agent (CHOO-1436).
- const registered = await registerKnownAgent(SERVER, {
- name: 'codex-hoot',
- description: 'Codex running in repo',
- agentType: 'codex',
- options: { channels_enabled: true, repo_dir: '/repo' },
- });
-
- expect(registered).toEqual({ id: 'sw-1', apiKey: 'tok-123' });
- const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];
- expect(JSON.parse(init.body)).toEqual({
- agent_type: 'codex',
- name: 'codex-hoot',
- description: 'Codex running in repo',
- options: { channels_enabled: true, repo_dir: '/repo' },
- overwrite: false,
- });
- });
-});
-
describe('room creation', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -378,3 +334,47 @@ describe('room creation', () => {
).rejects.toMatchObject({ status: 502, detail: undefined });
});
});
+
+describe('registerKnownAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));
+ fetchMock.mockImplementation(
+ async () =>
+ ({
+ status: 200,
+ ok: true,
+ json: async () => ({ id: 'sw-1', api_key: 'tok-123' }),
+ headers: { getSetCookie: () => [] },
+ text: async () => '',
+ }) as unknown as Response
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('sends the caller-supplied agent_type rather than a hardcoded default', async () => {
+ // The type governs the connector label and the hand-onboarding command the
+ // gateway shows, so a default here would silently mislabel every non-Claude
+ // agent (CHOO-1436).
+ const registered = await registerKnownAgent(SERVER, {
+ name: 'codex-hoot',
+ description: 'Codex running in repo',
+ agentType: 'codex',
+ options: { channels_enabled: true, repo_dir: '/repo' },
+ });
+
+ expect(registered).toEqual({ id: 'sw-1', apiKey: 'tok-123' });
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];
+ expect(JSON.parse(init.body)).toEqual({
+ agent_type: 'codex',
+ name: 'codex-hoot',
+ description: 'Codex running in repo',
+ options: { channels_enabled: true, repo_dir: '/repo' },
+ overwrite: false,
+ });
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts
new file mode 100644
index 000000000..414661bfb
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts
@@ -0,0 +1,324 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ exec: vi.fn(),
+ resolveCommandPath: vi.fn(),
+ getPlugin: vi.fn(),
+ listPlugins: vi.fn(),
+ ensureSshConnected: vi.fn(),
+}));
+
+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({
+ SshExecutionContext: class {
+ exec = mocks.exec;
+ },
+}));
+
+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({
+ ensureSshConnected: mocks.ensureSshConnected,
+}));
+
+vi.mock('@switchdash/core/deps/runtime', () => ({
+ resolveCommandPath: mocks.resolveCommandPath,
+}));
+
+vi.mock('../providers/plugin-registry', () => ({
+ getPlugin: mocks.getPlugin,
+ listPlugins: mocks.listPlugins,
+}));
+
+vi.mock('@main/lib/logger', () => ({
+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
+}));
+
+import { getRemoteSwitchSetupService } from './remote-switch-setup';
+
+const SSH_HOST = 'agent-host';
+
+const CLAUDE_AGENT = {
+ metadata: { id: 'claude' },
+ capabilities: {
+ switchSetup: {
+ kind: 'cli',
+ pluginName: 'switch-connector',
+ marketplaceName: 'switch-plugins',
+ marketplaceSource: 'sandbox-quantum/switch',
+ scope: 'user',
+ dialect: 'claude-code',
+ },
+ hostDependency: { binaryNames: ['claude'] },
+ },
+};
+
+const CODEX_AGENT = {
+ metadata: { id: 'codex' },
+ capabilities: {
+ switchSetup: {
+ kind: 'cli',
+ pluginName: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ marketplaceSource: 'sandbox-quantum/switch',
+ scope: 'user',
+ dialect: 'codex',
+ },
+ hostDependency: { binaryNames: ['codex'] },
+ },
+};
+
+const CODEX_REF = 'switch-connector-codex@switch-plugins';
+
+/**
+ * A login shell sources the host's profile before the command runs, so its MOTD
+ * lands on stdout ahead of the JSON. This one carries brackets of its own, which
+ * a naive "slice from the first bracket" would latch onto.
+ */
+const MOTD = [
+ '###############################################',
+ '# ACME [production] — authorized use only #',
+ '# Last login: Tue Jul 28 09:12:33 2026 #',
+ '###############################################',
+].join('\n');
+
+function withBanner(json: string): string {
+ return `${MOTD}\n${json}\nConnection to ${SSH_HOST} closed.\n`;
+}
+
+function claudeExecImpl(installedVersion: string, advertisedVersion: string) {
+ return (_bin: string, args: string[] = []) => {
+ const a = args.join(' ');
+ if (a === 'plugin list --json') {
+ return Promise.resolve({
+ stdout: withBanner(
+ JSON.stringify([
+ {
+ id: 'switch-connector@switch-plugins',
+ version: installedVersion,
+ scope: 'user',
+ installPath: '/home/dev/.claude/plugins/switch-connector',
+ },
+ ])
+ ),
+ stderr: '',
+ });
+ }
+ if (a === 'plugin marketplace list --json') {
+ return Promise.resolve({
+ stdout: withBanner(
+ JSON.stringify([
+ {
+ name: 'switch-plugins',
+ source: 'github',
+ repo: 'sandbox-quantum/switch',
+ installLocation: '/home/dev/.claude/marketplaces/switch-plugins',
+ plugins: [{ name: 'switch-connector', version: advertisedVersion }],
+ },
+ ])
+ ),
+ stderr: '',
+ });
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ };
+}
+
+function codexExecImpl(marketplaceSource: string) {
+ return (_bin: string, args: string[] = []) => {
+ const a = args.join(' ');
+ if (a === 'plugin list --json') {
+ return Promise.resolve({
+ stdout: JSON.stringify({
+ installed: [
+ {
+ pluginId: CODEX_REF,
+ name: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ version: '0.1.0',
+ installed: true,
+ enabled: true,
+ source: { source: 'local', path: '/home/dev/.codex/plugins/switch-connector-codex' },
+ },
+ ],
+ available: [],
+ }),
+ stderr: '',
+ });
+ }
+ if (a === 'plugin marketplace list --json') {
+ return Promise.resolve({
+ stdout: JSON.stringify({
+ marketplaces: [
+ {
+ name: 'switch-plugins',
+ root: '/home/dev/.codex/marketplaces/switch-plugins',
+ marketplaceSource: { sourceType: 'github', source: marketplaceSource },
+ },
+ ],
+ }),
+ stderr: '',
+ });
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ };
+}
+
+function calls(): string[] {
+ return mocks.exec.mock.calls.map((c) => (c[1] as string[]).join(' '));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ensureSshConnected.mockResolvedValue({});
+ mocks.resolveCommandPath.mockResolvedValue('/usr/bin/codex');
+ mocks.getPlugin.mockReturnValue(CODEX_AGENT);
+});
+
+describe('RemoteSwitchSetupService.getStatus', () => {
+ it('parses CLI JSON printed after a login-shell banner', async () => {
+ mocks.getPlugin.mockReturnValue(CLAUDE_AGENT);
+ mocks.resolveCommandPath.mockResolvedValue('/usr/bin/claude');
+ mocks.exec.mockImplementation(claudeExecImpl('0.1.0', '0.2.0'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const status = await service.getStatus('claude');
+
+ expect(status).toMatchObject({
+ supported: true,
+ installed: true,
+ installedVersion: '0.1.0',
+ latestVersion: '0.2.0',
+ updateAvailable: true,
+ });
+ });
+
+ it('issues exactly one plugin list and one marketplace list for codex', async () => {
+ // Codex advertises no versions, so an unknown latest is the correct answer —
+ // re-reading the plugin list to look for one would only cost another SSH exec.
+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const status = await service.getStatus('codex');
+
+ expect(status).toMatchObject({
+ supported: true,
+ installed: true,
+ installedVersion: '0.1.0',
+ latestVersion: null,
+ updateAvailable: false,
+ });
+ expect(calls()).toEqual(['plugin list --json', 'plugin marketplace list --json']);
+ });
+});
+
+describe('RemoteSwitchSetupService.update', () => {
+ it('repairs a stale marketplace before removing the installed plugin', async () => {
+ // With no per-plugin update verb the update is destructive: a marketplace
+ // still pointing at a pre-migration source would fail the re-add *after* the
+ // remove succeeded, leaving the host with no connector.
+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch-legacy'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const result = await service.update('codex');
+
+ expect(result.success).toBe(true);
+ const seen = calls();
+ expect(seen).toContain('plugin marketplace remove switch-plugins');
+ expect(seen.indexOf('plugin marketplace add sandbox-quantum/switch')).toBeLessThan(
+ seen.indexOf(`plugin remove ${CODEX_REF}`)
+ );
+ });
+
+ it('reports a marketplace failure without removing the installed plugin', async () => {
+ mocks.exec.mockImplementation((_bin: string, args: string[] = []) => {
+ if (args.join(' ') === 'plugin marketplace add sandbox-quantum/switch') {
+ return Promise.reject(
+ Object.assign(new Error('exit 1'), { code: 1, stderr: 'no network' })
+ );
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ });
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const result = await service.update('codex');
+
+ expect(result.success).toBe(false);
+ expect(result.message).toMatch(/Could not add marketplace/);
+ expect(calls()).not.toContain(`plugin remove ${CODEX_REF}`);
+ });
+
+ it('surfaces a refreshError when the codex marketplace upgrade fails', async () => {
+ const base = codexExecImpl('sandbox-quantum/switch');
+ mocks.exec.mockImplementation((bin: string, args: string[] = []) => {
+ if (args.join(' ') === 'plugin marketplace upgrade switch-plugins') {
+ return Promise.reject(Object.assign(new Error('exit 1'), { code: 1, stderr: 'offline' }));
+ }
+ return base(bin, args);
+ });
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const status = await service.checkForUpdates('codex');
+
+ expect(status.refreshError).toMatch(/offline/);
+ expect(status.installed).toBe(true);
+ });
+
+ it('removes then re-adds for codex, which has no per-plugin update verb', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const result = await service.update('codex');
+
+ expect(result.success).toBe(true);
+ // The marketplace is repaired first: the re-add resolves against it, so a
+ // stale source must not be discovered after the remove has succeeded.
+ expect(calls()).toEqual([
+ 'plugin marketplace list --json',
+ `plugin remove ${CODEX_REF}`,
+ `plugin add ${CODEX_REF}`,
+ ]);
+ });
+
+ it('reports the plugin as removed-but-not-reinstalled when the re-add fails', async () => {
+ mocks.exec.mockImplementation((_bin: string, args: string[] = []) => {
+ if (args.join(' ') === `plugin add ${CODEX_REF}`) {
+ // With no stderr to relay, our own wording is all the user gets — and it
+ // has to say the host now has no connector, not just "update failed".
+ return Promise.reject(Object.assign(new Error('exit 1'), { code: 1, stderr: '' }));
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ });
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const result = await service.update('codex');
+
+ expect(calls().slice(-2)).toEqual([`plugin remove ${CODEX_REF}`, `plugin add ${CODEX_REF}`]);
+ expect(result).toEqual({
+ success: false,
+ message:
+ 'Update failed: the plugin was removed but could not be reinstalled. Install it again for this host.',
+ });
+ });
+});
+
+describe('RemoteSwitchSetupService.checkForUpdates', () => {
+ it('leaves a marketplace already pointing at the expected source alone', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const status = await service.checkForUpdates('codex');
+
+ expect(status.refreshError).toBeNull();
+ expect(calls()).not.toContain('plugin marketplace remove switch-plugins');
+ expect(calls()).toContain('plugin marketplace upgrade switch-plugins');
+ });
+
+ it('re-points a same-named marketplace registered against a stale source', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch-legacy'));
+
+ const service = await getRemoteSwitchSetupService(SSH_HOST);
+ const status = await service.checkForUpdates('codex');
+
+ expect(status.refreshError).toBeNull();
+ expect(calls()).toContain('plugin marketplace remove switch-plugins');
+ expect(calls()).toContain('plugin marketplace add sandbox-quantum/switch');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts
index 14e760ac9..26474ccf2 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts
@@ -1,16 +1,12 @@
import { resolveCommandPath } from '@switchdash/core/deps/runtime';
-import semver from 'semver';
import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';
import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
import { log } from '@main/lib/logger';
import { getPlugin, listPlugins } from '../providers/plugin-registry';
-import type {
- MarketplaceListEntry,
- SwitchSetupResult,
- SwitchSetupStatus,
-} from './switch-setup-service';
-import { marketplaceMatchesSource } from './switch-setup-service';
+import { cliRulesFor, type SwitchSetupCliRules } from './switch-setup-cli-dialect';
+import type { SwitchSetupResult, SwitchSetupStatus } from './switch-setup-service';
+import { isNewerVersion, marketplaceMatchesSource } from './switch-setup-service';
const EXEC_TIMEOUT_MS = 120_000;
@@ -59,18 +55,14 @@ function parseJsonLoose(stdout: string): unknown {
return null;
}
-function isNewerVersion(installed: string, latest: string): boolean {
- const a = semver.coerce(installed);
- const b = semver.coerce(latest);
- if (a === null || b === null) return false;
- return semver.gt(b, a);
-}
-
/**
* Remote counterpart of SwitchSetupService: drives an agent type's
- * plugin-marketplace CLI (`<bin> plugin install/update/...`) on an SSH host to
- * manage its Switch connector plugin. Versions come from the CLI's own JSON
- * output (not on-disk manifests) so no SFTP round-trips are needed.
+ * plugin-marketplace CLI (`<bin> plugin ...`) on an SSH host to manage its
+ * Switch connector plugin, taking the host's verbs, flags and JSON shapes from
+ * the same dialect table the local driver uses. Versions come from the CLI's own
+ * JSON output (not on-disk manifests) so no SFTP round-trips are needed — which
+ * is why a dialect that advertises no versions (Codex) reports "unknown" here
+ * rather than "up to date".
*/
export class RemoteSwitchSetupService {
constructor(private readonly ctx: SshExecutionContext) {}
@@ -83,7 +75,13 @@ export class RemoteSwitchSetupService {
if (!binaryName) return null;
const bin = (await resolveCommandPath(binaryName, this.ctx)) ?? binaryName;
const ref = `${descriptor.pluginName}@${descriptor.marketplaceName}`;
- return { descriptor, bin, ref };
+ return {
+ descriptor,
+ bin,
+ ref,
+ marketplaceSource: descriptor.marketplaceSource,
+ rules: cliRulesFor(descriptor.dialect),
+ };
}
private async run(bin: string, args: string[]): Promise<RunResult> {
@@ -106,30 +104,27 @@ export class RemoteSwitchSetupService {
}
}
- private async findInstalled(bin: string, ref: string) {
+ private async findInstalled(bin: string, ref: string, rules: SwitchSetupCliRules) {
const { stdout } = await this.run(bin, ['plugin', 'list', '--json']);
- const parsed = parseJsonLoose(stdout);
- if (parsed === null) return null;
- const list: Array<{ id?: string; version?: string }> = Array.isArray(parsed)
- ? parsed
- : (((parsed as { installed?: unknown[] })?.installed ?? []) as never[]);
- return list.find((p) => p.id === ref) ?? null;
+ return rules.parsePluginList(parseJsonLoose(stdout)).find((p) => p.ref === ref) ?? null;
}
+ /**
+ * Advertised version from CLI output alone — no SFTP round-trip to read
+ * manifests. Null means "unknown", which callers must not read as up to date;
+ * a dialect that does not report versions for uninstalled plugins always
+ * returns null here.
+ */
private async advertisedVersion(
bin: string,
marketplaceName: string,
- pluginName: string
+ pluginName: string,
+ rules: SwitchSetupCliRules
): Promise<string | null> {
const { stdout } = await this.run(bin, ['plugin', 'marketplace', 'list', '--json']);
- const parsed = parseJsonLoose(stdout);
- if (!Array.isArray(parsed)) return null;
- const markets = parsed as Array<{
- name?: string;
- plugins?: Array<{ name?: string; version?: string }>;
- }>;
- const market = markets.find((m) => m.name === marketplaceName);
- return market?.plugins?.find((p) => p.name === pluginName)?.version ?? null;
+ return (
+ rules.parseAdvertisedVersions(parseJsonLoose(stdout), marketplaceName).get(pluginName) ?? null
+ );
}
/**
@@ -141,18 +136,18 @@ export class RemoteSwitchSetupService {
private async ensureMarketplace(
bin: string,
marketplaceName: string,
- marketplaceSource: string
+ marketplaceSource: string,
+ rules: SwitchSetupCliRules
): Promise<void> {
const { stdout } = await this.run(bin, ['plugin', 'marketplace', 'list', '--json']);
- const parsed = parseJsonLoose(stdout);
- const existing = Array.isArray(parsed)
- ? (parsed as MarketplaceListEntry[]).find((m) => m.name === marketplaceName)
- : undefined;
+ const existing = rules
+ .parseMarketplaceList(parseJsonLoose(stdout))
+ .find((m) => m.name === marketplaceName);
if (existing) {
if (marketplaceMatchesSource(existing, marketplaceSource)) return;
log.warn('remote-switch-setup: re-pointing marketplace to current source', {
marketplaceName,
- from: existing.repo ?? existing.path ?? null,
+ from: existing.source,
to: marketplaceSource,
});
const removed = await this.run(bin, ['plugin', 'marketplace', 'remove', marketplaceName]);
@@ -171,14 +166,15 @@ export class RemoteSwitchSetupService {
async getStatus(agentId: string): Promise<SwitchSetupStatus> {
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
- const { descriptor, bin, ref } = resolved;
+ const { descriptor, bin, ref, rules } = resolved;
- const entry = await this.findInstalled(bin, ref);
+ const entry = await this.findInstalled(bin, ref, rules);
const installedVersion = entry?.version ?? null;
const latestVersion = await this.advertisedVersion(
bin,
descriptor.marketplaceName,
- descriptor.pluginName
+ descriptor.pluginName,
+ rules
);
const installed = entry !== null;
const updateAvailable =
@@ -205,16 +201,11 @@ export class RemoteSwitchSetupService {
async checkForUpdates(agentId: string): Promise<SwitchSetupStatus> {
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
- const { descriptor, bin } = resolved;
+ const { descriptor, bin, marketplaceSource, rules } = resolved;
let refreshError: string | null = null;
try {
- await this.ensureMarketplace(bin, descriptor.marketplaceName, descriptor.marketplaceSource);
- const res = await this.run(bin, [
- 'plugin',
- 'marketplace',
- 'update',
- descriptor.marketplaceName,
- ]);
+ await this.ensureMarketplace(bin, descriptor.marketplaceName, marketplaceSource, rules);
+ const res = await this.run(bin, rules.marketplaceRefreshArgs(descriptor.marketplaceName));
if (res.code !== 0) {
throw new Error(
res.stderr.trim() || `Failed to update marketplace ${descriptor.marketplaceName}`
@@ -231,27 +222,61 @@ export class RemoteSwitchSetupService {
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
- const { descriptor, bin, ref } = resolved;
+ const { descriptor, bin, ref, marketplaceSource, rules } = resolved;
try {
- await this.ensureMarketplace(bin, descriptor.marketplaceName, descriptor.marketplaceSource);
+ await this.ensureMarketplace(bin, descriptor.marketplaceName, marketplaceSource, rules);
} catch (err) {
return { success: false, message: `Could not add marketplace: ${String(err)}` };
}
- const res = await this.run(bin, ['plugin', 'install', ref, '-s', descriptor.scope]);
+ const res = await this.run(bin, rules.installArgs(ref, descriptor.scope));
return res.code === 0
? { success: true }
: { success: false, message: res.stderr.trim() || 'Install failed.' };
}
+ /**
+ * The marketplace is repaired first, exactly as `install` does: the re-add
+ * below resolves against whatever marketplace is registered, so a stale source
+ * would otherwise fail it after the uninstall has already succeeded.
+ */
async update(agentId: string): Promise<SwitchSetupResult> {
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
- const { descriptor, bin, ref } = resolved;
- const res = await this.run(bin, ['plugin', 'update', ref, '-s', descriptor.scope]);
- return res.code === 0
+ const { descriptor, bin, ref, marketplaceSource, rules } = resolved;
+
+ try {
+ await this.ensureMarketplace(bin, descriptor.marketplaceName, marketplaceSource, rules);
+ } catch (err) {
+ return { success: false, message: `Could not add marketplace: ${String(err)}` };
+ }
+
+ const updateArgs = rules.updateArgs(ref, descriptor.scope);
+ if (updateArgs) {
+ const res = await this.run(bin, updateArgs);
+ return res.code === 0
+ ? { success: true }
+ : { success: false, message: res.stderr.trim() || 'Update failed.' };
+ }
+
+ // No per-plugin update verb (Codex): remove then re-add. A failed re-add
+ // leaves the host with no connector, so say that rather than 'Update failed'.
+ const removed = await this.run(bin, rules.uninstallArgs(ref, descriptor.scope));
+ if (removed.code !== 0) {
+ return {
+ success: false,
+ message: removed.stderr.trim() || 'Update failed: could not remove the installed plugin.',
+ };
+ }
+ const added = await this.run(bin, rules.installArgs(ref, descriptor.scope));
+ return added.code === 0
? { success: true }
- : { success: false, message: res.stderr.trim() || 'Update failed.' };
+ : {
+ success: false,
+ message:
+ added.stderr.trim() ||
+ 'Update failed: the plugin was removed but could not be reinstalled. Install it again for this host.',
+ };
}
/** Status of every Switch-supported agent type's connector plugin on this host. */
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.test.ts
new file mode 100644
index 000000000..ecb01bd1a
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from 'vitest';
+import { cliRulesFor } from './switch-setup-cli-dialect';
+
+/**
+ * Verbatim `codex plugin list --json` output, captured from Codex CLI 0.145.0.
+ * Kept literal so a future Codex change that renames a field fails here rather
+ * than silently reporting the connector as never installed.
+ */
+const CODEX_PLUGIN_LIST = JSON.stringify({
+ installed: [
+ {
+ pluginId: 'switch-connector-codex@switch-plugins',
+ name: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ version: '0.1.0',
+ installed: true,
+ enabled: true,
+ source: { source: 'local', path: '/repo/connectors/codex-plugin' },
+ },
+ ],
+ available: [],
+});
+
+/** Verbatim `codex plugin marketplace list --json` output (Codex CLI 0.145.0). */
+const CODEX_MARKETPLACE_LIST = JSON.stringify({
+ marketplaces: [
+ {
+ name: 'switch-plugins',
+ root: '/repo',
+ marketplaceSource: { sourceType: 'local', source: '/repo' },
+ },
+ ],
+});
+
+describe('codex dialect', () => {
+ const rules = cliRulesFor('codex');
+
+ it('reads the installed plugin from the object-wrapped list', () => {
+ // Claude's shape uses `id`/`installPath`; Codex uses `pluginId`/`source.path`.
+ // Parsing Codex output with Claude's reader yields nothing, which is how the
+ // connector would look permanently uninstalled without this dialect.
+ //
+ // `manifestPath` is null on purpose: `source.path` is the marketplace source
+ // directory, not the install directory, so a manifest read there reports the
+ // advertised version as the installed one and a stale install looks current.
+ expect(rules.parsePluginList(JSON.parse(CODEX_PLUGIN_LIST))).toEqual([
+ {
+ ref: 'switch-connector-codex@switch-plugins',
+ version: '0.1.0',
+ manifestPath: null,
+ },
+ ]);
+ expect(cliRulesFor('claude-code').parsePluginList(JSON.parse(CODEX_PLUGIN_LIST))).toEqual([]);
+ });
+
+ it('drops a disabled plugin, which Codex lists but does not load', () => {
+ const disabled = JSON.parse(CODEX_PLUGIN_LIST) as {
+ installed: Array<{ enabled: boolean }>;
+ };
+ disabled.installed[0].enabled = false;
+
+ expect(rules.parsePluginList(disabled)).toEqual([]);
+ });
+
+ it('reads marketplaces from the object-wrapped list', () => {
+ expect(rules.parseMarketplaceList(JSON.parse(CODEX_MARKETPLACE_LIST))).toEqual([
+ { name: 'switch-plugins', source: '/repo', root: '/repo' },
+ ]);
+ });
+
+ it('uses add/remove, no scope flag, and has no per-plugin update verb', () => {
+ expect(rules.installArgs('p@m', 'user')).toEqual(['plugin', 'add', 'p@m']);
+ expect(rules.uninstallArgs('p@m', 'user')).toEqual(['plugin', 'remove', 'p@m']);
+ // Null is the signal for callers to fall back to remove-then-add.
+ expect(rules.updateArgs('p@m', 'user')).toBeNull();
+ expect(rules.marketplaceRefreshArgs('m')).toEqual(['plugin', 'marketplace', 'upgrade', 'm']);
+ });
+
+ it("reports no advertised versions, since Codex's marketplace listing carries none", () => {
+ expect(
+ rules.parseAdvertisedVersions(JSON.parse(CODEX_MARKETPLACE_LIST), 'switch-plugins').size
+ ).toBe(0);
+ });
+
+ it('looks for plugin manifests under .codex-plugin but marketplaces under .claude-plugin', () => {
+ // Codex reads a Claude-style marketplace manifest, which is what lets one
+ // marketplace file serve both CLIs.
+ expect(rules.pluginManifestDir).toBe('.codex-plugin');
+ expect(rules.marketplaceManifestDir).toBe('.claude-plugin');
+ });
+});
+
+describe('claude-code dialect', () => {
+ const rules = cliRulesFor('claude-code');
+
+ it('reads a bare array or an {installed} wrapper', () => {
+ const entry = { id: 'p@m', version: '1.2.3', installPath: '/cache/p' };
+ const expected = [{ ref: 'p@m', version: '1.2.3', manifestPath: '/cache/p' }];
+ expect(rules.parsePluginList([entry])).toEqual(expected);
+ expect(rules.parsePluginList({ installed: [entry] })).toEqual(expected);
+ });
+
+ it('matches a marketplace on either repo or path', () => {
+ expect(
+ rules.parseMarketplaceList([{ name: 'm', repo: 'owner/repo', installLocation: '/loc' }])
+ ).toEqual([{ name: 'm', source: 'owner/repo', root: '/loc' }]);
+ expect(rules.parseMarketplaceList([{ name: 'm', path: '/src' }])).toEqual([
+ { name: 'm', source: '/src', root: null },
+ ]);
+ });
+
+ it('keeps install/uninstall/update with the scope flag', () => {
+ expect(rules.installArgs('p@m', 'user')).toEqual(['plugin', 'install', 'p@m', '-s', 'user']);
+ expect(rules.updateArgs('p@m', 'local')).toEqual(['plugin', 'update', 'p@m', '-s', 'local']);
+ expect(rules.marketplaceRefreshArgs('m')).toEqual(['plugin', 'marketplace', 'update', 'm']);
+ });
+});
+
+describe('parser robustness', () => {
+ // These feed status reads on the settings page. Unexpected output must degrade
+ // to "nothing found" rather than throw — a crash here blanks the whole page.
+ it.each(['claude-code', 'codex'] as const)('%s tolerates junk input', (dialect) => {
+ const rules = cliRulesFor(dialect);
+ for (const junk of [null, undefined, 'not json', 42, [], {}, { installed: 'nope' }]) {
+ expect(rules.parsePluginList(junk)).toEqual([]);
+ expect(rules.parseMarketplaceList(junk)).toEqual([]);
+ }
+ });
+
+ it('drops entries missing the identifying field rather than emitting partials', () => {
+ expect(cliRulesFor('codex').parsePluginList({ installed: [{ version: '1.0.0' }] })).toEqual([]);
+ expect(cliRulesFor('claude-code').parsePluginList([{ version: '1.0.0' }])).toEqual([]);
+ });
+
+ it('fails loudly on an unknown dialect', () => {
+ expect(() => cliRulesFor('nope' as never)).toThrow(/No plugin-CLI rules for dialect/);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.ts
new file mode 100644
index 000000000..63fb2b9f2
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-cli-dialect.ts
@@ -0,0 +1,190 @@
+import type { SwitchSetupCliDialect } from '@switchdash/core/agents/plugins';
+
+/**
+ * One installed plugin, normalised across CLI dialects.
+ *
+ * `ref` is the `<plugin>@<marketplace>` identifier used to address the plugin in
+ * install/remove commands. `manifestPath` is a directory that should contain the
+ * plugin manifest, when the CLI reports one worth reading.
+ */
+export type InstalledPlugin = {
+ ref: string;
+ version: string | null;
+ manifestPath: string | null;
+};
+
+/** One registered marketplace, normalised across CLI dialects. */
+export type RegisteredMarketplace = {
+ name: string;
+ /** The source it was registered from (a repo slug or a local path). */
+ source: string | null;
+ /** Local root of the marketplace checkout, where its manifest lives. */
+ root: string | null;
+};
+
+/**
+ * The surface differences between plugin-marketplace CLIs.
+ *
+ * Both dialects share the same model, so the driver stays generic; everything
+ * that genuinely differs — verbs, flags, and the JSON each command emits — is
+ * named here. Parsers are total: unparseable or unexpected output yields an
+ * empty list rather than throwing, because these feed status reads that must
+ * degrade to "not installed" rather than crash the settings page.
+ */
+export type SwitchSetupCliRules = {
+ /** Directory holding a plugin's manifest, relative to the plugin root. */
+ pluginManifestDir: string;
+ /** Directory holding a marketplace's manifest, relative to its root. */
+ marketplaceManifestDir: string;
+ installArgs(ref: string, scope: string): string[];
+ uninstallArgs(ref: string, scope: string): string[];
+ /**
+ * Args to update an installed plugin in place, or null when the CLI has no
+ * such verb — the driver then falls back to uninstall-then-install.
+ */
+ updateArgs(ref: string, scope: string): string[] | null;
+ /** Args to refresh a marketplace snapshot. */
+ marketplaceRefreshArgs(marketplaceName: string): string[];
+ /**
+ * Shape-readers over already-parsed CLI JSON. Callers own extraction — the
+ * local driver can `JSON.parse` directly, while the remote one must first
+ * strip login-shell banner noise — so the dialect only owns the shape.
+ */
+ parsePluginList(parsed: unknown): InstalledPlugin[];
+ parseMarketplaceList(parsed: unknown): RegisteredMarketplace[];
+ /**
+ * Versions the marketplace advertises, keyed by plugin name. Fed parsed
+ * `plugin marketplace list --json` output and nothing else — plugin-list
+ * output never carries advertised versions — so the remote driver can read
+ * them without a filesystem round-trip. An empty map means "unknown", which
+ * callers must treat as "no update detected" rather than "up to date".
+ */
+ parseAdvertisedVersions(parsed: unknown, marketplaceName: string): Map<string, string>;
+};
+
+const claudeCode: SwitchSetupCliRules = {
+ pluginManifestDir: '.claude-plugin',
+ marketplaceManifestDir: '.claude-plugin',
+ installArgs: (ref, scope) => ['plugin', 'install', ref, '-s', scope],
+ uninstallArgs: (ref, scope) => ['plugin', 'uninstall', ref, '-s', scope],
+ updateArgs: (ref, scope) => ['plugin', 'update', ref, '-s', scope],
+ marketplaceRefreshArgs: (name) => ['plugin', 'marketplace', 'update', name],
+
+ parsePluginList(parsed) {
+ const list: unknown = Array.isArray(parsed)
+ ? parsed
+ : ((parsed as { installed?: unknown } | null)?.installed ?? []);
+ if (!Array.isArray(list)) return [];
+ return list.flatMap((raw) => {
+ const e = raw as { id?: string; version?: string; installPath?: string };
+ if (typeof e.id !== 'string') return [];
+ return [{ ref: e.id, version: e.version ?? null, manifestPath: e.installPath ?? null }];
+ });
+ },
+
+ parseMarketplaceList(parsed) {
+ if (!Array.isArray(parsed)) return [];
+ return parsed.flatMap((raw) => {
+ const e = raw as { name?: string; repo?: string; path?: string; installLocation?: string };
+ if (typeof e.name !== 'string') return [];
+ return [{ name: e.name, source: e.repo ?? e.path ?? null, root: e.installLocation ?? null }];
+ });
+ },
+
+ parseAdvertisedVersions(parsed, marketplaceName) {
+ if (!Array.isArray(parsed)) return new Map();
+ const market = (
+ parsed as Array<{ name?: string; plugins?: Array<{ name?: string; version?: string }> }>
+ ).find((m) => m.name === marketplaceName);
+ const versions = new Map<string, string>();
+ for (const p of market?.plugins ?? []) {
+ if (typeof p.name === 'string' && typeof p.version === 'string')
+ versions.set(p.name, p.version);
+ }
+ return versions;
+ },
+};
+
+/**
+ * Codex's `plugin` subcommand. Verified against Codex CLI 0.145.0:
+ * `add`/`remove` rather than `install`/`uninstall`, no scope flag, no per-plugin
+ * update verb, `marketplace upgrade` rather than `update`, and both list
+ * commands return an object rather than a bare array. Its plugin manifests live
+ * under `.codex-plugin/`, but it reads a marketplace manifest from
+ * `.claude-plugin/` — so one marketplace file serves both CLIs.
+ */
+const codex: SwitchSetupCliRules = {
+ pluginManifestDir: '.codex-plugin',
+ marketplaceManifestDir: '.claude-plugin',
+ installArgs: (ref) => ['plugin', 'add', ref],
+ uninstallArgs: (ref) => ['plugin', 'remove', ref],
+ updateArgs: () => null,
+ marketplaceRefreshArgs: (name) => ['plugin', 'marketplace', 'upgrade', name],
+
+ parsePluginList(parsed) {
+ const list = (parsed as { installed?: unknown } | null)?.installed;
+ if (!Array.isArray(list)) return [];
+ return list.flatMap((raw) => {
+ const e = raw as {
+ pluginId?: string;
+ version?: string;
+ enabled?: boolean;
+ source?: { path?: string };
+ };
+ if (typeof e.pluginId !== 'string') return [];
+ // Codex lists a disabled plugin among the installed ones, but does not
+ // load its skill. Treating that as installed would offer the agent type
+ // for onboarding with its Switch tooling inert, so drop it and let the
+ // caller report the connector as absent — which is what it is, in effect.
+ if (e.enabled === false) return [];
+ // No manifest path. Codex copies the plugin into a versioned cache
+ // (`<CODEX_HOME>/plugins/cache/<marketplace>/<plugin>/<version>/`) but
+ // reports `source.path` as the marketplace SOURCE directory, so reading a
+ // manifest there yields the version the marketplace currently advertises,
+ // not the one installed. Handing that back as the installed version makes
+ // a stale install report itself up to date. `version` is the CLI's own
+ // account of what it installed, which is what this returns.
+ return [{ ref: e.pluginId, version: e.version ?? null, manifestPath: null }];
+ });
+ },
+
+ parseMarketplaceList(parsed) {
+ const list = (parsed as { marketplaces?: unknown } | null)?.marketplaces;
+ if (!Array.isArray(list)) return [];
+ return list.flatMap((raw) => {
+ const e = raw as { name?: string; root?: string; marketplaceSource?: { source?: string } };
+ if (typeof e.name !== 'string') return [];
+ return [{ name: e.name, source: e.marketplaceSource?.source ?? null, root: e.root ?? null }];
+ });
+ },
+
+ /**
+ * Codex's marketplace listing carries no plugin versions at all, so there is
+ * no advertised version to compare against from CLI output alone. Callers get
+ * an empty map, i.e. "unknown", and must not read that as "up to date".
+ *
+ * This only limits the remote driver. Locally, `advertisedVersion` reads the
+ * marketplace's on-disk manifests instead, which works for both dialects.
+ */
+ parseAdvertisedVersions() {
+ return new Map<string, string>();
+ },
+};
+
+const RULES: Record<SwitchSetupCliDialect, SwitchSetupCliRules> = {
+ 'claude-code': claudeCode,
+ codex,
+};
+
+export function cliRulesFor(dialect: SwitchSetupCliDialect): SwitchSetupCliRules {
+ const rules = RULES[dialect];
+ if (!rules) {
+ // Unreachable via a validated descriptor, but a missing entry would
+ // otherwise surface as an opaque "cannot read properties of undefined"
+ // several frames away from the actual cause.
+ throw new Error(
+ `No plugin-CLI rules for dialect '${dialect}'. Add an entry to the dialect table.`
+ );
+ }
+ return rules;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
index 85e6f01b9..1933d2e60 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
@@ -45,22 +45,47 @@ const CLI_AGENT = {
marketplaceName: 'switch-plugins',
marketplaceSource: 'sandbox-quantum/switch',
scope: 'user',
+ dialect: 'claude-code',
},
hostDependency: { binaryNames: ['claude'] },
},
};
-const NONE_AGENT = {
+const CODEX_AGENT = {
metadata: { id: 'codex' },
capabilities: {
- switchSetup: { kind: 'none' },
+ switchSetup: {
+ kind: 'cli',
+ pluginName: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ marketplaceSource: 'sandbox-quantum/switch',
+ scope: 'user',
+ dialect: 'codex',
+ },
hostDependency: { binaryNames: ['codex'] },
},
};
+const NONE_AGENT = {
+ metadata: { id: 'no-switch-agent' },
+ capabilities: {
+ switchSetup: { kind: 'none' },
+ hostDependency: { binaryNames: ['nosw'] },
+ },
+};
+
const INSTALL_PATH = '/cache/switch-plugins/switch-connector/0.1.0';
const MARKET_LOCATION = '/marketplaces/switch-plugins';
+const CODEX_REF = 'switch-connector-codex@switch-plugins';
+// Codex reports `source.path` as the marketplace SOURCE directory, not a
+// per-install cache — see the verbatim 0.145.0 capture in
+// switch-setup-cli-dialect.test.ts. For a local-path marketplace the installed
+// plugin therefore IS the checkout, and the installed and advertised manifests
+// resolve to the same file.
+const CODEX_MARKET_ROOT = '/repo';
+const CODEX_INSTALL_PATH = `${CODEX_MARKET_ROOT}/connectors/codex-plugin`;
+
/** Default happy-path exec: installed 0.1.0, marketplace present. */
function execImpl(installedVersion: string | null) {
return (_bin: string, args: string[] = []) => {
@@ -96,6 +121,75 @@ function execImpl(installedVersion: string | null) {
};
}
+/**
+ * Codex's CLI wraps both listings in an object and names its fields differently
+ * (`pluginId`/`source.path`, `marketplaces`/`marketplaceSource`), so the shapes
+ * are spelled out here rather than reusing the Claude fixtures.
+ */
+function codexExecImpl(installedVersion: string | null) {
+ return (_bin: string, args: string[] = []) => {
+ const a = args.join(' ');
+ if (a === 'plugin list --json') {
+ return Promise.resolve({
+ stdout: JSON.stringify({
+ installed:
+ installedVersion === null
+ ? []
+ : [
+ {
+ pluginId: CODEX_REF,
+ name: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ version: installedVersion,
+ installed: true,
+ enabled: true,
+ source: { source: 'local', path: CODEX_INSTALL_PATH },
+ },
+ ],
+ available: [],
+ }),
+ stderr: '',
+ });
+ }
+ if (a === 'plugin marketplace list --json') {
+ return Promise.resolve({
+ stdout: JSON.stringify({
+ marketplaces: [
+ {
+ name: 'switch-plugins',
+ root: CODEX_MARKET_ROOT,
+ marketplaceSource: { sourceType: 'github', source: 'sandbox-quantum/switch' },
+ },
+ ],
+ }),
+ stderr: '',
+ });
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ };
+}
+
+function codexReadFileImpl(manifestVersion: string) {
+ return (path: string) => {
+ if (path === `${CODEX_INSTALL_PATH}/.codex-plugin/plugin.json`) {
+ return Promise.resolve(JSON.stringify({ version: manifestVersion }));
+ }
+ // Present, and wrong, so a reader that went to Claude's manifest dir is
+ // caught rather than accidentally passing.
+ if (path === `${CODEX_INSTALL_PATH}/.claude-plugin/plugin.json`) {
+ return Promise.resolve(JSON.stringify({ version: '9.9.9' }));
+ }
+ if (path === `${CODEX_MARKET_ROOT}/.claude-plugin/marketplace.json`) {
+ return Promise.resolve(
+ JSON.stringify({
+ plugins: [{ name: 'switch-connector-codex', source: './connectors/codex-plugin' }],
+ })
+ );
+ }
+ return Promise.reject(new Error('ENOENT'));
+ };
+}
+
function readFileImpl(installedManifestVersion: string, advertisedVersion: string) {
return (path: string) => {
if (path === `${INSTALL_PATH}/.claude-plugin/plugin.json`) {
@@ -132,7 +226,7 @@ beforeEach(() => {
describe('switchSetupService.getStatus', () => {
it('reports unsupported for agents with kind: none', async () => {
mocks.getPlugin.mockReturnValue(NONE_AGENT);
- const status = await switchSetupService.getStatus('codex');
+ const status = await switchSetupService.getStatus('no-switch-agent');
expect(status.supported).toBe(false);
expect(status.installed).toBe(false);
expect(mocks.exec).not.toHaveBeenCalled();
@@ -247,7 +341,7 @@ describe('switchSetupService.checkForUpdates', () => {
{
name: 'switch-plugins',
source: 'github',
- repo: 'sandbox-quantum/napoleon',
+ repo: 'sandbox-quantum/switch-legacy',
installLocation: MARKET_LOCATION,
},
]),
@@ -360,3 +454,205 @@ describe('switchSetupService mutations', () => {
expect(result.message).toBe('no write access');
});
});
+
+describe('switchSetupService with the codex dialect', () => {
+ function calls(): string[] {
+ return mocks.exec.mock.calls.map((c) => (c[1] as string[]).join(' '));
+ }
+
+ beforeEach(() => {
+ mocks.getPlugin.mockReturnValue(CODEX_AGENT);
+ mocks.resolveCommandPath.mockResolvedValue('/usr/bin/codex');
+ });
+
+ it('takes the installed version from the CLI and the advertised one from the manifest', async () => {
+ // Codex copies the plugin into a versioned cache but reports `source.path`
+ // as the marketplace SOURCE directory. Reading a manifest there would give
+ // the advertised version and report it as installed, so a stale install
+ // would claim to be up to date. The CLI's own `version` is the installed
+ // one; the marketplace manifest under `.codex-plugin/` is the advertised
+ // one. Claude's `.claude-plugin/plugin.json` sits alongside reporting
+ // 9.9.9, so a reader that went to the wrong manifest dir fails here.
+ mocks.exec.mockImplementation(codexExecImpl('0.1.0'));
+ mocks.readFile.mockImplementation(codexReadFileImpl('0.2.0'));
+
+ const status = await switchSetupService.getStatus('codex');
+
+ expect(status).toMatchObject({
+ supported: true,
+ installed: true,
+ installedVersion: '0.1.0',
+ latestVersion: '0.2.0',
+ updateAvailable: true,
+ });
+ });
+
+ it('reports up to date when the installed version matches the marketplace', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('0.2.0'));
+ mocks.readFile.mockImplementation(codexReadFileImpl('0.2.0'));
+
+ expect(await switchSetupService.getStatus('codex')).toMatchObject({
+ installedVersion: '0.2.0',
+ latestVersion: '0.2.0',
+ updateAvailable: false,
+ });
+ });
+
+ it('reports not-installed when the object-wrapped list is empty', async () => {
+ mocks.exec.mockImplementation(codexExecImpl(null));
+ mocks.readFile.mockImplementation(codexReadFileImpl('0.2.0'));
+
+ const status = await switchSetupService.getStatus('codex');
+
+ expect(status).toMatchObject({
+ supported: true,
+ installed: false,
+ installedVersion: null,
+ updateAvailable: false,
+ });
+ });
+
+ it('installs with add and no scope flag', async () => {
+ mocks.exec.mockImplementation(codexExecImpl(null));
+
+ const result = await switchSetupService.install('codex');
+
+ expect(result.success).toBe(true);
+ expect(mocks.exec).toHaveBeenCalledWith(
+ '/usr/bin/codex',
+ ['plugin', 'add', CODEX_REF],
+ expect.anything()
+ );
+ });
+
+ it('uninstalls with remove and no scope flag', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('0.1.0'));
+
+ const result = await switchSetupService.uninstall('codex');
+
+ expect(result.success).toBe(true);
+ expect(mocks.exec).toHaveBeenCalledWith(
+ '/usr/bin/codex',
+ ['plugin', 'remove', CODEX_REF],
+ expect.anything()
+ );
+ });
+
+ it('refreshes the marketplace with upgrade rather than update', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('0.1.0'));
+ mocks.readFile.mockImplementation(codexReadFileImpl('0.1.0'));
+
+ const status = await switchSetupService.checkForUpdates('codex');
+
+ expect(status.refreshError).toBeNull();
+ expect(calls()).toContain('plugin marketplace upgrade switch-plugins');
+ expect(calls()).not.toContain('plugin marketplace update switch-plugins');
+ });
+
+ it('repairs a stale marketplace before removing the installed plugin', async () => {
+ // The destructive branch: with no per-plugin update verb, a marketplace still
+ // pointing at a pre-migration source would fail the re-add *after* the remove
+ // succeeded, leaving no connector at all.
+ const base = codexExecImpl('0.1.0');
+ mocks.exec.mockImplementation((bin: string, args: string[] = []) => {
+ if (args.join(' ') === 'plugin marketplace list --json') {
+ return Promise.resolve({
+ stdout: JSON.stringify({
+ marketplaces: [
+ {
+ name: 'switch-plugins',
+ root: CODEX_MARKET_ROOT,
+ marketplaceSource: {
+ sourceType: 'github',
+ source: 'sandbox-quantum/switch-legacy',
+ },
+ },
+ ],
+ }),
+ stderr: '',
+ });
+ }
+ return base(bin, args);
+ });
+
+ const result = await switchSetupService.update('codex');
+
+ expect(result.success).toBe(true);
+ const seen = calls();
+ expect(seen).toContain('plugin marketplace remove switch-plugins');
+ expect(seen).toContain('plugin marketplace add sandbox-quantum/switch');
+ expect(seen.indexOf('plugin marketplace add sandbox-quantum/switch')).toBeLessThan(
+ seen.indexOf(`plugin remove ${CODEX_REF}`)
+ );
+ });
+
+ it('reports a marketplace failure without removing the installed plugin', async () => {
+ mocks.exec.mockImplementation((_bin: string, args: string[] = []) => {
+ const a = args.join(' ');
+ if (a === 'plugin marketplace add sandbox-quantum/switch') {
+ return Promise.reject(
+ Object.assign(new Error('exit 1'), { code: 1, stderr: 'no network' })
+ );
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ });
+
+ const result = await switchSetupService.update('codex');
+
+ expect(result.success).toBe(false);
+ expect(result.message).toMatch(/Could not add marketplace/);
+ // Repairing first is what keeps this safe: nothing destructive ran.
+ expect(calls()).not.toContain(`plugin remove ${CODEX_REF}`);
+ });
+
+ it('surfaces a refreshError when the codex marketplace upgrade fails', async () => {
+ const base = codexExecImpl('0.1.0');
+ mocks.exec.mockImplementation((bin: string, args: string[] = []) => {
+ if (args.join(' ') === 'plugin marketplace upgrade switch-plugins') {
+ return Promise.reject(Object.assign(new Error('exit 1'), { code: 1, stderr: 'offline' }));
+ }
+ return base(bin, args);
+ });
+ mocks.readFile.mockImplementation(codexReadFileImpl('0.1.0'));
+
+ const status = await switchSetupService.checkForUpdates('codex');
+
+ expect(status.refreshError).toMatch(/offline/);
+ expect(status.installed).toBe(true);
+ });
+
+ it('updates by removing then re-adding, in that order', async () => {
+ mocks.exec.mockImplementation(codexExecImpl('0.1.0'));
+
+ const result = await switchSetupService.update('codex');
+
+ expect(result.success).toBe(true);
+ // The marketplace is repaired first: the re-add resolves against it, so a
+ // stale source must not be discovered after the remove has succeeded.
+ expect(calls()).toEqual([
+ 'plugin marketplace list --json',
+ `plugin remove ${CODEX_REF}`,
+ `plugin add ${CODEX_REF}`,
+ ]);
+ });
+
+ it('reports the plugin as removed-but-not-reinstalled when the re-add fails', async () => {
+ mocks.exec.mockImplementation((_bin: string, args: string[] = []) => {
+ if (args.join(' ') === `plugin add ${CODEX_REF}`) {
+ // With no stderr to relay, our own wording is all the user gets — and it
+ // has to say the host now has no connector, not just "update failed".
+ return Promise.reject(Object.assign(new Error('exit 1'), { code: 1, stderr: '' }));
+ }
+ return Promise.resolve({ stdout: '', stderr: '' });
+ });
+
+ const result = await switchSetupService.update('codex');
+
+ expect(calls().slice(-2)).toEqual([`plugin remove ${CODEX_REF}`, `plugin add ${CODEX_REF}`]);
+ expect(result).toEqual({
+ success: false,
+ message:
+ 'Update failed: the plugin was removed but could not be reinstalled. Install it again from Settings → Agents.',
+ });
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts
index 9e8e35f5a..80d7a04ae 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts
@@ -7,6 +7,12 @@ import { log } from '@main/lib/logger';
import { READ_PACKAGES_SCOPE } from '@shared/core/npm-registry';
import { getPlugin, listPlugins } from '../providers/plugin-registry';
import { probeLocalGhAuth } from './local-gh-auth';
+import {
+ cliRulesFor,
+ type InstalledPlugin,
+ type RegisteredMarketplace,
+ type SwitchSetupCliRules,
+} from './switch-setup-cli-dialect';
/** Status of an agent type's Switch connector plugin. */
export type SwitchSetupStatus = {
@@ -25,18 +31,9 @@ export type SwitchSetupStatus = {
refreshError: string | null;
};
-/** Marketplace entry shape from `plugin marketplace list --json`. */
-export type MarketplaceListEntry = {
- name?: string;
- source?: string;
- repo?: string;
- path?: string;
- installLocation?: string;
-};
-
-/** Whether a registered marketplace entry points at the expected source (repo or path). */
-export function marketplaceMatchesSource(entry: MarketplaceListEntry, source: string): boolean {
- return entry.repo === source || entry.path === source;
+/** Whether a registered marketplace entry points at the expected source. */
+export function marketplaceMatchesSource(entry: RegisteredMarketplace, source: string): boolean {
+ return entry.source === source;
}
/** Outcome of a mutating operation, mirroring the providers controller shape. */
@@ -80,6 +77,15 @@ async function describeInstallFailure(raw: string): Promise<string> {
type RunResult = { code: number; stdout: string; stderr: string };
+/** Parse CLI JSON, yielding null rather than throwing on unparseable output. */
+function parseJsonOrNull(stdout: string): unknown {
+ try {
+ return JSON.parse(stdout);
+ } catch {
+ return null;
+ }
+}
+
function unsupported(agentId: string): SwitchSetupStatus {
return {
agentId,
@@ -92,7 +98,8 @@ function unsupported(agentId: string): SwitchSetupStatus {
};
}
-function isNewerVersion(installed: string, latest: string): boolean {
+/** Whether `latest` is a newer semver than `installed`; false when either is unparseable. */
+export function isNewerVersion(installed: string, latest: string): boolean {
const a = semver.coerce(installed);
const b = semver.coerce(latest);
if (a === null || b === null) return false;
@@ -100,10 +107,13 @@ function isNewerVersion(installed: string, latest: string): boolean {
}
/**
- * Drives an agent's plugin-marketplace CLI (the Claude-Code model:
- * `<bin> plugin install/update/uninstall`, `<bin> plugin marketplace add/update/list`)
- * to manage that agent's Switch connector plugin. Status reads are local and fast;
- * the marketplace refresh used for update detection runs only on checkForUpdates.
+ * Drives an agent's plugin-marketplace CLI (`<bin> plugin ...`,
+ * `<bin> plugin marketplace ...`) to manage that agent's Switch connector
+ * plugin. The verbs, flags and JSON shapes differ per host, so everything
+ * host-specific comes from the dialect in `switch-setup-cli-dialect.ts` and this
+ * driver stays generic across Claude Code and Codex. Status reads are local and
+ * fast; the marketplace refresh used for update detection runs only on
+ * checkForUpdates.
*/
class SwitchSetupService {
private readonly ctx = new LocalExecutionContext();
@@ -117,7 +127,7 @@ class SwitchSetupService {
if (!binaryName) return null;
const bin = (await resolveCommandPath(binaryName, this.ctx)) ?? binaryName;
const ref = `${descriptor.pluginName}@${descriptor.marketplaceName}`;
- return { descriptor, bin, ref };
+ return { descriptor, bin, ref, rules: cliRulesFor(descriptor.dialect) };
}
/** Run a CLI command, capturing output and exit code without throwing. */
@@ -139,31 +149,25 @@ class SwitchSetupService {
}
}
- /** Find the installed plugin entry from `plugin list --json` (array or {installed}). */
- private async findInstalled(bin: string, ref: string) {
+ /** Find the installed plugin entry from `plugin list --json`. */
+ private async findInstalled(
+ bin: string,
+ ref: string,
+ rules: SwitchSetupCliRules
+ ): Promise<InstalledPlugin | null> {
const { stdout } = await this.run(bin, ['plugin', 'list', '--json']);
- let parsed: unknown;
- try {
- parsed = JSON.parse(stdout);
- } catch {
- return null;
- }
- const list: Array<{ id?: string; version?: string; installPath?: string }> = Array.isArray(
- parsed
- )
- ? parsed
- : (((parsed as { installed?: unknown[] })?.installed ?? []) as never[]);
- return list.find((p) => p.id === ref) ?? null;
+ return rules.parsePluginList(parseJsonOrNull(stdout)).find((p) => p.ref === ref) ?? null;
}
- /** Read the true installed version from the install dir's plugin.json (robust). */
+ /** Read the true installed version from the plugin manifest, falling back to the CLI's. */
private async installedVersion(
- entry: { version?: string; installPath?: string } | null
+ entry: InstalledPlugin | null,
+ rules: SwitchSetupCliRules
): Promise<string | null> {
if (!entry) return null;
- if (entry.installPath) {
+ if (entry.manifestPath) {
const manifest = await this.readJson<{ version?: string }>(
- join(entry.installPath, '.claude-plugin', 'plugin.json')
+ join(entry.manifestPath, rules.pluginManifestDir, 'plugin.json')
);
if (manifest?.version) return manifest.version;
}
@@ -174,24 +178,21 @@ class SwitchSetupService {
private async advertisedVersion(
bin: string,
marketplaceName: string,
- pluginName: string
+ pluginName: string,
+ rules: SwitchSetupCliRules
): Promise<string | null> {
const { stdout } = await this.run(bin, ['plugin', 'marketplace', 'list', '--json']);
- let markets: Array<{ name?: string; installLocation?: string }>;
- try {
- markets = JSON.parse(stdout);
- } catch {
- return null;
- }
- const market = markets.find((m) => m.name === marketplaceName);
- if (!market?.installLocation) return null;
+ const market = rules
+ .parseMarketplaceList(parseJsonOrNull(stdout))
+ .find((m) => m.name === marketplaceName && m.root !== null);
+ if (!market?.root) return null;
const manifest = await this.readJson<{ plugins?: Array<{ name?: string; source?: string }> }>(
- join(market.installLocation, '.claude-plugin', 'marketplace.json')
+ join(market.root, rules.marketplaceManifestDir, 'marketplace.json')
);
const entry = manifest?.plugins?.find((p) => p.name === pluginName);
if (!entry?.source) return null;
const pluginManifest = await this.readJson<{ version?: string }>(
- join(market.installLocation, entry.source, '.claude-plugin', 'plugin.json')
+ join(market.root, entry.source, rules.pluginManifestDir, 'plugin.json')
);
return pluginManifest?.version ?? null;
}
@@ -205,31 +206,27 @@ class SwitchSetupService {
private async ensureMarketplace(
bin: string,
marketplaceName: string,
- marketplaceSource: string
+ marketplaceSource: string,
+ rules: SwitchSetupCliRules
): Promise<void> {
const { stdout } = await this.run(bin, ['plugin', 'marketplace', 'list', '--json']);
- try {
- const markets: MarketplaceListEntry[] = JSON.parse(stdout);
- const existing = markets.find((m) => m.name === marketplaceName);
- if (existing) {
- if (marketplaceMatchesSource(existing, marketplaceSource)) return;
- log.warn('switch-setup: re-pointing marketplace to current source', {
- marketplaceName,
- from: existing.repo ?? existing.path ?? null,
- to: marketplaceSource,
- });
- const removed = await this.run(bin, ['plugin', 'marketplace', 'remove', marketplaceName]);
- if (removed.code !== 0) {
- throw new Error(
- removed.stderr.trim() || `Failed to remove stale marketplace ${marketplaceName}`
- );
- }
- }
- } catch (err) {
- if (err instanceof SyntaxError) {
- // Unparseable list output — fall through and attempt to add.
- } else {
- throw err;
+ // An unreadable listing yields no entries; the add below is idempotent, so
+ // attempting it is safer than treating an unparseable listing as fatal.
+ const existing = rules
+ .parseMarketplaceList(parseJsonOrNull(stdout))
+ .find((m) => m.name === marketplaceName);
+ if (existing) {
+ if (marketplaceMatchesSource(existing, marketplaceSource)) return;
+ log.warn('switch-setup: re-pointing marketplace to current source', {
+ marketplaceName,
+ from: existing.source,
+ to: marketplaceSource,
+ });
+ const removed = await this.run(bin, ['plugin', 'marketplace', 'remove', marketplaceName]);
+ if (removed.code !== 0) {
+ throw new Error(
+ removed.stderr.trim() || `Failed to remove stale marketplace ${marketplaceName}`
+ );
}
}
const res = await this.run(bin, ['plugin', 'marketplace', 'add', marketplaceSource]);
@@ -242,14 +239,15 @@ class SwitchSetupService {
async getStatus(agentId: string): Promise<SwitchSetupStatus> {
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
- const { descriptor, bin } = resolved;
+ const { descriptor, bin, rules } = resolved;
- const entry = await this.findInstalled(bin, resolved.ref);
- const installedVersion = await this.installedVersion(entry);
+ const entry = await this.findInstalled(bin, resolved.ref, rules);
+ const installedVersion = await this.installedVersion(entry, rules);
const latestVersion = await this.advertisedVersion(
bin,
descriptor.marketplaceName,
- descriptor.pluginName
+ descriptor.pluginName,
+ rules
);
const installed = entry !== null;
const updateAvailable =
@@ -313,16 +311,16 @@ class SwitchSetupService {
async checkForUpdates(agentId: string): Promise<SwitchSetupStatus> {
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
- const { descriptor, bin } = resolved;
+ const { descriptor, bin, rules } = resolved;
let refreshError: string | null = null;
try {
- await this.ensureMarketplace(bin, descriptor.marketplaceName, descriptor.marketplaceSource);
- const res = await this.run(bin, [
- 'plugin',
- 'marketplace',
- 'update',
+ await this.ensureMarketplace(
+ bin,
descriptor.marketplaceName,
- ]);
+ descriptor.marketplaceSource,
+ rules
+ );
+ const res = await this.run(bin, rules.marketplaceRefreshArgs(descriptor.marketplaceName));
if (res.code !== 0) {
throw new Error(
res.stderr.trim() || `Failed to update marketplace ${descriptor.marketplaceName}`
@@ -339,35 +337,82 @@ class SwitchSetupService {
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
- const { descriptor, bin, ref } = resolved;
+ const { descriptor, bin, ref, rules } = resolved;
try {
- await this.ensureMarketplace(bin, descriptor.marketplaceName, descriptor.marketplaceSource);
+ await this.ensureMarketplace(
+ bin,
+ descriptor.marketplaceName,
+ descriptor.marketplaceSource,
+ rules
+ );
} catch (err) {
return { success: false, message: await describeInstallFailure(String(err)) };
}
- const res = await this.run(bin, ['plugin', 'install', ref, '-s', descriptor.scope]);
+ const res = await this.run(bin, rules.installArgs(ref, descriptor.scope));
return res.code === 0
? { success: true }
: { success: false, message: await describeInstallFailure(res.stderr.trim()) };
}
+ /**
+ * Update the installed plugin. Dialects without a per-plugin update verb
+ * (Codex) are updated by uninstalling and reinstalling; a failed reinstall is
+ * reported as such rather than as a plain update failure, because it leaves
+ * the agent with no connector rather than with the previous version.
+ *
+ * The marketplace is repaired first, exactly as `install` does. The re-add
+ * resolves against whatever marketplace is registered, so a stale source would
+ * otherwise fail it — after the uninstall has already succeeded.
+ */
async update(agentId: string): Promise<SwitchSetupResult> {
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
- const { descriptor, bin, ref } = resolved;
- const res = await this.run(bin, ['plugin', 'update', ref, '-s', descriptor.scope]);
- return res.code === 0
+ const { descriptor, bin, ref, rules } = resolved;
+
+ try {
+ await this.ensureMarketplace(
+ bin,
+ descriptor.marketplaceName,
+ descriptor.marketplaceSource,
+ rules
+ );
+ } catch (err) {
+ return { success: false, message: `Could not add marketplace: ${String(err)}` };
+ }
+
+ const updateArgs = rules.updateArgs(ref, descriptor.scope);
+ if (updateArgs) {
+ const res = await this.run(bin, updateArgs);
+ return res.code === 0
+ ? { success: true }
+ : { success: false, message: res.stderr.trim() || 'Update failed.' };
+ }
+
+ const removed = await this.run(bin, rules.uninstallArgs(ref, descriptor.scope));
+ if (removed.code !== 0) {
+ return {
+ success: false,
+ message: removed.stderr.trim() || 'Update failed: could not remove the installed plugin.',
+ };
+ }
+ const added = await this.run(bin, rules.installArgs(ref, descriptor.scope));
+ return added.code === 0
? { success: true }
- : { success: false, message: res.stderr.trim() || 'Update failed.' };
+ : {
+ success: false,
+ message:
+ added.stderr.trim() ||
+ 'Update failed: the plugin was removed but could not be reinstalled. Install it again from Settings → Agents.',
+ };
}
async uninstall(agentId: string): Promise<SwitchSetupResult> {
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
- const { descriptor, bin, ref } = resolved;
- const res = await this.run(bin, ['plugin', 'uninstall', ref, '-s', descriptor.scope]);
+ const { descriptor, bin, ref, rules } = resolved;
+ const res = await this.run(bin, rules.uninstallArgs(ref, descriptor.scope));
return res.code === 0
? { success: true }
: { success: false, message: res.stderr.trim() || 'Uninstall failed.' };
diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.ts
index 1d6f697e9..1cdac86a1 100644
--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts
+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts
@@ -1,6 +1,7 @@
import { sql } from 'drizzle-orm';
import { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';
import { versionedJsonColumn } from '@main/db/versioned-column';
+import { agentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { sessionConfig } from '@shared/core/sessions/session-config';
import type { TerminalShellId } from '@shared/core/terminals/terminal-settings';
@@ -160,6 +161,9 @@ export const agents = sqliteTable(
// Defaults false for local agents; onboarding seeds it true for remote
// agents (see onboard-agent). Editable per agent in location settings.
autoApprove: integer('auto_approve', { mode: 'boolean' }).notNull().default(false),
+ // Per-agent, provider-specific launch config (Codex model / effort /
+ // instructions folded into the agent's Codex profile). Null when unset.
+ providerConfig: versionedJsonColumn(agentProviderConfig)('provider_config'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index 3d74d4de3..98ecbcaf5 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -41,10 +41,12 @@ import {
SelectValue,
} from '@renderer/lib/ui/select';
import { log } from '@renderer/utils/logger';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';
import { basenameFromAnyPath } from '@shared/path-name';
import { AgentAdvancedConfig } from './agent-advanced-config';
import { AgentTypePicker } from './agent-type-picker';
+import { CodexAgentConfig } from './codex-agent-config';
import { ConfigureAgentPanel } from './configure-agent-panel';
import { PickExistingPanel } from './content';
import { useConfigureAgentForm, usePickMode } from './modes';
@@ -166,6 +168,13 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
advancedAttributesRef.current = attributes;
}, []);
+ // Per-agent Codex config (model / effort / instructions), held in a ref for
+ // the same reason. Null when the user left the Codex section untouched.
+ const codexConfigRef = useRef<AgentProviderConfig | null>(null);
+ const onCodexConfigChange = useCallback((config: AgentProviderConfig | null) => {
+ codexConfigRef.current = config;
+ }, []);
+
const shouldCheckPathStatus = !isRemoteRun && pickState.path.trim().length > 0;
const pathStatusQuery = useQuery({
queryKey: ['locationPathStatus', 'local', pickState.path],
@@ -429,7 +438,8 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
if (result.kind === 'name-conflict') {
toast({
title: 'Agent name already taken',
- description: 'An agent with this name already exists on the server. Pick another name.',
+ description:
+ 'An agent with this name already exists in this directory or on the server. Pick another name.',
variant: 'destructive',
});
return;
@@ -465,6 +475,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
autoSession: form.autoSession,
autoApprove: form.autoApprove,
definitionAttributes: advancedAttributesRef.current,
+ providerConfig: codexConfigRef.current,
});
if (result.kind !== 'created') {
reportProvisionError(result);
@@ -693,6 +704,9 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
onAddServer={() => showAddServerModal({})}
/>
<AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} />
+ {pickState.providerId === 'codex' && (
+ <CodexAgentConfig onChange={onCodexConfigChange} />
+ )}
</>
)}
{switchAgent && (
@@ -734,6 +748,9 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc
onAddServer={() => showAddServerModal({})}
/>
<AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} />
+ {pickState.providerId === 'codex' && (
+ <CodexAgentConfig onChange={onCodexConfigChange} />
+ )}
</>
)}
</DialogContentArea>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
index 8b8c9263a..b2ef3c6dc 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
@@ -18,8 +18,10 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
* Picks the agent type for a new Switch agent. Only agent types that are both
* Switch-supported and have their connector plugin installed (i.e. actually
* usable) are offered; if none qualify, the user is pointed at the per-agent
- * Switch setup. The selection is auto-set to the single option when there is
- * only one, so the common case needs no extra click.
+ * Switch setup. Auto-selection is deliberately limited to the case where
+ * exactly one type is offered — there is nothing to choose, so the click is
+ * pure friction. With several connectors installed the user picks explicitly:
+ * pre-selecting one of them would silently decide which agent gets onboarded.
*/
export function AgentTypePicker({
value,
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx
new file mode 100644
index 000000000..b726c36eb
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx
@@ -0,0 +1,120 @@
+import type { RepoAgentField } from '@switchdash/core/agents/plugins';
+import { ChevronRight } from 'lucide-react';
+import { useCallback, useEffect, useState } from 'react';
+import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';
+import { cn } from '@renderer/utils/utils';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
+import {
+ attributesFromForm,
+ DefinitionFieldInput,
+ emptyForm,
+ type FormState,
+ type FormValue,
+} from '../agent-definition-fields';
+
+/**
+ * Per-agent Codex configuration for the add-agent modal. Codex has no repo-agent
+ * definition surface (so {@link AgentAdvancedConfig} renders nothing for it);
+ * instead switchdash folds these values into the agent's Codex profile at launch.
+ *
+ * Effort levels mirror `CODEX_REASONING_EFFORTS` in the codex plugin — kept small
+ * and stable there, duplicated here so the renderer needs no plugin import.
+ * Model is free text because the Codex model catalog changes over time; blank
+ * fields leave the user's base `~/.codex/config.toml` default in place.
+ */
+const CODEX_CONFIG_FIELDS: RepoAgentField[] = [
+ {
+ key: 'model',
+ label: 'Model',
+ type: 'text',
+ placeholder: 'e.g. gpt-5.6-terra — blank uses the Codex default',
+ help: 'Overrides the model for this agent only.',
+ },
+ {
+ key: 'effort',
+ label: 'Reasoning effort',
+ type: 'select',
+ options: [
+ { value: '', label: 'Default' },
+ { value: 'low', label: 'low' },
+ { value: 'medium', label: 'medium' },
+ { value: 'high', label: 'high' },
+ { value: 'xhigh', label: 'xhigh' },
+ { value: 'max', label: 'max' },
+ ],
+ },
+ {
+ key: 'instructions',
+ label: 'Instructions',
+ type: 'textarea',
+ placeholder: "A system prompt for this agent, e.g. 'You are a careful reviewer…'",
+ help: "Added to Codex's own instructions as extra developer guidance. Blank keeps Codex defaults.",
+ },
+];
+
+function toProviderConfig(state: FormState): AgentProviderConfig | null {
+ const attrs = attributesFromForm(CODEX_CONFIG_FIELDS, state);
+ const str = (value: unknown): string | undefined => {
+ const trimmed = typeof value === 'string' ? value.trim() : '';
+ return trimmed ? trimmed : undefined;
+ };
+ const model = str(attrs.model);
+ const effort = str(attrs.effort);
+ const instructions = str(attrs.instructions);
+ if (!model && !effort && !instructions) return null;
+ return { version: '1', model, effort, instructions };
+}
+
+/**
+ * Collapsed "Codex configuration" section. Reports the assembled per-agent
+ * provider config (or null when nothing is set) so the modal can pass it to
+ * `addAgent`, which persists it on the agent and folds it into the launch profile.
+ */
+export function CodexAgentConfig({
+ onChange,
+}: {
+ onChange: (config: AgentProviderConfig | null) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [state, setState] = useState<FormState>(() => emptyForm(CODEX_CONFIG_FIELDS));
+
+ useEffect(() => {
+ onChange(toProviderConfig(state));
+ }, [state, onChange]);
+
+ const setField = useCallback((key: string, value: FormValue) => {
+ setState((prev) => ({ ...prev, [key]: value }));
+ }, []);
+
+ return (
+ <div className="rounded-md border border-border">
+ <button
+ type="button"
+ className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"
+ onClick={() => setOpen((v) => !v)}
+ >
+ <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />
+ Codex configuration
+ </button>
+ {open && (
+ <div className="flex flex-col gap-4 border-t border-border px-3 py-3">
+ {CODEX_CONFIG_FIELDS.map((field) => (
+ <Field key={field.key}>
+ <FieldLabel htmlFor={`codex-config-${field.key}`}>
+ {field.label} (optional)
+ </FieldLabel>
+ <DefinitionFieldInput
+ field={field}
+ value={state[field.key] ?? ''}
+ onChange={(value) => setField(field.key, value)}
+ />
+ {field.help && (
+ <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>
+ )}
+ </Field>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts
index 42c398958..47db85faf 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/stores/location-manager.test.ts
@@ -72,6 +72,7 @@ function agent(overrides: Partial<Agent> = {}): Agent {
serverId: 'server-1',
status: null,
autoApprove: false,
+ providerConfig: null,
createdAt: '2026-05-28T00:00:00.000Z',
updatedAt: '2026-05-28T00:00:00.000Z',
...overrides,
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx
index c408a1737..c9dd55791 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx
@@ -16,6 +16,7 @@ import { Spinner } from '@renderer/lib/ui/spinner';
import { log } from '@renderer/utils/logger';
import { cn } from '@renderer/utils/utils';
import { sshConnectionEventChannel } from '@shared/core/ssh/sshEvents';
+import { updateCheckUnavailable } from '@shared/core/switch-setup/update-check';
import { GhAuthPanel } from './gh-auth-panel';
import { hostSetupQueryKey } from './query-keys';
@@ -524,12 +525,19 @@ function AgentTypeRow({
? 'partial'
: 'ready';
+ // Not "no update available": this agent type advertises no versions on a
+ // remote host, so `updateAvailable` is structurally always false and saying
+ // nothing would read as "current".
+ const currencyUnknown = plugin !== undefined && updateCheckUnavailable(plugin);
+
const pluginStepLabel =
plugin?.installed && plugin.updateAvailable
? 'Plugin · update available'
- : plugin?.installed
- ? `Plugin ${plugin.installedVersion ?? ''}`.trim()
- : 'Switch plugin';
+ : plugin?.installed && currencyUnknown
+ ? `Plugin ${plugin.installedVersion ?? ''} · updates not detectable`.trim()
+ : plugin?.installed
+ ? `Plugin ${plugin.installedVersion ?? ''}`.trim()
+ : 'Switch plugin';
const steps: Step[] = [
{
@@ -584,14 +592,18 @@ function AgentTypeRow({
{checkUpdates.isPending ? 'Checking…' : 'Check for updates'}
</Button>
)}
- {cliInstalled && plugin?.installed && plugin.updateAvailable && (
+ {cliInstalled && plugin?.installed && (plugin.updateAvailable || currencyUnknown) && (
<Button
size="sm"
variant="outline"
disabled={pending}
onClick={() => updatePlugin.mutate()}
>
- {updatePlugin.isPending ? 'Updating…' : 'Update plugin'}
+ {updatePlugin.isPending
+ ? 'Updating…'
+ : plugin.updateAvailable
+ ? 'Update plugin'
+ : 'Reinstall plugin'}
</Button>
)}
</div>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx
index 9098b3c01..2962d51d8 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/settings/agents-page/SwitchSetupCard.tsx
@@ -3,6 +3,7 @@ import { useSwitchSetup } from '@renderer/lib/stores/use-switch-setup';
import { Button } from '@renderer/lib/ui/button';
import { Field } from '@renderer/lib/ui/field';
import { Label } from '@renderer/lib/ui/label';
+import { updateCheckUnavailable } from '@shared/core/switch-setup/update-check';
import {
InstalledBadge,
InstallingBadge,
@@ -37,6 +38,8 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {
if (isLoading || !status?.supported) return null;
const busy = isInstalling || isUpdating || isUninstalling || isChecking;
+ // Distinct from "no update available": there is nothing to compare against.
+ const currencyUnknown = updateCheckUnavailable(status);
// Until the probe answers, do not disable Install — a slow check should not
// look like a blocked one.
const ghReady = !ghAuth || (ghAuth.ghInstalled && ghAuth.authenticated && ghAuth.canReadPackages);
@@ -96,6 +99,13 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {
)}
</Button>
)}
+ {/* `updateAvailable` can never go true here, so without this the
+ plugin could only be refreshed by uninstalling first. */}
+ {currencyUnknown && !status.updateAvailable && (
+ <Button size="xs" variant="outline" disabled={busy} onClick={() => update()}>
+ {isUpdating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Reinstall'}
+ </Button>
+ )}
<Button size="xs" variant="ghost" disabled={busy} onClick={() => uninstall()}>
{isUninstalling ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : 'Uninstall'}
</Button>
@@ -108,6 +118,12 @@ export function SwitchSetupCard({ agentId }: { agentId: string }) {
Couldn't refresh the plugin marketplace — showing cached status. {status.refreshError}
</p>
)}
+ {currencyUnknown && !status.refreshError && (
+ <p className="text-xs text-foreground-warning">
+ This agent type doesn't report plugin versions here, so switchdash can't tell whether an
+ update exists. Reinstall to be sure you are on the latest.
+ </p>
+ )}
{!status.installed && !ghReady && (
<p className="text-xs text-foreground-muted">
The plugin is published to a private GitHub repository. Authenticate above to install
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/use-switch-setup.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/use-switch-setup.ts
index 95a64a6ba..ebc75c2cf 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/use-switch-setup.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/use-switch-setup.ts
@@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
+import { updateCheckUnavailable } from '@shared/core/switch-setup/update-check';
function switchSetupQueryKey(agentId: string) {
return ['switch-setup', agentId] as const;
@@ -49,6 +50,13 @@ export function useSwitchSetup(agentId: string) {
description: status.refreshError,
variant: 'destructive',
});
+ } else if (updateCheckUnavailable(status)) {
+ // No advertised version to compare against, so the refresh proved
+ // nothing. Saying "up to date" here would assert what was not checked.
+ toast({
+ title: 'Could not determine whether an update exists',
+ description: 'This agent type does not report plugin versions on a remote host.',
+ });
} else if (status.supported && status.installed && !status.updateAvailable) {
toast({ title: 'Switch connector is up to date' });
}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.test.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.test.ts
new file mode 100644
index 000000000..97876ed17
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { agentProviderConfig, toSwitchSpecialization } from './agent-provider-config';
+
+describe('agentProviderConfig schema', () => {
+ it('parses a versioned config and rejects an unversioned one', () => {
+ const ok = agentProviderConfig.safeParse({ version: '1', model: 'gpt-5.6-terra' });
+ expect(ok).toEqual({ status: 'ok', data: { version: '1', model: 'gpt-5.6-terra' } });
+
+ expect(agentProviderConfig.safeParse({ model: 'x' }).status).not.toBe('ok');
+ });
+});
+
+describe('toSwitchSpecialization', () => {
+ it('maps effort → reasoningEffort and passes model/instructions through', () => {
+ expect(
+ toSwitchSpecialization({
+ version: '1',
+ model: 'o3',
+ effort: 'high',
+ instructions: 'be terse',
+ })
+ ).toEqual({ model: 'o3', reasoningEffort: 'high', instructions: 'be terse' });
+ });
+
+ it('drops empty/whitespace fields so the base default stands', () => {
+ expect(
+ toSwitchSpecialization({ version: '1', model: ' ', effort: '', instructions: 'x' })
+ ).toEqual({ model: undefined, reasoningEffort: undefined, instructions: 'x' });
+ });
+
+ it('returns undefined when nothing is set or the config is absent', () => {
+ expect(toSwitchSpecialization(null)).toBeUndefined();
+ expect(toSwitchSpecialization(undefined)).toBeUndefined();
+ expect(toSwitchSpecialization({ version: '1' })).toBeUndefined();
+ expect(toSwitchSpecialization({ version: '1', model: ' ' })).toBeUndefined();
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.ts
new file mode 100644
index 000000000..8c4366190
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agent-provider-config.ts
@@ -0,0 +1,57 @@
+import type { SwitchLaunchSpecialization } from '@switchdash/core/agents/plugins';
+import z from 'zod';
+import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';
+
+/**
+ * Per-agent, provider-specific launch configuration. Today this carries the
+ * Codex specialization folded into the agent's Codex profile at launch — model,
+ * reasoning effort, and a system-prompt/instructions body. Every field is
+ * optional; an unset field leaves the provider/base-config default in place.
+ *
+ * Stored as a versioned JSON column on the agent so the shape can evolve without
+ * a migration per field, mirroring `sessions.config`.
+ */
+const agentProviderConfigV1 = z.object({
+ version: z.literal('1'),
+ /** Provider model id, e.g. a Codex `model` override. */
+ model: z.string().optional(),
+ /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` value. */
+ effort: z.string().optional(),
+ /** System-prompt/instructions body, carried in the agent's Codex profile as
+ * `developer_instructions` — additive to Codex's own instructions. */
+ instructions: z.string().optional(),
+});
+
+export const agentProviderConfig = defineVersionedSchema()
+ .initial('1', agentProviderConfigV1)
+ .build();
+
+export type AgentProviderConfig = typeof agentProviderConfig.Type;
+
+/**
+ * Map stored per-agent config to the launch-time specialization the profile
+ * builder consumes. `effort` becomes `reasoningEffort`; empty/whitespace values
+ * are dropped so the profile omits them and the base default stands. Returns
+ * `undefined` when nothing is set, so callers pass no specialization at all.
+ */
+export function toSwitchSpecialization(
+ config: AgentProviderConfig | null | undefined
+): SwitchLaunchSpecialization | undefined {
+ if (!config) return undefined;
+
+ const clean = (value: string | undefined): string | undefined => {
+ const trimmed = value?.trim();
+ return trimmed ? trimmed : undefined;
+ };
+
+ const specialization: SwitchLaunchSpecialization = {
+ model: clean(config.model),
+ reasoningEffort: clean(config.effort),
+ instructions: clean(config.instructions),
+ };
+
+ if (!specialization.model && !specialization.reasoningEffort && !specialization.instructions) {
+ return undefined;
+ }
+ return specialization;
+}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts
index 63d980a2c..d0af134d2 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/agents/agents.ts
@@ -1,3 +1,4 @@
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
/**
@@ -25,6 +26,9 @@ export type Agent = {
* "bypass permissions" flag. Defaults false for local agents and true for
* remote agents (seeded at onboarding); editable per agent. */
autoApprove: boolean;
+ /** Per-agent, provider-specific launch config (e.g. Codex model / effort /
+ * instructions). Null when unset. */
+ providerConfig: AgentProviderConfig | null;
createdAt: string;
updatedAt: string;
};
@@ -43,6 +47,8 @@ export type CreateAgentParams = {
/** Seed for the per-agent bypass-permissions flag: false for local agents,
* true for remote agents. */
autoApprove: boolean;
+ /** Optional per-agent provider config set at creation. */
+ providerConfig?: AgentProviderConfig | null;
};
export type RenameAgentParams = {
diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
index 472eacf9b..31bb74a79 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
@@ -94,6 +94,13 @@ export type AgentProviderDefinition = {
supportsHooks?: boolean;
};
+/**
+ * Provider ids and display metadata, plus a mirror of each provider's argv shape.
+ *
+ * The argv fields here are descriptive, not authoritative: nothing reads them at
+ * spawn time. `packages/plugins/src/agents/impl/<id>/index.ts` builds the real
+ * command, so change the plugin first and update the mirror to match.
+ */
export const AGENT_PROVIDERS: AgentProviderDefinition[] = [
{
id: 'codex',
@@ -105,13 +112,12 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [
commands: ['codex'],
versionArgs: ['--version'],
cli: 'codex',
- // `--dangerously-bypass-hook-trust` lets Codex run switchdash's own hooks (notably the
- // SessionStart hook that reports the rollout session id) without an interactive trust
- // prompt. Automations always auto-approve and can't answer that prompt, so without this
- // the session id is never captured and resume falls back to `codex resume --last`,
- // reattaching the globally-most-recent Codex session instead of this one.
- autoApproveFlag:
- '-c approval_policy="never" -c sandbox_mode="danger-full-access" --dangerously-bypass-hook-trust',
+ // Hook trust is a default arg, not an auto-approve one: Codex skips any hook
+ // it has no persisted trust entry for, and switchdash's status signals and
+ // rollout-id capture are hooks. Kept in sync with the plugin by the parity
+ // test in src/main/core/providers/provider-argv-parity.test.ts.
+ defaultArgs: ['--dangerously-bypass-hook-trust'],
+ autoApproveFlag: '-c approval_policy="never"',
initialPromptFlag: '',
resumeFlag: 'resume',
sessionIdFlag: ' ',
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts
new file mode 100644
index 000000000..9fbd41d13
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts
@@ -0,0 +1,122 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { NPM_TOKEN_VAR } from '@shared/core/npm-registry';
+import {
+ SWITCH_AGENT_RUNTIME_PACKAGE,
+ SWITCH_AGENT_RUNTIME_VERSION,
+ SWITCH_RUNTIME_ENV_VARS,
+ SWITCH_RUNTIME_OPTIONAL_ENV,
+ SWITCH_RUNTIME_REQUIRED_ENV,
+ switchAgentRuntimeCommand,
+} from './switch-agent-runtime';
+
+const MCP_JSON_RELATIVE = 'connectors/claude-code-plugin/.mcp.json';
+
+/** Walk up from this file until the connector plugin's .mcp.json is found. */
+function findClaudeMcpJson(): string {
+ let dir = dirname(fileURLToPath(import.meta.url));
+ for (let i = 0; i < 12; i++) {
+ const candidate = join(dir, MCP_JSON_RELATIVE);
+ if (existsSync(candidate)) return candidate;
+ const parent = dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ throw new Error(`could not locate ${MCP_JSON_RELATIVE} above ${fileURLToPath(import.meta.url)}`);
+}
+
+/** The `switch` server entry from the Claude connector's bundled .mcp.json. */
+function claudeSwitchServer(): { args?: string[]; env?: Record<string, string> } {
+ const mcp = JSON.parse(readFileSync(findClaudeMcpJson(), 'utf8')) as {
+ mcpServers: Record<string, { args?: string[]; env?: Record<string, string> }>;
+ };
+ return mcp.mcpServers.switch ?? {};
+}
+
+/** The runtime package's own version, the third pin nothing else checks. */
+function runtimePackageVersion(): string {
+ let dir = dirname(fileURLToPath(import.meta.url));
+ for (let i = 0; i < 12; i++) {
+ const candidate = join(dir, 'dash/packages/switch-agent-runtime/package.json');
+ if (existsSync(candidate)) {
+ return (JSON.parse(readFileSync(candidate, 'utf8')) as { version: string }).version;
+ }
+ const parent = dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ throw new Error('could not locate packages/switch-agent-runtime/package.json');
+}
+
+describe('switchAgentRuntimeCommand', () => {
+ it('resolves npx against the pinned package version', () => {
+ const { command, args } = switchAgentRuntimeCommand();
+ expect(command).toBe('npx');
+ expect(args).toEqual(['-y', `${SWITCH_AGENT_RUNTIME_PACKAGE}@${SWITCH_AGENT_RUNTIME_VERSION}`]);
+ });
+
+ it('forwards what npx itself needs to reach the private registry', () => {
+ // Without these the child cannot fetch the package at all on a cold cache,
+ // and the failure reads as a 404 for something that does not exist.
+ expect(switchAgentRuntimeCommand().envVars).toEqual(
+ expect.arrayContaining(['npm_config_userconfig', NPM_TOKEN_VAR])
+ );
+ });
+
+ it('stays pinned to the same runtime version the Claude connector .mcp.json registers', () => {
+ // Codex registers this runtime via a profile and Claude via its bundled
+ // .mcp.json. Both must run the same published version; this guards the two
+ // pins from drifting when only one is bumped.
+ const args = claudeSwitchServer().args ?? [];
+ expect(args).toContain(`${SWITCH_AGENT_RUNTIME_PACKAGE}@${SWITCH_AGENT_RUNTIME_VERSION}`);
+ });
+
+ it('never pins a version ahead of the one the package declares', () => {
+ // The third pin AGENTS.md names. Not an equality: the package version may
+ // run ahead while a release is prepared, and the pin must keep naming a
+ // published version until then — pinning ahead points every session at
+ // something the registry does not have. Behind is staged; ahead is broken.
+ const pinned = SWITCH_AGENT_RUNTIME_VERSION.split('.').map(Number);
+ const declared = runtimePackageVersion().split('.').map(Number);
+ expect(pinned.length).toBe(3);
+ for (let i = 0; i < 3; i++) {
+ if (pinned[i]! !== declared[i]!) {
+ expect(pinned[i]!).toBeLessThan(declared[i]!);
+ return;
+ }
+ }
+ });
+});
+
+describe('the credentials the runtime needs', () => {
+ it('are declared identically by the Claude connector and this module', () => {
+ // Both hosts must route the same required credentials; neither side may add
+ // one without the other, or that host's sessions start without it.
+ const declared = Object.keys(claudeSwitchServer().env ?? {}).sort();
+ expect(declared).toEqual([...SWITCH_RUNTIME_REQUIRED_ENV].sort());
+ });
+
+ it('are expanded by the Claude connector under their own names', () => {
+ // Catches a transposed pair — ${SWITCH_API_TOKEN} filed under
+ // SWITCH_API_ENDPOINT — which no other assertion here would see.
+ for (const [name, value] of Object.entries(claudeSwitchServer().env ?? {})) {
+ expect(value).toBe(`\${${name}}`);
+ }
+ });
+
+ it('keep the optional ones out of the Claude connector, where declaring is requiring', () => {
+ // Claude expands ${VAR} and fails the whole server when one resolves to
+ // nothing, so an optional variable declared there costs every standalone
+ // session its tools. Codex forwards names, so an unset one is just skipped.
+ const declared = Object.keys(claudeSwitchServer().env ?? {});
+ for (const name of SWITCH_RUNTIME_OPTIONAL_ENV) {
+ expect(declared).not.toContain(name);
+ }
+ });
+
+ it('are all routed by the Codex launch command', () => {
+ expect(switchAgentRuntimeCommand().envVars).toEqual([...SWITCH_RUNTIME_ENV_VARS]);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts
new file mode 100644
index 000000000..f2a9d474e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts
@@ -0,0 +1,88 @@
+/**
+ * The published Switch agent-runtime package that serves the Switch MCP tools
+ * over local stdio (transport to switch-core is HTTP+SSE, held inside the
+ * runtime). The Claude Code connector plugin registers it from its bundled
+ * `.mcp.json`; providers whose plugin cannot expand variables in a bundled
+ * config — Codex — have switchdash register the same package itself at launch.
+ *
+ * Lives in `shared` so both halves of the remote path can reach it: the main
+ * process bakes the launch recipe, and the on-VM sidecar (bundled free of
+ * Electron and the database) spawns from it.
+ */
+
+import { NPM_TOKEN_VAR } from '@shared/core/npm-registry';
+
+/** npm package name of the local Switch MCP runtime. */
+export const SWITCH_AGENT_RUNTIME_PACKAGE = '@sandbox-quantum/switch-agent-runtime';
+
+/**
+ * Exact version the runtime is pinned to. Must match the pin in
+ * `connectors/claude-code-plugin/.mcp.json`; `switch-agent-runtime.test.ts`
+ * fails if the two drift. Bump both together when the runtime is republished.
+ */
+export const SWITCH_AGENT_RUNTIME_VERSION = '0.1.3';
+
+/**
+ * Credentials the runtime refuses to start without: it reads all three at
+ * `bin.ts` module scope and exits before answering `initialize` if any is
+ * missing, which a host reports only as a closed connection.
+ *
+ * This tier is the contract with the Claude Code connector, whose `.mcp.json`
+ * declares the same three for `${VAR}` expansion.
+ */
+export const SWITCH_RUNTIME_REQUIRED_ENV = [
+ 'SWITCH_API_ENDPOINT',
+ 'SWITCH_API_TOKEN',
+ 'SWITCH_AGENT_ID',
+] as const;
+
+/**
+ * Values the runtime uses when present and does without when absent — the
+ * connection id and poll suppression it reads directly, plus the npm settings
+ * `npx` needs to resolve the package from the private registry.
+ *
+ * Kept apart from the required tier because the two hosts cannot treat them
+ * alike. Codex forwards names, so an unset one is simply not passed. Claude
+ * expands `${VAR}`, which makes a declared variable mandatory — declaring
+ * `SWITCH_CONNECTION_ID` there once cost every standalone session its tools.
+ * These must therefore never be added to the connector's `.mcp.json`.
+ */
+export const SWITCH_RUNTIME_OPTIONAL_ENV = [
+ 'SWITCH_CONNECTION_ID',
+ 'SWITCH_CHANNEL_DISABLE_POLL',
+ 'npm_config_userconfig',
+ NPM_TOKEN_VAR,
+] as const;
+
+/** Every variable a host must route to the runtime, required tier first. */
+export const SWITCH_RUNTIME_ENV_VARS: readonly string[] = [
+ ...SWITCH_RUNTIME_REQUIRED_ENV,
+ ...SWITCH_RUNTIME_OPTIONAL_ENV,
+];
+
+/** stdio command that launches the runtime with `npx`, resolving the pinned version. */
+export type SwitchAgentRuntimeCommand = {
+ command: string;
+ args: string[];
+ /** Names the host must route into the server's process. See {@link SWITCH_RUNTIME_ENV_VARS}. */
+ envVars: string[];
+};
+
+/**
+ * The stdio command that runs the pinned Switch MCP runtime, and the names of
+ * the variables it needs.
+ *
+ * A host does not hand its own environment to an MCP server it spawns. Codex
+ * gives the child a fixed allowlist — `HOME`, `PATH`, `SHELL`, `USER`, `TMPDIR`
+ * and a few more — and forwards nothing else unless the server's config names
+ * it; Claude Code declares its own `env` block. So the command stays static and
+ * secret-free, while `envVars` says what has to travel with it: without them
+ * `npx` cannot reach the private registry and the runtime cannot authenticate.
+ */
+export function switchAgentRuntimeCommand(): SwitchAgentRuntimeCommand {
+ return {
+ command: 'npx',
+ args: ['-y', `${SWITCH_AGENT_RUNTIME_PACKAGE}@${SWITCH_AGENT_RUNTIME_VERSION}`],
+ envVars: [...SWITCH_RUNTIME_ENV_VARS],
+ };
+}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.test.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.test.ts
new file mode 100644
index 000000000..053131672
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { updateCheckUnavailable } from './update-check';
+
+const base = { supported: true, installed: true, latestVersion: '0.2.0' };
+
+describe('updateCheckUnavailable', () => {
+ it('is true when there is no advertised version to compare against', () => {
+ // Codex on a remote host: its marketplace listing carries no plugin
+ // versions, so `updateAvailable: false` means "unknown", not "current".
+ expect(updateCheckUnavailable({ ...base, latestVersion: null })).toBe(true);
+ });
+
+ it('is false when a version is advertised, update or no update', () => {
+ expect(updateCheckUnavailable(base)).toBe(false);
+ });
+
+ it('is false before the plugin is installed — nothing to be stale yet', () => {
+ expect(updateCheckUnavailable({ ...base, installed: false, latestVersion: null })).toBe(false);
+ });
+
+ it('is false for an agent type with no Switch setup at all', () => {
+ expect(updateCheckUnavailable({ ...base, supported: false, latestVersion: null })).toBe(false);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.ts
new file mode 100644
index 000000000..b81b4dc10
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-setup/update-check.ts
@@ -0,0 +1,21 @@
+/**
+ * Whether the installed connector plugin's currency is *unknowable*, as opposed
+ * to current.
+ *
+ * `updateAvailable: false` conflates the two: it is what you get both when the
+ * advertised version is older-or-equal and when there is no advertised version
+ * to compare against at all. The second case is real — Codex's marketplace
+ * listing carries no plugin versions, so the remote driver has nothing to read —
+ * and a caller that renders it as "up to date" asserts something it never
+ * checked. Branch on this to disclose the difference instead.
+ *
+ * Structural parameter rather than the main-process `SwitchSetupStatus`, so the
+ * renderer can share the one definition.
+ */
+export function updateCheckUnavailable(status: {
+ supported: boolean;
+ installed: boolean;
+ latestVersion: string | null;
+}): boolean {
+ return status.supported && status.installed && status.latestVersion === null;
+}
diff --git a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
index c26ab5ff8..9b490c380 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
@@ -48,14 +48,21 @@ describe('materializeAgentCommand', () => {
expect(cmd.env).toEqual({ BASE: '1', SHARED: 'override', HOOK: 'x' });
});
- it('throws when the session-id token is missing', () => {
- expect(() =>
- materializeAgentCommand(spec({ args: [INITIAL_PROMPT_PLACEHOLDER] }), {
+ it('launches a provider that takes no session id on a fresh session', () => {
+ // Codex mints its own rollout id and only accepts one when resuming, so its
+ // spec carries no session-id token. switchdash correlates the spawn through
+ // the pty id in the hook env, not through argv. The Switch MCP server rides a
+ // baked profile (launchFiles) and env, not argv, so nothing to substitute.
+ const cmd = materializeAgentCommand(
+ spec({ args: ['--profile', 'codex-hoot', INITIAL_PROMPT_PLACEHOLDER] }),
+ {
sessionId: 'c',
- initialPrompt: 'p',
+ initialPrompt: 'connect to switch room room-x',
extraEnv: {},
- })
- ).toThrow(SESSION_ID_PLACEHOLDER);
+ }
+ );
+
+ expect(cmd.args).toEqual(['--profile', 'codex-hoot', 'connect to switch room room-x']);
});
it('throws when the initial-prompt token is missing', () => {
@@ -67,4 +74,17 @@ describe('materializeAgentCommand', () => {
})
).toThrow(INITIAL_PROMPT_PLACEHOLDER);
});
+
+ it('refuses to launch with an unsubstituted placeholder rather than pointing at literal text', () => {
+ expect(() =>
+ materializeAgentCommand(
+ spec({ args: ['--session-id', '__SWITCHDASH_ROGUE__', INITIAL_PROMPT_PLACEHOLDER] }),
+ {
+ sessionId: 's1',
+ initialPrompt: 'p',
+ extraEnv: {},
+ }
+ )
+ ).toThrow(/unsubstituted placeholder/);
+ });
});
diff --git a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
index 68a9716a0..8429b2352 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
@@ -1,3 +1,17 @@
+/**
+ * A config file the sidecar must write on the VM before spawning, path relative
+ * to the agent's home directory. Baked into the spec because the watcher is
+ * provider-agnostic — it cannot build provider config itself, so switchdash
+ * precomputes it. Used for Codex's per-agent profile registering the Switch MCP
+ * runtime (`~/.codex/<slug>.config.toml`).
+ */
+export interface AgentLaunchFile {
+ /** Path relative to the agent's home directory on the VM. */
+ homeRelativePath: string;
+ /** Full file content to write. */
+ content: string;
+}
+
/**
* A serialised recipe for launching a fresh agent CLI session on the VM.
*
@@ -14,15 +28,20 @@ export interface AgentLaunchSpec {
/** Executable to run (absolute path resolved on the host at deploy time). */
command: string;
/**
- * Argv for a fresh session. Exactly one element equals
- * {@link SESSION_ID_PLACEHOLDER} and one equals {@link INITIAL_PROMPT_PLACEHOLDER};
- * the watcher swaps those for the real values per spawn.
+ * Argv for a fresh session. One element equals {@link INITIAL_PROMPT_PLACEHOLDER};
+ * the watcher swaps it for the real prompt per spawn. {@link SESSION_ID_PLACEHOLDER}
+ * appears only for providers that take it on argv, and is substituted when present.
*/
args: string[];
/** Base provider env (custom env + provider env); the per-spawn hook env is merged on top. */
env: Record<string, string>;
/** Absolute remote working dir the agent runs in (the agent's repo dir). */
cwd: string;
+ /**
+ * Home-relative config files the sidecar writes before spawning, e.g. Codex's
+ * per-agent profile. Static across spawns, so the watcher writes them verbatim.
+ */
+ launchFiles?: AgentLaunchFile[];
providerId: string;
deeplinkScheme: string;
}
@@ -33,6 +52,9 @@ export const SESSION_ID_PLACEHOLDER = '__SWITCHDASH_SESSION_ID__';
/** Argv token switchdash emits in place of the fresh session's initial prompt. */
export const INITIAL_PROMPT_PLACEHOLDER = '__SWITCHDASH_INITIAL_PROMPT__';
+/** Shared prefix of every launch-spec placeholder, used to catch leftovers. */
+const PLACEHOLDER_PREFIX = '__SWITCHDASH_';
+
export interface MaterializedAgentCommand {
command: string;
args: string[];
@@ -41,28 +63,49 @@ export interface MaterializedAgentCommand {
/**
* Resolve a launch spec into a concrete command for one spawn by substituting
- * the session id and initial prompt into the placeholder argv elements and
- * merging the per-spawn env (hook env) over the base env.
+ * the session id and initial prompt into the spec's argv, and merging the
+ * per-spawn env (hook env) over the base env.
*
- * Throws if either placeholder is missing from the spec's argv — a spec that
- * cannot carry the session id or prompt would silently spawn a session
- * that never connects to the room, so we fail loud instead.
+ * Throws if the prompt placeholder is missing: the prompt is what tells the
+ * agent which room to connect to, so a spec that cannot carry it would spawn a
+ * session that just sits there.
+ *
+ * The session id token is substituted when present and is not required. Not
+ * every provider takes a session id on a fresh session — Codex mints its own
+ * rollout id and only accepts one when resuming — and switchdash does not depend
+ * on the argv value either way: it correlates the spawn through the pty id in the
+ * hook env, and learns the provider's own id from the SessionStart hook. The
+ * Switch MCP server no longer rides argv; the runtime reads its endpoint and
+ * credentials from the env, and Codex loads it from a baked profile
+ * ({@link AgentLaunchSpec.launchFiles}).
+ *
+ * Throws if any `__SWITCHDASH_` token survives substitution, so a provider that
+ * grows a new placeholder cannot quietly launch an agent pointed at literal
+ * placeholder text.
*/
export function materializeAgentCommand(
spec: AgentLaunchSpec,
- params: { sessionId: string; initialPrompt: string; extraEnv: Record<string, string> }
+ params: {
+ sessionId: string;
+ initialPrompt: string;
+ extraEnv: Record<string, string>;
+ }
): MaterializedAgentCommand {
const substitutions: Record<string, string> = {
[SESSION_ID_PLACEHOLDER]: params.sessionId,
[INITIAL_PROMPT_PLACEHOLDER]: params.initialPrompt,
};
- for (const placeholder of [SESSION_ID_PLACEHOLDER, INITIAL_PROMPT_PLACEHOLDER]) {
- if (!spec.args.includes(placeholder)) {
- throw new Error(`agent launch spec is missing the ${placeholder} argv token`);
- }
+ if (!spec.args.includes(INITIAL_PROMPT_PLACEHOLDER)) {
+ throw new Error(`agent launch spec is missing the ${INITIAL_PROMPT_PLACEHOLDER} argv token`);
}
const args = spec.args.map((arg) => substitutions[arg] ?? arg);
+
+ const unresolved = args.find((arg) => arg.includes(PLACEHOLDER_PREFIX));
+ if (unresolved !== undefined) {
+ throw new Error(`agent launch spec has an unsubstituted placeholder in argv: ${unresolved}`);
+ }
+
return { command: spec.command, args, env: { ...spec.env, ...params.extraEnv } };
}
diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.ts
index 5105fdad0..78e4560a8 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts
@@ -232,6 +232,14 @@ async function main(): Promise<void> {
for (const s of runtime.connectedSessions()) byId.set(s.sessionId, s.roomId);
return [...byId].map(([sessionId, roomId]) => ({ sessionId, roomId }));
},
+ // switchdash is about to start a session over SSH: open its room
+ // connection here first and hand back the id, so the session's tool calls
+ // land on the connection this sidecar reads and injects from. Without it
+ // the session holds a connection nobody on the VM is listening to, and
+ // never learns which room it is in. No room yet — the agent's
+ // connect_to_room claims one and the server reports it back.
+ connectionHandler: (sessionId, providerId) =>
+ runtime.ensureForSession(sessionId, providerId, null),
// switchdash deleted a session: stop its room connection (ends the renew
// heartbeat keeping the agent live) and forget any watcher-launched entry.
// A deliberate delete/kill (terminated) is also broadcast to every attached
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
index 9ac6dbbe2..9a2f2aea9 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
@@ -1,4 +1,8 @@
-import { describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { parse as parseTOML } from 'smol-toml';
+import { afterAll, describe, expect, it, vi } from 'vitest';
import {
type AgentLaunchSpec,
INITIAL_PROMPT_PLACEHOLDER,
@@ -6,8 +10,32 @@ import {
} from './agent-launch-spec';
import { InProcessSessionSpawner, type InProcessSessionSpawnerDeps } from './session-spawner';
+/** Swap in a stand-in provider for one test; null falls through to the real one. */
+const pluginOverride = vi.hoisted(() => ({ current: null as unknown }));
+
+vi.mock('@main/core/providers/plugin-registry', async () => {
+ const { pluginRegistry } = await import('@switchdash/plugins/agents');
+ return { getPlugin: (id: string) => pluginOverride.current ?? pluginRegistry.get(id) };
+});
+
const silentLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+// A launch writes real files: the provider's hooks under the session's working
+// dir or the home, and any baked launch files under the home. Both point at
+// throwaway directories so a test run does not rewrite the developer's own
+// ~/.codex or fail trying to create the VM's paths.
+const CWD = await mkdtemp(join(tmpdir(), 'session-spawner-cwd-'));
+const HOME = await mkdtemp(join(tmpdir(), 'session-spawner-home-'));
+const realHome = process.env.HOME;
+process.env.HOME = HOME;
+
+afterAll(async () => {
+ if (realHome === undefined) delete process.env.HOME;
+ else process.env.HOME = realHome;
+ await rm(CWD, { recursive: true, force: true });
+ await rm(HOME, { recursive: true, force: true });
+});
+
const SPEC: AgentLaunchSpec = {
command: '/usr/bin/claude',
args: [
@@ -17,7 +45,7 @@ const SPEC: AgentLaunchSpec = {
INITIAL_PROMPT_PLACEHOLDER,
],
env: { BASE: '1' },
- cwd: '/home/agent/repo',
+ cwd: CWD,
providerId: 'claude',
deeplinkScheme: 'switchdash',
};
@@ -68,6 +96,75 @@ describe('InProcessSessionSpawner.launch', () => {
expect(inner).not.toContain(INITIAL_PROMPT_PLACEHOLDER);
});
+ it('gives the pane every credential the baked Codex profile forwards', async () => {
+ // The sidecar writes the profile but the pane supplies the values it names.
+ // Codex reads them from its own environment and forwards them onward, so a
+ // name the profile lists and the pane lacks reaches the runtime as nothing.
+ const profile = [
+ '[mcp_servers.switch]',
+ 'command = "npx"',
+ 'env_vars = ["SWITCH_API_ENDPOINT", "SWITCH_API_TOKEN", "SWITCH_AGENT_ID"]',
+ '',
+ ].join('\n');
+ const { spawner, calls } = makeSpawner({
+ spec: {
+ ...SPEC,
+ launchFiles: [{ homeRelativePath: '.codex/codex-hoot.config.toml', content: profile }],
+ },
+ });
+
+ await spawner.launch('room-x');
+
+ const inner = calls.find((c) => c.args[0] === 'new-session')!.args.at(-1)!;
+ const names = (parseTOML(profile) as { mcp_servers: Record<string, { env_vars: string[] }> })
+ .mcp_servers.switch.env_vars;
+ for (const name of names) {
+ expect(inner).toContain(`${name}=`);
+ }
+ expect(await readFile(join(HOME, '.codex/codex-hoot.config.toml'), 'utf8')).toBe(profile);
+ });
+
+ // The pane is launched pointing at this sidecar's hook server, but nothing
+ // posts to it unless the provider's own config registers the hook commands —
+ // and Codex keeps that config in the home, not the working dir. Without it the
+ // auto-started session never reports that it stopped, so the room it was
+ // spawned to answer shows it working forever.
+ it("writes a global-scope provider's hooks under the home before the pane starts", async () => {
+ const { spawner, calls } = makeSpawner({ spec: { ...SPEC, providerId: 'codex' } });
+
+ await spawner.launch('room-x');
+
+ const config = JSON.parse(await readFile(join(HOME, '.codex/hooks.json'), 'utf8')) as {
+ hooks: Record<string, unknown[]>;
+ };
+ expect(Object.keys(config.hooks).sort()).toEqual(['PermissionRequest', 'SessionStart', 'Stop']);
+ expect(calls.find((c) => c.args[0] === 'new-session')).toBeDefined();
+ });
+
+ it("writes a workspace-scoped provider's hooks under the session's working dir", async () => {
+ const { spawner } = makeSpawner();
+
+ await spawner.launch('room-x');
+
+ expect(await readFile(join(CWD, '.claude/settings.local.json'), 'utf8')).toContain('hooks');
+ });
+
+ // Neither root fits a scope this path has not been taught, and a session
+ // spawned with no hooks looks fine right up until nobody can tell it is done.
+ it('refuses to spawn a session whose hook scope has no root here', async () => {
+ pluginOverride.current = {
+ capabilities: { hooks: { kind: 'config', scope: 'user-profile', supportedEvents: [] } },
+ behavior: { hooks: { writeHooks: vi.fn(async () => []) } },
+ };
+ try {
+ const { spawner, calls } = makeSpawner();
+ await expect(spawner.launch('room-x')).rejects.toThrow(/no hook root for scope/);
+ expect(calls.find((c) => c.args[0] === 'new-session')).toBeUndefined();
+ } finally {
+ pluginOverride.current = null;
+ }
+ });
+
it('reports a launched-but-not-yet-connected room live while its pane is up', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
await spawner.launch('room-x');
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
index 39a324d60..05843e4b9 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
@@ -1,10 +1,16 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
+import { mkdir } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
+import { createPluginFs } from '@main/core/providers/plugin-fs';
+import { getPlugin } from '@main/core/providers/plugin-registry';
import { quoteShellArg } from '@main/utils/shellEscape';
import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';
import { makePtyId } from '@shared/core/pty/ptyId';
import { type AgentLaunchSpec, materializeAgentCommand } from './agent-launch-spec';
+import { atomicWriteFile } from './atomic-file';
import type { SessionSpawner, WatcherLogger } from './notification-watcher';
import { makeAgentTmuxSessionName } from './vm-tmux';
@@ -176,6 +182,8 @@ export class InProcessSessionSpawner implements SessionSpawner {
extraEnv: hookEnv,
});
+ await this.writeLaunchFiles();
+ await this.installHooks();
await this.startDetachedTmux(tmuxTarget, spec.cwd, command.env, command.command, command.args);
this.launched.set(roomId, { sessionId, tmuxTarget });
log.info('InProcessSessionSpawner: launched session for room', {
@@ -185,6 +193,55 @@ export class InProcessSessionSpawner implements SessionSpawner {
});
}
+ /**
+ * Write the spec's baked config files (e.g. Codex's Switch profile) under the
+ * VM home before spawning. Static across spawns and safe to rewrite, so this
+ * runs every launch rather than tracking whether it already ran.
+ */
+ private async writeLaunchFiles(): Promise<void> {
+ for (const file of this.spec.launchFiles ?? []) {
+ const absPath = join(homedir(), file.homeRelativePath);
+ await mkdir(dirname(absPath), { recursive: true });
+ await atomicWriteFile(absPath, file.content);
+ }
+ }
+
+ /**
+ * Install the provider's agent hooks on this VM before spawning, mirroring
+ * what the desktop does for a session it starts itself. The pane is launched
+ * with `SWITCHDASH_HOOK_*` pointing at this sidecar, but nothing posts to it
+ * unless the provider's own config registers the hook commands — and without
+ * them the session never reports that it has stopped, so the room it was
+ * spawned to answer shows it working forever. Idempotent, so it runs per
+ * launch rather than being tracked. Throws: the watcher retries a failed
+ * launch and reports it in the room, which beats a session that comes up deaf.
+ */
+ private async installHooks(): Promise<void> {
+ const providerId = this.spec.providerId;
+ const plugin = getPlugin(providerId);
+ const hooks = plugin.capabilities.hooks;
+ if (hooks.kind === 'none') return;
+ if (hooks.kind !== 'config' || !plugin.behavior.hooks) {
+ this.deps.log.error('InProcessSessionSpawner: provider hooks cannot be installed here', {
+ providerId,
+ kind: hooks.kind,
+ });
+ return;
+ }
+ if (hooks.scope !== 'global' && hooks.scope !== 'workspace') {
+ throw new Error(
+ `InProcessSessionSpawner: no hook root for scope '${String(hooks.scope)}' — the session ` +
+ 'would run with no hooks and never report that it has stopped'
+ );
+ }
+ const root = hooks.scope === 'global' ? homedir() : this.spec.cwd;
+ await plugin.behavior.hooks.writeHooks(createPluginFs(root), []);
+ this.deps.log.info('InProcessSessionSpawner: installed agent hooks', {
+ providerId,
+ scope: hooks.scope,
+ });
+ }
+
/** Launch a command in a fresh detached tmux session with env set on the process. */
private async startDetachedTmux(
sessionName: string,
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
index 5b6bdb012..43a54c162 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -112,6 +112,20 @@ describe('SidecarRuntime (multi-session)', () => {
expect(created[0].deps.roomId).toBe('room-1');
});
+ // What `/connection` answers switchdash with. The returned id has to be the
+ // one the connection was actually opened under, or the session is launched
+ // naming a connection the server has never heard of and every tool call fails.
+ it('returns the id of the connection it opened, for a session with no room yet', () => {
+ const { runtime, created } = makeRuntime();
+
+ const connectionId = runtime.ensureForSession('session-a', 'codex', null);
+
+ expect(created).toHaveLength(1);
+ expect(created[0].deps.connectionId).toBe(connectionId);
+ expect(created[0].deps.roomId).toBeNull();
+ expect(created[0].conn.start).toHaveBeenCalledTimes(1);
+ });
+
it('opens a session at head when no cursor was handed over', () => {
const { runtime, created } = makeRuntime();
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index a80f78604..d59e67089 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -130,7 +130,7 @@ export class SidecarRuntime {
let parsed: ParsedHookEvent;
try {
- parsed = await parseHookEvent(raw, this.resolveContext);
+ parsed = await parseHookEvent(raw, this.resolveContext, this.deps.log);
} catch (error) {
this.deps.log.warn('SidecarRuntime: failed to parse hook event', {
type: raw.type,
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
index a479a659d..c6e1147b6 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
@@ -18,8 +18,16 @@
*
* Bump policy: `x` on a wire break (and only then), `y` on every release that
* changes the sidecar.
+ *
+ * A *new* endpoint is not a wire break. Raising `x` past what a running sidecar
+ * reports only helps if `MIN_SUPPORTED_SIDECAR_MAJOR` moves with it, and that
+ * kills every older sidecar on sight — including one an older switchdash on the
+ * same host will then kill right back, each replacing the other forever. So the
+ * client owns this instead: call the endpoint, and when an older sidecar 404s
+ * it, fail the operation with a message naming the upgrade rather than
+ * continuing without whatever the endpoint was for.
*/
-export const SIDECAR_VERSION = '1.3';
+export const SIDECAR_VERSION = '1.6';
/**
* Oldest major this client can still speak to. Raise it only when support for an
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db
index 1d69ce577..bc06aa5fb 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db and b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db differ
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db
index 708c15bce..cbdddee6e 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db and b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db differ
diff --git a/dash/packages/core/src/agents/plugins/capabilities/mcp.ts b/dash/packages/core/src/agents/plugins/capabilities/mcp.ts
index 8484414fd..9d628c873 100644
--- a/dash/packages/core/src/agents/plugins/capabilities/mcp.ts
+++ b/dash/packages/core/src/agents/plugins/capabilities/mcp.ts
@@ -4,10 +4,99 @@ import type { PluginFs } from '../../runtime/fs';
export type McpTransport = 'stdio' | 'http';
+/**
+ * The Switch MCP runtime as a stdio command, handed to {@link
+ * IMcpBehavior.launchProfile}.
+ *
+ * Static and secret-free — but not self-sufficient. An agent host spawns an MCP
+ * server with an environment of its own choosing, not a copy of its own: Codex
+ * passes a fixed allowlist (`HOME`, `PATH`, `SHELL`, `USER`, `TMPDIR`, …) and
+ * drops everything else. `envVars` names what the host must route through for
+ * the runtime to authenticate and to resolve its package, carrying names only
+ * so no credential is written anywhere.
+ */
+export type SwitchMcpLaunchServer = {
+ command: string;
+ args: string[];
+ /**
+ * Environment variable names the host must forward from its own environment.
+ * Required rather than optional: a launch server that omits them produces a
+ * session whose Switch tools silently never start.
+ */
+ envVars: string[];
+};
+
+/** A single per-agent launch config file, path relative to the agent's home. */
+export type SwitchLaunchProfileFile = {
+ relativePath: string;
+ content: string;
+};
+
+/**
+ * A per-agent launch config — the files to write plus the argv that loads them —
+ * the result of {@link IMcpBehavior.launchProfile}. Pure data so it can be
+ * written directly (local/SSH runtimes) or baked into a precomputed launch spec
+ * and written by the headless VM sidecar, which has no plugin registry. A list
+ * rather than a single file so a host that needs the config split across several
+ * is not a change to this type; Codex today returns exactly one.
+ */
+export type SwitchLaunchProfile = {
+ files: SwitchLaunchProfileFile[];
+ /** Extra argv the launch command needs to load the profile. */
+ args: string[];
+};
+
+/** Optional per-agent specialization folded into the launch profile. */
+export type SwitchLaunchSpecialization = {
+ /** Model id, e.g. a Codex `model` override. */
+ model?: string;
+ /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` override. */
+ reasoningEffort?: string;
+ /** A system-prompt/instructions body, carried in the profile itself (Codex:
+ * `developer_instructions`), which adds to the host's own operating
+ * instructions rather than replacing them. */
+ instructions?: string;
+};
+
export type IMcpBehavior = {
readServers(fs: PluginFs): Promise<McpServerRegistration[]>;
writeServers(fs: PluginFs, servers: McpServerRegistration[]): Promise<void>;
removeServer(fs: PluginFs, name: string): Promise<void>;
+ /**
+ * Compute the launch config that registers the Switch MCP server for a
+ * session (and folds in any per-agent specialization), for agents whose
+ * connector plugin cannot resolve a per-session server from a bundled config.
+ * Pure: it returns the files to write and the argv to load them, leaving the
+ * write to the caller so the same result serves a direct write (local/SSH) and
+ * a baked launch spec the sidecar writes.
+ *
+ * Claude Code leaves this undefined: its plugin expands environment variables
+ * in a bundled `.mcp.json`, so the config is already per-session. Codex
+ * performs no such expansion and a stdio server cannot ride argv across the
+ * `resume` subcommand cleanly, so it returns a per-agent profile
+ * (`~/.codex/<name>.config.toml`) and `--profile <name>`. That profile must
+ * also name the environment it needs;
+ * see {@link SwitchMcpLaunchServer.envVars}.
+ *
+ * Returns `null` when there is nothing to write (no Switch identity and no
+ * specialization).
+ */
+ launchProfile?(
+ params: {
+ slug: string;
+ /** The agent's working directory, mixed into the profile name so two agents
+ * that share a name in different directories get distinct profiles. */
+ workingDir: string;
+ switchServer: SwitchMcpLaunchServer | null;
+ } & SwitchLaunchSpecialization
+ ): SwitchLaunchProfile | null;
+ /**
+ * Home-relative paths the launch profile occupies, so the agent's teardown
+ * (delete/rename) can remove them. Pure and identity-shaped — same `(slug,
+ * workingDir)` as {@link launchProfile} — so a caller can compute the paths for
+ * a name it is about to drop. Undefined for a provider that writes no profile.
+ */
+ launchProfilePaths?(params: { slug: string; workingDir: string }): string[];
};
export type McpServerRegistration = {
@@ -19,6 +108,13 @@ export type McpServerRegistration = {
url?: string;
headers?: Record<string, string>;
env?: Record<string, string>;
+ /**
+ * Name of an environment variable holding the bearer token, for agents that
+ * resolve it at request time rather than taking the secret inline. Declared
+ * rather than left to the index signature so a typo is a compile error and
+ * not a silently unauthenticated server.
+ */
+ bearer_token_env_var?: string;
[key: string]: unknown;
};
diff --git a/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts
index a6f8bee37..7b785abc1 100644
--- a/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts
+++ b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts
@@ -30,15 +30,25 @@ export type RepoAgentDefinition = {
/**
* The MCP permission rules that keep a Switch agent connected to the platform:
- * the connector's two MCP servers. Used both as `tools` allowlist entries (so an
+ * the connector's MCP server. Used both as `tools` allowlist entries (so an
* agent that restricts its tools stays Switch-capable) and as `permissions.allow`
* entries (so the connector's tools are auto-approved — "don't ask"). Authored
* once here so every provider's onboarding path agrees.
*/
-export const SWITCH_CONNECTOR_TOOL_RULES = [
- 'mcp__plugin_switch-connector_switch',
+export const SWITCH_CONNECTOR_TOOL_RULES = ['mcp__plugin_switch-connector_switch'] as const;
+
+/**
+ * Every rule switchdash has ever authored, including ones it no longer writes.
+ * The paths that strip switchdash's own contributions back out — the subagent
+ * form's read-back and the teardown that removes Switch settings — match against
+ * this, so a working directory set up before the connector's two MCP servers
+ * became one runtime is still cleaned up completely instead of keeping a rule
+ * that names a server nobody registers.
+ */
+export const RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES: readonly string[] = [
+ ...SWITCH_CONNECTOR_TOOL_RULES,
'mcp__plugin_switch-connector_switch-channel',
-] as const;
+];
/**
* Provider-neutral directory (relative to a location's working directory) for
@@ -110,7 +120,10 @@ export type IRepoAgentsBehavior = {
/** The current attribute values for an existing agent definition, keyed to
* {@link attributeFields}, or null if no definition exists. */
readDefinition(workspaceFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;
- /** Remove a named agent's definition and credentials files (workspace scope). */
+ /** Remove a named agent's provider-specific files — its definition and any
+ * legacy per-agent settings (workspace scope). The provider-neutral Switch
+ * credentials are not this hook's to remove: they are written for every
+ * provider, so they are torn down by the caller for every provider too. */
removeLocal(workspaceFs: PluginFs, name: string): Promise<void>;
};
diff --git a/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts b/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts
index 636dbd818..275924133 100644
--- a/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts
+++ b/dash/packages/core/src/agents/plugins/capabilities/switch-setup.ts
@@ -18,17 +18,35 @@ export type ISwitchSetupBehavior = {
removeCredentials(fs: PluginFs): Promise<void>;
};
+/**
+ * Which plugin-marketplace CLI dialect an agent speaks.
+ *
+ * Both dialects share the marketplace model — register a marketplace source,
+ * install a named plugin from it — but they disagree on verbs, flags and the
+ * JSON shapes they emit, so the driver cannot assume one from the other:
+ *
+ * - `claude-code`: `plugin install|update|uninstall <ref> -s <scope>`,
+ * `plugin marketplace update`; `plugin list --json` entries carry `id` and
+ * `installPath`; manifests live under `.claude-plugin/`.
+ * - `codex`: `plugin add|remove <ref>` (no scope flag, and **no per-plugin
+ * update verb** — updating is remove-then-add), `plugin marketplace upgrade`;
+ * `plugin list --json` returns `{ installed, available }` whose entries carry
+ * `pluginId` and `source.path`; manifests live under `.codex-plugin/`.
+ */
+export const SWITCH_SETUP_CLI_DIALECTS = ['claude-code', 'codex'] as const;
+export type SwitchSetupCliDialect = (typeof SWITCH_SETUP_CLI_DIALECTS)[number];
+
/**
* Describes how an agent type installs and manages its Switch connector plugin.
*
- * kind: 'cli' — the agent exposes a Claude-Code-style plugin marketplace CLI
- * (`<agent> plugin install/update/uninstall`, `<agent> plugin
- * marketplace add/update/list`). The main-process switch-setup
- * service drives that CLI from these descriptor fields.
+ * kind: 'cli' — the agent exposes a plugin marketplace CLI. The main-process
+ * switch-setup service drives that CLI from these descriptor
+ * fields, using the verb/parse rules for the declared `dialect`.
* kind: 'none' — the agent has no Switch connector setup; the UI surfaces nothing.
*
- * The descriptor is purely declarative — the generic CLI driver handles plugin
- * install/update for every agent that shares the marketplace model. The optional
+ * The descriptor is purely declarative — one generic driver serves every agent
+ * that shares the marketplace model, with `dialect` naming the surface
+ * differences rather than forking the code path. The optional
* {@link ISwitchSetupBehavior} is only for the one thing that can be genuinely
* provider-specific: where credentials live on disk, so they can be torn down on
* delete. Providers using the default `.claude` layout omit it.
@@ -44,8 +62,10 @@ export const switchSetupCapability = definePluginCapability<ISwitchSetupBehavior
marketplaceName: z.string(),
/** Source passed to `marketplace add`: a GitHub `owner/repo` or a path. */
marketplaceSource: z.string(),
- /** Install scope flag for `-s`. */
+ /** Install scope flag for `-s`. Ignored by dialects that have no scope. */
scope: z.enum(['user', 'project', 'local']).default('user'),
+ /** Which CLI dialect this agent's `plugin` subcommand speaks. */
+ dialect: z.enum(SWITCH_SETUP_CLI_DIALECTS).default('claude-code'),
}),
z.object({ kind: z.literal('none') }),
])
diff --git a/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts b/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts
index 852f964ca..2b10f958c 100644
--- a/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts
+++ b/dash/packages/core/src/agents/plugins/helpers/hooks.test.ts
@@ -1,4 +1,4 @@
-import { execFile } from 'node:child_process';
+import { execFile, spawn } from 'node:child_process';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -9,38 +9,69 @@ import { filterUserHooks, makeStdinHookCommand, SWITCHDASH_MARKER } from './hook
const execFileAsync = promisify(execFile);
/**
- * Run a generated POSIX hook command under a real `sh` with `curl` stubbed out,
- * and report the URL and token it would have posted to. The endpoint resolution
- * is shell code, so asserting on the string alone would not catch a quoting or
- * `sed` mistake — only executing it does.
+ * Run `sh -c command` with `stdin` delivered on fd 0 and then closed, mirroring
+ * how an agent host feeds a hook its event payload. `execFile` cannot do this —
+ * it has no stdin input option, so a command that reads fd 0 would hang.
*/
-async function resolveEndpoint(
- env: Record<string, string>
-): Promise<{ url: string; token: string }> {
+function runSh(command: string, env: NodeJS.ProcessEnv, stdin: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = spawn('sh', ['-c', command], { env, stdio: ['pipe', 'ignore', 'ignore'] });
+ child.on('error', reject);
+ child.on('close', () => resolve());
+ child.stdin.end(stdin);
+ });
+}
+
+/**
+ * Run a POSIX hook command under a real `sh` with `curl` stubbed out, and report
+ * what it would have posted. Both the endpoint resolution and the payload
+ * plumbing are shell code, so asserting on the string alone would not catch a
+ * quoting mistake or a pipeline that runs an assignment in a subshell — only
+ * executing it does.
+ *
+ * Exported so provider packages can point it at the command strings their own
+ * hook config writes.
+ */
+export async function runHookCommand(
+ command: string,
+ { env, stdin }: { env: Record<string, string>; stdin?: string }
+): Promise<{ url: string; token: string; body: string }> {
const dir = await mkdtemp(path.join(tmpdir(), 'hook-cmd-'));
try {
- // A `curl` that records its own argv instead of making a request.
+ // A `curl` that records its own argv — and, when the command asked it to
+ // read the request body from stdin, that body too.
const stub = path.join(dir, 'curl');
- const out = path.join(dir, 'argv');
- await writeFile(stub, `#!/bin/sh\nprintf '%s\\n' "$@" > ${JSON.stringify(out)}\n`, {
- mode: 0o755,
- });
-
- const command = makeStdinHookCommand('notification', { platform: 'linux' });
- await execFileAsync('sh', ['-c', command], {
- env: { ...env, PATH: `${dir}:${process.env.PATH ?? ''}` },
- });
-
- const { stdout } = await execFileAsync('cat', [out]);
+ const argvOut = path.join(dir, 'argv');
+ const bodyOut = path.join(dir, 'body');
+ await writeFile(
+ stub,
+ '#!/bin/sh\n' +
+ `printf '%s\\n' "$@" > ${JSON.stringify(argvOut)}\n` +
+ `for a in "$@"; do [ "$a" = "@-" ] && cat > ${JSON.stringify(bodyOut)}; done\n` +
+ 'exit 0\n',
+ { mode: 0o755 }
+ );
+ await writeFile(bodyOut, '');
+
+ await runSh(command, { ...env, PATH: `${dir}:${process.env.PATH ?? ''}` }, stdin ?? '');
+
+ const { stdout } = await execFileAsync('cat', [argvOut]);
const argv = stdout.split('\n');
const url = argv.find((a) => a.startsWith('http://')) ?? '';
const tokenIdx = argv.findIndex((a) => a.startsWith('X-Switchdash-Token:'));
- return { url, token: argv[tokenIdx]?.replace('X-Switchdash-Token: ', '') ?? '' };
+ const { stdout: body } = await execFileAsync('cat', [bodyOut]);
+ return { url, token: argv[tokenIdx]?.replace('X-Switchdash-Token: ', '') ?? '', body };
} finally {
await rm(dir, { recursive: true, force: true });
}
}
+async function resolveEndpoint(
+ env: Record<string, string>
+): Promise<{ url: string; token: string }> {
+ return runHookCommand(makeStdinHookCommand('notification', { platform: 'linux' }), { env });
+}
+
describe('makeStdinHookCommand endpoint resolution', () => {
it('uses the env port and token when no endpoint file is configured', async () => {
const { url, token } = await resolveEndpoint({
@@ -107,6 +138,27 @@ describe('makeStdinHookCommand endpoint resolution', () => {
}
});
+ it('forwards the hook payload on stdin as the request body', async () => {
+ // The port and the body travel through the same shell command, so a
+ // restructuring that puts either behind a pipeline subshell silently drops
+ // one or both — curl's `|| true` swallows the resulting failure.
+ const payload = '{"tool_response":{"room_id":"r1","agent_id":"a1"}}';
+ const { url, body } = await runHookCommand(
+ makeStdinHookCommand('switch_room_connect', { platform: 'linux' }),
+ {
+ env: {
+ SWITCHDASH_HOOK_PORT: '5001',
+ SWITCHDASH_HOOK_TOKEN: 'env-token',
+ SWITCHDASH_PTY_ID: 'codex:s1',
+ },
+ stdin: payload,
+ }
+ );
+
+ expect(url).toBe('http://127.0.0.1:5001/hook');
+ expect(body).toBe(payload);
+ });
+
it('stays recognisable to filterUserHooks so managed entries are replaced, not duplicated', () => {
const command = makeStdinHookCommand('notification', { platform: 'linux' });
diff --git a/dash/packages/core/src/agents/plugins/index.ts b/dash/packages/core/src/agents/plugins/index.ts
index 2a185ac22..e6569f02a 100644
--- a/dash/packages/core/src/agents/plugins/index.ts
+++ b/dash/packages/core/src/agents/plugins/index.ts
@@ -68,10 +68,21 @@ export type { PluginFs } from '../runtime/fs';
// Capability behavior interfaces — needed for dts portability
export type { IHostDependencyBehavior } from '../../host-dependencies/capability';
export type { IHooksBehavior } from './capabilities/hooks';
-export type { IMcpBehavior, McpServerRegistration } from './capabilities/mcp';
+export type {
+ IMcpBehavior,
+ McpServerRegistration,
+ SwitchLaunchProfile,
+ SwitchLaunchProfileFile,
+ SwitchLaunchSpecialization,
+ SwitchMcpLaunchServer,
+} from './capabilities/mcp';
export type { IPlugins } from './capabilities/plugins';
export type { ISessionsBehavior } from './capabilities/sessions';
-export { SWITCH_AGENT_SETTINGS_DIR, SWITCH_CONNECTOR_TOOL_RULES } from './capabilities/repo-agents';
+export {
+ RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES,
+ SWITCH_AGENT_SETTINGS_DIR,
+ SWITCH_CONNECTOR_TOOL_RULES,
+} from './capabilities/repo-agents';
export type {
IRepoAgentsBehavior,
LocalRepoAgent,
@@ -83,7 +94,12 @@ export type {
RepoAgentFieldType,
RepoAgentsDescriptor,
} from './capabilities/repo-agents';
-export type { ISwitchSetupBehavior, SwitchSetupDescriptor } from './capabilities/switch-setup';
+export type {
+ ISwitchSetupBehavior,
+ SwitchSetupCliDialect,
+ SwitchSetupDescriptor,
+} from './capabilities/switch-setup';
+export { SWITCH_SETUP_CLI_DIALECTS } from './capabilities/switch-setup';
// Typed registry factory
export { createPluginRegistry } from '../../lib/plugins/registry';
diff --git a/dash/packages/plugins/src/agents/impl/claude/index.ts b/dash/packages/plugins/src/agents/impl/claude/index.ts
index 293a61779..68e52d0ef 100644
--- a/dash/packages/plugins/src/agents/impl/claude/index.ts
+++ b/dash/packages/plugins/src/agents/impl/claude/index.ts
@@ -112,6 +112,7 @@ export const plugin = definePlugin(
marketplaceName: 'switch-plugins',
marketplaceSource: SWITCH_MARKETPLACE_SOURCE,
scope: 'user',
+ dialect: 'claude-code',
},
},
{ icon }
diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts
index 689ecc252..a88eb612c 100644
--- a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts
+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts
@@ -1,4 +1,3 @@
-import path from 'node:path';
import type { PluginFs } from '@switchdash/core/agents/plugins';
import { describe, expect, it } from 'vitest';
import { CLAUDE_SUBAGENTS, claudeRepoAgentsBehavior } from './subagents';
@@ -28,10 +27,13 @@ function fakeFs(files: Record<string, string>): PluginFs {
};
}
+// Forward-slash literals, not `path.join`: these keys are what a PluginFs sees,
+// and on Windows `path.join` would produce backslashes here *and* in the code
+// under test, so the two would agree with each other and with nothing else.
const settingsRel = (name: string) =>
- path.join(CLAUDE_SUBAGENTS.dirRelative, `${name}${CLAUDE_SUBAGENTS.settingsSuffix}`);
+ `${CLAUDE_SUBAGENTS.dirRelative}/${name}${CLAUDE_SUBAGENTS.settingsSuffix}`;
/** Provider-neutral per-agent credentials file (the current write location). */
-const defRel = (name: string) => path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, `${name}.md`);
+const defRel = (name: string) => `${CLAUDE_SUBAGENTS.definitionsDirRelative}/${name}.md`;
describe('claudeRepoAgentsBehavior.launchArgs', () => {
it('builds --agent and --settings for a subagent', () => {
@@ -39,9 +41,17 @@ describe('claudeRepoAgentsBehavior.launchArgs', () => {
'--agent',
'reviewer',
'--settings',
- path.join('/repo/agent', '.switch', 'agents', 'reviewer.json'),
+ '/repo/agent/.switch/agents/reviewer.json',
]);
});
+
+ it('keeps a remote POSIX path POSIX', () => {
+ // launchArgs is handed `remoteRepoDir` / the SSH session path for a remote
+ // agent, and the flag is parsed by a shell on that Linux host.
+ const args = claudeRepoAgentsBehavior.launchArgs('/home/agent/repo', 'reviewer');
+ expect(args[3]).toBe('/home/agent/repo/.switch/agents/reviewer.json');
+ expect(args[3]).not.toContain('\\');
+ });
});
describe('claudeRepoAgentsBehavior.discoverDefinitions', () => {
@@ -158,15 +168,36 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {
});
const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';
- expect(raw).toContain(
- 'tools: Read, Grep, mcp__plugin_switch-connector_switch, mcp__plugin_switch-connector_switch-channel'
- );
+ expect(raw).toContain('tools: Read, Grep, mcp__plugin_switch-connector_switch');
// Read-back strips the Switch rules so the form shows only the user's tools.
const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');
expect(attrs?.tools).toEqual(['Read', 'Grep']);
});
+ it('strips the retired switch-channel rule an older switchdash wrote', async () => {
+ const workspaceFs = fakeFs({
+ [defRel('reviewer')]: [
+ '---',
+ 'name: reviewer',
+ 'description: Reviews diffs',
+ 'tools: Read, mcp__plugin_switch-connector_switch, mcp__plugin_switch-connector_switch-channel',
+ '---',
+ 'body',
+ '',
+ ].join('\n'),
+ });
+
+ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');
+ expect(attrs?.tools).toEqual(['Read']);
+
+ // And it is not written back: only the rule switchdash still authors is.
+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, attrs ?? {});
+ const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';
+ expect(raw).toContain('tools: Read, mcp__plugin_switch-connector_switch\n');
+ expect(raw).not.toContain('switch-channel');
+ });
+
it('serialises optional scalar, number, and boolean fields and omits empty ones', async () => {
const workspaceFs = fakeFs({});
await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {
@@ -207,7 +238,7 @@ describe('claudeRepoAgentsBehavior.attributeFields', () => {
});
describe('claudeRepoAgentsBehavior.removeLocal', () => {
- it('deletes both the definition and credentials files', async () => {
+ it('deletes the definition and the legacy per-agent settings', async () => {
const workspaceFs = fakeFs({
[defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',
[settingsRel('reviewer')]: '{"env":{}}',
@@ -218,4 +249,16 @@ describe('claudeRepoAgentsBehavior.removeLocal', () => {
expect(await workspaceFs.exists(defRel('reviewer'))).toBe(false);
expect(await workspaceFs.exists(settingsRel('reviewer'))).toBe(false);
});
+
+ it('leaves the provider-neutral credentials to the caller, which removes them for every provider', async () => {
+ const neutralRel = '.switch/agents/reviewer.json';
+ const workspaceFs = fakeFs({
+ [defRel('reviewer')]: '---\nname: reviewer\ndescription: x\n---\n',
+ [neutralRel]: '{"env":{}}',
+ });
+
+ await claudeRepoAgentsBehavior.removeLocal(workspaceFs, 'reviewer');
+
+ expect(await workspaceFs.exists(neutralRel)).toBe(true);
+ });
});
diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.ts
index 62bafa867..c27f3e563 100644
--- a/dash/packages/plugins/src/agents/impl/claude/subagents.ts
+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.ts
@@ -6,6 +6,7 @@ import {
type RepoAgentAttributes,
type RepoAgentDefinition,
type RepoAgentField,
+ RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES,
SWITCH_AGENT_SETTINGS_DIR,
SWITCH_CONNECTOR_TOOL_RULES,
} from '@switchdash/core/agents/plugins';
@@ -18,10 +19,16 @@ import {
* also injected as real env vars (the credentials file's `env` block is not
* reliably propagated to the spawned MCP server otherwise).
*/
+/**
+ * Forward-slash literals, never `path.join`: these are relative paths handed to
+ * a `PluginFs`, which is either the local disk or a remote POSIX host over SFTP,
+ * and `path.join` emits backslashes when switchdash runs on Windows. Same rule
+ * as `switch-settings-paths.ts`.
+ */
export const CLAUDE_SUBAGENTS = {
- dirRelative: path.join('.claude', 'switch-subagents'),
+ dirRelative: '.claude/switch-subagents',
settingsSuffix: '.settings.json',
- definitionsDirRelative: path.join('.claude', 'agents'),
+ definitionsDirRelative: '.claude/agents',
} as const;
const SWITCH_ENV_KEYS = ['SWITCH_API_ENDPOINT', 'SWITCH_API_TOKEN', 'SWITCH_AGENT_ID'] as const;
@@ -31,8 +38,10 @@ const SWITCH_ENV_KEYS = ['SWITCH_API_ENDPOINT', 'SWITCH_API_TOKEN', 'SWITCH_AGEN
* Claude Code reads as "all tools"). */
const SWITCH_MCP_TOOL_PREFIX = 'mcp__plugin_switch-connector_switch';
-/** Non-literal view of the connector rules for `.includes` over arbitrary strings. */
-const SWITCH_RULES: readonly string[] = SWITCH_CONNECTOR_TOOL_RULES;
+/** Rules to strip on read-back, so the form shows only the user's own tools.
+ * Wider than what is written, so a definition authored by an older switchdash
+ * does not surface a retired rule as if the user had chosen it. */
+const SWITCH_RULES: readonly string[] = RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES;
const MD_SUFFIX = '.md';
@@ -326,12 +335,12 @@ function parseSettingsObject(raw: string | null): Record<string, unknown> {
/** Legacy per-subagent credentials file under `.claude/switch-subagents/`. */
function settingsRelPath(name: string): string {
- return path.join(CLAUDE_SUBAGENTS.dirRelative, `${name}${CLAUDE_SUBAGENTS.settingsSuffix}`);
+ return `${CLAUDE_SUBAGENTS.dirRelative}/${name}${CLAUDE_SUBAGENTS.settingsSuffix}`;
}
/** Provider-neutral per-agent credentials file (the current location). */
function neutralSettingsRelPath(name: string): string {
- return path.join(SWITCH_AGENT_SETTINGS_DIR, `${name}.json`);
+ return `${SWITCH_AGENT_SETTINGS_DIR}/${name}.json`;
}
/**
@@ -349,7 +358,7 @@ async function readCredsObject(
}
function definitionRelPath(name: string): string {
- return path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, `${name}${MD_SUFFIX}`);
+ return `${CLAUDE_SUBAGENTS.definitionsDirRelative}/${name}${MD_SUFFIX}`;
}
/** Description/model from a subagent's definition, project scope then user scope. */
@@ -424,7 +433,7 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {
return Promise.all(
files.map(async (file) => {
const content =
- (await workspaceFs.read(path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, file))) ?? '';
+ (await workspaceFs.read(`${CLAUDE_SUBAGENTS.definitionsDirRelative}/${file}`)) ?? '';
const fm = parseFrontmatter(content);
const name = fm.name ?? file.slice(0, -MD_SUFFIX.length);
const registered = await workspaceFs.exists(settingsRelPath(name));
@@ -440,11 +449,15 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {
},
launchArgs(workingDir, agentName): string[] {
+ // `path.posix`: workingDir is the agent's dir on whatever host it runs on,
+ // which for a remote agent is a POSIX path on the VM. Plain `path.join` on a
+ // Windows switchdash would emit backslash separators into a flag that a
+ // Linux shell then has to parse.
return [
'--agent',
agentName,
'--settings',
- path.join(workingDir, neutralSettingsRelPath(agentName)),
+ path.posix.join(workingDir, neutralSettingsRelPath(agentName)),
];
},
@@ -497,7 +510,6 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {
async removeLocal(workspaceFs, name): Promise<void> {
await workspaceFs.delete(definitionRelPath(name));
- await workspaceFs.delete(neutralSettingsRelPath(name));
await workspaceFs.delete(settingsRelPath(name));
},
};
diff --git a/dash/packages/plugins/src/agents/impl/codex/command.test.ts b/dash/packages/plugins/src/agents/impl/codex/command.test.ts
index 2ea0f38e5..055cf4653 100644
--- a/dash/packages/plugins/src/agents/impl/codex/command.test.ts
+++ b/dash/packages/plugins/src/agents/impl/codex/command.test.ts
@@ -14,15 +14,13 @@ const base: CommandContext = {
model: '',
};
-// The auto-approve flag, split the way buildStandardCommand splits it on
-// whitespace.
-const AUTO_FLAGS = [
- '-c',
- 'approval_policy="never"',
- '-c',
- 'sandbox_mode="danger-full-access"',
- '--dangerously-bypass-hook-trust',
-];
+// Emitted for every session: Codex runs no hook it has no persisted trust
+// entry for, and switchdash's hooks are how it reads the session's status and
+// captures the rollout id.
+const TRUST_FLAG = '--dangerously-bypass-hook-trust';
+
+// The approval flag, split the way buildStandardCommand splits it on whitespace.
+const AUTO_FLAGS = ['-c', 'approval_policy="never"'];
describe('codex buildCommand', () => {
it('starts a fresh session with auto-approve flags then the positional prompt', () => {
@@ -31,19 +29,38 @@ describe('codex buildCommand', () => {
expect(cmd.command).toBe('codex');
// sessionIdOnResumeOnly → the switchdash UUID is never injected on a fresh run.
// Full structural check: auto-approve flags in order, prompt last.
- expect(cmd.args).toEqual([...AUTO_FLAGS, 'Fix the bug']);
+ expect(cmd.args).toEqual([TRUST_FLAG, ...AUTO_FLAGS, 'Fix the bug']);
});
- it('omits auto-approve args when autoApprove is false', () => {
+ it('omits auto-approve args when autoApprove is false, but keeps hook trust', () => {
+ // Hook trust is orthogonal to approvals: gate it on auto-approve and a
+ // default agent runs none of switchdash's hooks, taking the session's status
+ // signals and its rollout-id capture with them.
const cmd = build({ ...base, initialPrompt: 'hello' });
- expect(cmd.args).not.toContain('--dangerously-bypass-hook-trust');
- expect(cmd.args).toEqual(['hello']);
+ expect(cmd.args).not.toContain('approval_policy="never"');
+ expect(cmd.args).toEqual([TRUST_FLAG, 'hello']);
+ });
+
+ it('never overrides the sandbox, whatever the approval setting', () => {
+ // Codex runs hooks outside the sandbox — verified against 0.146.0, a
+ // SessionStart hook curling 127.0.0.1 succeeds under workspace-write — so
+ // switchdash's loopback hooks are no reason to hand a session full disk and
+ // network access it was never asked to have.
+ for (const autoApprove of [true, false]) {
+ const cmd = build({ ...base, autoApprove, initialPrompt: 'hello' });
+ expect(cmd.args.join(' ')).not.toContain('sandbox_mode');
+ }
+ });
+
+ it('keeps hook trust on resume, where the flag precedes the subcommand', () => {
+ const cmd = build({ ...base, isResuming: true, providerSessionId: 'rollout-9' });
+ expect(cmd.args.slice(0, 3)).toEqual([TRUST_FLAG, 'resume', 'rollout-9']);
});
it('resumes with the captured rollout session id', () => {
const cmd = build({ ...base, isResuming: true, providerSessionId: 'rollout-9' });
- expect(cmd.args[0]).toBe('resume');
- expect(cmd.args[1]).toBe('rollout-9');
+ expect(cmd.args[1]).toBe('resume');
+ expect(cmd.args[2]).toBe('rollout-9');
// No positional prompt is added on resume.
expect(cmd.args).not.toContain('Fix the bug');
});
@@ -57,14 +74,14 @@ describe('codex buildCommand', () => {
});
// Regression guard on arg order: `resume <id>` must precede the -c flags,
// and no positional prompt is appended on resume.
- expect(cmd.args).toEqual(['resume', 'rollout-9', ...AUTO_FLAGS]);
+ expect(cmd.args).toEqual([TRUST_FLAG, 'resume', 'rollout-9', ...AUTO_FLAGS]);
});
it('falls back to `resume --last` as split args when no rollout id was captured', () => {
const cmd = build({ ...base, isResuming: true });
// Regression guard: the multi-token fallback must be two argv elements,
// not a single "resume --last" string.
- expect(cmd.args.slice(0, 2)).toEqual(['resume', '--last']);
+ expect(cmd.args.slice(1, 3)).toEqual(['resume', '--last']);
});
it('deduplicates the bypass-approvals-and-sandbox singleton flag', () => {
diff --git a/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts b/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts
index d103c0ef0..f5eb93f46 100644
--- a/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts
+++ b/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts
@@ -1,6 +1,73 @@
-import type { PluginFs } from '@switchdash/core/agents/plugins';
+import { execFile, spawn } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import type { HookEvent, PluginFs } from '@switchdash/core/agents/plugins';
import { describe, expect, it } from 'vitest';
import { CODEX_CONFIG_PATH, CODEX_HOOKS_PATH, buildCodexHookConfig } from './hooks';
+import { plugin } from './index';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Execute a generated hook command under a real `sh` with `curl` stubbed out,
+ * feeding it an event payload on stdin the way Codex does, and report the URL
+ * and request body it would have posted.
+ *
+ * A copy of the harness in `@switchdash/core`'s `helpers/hooks.test.ts`; this
+ * package resolves that one through `dist` subpath exports, which do not carry
+ * test files.
+ */
+async function runHookCommand(
+ command: string,
+ { env, stdin }: { env: Record<string, string>; stdin: string }
+): Promise<{ url: string; body: string }> {
+ const dir = await mkdtemp(path.join(tmpdir(), 'codex-hook-'));
+ try {
+ const stub = path.join(dir, 'curl');
+ const argvOut = path.join(dir, 'argv');
+ const bodyOut = path.join(dir, 'body');
+ await writeFile(
+ stub,
+ '#!/bin/sh\n' +
+ `printf '%s\\n' "$@" > ${JSON.stringify(argvOut)}\n` +
+ `for a in "$@"; do [ "$a" = "@-" ] && cat > ${JSON.stringify(bodyOut)}; done\n` +
+ 'exit 0\n',
+ { mode: 0o755 }
+ );
+ await writeFile(bodyOut, '');
+ await writeFile(argvOut, '');
+
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn('sh', ['-c', command], {
+ env: { ...env, PATH: `${dir}:${process.env.PATH ?? ''}` },
+ stdio: ['pipe', 'ignore', 'ignore'],
+ });
+ child.on('error', reject);
+ child.on('close', () => resolve());
+ child.stdin.end(stdin);
+ });
+
+ const { stdout: argv } = await execFileAsync('cat', [argvOut]);
+ const { stdout: body } = await execFileAsync('cat', [bodyOut]);
+ return { url: argv.split('\n').find((a) => a.startsWith('http://')) ?? '', body };
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+/** The `command` strings switchdash writes into Codex's `hooks.json`, by event. */
+async function installedCommands(): Promise<Record<string, string>> {
+ const fs = createMemoryFs();
+ await buildCodexHookConfig().writeHooks(fs, []);
+ const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {
+ hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>>;
+ };
+ return Object.fromEntries(
+ Object.entries(config.hooks).map(([key, entries]) => [key, entries[0].hooks[0].command])
+ );
+}
function createMemoryFs(initial: Record<string, string> = {}): PluginFs {
const files = new Map(Object.entries(initial));
@@ -109,6 +176,48 @@ describe('buildCodexHookConfig install/read/delete', () => {
}
});
+ it('installs no PostToolUse room-tracking hook — the room is connection-driven', async () => {
+ // Since the agent-bridge push transport (CHOO-1857), a session's room is
+ // claimed on the connection switchdash opens and hands it as
+ // SWITCH_CONNECTION_ID, so the server reports the room back. The old
+ // PostToolUse `connect_to_room` scrape is gone; only lifecycle hooks remain.
+ const fs = createMemoryFs();
+ await buildCodexHookConfig().writeHooks(fs, []);
+ const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {
+ hooks: Record<string, unknown>;
+ };
+
+ expect(config.hooks.PostToolUse).toBeUndefined();
+ expect(Object.keys(config.hooks).sort()).toEqual(['PermissionRequest', 'SessionStart', 'Stop']);
+ expect(JSON.stringify(config.hooks)).not.toContain('switch_room_connect');
+ });
+
+ it('declares exactly the events its installed hooks can produce', async () => {
+ // The declaration is what the rest of the app reasons about a provider from,
+ // so an event no installed hook emits is a claim nothing can honour.
+ const producible: Record<string, HookEvent> = {
+ Stop: 'stop',
+ PermissionRequest: 'notification',
+ SessionStart: 'session',
+ };
+
+ const fs = createMemoryFs();
+ await buildCodexHookConfig().writeHooks(fs, []);
+ const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {
+ hooks: Record<string, unknown>;
+ };
+
+ const emitted = Object.keys(config.hooks).map((key) => {
+ const event = producible[key];
+ if (!event) throw new Error(`unmapped Codex hook key ${key}`);
+ return event;
+ });
+ const hooks = plugin.capabilities.hooks;
+ const declared = hooks.kind === 'none' ? [] : hooks.supportedEvents;
+
+ expect([...declared].sort()).toEqual([...new Set(emitted)].sort());
+ });
+
it('reflects installation state through getHooksInstalled + readHooks', async () => {
const fs = createMemoryFs();
const cfg = buildCodexHookConfig();
@@ -185,3 +294,60 @@ describe('buildCodexHookConfig install/read/delete', () => {
await expect(buildCodexHookConfig().writeHooks(fs, [])).rejects.toThrow('transport failure');
});
});
+
+describe('the installed Codex hook commands actually post', () => {
+ // Codex runs each command as `$SHELL -lc "<command>"` and writes the event
+ // JSON to its stdin. These commands resolve their endpoint in shell, so
+ // asserting on the string only proves the text is present — a command that
+ // resolves an empty port, or never reads the payload, passes a string check
+ // and then fails silently behind curl's `|| true`.
+ const ENV = {
+ SWITCHDASH_HOOK_PORT: '5001',
+ SWITCHDASH_HOOK_TOKEN: 'env-token',
+ SWITCHDASH_PTY_ID: 'codex:s1',
+ };
+
+ it.each(['SessionStart'])(
+ 'the %s command reaches the hook server with the payload intact',
+ async (event) => {
+ const payload = JSON.stringify({ session_id: 's1' });
+ const { url, body } = await runHookCommand((await installedCommands())[event], {
+ env: ENV,
+ stdin: payload,
+ });
+
+ expect(url).toBe('http://127.0.0.1:5001/hook');
+ expect(body).toBe(payload);
+ }
+ );
+
+ it.each(['Stop', 'PermissionRequest'])(
+ 'the %s command reaches the hook server with its fixed body',
+ async (event) => {
+ const { url } = await runHookCommand((await installedCommands())[event], {
+ env: ENV,
+ stdin: '',
+ });
+
+ expect(url).toBe('http://127.0.0.1:5001/hook');
+ }
+ );
+
+ it('prefers the sidecar endpoint file over the baked-in env, for every event', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'codex-ep-'));
+ const endpointFile = path.join(dir, 'endpoint');
+ await writeFile(endpointFile, '6002\nfresh-token\n');
+
+ try {
+ for (const command of Object.values(await installedCommands())) {
+ const { url } = await runHookCommand(command, {
+ env: { ...ENV, SWITCHDASH_HOOK_ENDPOINT_FILE: endpointFile },
+ stdin: '{}',
+ });
+ expect(url).toBe('http://127.0.0.1:6002/hook');
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/dash/packages/plugins/src/agents/impl/codex/hooks.ts b/dash/packages/plugins/src/agents/impl/codex/hooks.ts
index 5db78456e..d0ec200e0 100644
--- a/dash/packages/plugins/src/agents/impl/codex/hooks.ts
+++ b/dash/packages/plugins/src/agents/impl/codex/hooks.ts
@@ -3,14 +3,35 @@ import type { CanonicalHookEvent, HookRegistration } from '@switchdash/core/agen
import {
buildNestedJsonHookConfig,
defaultHookEventParser,
- makeHookPostCommand,
makeNotificationHookCommand,
+ makeStdinHookCommand,
} from '@switchdash/core/agents/plugins/helpers';
import * as toml from 'smol-toml';
export const CODEX_HOOKS_PATH = '.codex/hooks.json';
export const CODEX_CONFIG_PATH = '.codex/config.toml';
+/**
+ * Lets Codex run the hooks switchdash installed without a persisted trust entry.
+ *
+ * Codex keys hook trust per entry in `~/.codex/config.toml`
+ * (`[hooks.state."<hooks.json>:<event>:<group>:<index>"] trusted_hash`) and
+ * skips any hook it has no entry for. Verified against 0.146.0: in `codex exec`
+ * that skip is silent — no dump, no mention of the hook in the transcript — and
+ * in the TUI it is a blocking startup review pane that a detached session has
+ * nobody to answer. Either way switchdash's own hooks would not run, taking the
+ * session's status signals and its rollout-id capture with them, and rewriting a
+ * hook command invalidates the entry a user had already granted.
+ *
+ * switchdash writes those hooks itself, which is the case the flag is documented
+ * for ("automation that already vets hook sources"). It is per-invocation and
+ * covers every enabled hook, so a hook the user added to `~/.codex/hooks.json`
+ * also runs unreviewed in switchdash-launched sessions. Writing per-entry trust
+ * instead would be narrower, but the hash input is undocumented and not
+ * derivable from the command text, so it would break silently on a Codex change.
+ */
+export const CODEX_HOOK_TRUST_FLAG = '--dangerously-bypass-hook-trust';
+
const LEGACY_CODEX_NOTIFY_COMMAND = [
'bash',
'-c',
@@ -54,12 +75,6 @@ async function removeLegacyCodexNotify(fs: PluginFs): Promise<void> {
await fs.write(CODEX_CONFIG_PATH, toml.stringify(config));
}
-function makeCodexSessionStartCommand(): string {
- const post = makeHookPostCommand('session-start', 'stdin', {});
- if (process.platform === 'win32') return post;
- return `INPUT="\${1:-$(cat)}"; printf '%s' "$INPUT" | ${post}`;
-}
-
/**
* Codex sends `{ type: 'agent-turn-complete' }` as its stop signal instead
* of a plain 'stop' event type, and uses fixed `notification_type` values
@@ -90,10 +105,15 @@ function parseCodexHookEvent(eventType: string, body: Record<string, unknown>):
}
export function buildCodexHookConfig() {
+ // No PostToolUse room-tracking hook: since the agent-bridge push transport
+ // (CHOO-1857), a session's room is driven by the connection switchdash opens
+ // and hands it as SWITCH_CONNECTION_ID, so `connect_to_room` claims the room
+ // on that connection and the server reports it back. Only lifecycle events
+ // remain, none matcher-scoped.
const base = buildNestedJsonHookConfig(CODEX_HOOKS_PATH, [
{ hookKey: 'Stop', command: makeNotificationHookCommand('idle_prompt') },
{ hookKey: 'PermissionRequest', command: makeNotificationHookCommand('permission_prompt') },
- { hookKey: 'SessionStart', command: makeCodexSessionStartCommand() },
+ { hookKey: 'SessionStart', command: makeStdinHookCommand('session-start') },
]);
return {
diff --git a/dash/packages/plugins/src/agents/impl/codex/index.ts b/dash/packages/plugins/src/agents/impl/codex/index.ts
index fdcafa59d..86f3eabb2 100644
--- a/dash/packages/plugins/src/agents/impl/codex/index.ts
+++ b/dash/packages/plugins/src/agents/impl/codex/index.ts
@@ -5,8 +5,10 @@ import {
homebrewOption,
npmDependency,
} from '@switchdash/core/agents/plugins/helpers';
-import { buildCodexHookConfig } from './hooks';
+import { SWITCH_MARKETPLACE_SOURCE } from '../../../distribution';
+import { buildCodexHookConfig, CODEX_HOOK_TRUST_FLAG } from './hooks';
import { icon } from './icon';
+import { codexLaunchProfile, codexProfilePaths } from './profile';
export const plugin = definePlugin(
{
@@ -64,7 +66,15 @@ export const plugin = definePlugin(
kind: 'resumable',
},
repoAgents: { kind: 'none' },
- switchSetup: { kind: 'none' },
+ switchSetup: {
+ kind: 'cli',
+ pluginName: 'switch-connector-codex',
+ marketplaceName: 'switch-plugins',
+ marketplaceSource: SWITCH_MARKETPLACE_SOURCE,
+ // Codex has no install-scope flag; the value is unused for this dialect.
+ scope: 'user',
+ dialect: 'codex',
+ },
},
{ icon }
);
@@ -73,8 +83,14 @@ export const provider = registerPluginBehavior(plugin, {
prompt: {
buildCommand: (ctx) =>
buildStandardCommand(ctx, {
- autoApproveFlag:
- '-c approval_policy="never" -c sandbox_mode="danger-full-access" --dangerously-bypass-hook-trust',
+ // Every session, not just auto-approving ones. See the flag's docblock.
+ defaultArgs: [CODEX_HOOK_TRUST_FLAG],
+ // Approvals only — the sandbox is left to the user's config. "Bypass
+ // permissions" promises unattended approval, not unattended filesystem
+ // and network access, and Codex runs hooks outside the sandbox, so
+ // switchdash's loopback curls reach the hook server under
+ // workspace-write just as they do under danger-full-access.
+ autoApproveFlag: '-c approval_policy="never"',
initialPromptFlag: '',
resumeFlag: 'resume',
sessionIdFlag: ' ',
@@ -84,5 +100,12 @@ export const provider = registerPluginBehavior(plugin, {
}),
},
hooks: buildCodexHookConfig(),
- mcp: codexMcpAdapter(),
+ mcp: {
+ ...codexMcpAdapter(),
+ // Codex cannot expand ${VAR} in a bundled .mcp.json, so switchdash registers
+ // the local Switch runtime itself: a per-agent profile in CODEX_HOME loaded
+ // with `--profile <slug>`.
+ launchProfile: codexLaunchProfile,
+ launchProfilePaths: codexProfilePaths,
+ },
});
diff --git a/dash/packages/plugins/src/agents/impl/codex/profile.test.ts b/dash/packages/plugins/src/agents/impl/codex/profile.test.ts
new file mode 100644
index 000000000..6030dcb67
--- /dev/null
+++ b/dash/packages/plugins/src/agents/impl/codex/profile.test.ts
@@ -0,0 +1,234 @@
+import { parse as parseTOML } from 'smol-toml';
+import { describe, expect, it } from 'vitest';
+import {
+ buildCodexProfileToml,
+ CODEX_MCP_STARTUP_TIMEOUT_SEC,
+ CODEX_PROFILE_SWITCH_SERVER_NAME,
+ CODEX_REASONING_EFFORTS,
+ codexLaunchProfile,
+ codexProfileName,
+ codexProfileRelativePath,
+} from './profile';
+
+const runtime = {
+ command: 'npx',
+ args: ['-y', '@sandbox-quantum/[email protected]'],
+ envVars: ['SWITCH_API_ENDPOINT', 'SWITCH_API_TOKEN', 'SWITCH_AGENT_ID', 'npm_config_userconfig'],
+};
+
+type ServerEntry = {
+ command: string;
+ args: string[];
+ env_vars?: string[];
+ env?: Record<string, string>;
+ bearer_token?: string;
+ startup_timeout_sec?: number;
+};
+
+function switchServerOf(toml: string): ServerEntry {
+ const parsed = parseTOML(toml) as { mcp_servers: Record<string, ServerEntry> };
+ return parsed.mcp_servers[CODEX_PROFILE_SWITCH_SERVER_NAME];
+}
+
+describe('buildCodexProfileToml', () => {
+ it('registers the Switch runtime as a stdio server', () => {
+ const server = switchServerOf(buildCodexProfileToml({ switchServer: runtime }));
+
+ expect(server.command).toBe('npx');
+ expect(server.args).toEqual(['-y', '@sandbox-quantum/[email protected]']);
+ });
+
+ it('forwards the env-var names the runtime needs, since Codex passes it none of its own', () => {
+ const server = switchServerOf(buildCodexProfileToml({ switchServer: runtime }));
+
+ expect(server.env_vars).toEqual(runtime.envVars);
+ });
+
+ it('names credential env vars without carrying one — the profile has no value channel', () => {
+ const toml = buildCodexProfileToml({ switchServer: runtime });
+ const server = switchServerOf(toml);
+
+ // A name list is the whole mechanism; any of these would be a value channel.
+ expect(server.env).toBeUndefined();
+ expect(server.bearer_token).toBeUndefined();
+ for (const name of server.env_vars ?? []) {
+ expect(name).toMatch(/^[A-Za-z_][A-Za-z0-9_]*$/);
+ }
+ expect(toml).not.toMatch(/Bearer /);
+ });
+
+ it('declares a startup budget a cold npx fetch can finish inside', () => {
+ const server = switchServerOf(buildCodexProfileToml({ switchServer: runtime }));
+
+ expect(server.startup_timeout_sec).toBe(CODEX_MCP_STARTUP_TIMEOUT_SEC);
+ // Codex defaults to 10s. Fetching the runtime from the private registry on a
+ // host that has never run it can exceed that before the server does any work.
+ expect(server.startup_timeout_sec).toBeGreaterThanOrEqual(60);
+ });
+
+ it('omits env_vars for a launch server that needs nothing forwarded', () => {
+ const server = switchServerOf(
+ buildCodexProfileToml({ switchServer: { ...runtime, envVars: [] } })
+ );
+
+ expect(server.env_vars).toBeUndefined();
+ });
+
+ it('emits model / effort scalars and the system prompt as developer_instructions', () => {
+ const parsed = parseTOML(
+ buildCodexProfileToml({
+ switchServer: runtime,
+ model: 'gpt-5.6-terra',
+ reasoningEffort: 'high',
+ instructions: 'be terse',
+ })
+ ) as Record<string, unknown>;
+
+ expect(parsed.model).toBe('gpt-5.6-terra');
+ expect(parsed.model_reasoning_effort).toBe('high');
+ expect(parsed.developer_instructions).toBe('be terse');
+ });
+
+ it('never references an instructions file, which would replace Codex’s own manual', () => {
+ // Measured on codex-cli 0.146.0: with `model_instructions_file` set, the
+ // request's `instructions` is the file and nothing else — the 20,751-char
+ // operating manual (exec/apply_patch protocol, sandbox escalation, planning
+ // tool, final-answer formatting) is gone. `developer_instructions` leaves it
+ // intact and adds a developer message, which is what the UI promises.
+ const toml = buildCodexProfileToml({ switchServer: runtime, instructions: 'be terse' });
+
+ expect(toml).not.toContain('model_instructions_file');
+ expect(toml).not.toContain('instructions.md');
+ });
+
+ it('omits unset specialization keys so the base config default is inherited', () => {
+ const parsed = parseTOML(buildCodexProfileToml({ switchServer: runtime })) as Record<
+ string,
+ unknown
+ >;
+ expect(parsed.model).toBeUndefined();
+ expect(parsed.model_reasoning_effort).toBeUndefined();
+ expect(parsed.developer_instructions).toBeUndefined();
+ });
+
+ it('round-trips a hostile multi-line body through TOML unchanged', () => {
+ // The body is free-form user text and reaches the VM as file content — over
+ // SFTP, base64 over SSH, or baked into the sidecar's launch spec. TOML
+ // escaping has to be lossless for all of it, including the characters a
+ // shell would eat if this ever moved onto argv.
+ const body = [
+ 'line with "double quotes" and \'single\'',
+ '$(whoami) `id -u` ${HOME}',
+ 'back\\slash and\ttab',
+ 'a """ triple quote and a # hash and [a table]',
+ 'trailing newline follows',
+ '',
+ ].join('\n');
+
+ const parsed = parseTOML(
+ buildCodexProfileToml({ switchServer: runtime, instructions: body })
+ ) as Record<string, unknown>;
+
+ expect(parsed.developer_instructions).toBe(body);
+ });
+});
+
+const WD = '/home/agent/repo';
+
+describe('codexLaunchProfile', () => {
+ it('writes the profile under ~/.codex keyed on the (dir, slug) and loads with --profile', () => {
+ const profile = codexLaunchProfile({
+ slug: 'codex-hoot',
+ workingDir: WD,
+ switchServer: runtime,
+ });
+ expect(profile).not.toBeNull();
+ expect(profile!.args).toEqual(['--profile', codexProfileName('codex-hoot', WD)]);
+ expect(profile!.files).toEqual([
+ {
+ relativePath: codexProfileRelativePath('codex-hoot', WD),
+ content: expect.stringContaining('[mcp_servers.switch]'),
+ },
+ ]);
+ expect(codexProfileRelativePath('codex-hoot', WD)).toBe(
+ `.codex/${codexProfileName('codex-hoot', WD)}.config.toml`
+ );
+ });
+
+ it('keeps a system prompt inside the one profile file, off the command line', () => {
+ // The argv is re-rendered as a shell string on the SSH and tmux paths, so a
+ // free-form body there would be mangled (newlines flattened) or executed
+ // (`$(…)`, backticks). Two fixed tokens is the whole command-line surface.
+ const instructions = 'be terse\n$(whoami) and "quotes"';
+ const profile = codexLaunchProfile({
+ slug: 'codex-hoot',
+ workingDir: WD,
+ switchServer: runtime,
+ instructions,
+ })!;
+
+ expect(profile.files).toHaveLength(1);
+ expect(profile.files[0].relativePath).toBe(codexProfileRelativePath('codex-hoot', WD));
+ const parsed = parseTOML(profile.files[0].content) as Record<string, unknown>;
+ expect(parsed.developer_instructions).toBe(instructions);
+ expect(profile.args).toEqual(['--profile', codexProfileName('codex-hoot', WD)]);
+ expect(profile.args.join(' ')).not.toContain('whoami');
+ });
+
+ it('returns a profile for specialization even without a Switch identity', () => {
+ const profile = codexLaunchProfile({
+ slug: 'a',
+ workingDir: WD,
+ switchServer: null,
+ model: 'gpt-5.6-terra',
+ });
+ expect(profile).not.toBeNull();
+ expect(profile!.files[0].content).toContain('model = "gpt-5.6-terra"');
+ expect(profile!.files[0].content).not.toContain('mcp_servers');
+ });
+
+ it('returns null when there is nothing to register or specialize', () => {
+ expect(codexLaunchProfile({ slug: 'a', workingDir: WD, switchServer: null })).toBeNull();
+ });
+
+ it('exposes the stable reasoning-effort levels', () => {
+ expect(CODEX_REASONING_EFFORTS).toEqual(['low', 'medium', 'high', 'xhigh', 'max']);
+ });
+});
+
+describe('codexProfileName', () => {
+ it('rewrites a dotted Switch agent name onto the alphabet Codex accepts', () => {
+ const name = codexProfileName('codex.yak.cmcdermott', WD);
+ expect(name).toMatch(/^[A-Za-z0-9_-]+$/);
+ expect(name).toContain('codex-yak-cmcdermott');
+ });
+
+ it('gives two agents that share a name in different dirs distinct profiles', () => {
+ // Agent names are unique only within a location, so the working dir must
+ // discriminate — otherwise the second launch overwrites the first's profile.
+ expect(codexProfileName('hoot', '/dir/one')).not.toBe(codexProfileName('hoot', '/dir/two'));
+ });
+
+ it('is stable for the same (slug, dir)', () => {
+ expect(codexProfileName('hoot', WD)).toBe(codexProfileName('hoot', WD));
+ });
+
+ it('keeps slugs that differ only in rewritten characters on distinct profiles', () => {
+ expect(codexProfileName('a.b', WD)).not.toBe(codexProfileName('a-b', WD));
+ });
+
+ it('drives the profile file and the --profile argv from the same name', () => {
+ const slug = 'codex.yak.cmcdermott';
+ const profile = codexLaunchProfile({
+ slug,
+ workingDir: WD,
+ switchServer: runtime,
+ instructions: 'be terse',
+ })!;
+ const name = codexProfileName(slug, WD);
+
+ expect(profile.args).toEqual(['--profile', name]);
+ expect(profile.files.map((file) => file.relativePath)).toEqual([`.codex/${name}.config.toml`]);
+ expect(profile.files[0].content).toContain('developer_instructions = "be terse"');
+ });
+});
diff --git a/dash/packages/plugins/src/agents/impl/codex/profile.ts b/dash/packages/plugins/src/agents/impl/codex/profile.ts
new file mode 100644
index 000000000..efae8a718
Binary files /dev/null and b/dash/packages/plugins/src/agents/impl/codex/profile.ts differ
diff --git a/dash/packages/switch-agent-runtime/package.json b/dash/packages/switch-agent-runtime/package.json
index 1ac7af1a2..5a34912b1 100644
--- a/dash/packages/switch-agent-runtime/package.json
+++ b/dash/packages/switch-agent-runtime/package.json
@@ -1,6 +1,6 @@
{
"name": "@sandbox-quantum/switch-agent-runtime",
- "version": "0.1.3",
+ "version": "0.1.4",
"description": "Switch agent protocol client, and the local MCP runtime built on it",
"license": "Apache-2.0",
"author": {
diff --git a/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts b/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts
new file mode 100644
index 000000000..36f4e3876
--- /dev/null
+++ b/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts
@@ -0,0 +1,181 @@
+import { type ChildProcess, spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import * as http from 'node:http';
+import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+/**
+ * The server's behaviour up to `initialize`, exercised as a real subprocess.
+ *
+ * A host that spawns this over stdio sees one symptom for every startup
+ * failure — the connection closing before the handshake — and does not show
+ * the child's stderr, so "no credentials", "endpoint unreachable" and "server
+ * is broken" are indistinguishable from outside. The distinction is only
+ * visible here, which is why these cases assert on the *manner* of failure
+ * (exits, promptly, saying why) and not merely that it failed.
+ *
+ * `bin.ts` reads its config at module scope and exits from it, so it cannot be
+ * imported: the only honest test spawns the built artifact.
+ */
+
+const PKG_ROOT = join(import.meta.dirname, '..');
+const BIN = join(PKG_ROOT, 'dist', 'bin.mjs');
+
+/** Well under Codex's own budget: a startup failure must resolve far sooner. */
+const DEADLINE_MS = 20_000;
+
+const INITIALIZE = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'handshake-test', version: '0' },
+ },
+};
+
+type Running = { child: ChildProcess; stdout: () => string; stderr: () => string };
+
+const running: ChildProcess[] = [];
+const servers: http.Server[] = [];
+
+afterEach(() => {
+ for (const child of running.splice(0)) child.kill('SIGKILL');
+ for (const server of servers.splice(0)) server.close();
+});
+
+/** An endpoint serving the operation list the runtime loads before serving. */
+async function opsServer(): Promise<string> {
+ const server = http.createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ operations: {} }));
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as { port: number };
+ return `http://127.0.0.1:${port}`;
+}
+
+/** An endpoint that accepts the connection and then never answers. */
+async function blackHoleServer(): Promise<string> {
+ const server = http.createServer(() => {
+ // Deliberately no response: the runtime must give up on its own.
+ });
+ servers.push(server);
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as { port: number };
+ return `http://127.0.0.1:${port}`;
+}
+
+function start(env: Record<string, string>): Running {
+ const child = spawn(process.execPath, [BIN], {
+ // A fixed environment, as a host gives it: nothing leaks in from this runner.
+ env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '', ...env },
+ stdio: ['pipe', 'pipe', 'pipe'],
+ });
+ running.push(child);
+
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (c: Buffer) => {
+ out += c.toString();
+ });
+ child.stderr.on('data', (c: Buffer) => {
+ err += c.toString();
+ });
+ return { child, stdout: () => out, stderr: () => err };
+}
+
+/** Resolve with the exit code, or reject if the process outlives the deadline. */
+function exitWithin(child: ChildProcess, ms: number): Promise<number | null> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`process still running after ${ms}ms`)), ms);
+ child.on('exit', (code) => {
+ clearTimeout(timer);
+ resolve(code);
+ });
+ });
+}
+
+/** Resolve with the JSON-RPC response to `initialize`. */
+function responseWithin(run: Running, ms: number): Promise<Record<string, unknown>> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`no initialize response within ${ms}ms`)), ms);
+ run.child.stdout!.on('data', () => {
+ for (const line of run.stdout().split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ const message = JSON.parse(line) as { id?: number };
+ if (message.id === 1) {
+ clearTimeout(timer);
+ resolve(message as Record<string, unknown>);
+ }
+ } catch {
+ // Partial line; wait for the rest.
+ }
+ }
+ });
+ });
+}
+
+describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () => {
+ it('answers initialize when its credentials are present', async () => {
+ const endpoint = await opsServer();
+ const run = start({
+ SWITCH_API_ENDPOINT: endpoint,
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'agent-1',
+ });
+ run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);
+
+ const response = (await responseWithin(run, DEADLINE_MS)) as {
+ result?: { protocolVersion?: string; serverInfo?: { name?: string } };
+ };
+
+ expect(response.result?.protocolVersion).toBeTruthy();
+ expect(response.result?.serverInfo?.name).toBeTruthy();
+ });
+
+ it('exits rather than hanging when the host forwarded it no credentials', async () => {
+ // The failure this whole change exists to fix: a host that forwards nothing
+ // leaves the runtime blind, and exiting is what makes that legible.
+ const run = start({});
+ run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);
+
+ expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);
+ for (const name of ['SWITCH_API_ENDPOINT', 'SWITCH_API_TOKEN', 'SWITCH_AGENT_ID']) {
+ expect(run.stderr()).toContain(name);
+ }
+ expect(run.stdout()).toBe('');
+ });
+
+ it(
+ 'exits rather than hanging when Switch never answers',
+ async () => {
+ const endpoint = await blackHoleServer();
+ const run = start({
+ SWITCH_API_ENDPOINT: endpoint,
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'agent-1',
+ });
+ run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);
+
+ expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);
+ expect(run.stderr()).toContain(endpoint);
+ },
+ // Must outlast the runtime's own fetch bound, which is the thing under test.
+ DEADLINE_MS + 5_000
+ );
+
+ it('names the endpoint it could not reach, not just that it failed', async () => {
+ const run = start({
+ SWITCH_API_ENDPOINT: 'http://127.0.0.1:1',
+ SWITCH_API_TOKEN: 'tok-123',
+ SWITCH_AGENT_ID: 'agent-1',
+ });
+
+ expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);
+ expect(run.stderr()).toMatch(/cannot reach Switch at http:\/\/127\.0\.0\.1:1/);
+ });
+});
diff --git a/dash/packages/switch-agent-runtime/src/bin.ts b/dash/packages/switch-agent-runtime/src/bin.ts
index 5f33c845c..95fa2576f 100644
--- a/dash/packages/switch-agent-runtime/src/bin.ts
+++ b/dash/packages/switch-agent-runtime/src/bin.ts
@@ -1,19 +1,29 @@
#!/usr/bin/env node
/**
- * Switch channel for Claude Code.
+ * The Switch agent runtime: one stdio MCP server, shared by every host.
*
- * Holds a push connection to the Switch Agent Bridge (server-sent events) and
- * pushes addressed messages and task events into the Claude Code session as
- * channel notifications.
+ * It serves the Switch tool surface — fetched from the server at startup rather
+ * than hardcoded, so it cannot drift — and turns each call into
+ * `POST /agents/{id}/ops/{tool}` on a connection to the Agent Bridge. That
+ * connection is a server-sent event stream, which is also how addressed
+ * messages and task events arrive; unless notifications are suppressed they are
+ * surfaced to the session.
*
- * The room is set by the PostToolUse hook on connect_to_room, which
- * POSTs the room id to a localhost port this server exposes. The port is
- * advertised at `${CLAUDE_PLUGIN_DATA}/sessions/${ppid}/port`, where ppid is
- * this process's parent PID (the Claude Code session). The hook resolves the
- * same path from its own getppid(), so each session's hook reaches its own
- * channel without any cross-session coordination.
+ * The room comes from `connect_to_room`, which claims it on this process's
+ * connection — or, when a supervisor handed one over in `SWITCH_CONNECTION_ID`,
+ * on the supervisor's. Either way the room is known here without observing
+ * anything.
*
- * Config comes from env vars set via .mcp.json env block (SWITCH_*).
+ * A localhost hook port remains for the one case that misses: a Claude Code
+ * session nobody supervised, whose `PostToolUse` hook POSTs the room id here.
+ * The port is advertised at `~/.switch/sessions/${ppid}/port`, where ppid is
+ * this process's parent PID (the host session). The hook resolves the same path
+ * from its own getppid(), so each session's hook reaches its own runtime
+ * without any cross-session coordination.
+ *
+ * Config comes from `SWITCH_*` env vars: the Claude connector sets them in its
+ * `.mcp.json` env block, the Codex profile in `env_vars`, and switchdash puts
+ * them in the session's environment when it launches one itself.
*/
import { randomUUID } from 'node:crypto';
@@ -46,6 +56,32 @@ function looksUnresolved(value: string): boolean {
return value.startsWith('${') && value.endsWith('}');
}
+const SESSION_PPID = process.ppid;
+const SESSION_DIR = path.join(os.homedir(), '.switch', 'sessions', String(SESSION_PPID));
+const PORT_FILE = path.join(SESSION_DIR, 'port');
+const STARTUP_ERROR_FILE = path.join(SESSION_DIR, 'startup-error.log');
+
+/** True once the transport is serving; before that, any failure is fatal. */
+let serving = false;
+
+/**
+ * Refuse to start, saying why in the two places someone can find it.
+ *
+ * A host reports a server that dies before the handshake as nothing more than a
+ * closed connection, and does not surface the child's stderr — so every cause
+ * looks identical from the outside. The file is what makes them tell apart.
+ */
+function failStartup(reason: string): never {
+ process.stderr.write(`switch: ${reason}\n`);
+ try {
+ fs.mkdirSync(SESSION_DIR, { recursive: true });
+ fs.writeFileSync(STARTUP_ERROR_FILE, `${new Date().toISOString()} ${reason}\n`);
+ } catch {
+ // Best effort: stderr already carries the reason.
+ }
+ process.exit(1);
+}
+
if (
!API_ENDPOINT ||
!API_TOKEN ||
@@ -54,25 +90,28 @@ if (
looksUnresolved(API_TOKEN) ||
looksUnresolved(AGENT_ID)
) {
- process.stderr.write(
- `switch: missing or unresolved config — need SWITCH_API_ENDPOINT, SWITCH_API_TOKEN, and SWITCH_AGENT_ID\n` +
+ failStartup(
+ `missing or unresolved config — need SWITCH_API_ENDPOINT, SWITCH_API_TOKEN, and SWITCH_AGENT_ID\n` +
` endpoint=${API_ENDPOINT || 'MISSING'}\n` +
` token=${API_TOKEN ? 'set' : 'MISSING'}\n` +
` agent_id=${AGENT_ID || 'MISSING'}\n` +
- `If these look like \`\${SWITCH_*}\`, the env block in \`.claude/settings.local.json\` has not been expanded — run the \`configure\` skill.\n`
+ `If these look like \`\${SWITCH_*}\`, the env block in \`.claude/settings.local.json\` has not been expanded — run the \`configure\` skill.\n` +
+ `If they are simply absent, the host did not pass them through: Codex forwards only the names listed in \`env_vars\` on its \`mcp_servers\` entry.`
);
- process.exit(1);
}
-const SESSION_PPID = process.ppid;
-const SESSION_DIR = path.join(os.homedir(), '.switch', 'sessions', String(SESSION_PPID));
-const PORT_FILE = path.join(SESSION_DIR, 'port');
process.stderr.write(`switch: ppid=${SESSION_PPID} session_dir=${SESSION_DIR}\n`);
+// Before the transport is serving these must be fatal. A listener that only
+// logs takes Node's own fatal-error path away, so a rejected top-level await
+// leaves the process to drain its event loop and exit having answered nothing
+// — the least debuggable shape this failure can take.
process.on('unhandledRejection', (err) => {
+ if (!serving) failStartup(`unhandled rejection during startup: ${err}`);
process.stderr.write(`switch: unhandled rejection: ${err}\n`);
});
process.on('uncaughtException', (err) => {
+ if (!serving) failStartup(`uncaught exception during startup: ${err}`);
process.stderr.write(`switch: uncaught exception: ${err}\n`);
});
@@ -221,7 +260,7 @@ let cursor = 0;
// Whether the currently open stream declared a room when it opened.
let streamHasRoom = false;
-// Unaddressed room messages are filtered out (never reach Claude as a
+// Unaddressed room messages are filtered out (never surfaced as a
// notification), so the agent silently falls behind on room chatter. We tally
// how many we've dropped since the agent last read context and surface that
// count on every notification we DO emit, so the agent knows when to call
@@ -324,7 +363,7 @@ const DOWNLOAD_ATTACHMENT_TOOL = {
};
// The outbound counterpart of download_attachment: the agent names a local
-// file (e.g. a screenshot it produced) and the channel uploads the bytes to
+// file (e.g. a screenshot it produced) and this runtime uploads the bytes to
// the agent bridge, which posts them into the room as an m.image / m.file
// event — from there the collaboration bridges relay it out to Slack /
// Mattermost like any other room message.
@@ -390,9 +429,19 @@ type SwitchOperation = {
let operations: SwitchOperation[] = [];
+/**
+ * How long to wait for the operation list before giving up.
+ *
+ * Unbounded, an unreachable endpoint holds the handshake open until the host's
+ * own startup timeout fires, which reports a timeout and names no cause. A
+ * bounded wait fails first and says what it was waiting for.
+ */
+const OPERATIONS_FETCH_TIMEOUT_MS = 15_000;
+
async function loadOperations(): Promise<void> {
const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/ops`, {
headers: { Authorization: `Bearer ${API_TOKEN}` },
+ signal: AbortSignal.timeout(OPERATIONS_FETCH_TIMEOUT_MS),
});
if (!resp.ok) {
// Without the operation list this process cannot serve the agent at all.
@@ -1236,9 +1285,9 @@ async function handleEvent(event: AgentEvent) {
const MEDIA_DIR = path.join(SESSION_DIR, 'media');
-// Download an inbound attachment from the agent bridge to a local file so
-// Claude can Read it. The bridge proxies the bytes out of the Matrix media
-// repo (the channel holds only the bridge API token, not Matrix creds).
+// Download an inbound attachment from the agent bridge to a local file so the
+// agent can read it. The bridge proxies the bytes out of the Matrix media repo
+// (this runtime holds only the bridge API token, not Matrix creds).
// Returns the local path, or null on failure (logged, never throws).
function sanitiseName(name: string): string {
return name.replace(/[^a-zA-Z0-9._-]/g, '_') || 'attachment';
@@ -1349,9 +1398,16 @@ unpublishPort();
// Load the operation list before serving: a tool surface that is empty
// because a fetch failed is worse than a process that refuses to start.
-await loadOperations();
+try {
+ await loadOperations();
+} catch (err) {
+ failStartup(
+ `cannot reach Switch at ${API_ENDPOINT} to load its operations: ${err instanceof Error ? err.message : err}`
+ );
+}
await mcp.connect(transport);
+serving = true;
startHookListener();
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 1bec25478..c227e5389 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -67,8 +67,8 @@ flowchart LR
DB[("PostgreSQL")]
OPS[Operator dashboard SPA]
- A1 <-->|MCP / long-poll| AB
- A2 <-->|HTTP / long-poll| AB
+ A1 <-->|MCP + SSE stream| AB
+ A2 <-->|HTTP + SSE stream| AB
SL <-->|WebSocket| CB
MM <-->|WebSocket| CB
DC <-->|WebSocket| CB
@@ -149,8 +149,14 @@ The relational schema is defined in
`BearerAuthMiddleware` ([`bridges/agent/auth.py`](../core/switch_core/bridges/agent/auth.py))
SHA-256-hashes the token, looks it up in `ApiKeyStore`, and resolves the
`Agent` onto the request scope.
-3. Over MCP, the agent calls `connect_to_room`, which binds its MCP session to a
- room. Events are then delivered by **long-polling** (see 4.3).
+3. The agent opens its event stream (`GET /agents/{id}/events` with
+ `Accept: text/event-stream`), which creates its **connection** — the unit
+ that owns scope, cursor, liveness and room slots. It then calls
+ `connect_to_room`, which **claims the room on that connection**; events for
+ the room are pushed down the same stream (see 4.3). A supervisor that
+ spawned the session may open the stream on its behalf and hand the id over
+ as `SWITCH_CONNECTION_ID`, so the session claims its room on the
+ supervisor's connection rather than opening a second one.
### 4.2 Inbound message: external platform → agent
@@ -171,7 +177,7 @@ sequenceDiagram
PU->>MX: Matrix m.room.message
MX-->>AC: sync event
AC->>AC: is this addressed to my agent?
- AC-->>AG: enqueue AgentEvent (delivered on long-poll)
+ AC-->>AG: append AgentEvent (pushed down the agent's SSE stream)
```
Inbound messages do **not** arrive through the `/collab` HTTP app (that app only
@@ -203,13 +209,29 @@ agent's name/icon, preserving threads and attachments.
### 4.3 Event delivery & mediation
-- **Delivery is long-poll, not push.** `ProtocolService`
+- **Delivery is a push stream over SSE.** `ProtocolService`
([`bridges/agent/protocol/service.py`](../core/switch_core/bridges/agent/protocol/service.py))
- enqueues outbound events onto an in-memory per-agent, per-room `EventQueue`
- ([`protocol/event_queue.py`](../core/switch_core/bridges/agent/protocol/event_queue.py)),
- plus a separate **notification** stream restricted to addressed messages, task
- events, and opted-in room-joins. Agents drain these via
- `GET /agents/{id}/events` / `.../notifications` (returning `204` on timeout).
+ appends outbound events to a per-agent sequenced `EventBuffer`
+ ([`protocol/event_buffer.py`](../core/switch_core/bridges/agent/protocol/event_buffer.py)),
+ which is read, never drained — so several readers can consume the same events
+ and a reader that drops off resumes from its cursor. An agent opens
+ `GET /agents/{id}/events` with `Accept: text/event-stream`; the stream
+ ([`protocol/stream.py`](../core/switch_core/bridges/agent/protocol/stream.py))
+ catches up from the cursor and then delivers live, tagging each event with its
+ sequence number so a reconnect resumes via `Last-Event-ID`. The stream is the
+ agent's **connection**
+ ([`protocol/connections.py`](../core/switch_core/bridges/agent/protocol/connections.py)),
+ which owns its scope (`single` / `all`), its event filter (`all` /
+ `addressed`), its heartbeat, and its room slots — at most one connection per
+ agent may act in a given room. `docs/api/AGENT_PROTOCOL.md` is the
+ authoritative spec.
+- **The long poll survives as a compatibility path.** `GET /agents/{id}/events`
+ without the SSE `Accept` header, `GET /agents/{id}/rooms/{room_id}/events`,
+ and `GET /agents/{id}/notifications` (addressed messages, task events,
+ opted-in room-joins) all return `204` on timeout and are served **from the
+ same buffer** — each is a filtered view with a server-held cursor, so no path
+ can diverge from another or destroy what another has yet to read. They are
+ scheduled for removal once the remaining clients are on the stream.
- **Mediation is synchronous.** The bridge exposes
`POST /agents/.../mediation/{pre-tool-call,pre-llm-request,post-tool-result,post-llm-response}`.
`RequestTracker`
@@ -250,6 +272,7 @@ Everything ingress-facing, and where to find it:
| Entry point | Path / transport | Auth | Code |
|-------------|------------------|------|------|
| Agent Bridge API | `/agents/*` (HTTP) | Bearer (agent API key / registration token) | `bridges/agent/api/`, `auth.py` |
+| Agent event stream | `/agents/{id}/events` (SSE) | Bearer | `bridges/agent/protocol/stream.py`, `protocol/connections.py` |
| MCP server | `/mcp` (HTTP, FastMCP) | Bearer | `bridges/agent/mcp/server.py` |
| Health | `/health` | public | `main.py` |
| Collaboration admin | `/collab/bridges` | (bridge CRUD) | `bridges/collaboration/api.py` |
diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.md
index 40aca9288..bbfe9aa58 100644
--- a/docs/api/AGENT_PROTOCOL.md
+++ b/docs/api/AGENT_PROTOCOL.md
@@ -4,7 +4,8 @@ Status: **design, under review** (CHOO-1857)
This document specifies the protocol between an agent and Switch: how an agent
connects, what it receives, what it sends, and what happens when things break.
-It replaces the long-poll delivery described in `ARCHITECTURE.md` §4.3.
+It replaces the long-poll delivery Switch originally shipped, and is the
+authoritative spec for the connection model `ARCHITECTURE.md` §4.3 summarises.
---
@@ -614,8 +615,10 @@ Planned second mode off the same code: *daemon* (long-lived, `scope: all`,
- **Claude Code** — plugin `.mcp.json` at the plugin root, `${CLAUDE_PLUGIN_ROOT}`
for the path, `${VAR}` expansion for endpoint and token.
-- **Codex** — Codex expands neither, so switchdash registers the server on argv
- at launch. It controls the launch, so it can also inject per-session
+- **Codex** — Codex expands neither, and a stdio server cannot be expressed on
+ argv the way an HTTP one can, so switchdash writes a per-agent Codex profile
+ (`$CODEX_HOME/<slug>.config.toml`) registering the server and launches with
+ `--profile <slug>`. It controls the launch, so it can also inject per-session
credentials.
### 9.2 Remote MCP (fallback)
@@ -639,9 +642,9 @@ fallback tier and costs minting, expiry, rotation and injection.
It asks; it does not observe.
-Today switchdash learns a session's room by watching: a `PostToolUse` hook
-fires after `connect_to_room` succeeds and switchdash records the room in its
-own map, persisted to SQLite. The hook is accurate — the flaw is the *copy*. A
+switchdash used to learn a session's room by watching: a `PostToolUse` hook
+fired after `connect_to_room` succeeded and switchdash recorded the room in its
+own map, persisted to SQLite. The hook was accurate — the flaw was the *copy*. A
copy drifts when the session dies, when the connection fails after the tool
returned, when the server restarts, or when the room is deleted.
@@ -650,6 +653,15 @@ that is authoritative. A client reads it from the local runtime it spawned
(same process as the connection) or from Switch. **The hook, the persisted
session→room blob, and the remote mirror all go away.**
+*State of the migration.* switchdash now opens the stream itself and hands the
+session `SWITCH_CONNECTION_ID`, so a switchdash-launched session claims its room
+on a connection switchdash already holds — for Claude Code and for Codex alike.
+The `PostToolUse` hook survives only as the fallback for a **Claude** session
+switchdash did not start and adopted afterwards, which holds a connection of its
+own. Codex registers no such hook: its Switch MCP server exists only in the
+per-agent profile switchdash writes, so a Codex session switchdash did not start
+has no `connect_to_room` to observe in the first place.
+
Cross-checking a room against incoming events becomes unnecessary: a
connection only receives events for rooms it is subscribed to, and any change
— including a room going dark because another connection claimed it — arrives
@@ -738,11 +750,12 @@ A connection that has silently missed events must never appear healthy.
`POST /ops/{operation}`, dispatched from the same registry so parity cannot
drift. Unblocks the local runtime and closes the overlap with CHOO-490.
- **Still to do — merging the two MCP servers into one local runtime.** Now
- possible: the runtime serves the tool surface over stdio and translates each
- call to `POST /ops/${toolName}` on its own connection. Until it lands the
- plugin keeps registering the remote `switch` MCP server alongside the local
- channel.
+ **The two MCP servers are merged into one local runtime.** *(implemented)*
+ `@sandbox-quantum/switch-agent-runtime` serves the tool surface over stdio —
+ fetched from the server at startup, so it cannot drift — and translates each
+ call to `POST /ops/${toolName}` on its connection. Each connector plugin now
+ registers exactly one MCP server (`switch`); the separate remote `switch` and
+ local `switch-channel` pair is gone.
**Stage B — migrate the clients. Nothing is removed.**
diff --git a/scripts/codex-hook-probe/mcp_probe.py b/scripts/codex-hook-probe/mcp_probe.py
new file mode 100644
index 000000000..d1d5b08c4
--- /dev/null
+++ b/scripts/codex-hook-probe/mcp_probe.py
@@ -0,0 +1,32 @@
+"""A stand-in for the Switch MCP server, faithful in the one way that matters.
+
+`connect_to_room` is declared exactly as the real tool is — an async FastMCP
+tool returning `dict[str, Any]` — so FastMCP serialises the result the same way
+here as in `switch_core.bridges.agent.mcp.server`. Running the probe shows what
+Codex puts in the PostToolUse hook's `tool_response` for that call.
+"""
+
+from typing import Any
+
+from fastmcp import FastMCP
+
+mcp: FastMCP = FastMCP("switch")
+
+
+async def connect_to_room(room_id: str) -> dict[str, Any]:
+ """Connect this session to a room.
+
+ Args:
+ room_id: The Switch room id to connect to.
+ """
+ return {
+ "room_id": room_id,
+ "agent_id": "probe-agent-1",
+ "name": "Probe Room",
+ "participants": [],
+ }
+
+
+if __name__ == "__main__":
+ mcp.run()
diff --git a/scripts/codex-hook-probe/run.sh b/scripts/codex-hook-probe/run.sh
new file mode 100755
index 000000000..26da284cd
--- /dev/null
+++ b/scripts/codex-hook-probe/run.sh
@@ -0,0 +1,215 @@
+#!/usr/bin/env bash
+#
+# Measure two things about Codex's hook contract that cannot be settled by
+# reading the binary:
+#
+# 1. Does Codex deliver a hook's event payload on stdin, with no positional
+# operands? switchdash's hook commands pipe stdin into curl (`-d @-`), so a
+# payload handed over as a positional operand instead would leave them
+# posting an empty body. This one is live: SessionStart is how switchdash
+# captures the rollout id.
+#
+# 2. What shape does `tool_response` take for an MCP tool call? Claude Code
+# unwraps the MCP result; Codex forwards the `CallToolResult` envelope, so
+# the payload sits under `structuredContent` / `content[0].text`. The hook
+# enricher handles either shape. switchdash no longer installs a PostToolUse
+# hook for Codex — a session's room comes from the connection switchdash
+# hands it — so this is a record of Codex's delivery contract, kept for when
+# a PostToolUse hook is wanted again, not something shipping code depends on.
+#
+# Runs against an isolated CODEX_HOME so your real ~/.codex is untouched. It
+# does spend one Codex turn on your account. Nothing is written outside the
+# probe directory.
+#
+# Usage: scripts/codex-hook-probe/run.sh [--keep]
+
+set -euo pipefail
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+PROBE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/codex-hook-probe.XXXXXX")"
+CODEX_HOME="$PROBE_DIR/home"
+DUMPS="$PROBE_DIR/dumps"
+KEEP="${1:-}"
+
+# Anything short of a clean run keeps the directory: a probe you cannot inspect
+# after it fails is worse than no probe.
+KEEP_ON_EXIT=1
+cleanup() {
+ # The auth copy goes regardless of why we are exiting — a kept probe
+ # directory is for reading hook dumps, not for leaving credentials in /tmp.
+ rm -f "$CODEX_HOME/auth.json"
+ if [ "$KEEP" = "--keep" ] || [ "$KEEP_ON_EXIT" = "1" ]; then
+ echo
+ echo "Probe directory: $PROBE_DIR (auth copy removed)"
+ echo " codex output: $PROBE_DIR/codex.log"
+ echo " hook dumps: $DUMPS"
+ echo " remove with: rm -rf $PROBE_DIR"
+ else
+ rm -rf "$PROBE_DIR"
+ fi
+}
+trap cleanup EXIT INT TERM
+
+mkdir -p "$CODEX_HOME" "$DUMPS"
+
+# Codex resolves credentials from CODEX_HOME, so the isolated home needs a copy.
+# mktemp -d gives 0700; the copy is narrowed to 0600 and removed on every exit
+# path by the trap above, including when the probe directory itself is kept.
+if [ ! -r "$HOME/.codex/auth.json" ]; then
+ echo "error: no ~/.codex/auth.json — run 'codex login' first." >&2
+ exit 1
+fi
+( umask 077 && cp "$HOME/.codex/auth.json" "$CODEX_HOME/auth.json" )
+chmod 600 "$CODEX_HOME/auth.json"
+
+# The hook commands record what Codex actually handed them: the operand count,
+# the first operand, and stdin. Deliberately NOT the commands switchdash
+# generates — this measures the delivery mechanism, not our shell.
+#
+# Built with json.dumps rather than a heredoc: the commands contain quotes, and
+# Codex responds to malformed hooks.json with a warning buried in the transcript
+# and then runs no hooks at all, which reads exactly like "hooks don't fire".
+python3 - "$CODEX_HOME/hooks.json" "$DUMPS" <<'PY'
+import json, sys
+
+out_path, dumps = sys.argv[1], sys.argv[2]
+
+
+def probe(event: str) -> str:
+ meta, stdin = f"{dumps}/{event}.meta", f"{dumps}/{event}.stdin"
+ return (
+ f'printf "argc=%s\\narg1=%s\\n" "$#" "${{1:-<unset>}}" > {meta}; '
+ f"cat > {stdin}"
+ )
+
+
+config = {
+ "hooks": {
+ "SessionStart": [{"hooks": [{"type": "command", "command": probe("session-start")}]}],
+ "PostToolUse": [
+ {
+ "matcher": "mcp__.*__connect_to_room",
+ "hooks": [{"type": "command", "command": probe("post-tool-use")}],
+ }
+ ],
+ }
+}
+
+with open(out_path, "w") as fh:
+ json.dump(config, fh, indent=2)
+PY
+
+python3 -c "import json,sys; json.load(open(sys.argv[1]))" "$CODEX_HOME/hooks.json" \
+ || { echo "error: generated hooks.json is not valid JSON" >&2; exit 1; }
+
+cat > "$CODEX_HOME/config.toml" <<EOF
+[mcp_servers.switch]
+command = "uv"
+args = ["run", "--project", "$REPO_ROOT/core", "python", "$REPO_ROOT/scripts/codex-hook-probe/mcp_probe.py"]
+EOF
+
+echo "Probe home: $CODEX_HOME"
+echo "Running a Codex turn that calls connect_to_room…"
+echo
+
+# `--dangerously-bypass-hook-trust` is required: Codex persists a `trusted_hash`
+# per hook and silently skips any it has not been told to trust, so without it
+# the probe reports "HOOK DID NOT FIRE" for reasons that have nothing to do with
+# what it is measuring. switchdash passes the same flag on every Codex session
+# (see `CODEX_HOOK_TRUST_FLAG` in
+# dash/packages/plugins/src/agents/impl/codex/hooks.ts).
+CODEX_HOME="$CODEX_HOME" codex exec \
+ --dangerously-bypass-approvals-and-sandbox \
+ --dangerously-bypass-hook-trust \
+ --skip-git-repo-check \
+ -C "$PROBE_DIR" \
+ 'Call the connect_to_room tool on the switch MCP server with room_id "r1". Then stop and say DONE. Do not do anything else.' \
+ >"$PROBE_DIR/codex.log" 2>&1 || {
+ echo "codex exec failed; tail of its output:" >&2
+ tail -30 "$PROBE_DIR/codex.log" >&2
+ exit 1
+ }
+
+if grep -q 'failed to parse hooks config' "$PROBE_DIR/codex.log"; then
+ echo "error: Codex rejected the hooks config, so no hook ran:" >&2
+ grep 'failed to parse hooks config' "$PROBE_DIR/codex.log" | sed 's/^/ /' >&2
+ exit 1
+fi
+
+if ! grep -qi 'connect_to_room' "$PROBE_DIR/codex.log"; then
+ echo "warning: the transcript never mentions connect_to_room — the model may" >&2
+ echo " not have called the tool, so PostToolUse would not fire." >&2
+fi
+
+echo "Codex version under test: $(codex --version 2>/dev/null || echo unknown)"
+
+echo "──────────────────────────────────────────────────────────────────────"
+echo "Q1 Payload delivery — expect argc=0 and non-empty stdin"
+echo "──────────────────────────────────────────────────────────────────────"
+fired=0
+for event in session-start post-tool-use; do
+ echo
+ echo "[$event]"
+ if [ -r "$DUMPS/$event.meta" ]; then
+ fired=1
+ sed 's/^/ /' "$DUMPS/$event.meta"
+ bytes=$(wc -c <"$DUMPS/$event.stdin" | tr -d ' ')
+ echo " stdin_bytes=$bytes"
+ else
+ echo " HOOK DID NOT FIRE"
+ fi
+done
+
+if [ "$fired" = "0" ]; then
+ echo
+ echo "Neither hook fired. Last 25 lines of the Codex transcript:"
+ tail -25 "$PROBE_DIR/codex.log" | sed 's/^/ /'
+fi
+
+if [ -s "$DUMPS/session-start.stdin" ]; then
+ echo
+ echo " session-start body keys:"
+ python3 -c "
+import json, sys
+body = json.load(open(sys.argv[1]))
+print(' ', sorted(body))
+for key in ('session_id', 'resource_id', 'resourceId', 'sessionId'):
+ if key in body:
+ print(f' parseCodexHookEvent reads {key!r} -> {body[key]!r}')
+" "$DUMPS/session-start.stdin" || true
+fi
+
+echo
+echo "──────────────────────────────────────────────────────────────────────"
+echo "Q2 tool_response shape — payload direct, or CallToolResult envelope?"
+echo "──────────────────────────────────────────────────────────────────────"
+if [ -s "$DUMPS/post-tool-use.stdin" ]; then
+ python3 - "$DUMPS/post-tool-use.stdin" <<'PY'
+import json, sys
+
+body = json.load(open(sys.argv[1]))
+tr = body.get("tool_response")
+print(f" tool_name : {body.get('tool_name')}")
+print(f" tool_response : {type(tr).__name__}")
+if isinstance(tr, dict):
+ print(f" top-level keys : {sorted(tr)}")
+ if "room_id" in tr:
+ print(" VERDICT : UNWRAPPED — payload is at the top level (Claude-like)")
+ elif "structuredContent" in tr or "content" in tr:
+ print(" VERDICT : ENVELOPE — CallToolResult forwarded intact")
+ else:
+ print(" VERDICT : UNKNOWN — neither payload nor envelope")
+else:
+ print(f" VERDICT : non-dict ({tr!r:.120})")
+print()
+print(" raw tool_response:")
+print(json.dumps(tr, indent=2)[:1500])
+PY
+else
+ echo " no PostToolUse payload captured — see $PROBE_DIR/codex.log"
+fi
+
+# Only a run that answered both questions is clean enough to discard.
+if [ -s "$DUMPS/session-start.stdin" ] && [ -s "$DUMPS/post-tool-use.stdin" ]; then
+ KEEP_ON_EXIT=0
+fi