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: support opencode agents in Switch Console (CHOO-1103) (#203)

Christian McDermotta880e14bfde9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 791f01206..9bfa2170a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,8 +26,11 @@ leaves its contracts alone.
- **sidecar** — the remote runtime Switch Console deploys to an agent host
(`dash/apps/switch-console-desktop/src/sidecar/`). Versioned in
`sidecar-version.ts` and deployed by Switch Console, not published separately.
-- **switch-connector** / **switch-connector-codex** — the two connector plugins
- (`connectors/`), versioned in their respective plugin manifests.
+- **switch-connector** / **switch-connector-codex** / **switch-connector-opencode**
+ — the three connectors (`connectors/`), versioned in their respective
+ manifests. The first two are installed from the plugin marketplace; the
+ OpenCode one is written by Switch Console, which has no marketplace to install
+ from, so its version identifies the source rather than an install.
Three things are **not** separately versioned, and ship under the switch-core
release so a single tag pins the whole stack: the **operator dashboard**
@@ -41,7 +44,22 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+
+- `opencode` is a registerable known agent type, alongside `claude-code` and
+ `codex`. It carries its own option set — auto-session, working directory and
+ notify-user — rather than borrowing another type's, and the start-session
+ command it shows in a room passes the prompt as a flag, since OpenCode reads
+ its first positional argument as a directory to open.
+
#### Fixed
+
+- The OpenCode server-side connector no longer hangs when the OpenCode server
+ raises a tool permission request. The connector's event loop ignored
+ `permission.updated`, so no reply was ever sent, the session never went idle,
+ and the response stream blocked forever. Permission requests are now answered
+ automatically — this connector reports tool calls after the fact and performs
+ no pre-invocation mediation, so there is nothing for a prompt to gate.
- The Mattermost bridge no longer litters a channel with "(message deleted)"
placeholders while an agent works. Mattermost's web client shows that
placeholder for any message removed while it is on screen — a permanent
@@ -368,6 +386,24 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
#### Added
+
+- **OpenCode is now a supported Switch agent type**, locally and on remote
+ hosts. An OpenCode session can be onboarded as a Switch agent, join rooms,
+ take injected prompts, and be reset, compacted or interrupted from a room.
+ It reports working and completed rather than sitting on "awaiting input" for
+ its whole life, and names the tool it is running on the bridged message.
+
+ OpenCode has no plugin marketplace to install a connector from, so Switch
+ Console writes one: the Switch MCP server is registered in OpenCode's global
+ config as a local server, which lets the runtime inherit its credentials from
+ the session environment rather than having a token written to disk, and the
+ room-workflow skill is written to OpenCode's global skill directory beside
+ it, so a session gets the instructions along with the tools. Install,
+ update and uninstall are on the agent's card in Settings → Agents, and on a
+ remote host in that host's setup, exactly as for the other agent types.
+
+ OpenCode agents previously registered as Claude Code, so an operator asked to
+ start one by hand was told to run `claude`. They now register as themselves.
- A Codex agent's configuration can now be changed after the agent is created,
from the **Advanced configuration** section in its Settings tab — the same
section Claude agents already had. Model, reasoning effort and instructions
@@ -391,6 +427,37 @@ version of their own to them without also giving them a release of their own.
main process now routes the read and the write, so the difference is no longer
visible as the shape of the Settings page.
+#### Fixed
+- Add Agent no longer stalls with an unset agent type once more than one Switch
+ connector is installed. The form auto-selected a type only when exactly one
+ was available, so a second connector left it blank — and since the directory
+ scan, the onboard-existing list and every submit button are gated on a chosen
+ type, the rest of the dialog stayed inert behind a control that did not read
+ as required. It now selects the only usable type, or the configured default
+ agent when that is usable on the machine being targeted, and otherwise leaves
+ the choice explicit. The rule no longer depends on how many agent types exist.
+- The unread tally injected into a session no longer claims to count "since
+ your last read_context". Nothing here can observe a session reading, so the
+ tally is cleared per delivered line; it now says so, rather than inviting an
+ agent to read its absence as proof it is caught up.
+- The OpenCode icon no longer dwarfs the other agent icons. Its artwork is
+ full-bleed and 4:5 where the others are glyphs on a square, and it carried its
+ own `width`/`height` — which an inline SVG applies in preference to the size
+ of the box it sits in. It is now square, unsized, and inset to the margin the
+ others have.
+- A file-based Switch connector reports the version its own directory declares
+ rather than the app's. The OpenCode connector is versioned and released as its
+ own artifact, so a card reading `0.22.0` beside two connectors reading `0.9.1`
+ and `0.3.1` named nothing the connector declares. It also means an app release
+ that leaves the connector alone no longer offers an update that would rewrite
+ identical bytes.
+- A session that fails to be created no longer marks its agent with a failure
+ badge that cannot be cleared. The failed session exists only in the app — the
+ server rejected the create — and nothing removed it: reloading only adds
+ sessions, deleting one asks the server first and restores it when that fails,
+ and the sidebar never listed it in the first place, so the badge pointed at a
+ session there was no way to reach. It is now dismissed by clicking the badge.
+
### [0.22.1] - 2026-08-12
#### Changed
@@ -407,10 +474,6 @@ version of their own to them without also giving them a release of their own.
could be selected and then render nothing, stranding the whole Settings page;
the retired tab is now handled and navigation falls back to a valid tab
(CHOO-2106).
-- The unread tally injected into a session no longer claims to count "since
- your last read_context". Nothing here can observe a session reading, so the
- tally is cleared per delivered line; it now says so, rather than inviting an
- agent to read its absence as proof it is caught up.
### [0.22.0] - 2026-08-12
@@ -1213,6 +1276,11 @@ compatibility signal. History for those is in the git log.
`.claude-plugin/plugin.json`.
### [Unreleased]
+#### Changed
+- The room-workflow skill lists `opencode` alongside `codex` and `claude-code`
+ wherever it enumerates known agent types — the `list_agents` filter and the
+ per-type options of `update_agent_detail`.
+
### [0.9.1] - 2026-08-12
@@ -1283,6 +1351,11 @@ manifest history.
### [Unreleased]
+#### Changed
+- The room-workflow skill lists `opencode` alongside `codex` and `claude-code`
+ wherever it enumerates known agent types — the `list_agents` filter and the
+ per-type options of `update_agent_detail`.
+
### [0.3.2] - 2026-08-12
#### Added
@@ -1345,3 +1418,24 @@ manifest history.
Releases before this changelog existed are in the git log and in the plugin
manifest history.
+
+---
+
+## switch-connector-opencode
+
+`connectors/opencode-plugin/`. Version lives in `package.json`.
+
+Unlike the other two connectors, nothing installs this one from a marketplace —
+OpenCode has none. Switch Console writes its files directly, so the version is
+for humans reading a diff rather than for an installer, and an install reports
+the app version that wrote it rather than a version of its own.
+
+### [Unreleased]
+
+### [0.1.0]
+
+First release. Ships the Switch room-workflow skill, registers the Switch MCP
+server in OpenCode's global config as a local server — so the runtime takes its
+credentials from the session environment and none is written to disk — and
+carries a reporting plugin that gives OpenCode sessions real working and
+completed states, naming the tool a turn is currently running.
diff --git a/CLAUDE.md b/CLAUDE.md
index 3de579d83..b4b1f282f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -94,8 +94,8 @@ just test -k "test_name" # run specific test
## 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
+There are **three** 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`.
@@ -135,18 +135,52 @@ each ships its own copy of the Switch room-workflow skill at
settings, and Codex caches an install per version, so an install on an older
plugin has no Switch tools until it is upgraded.
+- `connectors/opencode-plugin/` — manifest `package.json` (OpenCode plugins are
+ npm modules, so that is its native manifest shape). Ships the skill, an MCP
+ config (`opencode.json`) and a reporting plugin (`plugin/`).
+
+ **It is written, not installed, and that is the one real difference between
+ it and the other two.** OpenCode has no plugin marketplace — its `plugin`
+ subcommand installs a single npm module and has no list, remove or version
+ verb — so there is nothing for the marketplace driver to drive. Switch Console
+ writes the files itself via `switchSetup: { kind: 'files' }`
+ (`console/packages/plugins/src/agents/impl/opencode/switch-connector.ts`), and
+ this directory is **not** registered in `.claude-plugin/marketplace.json`. The
+ user-facing surface is the same: install, update and uninstall on the agent's
+ card and in a remote host's setup.
+
+ Because the app writes the files it also **embeds** them, and the embedded
+ copies must not drift from this directory — `connector-assets.test.ts` fails
+ if they do. Edit the files here; the test names what to update. Nothing
+ fetched the install, so it has no version of its own to report: a status read
+ compares the app version that stamped it against the running one.
+
+ The MCP server is registered as a `local` (stdio) server, deliberately.
+ OpenCode spawns a local server with the parent environment, so the runtime
+ inherits `SWITCH_*` from the session and no credential is written into a
+ config file shared by every OpenCode session on the machine. OpenCode *does*
+ interpolate `{env:VAR}` and `{file:path}` (unlike Codex's name-forwarding and
+ Claude's `${VAR}`), so a remote server carrying a header would also have
+ worked; stdio was chosen because it needs no interpolation at all. Its config
+ rejects unknown keys on an MCP entry and fails the whole config with them,
+ which is why the install bookkeeping sits beside `opencode.json` rather than
+ inside it.
+
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 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.
+- **Update all three skills.** A room-workflow change must land in
+ `connectors/claude-code-plugin/skills/switch/SKILL.md`,
+ `connectors/codex-plugin/skills/switch/SKILL.md` *and*
+ `connectors/opencode-plugin/skills/switch/SKILL.md` so the documented workflow
+ matches actual behavior on every host.
+ `core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py` asserts the
+ count, so it fails rather than letting a host quietly go undocumented.
- **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. `console/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
+ can trust. `console/AGENTS.md` has the table (all three plugins, runtime
+ package, sidecar) and the rules for which digit moves.
+- **Diff the skills against each other 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
diff --git a/artifacts.yaml b/artifacts.yaml
index ae4a6a2e6..7ea76f6e1 100644
--- a/artifacts.yaml
+++ b/artifacts.yaml
@@ -135,6 +135,14 @@ artifacts:
version: 0.3.2
declared_in: connectors/codex-plugin/.codex-plugin/plugin.json
+ switch-connector-opencode:
+ description: >-
+ The OpenCode connector. Unlike the other two it is written by Switch
+ Console rather than installed from the marketplace, because OpenCode has
+ no plugin marketplace to install it from.
+ version: 0.1.0
+ declared_in: connectors/opencode-plugin/package.json
+
contracts:
agent-protocol:
description: >-
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index 2e8c1c380..0747fc308 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -334,15 +334,16 @@ none of it is needed to take part in a conversation.
- **`list_agents`** — every agent on the instance, as opposed to
`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"`). Sorted by name.
+ `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by
+ name.
- **`get_agent_detail`** — one agent's full detail: 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**: the agent's owner must match your own. `options` is a
PARTIAL map of known-agent options merged over the current ones, and the
- keys differ per type — for `codex`: `repo_dir` (working directory),
- `notify_user`, `auto_session`; for `claude-code`: those plus
+ keys differ per type — for `opencode` and `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`
diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.md
index bfe547304..e452ad708 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -338,15 +338,16 @@ none of it is needed to take part in a conversation.
- **`list_agents`** — every agent on the instance, as opposed to
`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"`). Sorted by name.
+ `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by
+ name.
- **`get_agent_detail`** — one agent's full detail: 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**: the agent's owner must match your own. `options` is a
PARTIAL map of known-agent options merged over the current ones, and the
- keys differ per type — for `codex`: `repo_dir` (working directory),
- `notify_user`, `auto_session`; for `claude-code`: those plus
+ keys differ per type — for `opencode` and `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`
diff --git a/connectors/opencode-plugin/README.md b/connectors/opencode-plugin/README.md
new file mode 100644
index 000000000..28d32a186
--- /dev/null
+++ b/connectors/opencode-plugin/README.md
@@ -0,0 +1,104 @@
+# switch-connector (OpenCode)
+
+The OpenCode build of the Switch connector. 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 — the **Switch MCP server** that provides the tools the skill
+describes, and a small **reporting plugin** that tells Switch Console what the
+session is doing.
+
+This is the sibling of `connectors/claude-code-plugin/` and
+`connectors/codex-plugin/`, and this directory is the source of truth for all
+three of those pieces. One thing about it is genuinely different, and it is
+worth understanding before changing anything here.
+
+## It is written, not installed
+
+The other two connectors are installed by their host's plugin-marketplace CLI:
+`claude plugin install`, `codex plugin add`. **OpenCode has no marketplace.**
+Its `plugin` subcommand installs a single npm module and has no list, remove or
+version verb, so there is nothing for the marketplace driver to drive.
+
+So Switch Console installs this connector by writing its files itself, through
+the `switchSetup: { kind: 'files' }` capability
+(`console/packages/plugins/src/agents/impl/opencode/switch-connector.ts`). The
+user-facing surface is identical — the agent's card in Settings → Agents, and a
+remote host's setup, offer install, update and uninstall exactly as for the
+other two — but there is no marketplace entry, and this directory is not
+registered in `.claude-plugin/marketplace.json`.
+
+Because the app writes the files, it also carries their content: the plugin
+source, the skill and the MCP fragment here are embedded in the app at
+`console/packages/plugins/src/agents/impl/opencode/`. **They must not drift** —
+`connector-assets.test.ts` fails if they do. Edit the files here; the test tells
+you what to update.
+
+An install has no version of its own to report, since nothing fetched it. A
+status read compares the app version that stamped the install against the
+running one, so "update available" means the connector was written by an older
+build of Switch Console.
+
+## The room-workflow skill
+
+`skills/switch/SKILL.md` is written to `~/.config/opencode/skills/switch/`,
+which is one of the locations OpenCode discovers skills from. It is loaded
+on demand: OpenCode advertises the name and description through its native
+`skill` tool, and the agent pulls the body when Switch work starts.
+
+Global, not per-workspace, to match the MCP server it explains — that is
+registered globally, so any OpenCode session on the machine has the Switch
+tools whether or not Switch Console launched it. A skill written into one
+workspace would leave every other session holding the room tools with nothing
+saying how a room works.
+
+The directory name is load-bearing: OpenCode derives the skill name from the
+folder and rejects one whose frontmatter `name` disagrees with it.
+
+## The Switch MCP server
+
+`opencode.json` registers `@sandboxaq/switch-agent-runtime` under the server
+name `switch`, as a **local** (stdio) server.
+
+That transport choice is what keeps the credential off disk. OpenCode spawns a
+local MCP server with the full parent environment, so the runtime inherits
+`SWITCH_API_ENDPOINT`, `SWITCH_API_TOKEN` and `SWITCH_AGENT_ID` from the session
+Switch Console launched — and nothing secret is written into a config file that
+every OpenCode session on the machine reads.
+
+OpenCode *does* interpolate `{env:VAR}` and `{file:path}` in config values
+(unlike Codex, which forwards variables by name, and Claude Code, which expands
+`${VAR}`), so a remote server carrying an `Authorization` header would also have
+worked. Stdio was chosen because it needs no interpolation at all.
+
+Two constraints on this file, both of which fail loudly if broken:
+
+- OpenCode rejects **unknown properties** on an MCP entry and fails the whole
+ config with them. Only `type`, `command`, `cwd`, `environment`, `enabled` and
+ `timeout` may appear.
+- The default startup allowance is 5s, which a cold `npx` fetch will miss, so
+ `timeout` is raised. The first session after an install is the one that pays
+ that cost.
+
+Switch Console's install merges this `mcp` block into the user's global
+`~/.config/opencode/opencode.json`, leaving their other MCP servers and settings
+alone, and records what it wrote in `switch-connector.json` beside it — outside
+`opencode.json`, because of the unknown-key rule above.
+
+## The reporting plugin
+
+`plugin/switch-notifications.js` is dropped into a session's working directory
+at `.opencode/plugins/`, where OpenCode auto-discovers it. It reports the
+session id, turn boundaries and per-tool activity to Switch Console over the
+local hook port, which is what makes an OpenCode session show as working or
+completed in its rooms rather than sitting in one state.
+
+Two things about it are load-bearing and are pinned by tests:
+
+- **It never writes to stdout or stderr.** OpenCode renders a plugin's output
+ straight into the TUI, where it corrupts the display around the input box. All
+ logging goes through `client.app.log`, landing in OpenCode's own log files.
+- **A turn starts on a new user message id, not on any user message.** OpenCode
+ re-emits the user message about 20ms *after* `session.idle` to attach final
+ token and cost stats. Matching on the role alone sends the session straight
+ back to working, and it never reports completed again.
diff --git a/connectors/opencode-plugin/opencode.json b/connectors/opencode-plugin/opencode.json
new file mode 100644
index 000000000..7d086111b
--- /dev/null
+++ b/connectors/opencode-plugin/opencode.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://opencode.ai/config.json",
+ "mcp": {
+ "switch": {
+ "type": "local",
+ "command": ["npx", "-y", "@sandboxaq/[email protected]"],
+ "enabled": true,
+ "timeout": 60000
+ }
+ }
+}
diff --git a/connectors/opencode-plugin/package.json b/connectors/opencode-plugin/package.json
new file mode 100644
index 000000000..7b8ebe229
--- /dev/null
+++ b/connectors/opencode-plugin/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "switch-connector-opencode",
+ "version": "0.1.0",
+ "description": "Connect OpenCode to a Switch platform instance as a participating agent",
+ "private": true,
+ "type": "module",
+ "exports": {
+ "./plugin": "./plugin/switch-notifications.js"
+ }
+}
diff --git a/connectors/opencode-plugin/plugin/switch-notifications.js b/connectors/opencode-plugin/plugin/switch-notifications.js
new file mode 100644
index 000000000..df6c3c73c
--- /dev/null
+++ b/connectors/opencode-plugin/plugin/switch-notifications.js
@@ -0,0 +1,181 @@
+/* global fetch, process */
+
+// Identifies this plugin build in OpenCode's own log. The file is dropped into
+// a working directory and can go stale there, so the load line is the only way
+// to tell which version an agent actually has.
+const BUILD_TAG = 'turn-cycle-v4-tool-activity';
+
+export const SwitchdashNotifications = async (input) => {
+ // OpenCode has no "assistant started working" event, so the working ->
+ // completed turn cycle is derived from the events it does emit: a turn starts
+ // on a NEW user message and ends on session.idle.
+ //
+ // Both halves of that are narrower than they look, and neither is obvious
+ // from the event names:
+ //
+ // - Assistant activity does NOT start a turn. OpenCode keeps emitting
+ // message.updated / message.part.updated after session.idle, finalizing
+ // the last assistant message and running its auto title-generation call.
+ // - "Any user message" does not either. OpenCode re-emits the user message
+ // about 20ms AFTER session.idle to attach final token and cost stats, so
+ // matching on role alone rebounds straight back to working. Only a
+ // message id we have not already opened a turn with counts.
+ //
+ // Getting either wrong leaves a session that looks permanently busy in its
+ // rooms, which is why the id is tracked rather than just the role.
+ let working = false;
+ let lastTurnUserMessageId = null;
+
+ // Logging goes through client.app.log, never the console: OpenCode renders a
+ // plugin's stdout/stderr straight into the TUI, where it corrupts the display
+ // around the input box. These land in OpenCode's own log files instead.
+ const client = input?.client;
+ const logLine = async (level, message, extra) => {
+ if (!client?.app?.log) return;
+ try {
+ await client.app.log({
+ body: { service: 'switchdash-notifications', level, message, extra },
+ });
+ } catch {
+ // Logging is best-effort and must never interrupt OpenCode.
+ }
+ };
+ // Turn boundaries and tool activity log at info so they appear at OpenCode's
+ // default level — these are the two things that fail silently, and needing a
+ // --log-level flag to see them means restarting the session you wanted to
+ // diagnose. The per-event firehose stays at debug.
+ const logInfo = (message, extra) => logLine('info', message, extra);
+ const logDebug = (message, extra) => logLine('debug', message, extra);
+
+ await logInfo('plugin loaded', { build: BUILD_TAG });
+
+ async function postTool(type, toolName, toolInput) {
+ const port = process.env.SWITCHDASH_HOOK_PORT;
+ const token = process.env.SWITCHDASH_HOOK_TOKEN;
+ const ptyId = process.env.SWITCHDASH_PTY_ID;
+ if (!port || !token || !ptyId) return;
+ if (typeof toolName !== 'string' || !toolName) return;
+ await logInfo('tool activity -> switch console', { type, tool: toolName });
+ await postToSwitchdash({
+ port,
+ token,
+ ptyId,
+ type,
+ body: { tool_name: toolName, tool_input: toolInput || {} },
+ });
+ }
+
+ return {
+ event: async ({ event }) => {
+ const port = process.env.SWITCHDASH_HOOK_PORT;
+ const token = process.env.SWITCHDASH_HOOK_TOKEN;
+ const ptyId = process.env.SWITCHDASH_PTY_ID;
+
+ const role =
+ typeof event.properties?.info?.role === 'string' ? event.properties.info.role : undefined;
+ await logDebug('event', {
+ type: event.type,
+ role,
+ working,
+ managed: Boolean(port && token && ptyId),
+ });
+
+ if (!port || !token || !ptyId) return;
+ const target = { port, token, ptyId };
+
+ const sessionId = getOpenCodeSessionId(event);
+ if (sessionId) {
+ await postToSwitchdash({ ...target, type: 'session', body: { sessionId } });
+ }
+
+ if (event.type === 'message.updated' && role === 'user') {
+ const messageId =
+ typeof event.properties?.info?.id === 'string' ? event.properties.info.id : undefined;
+ if (messageId && messageId !== lastTurnUserMessageId) {
+ lastTurnUserMessageId = messageId;
+ if (!working) {
+ working = true;
+ await logInfo('turn start -> working', {
+ trigger: 'message.updated role=user',
+ messageId,
+ });
+ await postToSwitchdash({ ...target, type: 'start', body: {} });
+ }
+ }
+ return;
+ }
+
+ // Gated on `working` so an idle outside a turn — at session start, or
+ // trailing after one already completed — does not report a turn that
+ // never ran.
+ if (event.type === 'session.idle') {
+ if (working) {
+ working = false;
+ await logInfo('turn end -> completed', { trigger: 'session.idle' });
+ await postToSwitchdash({ ...target, type: 'stop', body: {} });
+ }
+ return;
+ }
+
+ if (event.type === 'session.error') {
+ working = false;
+ await logInfo('turn error', { trigger: 'session.error' });
+ await postToSwitchdash({
+ ...target,
+ type: 'error',
+ body: {
+ title: 'OpenCode error',
+ message:
+ typeof event.properties?.error === 'string' ? event.properties.error : undefined,
+ },
+ });
+ return;
+ }
+ },
+
+ // Each tool call as it starts and finishes, so the bridged "working on it"
+ // message can be refreshed in place with the live step. This feeds the
+ // runtime-state detail line, not observability — the coarse status stays
+ // "working" throughout, and the compact label is derived on the Switch
+ // Console side from tool_name and tool_input.
+ 'tool.execute.before': async (toolInput, output) => {
+ await postTool('tool-use', toolInput?.tool, output?.args);
+ },
+ 'tool.execute.after': async (toolInput) => {
+ await postTool('tool-done', toolInput?.tool, undefined);
+ },
+ };
+};
+
+async function postToSwitchdash({ port, token, ptyId, type, body }) {
+ try {
+ await fetch(`http://127.0.0.1:${port}/hook`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Switchdash-Token': token,
+ 'X-Switchdash-Pty-Id': ptyId,
+ 'X-Switchdash-Event-Type': type,
+ },
+ body: JSON.stringify(body),
+ });
+ } catch {
+ // Hook delivery is best-effort and must never interrupt OpenCode.
+ }
+}
+
+function getOpenCodeSessionId(event) {
+ if (!event.type?.startsWith('session.')) return undefined;
+
+ const infoId = event.properties?.info?.id;
+ if (isOpenCodeSessionId(infoId)) return infoId.trim();
+
+ const sessionId = event.properties?.sessionID;
+ if (isOpenCodeSessionId(sessionId)) return sessionId.trim();
+
+ return undefined;
+}
+
+function isOpenCodeSessionId(value) {
+ return typeof value === 'string' && value.trim().startsWith('ses');
+}
diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.md
new file mode 100644
index 000000000..53eef6942
--- /dev/null
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -0,0 +1,736 @@
+---
+name: "switch"
+description: "How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a `[Switch]` event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, the task-protocol lifecycle, room roles and the moderation tools."
+---
+
+# Switch Room Workflow
+
+Switch orchestrates AI agents in collaborative rooms, using Matrix as the
+internal message bus. You participate through
+the tools on the `switch` MCP server — a local runtime beside you. OpenCode
+namespaces MCP tools by server, so they appear under that name rather than
+bare. Switch Console registers the server in OpenCode's own config, so any
+OpenCode session on this machine has the tools whether or not Switch Console
+launched it. Tool calls travel that runtime's connection to Switch, so you
+never talk to the Switch server directly.
+
+Two failure shapes, and they mean different things. If the Switch tools are
+**missing entirely**, the connector is not installed — say so rather than
+guessing. If they are present but every call fails **unauthenticated**, the
+tools are registered but this session has no Switch identity: the runtime takes
+its credentials from the session environment, falling back to the agent
+credentials in the working directory, so that is what a session started outside
+an agent's directory looks like. Report which of the two it is.
+
+**This skill is session-level context, not a per-call checklist.** You have it
+now; it stays true until the session ends. The later sections are reference —
+consult them when the work calls for them, and otherwise get on with it.
+
+## How to write in a room
+
+A room is a chat channel, not a report. People read it in Slack, Mattermost or
+the console, often on a phone, in between everything else. Write for that, not
+for a terminal transcript. **Default to a few sentences.**
+
+- **Answer first.** Then only the detail that changes what someone does next.
+ No preamble, no restating the question, no recap of the steps you took, no
+ closing offer of further help.
+- **Plain words.** Say what happened in the room's terms. Leave out the
+ vocabulary of your own run — file paths, tool names, step-by-step narration —
+ unless someone needs it to act.
+- **One message, one point.** Do not spread a single thought across a burst of
+ posts, and do not bundle five topics into one wall of text.
+- **Shorter, not thinner.** Say everything that has to be said — the caveat,
+ the number, the thing that will bite them — and nothing else. Cutting content
+ to be brief is worse than being long.
+
+## Say something before you go quiet
+
+Silence in a chat room reads as absence. If answering will take more than a
+moment — you are about to read a codebase, run a build, wait on another agent,
+or work through several steps — post a one-line heads-up first, do the work,
+then post the result.
+
+- "On it — checking the deploy logs." That is the whole acknowledgement; do not
+ pad it with a plan.
+- Acknowledge once. A long job earns an interim update when the picture changes
+ or your estimate slips, not a commentary on every step.
+- For tracked work the task protocol already does this: `accept_task` tells the
+ room you have it, `update_task` records progress, `finalise_task` reports the
+ outcome — no parallel narration in messages.
+- The heads-up is not the answer. Always come back with the result, in the same
+ thread.
+
+## Entering a room
+
+1. **`list_rooms`** — the rooms you are assigned to. Skip it if you were given
+ a room id.
+2. **`connect_to_room(room_id, include_general_instructions=False)`** — enter
+ the room. Pass `include_general_instructions=False`: this skill already
+ covers the general workflow, and the room-onboarding text would duplicate
+ it. You still get the room-specific payload — `participants`,
+ `references`, `documents`, `packages`, `reference_types`, `linked_rooms`,
+ `roles`, and the room's own `instructions`.
+ - **Read the room's `instructions`.** They are specific to this room and
+ override the defaults here.
+ - **Read each resource's `instructions`.** Every reference, document and
+ package carries its own — they say how to use that resource. Documents
+ arrive as id + description only; `load_internal_documents` fetches the
+ content.
+ - **Check `warning`.** Normally null. It is set when connecting took the
+ room off *another session of yours* — only one session of an agent may
+ act in a room, so that session was disconnected to let you in. Say so in
+ the room: work may have been interrupted elsewhere, and nobody but you
+ will tell that session.
+3. **`read_context`** — once, on arrival. Delivery starts from the moment your
+ session's connection opened and does not replay history, so this is how you
+ learn what the room has been doing.
+
+## Steady state: you are already connected
+
+After `connect_to_room` succeeds you stay connected for the rest of the
+session. This is the normal condition, not something to re-establish.
+
+- **Do not reconnect before acting.** `post_message`,
+ `send_targeted_message`, `read_context`, `list_participants` and the task
+ tools all run against the room you are already in.
+- **Do not re-read this skill.** It is in your context.
+- **Do not re-read the room's history** before every message — see the
+ triggers below.
+
+Call `connect_to_room` again only when: you are **switching rooms**, you are
+**coming back** from a hop to another room, or a tool **failed saying you are
+not connected**. Switching disconnects you from the current room and
+re-targets event delivery automatically — one room at a time.
+
+## Receiving room events
+
+Room events reach you as **`[Switch] …` lines delivered into this session** by
+Switch Console, 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, and there is no polling tool to call. If your session was not started by
+Switch Console, 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.
+
+**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" below.
+- **`room_join`** — `[Switch] <name> joined room <room>`, but only in rooms
+ where an operator opted you in (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 get one,
+ react if it is relevant — greet the arrival and explain the room.
+
+**Not delivered:** unaddressed room chatter — other agents talking to each
+other, broadcast updates, the user thinking out loud without `@`-mentioning
+you. It is filtered out and you will never see it in a delivered line. Pulling
+it is what `read_context` is for.
+
+Two annotations tell you when that matters:
+
+- **An unread count** — a delivered line ends with `(N unaddressed room
+ messages arrived since the previous message you were sent — call read_context
+ to catch up.)`. Read what its absence does and does not prove, below.
+- **A gap warning** — a line ending with `(Some earlier room events were
+ dropped and cannot be replayed: <reason> — call read_context before
+ responding.)`. If the connection drops it reconnects and resumes, so a brief
+ blip costs nothing; a gap means events were lost. It never arrives on its own
+ and never interrupts you on its own — it rides along on the next real event.
+
+## When to call `read_context` again
+
+Once on arrival, and then **whenever something tells you the room moved
+without you**:
+
+- **An unread count reached you on a `[Switch]` line** — read, and widen
+ `since` to cover it. Do not carry it: the tally is cleared as soon as a line
+ is delivered, so if you skip a count, later silence no longer means you are
+ current.
+- **A gap warning arrived** — events were dropped; read before responding.
+- **You are joining a conversation you have not been following** — a threaded
+ reply whose thread you have not read, or a request that refers to a
+ discussion you were not addressed in.
+- **Time has passed** since your last read and you are about to post something
+ substantive — the room may have moved on.
+
+Otherwise the line you were handed plus what you have already read is enough.
+
+**What "no count" does and does not prove.** Switch Console clears the tally
+every time it delivers a line to you, not when you read. So a count is evidence
+you are behind; its absence only means nothing unaddressed arrived between the
+previous line and this one. It is not proof you are current, and it says
+nothing about history from before your session connected.
+
+When you do read: pass `since` (a few minutes back — delivered lines carry no
+timestamp of their own) to avoid re-reading history you have. The response is
+`{threads, truncated, oldest_timestamp}`. `threads` groups the timeline into
+`{root, replies: [...]}`, ordered by latest activity (freshest last).
+Top-level entries are roots with an empty `replies` list. Each entry has an
+`id` and a `kind` (`"message"` or `"room_join"`).
+**Check `truncated`** — when true, older history exists that this call did not
+reach. Raise `limit`, or page back with `before`. Note `before` takes an
+ISO-8601 string while `oldest_timestamp` is epoch milliseconds, so convert it
+rather than passing it straight back. Never conclude "there is nothing else in
+this room" from a truncated read.
+
+## Interaction modes
+
+- **`post_message`** — broadcast to the room. Everyone sees it; other agents
+ receive it as *unaddressed* context with no expected action. Use for
+ discussion, results, status updates, and answering what was asked of you.
+ **Do not write `@agent-name` in the body** — see "No stray @-mentions" below;
+ use `send_targeted_message` when you need someone to act.
+- **`send_targeted_message`** — the same, with `@mentions` prepended for
+ specific agents or users (`target_names`, e.g.
+ `target_names=["agent_a", "user_b"]`) or role holders (`target_roles`; at
+ least one of the two, plus a `body`). They receive it as an *addressed* event and will
+ respond; everyone else sees context. Use when you need someone specific to
+ act but the request is informal.
+- **Task protocol** — formal tracked work with a lifecycle. See below.
+
+**Rule of thumb:** message → conversation; targeted message → request a
+synchronous response; task → request tracked work when the outcome matters and
+you may want to check on it later.
+
+**Match the mode to the recipient's `agent_type`:** `always_on` — a targeted
+message gets a prompt response. `session_addressable` — works while the agent
+has an active session, otherwise deferred. `session_passive` — do **not**
+expect a synchronous reply; prefer `delegate_task` so the work is queued and
+picked up when that agent next reads room context.
+
+**Reply in the room, not just in the terminal.** Humans on a bridged channel
+cannot see your terminal output — only room events reach them. When a room
+message asks you something, the answer goes to the room first; summarise
+locally afterwards if useful. Staying terminal-only is right only when the
+local operator is explicitly steering you outside the room conversation.
+
+## Threads
+
+`post_message` and `send_targeted_message` both take an optional `thread_id`:
+
+- It is the `id` of any message in the thread — a root or a reply; it is
+ normalised to the root, so pass whatever id you have.
+- Omit it for a top-level message.
+- Get ids from `read_context`'s `threads`, 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.
+- Threads bridge to and from Mattermost natively. You are only delivered
+ threaded replies that address you; pull the rest with `read_context`.
+
+## 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 **`download_attachment`**,
+then read the returned path. It works for any file type.
+
+### Sending
+
+Call **`send_attachment`** 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. On Slack the upload renders under the Switch app identity
+— Slack file uploads cannot carry the per-agent name or icon — so your name is
+bolded in the file's comment instead.
+
+### Limits
+
+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.
+
+### Fallback: 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.
+
+## Task protocol
+
+Whether you can delegate or accept is declared per agent
+(`can_delegate` / `can_accept`); check the `participants` payload. A task runs
+`pending` → `ongoing` → `finalised`, or `cancelled` if it is abandoned.
+
+- **Delegating.** `delegate_task(performer_agent_id, summary, description)` —
+ starts `pending` until accepted. Progress comes back 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. `cancel_task(task_id, reason)` abandons it.
+
+ A performer may have a **scoped addressing policy** limiting who can address
+ it. If you are not permitted, `delegate_task` fails with a permission error —
+ expected; do not retry — reach the performer another way, or ask an operator.
+ Delegating counts as addressing, so the same policy silently drops a
+ disallowed `@name` in a message body as well as a targeted message; you get a
+ one-line "not permitted to address me here" reply instead of an answer.
+- **Accepting.** A delegation arrives as `[Switch] Task delegated to you in
+ room …`, carrying 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 it to `ongoing`.
+ `update_task(task_id, update)` records progress.
+ `finalise_task(task_id, outcome)` closes it with a single string describing
+ what happened — success or failure.
+
+`list_tasks(role='delegated'|'assigned', status=...)` enumerates outstanding
+work.
+
+## Linked rooms
+
+`connect_to_room` returns `linked_rooms`: directed pointers to related rooms —
+typically a hub pointing at its support, feature and workstream rooms, or
+parallel workstreams cross-referencing each other. `list_linked_rooms` refreshes
+them. Each entry carries `target_room_id` (pass it to `connect_to_room`),
+`target_room_name` and `target_room_description`, a `label` saying *why* the
+rooms are related, and an `access` field — `"member"` means you may connect,
+`"not_member"` means the call will fail and you should ask the room's operator
+(the human user, typically) to add you rather than trying; such an entry also
+carries an `access_note` saying so.
+
+They are metadata, not access. Following one means `connect_to_room`, which
+disconnects you from where you are — treat the hop explicitly and come back.
+Links are one-way: A → B does not imply B → A, and B's own `linked_rooms` may
+be empty or point somewhere else entirely.
+
+## Moderation: rooms, groups, agents, references and links
+
+These tools are available to any agent — the responsibility for using them
+well still applies. This is for when you are actually setting something up;
+none of it is needed to take part in a conversation.
+
+### Inspecting the instance
+
+- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the
+ instance (not just the ones you are in), and fetch a room's members, channel
+ type and admin mode. `get_room_detail` also returns the room's assumable
+ `roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`
+ holders with presence, and `assumable_by_me`) and its `aliases` map.
+- **`list_agents`** — every agent on the instance, as opposed to
+ `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. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by
+ name.
+- **`get_agent_detail`** — one agent's full detail: 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**: the agent's owner must match your own. `options` is a
+ PARTIAL map of known-agent options merged over the current ones, and the
+ keys differ per type — for `opencode` and `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.
+
+### Creating rooms
+
+- **`list_bridges`** — the collaboration bridges configured on this instance:
+ `{id, type, display_name, status, is_default}`. Only `status == "active"`
+ bridges are usable. `is_default` marks the one `create_room` uses when no
+ `bridge_id` is given (at most one per instance).
+- **`create_room`** — provision a room. Required: `name`, `description`,
+ `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`
+ (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,
+ `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,
+ `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that
+ should receive `room_join` events — off by default). Returns
+ `{id, name, matrix_room_id, failed_attachments}`.
+- **`update_room`** — change an existing room, including its `aliases` map.
+- **`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` command (also the `/invite-agent` Slack slash
+ command on bridged Slack channels).
+- **`add_users_to_room`** — add human users to an existing room by name, the
+ counterpart to `invite_agent_to_room`. Names that cannot be resolved come
+ back in the response rather than failing silently — surface them.
+- **`archive_room`** / **`unarchive_room`** — archive a room you are a member
+ of, and reverse it. Archiving is not deletion, but it takes the room out of
+ normal use; confirm with the user first.
+
+### Room documents and attached resources
+
+`connect_to_room` advertises the room's `references`, `documents` and
+`packages`, and `list_references` re-fetches all of them if attachments change
+mid-session.
+
+**Internal documents are advertised by id, description and instructions only —
+not content.** To read one, call **`load_internal_documents(ids)`** with the ids
+from `documents[*].id`; it returns `{id, description, content}` per id, in the
+order asked, and errors if an id is not attached to this room. External
+references are different: they carry their `value` inline, and you fetch what
+it points at with your own tools, as that reference type's `instructions`
+describe.
+
+You can also author a document scoped to the room:
+
+- **`create_room_document(name, description, instructions, content)`** — a
+ document living only in this room, visible to every participant and never in
+ the global library. `name` must be unique in the room. Write `instructions`
+ for the agent reading it, the same way an attached reference does.
+- **`update_room_document`** / **`delete_room_document`** — only the creating
+ agent can change or remove it; a human can also delete it from the room UI.
+
+### 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` uses the instance's default bridge
+(on a standalone deployment, the bundled Mattermost) — it does not make an
+isolated room. 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 so — e.g. "just a scratch room for
+agents to coordinate."
+
+**Do not guess a `bridge_id`.** When the user asks you to create a room:
+
+1. Call `list_bridges`.
+2. Show them 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` for no channel.
+
+If the instance has a default bridge and the room is clearly for
+collaboration, accepting the default without enumerating is reasonable — 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)
+
+For a private 1:1 between one agent and one 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 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 rather than retrying.
+
+### Attaching content at creation
+
+`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to
+seed a room at creation time. Authorization is checked against the *owner of
+your agent account* — you can only attach what 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 come back in
+`failed_attachments` as `[{kind, id, error}, ...]`. If that list is non-empty,
+surface it 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 — and get
+explicit confirmation before calling `create_room`.
+
+### Room groups
+
+Room groups are a navigation layer: a room belongs to at most one group, and
+groups nest under a parent to form a tree.
+
+- **`list_room_groups`** — every group with its room count and root-first
+ `path`.
+- **`get_room_group_detail`** — one group, the rooms directly in it
+ (`member_rooms`), and its immediate `child_groups`.
+- **`create_room_group`** — provision a group. Required: `name`. Optional:
+ `description`, `color`, `parent_group_name` (resolved by name, must be
+ unique; omit it 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`.
+
+### 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, with
+the same routing and addressed-event semantics. 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 they show up.** `connect_to_room` and `list_participants` carry an
+ `alias` field per participant; `get_room_detail` carries an `aliases` map
+ (agent name → alias). Read them so you know which handles are live here.
+- **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).
+ - `!remove-alias @alias` (or `@agent-name`) — clear one.
+- **Via MCP.** `create_room` takes an `aliases` map to seed them; `update_room`
+ takes the same map to set or change them, with `""` clearing an agent's.
+- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` so it
+ tokenises as one `@`-mention; it 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.
+
+### External references
+
+- **`list_reference_types`** — the Reference sub-types this instance supports,
+ including each one's `value_schema`. Call this first if you do not already
+ know the `type` and `value` shape to use.
+- **`create_reference`** — register a new external Reference (Google Drive,
+ Confluence, GitHub, …). 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 `instructions` to tell other agents how to USE it — what is in it,
+ when to consult it, any caveats.
+- **`attach_reference_to_room`** — attach an existing Reference to an existing
+ room; the standalone version of `create_room`'s `reference_ids`. Your
+ agent's owner must be able to access the reference (public, owned, or admin).
+
+### Linking rooms
+
+- **`link_rooms`** — a directed link from one room to another with a free-text
+ `label` describing the relationship (`"support"`, `"parent project"`,
+ `"depends on"`). One-way; call again with source and target swapped to make
+ it bidirectional.
+- **`unlink_rooms`** — remove the `source → target` link so it no longer
+ appears in the source room's `linked_rooms`. Also one-way; call again
+ swapped to remove the reverse. Errors if no such link exists.
+
+## 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
+appear in the `connect_to_room` payload as `roles`, and via `list_roles`.
+
+### Taking a role
+
+- **`list_roles`** — the room's roles. Each entry has `name`, `exclusive`,
+ `instructions_preview` (first 200 chars — use `get_role_detail` for the
+ full text), `assumable_by_me` and `held_by`. `held_by` is a list
+ of `{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, or is null
+ if no live session is found. The preview is truncated to 200 characters.
+- **`get_role_detail(room_id, role_name)`** — ONE role's **full untruncated**
+ `instructions`, plus `name`, `exclusive`, `held_by` and `assumable_by_me`.
+ Use it when the preview is cut off and you need the whole bundle — e.g. to
+ read what a role entails before taking it. Requires room membership; the
+ room need not be the one you are 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.
+
+### 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, or the single holder of an exclusive
+one. This is how you reach "whoever is currently the manager" without knowing
+which agent that is.
+
+**Presence is availability.** Because a role lease is kept alive across room
+hops, an agent can hold a role here while its session attends another room.
+Use `present_here` / `session_room` — 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.
+
+### Authoring roles
+
+The 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 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 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.
+
+## 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
+ — that agent will respond, even though you only meant to mention 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)`. Write the bare name instead
+ ("opencode.test-opencode posted the greeting"). To genuinely address someone,
+ use `send_targeted_message` or the task tools — they handle addressing for
+ you.
+- **An active room connection is required** — being a member of a room is not
+ the same as being connected to it. `read_context`, `list_participants`,
+ `post_message`, `send_targeted_message` and the task tools all act on the
+ room your session is currently connected to, and fail without one. You
+ connected on arrival; that holds for the session.
+- **Switch does not mediate your local tool calls.** Pre-execution mediation is
+ a Claude Code connector feature; an OpenCode session has no such hook, so your
+ shell commands and edits are gated by OpenCode's own permission 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 humans are
+ in the room. Read the conversation and contribute meaningfully.
+- **Confirm before creating rooms.** Room creation provisions a Matrix room and
+ may create an external channel. Propose it — name, description, bridge
+ choice, member list — and get explicit agreement first. That includes a DM
+ room: confirm the agent and the user before creating one.
+
+## Formatting for bridged channels
+
+Your messages render on whatever platform the room is bridged to
+(`bridge_display_name` in `get_room_detail`), and the platforms differ:
+
+- **Slack** renders only a subset of Markdown (mrkdwn). Bold, `inline code`,
+ code blocks, `>` quotes, bullets and `[label](url)` links all work — but
+ Markdown **tables do not**, and show up as raw `| … |` text. So in a
+ Slack-bridged room, **never use a Markdown table**: for any multi-item list
+ with attributes (status digests, backlogs, queues), use one short line per
+ item with bold field labels instead —
+ `- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with
+ the bold identifier and separate fields with `·` or `—`.
+- **Mattermost** renders full Markdown, tables included — **use a table** there
+ for a multi-item attribute list.
+
+When unsure, prefer the Slack-safe shape — it reads fine everywhere.
+
+## If you see a `select_agent` tool
+
+It means this session has **no Switch identity yet**. Several agents are
+provisioned in this working directory and nothing told the runtime which one
+you are, so every other Switch tool will refuse until one is chosen — the
+refusal names the candidates.
+
+Call `select_agent` once with the name you are, then carry on as normal. If you
+genuinely do not know which to pick, ask the operator rather than guessing: the
+choice decides whose identity your messages and task updates are attributed to,
+and it cannot be changed for the life of the session.
+
+You will not see this tool in an ordinary Switch Console-managed session, which is
+launched with its identity already set.
+
+## If `switch_unavailable` is your only tool
+
+Switch could not start for this session — wrong or missing credentials, an
+unreachable server, or agents here belonging to two different Switch servers.
+
+Call it. Its answer is the actual reason. Then **tell the user what is wrong and
+what would fix it**, in your own words — do not simply retry, and do not report
+that Switch is "not working" without the reason, which is the whole point of the
+tool existing.
+
+Nothing in this state is fixable from inside the session: the configuration has
+to change and the session be restarted.
+
+## Tool index
+
+Every Switch tool you call in normal operation, one line each. The two
+failure-mode tools are covered in the sections just above.
+
+- `list_rooms` — rooms you are assigned to.
+- `connect_to_room` — enter a room. Once, then see steady state above.
+- `read_context` — room history, grouped into threads. Check `truncated`.
+- `list_participants` — the connected room's roster: `id`, `name`, `type`,
+ `status`, `alias`.
+- `post_message` — broadcast to the room.
+- `send_targeted_message` — broadcast addressed to names and/or roles.
+- `send_attachment` — post one or more files to the room.
+- `download_attachment` — fetch a file seen in history, by `mxc`.
+- `delegate_task` — hand tracked work to a performer.
+- `accept_task` — take a delegated task to `ongoing`.
+- `update_task` — record progress on a task you accepted.
+- `finalise_task` — close a task with its outcome.
+- `cancel_task` — abandon a task you delegated.
+- `list_tasks` — enumerate tasks by role and status.
+- `list_roles` — the room's assumable roles and who holds them.
+- `get_role_detail` — one role's full untruncated instructions.
+- `assume_role` — take a role and its instruction bundle.
+- `release_role` — drop the role you hold.
+- `define_role` — add a role to the connected room.
+- `edit_role` — change a role's instructions or exclusivity.
+- `delete_role` — remove a role and any lease on it.
+- `list_linked_rooms` — refresh this room's outbound pointers.
+- `list_all_rooms` — every room on the instance, not just yours.
+- `get_room_detail` — one room's members, channel type, roles, aliases.
+- `list_bridges` — the collaboration bridges available for new rooms.
+- `create_room` — provision a room. Confirm with the user first.
+- `update_room` — change an existing room, including its aliases.
+- `invite_agent_to_room` — add an agent to an existing room by name.
+- `list_references` — re-fetch the room's references, documents and packages.
+- `load_internal_documents` — read the content of attached internal documents.
+- `create_room_document` — author a document scoped to the connected room.
+- `update_room_document` — change a document you created.
+- `delete_room_document` — remove a document you created.
+- `add_users_to_room` — add human users to an existing room by name.
+- `archive_room` — archive a room you belong to.
+- `unarchive_room` — reverse an archive.
+- `list_room_groups` — the group tree rooms are organised into.
+- `get_room_group_detail` — one group's rooms and child groups.
+- `create_room_group` — provision a new room group.
+- `list_agents` — every agent on the instance, with optional filters.
+- `get_agent_detail` — one agent's config, capabilities and sessions.
+- `update_agent_detail` — change an agent you own.
+- `list_reference_types` — the Reference types and their value schemas.
+- `create_reference` — register an external Reference.
+- `attach_reference_to_room` — attach an existing Reference to a room.
+- `link_rooms` — add a directed pointer between two rooms.
+- `unlink_rooms` — remove one.
diff --git a/console/AGENTS.md b/console/AGENTS.md
index 2eb989812..00ac6d11a 100644
--- a/console/AGENTS.md
+++ b/console/AGENTS.md
@@ -460,7 +460,8 @@ 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 |
| Codex plugin | `connectors/codex-plugin/.codex-plugin/plugin.json` | any change to the plugin (the room-workflow and `configure` skills, and its own `.mcp.json`) — installs will not pick it up otherwise |
-| Agent runtime package | `packages/switch-agent-runtime/package.json` | any change; it is published, and **both** connectors' `.mcp.json` pin the version sessions actually run. Nothing in the app pins it — the plugins register the runtime themselves — so those two files are the only pins |
+| OpenCode connector | `connectors/opencode-plugin/package.json` | any change to the connector. Nothing fetches it — Switch Console writes it — so the number is for humans reading a diff rather than for an installer, and `just artifacts-check` fails if it disagrees with `artifacts.yaml` |
+| Agent runtime package | `packages/switch-agent-runtime/package.json` | any change; it is published, and the marketplace connectors' `.mcp.json` pin the version sessions actually run. An agent type whose connector the app writes rather than installs is pinned by `SWITCH_AGENT_RUNTIME_PIN` in `packages/plugins/src/distribution.ts`, which `connectors/opencode-plugin/opencode.json` must match. `runtime-pin.test.ts` and `connector-assets.test.ts` fail if any of them disagree |
"Non-trivial" means anything a user could observe: behaviour, protocol, wiring,
dependencies. A comment or a rename that changes nothing does not need one.
@@ -539,6 +540,18 @@ pnpm run test
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.
+- **How an agent type gets its Switch connector** is the `switchSetup` capability
+ in `packages/core/src/agents/plugins/capabilities/switch-setup.ts`, and it has
+ two working shapes. `kind: 'cli'` drives the host's plugin-marketplace CLI, with
+ the per-host verbs and JSON shapes in
+ `src/main/core/switch-setup/switch-setup-cli-dialect.ts` (Claude Code, Codex).
+ `kind: 'files'` is for a host with no marketplace: the plugin supplies a
+ behavior that writes the connector itself, through a home-rooted `PluginFs` so
+ one implementation serves a local machine and an SSH host alike (OpenCode).
+ Both reach the same status / install / update / uninstall surface in
+ `switch-setup-service.ts` and `remote-switch-setup.ts`. A `files` connector has
+ no version of its own — it ships inside the app, so the app version stamps the
+ install and "update available" means an install written by an older build.
- Provider detection lives in `src/main/core/dependencies/` (`dependency-managers.ts`,
`registry.ts`), with remote detection in `remote-dependency-manager.ts`.
- Provider PTY behavior and env passthrough live under `src/main/core/pty/`.
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index 2df0b626e..f99fc76f9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -1,4 +1,8 @@
-import type { PluginFs, SwitchLaunchSpecialization } from '@switch-console/core/agents/plugins';
+import type {
+ PluginFs,
+ PluginScope,
+ SwitchLaunchSpecialization,
+} from '@switch-console/core/agents/plugins';
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';
import { resolveAgentLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';
@@ -298,16 +302,38 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime
const plugin = getPlugin(providerId);
const hooks = plugin.capabilities.hooks;
if (hooks.kind === 'none') return;
- if (hooks.kind !== 'config' || !plugin.behavior.hooks) {
+
+ const fs = this.remoteHookFs(hooks.scope);
+ // Both delivery mechanisms, not just config files. A provider whose hooks
+ // ride a dropped plugin (OpenCode) would otherwise run on the host with
+ // nothing installed — no session id captured, and a "working on it" that
+ // never clears.
+ let install: (() => Promise<unknown>) | null = null;
+ // Null unless a config write actually resolved it: the hook commands are
+ // built for the VM's platform, and a provider whose hooks ride a dropped
+ // plugin never needs it, so it is not worth a round-trip to the host.
+ let resolvedPlatform: NodeJS.Platform | null = null;
+ if (hooks.kind === 'config' && plugin.behavior.hooks) {
+ const writeHooks = plugin.behavior.hooks.writeHooks;
+ install = async () => {
+ resolvedPlatform = await remoteNodePlatform(this.connectionId, this.ctx);
+ return writeHooks(fs, [], { platform: resolvedPlatform });
+ };
+ } else if (hooks.kind === 'plugin' && plugin.behavior.plugins) {
+ const installPlugin = plugin.behavior.plugins.installPlugin;
+ const scope: PluginScope =
+ hooks.scope === 'global'
+ ? { kind: 'global' }
+ : { kind: 'workspace', path: this.sessionPath };
+ install = () => installPlugin(fs, scope);
+ }
+ if (!install) {
log.error('SshAgentRuntime: provider hooks cannot be installed on a remote host', {
providerId,
kind: hooks.kind,
});
return;
}
- const writeHooks = plugin.behavior.hooks.writeHooks;
- const fs = this.remoteHookFs(hooks.scope);
- const platform = await remoteNodePlatform(this.connectionId, this.ctx);
// A global-scope write targets the VM's home, so it is shared by every dir
// on the host; keying it on the dir would let one write per dir through.
const scopeKey = hooks.scope === 'global' ? '~' : this.sessionPath;
@@ -315,12 +341,12 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime
await dedupeInFlight(
remoteHookInstallsInFlight,
`${this.connectionId}::${scopeKey}::${providerId}`,
- () => writeHooks(fs, [], { platform })
+ install
);
log.info('SshAgentRuntime: installed remote agent hooks', {
providerId,
scope: hooks.scope,
- platform,
+ platform: resolvedPlatform,
});
} catch (error) {
log.error('SshAgentRuntime: failed to install remote agent hooks', {
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
index a9f2addd9..4db26be66 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
@@ -98,6 +98,45 @@ describe('resolveAgentSessionCommandArgs', () => {
expect(result.args).toContain(session.id);
});
+ it('uses the stored OpenCode session id when resuming', () => {
+ expect(
+ resolveAgentSessionCommandArgs(
+ makeSession({ providerId: 'opencode', providerSessionId: 'ses_abc123' }),
+ true
+ )
+ ).toEqual({ sessionId: 'ses_abc123', isResuming: true });
+ });
+
+ // Without this, resume falls through to OpenCode's `--continue`, which
+ // reattaches to whatever ran last in that directory — for a Switch agent,
+ // very possibly a conversation belonging to someone else.
+ it('starts fresh instead of continuing the last OpenCode session', () => {
+ expect(resolveAgentSessionCommandArgs(makeSession({ providerId: 'opencode' }), true)).toEqual({
+ sessionId: 'session-1',
+ isResuming: false,
+ });
+ });
+
+ it('builds an OpenCode resume command from the stored provider session id', () => {
+ const session = makeSession({
+ id: '6fac6620-9fa8-4604-b7e0-1fe361589104',
+ providerId: 'opencode',
+ providerSessionId: 'ses_abc123',
+ });
+ const spawnPlan = resolveAgentSessionCommandArgs(session, true);
+ const result = pluginRegistry.get('opencode')!.behavior.prompt!.buildCommand({
+ cli: 'opencode',
+ autoApprove: false,
+ model: '',
+ sessionId: spawnPlan.sessionId,
+ providerSessionId: session.providerSessionId ?? undefined,
+ isResuming: spawnPlan.isResuming,
+ });
+
+ expect(result.command).toBe('opencode');
+ expect(result.args).toEqual(['--session', 'ses_abc123']);
+ });
+
it('builds a Codex replacement resume command from the stored provider session id', () => {
const session = makeSession({
id: '6fac6620-9fa8-4604-b7e0-1fe361589104',
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts
index f256b2403..635f2894f 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts
@@ -1,12 +1,27 @@
import type { Session } from '@shared/core/sessions/sessions';
-/** Droid `--resume` needs the provider-native session UUID, not the Switch Console session id. */
+/**
+ * Providers whose resume takes the provider-native session id rather than the
+ * Switch Console session id.
+ *
+ * For these, resuming without a captured provider session id must fall back to
+ * starting a fresh session. The alternative is worse than it looks: their
+ * resume-without-an-id flag reattaches to whatever the *last* session in that
+ * directory was, which for a Switch agent means silently picking up an
+ * unrelated conversation — possibly another agent's.
+ *
+ * Several other providers also declare `sessionIdOnResumeOnly` and are not
+ * listed here. Whether they have the same problem has not been established, so
+ * they are deliberately left as they are rather than changed untested.
+ */
+const RESUME_NEEDS_PROVIDER_SESSION_ID = new Set(['codex', 'droid', 'opencode']);
+
export function resolveAgentSessionCommandArgs(
session: Session,
isResuming: boolean,
options: { requireProviderSessionId?: boolean } = {}
): { sessionId: string; isResuming: boolean } {
- if ((session.providerId === 'codex' || session.providerId === 'droid') && isResuming) {
+ if (RESUME_NEEDS_PROVIDER_SESSION_ID.has(session.providerId) && isResuming) {
if (session.providerSessionId) {
return { sessionId: session.providerSessionId, isResuming: true };
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts
index 42327a65d..d407ec2aa 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts
@@ -21,9 +21,18 @@ describe('knownAgentTypeForProvider', () => {
expect(log.warn).not.toHaveBeenCalled();
});
+ it('maps opencode to its own gateway known-agent type', () => {
+ // Without this it fell through to the fallback and registered as
+ // claude-code, so an operator onboarding it by hand was told to run
+ // `claude` in an OpenCode agent's directory.
+ expect(knownAgentTypeForProvider('opencode')).toBe('opencode');
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
it('warns when a provider has no gateway known-agent type, then falls back visibly', () => {
- // Only claude-code and codex exist server-side, so anything else registers
- // as a type it is not. That is a disclosed fallback, never a silent one.
+ // Only the types in KNOWN_AGENTS exist server-side, so anything else
+ // registers as a type it is not. That is a disclosed fallback, never a
+ // silent one.
for (const id of ['grok', 'gemini', 'cursor', 'droid'] as const) {
vi.clearAllMocks();
expect(knownAgentTypeForProvider(id)).toBe('claude-code');
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts
index dc9e9efcf..7dde2665b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts
@@ -6,11 +6,12 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
* in `switch_core/gateway/known_agents.py` — a value outside it is rejected at
* registration, so it is worth catching at the call site instead.
*/
-export type KnownAgentType = 'claude-code' | 'codex';
+export type KnownAgentType = 'claude-code' | 'codex' | 'opencode';
const KNOWN_AGENT_TYPE_BY_PROVIDER: Partial<Record<AgentProviderId, KnownAgentType>> = {
claude: 'claude-code',
codex: 'codex',
+ opencode: 'opencode',
};
const FALLBACK_KNOWN_AGENT_TYPE: KnownAgentType = 'claude-code';
@@ -18,7 +19,7 @@ const FALLBACK_KNOWN_AGENT_TYPE: KnownAgentType = 'claude-code';
/**
* Map a Switch Console provider to the gateway known-agent type it registers as.
*
- * A provider outside the two server-side types has no faithful representation.
+ * A provider outside the server-side types has no faithful representation.
* It still registers as `claude-code` — the generic Switch Console-managed shape —
* because Switch Console drives the session itself and the type mainly determines
* the connector label and the hand-onboarding command an operator is shown. That
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.ts
index 026206dc3..adeac73c5 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/remove-switch-settings.ts
@@ -29,9 +29,9 @@ async function removeDefaultSwitchCredentials(fs: PluginFs): Promise<void> {
* at the agent's working directory (local or remote), so one call covers both.
*/
export async function removeSwitchCredentials(providerId: string, fs: PluginFs): Promise<void> {
- const behavior = getPlugin(providerId).behavior.switchSetup;
- if (behavior) {
- await behavior.removeCredentials(fs);
+ const removeCredentials = getPlugin(providerId).behavior.switchSetup?.removeCredentials;
+ if (removeCredentials) {
+ await removeCredentials(fs);
return;
}
await removeDefaultSwitchCredentials(fs);
diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts
index adae73b4e..4d31033b2 100644
--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts
@@ -53,7 +53,7 @@ function plannableAgentTypes() {
return listPlugins()
.filter(
(plugin) =>
- plugin.capabilities.switchSetup.kind === 'cli' &&
+ plugin.capabilities.switchSetup.kind !== 'none' &&
plugin.capabilities.hostDependency.binaryNames.length > 0
)
.map((plugin) => ({
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.test.ts
index 800924707..4c61923cc 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.test.ts
@@ -17,7 +17,7 @@ describe('resolveSessionControl', () => {
expect(control.plan('interrupt', ctx)).toBeNull();
});
- it.each(['claude', 'codex'])('supports all three commands for %s', (providerId) => {
+ it.each(['claude', 'codex', 'opencode'])('supports all three commands for %s', (providerId) => {
expect(resolveSessionControl(providerId).capabilities).toEqual({
reset: true,
compact: true,
@@ -33,18 +33,22 @@ describe('resolveSessionControl', () => {
]);
});
- it.each(['claude', 'codex'])('returns null for an unknown command on %s', (providerId) => {
- expect(resolveSessionControl(providerId).plan('explode', ctx)).toBeNull();
- });
+ it.each(['claude', 'codex', 'opencode'])(
+ 'returns null for an unknown command on %s',
+ (providerId) => {
+ expect(resolveSessionControl(providerId).plan('explode', ctx)).toBeNull();
+ }
+ );
- it.each(['claude', 'codex'])(
+ it.each(['claude', 'codex', 'opencode'])(
'reconnects and re-assumes the role after %s reset',
(providerId) => {
const steps = resolveSessionControl(providerId).plan('reset', ctx);
expect(steps).not.toBeNull();
- // `/clear` drops the context, so the follow-up must put the agent back in
- // the room, back in its role, and tell the asker in their thread.
+ // Whatever the provider calls it, reset drops the context — so the
+ // follow-up must put the agent back in the room, back in its role, and
+ // tell the asker in their thread.
const announce = steps!.at(-1);
expect(announce).toMatchObject({ kind: 'prompt' });
const text = (announce as { text: string }).text;
@@ -77,10 +81,43 @@ describe('resolveSessionControl', () => {
});
});
- it.each(['claude', 'codex'])('announces the compaction back to the room on %s', (providerId) => {
- const steps = resolveSessionControl(providerId).plan('compact', ctx);
- expect(steps).not.toBeNull();
- expect((steps!.at(-1) as { text: string }).text).toContain('context has been compacted');
+ it.each(['claude', 'codex', 'opencode'])(
+ 'announces the compaction back to the room on %s',
+ (providerId) => {
+ const steps = resolveSessionControl(providerId).plan('compact', ctx);
+ expect(steps).not.toBeNull();
+ expect((steps!.at(-1) as { text: string }).text).toContain('context has been compacted');
+ }
+ );
+
+ // OpenCode needs Escape TWICE, and coalesces `\x1b\x1b` arriving as one write
+ // into a single escape sequence that does nothing — so the two must stay
+ // separate steps for the executor to space them apart. A regression here is
+ // silent: the interrupt is simply ignored and the turn keeps running.
+ it('interrupts opencode with two separate ESC writes', () => {
+ expect(resolveSessionControl('opencode').plan('interrupt', ctx)).toEqual([
+ { kind: 'raw', data: ESC },
+ { kind: 'raw', data: ESC },
+ ]);
+ });
+
+ it('does not interrupt opencode with one doubled ESC write', () => {
+ const steps = resolveSessionControl('opencode').plan('interrupt', ctx);
+ expect(steps).not.toContainEqual({ kind: 'raw', data: `${ESC}${ESC}` });
+ });
+
+ // OpenCode has no /clear; a fresh session is /new.
+ it('resets opencode with /new rather than /clear', () => {
+ const steps = resolveSessionControl('opencode').plan('reset', ctx);
+ expect(steps?.[0]).toEqual({ kind: 'prompt', text: '/new' });
+ expect(steps).not.toContainEqual({ kind: 'prompt', text: '/clear' });
+ });
+
+ it('compacts opencode with /compact and no preceding interrupt', () => {
+ expect(resolveSessionControl('opencode').plan('compact', ctx)?.[0]).toEqual({
+ kind: 'prompt',
+ text: '/compact',
+ });
});
it('omits the role and thread clauses when there is neither', () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.ts
index 2f3e95585..dbfeb7d32 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-control.ts
@@ -132,6 +132,40 @@ const CODEX_CONTROL: SessionControl = {
},
};
+/**
+ * OpenCode: also a TUI. It starts a fresh session on `/new` rather than
+ * `/clear`, and summarises the transcript on `/compact`.
+ */
+const OPENCODE_CONTROL: SessionControl = {
+ capabilities: { reset: true, compact: true, interrupt: true },
+ plan(command, ctx) {
+ switch (command) {
+ case 'interrupt':
+ // OpenCode interrupts on Escape pressed TWICE. Two ESC bytes in one
+ // write (`\x1b\x1b`) are coalesced by its input parser into a single
+ // escape sequence and do nothing at all, so they go as two separate
+ // steps — the executor spaces steps apart, which is what makes each
+ // land as its own keypress.
+ return [
+ { kind: 'raw', data: ESC },
+ { kind: 'raw', data: ESC },
+ ];
+ case 'compact':
+ return [
+ { kind: 'prompt', text: '/compact' },
+ { kind: 'prompt', text: reconnectAndAnnounce(ctx, 'context has been compacted') },
+ ];
+ case 'reset':
+ return [
+ { kind: 'prompt', text: '/new' },
+ { kind: 'prompt', text: reconnectAndAnnounce(ctx, 'session has been reset') },
+ ];
+ default:
+ return null;
+ }
+ },
+};
+
const NO_CONTROL: SessionControl = {
capabilities: { reset: false, compact: false, interrupt: false },
plan: () => null,
@@ -140,6 +174,7 @@ const NO_CONTROL: SessionControl = {
const BY_PROVIDER: Record<string, SessionControl> = {
claude: CLAUDE_CONTROL,
codex: CODEX_CONTROL,
+ opencode: OPENCODE_CONTROL,
};
/** Resolve the session-control support + recipes for a provider. */
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts
index ed63b07f0..fe2c5f70d 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts
@@ -1,4 +1,7 @@
+import type { ISwitchSetupFilesBehavior, PluginFs } from '@switch-console/core/agents/plugins';
import { resolveCommandPath } from '@switch-console/core/deps/runtime';
+import { type ArtifactName, artifactVersion } from '@switch-console/shared';
+import { createRemoteHomePluginFs } from '@main/core/agent-runtime/impl/remote-home-plugin-fs';
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';
@@ -14,6 +17,19 @@ const EXEC_TIMEOUT_MS = 120_000;
/** POSIX shells use 127 for "command not found". */
const COMMAND_NOT_FOUND = 127;
+/**
+ * The version stamped into a file-based connector install — the connector's own
+ * artifact version, on a remote host exactly as locally, so the two report the
+ * same number for the same connector.
+ */
+function connectorVersion(agentId: string): string {
+ const descriptor = getPlugin(agentId).capabilities.switchSetup;
+ if (descriptor.kind !== 'files') {
+ throw new Error(`Agent '${agentId}' has no file-based Switch connector to version.`);
+ }
+ return artifactVersion(descriptor.artifact as ArtifactName);
+}
+
type RunResult = { code: number; stdout: string; stderr: string };
/**
@@ -89,6 +105,22 @@ function parseJsonLoose(stdout: string): unknown {
export class RemoteSwitchSetupService {
constructor(private readonly ctx: SshExecutionContext) {}
+ /**
+ * The `files` connector behavior for an agent whose connector Switch Console
+ * writes itself, rooted at the remote host's home. Null for any other agent.
+ */
+ private resolveFiles(agentId: string) {
+ const plugin = getPlugin(agentId);
+ if (plugin.capabilities.switchSetup.kind !== 'files') return null;
+ const files = plugin.behavior.switchSetup?.files;
+ if (!files) {
+ throw new Error(
+ `Agent '${agentId}' declares a file-based Switch connector but implements no behavior for it.`
+ );
+ }
+ return { files, homeFs: createRemoteHomePluginFs(this.ctx) };
+ }
+
private async resolve(agentId: string) {
const plugin = getPlugin(agentId);
const descriptor = plugin.capabilities.switchSetup;
@@ -228,7 +260,48 @@ export class RemoteSwitchSetupService {
}
}
+ /**
+ * Status of a file-based connector on this host. Its content ships inside the
+ * app, so the version the connector's own directory declares is the latest
+ * there is, and an install stamped with an older one is what "update
+ * available" means.
+ */
+ private async filesStatus(agentId: string, version: string): Promise<SwitchSetupStatus> {
+ const resolved = this.resolveFiles(agentId);
+ if (!resolved) return unsupported(agentId);
+ const installedVersion = await resolved.files.installedVersion(resolved.homeFs);
+ return {
+ agentId,
+ supported: true,
+ installed: installedVersion !== null,
+ installedVersion,
+ latestVersion: version,
+ updateAvailable: installedVersion !== null && isNewerVersion(installedVersion, version),
+ refreshError: null,
+ };
+ }
+
+ /** Install, update and uninstall for a file-based connector on this host. */
+ private async runFiles(
+ agentId: string,
+ action: (files: ISwitchSetupFilesBehavior, homeFs: PluginFs) => Promise<unknown>
+ ): Promise<SwitchSetupResult> {
+ const resolved = this.resolveFiles(agentId);
+ if (!resolved)
+ return { success: false, message: 'Switch setup is not supported for this agent.' };
+ try {
+ await action(resolved.files, resolved.homeFs);
+ return { success: true };
+ } catch (err) {
+ log.error('remote-switch-setup: file-based connector operation failed', { agentId, err });
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
+ }
+ }
+
async getStatus(agentId: string): Promise<SwitchSetupStatus> {
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.filesStatus(agentId, connectorVersion(agentId));
+ }
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
const { descriptor, bin, ref, rules } = resolved;
@@ -264,6 +337,10 @@ export class RemoteSwitchSetupService {
* versions with `refreshError` set so the UI can disclose the staleness.
*/
async checkForUpdates(agentId: string): Promise<SwitchSetupStatus> {
+ // A file-based connector ships inside the app: nothing to refresh.
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.filesStatus(agentId, connectorVersion(agentId));
+ }
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
const { descriptor, bin, marketplaceSource, rules } = resolved;
@@ -284,6 +361,10 @@ export class RemoteSwitchSetupService {
}
async install(agentId: string): Promise<SwitchSetupResult> {
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ const version = connectorVersion(agentId);
+ return this.runFiles(agentId, (files, fs) => files.install(fs, { version }));
+ }
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
@@ -305,6 +386,12 @@ export class RemoteSwitchSetupService {
* would otherwise fail it after the uninstall has already succeeded.
*/
async update(agentId: string): Promise<SwitchSetupResult> {
+ // Installing overwrites in place, so update is the same operation — there
+ // is no removed-but-not-reinstalled window to report on.
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ const version = connectorVersion(agentId);
+ return this.runFiles(agentId, (files, fs) => files.install(fs, { version }));
+ }
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
@@ -348,7 +435,7 @@ export class RemoteSwitchSetupService {
async listAgentTypeStatuses(): Promise<SwitchSetupStatus[]> {
const statuses: SwitchSetupStatus[] = [];
for (const plugin of listPlugins()) {
- if (plugin.capabilities.switchSetup.kind !== 'cli') continue;
+ if (plugin.capabilities.switchSetup.kind === 'none') continue;
statuses.push(await this.getStatus(plugin.metadata.id));
}
return statuses;
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
index 55aa970f2..476e09e4d 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts
@@ -31,6 +31,7 @@ vi.mock('@main/lib/logger', () => ({
log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },
}));
+import { ARTIFACT_VERSIONS } from '@switch-console/shared';
import { switchSetupService } from './switch-setup-service';
const CLI_AGENT = {
@@ -642,3 +643,47 @@ describe('switchSetupService with the codex dialect', () => {
});
});
});
+
+describe('file-based connector version', () => {
+ const installedVersion = vi.fn();
+ const FILES_AGENT = {
+ metadata: { id: 'opencode' },
+ capabilities: {
+ switchSetup: {
+ kind: 'files',
+ connectorName: 'Switch connector',
+ artifact: 'switch-connector-opencode',
+ },
+ hostDependency: { binaryNames: ['opencode'] },
+ },
+ behavior: { switchSetup: { files: { installedVersion } } },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getPlugin.mockReturnValue(FILES_AGENT);
+ });
+
+ // The connector is versioned in its own directory and listed in the registry
+ // beside the marketplace connectors. Reporting the app's version here would
+ // put a number on the card that matches nothing the connector declares.
+ it('reports the connector artifact version, not the app version', async () => {
+ installedVersion.mockResolvedValue('0.1.0');
+
+ const status = await switchSetupService.getStatus('opencode');
+
+ expect(status.latestVersion).toBe(ARTIFACT_VERSIONS['switch-connector-opencode']);
+ expect(status.installedVersion).toBe('0.1.0');
+ });
+
+ // Keying "update available" on the app version offered an update on every
+ // app release, even one that rewrote the connector with identical bytes.
+ it('offers no update when the installed connector is the current one', async () => {
+ installedVersion.mockResolvedValue(ARTIFACT_VERSIONS['switch-connector-opencode']);
+
+ const status = await switchSetupService.getStatus('opencode');
+
+ expect(status.installed).toBe(true);
+ expect(status.updateAvailable).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts
index 98648caa3..a8a4697c3 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts
@@ -1,10 +1,14 @@
import { readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
import { join } from 'node:path';
+import type { ISwitchSetupFilesBehavior, PluginFs } from '@switch-console/core/agents/plugins';
import { resolveCommandPath } from '@switch-console/core/deps/runtime';
+import { type ArtifactName, artifactVersion } from '@switch-console/shared';
import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';
import { log } from '@main/lib/logger';
import { isNewerVersion } from '@main/lib/semver';
import type { AgentTypeAvailability } from '@shared/core/switch-setup/agent-type-availability';
+import { createPluginFs } from '../providers/plugin-fs';
import { getPlugin, listPlugins } from '../providers/plugin-registry';
import {
cliRulesFor,
@@ -40,6 +44,21 @@ export type SwitchSetupResult = { success: boolean; message?: string };
const EXEC_TIMEOUT_MS = 120_000;
+/**
+ * The version stamped into a file-based connector install, and the one it is
+ * compared against.
+ *
+ * The connector's own artifact version, not the app's: it is versioned in its
+ * own directory and listed in the registry beside the marketplace connectors,
+ * so reporting the app's version here would put a number on the card that
+ * matches nothing the connector declares. Keying "update available" on it also
+ * means an app release that does not touch the connector no longer offers an
+ * update that would rewrite the same bytes.
+ */
+function connectorVersion(artifact: string): string {
+ return artifactVersion(artifact as ArtifactName);
+}
+
/** A CLI failure with no stderr still needs to say something. */
function installFailureMessage(raw: string): string {
return raw || 'Install failed.';
@@ -80,6 +99,29 @@ function unsupported(agentId: string): SwitchSetupStatus {
class SwitchSetupService {
private readonly ctx = new LocalExecutionContext();
+ /**
+ * The `files` connector behavior for an agent whose connector Switch Console
+ * writes itself, or null for any other agent.
+ */
+ private resolveFiles(agentId: string) {
+ const plugin = getPlugin(agentId);
+ if (plugin.capabilities.switchSetup.kind !== 'files') return null;
+ const files = plugin.behavior.switchSetup?.files;
+ if (!files) {
+ // A declared descriptor with no behavior cannot install anything, and
+ // reporting "not installed" forever would send the user to a button that
+ // silently does nothing.
+ throw new Error(
+ `Agent '${agentId}' declares a file-based Switch connector but implements no behavior for it.`
+ );
+ }
+ return {
+ files,
+ homeFs: createPluginFs(homedir()),
+ version: connectorVersion(plugin.capabilities.switchSetup.artifact),
+ };
+ }
+
/** Returns the `cli` descriptor + agent binary, or null when unsupported/unresolvable. */
private async resolve(agentId: string) {
const plugin = getPlugin(agentId);
@@ -197,8 +239,33 @@ class SwitchSetupService {
}
}
+ /**
+ * Status of a file-based connector. There is no catalog to consult: the
+ * connector ships inside the app, so the version its own directory declares
+ * is the latest there is, and an install stamped with an older one is what
+ * "update available" means here.
+ */
+ private async filesStatus(agentId: string): Promise<SwitchSetupStatus> {
+ const resolved = this.resolveFiles(agentId);
+ if (!resolved) return unsupported(agentId);
+ const installedVersion = await resolved.files.installedVersion(resolved.homeFs);
+ const latestVersion = resolved.version;
+ return {
+ agentId,
+ supported: true,
+ installed: installedVersion !== null,
+ installedVersion,
+ latestVersion,
+ updateAvailable: installedVersion !== null && isNewerVersion(installedVersion, latestVersion),
+ refreshError: null,
+ };
+ }
+
/** Fast, local status read — no network/catalog refresh. */
async getStatus(agentId: string): Promise<SwitchSetupStatus> {
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.filesStatus(agentId);
+ }
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
const { descriptor, bin, rules } = resolved;
@@ -239,7 +306,7 @@ class SwitchSetupService {
*/
async listAgentTypeAvailability(): Promise<AgentTypeAvailability[]> {
const types = listPlugins()
- .filter((plugin) => plugin.capabilities.switchSetup.kind === 'cli')
+ .filter((plugin) => plugin.capabilities.switchSetup.kind !== 'none')
.map((plugin) => plugin.metadata.id);
const availability: AgentTypeAvailability[] = [];
@@ -264,6 +331,11 @@ class SwitchSetupService {
* versions with `refreshError` set so the UI can disclose the staleness.
*/
async checkForUpdates(agentId: string): Promise<SwitchSetupStatus> {
+ // A file-based connector ships inside the app, so there is no catalog to
+ // refresh and the plain status read is already current.
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.filesStatus(agentId);
+ }
const resolved = await this.resolve(agentId);
if (!resolved) return unsupported(agentId);
const { descriptor, bin, rules } = resolved;
@@ -288,7 +360,31 @@ class SwitchSetupService {
return { ...(await this.getStatus(agentId)), refreshError };
}
+ /** Install, update and uninstall for a file-based connector. */
+ private async runFiles(
+ agentId: string,
+ action: (
+ files: ISwitchSetupFilesBehavior,
+ homeFs: PluginFs,
+ version: string
+ ) => Promise<unknown>
+ ): Promise<SwitchSetupResult> {
+ const resolved = this.resolveFiles(agentId);
+ if (!resolved)
+ return { success: false, message: 'Switch setup is not supported for this agent.' };
+ try {
+ await action(resolved.files, resolved.homeFs, resolved.version);
+ return { success: true };
+ } catch (err) {
+ log.error('switch-setup: file-based connector operation failed', { agentId, err });
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
+ }
+ }
+
async install(agentId: string): Promise<SwitchSetupResult> {
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.runFiles(agentId, (files, fs, version) => files.install(fs, { version }));
+ }
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
@@ -320,6 +416,11 @@ class SwitchSetupService {
* otherwise fail it — after the uninstall has already succeeded.
*/
async update(agentId: string): Promise<SwitchSetupResult> {
+ // Installing a file-based connector overwrites in place, so update is the
+ // same operation — there is no removed-but-not-reinstalled window.
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.runFiles(agentId, (files, fs, version) => files.install(fs, { version }));
+ }
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
@@ -363,6 +464,9 @@ class SwitchSetupService {
}
async uninstall(agentId: string): Promise<SwitchSetupResult> {
+ if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {
+ return this.runFiles(agentId, (files, fs) => files.uninstall(fs));
+ }
const resolved = await this.resolve(agentId);
if (!resolved)
return { success: false, message: 'Switch setup is not supported for this agent.' };
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.test.ts
new file mode 100644
index 000000000..ee43909c2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { autoSelectedAgentType } from './agent-type-auto-selection';
+
+const CLAUDE = 'claude' as AgentProviderId;
+const CODEX = 'codex' as AgentProviderId;
+const OPENCODE = 'opencode' as AgentProviderId;
+
+describe('autoSelectedAgentType', () => {
+ it('picks nothing when no type is usable', () => {
+ expect(autoSelectedAgentType([], 'claude')).toBeNull();
+ });
+
+ it('picks the only usable type, default or not', () => {
+ expect(autoSelectedAgentType([CODEX], 'claude')).toBe(CODEX);
+ expect(autoSelectedAgentType([CODEX], undefined)).toBe(CODEX);
+ });
+
+ it('picks the default when several are usable', () => {
+ expect(autoSelectedAgentType([CLAUDE, CODEX], 'codex')).toBe(CODEX);
+ expect(autoSelectedAgentType([CLAUDE, CODEX], 'claude')).toBe(CLAUDE);
+ });
+
+ it('leaves the choice to the user when the default is not usable here', () => {
+ expect(autoSelectedAgentType([CLAUDE, CODEX], 'opencode')).toBeNull();
+ });
+
+ it('leaves the choice to the user while the default is still loading', () => {
+ expect(autoSelectedAgentType([CLAUDE, CODEX], undefined)).toBeNull();
+ });
+
+ // The bug this rule replaced keyed on `length === 1`, so onboarding silently
+ // changed behaviour the moment a second connector shipped. A third must not
+ // move it again.
+ it('does not depend on how many types are usable', () => {
+ expect(autoSelectedAgentType([CLAUDE, CODEX, OPENCODE], 'codex')).toBe(CODEX);
+ expect(autoSelectedAgentType([CLAUDE, CODEX, OPENCODE], undefined)).toBeNull();
+ });
+
+ it('does not depend on the order they arrive in', () => {
+ expect(autoSelectedAgentType([OPENCODE, CODEX, CLAUDE], 'claude')).toBe(CLAUDE);
+ expect(autoSelectedAgentType([CLAUDE, CODEX, OPENCODE], 'claude')).toBe(CLAUDE);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.ts
new file mode 100644
index 000000000..2c4b89d02
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-auto-selection.ts
@@ -0,0 +1,35 @@
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+
+/**
+ * Which agent type to pick on the user's behalf, given the types that are
+ * usable on the machine being targeted and the user's configured default agent.
+ * Returns null to leave the choice to them.
+ *
+ * Everything past the agent-type picker is gated on a chosen type, so an unset
+ * picker strands the rest of the Add Agent form. Auto-selection covers the two
+ * cases where the choice is not a guess:
+ *
+ * - exactly one usable type — there is nothing to choose;
+ * - several, one of which is the user's own default — a stated preference.
+ *
+ * With several usable types and no default among them the answer is null: the
+ * user picks, because choosing for them silently decides which agent gets
+ * onboarded.
+ *
+ * `defaultAgentId` is undefined while the setting is still loading. That
+ * deliberately reads the same as "no default among them" — the ambiguous case
+ * resolves to null and is retried once the value arrives, rather than racing
+ * the read and picking differently depending on how slow it was.
+ *
+ * The rule never looks at how many types exist beyond the one/many split, and
+ * never at their order. Keying on either makes onboarding change behaviour
+ * every time a connector is added.
+ */
+export function autoSelectedAgentType(
+ selectableIds: readonly AgentProviderId[],
+ defaultAgentId: string | undefined
+): AgentProviderId | null {
+ if (selectableIds.length === 0) return null;
+ if (selectableIds.length === 1) return selectableIds[0];
+ return selectableIds.find((id) => id === defaultAgentId) ?? null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
index aa857735c..d6c510bd1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx
@@ -1,5 +1,6 @@
import { CircleAlert } from 'lucide-react';
import { useEffect, useMemo } from 'react';
+import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { useAgents } from '@renderer/lib/stores/use-agents';
import { useAgentTypeAvailability } from '@renderer/lib/stores/use-switch-setup';
@@ -13,15 +14,18 @@ import {
} from '@renderer/lib/ui/select';
import { Spinner } from '@renderer/lib/ui/spinner';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { autoSelectedAgentType } from './agent-type-auto-selection';
/**
* 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. 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.
+ * Switch setup.
+ *
+ * Everything past this picker is gated on a chosen type — the directory scan,
+ * the onboard-existing list and every submit button — so leaving it unset
+ * strands the rest of the form behind a control the user may not read as
+ * required. `autoSelectedAgentType` decides when the pick can be made for them.
*/
export function AgentTypePicker({
value,
@@ -34,6 +38,7 @@ export function AgentTypePicker({
}) {
const { data: availability, isPending } = useAgentTypeAvailability(sshHost);
const { data: agents } = useAgents();
+ const { value: defaultAgent } = useAppSettingsKey('defaultAgent');
// Every known type, each with the agent registry's name and icon plus the
// verdict from the machine being targeted. Types the registry does not know
@@ -52,8 +57,12 @@ export function AgentTypePicker({
// Only ever auto-select something that can actually be used. Picking a
// greyed-out type on the user's behalf would put them straight into the
// refusal the greying exists to prevent.
- if (selectable.length === 1) onChange(selectable[0].agent.id as AgentProviderId);
- }, [value, selectable, onChange]);
+ const picked = autoSelectedAgentType(
+ selectable.map((o) => o.agent.id as AgentProviderId),
+ defaultAgent
+ );
+ if (picked) onChange(picked);
+ }, [value, selectable, onChange, defaultAgent]);
// Nothing usable is a real dead end and still needs saying — but the list
// below now shows *which* types exist and what each is missing, so this is
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
index d6f27093f..9af7b67f6 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@shared/core/sessions/sessions';
import { SessionManagerStore } from './session-manager';
-import { createUnprovisionedSession } from './session-store';
+import { createUnprovisionedSession, createUnregisteredSession } from './session-store';
type MockViewModel = {
initialize: ReturnType<typeof vi.fn>;
@@ -172,3 +172,75 @@ describe('SessionManagerStore archive lifecycle', () => {
manager.dispose();
});
});
+
+describe('SessionManagerStore discardFailedCreations', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.viewModels.length = 0;
+ mocks.getLocationManagerStore.mockReturnValue({ mountLocation: mocks.mountLocation });
+ mocks.getSessions.mockResolvedValue([]);
+ mocks.mountLocation.mockResolvedValue(undefined);
+ });
+
+ function makeFailedCreation(manager: SessionManagerStore, id: string) {
+ const store = createUnregisteredSession('location-1', {
+ id,
+ title: 'Failed session',
+ status: 'in_progress',
+ lastInteractedAt: '2026-01-01T00:00:00.000Z',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ statusChangedAt: '2026-01-01T00:00:00.000Z',
+ isPinned: false,
+ });
+ store.phase = 'create-error';
+ store.errorMessage = 'remote host cannot reach the Switch endpoint';
+ manager.sessions.set(id, store);
+ return store;
+ }
+
+ // The server rejected the create, so there is nothing there to delete. The
+ // mocked rpc.sessions has no deleteSessions at all — reaching for the server
+ // would throw, so this passing is what proves the discard stays local.
+ it('drops a session whose creation failed, without going to the server', () => {
+ const manager = makeSessionManager();
+ makeFailedCreation(manager, 'session-failed');
+
+ manager.discardFailedCreations();
+
+ expect(manager.sessions.has('session-failed')).toBe(false);
+ expect(mocks.agentRelease).toHaveBeenCalledWith('session-failed');
+
+ manager.dispose();
+ });
+
+ // A provision error belongs to a session the server did register, so it is
+ // listed in the sidebar and its own view offers a retry. Discarding it would
+ // hide a session that still exists.
+ it('leaves a provision error alone', () => {
+ const manager = makeSessionManager();
+ const session = makeSession({ id: 'session-provisioned' });
+ const store = createUnprovisionedSession('location-1', session);
+ store.phase = 'provision-error';
+ manager.sessions.set(session.id, store);
+
+ manager.discardFailedCreations();
+
+ expect(manager.sessions.has('session-provisioned')).toBe(true);
+ expect(mocks.agentRelease).not.toHaveBeenCalled();
+
+ manager.dispose();
+ });
+
+ it('is a no-op when nothing failed to be created', () => {
+ const manager = makeSessionManager();
+ const session = makeSession({ id: 'session-healthy' });
+ manager.sessions.set(session.id, createUnprovisionedSession('location-1', session));
+
+ manager.discardFailedCreations();
+
+ expect(manager.sessions.has('session-healthy')).toBe(true);
+ expect(mocks.agentRelease).not.toHaveBeenCalled();
+
+ manager.dispose();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
index f0f4f923f..f024d2172 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-manager.ts
@@ -460,6 +460,33 @@ export class SessionManagerStore {
}
}
+ /**
+ * Drop sessions whose creation failed, which exist only in this store: the
+ * server rejected the create, so there is nothing there to delete.
+ *
+ * They cannot go through {@link deleteSessions}, which restores what it
+ * removed when the server call fails — and that call fails for a session the
+ * server never registered. Nor does anything else clear them: `loadSessions`
+ * only adds, and an unregistered session carries no `agentId`, so the sidebar
+ * omits it from the agent's list while still counting it as an error. Without
+ * this the agent keeps a failure badge, pointing at a session the user cannot
+ * reach, until the app restarts.
+ */
+ discardFailedCreations(): void {
+ const failed = Array.from(this.sessions.values()).filter(
+ (session) => isUnregistered(session) && session.phase === 'create-error'
+ );
+ if (failed.length === 0) return;
+
+ runInAction(() => {
+ for (const session of failed) this.sessions.delete(session.data.id);
+ });
+ for (const session of failed) {
+ this._releaseSessionRegistries(session.data.id);
+ session.dispose();
+ }
+ }
+
async deleteSession(sessionId: string): Promise<void> {
return this.deleteSessions([sessionId]);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-selectors.ts b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-selectors.ts
index e7de60ba8..258b7b53b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-selectors.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sessions/stores/session-selectors.ts
@@ -162,6 +162,21 @@ export function hasSessionError(locationId: string): boolean {
return false;
}
+/**
+ * Returns true if this location's error comes from a session that failed to be
+ * created. A provision error is reachable — that session is registered, so it
+ * is listed in the sidebar and its view offers a retry. A create error is not:
+ * nothing lists it, so discarding it is the only way to clear the badge.
+ */
+export function hasDiscardableSessionError(locationId: string): boolean {
+ const manager = getSessionManagerStore(locationId);
+ if (!manager) return false;
+ for (const session of manager.sessions.values()) {
+ if (isUnregistered(session) && session.phase === 'create-error') return true;
+ }
+ return false;
+}
+
/** Returns the mount error message for the location. */
export function locationMountErrorMessage(locationId: string): string {
const store = getLocationManagerStore().locations.get(locationId);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx
index dc9c4063c..4636c906b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/AgentRow.tsx
@@ -32,7 +32,7 @@ export const AgentRow = ({ agent, onClick }: { agent: AgentPayload; onClick?: ()
<div className="flex items-center gap-1.5">
<AgentRowStatus
agentId={agent.id}
- supportsSwitch={agent.capabilities.switchSetup.kind === 'cli'}
+ supportsSwitch={agent.capabilities.switchSetup.kind !== 'none'}
cliInstalled={isInstalled}
cliUpdateAvailable={!!updateState.render}
/>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/CliAgentsList.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/CliAgentsList.tsx
index 435eb8cd8..73cc2a21b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/CliAgentsList.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/CliAgentsList.tsx
@@ -40,7 +40,7 @@ export const CliAgentsList: React.FC<CliAgentsListProps> = ({
(agentPayloads ?? [])
// Only Switch-supported agent types are shown for now; the others aren't
// usable in Switch yet, so surfacing them here would be misleading.
- .filter((a) => a.capabilities.switchSetup.kind === 'cli')
+ .filter((a) => a.capabilities.switchSetup.kind !== 'none')
.filter((a) => !normalizedQuery || a.name.toLowerCase().includes(normalizedQuery))
.sort((a, b) => a.name.localeCompare(b.name)),
[agentPayloads, normalizedQuery]
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index d85a7e381..346ce85bb 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -16,7 +16,11 @@ import {
} from '@renderer/features/locations/stores/location-selectors';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { HostTroubleIndicator } from '@renderer/features/remote-hosts/host-trouble-indicator';
-import { hasSessionError } from '@renderer/features/sessions/stores/session-selectors';
+import {
+ getSessionManagerStore,
+ hasDiscardableSessionError,
+ hasSessionError,
+} from '@renderer/features/sessions/stores/session-selectors';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { useToast } from '@renderer/lib/hooks/use-toast';
@@ -156,14 +160,36 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
Shared with the room-grouped rows so the two trees cannot
disagree about the same agent (CHOO-1682/1809). */}
<HostTroubleIndicator sshHost={sshHost} agentId={agent.providerId ?? null} />
- {locationViewKind(location) === 'ready' && hasSessionError(agent.locationId) && (
- <Tooltip>
- <TooltipTrigger>
- <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />
- </TooltipTrigger>
- <TooltipContent>A session failed to connect</TooltipContent>
- </Tooltip>
- )}
+ {locationViewKind(location) === 'ready' &&
+ hasSessionError(agent.locationId) &&
+ (hasDiscardableSessionError(agent.locationId) ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <SidebarItemMiniButton
+ type="button"
+ aria-label={`Dismiss failed session for ${label}`}
+ onClick={(e) => {
+ e.stopPropagation();
+ getSessionManagerStore(agent.locationId)?.discardFailedCreations();
+ }}
+ >
+ <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />
+ </SidebarItemMiniButton>
+ }
+ />
+ <TooltipContent>
+ A session failed to connect — click to dismiss
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger>
+ <TriangleAlert className="h-3.5 w-3.5 shrink-0 text-foreground-destructive" />
+ </TooltipTrigger>
+ <TooltipContent>A session failed to connect</TooltipContent>
+ </Tooltip>
+ ))}
</span>
</SidebarMenuAction>
</div>
diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
index da174f8c6..278933531 100644
--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
@@ -155,6 +155,24 @@ describe('InProcessSessionSpawner.launch', () => {
expect(await readFile(join(CWD, '.claude/settings.local.json'), 'utf8')).toContain('hooks');
});
+ // A provider can deliver its hooks as a dropped plugin rather than a config
+ // file. That path used to be rejected here, so an OpenCode session started on
+ // a VM came up with nothing installed and reported neither its session id nor
+ // that it had stopped — the same failure as a missing hook config, reached a
+ // different way.
+ it("installs a plugin-delivered provider's hooks under the session's working dir", async () => {
+ const { spawner, calls } = makeSpawner({ spec: { ...SPEC, providerId: 'opencode' } });
+
+ await spawner.launch('room-x');
+
+ const dropped = await readFile(
+ join(CWD, '.opencode/plugins/switchdash-notifications.js'),
+ 'utf8'
+ );
+ expect(dropped).toContain('SwitchdashNotifications');
+ expect(calls.find((c) => c.args[0] === 'new-session')).toBeDefined();
+ });
+
// 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 () => {
diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
index de3302f6b..4cb583474 100644
--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
@@ -223,13 +223,6 @@ export class InProcessSessionSpawner implements SessionSpawner {
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 ` +
@@ -237,13 +230,33 @@ export class InProcessSessionSpawner implements SessionSpawner {
);
}
const root = hooks.scope === 'global' ? homedir() : this.spec.cwd;
- // The sidecar runs on the machine the session runs on, so its own platform
- // is the target platform.
- await plugin.behavior.hooks.writeHooks(createPluginFs(root), [], {
- platform: process.platform,
- });
+ const fs = createPluginFs(root);
+
+ // Both delivery mechanisms have to be handled here, not just config files.
+ // A provider whose hooks ride a dropped plugin (OpenCode) would otherwise
+ // launch on a VM with nothing installed and never report that it stopped —
+ // the exact failure this method exists to prevent, reached by a different
+ // route. Mirrors `ensureHooksInstalled` on the desktop side.
+ if (hooks.kind === 'config' && plugin.behavior.hooks) {
+ // The sidecar runs on the machine the session runs on, so its own platform
+ // is the target platform.
+ await plugin.behavior.hooks.writeHooks(fs, [], { platform: process.platform });
+ } else if (hooks.kind === 'plugin' && plugin.behavior.plugins) {
+ await plugin.behavior.plugins.installPlugin(
+ fs,
+ hooks.scope === 'global' ? { kind: 'global' } : { kind: 'workspace', path: root }
+ );
+ } else {
+ this.deps.log.error('InProcessSessionSpawner: provider hooks cannot be installed here', {
+ providerId,
+ kind: hooks.kind,
+ });
+ return;
+ }
+
this.deps.log.info('InProcessSessionSpawner: installed agent hooks', {
providerId,
+ kind: hooks.kind,
scope: hooks.scope,
});
}
diff --git a/console/packages/core/src/agents/plugins/capabilities/switch-setup.ts b/console/packages/core/src/agents/plugins/capabilities/switch-setup.ts
index 275924133..f4fe6dbf4 100644
--- a/console/packages/core/src/agents/plugins/capabilities/switch-setup.ts
+++ b/console/packages/core/src/agents/plugins/capabilities/switch-setup.ts
@@ -15,7 +15,39 @@ import type { PluginFs } from '../../runtime/fs';
* for a local dir or a remote SSH host, so one implementation covers both.
*/
export type ISwitchSetupBehavior = {
- removeCredentials(fs: PluginFs): Promise<void>;
+ removeCredentials?(fs: PluginFs): Promise<void>;
+ /**
+ * Installing and removing the connector's files. Required by — and only
+ * consulted for — a `kind: 'files'` descriptor.
+ */
+ files?: ISwitchSetupFilesBehavior;
+};
+
+/**
+ * Installing the Switch connector for an agent that has no plugin marketplace
+ * to install it from.
+ *
+ * The marketplace dialects assume a CLI that can fetch, list and version a
+ * plugin. An agent without one still needs the same outcome — the Switch MCP
+ * server registered, and the room-workflow skill on disk — so Switch Console
+ * writes those files itself and owns the bookkeeping the CLI would otherwise
+ * do. `version` is what the running app ships, so a status read can tell an
+ * install written by an older build from a current one.
+ *
+ * `fs` is rooted at the agent's home directory and behaves identically for a
+ * local machine and a remote SSH host, so one implementation serves both.
+ */
+export type ISwitchSetupFilesBehavior = {
+ /** Write the connector's files. Returns the home-relative paths written. */
+ install(fs: PluginFs, params: { version: string }): Promise<string[]>;
+ /** Remove them again, leaving unrelated config untouched. */
+ uninstall(fs: PluginFs): Promise<void>;
+ /**
+ * The version recorded by the last install, or null when not installed.
+ * Null must mean absent rather than unreadable — a status read that cannot
+ * tell the difference reports a broken install as a missing one.
+ */
+ installedVersion(fs: PluginFs): Promise<string | null>;
};
/**
@@ -39,10 +71,12 @@ 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 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.
+ * 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: 'files' — the agent has no marketplace, so Switch Console writes the
+ * connector's files itself via {@link ISwitchSetupFilesBehavior}.
+ * kind: 'none' — the agent has no Switch connector setup; the UI surfaces nothing.
*
* The descriptor is purely declarative — one generic driver serves every agent
* that shares the marketplace model, with `dialect` naming the surface
@@ -67,6 +101,23 @@ export const switchSetupCapability = definePluginCapability<ISwitchSetupBehavior
/** Which CLI dialect this agent's `plugin` subcommand speaks. */
dialect: z.enum(SWITCH_SETUP_CLI_DIALECTS).default('claude-code'),
}),
+ z.object({
+ kind: z.literal('files'),
+ /**
+ * What the settings card calls this install. There is no marketplace to
+ * name it, so the descriptor carries the label.
+ */
+ connectorName: z.string(),
+ /**
+ * The artifact in the registry whose version identifies this connector —
+ * the same version its own directory declares, so the card reads like the
+ * marketplace connectors' cards rather than reporting the app's version
+ * for a component that is versioned separately. It is also what "update
+ * available" compares, so a release that leaves the connector alone no
+ * longer offers an update that would change nothing.
+ */
+ artifact: z.string(),
+ }),
z.object({ kind: z.literal('none') }),
])
);
diff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.ts
index 92b0fc321..505189f18 100644
--- a/console/packages/core/src/agents/plugins/index.ts
+++ b/console/packages/core/src/agents/plugins/index.ts
@@ -77,7 +77,7 @@ export type {
SwitchLaunchProfileFile,
SwitchLaunchSpecialization,
} from './capabilities/mcp';
-export type { IPlugins } from './capabilities/plugins';
+export type { IPlugins, PluginScope } from './capabilities/plugins';
export type { ISessionsBehavior } from './capabilities/sessions';
export {
RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES,
@@ -97,6 +97,7 @@ export type {
} from './capabilities/repo-agents';
export type {
ISwitchSetupBehavior,
+ ISwitchSetupFilesBehavior,
SwitchSetupCliDialect,
SwitchSetupDescriptor,
} from './capabilities/switch-setup';
diff --git a/console/packages/plugins/src/agents/impl/opencode/connector-assets.test.ts b/console/packages/plugins/src/agents/impl/opencode/connector-assets.test.ts
new file mode 100644
index 000000000..43982fbe9
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/connector-assets.test.ts
@@ -0,0 +1,142 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { SWITCH_AGENT_RUNTIME_PIN } from '../../../distribution';
+import { icon } from './icon';
+import { OPENCODE_PLUGIN_CONTENT } from './plugin-file';
+import { OPENCODE_SKILL_CONTENT } from './skill-file';
+import {
+ buildOpencodeSwitchConnector,
+ OPENCODE_CONFIG_PATH,
+ OPENCODE_SKILL_PATH,
+} from './switch-connector';
+
+// …/console/packages/plugins/src/agents/impl/opencode → repo root
+const CONNECTOR_DIR = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '..',
+ '..',
+ '..',
+ '..',
+ '..',
+ '..',
+ '..',
+ 'connectors',
+ 'opencode-plugin'
+);
+
+function connectorFile(...segments: string[]): string {
+ return readFileSync(join(CONNECTOR_DIR, ...segments), 'utf8');
+}
+
+/**
+ * `connectors/opencode-plugin/` is the source of truth for what this connector
+ * is, the same as the two marketplace connectors — but nothing fetches it.
+ * Switch Console writes the connector itself, so it carries its own copy of
+ * these assets, and the two can drift with nothing to notice.
+ *
+ * Drift is silent in the worst way: the directory is what a reader reviews and
+ * edits, while sessions run whatever the app embedded. Editing the connector
+ * and shipping the old behaviour would look, in review, exactly like shipping
+ * the new one.
+ */
+function memoryFs(files: Map<string, string>) {
+ return {
+ read: async (path: string) => files.get(path) ?? null,
+ write: async (path: string, content: string) => void files.set(path, content),
+ delete: async (path: string) => void files.delete(path),
+ exists: async (path: string) => files.has(path),
+ list: async () => [...files.keys()],
+ };
+}
+
+async function install(): Promise<Map<string, string>> {
+ const files = new Map<string, string>();
+ await buildOpencodeSwitchConnector().install(memoryFs(files), { version: '1.0.0' });
+ return files;
+}
+
+describe('opencode connector assets', () => {
+ it('embeds the reporting plugin exactly as the connector ships it', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toBe(connectorFile('plugin', 'switch-notifications.js'));
+ });
+
+ it('embeds the room-workflow skill exactly as the connector ships it', () => {
+ expect(OPENCODE_SKILL_CONTENT).toBe(connectorFile('skills', 'switch', 'SKILL.md'));
+ });
+
+ it('registers the MCP server exactly as the connector declares it', async () => {
+ const declared = JSON.parse(connectorFile('opencode.json')) as {
+ mcp: Record<string, unknown>;
+ };
+
+ const files = await install();
+ const written = JSON.parse(files.get(OPENCODE_CONFIG_PATH) ?? '{}') as {
+ mcp: Record<string, unknown>;
+ };
+
+ expect(written.mcp.switch).toEqual(declared.mcp.switch);
+ });
+
+ /**
+ * The tools without the instructions is the failure this guards. Registering
+ * the MCP server is what an install visibly does, and it is easy to call that
+ * the whole job: the session then has forty room tools and nothing telling it
+ * how a room works. Shipping the skill in the connector directory does not
+ * deliver it — OpenCode only reads skills it discovers on disk.
+ */
+ it('writes the skill where OpenCode discovers it', async () => {
+ const files = await install();
+ expect(files.get(OPENCODE_SKILL_PATH)).toBe(OPENCODE_SKILL_CONTENT);
+ });
+
+ it('names the skill directory to match the skill, as OpenCode requires', () => {
+ const declaredName = /^---\n(?:.*\n)*?name:\s*"?([\w-]+)"?\s*$/m.exec(OPENCODE_SKILL_CONTENT);
+ // …/skills/<dir>/SKILL.md — the folder OpenCode derives the skill name from.
+ const directory = OPENCODE_SKILL_PATH.split('/').at(-2);
+
+ expect(declaredName?.[1]).toBe(directory);
+ });
+
+ it('removes the skill on uninstall', async () => {
+ const files = await install();
+ await buildOpencodeSwitchConnector().uninstall(memoryFs(files));
+
+ expect(files.has(OPENCODE_SKILL_PATH)).toBe(false);
+ });
+
+ it('pins the same agent runtime as the rest of the repo', () => {
+ expect(connectorFile('opencode.json')).toContain(SWITCH_AGENT_RUNTIME_PIN);
+ });
+
+ it('declares a version for the connector', () => {
+ const manifest = JSON.parse(connectorFile('package.json')) as {
+ name?: string;
+ version?: string;
+ };
+ expect(manifest.name).toBe('switch-connector-opencode');
+ expect(manifest.version).toMatch(/^\d+\.\d+\.\d+$/);
+ });
+});
+
+// The mark is full-bleed and 4:5, so authored as-is it both overflowed the icon
+// box — an inline SVG's own width/height win over the wrapper's size — and read
+// far heavier than the glyph icons beside it.
+describe('opencode icon', () => {
+ const svg = icon.variants[0];
+
+ it('is square and carries no intrinsic size, so the icon box decides how big it is', () => {
+ for (const variant of [svg?.light, svg?.dark]) {
+ expect(variant).toBeDefined();
+ expect(variant).toContain('viewBox="0 0 24 24"');
+ expect(variant).not.toMatch(/<svg[^>]*\swidth=/);
+ expect(variant).not.toMatch(/<svg[^>]*\sheight=/);
+ }
+ });
+
+ it('insets the mark rather than filling the box edge to edge', () => {
+ expect(svg?.light).toMatch(/translate\(/);
+ expect(svg?.dark).toMatch(/translate\(/);
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/opencode/hooks.test.ts b/console/packages/plugins/src/agents/impl/opencode/hooks.test.ts
new file mode 100644
index 000000000..f080ffcb8
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/hooks.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+import { buildOpencodeHookBehavior, parseOpencodeHookEvent } from './hooks';
+
+function activity(eventType: string, body: Record<string, unknown>): string | undefined {
+ const parsed = parseOpencodeHookEvent(eventType, body);
+ return parsed.kind === 'activity' ? parsed.detail : undefined;
+}
+
+describe('parseOpencodeHookEvent', () => {
+ it('turns a tool-use into a running-tool activity line', () => {
+ expect(
+ activity('tool-use', { tool_name: 'edit', tool_input: { filePath: '/a/b/foo.py' } })
+ ).toBe('_Running tool_ `edit` — foo.py');
+ });
+
+ it('turns a tool-done into a ran-tool activity line', () => {
+ expect(
+ activity('tool-done', { tool_name: 'edit', tool_input: { filePath: '/a/b/foo.py' } })
+ ).toBe('_Ran tool_ `edit` — foo.py');
+ });
+
+ it('uses the command for bash', () => {
+ expect(activity('tool-use', { tool_name: 'bash', tool_input: { command: 'ls -la' } })).toBe(
+ '_Running tool_ `bash` — ls -la'
+ );
+ });
+
+ it('collapses and truncates a long bash command', () => {
+ const detail = activity('tool-use', {
+ tool_name: 'bash',
+ tool_input: { command: `echo ${'x'.repeat(200)}` },
+ });
+ expect(detail).toContain('…');
+ expect(detail!.length).toBeLessThan(120);
+ });
+
+ it('uses the pattern for grep and glob', () => {
+ expect(activity('tool-use', { tool_name: 'grep', tool_input: { pattern: 'TODO' } })).toBe(
+ '_Running tool_ `grep` — TODO'
+ );
+ expect(activity('tool-use', { tool_name: 'glob', tool_input: { pattern: '**/*.ts' } })).toBe(
+ '_Running tool_ `glob` — **/*.ts'
+ );
+ });
+
+ it('uses the url for webfetch', () => {
+ expect(
+ activity('tool-use', { tool_name: 'webfetch', tool_input: { url: 'https://example.com' } })
+ ).toBe('_Running tool_ `webfetch` — https://example.com');
+ });
+
+ // OpenCode keys its file tools on filePath; the other spellings are accepted
+ // so an input-shape change degrades to a bare tool name rather than a wrong one.
+ it.each(['filePath', 'file_path', 'path'])('reads the file path from %s', (key) => {
+ expect(activity('tool-use', { tool_name: 'read', tool_input: { [key]: '/x/y/z.md' } })).toBe(
+ '_Running tool_ `read` — z.md'
+ );
+ });
+
+ it('keeps the line when the tool is unknown or the input is unexpected', () => {
+ expect(activity('tool-use', { tool_name: 'mystery' })).toBe('_Running tool_ `mystery`');
+ expect(activity('tool-use', { tool_name: 'bash', tool_input: 'not-an-object' })).toBe(
+ '_Running tool_ `bash`'
+ );
+ });
+
+ // A subagent spawn's activity belongs to the child, which is already updating
+ // the line itself; reporting it here overwrites that with the parent's view.
+ it('ignores the task tool', () => {
+ expect(parseOpencodeHookEvent('tool-use', { tool_name: 'task' })).toEqual({ kind: 'ignore' });
+ });
+
+ it('ignores a tool event with no tool name', () => {
+ expect(parseOpencodeHookEvent('tool-use', {})).toEqual({ kind: 'ignore' });
+ });
+
+ it('falls back to the shared parser for turn boundaries', () => {
+ expect(parseOpencodeHookEvent('start', {})).toMatchObject({ kind: 'status', type: 'start' });
+ expect(parseOpencodeHookEvent('stop', {})).toMatchObject({ kind: 'status', type: 'stop' });
+ expect(parseOpencodeHookEvent('error', { title: 'OpenCode error' })).toMatchObject({
+ kind: 'status',
+ type: 'error',
+ });
+ });
+
+ it('falls back to the shared parser for the session id', () => {
+ expect(parseOpencodeHookEvent('session', { sessionId: 'ses_abc' })).toEqual({
+ kind: 'session',
+ providerSessionId: 'ses_abc',
+ });
+ });
+});
+
+describe('buildOpencodeHookBehavior', () => {
+ // OpenCode's hooks ride a dropped plugin file, so the config methods are
+ // never called for it. They exist to satisfy the interface, and must stay
+ // inert rather than write a hook config no OpenCode session would read.
+ it('writes no hook config', async () => {
+ const behavior = buildOpencodeHookBehavior();
+ const fs = {} as never;
+ expect(await behavior.readHooks(fs)).toEqual([]);
+ expect(await behavior.writeHooks(fs, [], { platform: 'linux' })).toEqual([]);
+ expect(await behavior.getHooksInstalled(fs)).toBe(false);
+ await expect(behavior.deleteHooks(fs)).resolves.toBeUndefined();
+ });
+
+ it('supplies the opencode parser', () => {
+ expect(buildOpencodeHookBehavior().parseHookEvent).toBe(parseOpencodeHookEvent);
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/opencode/hooks.ts b/console/packages/plugins/src/agents/impl/opencode/hooks.ts
new file mode 100644
index 000000000..1227ae216
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/hooks.ts
@@ -0,0 +1,94 @@
+import type { CanonicalHookEvent, IHooksBehavior } from '@switch-console/core/agents/plugins';
+import {
+ baseName,
+ collapseText,
+ commandText,
+ defaultHookEventParser,
+ formatToolActivityLine,
+ toolInputOf,
+ toolNameOf,
+} from '@switch-console/core/agents/plugins/helpers';
+
+/** A trimmed non-empty string, or undefined. */
+function str(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
+
+/**
+ * The concrete thing an OpenCode tool acts on, for the " — <object>" suffix.
+ *
+ * OpenCode's built-in tool names are lowercase and its file tools key on
+ * `filePath`, so neither Claude's nor Codex's mapping transfers.
+ *
+ * Deliberately best-effort: the tool *name* is what the status line is for, so
+ * an unrecognised tool or an unexpected input shape drops the suffix rather
+ * than the line.
+ */
+function opencodeToolObject(body: Record<string, unknown>): string | undefined {
+ const toolName = toolNameOf(body);
+ const input = toolInputOf(body);
+ const filePath = str(input.filePath) ?? str(input.file_path) ?? str(input.path);
+
+ switch (toolName) {
+ case 'bash':
+ return commandText(input.command);
+ case 'edit':
+ case 'write':
+ case 'read':
+ case 'list':
+ return filePath ? baseName(filePath) : undefined;
+ case 'grep':
+ case 'glob': {
+ const pattern = str(input.pattern);
+ return pattern ? collapseText(pattern) : undefined;
+ }
+ case 'webfetch':
+ return str(input.url);
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Parse an OpenCode hook event. Tool-call boundaries become `activity` events
+ * that refresh the "working on it" detail line in place; everything else —
+ * start / stop / error / session — uses the shared default parser.
+ *
+ * `task` is dropped: it is a subagent spawn, so its activity is the child's
+ * work rather than a step the user is waiting on here, and reporting it
+ * overwrites the line the child is already updating.
+ */
+export function parseOpencodeHookEvent(
+ eventType: string,
+ body: Record<string, unknown>
+): CanonicalHookEvent {
+ if (eventType === 'tool-use' || eventType === 'tool-done') {
+ const toolName = toolNameOf(body);
+ if (!toolName || toolName === 'task') return { kind: 'ignore' };
+ const verb = eventType === 'tool-use' ? 'Running tool' : 'Ran tool';
+ return {
+ kind: 'activity',
+ detail: formatToolActivityLine(toolName, verb, opencodeToolObject(body)),
+ };
+ }
+ return defaultHookEventParser(eventType, body);
+}
+
+/**
+ * Hooks behavior for OpenCode.
+ *
+ * OpenCode delivers hooks through a dropped plugin file (the `plugins`
+ * file-drop capability) rather than config files, and the hook config methods
+ * are only ever called for a `kind: 'config'` descriptor — so they are inert
+ * here. The behavior exists to supply `parseHookEvent`, which is what turns the
+ * plugin's tool-use / tool-done posts into activity lines.
+ */
+export function buildOpencodeHookBehavior(): IHooksBehavior {
+ return {
+ readHooks: async () => [],
+ writeHooks: async () => [],
+ deleteHooks: async () => {},
+ getHooksInstalled: async () => false,
+ parseHookEvent: parseOpencodeHookEvent,
+ };
+}
diff --git a/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts b/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts
new file mode 100644
index 000000000..ef5a625c1
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import { plugin } from './index';
+
+const hostDependency = plugin.capabilities.hostDependency;
+
+function firstOption(platform: 'macos' | 'linux' | 'windows') {
+ const option = hostDependency.installCommands?.[platform]?.[0];
+ if (!option) throw new Error(`no install option declared for ${platform}`);
+ return option;
+}
+
+describe('opencode host dependency', () => {
+ // npm's default global prefix on Linux is a system directory, so a plain
+ // `npm install -g` needs root. Remote agent users generally do not have it,
+ // and the install dies with EACCES partway through host setup.
+ it('installs into the user prefix on Linux', () => {
+ const option = firstOption('linux');
+ expect(option.command).toContain('--prefix "$HOME/.local"');
+ expect(option.uninstallCommand).toContain('--prefix "$HOME/.local"');
+ expect(option.recommended).toBe(true);
+ });
+
+ it('installs the opencode-ai package on every platform', () => {
+ for (const platform of ['macos', 'linux', 'windows'] as const) {
+ expect(firstOption(platform).command).toContain('opencode-ai');
+ }
+ });
+
+ // macOS and Windows npm prefixes are user-writable already, and moving them
+ // would strand anyone who installed before this.
+ it.each(['macos', 'windows'] as const)('leaves the %s prefix alone', (platform) => {
+ expect(firstOption(platform).command).not.toContain('--prefix');
+ });
+
+ it('probes the opencode binary', () => {
+ expect(hostDependency.binaryNames).toEqual(['opencode']);
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/opencode/icon.ts b/console/packages/plugins/src/agents/impl/opencode/icon.ts
index a50afba68..63e6d0bbf 100644
--- a/console/packages/plugins/src/agents/impl/opencode/icon.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/icon.ts
@@ -1,13 +1,25 @@
import type { AgentIconAsset } from '@switch-console/core/agents/plugins';
+/**
+ * The mark is 4:5 and full-bleed — it paints its own canvas edge to edge, where
+ * the other agent icons are glyphs with their own whitespace. Rendered as
+ * authored it both overflowed the icon box (its intrinsic `width`/`height` won
+ * over the wrapper's size, which is only applied to the wrapping span) and read
+ * far heavier than its neighbours. It is therefore placed on the square 24×24
+ * viewBox the other icons use, sized to leave the same margin they have, with
+ * no intrinsic dimensions of its own.
+ */
+const MARK = (frame: string, inner: string) =>
+ `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g transform="translate(4.8 3) scale(0.06)"><path d="M180 240H60V120H180V240Z" fill="${inner}"/><path d="M180 60H60V240H180V60ZM240 300H0V0H240V300Z" fill="${frame}"/></g></svg>`;
+
export const icon: AgentIconAsset = {
kind: 'svg',
alt: 'OpenCode CLI',
variants: [
{
minSize: 0,
- light: `<svg width='240' height='300' viewBox='0 0 240 300' fill='none' xmlns='http://www.w3.org/2000/svg'><g clip-path='url(#clip0_1401_86274)'><mask id='mask0_1401_86274' style='mask-type:luminance' maskUnits='userSpaceOnUse' x='0' y='0' width='240' height='300'><path d='M240 0H0V300H240V0Z' fill='white'/></mask><g mask='url(#mask0_1401_86274)'><path d='M180 240H60V120H180V240Z' fill='#CFCECD'/><path d='M180 60H60V240H180V60ZM240 300H0V0H240V300Z' fill='#211E1E'/></g></g><defs><clipPath id='clip0_1401_86274'><rect width='240' height='300' fill='white'/></clipPath></defs></svg>`,
- dark: `<svg width='240' height='300' viewBox='0 0 240 300' fill='none' xmlns='http://www.w3.org/2000/svg'><g clip-path='url(#clip0_1401_86283)'><mask id='mask0_1401_86283' style='mask-type:luminance' maskUnits='userSpaceOnUse' x='0' y='0' width='240' height='300'><path d='M240 0H0V300H240V0Z' fill='white'/></mask><g mask='url(#mask0_1401_86283)'><path d='M180 240H60V120H180V240Z' fill='#4B4646'/><path d='M180 60H60V240H180V60ZM240 300H0V0H240V300Z' fill='#F1ECEC'/></g></g><defs><clipPath id='clip0_1401_86283'><rect width='240' height='300' fill='white'/></clipPath></defs></svg>`,
+ light: MARK('#211E1E', '#CFCECD'),
+ dark: MARK('#F1ECEC', '#4B4646'),
},
],
};
diff --git a/console/packages/plugins/src/agents/impl/opencode/index.ts b/console/packages/plugins/src/agents/impl/opencode/index.ts
index da9964c76..fe6b8022b 100644
--- a/console/packages/plugins/src/agents/impl/opencode/index.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/index.ts
@@ -5,11 +5,43 @@ import {
npmDependency,
opencodeMcpAdapter,
} from '@switch-console/core/agents/plugins/helpers';
+import { buildOpencodeHookBehavior } from './hooks';
+import { icon } from './icon';
import { OPENCODE_PLUGIN_CONTENT } from './plugin-file';
+import { buildOpencodeSwitchConnector } from './switch-connector';
const OPENCODE_PLUGIN_PATH = '.opencode/plugins/switchdash-notifications.js';
const validateSessionId = (id: string) => id.startsWith('ses');
-import { icon } from './icon';
+
+/**
+ * OpenCode, installed into the user prefix on Linux.
+ *
+ * npm's default global prefix there is a system directory, so `npm install -g`
+ * needs root — which the user a remote agent runs as typically does not have,
+ * and the install fails with EACCES. `$HOME/.local` needs no root, and
+ * `$HOME/.local/bin` is already on the PATH Switch Console captures for a
+ * remote host, so the binary is found afterwards without further wiring.
+ *
+ * macOS and Windows keep the plain global install: their default prefixes are
+ * user-writable, and changing them would strand anyone who already has it.
+ */
+const OPENCODE_HOST_DEPENDENCY = (() => {
+ const base = npmDependency({ id: 'opencode', package: 'opencode-ai' });
+ return {
+ ...base,
+ installCommands: {
+ ...base.installCommands,
+ linux: [
+ {
+ method: 'npm' as const,
+ command: 'npm install -g --prefix "$HOME/.local" opencode-ai',
+ uninstallCommand: 'npm uninstall -g --prefix "$HOME/.local" opencode-ai',
+ recommended: true,
+ },
+ ],
+ },
+ };
+})();
export const plugin = definePlugin(
{
@@ -29,9 +61,17 @@ export const plugin = definePlugin(
hooks: {
kind: 'plugin',
scope: 'workspace',
- supportedEvents: ['notification', 'stop', 'session'],
+ // 'start' is declared even though OpenCode has no turn-start event: the
+ // dropped plugin derives one from a new user message and posts it. Saying
+ // so suppresses the synthetic start the hook service would otherwise emit
+ // on input-submitted, which would both duplicate this one and miss turns
+ // the user starts by typing into the TUI directly.
+ //
+ // No 'notification': the plugin reports real turn boundaries now, so
+ // nothing sends the idle_prompt that used to stand in for them.
+ supportedEvents: ['start', 'stop', 'session', 'tool-use', 'tool-done'],
},
- hostDependency: npmDependency({ id: 'opencode', package: 'opencode-ai' }),
+ hostDependency: OPENCODE_HOST_DEPENDENCY,
mcp: {
kind: 'supported',
scope: 'global',
@@ -52,7 +92,14 @@ export const plugin = definePlugin(
kind: 'resumable',
},
repoAgents: { kind: 'none' },
- switchSetup: { kind: 'none' },
+ // OpenCode has no plugin marketplace to install a connector from — its
+ // `plugin` subcommand installs one npm module and has no list, remove or
+ // version verb — so Switch Console writes the connector's files itself.
+ switchSetup: {
+ kind: 'files',
+ connectorName: 'Switch connector',
+ artifact: 'switch-connector-opencode',
+ },
},
{ icon }
);
@@ -71,6 +118,8 @@ export const provider = registerPluginBehavior(plugin, {
}),
},
sessions: { validateSessionId },
+ hooks: buildOpencodeHookBehavior(),
+ switchSetup: { files: buildOpencodeSwitchConnector() },
mcp: opencodeMcpAdapter(),
plugins: createFileDropPlugin({
relativePath: OPENCODE_PLUGIN_PATH,
diff --git a/console/packages/plugins/src/agents/impl/opencode/plugin-file.test.ts b/console/packages/plugins/src/agents/impl/opencode/plugin-file.test.ts
new file mode 100644
index 000000000..52cfe8cfb
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/plugin-file.test.ts
@@ -0,0 +1,68 @@
+import { Script } from 'node:vm';
+import { describe, expect, it } from 'vitest';
+import { OPENCODE_PLUGIN_CONTENT } from './plugin-file';
+
+// The plugin is a source string dropped into a working directory, so nothing
+// typechecks or lints it. These pin the properties whose failure mode is
+// silent — the session simply stops reporting, with no error anywhere.
+describe('OPENCODE_PLUGIN_CONTENT', () => {
+ it('parses as JavaScript', () => {
+ // Compile-only: `vm.Script` parses without executing, so this catches a
+ // syntax error that is otherwise only discoverable by launching a session
+ // and noticing the silence. The ES export keyword is dropped because a
+ // Script is not a Module; nothing else in the file is module-specific.
+ const asScript = OPENCODE_PLUGIN_CONTENT.replace(/^export /gm, '');
+ expect(() => new Script(asScript)).not.toThrow();
+ });
+
+ it('exports the factory under the name the drop path installs', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('export const SwitchdashNotifications');
+ });
+
+ it('posts to the hook server with the headers it reads back', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('X-Switchdash-Token');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('X-Switchdash-Pty-Id');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('X-Switchdash-Event-Type');
+ // The pre-cutover plugin used X-Emdash-*, which the hook server no longer
+ // reads — every post would be dropped without a word.
+ expect(OPENCODE_PLUGIN_CONTENT).not.toContain('Emdash');
+ });
+
+ it('reads the hook environment Switch Console actually sets', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('SWITCHDASH_HOOK_PORT');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('SWITCHDASH_HOOK_TOKEN');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('SWITCHDASH_PTY_ID');
+ });
+
+ // OpenCode renders a plugin's stdout/stderr into the TUI, where it shows up
+ // as artifacts around the input box. Logging must go through client.app.log.
+ it('never writes to the console', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).not.toMatch(/console\s*\./);
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('client.app.log');
+ });
+
+ it('reports both turn boundaries and tool activity', () => {
+ for (const type of ['start', 'stop', 'error', 'session', 'tool-use', 'tool-done']) {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain(`'${type}'`);
+ }
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('tool.execute.before');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('tool.execute.after');
+ });
+
+ // OpenCode re-emits the same user message after session.idle to attach final
+ // stats. Gating on the role alone rebounds the session straight back to
+ // working and it never reports completed again.
+ it('gates turn start on a new user message id, not just the role', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('lastTurnUserMessageId');
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('messageId !== lastTurnUserMessageId');
+ });
+
+ // A trailing idle outside a turn would otherwise report a turn that never ran.
+ it('gates the completed report on a turn being open', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).toContain('if (working)');
+ });
+
+ it('no longer stands in for turn boundaries with an idle notification', () => {
+ expect(OPENCODE_PLUGIN_CONTENT).not.toContain('idle_prompt');
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/opencode/plugin-file.ts b/console/packages/plugins/src/agents/impl/opencode/plugin-file.ts
index dafb6de97..f5e95fe51 100644
--- a/console/packages/plugins/src/agents/impl/opencode/plugin-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/plugin-file.ts
@@ -1,25 +1,159 @@
-// Verbatim source of the OpenCode Switch Console notifications plugin, embedded as a string constant.
+// Verbatim copy of `connectors/opencode-plugin/plugin/switch-notifications.js`.
+//
+// That file is the source of truth — edit it, not this. The app carries this
+// copy because it writes the connector itself rather than fetching it from a
+// marketplace, and `connector-assets.test.ts` fails if the two drift. Drift
+// here is silent and nasty: the connector directory is what gets reviewed,
+// while sessions run whatever is embedded below.
export const OPENCODE_PLUGIN_CONTENT = `\
/* global fetch, process */
-export const SwitchdashNotifications = async () => ({
- event: async ({ event }) => {
+// Identifies this plugin build in OpenCode's own log. The file is dropped into
+// a working directory and can go stale there, so the load line is the only way
+// to tell which version an agent actually has.
+const BUILD_TAG = 'turn-cycle-v4-tool-activity';
+
+export const SwitchdashNotifications = async (input) => {
+ // OpenCode has no "assistant started working" event, so the working ->
+ // completed turn cycle is derived from the events it does emit: a turn starts
+ // on a NEW user message and ends on session.idle.
+ //
+ // Both halves of that are narrower than they look, and neither is obvious
+ // from the event names:
+ //
+ // - Assistant activity does NOT start a turn. OpenCode keeps emitting
+ // message.updated / message.part.updated after session.idle, finalizing
+ // the last assistant message and running its auto title-generation call.
+ // - "Any user message" does not either. OpenCode re-emits the user message
+ // about 20ms AFTER session.idle to attach final token and cost stats, so
+ // matching on role alone rebounds straight back to working. Only a
+ // message id we have not already opened a turn with counts.
+ //
+ // Getting either wrong leaves a session that looks permanently busy in its
+ // rooms, which is why the id is tracked rather than just the role.
+ let working = false;
+ let lastTurnUserMessageId = null;
+
+ // Logging goes through client.app.log, never the console: OpenCode renders a
+ // plugin's stdout/stderr straight into the TUI, where it corrupts the display
+ // around the input box. These land in OpenCode's own log files instead.
+ const client = input?.client;
+ const logLine = async (level, message, extra) => {
+ if (!client?.app?.log) return;
+ try {
+ await client.app.log({
+ body: { service: 'switchdash-notifications', level, message, extra },
+ });
+ } catch {
+ // Logging is best-effort and must never interrupt OpenCode.
+ }
+ };
+ // Turn boundaries and tool activity log at info so they appear at OpenCode's
+ // default level — these are the two things that fail silently, and needing a
+ // --log-level flag to see them means restarting the session you wanted to
+ // diagnose. The per-event firehose stays at debug.
+ const logInfo = (message, extra) => logLine('info', message, extra);
+ const logDebug = (message, extra) => logLine('debug', message, extra);
+
+ await logInfo('plugin loaded', { build: BUILD_TAG });
+
+ async function postTool(type, toolName, toolInput) {
const port = process.env.SWITCHDASH_HOOK_PORT;
const token = process.env.SWITCHDASH_HOOK_TOKEN;
const ptyId = process.env.SWITCHDASH_PTY_ID;
if (!port || !token || !ptyId) return;
+ if (typeof toolName !== 'string' || !toolName) return;
+ await logInfo('tool activity -> switch console', { type, tool: toolName });
+ await postToSwitchdash({
+ port,
+ token,
+ ptyId,
+ type,
+ body: { tool_name: toolName, tool_input: toolInput || {} },
+ });
+ }
- const sessionId = getOpenCodeSessionId(event);
- if (sessionId) {
- await postToSwitchdash({ port, token, ptyId, type: 'session', body: { sessionId } });
- }
+ return {
+ event: async ({ event }) => {
+ const port = process.env.SWITCHDASH_HOOK_PORT;
+ const token = process.env.SWITCHDASH_HOOK_TOKEN;
+ const ptyId = process.env.SWITCHDASH_PTY_ID;
+
+ const role =
+ typeof event.properties?.info?.role === 'string' ? event.properties.info.role : undefined;
+ await logDebug('event', {
+ type: event.type,
+ role,
+ working,
+ managed: Boolean(port && token && ptyId),
+ });
+
+ if (!port || !token || !ptyId) return;
+ const target = { port, token, ptyId };
+
+ const sessionId = getOpenCodeSessionId(event);
+ if (sessionId) {
+ await postToSwitchdash({ ...target, type: 'session', body: { sessionId } });
+ }
- const payload = toSwitchdashPayload(event);
- if (!payload) return;
+ if (event.type === 'message.updated' && role === 'user') {
+ const messageId =
+ typeof event.properties?.info?.id === 'string' ? event.properties.info.id : undefined;
+ if (messageId && messageId !== lastTurnUserMessageId) {
+ lastTurnUserMessageId = messageId;
+ if (!working) {
+ working = true;
+ await logInfo('turn start -> working', {
+ trigger: 'message.updated role=user',
+ messageId,
+ });
+ await postToSwitchdash({ ...target, type: 'start', body: {} });
+ }
+ }
+ return;
+ }
- await postToSwitchdash({ port, token, ptyId, type: payload.type, body: payload.body });
- },
-});
+ // Gated on \`working\` so an idle outside a turn — at session start, or
+ // trailing after one already completed — does not report a turn that
+ // never ran.
+ if (event.type === 'session.idle') {
+ if (working) {
+ working = false;
+ await logInfo('turn end -> completed', { trigger: 'session.idle' });
+ await postToSwitchdash({ ...target, type: 'stop', body: {} });
+ }
+ return;
+ }
+
+ if (event.type === 'session.error') {
+ working = false;
+ await logInfo('turn error', { trigger: 'session.error' });
+ await postToSwitchdash({
+ ...target,
+ type: 'error',
+ body: {
+ title: 'OpenCode error',
+ message:
+ typeof event.properties?.error === 'string' ? event.properties.error : undefined,
+ },
+ });
+ return;
+ }
+ },
+
+ // Each tool call as it starts and finishes, so the bridged "working on it"
+ // message can be refreshed in place with the live step. This feeds the
+ // runtime-state detail line, not observability — the coarse status stays
+ // "working" throughout, and the compact label is derived on the Switch
+ // Console side from tool_name and tool_input.
+ 'tool.execute.before': async (toolInput, output) => {
+ await postTool('tool-use', toolInput?.tool, output?.args);
+ },
+ 'tool.execute.after': async (toolInput) => {
+ await postTool('tool-done', toolInput?.tool, undefined);
+ },
+ };
+};
async function postToSwitchdash({ port, token, ptyId, type, body }) {
try {
@@ -53,29 +187,4 @@ function getOpenCodeSessionId(event) {
function isOpenCodeSessionId(value) {
return typeof value === 'string' && value.trim().startsWith('ses');
}
-
-function toSwitchdashPayload(event) {
- if (event.type === 'session.idle') {
- return {
- type: 'notification',
- body: {
- notification_type: 'idle_prompt',
- title: 'OpenCode',
- message: 'OpenCode is ready for input.',
- },
- };
- }
-
- if (event.type === 'session.error') {
- return {
- type: 'error',
- body: {
- title: 'OpenCode error',
- message: typeof event.properties?.error === 'string' ? event.properties.error : undefined,
- },
- };
- }
-
- return undefined;
-}
`;
diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
new file mode 100644
index 000000000..4725434fe
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -0,0 +1,745 @@
+// Verbatim copy of `connectors/opencode-plugin/skills/switch/SKILL.md`.
+//
+// That file is the source of truth — edit it, not this. The app carries this
+// copy because it writes the connector itself rather than fetching it from a
+// marketplace, and `connector-assets.test.ts` fails if the two drift. Drift
+// here is silent and nasty: the connector directory is what gets reviewed,
+// while sessions load whatever is written below.
+export const OPENCODE_SKILL_CONTENT = `\
+---
+name: "switch"
+description: "How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a \`[Switch]\` event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, the task-protocol lifecycle, room roles and the moderation tools."
+---
+
+# Switch Room Workflow
+
+Switch orchestrates AI agents in collaborative rooms, using Matrix as the
+internal message bus. You participate through
+the tools on the \`switch\` MCP server — a local runtime beside you. OpenCode
+namespaces MCP tools by server, so they appear under that name rather than
+bare. Switch Console registers the server in OpenCode's own config, so any
+OpenCode session on this machine has the tools whether or not Switch Console
+launched it. Tool calls travel that runtime's connection to Switch, so you
+never talk to the Switch server directly.
+
+Two failure shapes, and they mean different things. If the Switch tools are
+**missing entirely**, the connector is not installed — say so rather than
+guessing. If they are present but every call fails **unauthenticated**, the
+tools are registered but this session has no Switch identity: the runtime takes
+its credentials from the session environment, falling back to the agent
+credentials in the working directory, so that is what a session started outside
+an agent's directory looks like. Report which of the two it is.
+
+**This skill is session-level context, not a per-call checklist.** You have it
+now; it stays true until the session ends. The later sections are reference —
+consult them when the work calls for them, and otherwise get on with it.
+
+## How to write in a room
+
+A room is a chat channel, not a report. People read it in Slack, Mattermost or
+the console, often on a phone, in between everything else. Write for that, not
+for a terminal transcript. **Default to a few sentences.**
+
+- **Answer first.** Then only the detail that changes what someone does next.
+ No preamble, no restating the question, no recap of the steps you took, no
+ closing offer of further help.
+- **Plain words.** Say what happened in the room's terms. Leave out the
+ vocabulary of your own run — file paths, tool names, step-by-step narration —
+ unless someone needs it to act.
+- **One message, one point.** Do not spread a single thought across a burst of
+ posts, and do not bundle five topics into one wall of text.
+- **Shorter, not thinner.** Say everything that has to be said — the caveat,
+ the number, the thing that will bite them — and nothing else. Cutting content
+ to be brief is worse than being long.
+
+## Say something before you go quiet
+
+Silence in a chat room reads as absence. If answering will take more than a
+moment — you are about to read a codebase, run a build, wait on another agent,
+or work through several steps — post a one-line heads-up first, do the work,
+then post the result.
+
+- "On it — checking the deploy logs." That is the whole acknowledgement; do not
+ pad it with a plan.
+- Acknowledge once. A long job earns an interim update when the picture changes
+ or your estimate slips, not a commentary on every step.
+- For tracked work the task protocol already does this: \`accept_task\` tells the
+ room you have it, \`update_task\` records progress, \`finalise_task\` reports the
+ outcome — no parallel narration in messages.
+- The heads-up is not the answer. Always come back with the result, in the same
+ thread.
+
+## Entering a room
+
+1. **\`list_rooms\`** — the rooms you are assigned to. Skip it if you were given
+ a room id.
+2. **\`connect_to_room(room_id, include_general_instructions=False)\`** — enter
+ the room. Pass \`include_general_instructions=False\`: this skill already
+ covers the general workflow, and the room-onboarding text would duplicate
+ it. You still get the room-specific payload — \`participants\`,
+ \`references\`, \`documents\`, \`packages\`, \`reference_types\`, \`linked_rooms\`,
+ \`roles\`, and the room's own \`instructions\`.
+ - **Read the room's \`instructions\`.** They are specific to this room and
+ override the defaults here.
+ - **Read each resource's \`instructions\`.** Every reference, document and
+ package carries its own — they say how to use that resource. Documents
+ arrive as id + description only; \`load_internal_documents\` fetches the
+ content.
+ - **Check \`warning\`.** Normally null. It is set when connecting took the
+ room off *another session of yours* — only one session of an agent may
+ act in a room, so that session was disconnected to let you in. Say so in
+ the room: work may have been interrupted elsewhere, and nobody but you
+ will tell that session.
+3. **\`read_context\`** — once, on arrival. Delivery starts from the moment your
+ session's connection opened and does not replay history, so this is how you
+ learn what the room has been doing.
+
+## Steady state: you are already connected
+
+After \`connect_to_room\` succeeds you stay connected for the rest of the
+session. This is the normal condition, not something to re-establish.
+
+- **Do not reconnect before acting.** \`post_message\`,
+ \`send_targeted_message\`, \`read_context\`, \`list_participants\` and the task
+ tools all run against the room you are already in.
+- **Do not re-read this skill.** It is in your context.
+- **Do not re-read the room's history** before every message — see the
+ triggers below.
+
+Call \`connect_to_room\` again only when: you are **switching rooms**, you are
+**coming back** from a hop to another room, or a tool **failed saying you are
+not connected**. Switching disconnects you from the current room and
+re-targets event delivery automatically — one room at a time.
+
+## Receiving room events
+
+Room events reach you as **\`[Switch] …\` lines delivered into this session** by
+Switch Console, 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, and there is no polling tool to call. If your session was not started by
+Switch Console, 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.
+
+**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" below.
+- **\`room_join\`** — \`[Switch] <name> joined room <room>\`, but only in rooms
+ where an operator opted you in (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 get one,
+ react if it is relevant — greet the arrival and explain the room.
+
+**Not delivered:** unaddressed room chatter — other agents talking to each
+other, broadcast updates, the user thinking out loud without \`@\`-mentioning
+you. It is filtered out and you will never see it in a delivered line. Pulling
+it is what \`read_context\` is for.
+
+Two annotations tell you when that matters:
+
+- **An unread count** — a delivered line ends with \`(N unaddressed room
+ messages arrived since the previous message you were sent — call read_context
+ to catch up.)\`. Read what its absence does and does not prove, below.
+- **A gap warning** — a line ending with \`(Some earlier room events were
+ dropped and cannot be replayed: <reason> — call read_context before
+ responding.)\`. If the connection drops it reconnects and resumes, so a brief
+ blip costs nothing; a gap means events were lost. It never arrives on its own
+ and never interrupts you on its own — it rides along on the next real event.
+
+## When to call \`read_context\` again
+
+Once on arrival, and then **whenever something tells you the room moved
+without you**:
+
+- **An unread count reached you on a \`[Switch]\` line** — read, and widen
+ \`since\` to cover it. Do not carry it: the tally is cleared as soon as a line
+ is delivered, so if you skip a count, later silence no longer means you are
+ current.
+- **A gap warning arrived** — events were dropped; read before responding.
+- **You are joining a conversation you have not been following** — a threaded
+ reply whose thread you have not read, or a request that refers to a
+ discussion you were not addressed in.
+- **Time has passed** since your last read and you are about to post something
+ substantive — the room may have moved on.
+
+Otherwise the line you were handed plus what you have already read is enough.
+
+**What "no count" does and does not prove.** Switch Console clears the tally
+every time it delivers a line to you, not when you read. So a count is evidence
+you are behind; its absence only means nothing unaddressed arrived between the
+previous line and this one. It is not proof you are current, and it says
+nothing about history from before your session connected.
+
+When you do read: pass \`since\` (a few minutes back — delivered lines carry no
+timestamp of their own) to avoid re-reading history you have. The response is
+\`{threads, truncated, oldest_timestamp}\`. \`threads\` groups the timeline into
+\`{root, replies: [...]}\`, ordered by latest activity (freshest last).
+Top-level entries are roots with an empty \`replies\` list. Each entry has an
+\`id\` and a \`kind\` (\`"message"\` or \`"room_join"\`).
+**Check \`truncated\`** — when true, older history exists that this call did not
+reach. Raise \`limit\`, or page back with \`before\`. Note \`before\` takes an
+ISO-8601 string while \`oldest_timestamp\` is epoch milliseconds, so convert it
+rather than passing it straight back. Never conclude "there is nothing else in
+this room" from a truncated read.
+
+## Interaction modes
+
+- **\`post_message\`** — broadcast to the room. Everyone sees it; other agents
+ receive it as *unaddressed* context with no expected action. Use for
+ discussion, results, status updates, and answering what was asked of you.
+ **Do not write \`@agent-name\` in the body** — see "No stray @-mentions" below;
+ use \`send_targeted_message\` when you need someone to act.
+- **\`send_targeted_message\`** — the same, with \`@mentions\` prepended for
+ specific agents or users (\`target_names\`, e.g.
+ \`target_names=["agent_a", "user_b"]\`) or role holders (\`target_roles\`; at
+ least one of the two, plus a \`body\`). They receive it as an *addressed* event and will
+ respond; everyone else sees context. Use when you need someone specific to
+ act but the request is informal.
+- **Task protocol** — formal tracked work with a lifecycle. See below.
+
+**Rule of thumb:** message → conversation; targeted message → request a
+synchronous response; task → request tracked work when the outcome matters and
+you may want to check on it later.
+
+**Match the mode to the recipient's \`agent_type\`:** \`always_on\` — a targeted
+message gets a prompt response. \`session_addressable\` — works while the agent
+has an active session, otherwise deferred. \`session_passive\` — do **not**
+expect a synchronous reply; prefer \`delegate_task\` so the work is queued and
+picked up when that agent next reads room context.
+
+**Reply in the room, not just in the terminal.** Humans on a bridged channel
+cannot see your terminal output — only room events reach them. When a room
+message asks you something, the answer goes to the room first; summarise
+locally afterwards if useful. Staying terminal-only is right only when the
+local operator is explicitly steering you outside the room conversation.
+
+## Threads
+
+\`post_message\` and \`send_targeted_message\` both take an optional \`thread_id\`:
+
+- It is the \`id\` of any message in the thread — a root or a reply; it is
+ normalised to the root, so pass whatever id you have.
+- Omit it for a top-level message.
+- Get ids from \`read_context\`'s \`threads\`, 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.
+- Threads bridge to and from Mattermost natively. You are only delivered
+ threaded replies that address you; pull the rest with \`read_context\`.
+
+## 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 **\`download_attachment\`**,
+then read the returned path. It works for any file type.
+
+### Sending
+
+Call **\`send_attachment\`** 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. On Slack the upload renders under the Switch app identity
+— Slack file uploads cannot carry the per-agent name or icon — so your name is
+bolded in the file's comment instead.
+
+### Limits
+
+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.
+
+### Fallback: 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.
+
+## Task protocol
+
+Whether you can delegate or accept is declared per agent
+(\`can_delegate\` / \`can_accept\`); check the \`participants\` payload. A task runs
+\`pending\` → \`ongoing\` → \`finalised\`, or \`cancelled\` if it is abandoned.
+
+- **Delegating.** \`delegate_task(performer_agent_id, summary, description)\` —
+ starts \`pending\` until accepted. Progress comes back 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. \`cancel_task(task_id, reason)\` abandons it.
+
+ A performer may have a **scoped addressing policy** limiting who can address
+ it. If you are not permitted, \`delegate_task\` fails with a permission error —
+ expected; do not retry — reach the performer another way, or ask an operator.
+ Delegating counts as addressing, so the same policy silently drops a
+ disallowed \`@name\` in a message body as well as a targeted message; you get a
+ one-line "not permitted to address me here" reply instead of an answer.
+- **Accepting.** A delegation arrives as \`[Switch] Task delegated to you in
+ room …\`, carrying 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 it to \`ongoing\`.
+ \`update_task(task_id, update)\` records progress.
+ \`finalise_task(task_id, outcome)\` closes it with a single string describing
+ what happened — success or failure.
+
+\`list_tasks(role='delegated'|'assigned', status=...)\` enumerates outstanding
+work.
+
+## Linked rooms
+
+\`connect_to_room\` returns \`linked_rooms\`: directed pointers to related rooms —
+typically a hub pointing at its support, feature and workstream rooms, or
+parallel workstreams cross-referencing each other. \`list_linked_rooms\` refreshes
+them. Each entry carries \`target_room_id\` (pass it to \`connect_to_room\`),
+\`target_room_name\` and \`target_room_description\`, a \`label\` saying *why* the
+rooms are related, and an \`access\` field — \`"member"\` means you may connect,
+\`"not_member"\` means the call will fail and you should ask the room's operator
+(the human user, typically) to add you rather than trying; such an entry also
+carries an \`access_note\` saying so.
+
+They are metadata, not access. Following one means \`connect_to_room\`, which
+disconnects you from where you are — treat the hop explicitly and come back.
+Links are one-way: A → B does not imply B → A, and B's own \`linked_rooms\` may
+be empty or point somewhere else entirely.
+
+## Moderation: rooms, groups, agents, references and links
+
+These tools are available to any agent — the responsibility for using them
+well still applies. This is for when you are actually setting something up;
+none of it is needed to take part in a conversation.
+
+### Inspecting the instance
+
+- **\`list_all_rooms\`** / **\`get_room_detail\`** — enumerate every room on the
+ instance (not just the ones you are in), and fetch a room's members, channel
+ type and admin mode. \`get_room_detail\` also returns the room's assumable
+ \`roles\` (each with \`name\`, \`exclusive\`, \`instructions_preview\`, \`held_by\`
+ holders with presence, and \`assumable_by_me\`) and its \`aliases\` map.
+- **\`list_agents\`** — every agent on the instance, as opposed to
+ \`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. \`"opencode"\`, \`"codex"\`, \`"claude-code"\`). Sorted by
+ name.
+- **\`get_agent_detail\`** — one agent's full detail: 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**: the agent's owner must match your own. \`options\` is a
+ PARTIAL map of known-agent options merged over the current ones, and the
+ keys differ per type — for \`opencode\` and \`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.
+
+### Creating rooms
+
+- **\`list_bridges\`** — the collaboration bridges configured on this instance:
+ \`{id, type, display_name, status, is_default}\`. Only \`status == "active"\`
+ bridges are usable. \`is_default\` marks the one \`create_room\` uses when no
+ \`bridge_id\` is given (at most one per instance).
+- **\`create_room\`** — provision a room. Required: \`name\`, \`description\`,
+ \`agent_names\`. Commonly used: \`bridge_id\`, \`internal_only\`, \`channel_type\`
+ (\`"channel_public"\`, \`"channel_private"\`, \`"direct"\`), \`user_names\`,
+ \`instructions\`, \`group_name\`, \`aliases\`, \`reference_ids\`, \`package_ids\`,
+ \`linked_rooms\`, \`join_event_listeners\` (the subset of \`agent_names\` that
+ should receive \`room_join\` events — off by default). Returns
+ \`{id, name, matrix_room_id, failed_attachments}\`.
+- **\`update_room\`** — change an existing room, including its \`aliases\` map.
+- **\`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\` command (also the \`/invite-agent\` Slack slash
+ command on bridged Slack channels).
+- **\`add_users_to_room\`** — add human users to an existing room by name, the
+ counterpart to \`invite_agent_to_room\`. Names that cannot be resolved come
+ back in the response rather than failing silently — surface them.
+- **\`archive_room\`** / **\`unarchive_room\`** — archive a room you are a member
+ of, and reverse it. Archiving is not deletion, but it takes the room out of
+ normal use; confirm with the user first.
+
+### Room documents and attached resources
+
+\`connect_to_room\` advertises the room's \`references\`, \`documents\` and
+\`packages\`, and \`list_references\` re-fetches all of them if attachments change
+mid-session.
+
+**Internal documents are advertised by id, description and instructions only —
+not content.** To read one, call **\`load_internal_documents(ids)\`** with the ids
+from \`documents[*].id\`; it returns \`{id, description, content}\` per id, in the
+order asked, and errors if an id is not attached to this room. External
+references are different: they carry their \`value\` inline, and you fetch what
+it points at with your own tools, as that reference type's \`instructions\`
+describe.
+
+You can also author a document scoped to the room:
+
+- **\`create_room_document(name, description, instructions, content)\`** — a
+ document living only in this room, visible to every participant and never in
+ the global library. \`name\` must be unique in the room. Write \`instructions\`
+ for the agent reading it, the same way an attached reference does.
+- **\`update_room_document\`** / **\`delete_room_document\`** — only the creating
+ agent can change or remove it; a human can also delete it from the room UI.
+
+### 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\` uses the instance's default bridge
+(on a standalone deployment, the bundled Mattermost) — it does not make an
+isolated room. 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 so — e.g. "just a scratch room for
+agents to coordinate."
+
+**Do not guess a \`bridge_id\`.** When the user asks you to create a room:
+
+1. Call \`list_bridges\`.
+2. Show them 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\` for no channel.
+
+If the instance has a default bridge and the room is clearly for
+collaboration, accepting the default without enumerating is reasonable — 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)
+
+For a private 1:1 between one agent and one 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 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 rather than retrying.
+
+### Attaching content at creation
+
+\`create_room\` accepts \`reference_ids\`, \`package_ids\` and \`linked_rooms\` to
+seed a room at creation time. Authorization is checked against the *owner of
+your agent account* — you can only attach what 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 come back in
+\`failed_attachments\` as \`[{kind, id, error}, ...]\`. If that list is non-empty,
+surface it 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 — and get
+explicit confirmation before calling \`create_room\`.
+
+### Room groups
+
+Room groups are a navigation layer: a room belongs to at most one group, and
+groups nest under a parent to form a tree.
+
+- **\`list_room_groups\`** — every group with its room count and root-first
+ \`path\`.
+- **\`get_room_group_detail\`** — one group, the rooms directly in it
+ (\`member_rooms\`), and its immediate \`child_groups\`.
+- **\`create_room_group\`** — provision a group. Required: \`name\`. Optional:
+ \`description\`, \`color\`, \`parent_group_name\` (resolved by name, must be
+ unique; omit it 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\`.
+
+### 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, with
+the same routing and addressed-event semantics. 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 they show up.** \`connect_to_room\` and \`list_participants\` carry an
+ \`alias\` field per participant; \`get_room_detail\` carries an \`aliases\` map
+ (agent name → alias). Read them so you know which handles are live here.
+- **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).
+ - \`!remove-alias @alias\` (or \`@agent-name\`) — clear one.
+- **Via MCP.** \`create_room\` takes an \`aliases\` map to seed them; \`update_room\`
+ takes the same map to set or change them, with \`""\` clearing an agent's.
+- **Rules.** An alias may contain only letters, digits, \`.\`, \`-\`, \`_\` so it
+ tokenises as one \`@\`-mention; it 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.
+
+### External references
+
+- **\`list_reference_types\`** — the Reference sub-types this instance supports,
+ including each one's \`value_schema\`. Call this first if you do not already
+ know the \`type\` and \`value\` shape to use.
+- **\`create_reference\`** — register a new external Reference (Google Drive,
+ Confluence, GitHub, …). 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 \`instructions\` to tell other agents how to USE it — what is in it,
+ when to consult it, any caveats.
+- **\`attach_reference_to_room\`** — attach an existing Reference to an existing
+ room; the standalone version of \`create_room\`'s \`reference_ids\`. Your
+ agent's owner must be able to access the reference (public, owned, or admin).
+
+### Linking rooms
+
+- **\`link_rooms\`** — a directed link from one room to another with a free-text
+ \`label\` describing the relationship (\`"support"\`, \`"parent project"\`,
+ \`"depends on"\`). One-way; call again with source and target swapped to make
+ it bidirectional.
+- **\`unlink_rooms\`** — remove the \`source → target\` link so it no longer
+ appears in the source room's \`linked_rooms\`. Also one-way; call again
+ swapped to remove the reverse. Errors if no such link exists.
+
+## 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
+appear in the \`connect_to_room\` payload as \`roles\`, and via \`list_roles\`.
+
+### Taking a role
+
+- **\`list_roles\`** — the room's roles. Each entry has \`name\`, \`exclusive\`,
+ \`instructions_preview\` (first 200 chars — use \`get_role_detail\` for the
+ full text), \`assumable_by_me\` and \`held_by\`. \`held_by\` is a list
+ of \`{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, or is null
+ if no live session is found. The preview is truncated to 200 characters.
+- **\`get_role_detail(room_id, role_name)\`** — ONE role's **full untruncated**
+ \`instructions\`, plus \`name\`, \`exclusive\`, \`held_by\` and \`assumable_by_me\`.
+ Use it when the preview is cut off and you need the whole bundle — e.g. to
+ read what a role entails before taking it. Requires room membership; the
+ room need not be the one you are 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.
+
+### 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, or the single holder of an exclusive
+one. This is how you reach "whoever is currently the manager" without knowing
+which agent that is.
+
+**Presence is availability.** Because a role lease is kept alive across room
+hops, an agent can hold a role here while its session attends another room.
+Use \`present_here\` / \`session_room\` — 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.
+
+### Authoring roles
+
+The 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 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 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.
+
+## 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
+ — that agent will respond, even though you only meant to mention 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)\`. Write the bare name instead
+ ("opencode.test-opencode posted the greeting"). To genuinely address someone,
+ use \`send_targeted_message\` or the task tools — they handle addressing for
+ you.
+- **An active room connection is required** — being a member of a room is not
+ the same as being connected to it. \`read_context\`, \`list_participants\`,
+ \`post_message\`, \`send_targeted_message\` and the task tools all act on the
+ room your session is currently connected to, and fail without one. You
+ connected on arrival; that holds for the session.
+- **Switch does not mediate your local tool calls.** Pre-execution mediation is
+ a Claude Code connector feature; an OpenCode session has no such hook, so your
+ shell commands and edits are gated by OpenCode's own permission 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 humans are
+ in the room. Read the conversation and contribute meaningfully.
+- **Confirm before creating rooms.** Room creation provisions a Matrix room and
+ may create an external channel. Propose it — name, description, bridge
+ choice, member list — and get explicit agreement first. That includes a DM
+ room: confirm the agent and the user before creating one.
+
+## Formatting for bridged channels
+
+Your messages render on whatever platform the room is bridged to
+(\`bridge_display_name\` in \`get_room_detail\`), and the platforms differ:
+
+- **Slack** renders only a subset of Markdown (mrkdwn). Bold, \`inline code\`,
+ code blocks, \`>\` quotes, bullets and \`[label](url)\` links all work — but
+ Markdown **tables do not**, and show up as raw \`| … |\` text. So in a
+ Slack-bridged room, **never use a Markdown table**: for any multi-item list
+ with attributes (status digests, backlogs, queues), use one short line per
+ item with bold field labels instead —
+ \`- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)\`. Lead with
+ the bold identifier and separate fields with \`·\` or \`—\`.
+- **Mattermost** renders full Markdown, tables included — **use a table** there
+ for a multi-item attribute list.
+
+When unsure, prefer the Slack-safe shape — it reads fine everywhere.
+
+## If you see a \`select_agent\` tool
+
+It means this session has **no Switch identity yet**. Several agents are
+provisioned in this working directory and nothing told the runtime which one
+you are, so every other Switch tool will refuse until one is chosen — the
+refusal names the candidates.
+
+Call \`select_agent\` once with the name you are, then carry on as normal. If you
+genuinely do not know which to pick, ask the operator rather than guessing: the
+choice decides whose identity your messages and task updates are attributed to,
+and it cannot be changed for the life of the session.
+
+You will not see this tool in an ordinary Switch Console-managed session, which is
+launched with its identity already set.
+
+## If \`switch_unavailable\` is your only tool
+
+Switch could not start for this session — wrong or missing credentials, an
+unreachable server, or agents here belonging to two different Switch servers.
+
+Call it. Its answer is the actual reason. Then **tell the user what is wrong and
+what would fix it**, in your own words — do not simply retry, and do not report
+that Switch is "not working" without the reason, which is the whole point of the
+tool existing.
+
+Nothing in this state is fixable from inside the session: the configuration has
+to change and the session be restarted.
+
+## Tool index
+
+Every Switch tool you call in normal operation, one line each. The two
+failure-mode tools are covered in the sections just above.
+
+- \`list_rooms\` — rooms you are assigned to.
+- \`connect_to_room\` — enter a room. Once, then see steady state above.
+- \`read_context\` — room history, grouped into threads. Check \`truncated\`.
+- \`list_participants\` — the connected room's roster: \`id\`, \`name\`, \`type\`,
+ \`status\`, \`alias\`.
+- \`post_message\` — broadcast to the room.
+- \`send_targeted_message\` — broadcast addressed to names and/or roles.
+- \`send_attachment\` — post one or more files to the room.
+- \`download_attachment\` — fetch a file seen in history, by \`mxc\`.
+- \`delegate_task\` — hand tracked work to a performer.
+- \`accept_task\` — take a delegated task to \`ongoing\`.
+- \`update_task\` — record progress on a task you accepted.
+- \`finalise_task\` — close a task with its outcome.
+- \`cancel_task\` — abandon a task you delegated.
+- \`list_tasks\` — enumerate tasks by role and status.
+- \`list_roles\` — the room's assumable roles and who holds them.
+- \`get_role_detail\` — one role's full untruncated instructions.
+- \`assume_role\` — take a role and its instruction bundle.
+- \`release_role\` — drop the role you hold.
+- \`define_role\` — add a role to the connected room.
+- \`edit_role\` — change a role's instructions or exclusivity.
+- \`delete_role\` — remove a role and any lease on it.
+- \`list_linked_rooms\` — refresh this room's outbound pointers.
+- \`list_all_rooms\` — every room on the instance, not just yours.
+- \`get_room_detail\` — one room's members, channel type, roles, aliases.
+- \`list_bridges\` — the collaboration bridges available for new rooms.
+- \`create_room\` — provision a room. Confirm with the user first.
+- \`update_room\` — change an existing room, including its aliases.
+- \`invite_agent_to_room\` — add an agent to an existing room by name.
+- \`list_references\` — re-fetch the room's references, documents and packages.
+- \`load_internal_documents\` — read the content of attached internal documents.
+- \`create_room_document\` — author a document scoped to the connected room.
+- \`update_room_document\` — change a document you created.
+- \`delete_room_document\` — remove a document you created.
+- \`add_users_to_room\` — add human users to an existing room by name.
+- \`archive_room\` — archive a room you belong to.
+- \`unarchive_room\` — reverse an archive.
+- \`list_room_groups\` — the group tree rooms are organised into.
+- \`get_room_group_detail\` — one group's rooms and child groups.
+- \`create_room_group\` — provision a new room group.
+- \`list_agents\` — every agent on the instance, with optional filters.
+- \`get_agent_detail\` — one agent's config, capabilities and sessions.
+- \`update_agent_detail\` — change an agent you own.
+- \`list_reference_types\` — the Reference types and their value schemas.
+- \`create_reference\` — register an external Reference.
+- \`attach_reference_to_room\` — attach an existing Reference to a room.
+- \`link_rooms\` — add a directed pointer between two rooms.
+- \`unlink_rooms\` — remove one.
+`;
diff --git a/console/packages/plugins/src/agents/impl/opencode/switch-connector.test.ts b/console/packages/plugins/src/agents/impl/opencode/switch-connector.test.ts
new file mode 100644
index 000000000..02f1adf59
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/switch-connector.test.ts
@@ -0,0 +1,176 @@
+import type { PluginFs } from '@switch-console/core/agents/plugins';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { SWITCH_AGENT_RUNTIME_PIN } from '../../../distribution';
+import {
+ buildOpencodeSwitchConnector,
+ OPENCODE_CONFIG_PATH,
+ OPENCODE_CONNECTOR_MARKER_PATH,
+} from './switch-connector';
+
+function memoryFs(seed: Record<string, string> = {}) {
+ const files = new Map(Object.entries(seed));
+ const fs: PluginFs = {
+ read: async (path) => files.get(path) ?? null,
+ write: async (path, content) => void files.set(path, content),
+ delete: async (path) => void files.delete(path),
+ exists: async (path) => files.has(path),
+ list: async () => [...files.keys()],
+ };
+ return { fs, files };
+}
+
+function readConfig(files: Map<string, string>) {
+ return JSON.parse(files.get(OPENCODE_CONFIG_PATH) ?? '{}') as {
+ mcp?: Record<string, Record<string, unknown>>;
+ $schema?: string;
+ };
+}
+
+let connector: ReturnType<typeof buildOpencodeSwitchConnector>;
+
+beforeEach(() => {
+ connector = buildOpencodeSwitchConnector();
+});
+
+describe('install', () => {
+ it('registers the Switch MCP server in the global opencode config', async () => {
+ const { fs, files } = memoryFs();
+
+ const written = await connector.install(fs, { version: '1.2.3' });
+
+ const entry = readConfig(files).mcp?.switch;
+ expect(entry).toEqual({
+ type: 'local',
+ command: ['npx', '-y', SWITCH_AGENT_RUNTIME_PIN],
+ enabled: true,
+ timeout: 60_000,
+ });
+ expect(written).toContain(OPENCODE_CONFIG_PATH);
+ });
+
+ // OpenCode spawns a local MCP server with the parent environment, so the
+ // runtime picks up SWITCH_* from the session. Writing a token here would put
+ // a live credential in a file shared by every OpenCode session on the machine.
+ it('writes no credential into the config', async () => {
+ const { fs, files } = memoryFs();
+
+ await connector.install(fs, { version: '1.2.3' });
+
+ const raw = files.get(OPENCODE_CONFIG_PATH) ?? '';
+ expect(raw).not.toMatch(/SWITCH_API_TOKEN|Bearer|Authorization/i);
+ });
+
+ // OpenCode rejects unknown properties on an MCP entry and fails the whole
+ // config with them, so the entry must use only keys its schema declares.
+ it('uses only keys the opencode schema declares', async () => {
+ const { fs, files } = memoryFs();
+
+ await connector.install(fs, { version: '1.2.3' });
+
+ const allowed = new Set(['type', 'command', 'cwd', 'environment', 'enabled', 'timeout']);
+ for (const key of Object.keys(readConfig(files).mcp?.switch ?? {})) {
+ expect(allowed).toContain(key);
+ }
+ });
+
+ it("keeps the user's other MCP servers and unrelated config", async () => {
+ const { fs, files } = memoryFs({
+ [OPENCODE_CONFIG_PATH]: JSON.stringify({
+ theme: 'dark',
+ mcp: { other: { type: 'local', command: ['other'] } },
+ }),
+ });
+
+ await connector.install(fs, { version: '1.2.3' });
+
+ const config = readConfig(files) as Record<string, unknown> & {
+ mcp?: Record<string, unknown>;
+ };
+ expect(config.theme).toBe('dark');
+ expect(config.mcp?.other).toEqual({ type: 'local', command: ['other'] });
+ expect(config.mcp?.switch).toBeDefined();
+ });
+
+ it('is idempotent', async () => {
+ const { fs, files } = memoryFs();
+
+ await connector.install(fs, { version: '1.2.3' });
+ const first = files.get(OPENCODE_CONFIG_PATH);
+ await connector.install(fs, { version: '1.2.3' });
+
+ expect(files.get(OPENCODE_CONFIG_PATH)).toBe(first);
+ });
+
+ // A config we cannot parse is not ours to replace — doing so would silently
+ // discard whatever the user had in it.
+ it('refuses to rewrite a config it cannot parse', async () => {
+ const { fs, files } = memoryFs({ [OPENCODE_CONFIG_PATH]: '{ not json' });
+
+ await expect(connector.install(fs, { version: '1.2.3' })).rejects.toThrow(/not valid JSON/);
+ expect(files.get(OPENCODE_CONFIG_PATH)).toBe('{ not json');
+ });
+});
+
+describe('installedVersion', () => {
+ it('reports the version the install recorded', async () => {
+ const { fs } = memoryFs();
+ await connector.install(fs, { version: '1.2.3' });
+
+ expect(await connector.installedVersion(fs)).toBe('1.2.3');
+ });
+
+ it('reports nothing when never installed', async () => {
+ const { fs } = memoryFs();
+ expect(await connector.installedVersion(fs)).toBeNull();
+ });
+
+ // The marker alone is not proof: `opencode mcp` or a hand edit can drop the
+ // server and leave it behind. Reporting installed then hides exactly why the
+ // agent has no Switch tools.
+ it('reports nothing when the marker survives but the server is gone', async () => {
+ const { fs, files } = memoryFs();
+ await connector.install(fs, { version: '1.2.3' });
+ files.set(OPENCODE_CONFIG_PATH, JSON.stringify({ mcp: {} }));
+
+ expect(await connector.installedVersion(fs)).toBeNull();
+ });
+
+ it('reports nothing when the marker is unreadable', async () => {
+ const { fs, files } = memoryFs();
+ await connector.install(fs, { version: '1.2.3' });
+ files.set(OPENCODE_CONNECTOR_MARKER_PATH, 'not json');
+
+ expect(await connector.installedVersion(fs)).toBeNull();
+ });
+});
+
+describe('uninstall', () => {
+ it('removes the Switch server and the marker', async () => {
+ const { fs, files } = memoryFs();
+ await connector.install(fs, { version: '1.2.3' });
+
+ await connector.uninstall(fs);
+
+ expect(readConfig(files).mcp?.switch).toBeUndefined();
+ expect(files.has(OPENCODE_CONNECTOR_MARKER_PATH)).toBe(false);
+ expect(await connector.installedVersion(fs)).toBeNull();
+ });
+
+ it("leaves the user's other MCP servers alone", async () => {
+ const { fs, files } = memoryFs({
+ [OPENCODE_CONFIG_PATH]: JSON.stringify({
+ mcp: { other: { type: 'local', command: ['other'] } },
+ }),
+ });
+ await connector.install(fs, { version: '1.2.3' });
+
+ await connector.uninstall(fs);
+
+ expect(readConfig(files).mcp).toEqual({ other: { type: 'local', command: ['other'] } });
+ });
+
+ it('is safe to run when nothing was installed', async () => {
+ const { fs } = memoryFs();
+ await expect(connector.uninstall(fs)).resolves.toBeUndefined();
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/opencode/switch-connector.ts b/console/packages/plugins/src/agents/impl/opencode/switch-connector.ts
new file mode 100644
index 000000000..29e8e57d1
--- /dev/null
+++ b/console/packages/plugins/src/agents/impl/opencode/switch-connector.ts
@@ -0,0 +1,143 @@
+import type { ISwitchSetupFilesBehavior, PluginFs } from '@switch-console/core/agents/plugins';
+import { SWITCH_AGENT_RUNTIME_PIN } from '../../../distribution';
+import { OPENCODE_SKILL_CONTENT } from './skill-file';
+
+/**
+ * OpenCode's global config, relative to the home directory. It reads several
+ * files; this is the canonical one, and the one `opencode mcp add` writes.
+ */
+export const OPENCODE_CONFIG_PATH = '.config/opencode/opencode.json';
+
+/**
+ * Records what Switch Console installed, beside the config rather than inside
+ * it. OpenCode validates its config against a published schema that rejects
+ * unknown keys, so bookkeeping cannot ride along in `opencode.json` without
+ * risking a config the agent refuses to start with.
+ */
+export const OPENCODE_CONNECTOR_MARKER_PATH = '.config/opencode/switch-connector.json';
+
+/**
+ * The room-workflow skill, in OpenCode's global skill directory.
+ *
+ * Global rather than per-workspace to match the MCP server it explains: that
+ * is registered in the global config, so every OpenCode session on the machine
+ * has the Switch tools whether or not Switch Console launched it. A skill
+ * dropped in a workspace would leave those sessions holding forty room tools
+ * and no instructions for using them.
+ *
+ * The directory name has to be the skill's own name — OpenCode discovers
+ * `skills/<name>/SKILL.md` and rejects a skill whose frontmatter `name`
+ * disagrees with its folder.
+ */
+export const OPENCODE_SKILL_PATH = '.config/opencode/skills/switch/SKILL.md';
+
+/** The key the Switch MCP server is registered under. */
+const SERVER_NAME = 'switch';
+
+/**
+ * npx has to fetch the runtime on a cold cache before the server answers, and
+ * OpenCode's default startup allowance is 5s — short enough that the first
+ * session after an install would routinely fail to see any Switch tools.
+ */
+const STARTUP_TIMEOUT_MS = 60_000;
+
+type OpencodeConfig = {
+ mcp?: Record<string, unknown>;
+ [key: string]: unknown;
+};
+
+/**
+ * The Switch MCP server as OpenCode declares one.
+ *
+ * Mirrors `connectors/opencode-plugin/opencode.json`, which is the source of
+ * truth for what this connector registers; `connector-assets.test.ts` fails if
+ * the two disagree.
+ *
+ * Registered as a `local` (stdio) server, which is what keeps the credential
+ * off disk: OpenCode spawns a local server with the full parent environment,
+ * so the runtime inherits the `SWITCH_*` variables Switch Console already puts
+ * in the session, and nothing secret is written into a config file that is
+ * shared by every OpenCode session on the machine.
+ *
+ * Only keys OpenCode's schema declares may appear here — it rejects unknown
+ * properties on an MCP entry outright, taking the whole config with them.
+ */
+function switchServerEntry(): Record<string, unknown> {
+ return {
+ type: 'local',
+ command: ['npx', '-y', SWITCH_AGENT_RUNTIME_PIN],
+ enabled: true,
+ timeout: STARTUP_TIMEOUT_MS,
+ };
+}
+
+function parseConfig(raw: string | null): OpencodeConfig {
+ if (!raw?.trim()) return {};
+ try {
+ return JSON.parse(raw) as OpencodeConfig;
+ } catch {
+ // A config we cannot parse is not ours to rewrite: replacing it would
+ // discard whatever the user has in there. Fail loudly instead.
+ throw new Error(
+ `${OPENCODE_CONFIG_PATH} is not valid JSON. Fix or move it, then install the Switch connector again.`
+ );
+ }
+}
+
+function serialize(config: OpencodeConfig): string {
+ return `${JSON.stringify(config, null, 2)}\n`;
+}
+
+export function buildOpencodeSwitchConnector(): ISwitchSetupFilesBehavior {
+ return {
+ async install(fs: PluginFs, { version }: { version: string }): Promise<string[]> {
+ const config = parseConfig(await fs.read(OPENCODE_CONFIG_PATH));
+ // OpenCode rewrites its own config to add `$schema` when it is missing;
+ // writing it ourselves keeps that from showing up as a spurious change.
+ config.$schema ??= 'https://opencode.ai/config.json';
+ config.mcp = { ...config.mcp, [SERVER_NAME]: switchServerEntry() };
+ await fs.write(OPENCODE_CONFIG_PATH, serialize(config));
+ await fs.write(OPENCODE_SKILL_PATH, OPENCODE_SKILL_CONTENT);
+ await fs.write(
+ OPENCODE_CONNECTOR_MARKER_PATH,
+ `${JSON.stringify({ version, runtime: SWITCH_AGENT_RUNTIME_PIN }, null, 2)}\n`
+ );
+ return [OPENCODE_CONFIG_PATH, OPENCODE_SKILL_PATH, OPENCODE_CONNECTOR_MARKER_PATH];
+ },
+
+ async uninstall(fs: PluginFs): Promise<void> {
+ const raw = await fs.read(OPENCODE_CONFIG_PATH);
+ if (raw !== null) {
+ const config = parseConfig(raw);
+ if (config.mcp && SERVER_NAME in config.mcp) {
+ // Only our own entry: the user's other MCP servers live in this file.
+ const { [SERVER_NAME]: _removed, ...rest } = config.mcp;
+ config.mcp = rest;
+ if (Object.keys(rest).length === 0) delete config.mcp;
+ await fs.write(OPENCODE_CONFIG_PATH, serialize(config));
+ }
+ }
+ await fs.delete(OPENCODE_SKILL_PATH);
+ await fs.delete(OPENCODE_CONNECTOR_MARKER_PATH);
+ },
+
+ async installedVersion(fs: PluginFs): Promise<string | null> {
+ const marker = await fs.read(OPENCODE_CONNECTOR_MARKER_PATH);
+ if (!marker) return null;
+
+ // The marker alone is not proof. Someone editing `opencode.json` by hand,
+ // or `opencode mcp` rewriting it, can leave the marker behind with no
+ // server registered — reporting that as installed hides the reason the
+ // agent has no Switch tools.
+ const config = parseConfig(await fs.read(OPENCODE_CONFIG_PATH));
+ if (!config.mcp || !(SERVER_NAME in config.mcp)) return null;
+
+ try {
+ const parsed = JSON.parse(marker) as { version?: unknown };
+ return typeof parsed.version === 'string' ? parsed.version : null;
+ } catch {
+ return null;
+ }
+ },
+ };
+}
diff --git a/console/packages/plugins/src/distribution.ts b/console/packages/plugins/src/distribution.ts
index badc0ef7d..2fafcf893 100644
--- a/console/packages/plugins/src/distribution.ts
+++ b/console/packages/plugins/src/distribution.ts
@@ -8,3 +8,23 @@
* (RELEASE_REPO_* in apps/switch-console-desktop/src/shared/app-identity.ts).
*/
export const SWITCH_MARKETPLACE_SOURCE = 'sandbox-quantum/switch';
+
+/**
+ * The published agent-runtime version a session runs, for agents whose Switch
+ * connector Switch Console writes itself rather than installing from the
+ * marketplace.
+ *
+ * The two marketplace connectors pin this in their own `.mcp.json`, which is
+ * what a Claude Code or Codex session actually reads. An agent with no
+ * marketplace has no such file, so the pin lives here instead — and the two
+ * must agree, or one host runs a different runtime from the others for no
+ * visible reason. `runtime-pin.test.ts` fails when they drift.
+ *
+ * It must name a version that is *published*: the tag is pushed separately from
+ * the merge, so this moves after the tag exists, never ahead of it. That is why
+ * it is a literal rather than being derived from the artifact registry the way
+ * the runtime's own `RUNTIME_VERSION` is — the registry says where the runtime
+ * has got to, which during a release is a version npm does not have yet. A
+ * pin has to lag it deliberately, and the lag is the point.
+ */
+export const SWITCH_AGENT_RUNTIME_PIN = '@sandboxaq/[email protected]';
diff --git a/console/packages/plugins/src/runtime-pin.test.ts b/console/packages/plugins/src/runtime-pin.test.ts
new file mode 100644
index 000000000..fd64fa6fa
--- /dev/null
+++ b/console/packages/plugins/src/runtime-pin.test.ts
@@ -0,0 +1,43 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { SWITCH_AGENT_RUNTIME_PIN } from './distribution';
+
+// packages/plugins/src → repo root
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..');
+
+const BUNDLED_MCP_CONFIGS = [
+ 'connectors/claude-code-plugin/.mcp.json',
+ 'connectors/codex-plugin/.mcp.json',
+];
+
+function pinnedRuntimeIn(relativePath: string): string {
+ const raw = readFileSync(join(REPO_ROOT, relativePath), 'utf8');
+ const config = JSON.parse(raw) as {
+ mcpServers?: Record<string, { args?: string[] }>;
+ };
+ const args = config.mcpServers?.switch?.args ?? [];
+ const pin = args.find((arg) => arg.includes('switch-agent-runtime'));
+ if (!pin) throw new Error(`${relativePath} pins no agent runtime`);
+ return pin;
+}
+
+/**
+ * The two marketplace connectors pin the runtime in their own `.mcp.json`, and
+ * an agent with no marketplace gets the pin from `distribution.ts` instead.
+ * Nothing forces those to agree, and disagreement is invisible: each host just
+ * runs whatever its own file says, so one agent type silently runs a different
+ * protocol client from the others.
+ */
+describe('agent runtime pin', () => {
+ it.each(BUNDLED_MCP_CONFIGS)('matches the pin bundled in %s', (relativePath) => {
+ expect(pinnedRuntimeIn(relativePath)).toBe(SWITCH_AGENT_RUNTIME_PIN);
+ });
+
+ it('names an exact published version', () => {
+ // A floating range would make two sessions started minutes apart run
+ // different runtimes, which is untraceable after the fact.
+ expect(SWITCH_AGENT_RUNTIME_PIN).toMatch(/^@sandboxaq\/switch-agent-runtime@\d+\.\d+\.\d+$/);
+ });
+});
diff --git a/console/packages/shared/src/artifacts.ts b/console/packages/shared/src/artifacts.ts
index c967e75c6..675b51c66 100644
--- a/console/packages/shared/src/artifacts.ts
+++ b/console/packages/shared/src/artifacts.ts
@@ -30,6 +30,7 @@ export const ARTIFACT_VERSIONS = {
compose: '0.13.2',
'switch-connector': '0.9.1',
'switch-connector-codex': '0.3.2',
+ 'switch-connector-opencode': '0.1.0',
} as const satisfies Record<string, string>;
export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;
diff --git a/console/packages/switch-agent-runtime/src/artifacts.ts b/console/packages/switch-agent-runtime/src/artifacts.ts
index c967e75c6..675b51c66 100644
--- a/console/packages/switch-agent-runtime/src/artifacts.ts
+++ b/console/packages/switch-agent-runtime/src/artifacts.ts
@@ -30,6 +30,7 @@ export const ARTIFACT_VERSIONS = {
compose: '0.13.2',
'switch-connector': '0.9.1',
'switch-connector-codex': '0.3.2',
+ 'switch-connector-opencode': '0.1.0',
} as const satisfies Record<string, string>;
export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;
diff --git a/core/switch_core/artifacts.py b/core/switch_core/artifacts.py
index c27c322cb..91af23157 100644
--- a/core/switch_core/artifacts.py
+++ b/core/switch_core/artifacts.py
@@ -30,6 +30,7 @@ ARTIFACT_VERSIONS: Final[dict[str, str]] = {
"compose": "0.13.2",
"switch-connector": "0.9.1",
"switch-connector-codex": "0.3.2",
+ "switch-connector-opencode": "0.1.0",
}
CONTRACTS: Final[dict[str, dict[str, ContractRange]]] = {
diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/client.py b/core/switch_core/bridges/agent/server_connectors/opencode/client.py
index 088dbd6a7..05c4c48a0 100644
--- a/core/switch_core/bridges/agent/server_connectors/opencode/client.py
+++ b/core/switch_core/bridges/agent/server_connectors/opencode/client.py
@@ -68,6 +68,20 @@ class OpenCodeClient:
)
resp.raise_for_status()
+ async def respond_permission(
+ self, session_id: str, permission_id: str, response: str
+ ) -> None:
+ """Respond to a permission request raised by the OpenCode server.
+
+ `response` is one of "once", "always", or "reject". Without a reply
+ the server pauses the session indefinitely waiting for approval.
+ """
+ resp = await self._http.post(
+ f"/session/{session_id}/permissions/{permission_id}",
+ json={"response": response},
+ )
+ resp.raise_for_status()
+
@asynccontextmanager
async def subscribe_events(self) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:
"""Subscribe to the SSE event stream. Yields parsed events."""
diff --git a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py b/core/switch_core/bridges/agent/server_connectors/opencode/connector.py
index 3fcf4b8af..31c279ba8 100644
--- a/core/switch_core/bridges/agent/server_connectors/opencode/connector.py
+++ b/core/switch_core/bridges/agent/server_connectors/opencode/connector.py
@@ -27,6 +27,12 @@ logger = logging.getLogger(__name__)
_SANITIZE_RE = re.compile(r"[^a-z0-9._-]")
+# OpenCode pauses a session until a permission request is answered. This
+# connector reports tool calls post-hoc and runs no pre-invocation mediation
+# (see _INTEGRATION_PROFILE), so permission requests are auto-approved to keep
+# the session from blocking. "always" so a given tool/pattern is not re-asked.
+_PERMISSION_RESPONSE = "always"
+
_INTEGRATION_PROFILE = IntegrationProfile(
connection_model="always_on",
message_exchange=True,
@@ -168,6 +174,7 @@ class OpenCodeConnector(ServerSideConnector):
reported_tool_ids: set[str] = set()
notified_tool_ids: set[str] = set()
sent_text_ids: set[str] = set()
+ responded_permission_ids: set[str] = set()
async with self.client.subscribe_events() as events:
async for event in events:
@@ -179,6 +186,32 @@ class OpenCodeConnector(ServerSideConnector):
if props.get("sessionID") == session_id:
break
+ if event_type == "permission.updated":
+ props = event.get("properties") or event.get("data", {})
+ if props.get("sessionID") != session_id:
+ continue
+ permission_id = props.get("id", "")
+ if not permission_id or permission_id in responded_permission_ids:
+ continue
+ responded_permission_ids.add(permission_id)
+ logger.info(
+ "Auto-approving OpenCode permission %s (%s) for session %s",
+ permission_id,
+ props.get("type") or props.get("title", ""),
+ session_id,
+ )
+ try:
+ await self.client.respond_permission(
+ session_id, permission_id, _PERMISSION_RESPONSE
+ )
+ except Exception:
+ logger.error(
+ "Failed to respond to OpenCode permission %s; session "
+ "may block waiting for approval",
+ permission_id,
+ )
+ continue
+
if event_type not in (
"message.part.updated",
"message.part.updated.1",
diff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.py
index 13e4047e1..c9a944399 100644
--- a/core/switch_core/gateway/known_agents.py
+++ b/core/switch_core/gateway/known_agents.py
@@ -420,9 +420,136 @@ class CodexKnownAgent(KnownAgent):
)
+class OpenCodeOptions(KnownAgentOptions):
+ auto_session: bool = False
+ """When True, the operator's connector (Switch Console) watches every room this
+ agent belongs to and auto-spawns an OpenCode session — connected to the room
+ and wired to the agent's identity — the moment the agent is addressed in a
+ room where it has no live session. The registered profile becomes
+ `auto_session`. Like Codex, OpenCode has no connector channel of its own;
+ Switch Console delivers inbound room messages by injecting them into the
+ session's terminal."""
+
+ repo_dir: str | None = None
+ """Absolute path to the directory the operator runs OpenCode from. Used to
+ generate a ready-to-paste `cd <repo_dir> && opencode --prompt "connect to
+ switch room …"` command shown when the agent is addressed with no live
+ session. None → an `<opencode-dir>` placeholder is shown instead."""
+
+ notify_user: str | None = None
+ """Username (on the room's bridged platform) to `@`-mention in the
+ unavailable-session message so the operator gets a notification. Bare name,
+ no leading `@`. None → post without a mention."""
+
+ # No `channels_enabled`, for the same reason as Codex: Switch Console sends it
+ # for every provider, but OpenCode has no connector channel for it to act on.
+
+ @field_validator("repo_dir", "notify_user", mode="before")
+ @classmethod
+ def _blank_string_to_none(cls, value: object) -> object:
+ if isinstance(value, str) and value.strip() == "":
+ return None
+ return value
+
+
+class OpenCodeKnownAgent(KnownAgent):
+ connector_type = "OpenCode CLI"
+ options_schema = OpenCodeOptions
+ tools = [
+ ToolSpec(name="Bash", description="Executes shell commands"),
+ ToolSpec(name="Edit", description="Edits existing files"),
+ ToolSpec(name="Write", description="Writes new files"),
+ ToolSpec(name="Read", description="Reads file contents"),
+ ToolSpec(name="Grep", description="Searches file contents"),
+ ToolSpec(name="Glob", description="Finds files by pattern"),
+ ToolSpec(name="List", description="Lists directory contents"),
+ ToolSpec(name="WebFetch", description="Fetches web pages"),
+ ToolSpec(name="Task", description="Spawns a sub-agent"),
+ ]
+ models: ClassVar[list[ModelSpec]] = []
+
+ @classmethod
+ def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:
+ assert isinstance(options, OpenCodeOptions)
+ return IntegrationProfile(
+ connection_model=(
+ "auto_session" if options.auto_session else "session_addressable"
+ ),
+ message_exchange=True,
+ # OpenCode's connector reports session and tool activity to Switch
+ # Console over its local hook port, which drives the session's status
+ # in the app. None of it reaches Switch as reported events, and
+ # nothing mediates a tool call before it runs, so both stay empty —
+ # the same position as Codex, and unlike Claude Code.
+ pre_invocation_mediation=[],
+ post_invocation_mediation=[],
+ event_reporting=[],
+ task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),
+ # A TUI, so reset / compact / interrupt only work while Switch Console
+ # is driving the session and can write to it. A standalone `opencode`
+ # cannot be controlled, so all three resolve per live session via
+ # AgentRuntimeState.
+ command_capabilities=CommandCapabilities(
+ reset="session_dependent",
+ compact="session_dependent",
+ interrupt="session_dependent",
+ ),
+ )
+
+ @classmethod
+ def start_session_instructions(
+ cls,
+ options: KnownAgentOptions,
+ agent: Agent,
+ room_name: str,
+ assume_role: str | None = None,
+ other_room_names: list[str] | None = None,
+ connected_not_live: bool = False,
+ ) -> str | None:
+ """Build the room-facing onboarding message for an OpenCode agent.
+
+ The prompt goes through `--prompt`, never as a positional argument:
+ OpenCode reads its first positional as the project directory, so a bare
+ `opencode "connect to switch room …"` is a request to open a directory of
+ that name rather than a prompt.
+ """
+ assert isinstance(options, OpenCodeOptions)
+ dir_token = options.repo_dir if options.repo_dir else "<opencode-dir>"
+ prompt = f"connect to switch room {room_name}"
+ if assume_role:
+ prompt += f" and assume the role {assume_role}"
+ cmd = f'cd "{dir_token}" && opencode --prompt "{prompt}"'
+
+ prefix = f"@{options.notify_user}\n\n" if options.notify_user else ""
+ if connected_not_live:
+ opening = (
+ "I have a session connected to this room, but it isn't reporting "
+ "as live, so I'm not receiving messages. Relaunch it, or start a "
+ "fresh session, with:"
+ )
+ elif other_room_names:
+ where = ", ".join(f"**{name}**" for name in other_room_names)
+ opening = (
+ f"I don't have a session connected to this room right now, but I "
+ f"do have other session(s) connected to {where}. Either ask me in "
+ "one of those rooms to come here, or start a new session connected "
+ "to this room — my operator should run:"
+ )
+ else:
+ opening = (
+ "I don't have a session connected to this room. To set up a new "
+ "session connected to this room, my operator should run:"
+ )
+ return (
+ f"{prefix}{opening}\n\n```\n{cmd}\n```\n\n(or start OpenCode manually "
+ "and ask me to connect to the room.)"
+ )
+
+
KNOWN_AGENTS: dict[str, type[KnownAgent]] = {
"claude-code": ClaudeCodeKnownAgent,
"codex": CodexKnownAgent,
+ "opencode": OpenCodeKnownAgent,
}
diff --git a/core/tests/switch_core/bridges/agent/server_connectors/__init__.py b/core/tests/switch_core/bridges/agent/server_connectors/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/tests/switch_core/bridges/agent/server_connectors/opencode/__init__.py b/core/tests/switch_core/bridges/agent/server_connectors/opencode/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py b/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py
new file mode 100644
index 000000000..9042b8236
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/server_connectors/opencode/test_connector.py
@@ -0,0 +1,201 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from typing import Any
+
+from switch_core.bridges.agent.server_connectors.base import ConnectorReporter
+from switch_core.bridges.agent.server_connectors.opencode.connector import (
+ OpenCodeConnectionConfig,
+ OpenCodeConnector,
+)
+
+SESSION_ID = "sess-1"
+ROOM_ID = "room-1"
+
+
+class _FakeReporter(ConnectorReporter):
+ def __init__(self) -> None:
+ self.messages: list[str] = []
+ self.statuses: list[str] = []
+ self.events: list[Any] = []
+
+ async def send_message(self, room_id: str, content: str) -> None:
+ self.messages.append(content)
+
+ async def report_events(self, room_id: str, events: Any) -> None:
+ self.events.extend(events)
+
+ async def send_status(self, room_id: str, detail: str) -> None:
+ self.statuses.append(detail)
+
+ async def set_typing(self, room_id: str, is_typing: bool) -> None:
+ pass
+
+
+class _FakeClient:
+ """Stands in for OpenCodeClient, replaying a scripted SSE event stream."""
+
+ def __init__(self, events: list[dict[str, Any]]) -> None:
+ self._events = events
+ self.permission_responses: list[tuple[str, str, str]] = []
+
+ @asynccontextmanager
+ async def subscribe_events(self) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:
+ async def _gen() -> AsyncIterator[dict[str, Any]]:
+ for event in self._events:
+ yield event
+
+ yield _gen()
+
+ async def respond_permission(
+ self, session_id: str, permission_id: str, response: str
+ ) -> None:
+ self.permission_responses.append((session_id, permission_id, response))
+
+
+class _FailingPermissionClient(_FakeClient):
+ """A client whose permission reply always fails."""
+
+ async def respond_permission(
+ self, session_id: str, permission_id: str, response: str
+ ) -> None:
+ raise RuntimeError("opencode unreachable")
+
+
+def _connector_with(
+ events: list[dict[str, Any]],
+ client: _FakeClient | None = None,
+) -> tuple[OpenCodeConnector, _FakeClient]:
+ config = OpenCodeConnectionConfig(
+ server_url="http://localhost", username="u", password="p"
+ )
+ connector = OpenCodeConnector(config)
+ client = client or _FakeClient(events)
+ connector._client = client # type: ignore[assignment]
+ return connector, client
+
+
+async def test_permission_request_is_auto_approved() -> None:
+ events = [
+ {
+ "type": "permission.updated",
+ "properties": {
+ "id": "perm-1",
+ "sessionID": SESSION_ID,
+ "type": "bash",
+ },
+ },
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, client = _connector_with(events)
+ reporter = _FakeReporter()
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, reporter)
+
+ assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]
+
+
+async def test_permission_for_other_session_is_ignored() -> None:
+ events = [
+ {
+ "type": "permission.updated",
+ "properties": {"id": "perm-x", "sessionID": "other-session"},
+ },
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, client = _connector_with(events)
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())
+
+ assert client.permission_responses == []
+
+
+async def test_permission_responded_only_once() -> None:
+ perm = {
+ "type": "permission.updated",
+ "properties": {"id": "perm-1", "sessionID": SESSION_ID},
+ }
+ events = [
+ perm,
+ perm,
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, client = _connector_with(events)
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())
+
+ assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]
+
+
+async def test_permission_event_read_from_data_key() -> None:
+ """Some OpenCode builds carry the payload under `data` rather than `properties`."""
+ events = [
+ {
+ "type": "permission.updated",
+ "data": {"id": "perm-1", "sessionID": SESSION_ID},
+ },
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, client = _connector_with(events)
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, _FakeReporter())
+
+ assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]
+
+
+async def test_permission_reply_failure_does_not_break_the_stream() -> None:
+ events = [
+ {
+ "type": "permission.updated",
+ "properties": {"id": "perm-1", "sessionID": SESSION_ID},
+ },
+ {
+ "type": "message.part.updated",
+ "properties": {
+ "sessionID": SESSION_ID,
+ "part": {
+ "type": "text",
+ "id": "text-1",
+ "text": "done",
+ "time": {"end": 1},
+ },
+ },
+ },
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, _ = _connector_with(events, client=_FailingPermissionClient(events))
+ reporter = _FakeReporter()
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, reporter)
+
+ assert reporter.messages == ["done"]
+
+
+async def test_text_part_still_relayed_after_permission() -> None:
+ events = [
+ {
+ "type": "permission.updated",
+ "properties": {"id": "perm-1", "sessionID": SESSION_ID},
+ },
+ {
+ "type": "message.part.updated",
+ "properties": {
+ "sessionID": SESSION_ID,
+ "part": {
+ "type": "text",
+ "id": "text-1",
+ "text": "done",
+ "time": {"end": 1},
+ },
+ },
+ },
+ {"type": "session.idle", "properties": {"sessionID": SESSION_ID}},
+ ]
+ connector, client = _connector_with(events)
+ reporter = _FakeReporter()
+
+ await connector._stream_response(SESSION_ID, ROOM_ID, reporter)
+
+ assert client.permission_responses == [(SESSION_ID, "perm-1", "always")]
+ assert reporter.messages == ["done"]
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
index 361aad9a5..f6b638e53 100644
--- a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
+++ b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
@@ -146,16 +146,40 @@ async def test_every_registered_tool_is_indexed(tool_names: set[str]) -> None:
)
-def test_both_skills_index_the_same_tools() -> None:
- """The two connectors' tool indexes must not drift apart.
+def test_every_connector_ships_a_skill() -> None:
+ """Each connector documents the room workflow for its own host.
+
+ A connector added without one leaves its agents with the Switch tools and
+ no instructions for using them — which looks like a badly behaved agent
+ rather than a missing file.
+ """
+ connectors = {
+ path.name
+ for path in (Path(__file__).parents[5] / "connectors").iterdir()
+ if path.is_dir()
+ }
+ with_skills = {skill.parents[2].name for skill in SKILLS}
+ assert connectors == with_skills, (
+ f"connectors without a skill: {sorted(connectors - with_skills)}"
+ )
+
+
+def test_all_skills_index_the_same_tools() -> None:
+ """The connectors' tool indexes 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 index is silently absent from the
- other's.
+ others'.
"""
- assert len(SKILLS) == 2, f"expected two connector skills, found {SKILLS}"
- first, second = (_indexed_tools(skill) for skill in SKILLS)
- assert first == second
+ assert len(SKILLS) >= 2, f"expected several connector skills, found {SKILLS}"
+ indexes = {skill: _indexed_tools(skill) for skill in SKILLS}
+ reference, expected = next(iter(indexes.items()))
+ for skill, indexed in indexes.items():
+ assert indexed == expected, (
+ f"{skill}'s tool index differs from {reference}'s: "
+ f"only in {skill}: {sorted(set(indexed) - set(expected))}, "
+ f"only in {reference}: {sorted(set(expected) - set(indexed))}"
+ )
async def test_skill_indexed_tools_are_registered(tool_names: set[str]) -> None:
diff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.py
index 173eab86b..3cf196045 100644
--- a/core/tests/switch_core/gateway/test_known_agents.py
+++ b/core/tests/switch_core/gateway/test_known_agents.py
@@ -8,6 +8,8 @@ from switch_core.gateway.known_agents import (
ClaudeCodeOptions,
CodexKnownAgent,
CodexOptions,
+ OpenCodeKnownAgent,
+ OpenCodeOptions,
known_agent_for,
)
@@ -377,6 +379,140 @@ class TestCodexKnownAgent:
assert options.repo_dir == "/tmp/r"
+class TestOpenCodeKnownAgent:
+ def test_registered_under_opencode_key(self) -> None:
+ assert KNOWN_AGENTS.get("opencode") is OpenCodeKnownAgent
+ assert OpenCodeKnownAgent.connector_type == "OpenCode CLI"
+
+ def test_default_profile_is_session_addressable(self) -> None:
+ profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())
+ assert profile.connection_model == "session_addressable"
+
+ def test_auto_session_sets_auto_session_model(self) -> None:
+ profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions(auto_session=True))
+ assert profile.connection_model == "auto_session"
+
+ def test_no_tool_call_mediation_or_reporting(self) -> None:
+ # OpenCode's connector reports activity to Switch Console over the local
+ # hook port to drive session status; none of it reaches Switch as
+ # reported events, and nothing gates a tool call before it runs.
+ profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())
+ assert profile.pre_invocation_mediation == []
+ assert profile.post_invocation_mediation == []
+ assert profile.event_reporting == []
+
+ def test_can_delegate_and_accept_tasks(self) -> None:
+ profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())
+ assert profile.task_protocol.can_delegate is True
+ assert profile.task_protocol.can_accept is True
+
+ def test_commands_are_session_dependent(self) -> None:
+ # Must stay in step with `BY_PROVIDER.opencode` in Switch Console's
+ # `main/core/switch-rooms/session-control.ts`; declaring a command here
+ # that Switch Console cannot execute yields a worse message than
+ # "unsupported".
+ caps = OpenCodeKnownAgent.build_profile(OpenCodeOptions()).command_capabilities
+ assert caps.reset == "session_dependent"
+ assert caps.compact == "session_dependent"
+ assert caps.interrupt == "session_dependent"
+
+ def test_prompt_is_passed_as_a_flag_not_a_positional(self) -> None:
+ # OpenCode reads its first positional as the project directory, so a bare
+ # `opencode "connect to switch room hub"` asks it to open a directory of
+ # that name. The prompt must go through --prompt.
+ opts = OpenCodeOptions(repo_dir="/Users/x/repo")
+ msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ assert msg is not None
+ assert (
+ 'cd "/Users/x/repo" && opencode --prompt "connect to switch room hub"'
+ in msg
+ )
+ assert 'opencode "connect' not in msg
+
+ def test_start_session_instructions_emit_opencode_only(self) -> None:
+ opts = OpenCodeOptions(repo_dir="/Users/x/repo")
+ msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ assert msg is not None
+ assert "claude" not in msg
+ assert "codex" not in msg
+ assert "--dangerously-load-development-channels" not in msg
+ assert "auto-starts one when I'm addressed" not in msg
+ assert "start OpenCode manually" in msg
+
+ def test_repo_dir_with_spaces_stays_quoted(self) -> None:
+ opts = OpenCodeOptions(repo_dir="/Users/alice/my project")
+ msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ assert msg is not None
+ assert 'cd "/Users/alice/my project" && opencode' in msg
+
+ def test_assume_role_is_folded_into_the_prompt(self) -> None:
+ opts = OpenCodeOptions(repo_dir="/r")
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ opts, _agent({}), "ops", assume_role="reviewer"
+ )
+ assert msg is not None
+ assert (
+ '--prompt "connect to switch room ops and assume the role reviewer"' in msg
+ )
+
+ def test_blank_repo_dir_uses_placeholder(self) -> None:
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ OpenCodeOptions(repo_dir=""), _agent({}), "triage"
+ )
+ assert msg is not None
+ assert 'cd "<opencode-dir>"' in msg
+
+ def test_no_repo_dir_uses_placeholder(self) -> None:
+ msg = OpenCodeKnownAgent.start_session_instructions(
+ OpenCodeOptions(repo_dir=None), _agent({}), "triage"
+ )
+ assert msg is not None
+ assert 'cd "<opencode-dir>"' in msg
+
+ def test_blank_notify_user_produces_no_mention(self) -> None:
+ opts = OpenCodeOptions(notify_user="")
+ msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ assert msg is not None
+ assert not msg.startswith("@")
+
+ def test_notify_user_is_mentioned(self) -> None:
+ opts = OpenCodeOptions(repo_dir="/x", notify_user="cmcd")
+ msg = OpenCodeKnownAgent.start_session_instructions(opts, _agent({}), "hub")
+ assert msg is not None
+ assert msg.startswith("@cmcd")
+
+ def test_channels_enabled_is_dropped_not_offered_as_an_option(self) -> None:
+ # Switch Console sends channels_enabled for every provider, so registration
+ # must still accept it — but OpenCode has no channel, so it is not a
+ # field. The gateway renders the options form from this schema; a
+ # declared field would be an interactive control that changes nothing.
+ assert (
+ "channels_enabled" not in OpenCodeOptions.model_json_schema()["properties"]
+ )
+
+ opts = OpenCodeOptions.model_validate({"channels_enabled": False})
+ assert "channels_enabled" not in opts.model_dump()
+ assert (
+ OpenCodeKnownAgent.build_profile(opts).connection_model
+ == "session_addressable"
+ )
+
+ def test_known_agent_for_round_trips_opencode(self) -> None:
+ agent = _agent(
+ {
+ "known_agent_type": "opencode",
+ "known_agent_options": {"auto_session": True, "repo_dir": "/tmp/r"},
+ }
+ )
+ result = known_agent_for(agent)
+ assert result is not None
+ spec, options = result
+ assert spec is OpenCodeKnownAgent
+ assert isinstance(options, OpenCodeOptions)
+ assert options.auto_session is True
+ assert options.repo_dir == "/tmp/r"
+
+
class TestKnownAgentFor:
def test_round_trips_claude_code_options(self) -> None:
agent = _agent(