Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
[CHOO-3238] Correct stale docs and remove the start command that never worked (#730)
Christian McDermott335bdd95c019
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 65bc5687e..49dad28e0 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -19,8 +19,8 @@ body:- switch-core (control plane)- gateway (operator dashboard)- Switch Console (desktop app)- - Connector plugin (Claude Code / Codex)- - Collaboration bridge (Slack / Mattermost)+ - Agent sessions (Claude Code / Codex / OpenCode / Cursor / Antigravity)+ - Collaboration bridge (Slack / Mattermost / Discord / Teams / Telegram)- Deployment (Docker Compose / Helm)- Not surevalidations:@@ -65,5 +65,5 @@ body:id: environmentattributes:label: Environment- description: OS and version, and anything else that might matter.- placeholder: 'macOS 15.2 (arm64), Docker 27.0.0'+ description: OS and version, the agent provider and messaging app involved, and anything else that might matter. In Switch Console, Help → Troubleshooting → Copy Version Info gives the versions.+ placeholder: 'macOS 15.2 (arm64), Docker 27.0.0, Claude Code, Slack'diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 54a7e80d7..af85512e3 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -32,7 +32,7 @@ body:- switch-core (control plane)- gateway (operator dashboard)- Switch Console (desktop app)- - Connector plugin (Claude Code / Codex)- - Collaboration bridge (Slack / Mattermost)+ - Agent sessions (Claude Code / Codex / OpenCode / Cursor / Antigravity)+ - Collaboration bridge (Slack / Mattermost / Discord / Teams / Telegram)- Deployment (Docker Compose / Helm)- Not surediff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6ce1be79..f3924821c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,26 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Fixed+- **The Teams command menu fits Teams' limit again.** Switch's own Teams app+ listed thirteen commands, one more than Teams allows, once `/remove-agent`+ joined it. Both Teams apps now offer the same twelve: `/remove-agent` is in,+ and `/room-url` leaves the menu but still works when typed. A self-hosted+ Teams app shows the change once its package is rebuilt with `--bump` and+ uploaded again.++#### Removed+- **`!run-cmd`, and the terminal command in offline replies.** A CLI started+ with that command got none of the Switch tools, so it never brought the agent+ online. The reply for an agent that is offline or not live now says what's+ wrong and who has to act, with no start command to paste. Where the owner+ starts it from Switch Console, the reply names the room to connect it to and+ the provider's sign-in command, for when Console says it is signed out. An+ always_on agent says its connector is down, whatever provider it registered+ through. Slack apps that list `/run-cmd` in their manifest keep showing it,+ answering "Unknown command", until an admin deletes it; Discord and Telegram+ drop it from their command lists by themselves (#730).+### [0.31.0] - 2026-10-20#### Addeddiff --git a/CLAUDE.md b/CLAUDE.mdindex 658462614..d6166e795 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -34,10 +34,11 @@ participate in Switch. The upstream app is built around coding workflows(projects → sessions → conversations); Switch Console is being reworkedaround **Switch agents and their sessions** — which rooms an agent belongs to andis connected to, its config (working dir, identity), and scheduling: e.g.-auto-starting a Claude Code session when a Slack user addresses an agent that has-no live session, viewing all sessions in one place, and injecting prompts into a-running TUI when the provider can't push events into a live session. It has its-own `console/CLAUDE.md` (→ `AGENTS.md`); read that before working in the app.+auto-starting a session when a Slack user addresses an agent that has no live+session, and viewing all sessions in one place. Every provider runs through a+native SDK or protocol adapter in a long-running session host+(`console/docs/sdk-sessions.md`); there is no terminal or prompt injection. It+has its own `console/CLAUDE.md` (→ `AGENTS.md`); read that before working in the app.## Common Commands@@ -47,8 +48,9 @@ uv sync # install/update Python dependencies# Local dev infrastructure (Docker Compose)just init-env # first-time setup — generate .env with random secrets-just up # start Switch locally-just down # stop Switch+just up # start the supporting stack (Postgres, Mattermost) in Docker+just run # run switch-core locally (:8000)+just down # stop the supporting stack# Database migrationsjust migrate # alembic upgrade head@@ -77,7 +79,7 @@ just test -k "test_name" # run specific test- `stores/` — query methods and domain-specific data access- `migrations/` — Alembic migrations (`env.py`, `versions/`)- `room_service.py` / `rooms_yaml.py` — Room lifecycle, configuration, provisioning-- `clients/` — room participants: `actor.py` (identity, membership, writes: `HumanActor`, `AgentActor`, `SystemActor`) and `consumer.py` (the delivery loop and hooks: `CommandConsumer`, `WorkspaceConsumer`)+- `clients/` — room participants: `actor.py` (identity, membership, writes: `HumanActor`, `AgentActor`, `SystemActor`) and `consumer.py` (the `Consumer` delivery loop and hooks), subclassed by `CommandConsumer` (`command_consumer.py`) and `WorkspaceConsumer` (`workspace_consumer.py`)- `delivery/` decides who a row is for: `addressing.py` (the rules), `router.py` (`MessageRouter`, which decides every row for every agent in its room as the row is written, in the same transaction) and `recipient.py` (`AgentRecipient`, one agent's decisions and the replies posted on its behalf)- `bridges/` — External integrations- `agent/` — Agent Bridge (HTTP API, MCP server, server-side connectors); `protocol/agent_core.py` is `AgentCore`, `protocol/agent_connections.py` holds each `AgentConnection`@@ -113,35 +115,16 @@ stable identifiers and wire shapes, not as a sign that Matrix is in use. InPython they are `transport_room_id` / `transport_user_id`, and the server nameis `ID_SERVER_NAME` (`MATRIX_SERVER_NAME` is still read, with a warning).-**The message bus is PostgreSQL** (`transport/postgres.py`). Switch once ran on a-Matrix homeserver; that is gone, and no Matrix server or client library is-involved. A send is an `INSERT` into `messages`, with a per-room advisory lock-assigning `seq` (`db/stores/message_store.py`). The `messages_notify` trigger-calls `pg_notify('switch_message', …)` with the room, `seq` and row id, delivered-on commit (`db/notify_ddl.py`). Every row is written by the router-(`delivery/router.py`), which decides in the same transaction which agents in-the room it is for and stores their own events (`agent_events`) with it. One-`MessageListener` (`messages/notify.py`) holds a dedicated `LISTEN` connection-and wakes the subscribers for that room; each client then reads the rows after-its own cursor, 200 at a time. The notification is a wake-up, never the-payload. Membership changes reach every-process through a `NOTIFY` trigger on `client_rooms` and the signal bus-(`signals.py`, `transport/membership_signals.py`); presence still travels over-an in-process bus (`transport/ephemeral.py`), which is part of why switch-core-runs as a single replica. Names such as-`matrix_room_id`, `matrix_user_id`, `MATRIX_SERVER_NAME`, the `@localpart:server`-id shape and `m.room.message` content types are kept as stable identifiers and-wire shapes, not as a sign that Matrix is in use.-## The Switch skill-Every agent session is started by Switch Console or its sidecar; there are no-connector plugins and no standalone runtime. Each session gets the Switch MCP+Every agent session is started by Switch Console, its sidecar on an SSH host,+or the headless agents controller (`console/packages/agent-controller`); there+are no connector plugins and no standalone runtime. Each session gets the Switch MCPtools from its own session host, and the room-workflow skill from Console:`console/packages/plugins/src/switch-skill/SKILL.md` is the single copy,-exported as `@switch-console/plugins/switch-skill`. Codex and OpenCode load it-as a skill file; Claude Code, Cursor and Antigravity get it (without its-frontmatter) as system context.+exported as `@switch-console/plugins/switch-skill`. OpenCode loads it as a+skill file; Codex gets it as developer instructions; Claude Code, Cursor and+Antigravity get it (without its frontmatter) as system context.When you change how agents interact with Switch — new/changed MCP tools, in-roomcommands, room workflow, event delivery, or anything an agent needs to know —@@ -191,12 +174,12 @@ Tests live in `core/tests/switch_core/` mirroring the module structure. Uses pytdocs repository, never here. Start at `docs/README.md` for how the syncworks; `docs/official/internals/` covers architecture and the agentprotocol for readers of this repo.-- `docs/old/ARCHITECTURE.md` — historical system overview: components, domain- model, key flows, entry points, and a code map. Predates the docs sync and- may lag the tree.-- `docs/old/api/AGENT_PROTOCOL.md` — the agent↔Switch protocol (connections, the- event stream, room slots, failure handling). Authoritative where it and- `ARCHITECTURE.md` overlap+- `docs/old/ARCHITECTURE.md` — historical system overview from when Switch ran+ on Matrix. Much of it no longer matches the code; read it for background only.+- `docs/old/api/AGENT_PROTOCOL.md` — the original design of the agent↔Switch+ protocol (connections, the event stream, room slots, failure handling). Parts+ are out of date; where it and the code disagree, the code in+ `core/switch_core/bridges/agent/` is right.- `docs/old/bridges/` — collaboration bridge setup: `README.md` plus one page eachfor Slack, Mattermost, Discord, Teams, and Telegram- `docs/old/GATEWAY_OIDC_SETUP.md` — configuring the gateway's bring-your-owndiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1ba2c72ac..fb1867f32 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -69,8 +69,9 @@ Run `just` with no arguments to list every recipe. The most-used ones:| `switch-expert/` | Instructions and knowledge for an agent that answers questions about Switch || `justfile` | Repo-root task runner (drives all code trees) |-[`docs/old/ARCHITECTURE.md`](docs/old/ARCHITECTURE.md) describes the service's internal-module structure and the key request flows.+[`docs/official/internals/`](docs/official/internals/index.md) explains how Switch+works. [`docs/old/ARCHITECTURE.md`](docs/old/ARCHITECTURE.md) is an older overview from+when Switch ran on Matrix, and much of it is out of date.[`docs/old/GATEWAY_OIDC_SETUP.md`](docs/old/GATEWAY_OIDC_SETUP.md) coverssetting up bring-your-own OIDC sign-in for the gateway, including the WorkOSsetup path.diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.tsindex 475195bc0..2aad4fa9f 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts@@ -24,7 +24,7 @@ export type ParsedAgentTemplate = {sources: AgentTemplateSource[];/** The room the agent is put in once it exists, when the template declares one. */room: { name: string | null; kickoff: string | null } | null;- /** A provider id (`claude`, `codex`, `opencode`) or a `{param}` whose value is one. Null when the template has no `provider` field. */+ /** A provider id (`claude`, `codex`, `opencode`, `antigravity`, `cursor`) or a `{param}` whose value is one. Null when the template has no `provider` field. */provider: string | null;warnings: string[];};diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.tsindex 5c6867a13..8ad653fce 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts@@ -50,8 +50,8 @@ export type ParsedAgentEntry = {addressing: AgentTemplateAddressing | null;/*** Which coding agent runs it. Either a provider id (`claude`, `codex`,- * `opencode`) or a `{param}` whose value is one. Null when the template- * has no `provider` field.+ * `opencode`, `antigravity`, `cursor`) or a `{param}` whose value is one.+ * Null when the template has no `provider` field.*/provider: string | null;/** Where it runs: `local`, an ssh host, or a `{param}`. Null when the template has no `location` field. */diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex 59691a8cc..41653686c 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -753,9 +753,9 @@ describe('registerKnownAgent', () => {});it('sends the caller-supplied agent_type rather than a hardcoded default', async () => {- // The type governs the connector label and the hand-onboarding command the- // gateway shows, so a default here would silently mislabel every non-Claude- // agent (CHOO-1436).+ // The type governs the agent's provider label and the replies the gateway+ // builds for it, so a default here would silently mislabel every+ // non-Claude agent (CHOO-1436).const registered = await registerKnownAgent(SERVER, {name: 'codex-hoot',description: 'Codex running in repo',diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex bb74190c3..4d7a821b3 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -931,8 +931,8 @@ export type AgentProviderKind = 'anthropic' | 'third-party';*/export type ProvisionAgentParams = {workspaceId: string;- /** The agent's working directory; the settings file is written here and used- * as `repo_dir` so an offline-session command can `cd` into it. */+ /** The agent's working directory; the settings file is written here, and it+ * is recorded as `repo_dir` so Console can find the agent on a remote host. */dir: string;name: string;description: string;diff --git a/console/docs/INSTALL.md b/console/docs/INSTALL.mdindex f50fea0af..6f91dce25 100644--- a/console/docs/INSTALL.md+++ b/console/docs/INSTALL.md@@ -5,8 +5,9 @@ repository** (`sandbox-quantum/switch`). The repo is public, so the downloadsneed no account, token or sign-up. No need to build from source.> Builds are currently **macOS arm64 (Apple Silicon) and x64 (Intel)**, **Linux-> x64 and arm64** and **Windows x64**. Windows builds are not code signed — see-> [Install (Windows x64)](#install-windows-x64).+> x64 and arm64** and **Windows x64**. On Windows, an agent runs on the PC+> itself as a managed agent, on a server with agent management on; otherwise it+> needs an SSH host — see [Install (Windows x64)](#install-windows-x64).## Download@@ -137,12 +138,24 @@ Two caveats:The `.msi` supports the usual `msiexec` flow if you would rather not run theinstaller interactively.-### Docker-backed features are not available on Windows+### Where agents run on Windows-Switch Console can manage a local or remote Switch server through Docker. That-path is **macOS/Linux only** — Docker CLI discovery does not resolve-`docker.exe` on Windows. Connecting to a Switch server that is already running-elsewhere is unaffected.+On a server with agent management on (a local server Console runs has it), a+new agent on **This computer** runs on the PC as a managed agent: Console's+built-in agents controller runs it, once **Run managed agents on this computer**+is on. Antigravity has no Windows build, so it can't run there.++On a server without agent management, Console runs the agent itself, and those+sessions need a POSIX execution host, so Windows Console asks you to pick an SSH+host instead: a Linux or macOS machine you can reach over SSH, set up from+**Settings → Remote hosts**. Connecting to a Switch server and working in rooms+are unaffected either way.++### Running a server through Docker++Switch Console looks for Docker Desktop and Rancher Desktop on Windows, so it can+find `docker.exe` for a local server. Running a local server from Windows Console+has not been exercised end to end yet; please report what happens if you try it.Windows support is new and less exercised than the other platforms; please reportanything that misbehaves.diff --git a/console/packages/agent-providers/src/providers/registry.ts b/console/packages/agent-providers/src/providers/registry.tsindex 312ace4f5..a26d13c27 100644--- a/console/packages/agent-providers/src/providers/registry.ts+++ b/console/packages/agent-providers/src/providers/registry.ts@@ -18,8 +18,9 @@ export interface ProviderRuntimeOptions {logger: ProviderLogger | undefined;/*** The Switch skill file, for a provider that loads skills from a directory- * it is given (OpenCode), or '' for none. Codex takes it through its session- * home instead, and ACP agents through the session's system context.+ * it is given (OpenCode), or '' for none. Codex and the ACP agents take it+ * through the session's system context instead (Codex as its+ * `developerInstructions`).*/skill: string;/**diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 4477f96bd..0a3ea94ff 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -5,8 +5,7 @@ description: "How to take part in a Switch room. Load this skill before your fir# Switch Room Workflow-Switch orchestrates AI agents in collaborative rooms, using Matrix as the-internal message bus. You participate through+Switch orchestrates AI agents in collaborative rooms. You participate throughthe tools on the `switch` MCP server, which the session host Switch Consolestarted for you serves on this machine. Tool calls travel that host'sconnection to Switch, so you never talk to the Switch server directly. If the@@ -287,9 +286,13 @@ when it is, it never reaches the room or you at all, and the sender is told ontheir own platform instead.Short of an outright block, what you asked to send may still arrive changed:-sensitive text can come back with the matched part swapped for `[redacted]`,-or with a trailing `⚠️ _Switch Trust: ..._` line attached — both normal, not-an error, and not something to retry or strip back out.+sensitive text can come back with the matched part swapped for `[redacted]`.+A message Switch Trust flags, or could not check, is sent as written, and+Switch posts its own notice in a thread under it. Both are normal, not an+error, and not something to retry or undo. A person's message that Switch+Trust flagged reaches you with a trailing `⚠️ _Switch Trust flagged this+message…_` line: that line is Switch's annotation, not something the sender+wrote.## Questions and approvals@@ -298,17 +301,16 @@ room presents one question at a time; each addressed reply answers thatquestion. A form with several questions stays open until all questions haveanswers. Wait for the tool to return before acting on the answers.-**Antigravity is the exception.** It runs headless, and headless Antigravity-cannot prompt: a clarifying question it would have asked is skipped and an-approval it would have requested is denied, neither reaching the Console or the-room. When you genuinely need a decision there, ask in the room with-`send_targeted_message` and wait for the reply as an ordinary event — do not-stall on an answer the CLI will never surface.--Request cards (your session's questions and approvals) use server authorization. Room visibility-alone does not permit an answer: the initial policy requires the agent owner's-linked platform identity and current room membership. A pending answer is not-an approval; wait for the confirmed result. Cancellation remains cancellation.+Approvals reach the room on every host. Native question forms do not: Claude+Code, OpenCode and Antigravity have them, while Codex and Cursor sessions+generally do not. Without one, when you genuinely need a decision, ask in the+room with `send_targeted_message` and wait for the reply as an ordinary event.++Request cards (your session's questions and approvals) use server authorization.+Room visibility alone does not permit an answer: only someone allowed to address+you in that room may answer, under your addressing policy. By default that is+your owner and your owner's own agents; your owner can narrow or widen it. A+pending answer is not an approval; wait for the confirmed result. Cancellation remains cancellation.The server chooses request-card destinations. Ordinary session output stays insession details; use the Switch messaging tools for explicit room replies.@@ -659,7 +661,7 @@ endpoints, or accept the partial state.### Confirm before creating-Room creation is a real side effect: a Matrix room is provisioned, an external+Room creation is a real side effect: a Switch room is provisioned, an externalchannel may be created on the bridge, and agents are auto-joined. Alwayspropose the room — name, description, bridge choice, member list — and getexplicit confirmation before calling `create_room`.@@ -938,7 +940,7 @@ permission policy. Switch server authorization still applies to every operation.see the reason. Do not try to circumvent a denial.- **You are a participant, not the controller.** Other agents and humans arein the room. Read the conversation and contribute meaningfully.-- **Confirm before creating rooms.** Room creation provisions a Matrix room and+- **Confirm before creating rooms.** Room creation provisions a Switch room andmay create an external channel. Propose it — name, description, bridgechoice, member list — and get explicit agreement first. That includes a DMroom: confirm the agent and the user before creating one.@@ -974,8 +976,9 @@ When unsure, prefer the Slack-safe shape — it reads fine everywhere.## Session controlsIn a room your session is connected to, `!reset`, `!compact`, and `!interrupt`-use server-authorized durable commands. The agent owner must issue these controls-from a verified account. An acknowledgement reports command status, not completion;+use server-authorized durable commands. They take the same permission as a+message: only someone allowed to address you can issue them, which by default+is your owner and your owner's own agents. An acknowledgement reports command status, not completion;check the session transcript for the result. Unsupported controls fail explicitly.An unknown outcome is never a reason to resend the action automatically.After a confirmed reset or compaction, Switch queues a follow-up to reconnect,@@ -983,11 +986,6 @@ read context, re-assume the previous role if one was held, and confirm the resulto the requester in the original thread. If the role cannot be restored, reportthat limitation. Failed or unknown controls do not queue a success announcement.-On Antigravity, `!interrupt` restarts the Antigravity process and resumes the-same conversation rather than stopping a turn in place. The work in flight does-not continue on the other side of it, so treat an interrupted request as one to-be asked again, not one you are still part-way through.-## Tool indexEvery Switch tool you call in normal operation, one line each.diff --git a/console/packages/plugins/src/switch-skill/index.ts b/console/packages/plugins/src/switch-skill/index.tsindex 0a8d7ed9e..491f7d7cb 100644--- a/console/packages/plugins/src/switch-skill/index.ts+++ b/console/packages/plugins/src/switch-skill/index.ts@@ -2,8 +2,8 @@ import skill from './SKILL.md';/*** The Switch room-workflow skill every session is given, as a skill file:- * frontmatter and body. Codex and OpenCode load it from a skills directory- * under the name `switch`, which must match the frontmatter's `name`.+ * frontmatter and body. OpenCode loads it from a skills directory under the+ * name `switch`, which must match the frontmatter's `name`.*/export const SWITCH_SKILL_FILE: string = skill;diff --git a/console/tooling-e2e/README.md b/console/tooling-e2e/README.mdindex 77dd3fcde..a0b375280 100644--- a/console/tooling-e2e/README.md+++ b/console/tooling-e2e/README.md@@ -20,10 +20,8 @@ SWITCH_E2E=1 ../node_modules/.bin/vitest run src/loopback.integration.test.tsSWITCH_E2E=1 ../node_modules/.bin/vitest run src/run.integration.test.ts```-This package is not yet listed in `console/pnpm-workspace.yaml`, so it has no-`node_modules` of its own and runs against the workspace root's hoisted `vitest`-and `typescript`. Adding `- 'tooling-e2e'` to that file's `packages:` list makes-the usual forms work instead:+The package is listed in `console/pnpm-workspace.yaml`, so the usual forms work+too:```bashpnpm --filter @switch-console/tooling-e2e test@@ -60,7 +58,7 @@ beside this file. Never commit one.| `SWITCH_E2E_MANIFEST` | no | File the setup records its agent and room in, so a second process can reuse them instead of registering its own. See "Seeding first" below. || `SWITCH_E2E_REPLY_TIMEOUT_MS` | no | How long a scenario waits for the agent (default 5 min). || `SWITCH_E2E_SESSION_TIMEOUT_MS` | no | How long setup waits for a live session (default 2 min). |-| `SWITCH_E2E_AGENT_TYPE` | no | `opencode` (default), `claude-code`, or `codex` — which provider's runtime is under test. Decides the agent name prefix, the Switch known-agent type, and (for `claude-code`) the extra files written into the working dir. |+| `SWITCH_E2E_AGENT_TYPE` | no | `opencode` (default), `claude-code`, `codex`, `antigravity` or `cursor` — which provider's runtime is under test. Decides the agent name prefix, the Switch known-agent type, and (for `claude-code`) the extra files written into the working dir. || `SWITCH_E2E_QUESTION_MODE` | no | `numbered` (default, every agent type) or `prose`; see the `question` row below. |The suite **skips, with the reason printed**, when `SWITCH_E2E` is unset, when@@ -140,9 +138,7 @@ definition the session is launched as.For Codex, use `SWITCH_E2E_AGENT_TYPE=codex` and `SWITCH_E2E_QUESTION_MODE=prose`,with `provider_id` and `providerId` both `codex`. The normal Codex mode doesnot expose its native question tool; the prose scenario verifies the room-round trip without claiming to test a native question card. Codex may request-approval to read the Switch skill on first launch; answer it in Console or-the room before the greeting proceeds.+round trip without claiming to test a native question card.Setup finds the manifest, reuses what is in it rather than registering a secondagent, and deletes it during teardown — so a manifest never outlives its room.diff --git a/console/tooling-e2e/src/switch-client.ts b/console/tooling-e2e/src/switch-client.tsindex 798b103e2..a28c0d9ce 100644--- a/console/tooling-e2e/src/switch-client.ts+++ b/console/tooling-e2e/src/switch-client.ts@@ -389,9 +389,9 @@ export class SwitchClient {/*** Register a "known agent" (`POST /agents/register-known`, registration-token- * auth). `agentType` is one of the gateway's known types — `opencode`,- * `codex`, `claude-code` — and `options` is that type's option schema, which- * for OpenCode is `{ auto_session, repo_dir }`.+ * auth). `agentType` is one of the gateway's known types — `claude-code`,+ * `codex`, `opencode`, `cursor` or `antigravity` — and `options` is that+ * type's option schema, which for OpenCode is `{ auto_session, repo_dir }`.** Registration is also what mints the agent's Mattermost bot account: the* protocol service calls `create_agent_identity` on every collaborationdiff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex 5c8643058..27f03b212 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -36,7 +36,6 @@ from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.events import CommandEvent-from switch_core.gateway.known_agents import known_agent_forfrom switch_core.transport import RoomRefif TYPE_CHECKING:@@ -66,7 +65,7 @@ CommandHandler = Callable[]# (client, args, room_id) -> whether THIS agent is addressed by the command.# Targeting is a per-command policy (see Command.addressed) rather than a fixed-# rule in on_command, so a command like `run-cmd` can interpret its args its+# rule in on_command, so a command like `reset` can interpret its args its# own way.CommandTargeting = Callable[["AgentRecipient", str, str], Awaitable[bool]]# (host, room, event, meta) -> None. An admin-side usage check run by the@@ -102,29 +101,14 @@ async def _addressed_by_name_or_role(return await client._text_tags_my_role(session, args, room_id)-async def _addressed_by_first_mention(- client: AgentRecipient, args: str, room_id: str-) -> bool:- """Targeting for `run-cmd`: only the FIRST `@token` addresses an agent (by- name or by a role it holds). Any further `@token` is data for the handler- (the role to name in the output), not an addressing token — so- `!run-cmd @alice @manager` reaches alice, not whoever holds manager.-- No `@token` → addressed to everyone (the command applies room-wide).- """- tokens = _mention_tokens(args)- if not tokens:- return True- return await _first_token_is_me(client, tokens[0], room_id)--async def _addressed_by_required_first_mention(client: AgentRecipient, args: str, room_id: str) -> bool:- """Like `_addressed_by_first_mention`, but a missing target addresses NO- ONE. Used by `!reset`, where a bare `!reset` must not silently reset every- agent in the room — resetting all agents is the separate, explicit- `!reset-all-agents` command.+ """Targeting for a command that needs a target: only the FIRST `@token`+ addresses an agent (by name or by a role it holds), and a missing target+ addresses no one. Used by `!reset`, where a bare `!reset` must not+ silently reset every agent in the room — resetting all agents is the+ separate, explicit `!reset-all-agents` command."""tokens = _mention_tokens(args)if not tokens:@@ -252,7 +236,7 @@ class Command:# If True, the always-present admin client owns this command: it parses,# executes, and renders the result as an admin/system message. Agents ignore# it. If False, the command is handled by the agents themselves (e.g.- # `!run-cmd`, `!reset`, `!agents-greet`), which answer in their own voice.+ # `!reset`, `!agents-greet`), which answer in their own voice.admin_owned: bool = False# Set for a command that is queued for the agent (the session controls).# The router decides it in the transaction that writes the command and@@ -1755,78 +1739,6 @@ async def _cmd_list_all_agents(await _reply(client, room, event, "\n".join(lines))-def _role_arg(args: str) -> str | None:- """The role to name in the `run-cmd` output, if one was supplied.-- The first `@token` targets the agent (see `_addressed_by_first_mention`);- the SECOND `@token`, if present, is the role the started session should- assume (`!run-cmd @agent @role`). Returns that second token, or None.- """- tokens = _mention_tokens(args)- return tokens[1] if len(tokens) >= 2 else None---async def _cmd_run_cmd(- client: AgentRecipient,- room: RoomRef,- event: CommandEvent,- _is_direct: bool,-) -> None:- meta = await client._resolve_room_meta(room.room_id)- if meta is None:- await _reply(client, room, event, "Room not found.")- return-- # Re-read the agent so edits to options via the gateway are reflected- # without restarting this client.- async with client.session_factory() as session:- fresh = await client._agent_store.get(session, client.agent.id)- agent = fresh or client.agent- spec_options = known_agent_for(agent)- if spec_options is None:- await _reply(- client, room, event, "No onboarding command available for this agent."- )- return-- spec, options = spec_options-- # `!run-cmd @agent @role`: fold a real role into the connect prompt so the- # started session lands in the room AND assumes the role in one command.- # An unknown role is NOT folded in — we warn instead of silently dropping.- role = _role_arg(event.args)- async with client.session_factory() as session:- role_obj = (- await client._room_role_store.get_role(session, meta.room_id, role)- if role is not None- else None- )- owner_handle = await client.owner_handle_in(session, agent, meta.bridge_id)- role_known = role_obj is not None-- msg = spec.start_session_instructions(- options,- agent,- meta.name,- owner_handle,- assume_role=role if role_known else None,- )- if msg is None:- await _reply(- client, room, event, "No onboarding command available for this agent."- )- return-- if role is not None and not role_known:- msg += (- f"\n\n⚠️ Note: there is no role named **{role}** in **{meta.name}**, "- "so I left it out of the command — double-check the role name (see "- "the room's roles)."- )-- await _reply(client, room, event, msg)--async def _cmd_agents_greet(client: AgentRecipient,room: RoomRef,@@ -2079,26 +1991,6 @@ COMMANDS: list[Command] = ["Have agents in the room introduce themselves.",_cmd_agents_greet,),- Command(- "run-cmd",- "Show the terminal command to start a session for an agent. "- "Usage: `!run-cmd @agent-name`, `!run-cmd @role` (the role's holder), "- "or `!run-cmd @agent-name @role` to also assume that role on connect.",- _cmd_run_cmd,- # `role` is second because the handler reads it from the second token,- # so it cannot be given without `agent` — see the positional-gap check- # in the Discord adapter, which rejects that combination loudly rather- # than silently shifting the role into the agent slot.- args_spec=(- CommandArg("agent", "Agent to show the start command for", required=False),- CommandArg(- "role", "Role for that agent to assume on connect", required=False- ),- ),- # Only the first @token targets; a second @token is the role to assume,- # not an address — so it doesn't pull in whoever else holds that role.- addressed=_addressed_by_first_mention,- ),]COMMANDS_BY_NAME: dict[str, Command] = {cmd.name: cmd for cmd in COMMANDS}diff --git a/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.json b/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.jsonindex f8dbe6309..c157ca50a 100644--- a/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.json+++ b/core/switch_core/bridges/collaboration/teams/distributed_app/manifest.json@@ -92,10 +92,6 @@{"title": "/list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "/room-url",- "description": "Show this room's address in Switch"}]},@@ -156,10 +152,6 @@{"title": "list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "room-url",- "description": "Show this room's address in Switch"}]}diff --git a/core/switch_core/db/stores/agent_session_store.py b/core/switch_core/db/stores/agent_session_store.pyindex ace35dca8..a9b674ae5 100644--- a/core/switch_core/db/stores/agent_session_store.py+++ b/core/switch_core/db/stores/agent_session_store.py@@ -155,7 +155,7 @@ class AgentSessionStore:session-close signal, so the binding lingers after a session ends.Paired with a liveness check by the caller: a binding present while theagent is not live means a session_addressable session is connected but- not reporting in (e.g. launched without the dev-channels flag).+ not reporting in."""result = await session.execute(select(AgentSession.agent_id)diff --git a/core/switch_core/deeplinks.py b/core/switch_core/deeplinks.pyindex e8db4bb22..ec5179b0d 100644--- a/core/switch_core/deeplinks.py+++ b/core/switch_core/deeplinks.py@@ -161,6 +161,7 @@ class ConsolePage:# with the names a person reads. A test holds the two together.CONSOLE_PAGES: Mapping[str, ConsolePage] = {"home": ConsolePage("the server's home"),+ "server": ConsolePage("this server's own settings"),"agents": ConsolePage("the list of agents"),"agents/new": ConsolePage("the page to add a new agent"),"agent": ConsolePage(@@ -195,6 +196,13 @@ CONSOLE_PAGES: Mapping[str, ConsolePage] = {"messaging-apps/connect": ConsolePage("the page to connect a messaging app"),"connections": ConsolePage("your connectors"),"invite": ConsolePage("the page to invite people to the workspace"),+ "admin": ConsolePage(+ "the workspace's admin page",+ tabs={+ "connectors": "the connectors the workspace offers",+ "apps": "the apps connectors sign in through",+ },+ ),"settings": ConsolePage("Switch Console's settings",tabs={diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.pyindex 48cc0b3c9..3ce10db65 100644--- a/core/switch_core/delivery/recipient.py+++ b/core/switch_core/delivery/recipient.py@@ -208,11 +208,6 @@ _UNAVAILABLE_MESSAGES = {"I'm not in an active session right now. ""I'll see this when I next connect to the room."),- "session_passive": (- "I read room messages asynchronously, not in real time — my operator "- "has to trigger me to pull the latest messages, either from a session I "- "already have open or by starting a new one."- ),# auto_session with no watcher reporting in: same honest "offline" story as# always_on — nothing is going to spin a session up right now."auto_session": (@@ -227,18 +222,15 @@ _UNAVAILABLE_MESSAGES = {# the connector will spin a session up on demand to handle the message._STARTING_SESSION_MESSAGE = "Starting a session to handle this — one moment."-# Fallback (no known-agent connect command) for a session_addressable agent-# that has a session bound to this room but is not reporting as live — the-# usual cause is a session started without the dev-channels flag.+# Fallback, for an agent with no known-agent spec, when it has a session bound+# to this room that is not reporting as live._CONNECTED_NOT_LIVE_MESSAGE = ("I have a session connected to this room, but it isn't reporting as live, "- "so I'm not receiving messages — my operator may need to restart it."+ "so I'm not receiving messages — my owner may need to restart it.")-def _offline_owner_message(- owner_handle: str | None, asker_handle: str, cmd: str | None-) -> str:+def _offline_owner_message(owner_handle: str | None, asker_handle: str) -> str:"""The reply for an auto_session agent addressed with nothing to start it.An auto_session agent is brought online by Switch Console watching on its@@ -255,22 +247,97 @@ def _offline_owner_message(# the reason they should act reads as a stutter ("@me … and @me needs me").needs_me = "" if owner_handle == asker_handle else f", and @{asker_handle} needs me"if owner_handle:- opening = (+ return (f"@{owner_handle} — I'm not online in this room{needs_me}. ""Open Switch Console to bring me online here.")- terminal = "If you'd rather do it from a terminal:"- else:- # No owner account on this platform to mention. Still name who has to- # act, so the message is not read as something the room can fix.- opening = (- f"I'm not online in this room{needs_me}. **My owner needs to open "- "Switch Console** to bring me online here."+ # No owner account on this platform to mention. Still name who has to act,+ # so the message is not read as something the room can fix.+ return (+ f"I'm not online in this room{needs_me}. **My owner needs to open "+ "Switch Console** to bring me online here."+ )+++def _join_room_names(names: list[str]) -> str:+ bold = [f"**{name}**" for name in names]+ if len(bold) == 1:+ return bold[0]+ return f"{', '.join(bold[:-1])} and {bold[-1]}"+++def _owner_actor(owner_handle: str | None, asker_handle: str) -> str:+ """Who to name as the person who has to act: the owner's @-mention, so the+ owner is notified; "you" when the owner is the one asking; "my owner" when+ the owner has no account on this platform to mention."""+ if owner_handle is None:+ return "my owner"+ if owner_handle == asker_handle:+ return "you"+ return f"@{owner_handle}"+++def _passive_message(owner_handle: str | None, asker_handle: str) -> str:+ """The reply for a session_passive agent addressed in a room.++ Such an agent never receives room messages in real time, so it is not+ told it has no session; the owner has to trigger it to read the room, and+ is mentioned so they are notified.+ """+ actor = _owner_actor(owner_handle, asker_handle)+ verb = "have" if actor == "you" else "has"+ return (+ f"I read room messages asynchronously, not in real time — {actor} {verb} "+ "to trigger me to pull the latest messages, either from a session I "+ "already have open or by starting a new one."+ )+++def _start_from_console_message(+ agent_name: str,+ room_name: str,+ sign_in_command: str,+ owner_handle: str | None,+ asker_handle: str,+ other_room_names: list[str] | None,+ connected_not_live: bool,+) -> str:+ """The reply for an agent Switch Console runs, addressed where it has no+ live session, when the plain "I'm not online" reply does not fit: it has+ sessions in other rooms, or a session here that is not live.++ The fix is always to start or restart it from Switch Console, so that is+ what the reply says, naming the room to connect the session to. A CLI+ started by hand in a terminal gets none of the Switch tools, which is why+ no terminal command is offered; the provider's sign-in command is, since a+ signed-out CLI is the usual reason Console cannot start one. The owner is+ named where the action is, and called "you" when they are the one asking.+ """+ actor = _owner_actor(owner_handle, asker_handle)+ sentence_actor = actor if actor.startswith("@") else actor.capitalize()+ console = f"opening **{agent_name}** in Switch Console"+ sign_in = (+ "If Switch Console says I'm signed out, sign me in first with "+ f"`{sign_in_command}` on the machine I run on."+ )+ if connected_not_live:+ return (+ "I have a session connected to this room, but it isn't reporting as "+ "live, so I'm not receiving messages. "+ f"{sentence_actor} can restart it by {console}. {sign_in}"+ )+ if other_room_names:+ return (+ "I don't have a session in this room right now, but I'm working in "+ f"{_join_room_names(other_room_names)}, so you can ask me there. "+ f"Or {actor} can start one connected to **{room_name}** by {console}. "+ f"{sign_in}")- terminal = "Or, from a terminal:"- if cmd is None:- return opening- return f"{opening} {terminal}\n\n```\n{cmd}\n```"+ return (+ "I don't have a session connected to this room. "+ f"{sentence_actor} can start one connected to **{room_name}** by "+ f"{console}. {sign_in}"+ )def _stopped_owner_message(owner_handle: str | None, asker_handle: str) -> str:@@ -677,8 +744,8 @@ class AgentRecipient:## Everything else here is the whole reply and nothing follows# it, so it threads off the triggering message: an owner mention- # and a paste-ready command are a wall of text to drop into a- # channel for something only one person can act on (CHOO-2344).+ # is noise in a channel for something only one person can act+ # on (CHOO-2344).thread_idif unavailable == _STARTING_SESSION_MESSAGEelse reply_thread_root,@@ -991,7 +1058,7 @@ class AgentRecipient:# Targeting is a per-command policy: each Command decides whether its# args address this agent (Command.addressed). The default matches our- # @name or a role we hold; some commands (e.g. run-cmd) override it.+ # @name or a role we hold; some commands (e.g. reset) override it.addressed = cmd.addressed if cmd is not None else _addressed_by_name_or_roleif not await addressed(self, event.args, meta.room_id):return@@ -1107,7 +1174,7 @@ class AgentRecipient:thread_root_id: str | None = None,) -> None:"""Post a command result as this agent (an agent-owned command like- `!run-cmd` answers in the agent's own voice, not as a system message)."""+ `!reset` answers in the agent's own voice, not as a system message)."""await self.actor.send_message(room_id,body,@@ -1149,11 +1216,10 @@ class AgentRecipient:useless).session_passive agents have no heartbeat, so the elsewhere/role logic- never applies: they fall through to the generic reply, whose wording- already covers pulling from an existing session or starting a new one.- For a session_addressable agent with a session bound to THIS room but- not live here (and no live session in a distinct room), the reply says- so and tells the operator to relaunch with live channels.+ never applies: they get the passive reply, which says they read when+ their owner triggers them. For a session_addressable agent with a+ session bound to THIS room but not live here (and no live session in a+ distinct room), the reply says so and asks the owner to restart it.A controller-backed agent is answered from its controller alone, beforeanything here could promise a session: Switch does not know where its@@ -1230,17 +1296,15 @@ class AgentRecipient:if names:if holds_role_here:return _elsewhere_message(names, holds_role_here=True)- # No role lease here, just sessions elsewhere: prefer the- # known-agent reply so the operator gets the paste-ready- # connect command alongside the "ask me there" alternative.+ # No role lease here, just sessions elsewhere: the reply offers+ # "ask me there" alongside starting a session here.return await self._unavailable_reply(session, meta, agent, asker_handle, other_room_names=names)# No live session in a distinct room. A session_addressable agent bound- # to THIS room but not live here was most likely launched without live- # channels: say a session is connected-but-not-live rather than imply- # there is none.+ # to THIS room but not live here: say a session is connected but not+ # live rather than imply there is none.if connection_model == "session_addressable" and bound_here:return await self._unavailable_reply(session, meta, agent, asker_handle, connected_not_live=True@@ -1252,7 +1316,7 @@ class AgentRecipient:) -> str | None:"""Why an agent run by an agents controller cannot answer here.- Never the terminal command or "open Switch Console": a managed agent+ Never "open Switch Console": a managed agentis started by its controller, so the reply names what stands in theway: the owner stopped it, or its machine was removed or is offline.None while it is connected: the message is delivered, and any notice@@ -1341,12 +1405,16 @@ class AgentRecipient:An auto_session agent with nowhere else to point the asker gets theowner-facing "I'm not online" reply: only its owner can act, so the- message asks them and nobody else. Every other case prefers the- per-known-agent `start_session_instructions` (e.g. the paste-ready- terminal command for Claude Code), falling back to the static- `_UNAVAILABLE_MESSAGES` text keyed by connection_model when the agent- has no known-agent spec or the spec returns None; `connected_not_live`- selects the "bound here but not live" fallback.+ message asks them and nobody else. A session_passive agent is never live+ in real time, so it gets `_passive_message`, which names its owner,+ rather than being told it has no session. A known agent that Switch+ Console starts or keeps live (auto_session, session_addressable)+ otherwise gets `_start_from_console_message`. Anything else falls back+ to the static `_UNAVAILABLE_MESSAGES` text keyed by connection_model:+ an always_on agent is down because its connector is, whatever spec it+ registered through, and starting a session would not fix that.+ `connected_not_live` selects the "bound here but not live" fallback, and+ a connection_model with no text of its own is treated as passive.`agent` is the row read for this routing, so option edits made throughthe gateway (e.g. `PATCH /agents/{id}/options`, `connection_model`)@@ -1355,7 +1423,11 @@ class AgentRecipient:connection_model = (agent.integration_profile or {}).get("connection_model", "session_passive")- spec_options = known_agent_for(agent)+ if connection_model == "session_passive":+ return _passive_message(+ await self.owner_handle_in(session, agent, meta.bridge_id),+ asker_handle,+ )# `other_room_names` outranks this: a live session in another room is# somewhere the asker can go right now, which beats asking the owner to# start something.@@ -1364,32 +1436,32 @@ class AgentRecipient:and not other_room_namesand not connected_not_live):- cmd = (- spec_options[0].connect_command(spec_options[1], agent, meta.name, None)- if spec_options is not None- else None- )return _offline_owner_message(await self.owner_handle_in(session, agent, meta.bridge_id),asker_handle,- cmd,)- if spec_options is not None:- spec, options = spec_options- msg = spec.start_session_instructions(- options,- agent,+ spec_options = known_agent_for(agent)+ if spec_options is not None and connection_model in (+ "auto_session",+ "session_addressable",+ ):+ return _start_from_console_message(+ agent.name,meta.name,+ spec_options[0].provider.sign_in_command,await self.owner_handle_in(session, agent, meta.bridge_id),- other_room_names=other_room_names,- connected_not_live=connected_not_live,+ asker_handle,+ other_room_names,+ connected_not_live,)- if msg is not None:- return msgif connected_not_live:return _CONNECTED_NOT_LIVE_MESSAGE- return _UNAVAILABLE_MESSAGES.get(- connection_model, _UNAVAILABLE_MESSAGES["session_passive"]+ static = _UNAVAILABLE_MESSAGES.get(connection_model)+ if static is not None:+ return static+ return _passive_message(+ await self.owner_handle_in(session, agent, meta.bridge_id),+ asker_handle,)async def _is_available(diff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.pyindex 05611d87d..f5cf98005 100644--- a/core/switch_core/gateway/known_agents.py+++ b/core/switch_core/gateway/known_agents.py@@ -13,8 +13,6 @@ from switch_core.bridges.agent.protocol.types import ()from switch_core.providers.registry import (AgentProvider,- ConsoleStart,- TerminalStart,agent_provider,agent_providers,)@@ -23,27 +21,6 @@ if TYPE_CHECKING:from switch_core.db.models import Agent-def connect_prompt(- room_name: str,- agent_name: str,- assume_role: str | None,- also_pull: bool,-) -> str:- """The natural-language prompt a started session is launched with.-- One directory can hold credentials for several provisioned agents, in which- case the session has to be told which one it is before it may act. Naming- the agent in the prompt itself answers that without the operator having to- know it happens.- """- prompt = f"connect to switch room {room_name}"- if assume_role:- prompt += f" and assume the role {assume_role}"- if also_pull:- prompt += " and pull the latest messages"- return f"{prompt} — if you are asked which agent you are, you are {agent_name}"--class KnownAgentOptions(BaseModel):"""Base class for per-known-agent registration options.@@ -86,77 +63,12 @@ class KnownAgent(ABC):def parse_options(self, raw: dict[str, Any] | None) -> KnownAgentOptions:return self.options_schema.model_validate(raw or {})- def connect_command(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- assume_role: str | None,- ) -> str | None:- """The paste-ready shell command that starts this agent connected to- `room_name`, with no surrounding prose.-- Split out from `start_session_instructions` because the command is the- one host-specific part: callers that need their own wording around it- (the addressed-but-offline reply) take the command and write the rest- themselves, rather than each host restating the same sentences.-- None when no command applies — the same condition that makes- `start_session_instructions` return None.- """- return None-- def start_session_instructions(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- assume_role: str | None = None,- other_room_names: list[str] | None = None,- connected_not_live: bool = False,- ) -> str | None:- """Return markdown telling the operator how to start a session that- connects this agent to the room named `room_name`. Posted- automatically when the agent is addressed but has no live session,- and on demand via `!run-cmd`.-- `owner_handle` is the agent owner's account on the platform this room- is bridged to, @-mentioned so they are actually notified — None when- the agent has no owner or that owner has claimed no account there, in- which case the message still posts and simply says "my operator". It- is passed in rather than read from `options`: the right handle depends- on which platform the room is on, which the caller knows and a- per-agent setting could not.-- When `assume_role` is set, the generated connect prompt also tells the- agent to assume that role on connect (e.g. `!run-cmd @agent @role`).-- When `other_room_names` is set, the agent has no session here but does- have live session(s) connected to those rooms; the opening sentence- names them and offers asking there as an alternative to running the- command.-- When `connected_not_live` is set, a session is bound to THIS room but- is not reporting as live (e.g. a session_addressable install launched- without the dev-channels flag); the opening says so and tells the- operator to relaunch with live channels.-- Default is None — meaning "no onboarding command applies" (e.g.- always_on agents that aren't operator-driven).- """- return None-class ClaudeCodeOptions(KnownAgentOptions):channels_enabled: bool = True- """Whether the Claude Code installation can run with- `--dangerously-load-development-channels plugin:switch-connector@switch-plugins`- so the channel server delivers inbound room events. Defaults to True for- backwards compatibility. Set to False for installations that cannot enable- that flag (e.g. Vertex AI or other managed setups without a Claude- subscription); the registered profile then becomes `session_passive`- instead of `session_addressable`."""+ """Whether sessions receive room events as they happen. Switch Console+ registers every agent with this on. When False, the registered profile+ becomes `session_passive` instead of `session_addressable`."""auto_session: bool = False"""When True, the operator's connector (Switch Console) watches every room this@@ -173,23 +85,16 @@ class ClaudeCodeOptions(KnownAgentOptions):started, same as any `session_passive` install."""repo_dir: str | None = None- """Absolute path to the local checkout/directory the operator runs Claude- Code from. When set, Switch uses it to generate ready-to-paste terminal- commands (`cd <repo_dir> && claude "connect to switch room ..."`) shown- in rooms whenever someone tries to address this agent while no session is- active. Leave None if the directory is unknown — a fallback guidance- message is shown instead."""+ """Absolute path to the directory the agent's sessions run in. Switch+ Console sets it when the agent is onboarded. None when it is unknown."""subagent_name: str | None = None"""When set, this agent is a Claude Code *subagent* (a `.claude/agents/*.md`definition) rather than a top-level Claude Code install. The value is thebare Claude Code subagent identifier (its `name` frontmatter field). Switch- uses it to launch the session as that subagent: the generated connect- command gains `--agent <subagent_name>` (adopt the subagent persona/tools/- model) and `--settings .claude/switch-subagents/<subagent_name>.settings.json`- (a settings file holding this subagent's own SWITCH_* credentials, so the- session authenticates to Switch as the subagent, not the parent). Leave- None for ordinary top-level agents."""+ Console uses it to start the session as that subagent, with the subagent's+ own credentials, so the session authenticates to Switch as the subagent+ rather than the parent. Leave None for ordinary top-level agents."""@field_validator("repo_dir", "subagent_name", mode="before")@classmethod@@ -219,10 +124,9 @@ class ClaudeCodeKnownAgent(KnownAgent):pre_invocation_mediation=["tool_calls"],post_invocation_mediation=[],event_reporting=["tool_calls"],- # Claude Code can reset / compact / interrupt only when a session is- # driving it from Switch Console (which can inject keystrokes and- # relaunch it). A standalone `claude` session can't be controlled,- # so all three resolve per live session via AgentRuntimeState.+ # Reset / compact / interrupt work only on a session that Switch+ # Console (or its sidecar or an agents controller) is running, so+ # all three resolve per live session via AgentRuntimeState.command_capabilities=CommandCapabilities(reset="session_dependent",compact="session_dependent",@@ -230,119 +134,6 @@ class ClaudeCodeKnownAgent(KnownAgent):),)- def connect_command(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- assume_role: str | None,- ) -> str | None:- assert isinstance(options, ClaudeCodeOptions)- # Channels-enabled installations need the dev-channels flag so the- # plugin can deliver inbound events; without channels the flag is a- # no-op (e.g. Vertex AI / Bedrock installations).- flag = (- " --dangerously-load-development-channels plugin:switch-connector@switch-plugins"- if options.channels_enabled- else ""- )- # Use a `<claude-dir>` placeholder when the operator hasn't configured- # a directory — the command is still useful, the operator just has to- # substitute their own path.- dir_token = options.repo_dir if options.repo_dir else "<claude-dir>"- # Subagents launch as their own session: `--agent <name>` adopts the- # subagent persona, and `--settings <file>` points at a settings file- # holding the subagent's own SWITCH_* credentials so the session- # authenticates to Switch as the subagent rather than the parent. The- # settings path is relative to the directory we `cd` into above.- subagent_flags = ""- if options.subagent_name:- settings_path = (- f".claude/switch-subagents/{options.subagent_name}.settings.json"- )- subagent_flags = (- f" --agent {options.subagent_name} --settings {settings_path}"- )- # A session_passive session receives no pushed events, so the connect- # must also pull — fold that into the prompt itself.- prompt = connect_prompt(- room_name,- agent.name,- assume_role,- also_pull=not options.channels_enabled,- )- return f'cd {dir_token} && claude "{prompt}"{subagent_flags}{flag}'-- def start_session_instructions(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- 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.-- Shape depends on the install's connection model:-- - channels disabled (session_passive): the agent reads asynchronously,- so the message says the operator must trigger a pull, the connect- command itself includes "and pull the latest messages", and a note- explains real-time delivery needs an Anthropic API key / subscription.- - channels enabled (session_addressable): the usual connect command.- `connected_not_live` switches the opening to "a session is connected- here but isn't live" (operator likely launched it without the- dev-channels flag); `other_room_names` points the asker at live- sessions in genuinely different rooms instead.- """- assert isinstance(options, ClaudeCodeOptions)- cmd = self.connect_command(options, agent, room_name, assume_role)-- if not options.channels_enabled:- # session_passive: reads asynchronously, so the operator must- # trigger a pull (from an open session or a fresh one). Mention the- # configured operator inline so they get pinged.- operator = f"my operator @{owner_handle}" if owner_handle else "my operator"- return (- f"I read room messages asynchronously, not in real time — "- f"{operator} has to trigger me to pull the latest messages. "- f"They can use a session I already have open, or start a new "- f"one:\n\n```\n{cmd}\n```\n\n(For me to process messages in real "- f"time instead, run my Claude Code with an Anthropic API key or "- f"subscription so live channels can be enabled.)"- )-- # session_addressable: an optional @-mention so the operator gets a- # push from the bridged platform. The bridge re-parses these as- # addressed events.- prefix = f"@{owner_handle}\n\n" if owner_handle 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. If it's "- "still running it was likely started without live channels — "- "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 "- f"I 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 Claude Code "- "manually and ask me to connect to the room.)"- )-class GenericAgentOptions(KnownAgentOptions):auto_session: bool = False@@ -354,9 +145,8 @@ class GenericAgentOptions(KnownAgentOptions):Switch Console delivers inbound room messages into the session itself."""repo_dir: str | None = None- """Absolute path to the directory the operator runs the agent from, used in- the start command shown when the agent is addressed with no live session.- None shows a `<provider-dir>` placeholder instead."""+ """Absolute path to the directory the agent's sessions run in. Switch+ Console sets it when the agent is onboarded. None when it is unknown."""# No `channels_enabled`: Switch Console sends it for every provider, but# only Claude Code has a connector channel that could act on it.@@ -404,87 +194,6 @@ class GenericKnownAgent(KnownAgent):),)- def connect_command(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- assume_role: str | None,- ) -> str | None:- assert isinstance(options, GenericAgentOptions)- start = self.provider.session_start- if not isinstance(start, TerminalStart):- return None- dir_token = (- options.repo_dir if options.repo_dir else f"<{self.provider.id}-dir>"- )- prompt = connect_prompt(room_name, agent.name, assume_role, also_pull=False)- return f'cd "{dir_token}" && ' + start.command.replace("{prompt}", prompt)-- def start_session_instructions(- self,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- 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: the start command for a- provider started from a terminal, else how to start it from Switch- Console. These sessions are normally auto-managed by Switch Console, so- this is shown mainly when no connector is watching."""- assert isinstance(options, GenericAgentOptions)- start = self.provider.session_start- if isinstance(start, ConsoleStart):- return _console_start_instructions(start, agent, room_name, owner_handle)- cmd = self.connect_command(options, agent, room_name, assume_role)- prefix = f"@{owner_handle}\n\n" if owner_handle 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 "- f"{self.provider.label} manually and ask me to connect to the room.)"- )---def _console_start_instructions(- start: ConsoleStart, agent: Agent, room_name: str, owner_handle: str | None-) -> str:- prefix = f"{owner_handle} — " if owner_handle else ""- runtime = (- f", enable the {start.runtime} runtime in its advanced settings,"- if start.runtime- else ""- )- sign_in = (- f" Sign in with `{start.sign_in_command}` first if you have not already."- if start.sign_in_command- else ""- )- return (- f"{prefix}open **{agent.name}** in Switch Console{runtime} and start a "- f"local session in **{room_name}**.{sign_in}"- )-# Providers whose known agent is not the generic one, by `known_agent_type`._SPECIALISED: dict[str, type[KnownAgent]] = {"claude-code": ClaudeCodeKnownAgent}diff --git a/core/switch_core/official_templates/switch-expert/AGENT.md b/core/switch_core/official_templates/switch-expert/AGENT.mdindex f9fa5a191..16b1951cb 100644--- a/core/switch_core/official_templates/switch-expert/AGENT.md+++ b/core/switch_core/official_templates/switch-expert/AGENT.md@@ -90,7 +90,7 @@ Switch runs on many servers and the details differ per server. You ship with **nthem. At the start of a setup conversation, ask for what you need and remember it for theconversation:-- The server's Gateway and API URLs.+- The server's address.- How they sign in.- Any network prerequisite to reach it (a VPN, an allow-list, nothing at all).- Which chat platform their rooms are bridged to, if any.@@ -182,9 +182,9 @@ properly, and the person will hit the gaps later rather than sooner.again there. Get this one right the first time.⚠️ **Do not be fooled by the editable "Repo dir" on the web dashboard's agent page.**- That field exists, and changing it changes nothing about where the agent runs — it only- feeds the ready-to-paste command the dashboard shows for starting a session by hand. Edit- it and you have simply made the dashboard disagree with reality. The same goes for setting+ That field exists, and changing it changes nothing about where the agent runs. Switch+ Console only uses it as a hint when it looks for agents it can load from a remote host.+ Edit it and you have simply made the dashboard disagree with reality. The same goes for setting`repo_dir` through the agent-update tool.2. **Give it its expertise through its Agent instructions.** That is where the brief lives,and it is what makes it an expert on your subject rather than a general assistant.diff --git a/core/switch_core/providers/registry.py b/core/switch_core/providers/registry.pyindex 672b4cc93..9ec21faae 100644--- a/core/switch_core/providers/registry.py+++ b/core/switch_core/providers/registry.py@@ -30,25 +30,6 @@ class UnknownProvider(ValueError):pass-@dataclass(frozen=True)-class TerminalStart:- """The operator starts a session by running `command` in the agent's- directory; `{prompt}` in it stands for the connect prompt."""-- command: str---@dataclass(frozen=True)-class ConsoleStart:- """The operator starts a session from Switch Console. `runtime` names the- runtime to enable in the agent's advanced settings there and- `sign_in_command` the command that signs the CLI in; None when there is- nothing to say."""-- runtime: str | None- sign_in_command: str | None--@dataclass(frozen=True)class AgentProvider:id: str@@ -57,6 +38,11 @@ class AgentProvider:label: str"""How people see it named."""+ sign_in_command: str+ """What its owner runs, on the machine an agent runs on, to sign the CLI+ in: Switch Console's `loginCommand` for the provider, which a test holds+ this to."""+known_agent_type: str = """""The known-agent spec its agents register through, stored on each agentas `known_agent_type`. Defaults to `id`."""@@ -71,12 +57,6 @@ class AgentProvider:tools: tuple[ToolSpec, ...] = ()"""The built-in tools its agents register."""- session_start: TerminalStart | ConsoleStart = ConsoleStart(- runtime=None, sign_in_command=None- )- """How the operator starts a session when the agent is addressed with none- running."""-def __post_init__(self) -> None:if not self.known_agent_type:object.__setattr__(self, "known_agent_type", self.id)@@ -85,11 +65,10 @@ class AgentProvider:AGENT_PROVIDERS: tuple[AgentProvider, ...] = (- # Claude Code's known agent (`ClaudeCodeKnownAgent`) builds its own launch- # command, so `session_start` is not read for it.AgentProvider(id="claude",label="Claude Code",+ sign_in_command="claude auth login",known_agent_type="claude-code",advanced_fields=CLAUDE_FIELDS,tools=(@@ -112,6 +91,7 @@ AGENT_PROVIDERS: tuple[AgentProvider, ...] = (AgentProvider(id="codex",label="Codex",+ sign_in_command="codex login",connector_type="Codex CLI",advanced_fields=CODEX_FIELDS,tools=(@@ -119,11 +99,11 @@ AGENT_PROVIDERS: tuple[AgentProvider, ...] = (ToolSpec(name="ApplyPatch", description="Applies patches to files"),ToolSpec(name="Read", description="Reads file contents"),),- session_start=TerminalStart(command='codex "{prompt}"'),),AgentProvider(id="opencode",label="OpenCode",+ sign_in_command="opencode auth login",connector_type="OpenCode CLI",advanced_fields=OPENCODE_FIELDS,tools=(@@ -137,13 +117,11 @@ AGENT_PROVIDERS: tuple[AgentProvider, ...] = (ToolSpec(name="WebFetch", description="Fetches web pages"),ToolSpec(name="Task", description="Spawns a sub-agent"),),- # OpenCode reads its first positional argument as the project- # directory, so the prompt has to go through `--prompt`.- session_start=TerminalStart(command='opencode --prompt "{prompt}"'),),AgentProvider(id="antigravity",label="Antigravity",+ sign_in_command="antigravity-acp --login",connector_type="Antigravity CLI",tools=(ToolSpec(name="run_command", description="Executes shell commands"),@@ -162,11 +140,11 @@ AGENT_PROVIDERS: tuple[AgentProvider, ...] = (ToolSpec(name="call_mcp_tool", description="Calls a tool on an MCP server"),ToolSpec(name="invoke_subagent", description="Delegates to a subagent"),),- session_start=ConsoleStart(runtime="Antigravity CLI", sign_in_command="agy"),),AgentProvider(id="cursor",label="Cursor CLI",+ sign_in_command="agent login",tools=(ToolSpec(name="shell", description="Executes shell commands"),ToolSpec(name="read_file", description="Reads file contents"),@@ -175,7 +153,6 @@ AGENT_PROVIDERS: tuple[AgentProvider, ...] = (ToolSpec(name="grep", description="Searches file contents"),ToolSpec(name="glob", description="Finds files by pattern"),),- session_start=ConsoleStart(runtime="Cursor CLI ACP", sign_in_command="agent"),),)diff --git a/core/switch_core/template_guide.py b/core/switch_core/template_guide.pyindex e9aadd053..66a464382 100644--- a/core/switch_core/template_guide.py+++ b/core/switch_core/template_guide.py@@ -51,7 +51,7 @@ A condition reads one param: "{param}" (true when it has a value) or## An agent (type: agent)instructions: text # REQUIRED. The agent's brief.- provider: claude | codex | opencode | "{param}" # REQUIRED+ provider: claude | codex | opencode | antigravity | cursor | "{param}" # REQUIREDmachine: machine name or id | "{param}" # REQUIRED: where it runsdirectory: path | "{param}" # REQUIREDname: identifier # optional; else derived from display_name.diff --git a/core/switch_core/trust/client.py b/core/switch_core/trust/client.pyindex 1188e73ea..1a5e8fc7a 100644--- a/core/switch_core/trust/client.py+++ b/core/switch_core/trust/client.py@@ -283,13 +283,13 @@ class HttpTrustClient:def trust_annotation(result: TrustCheckResult) -> str | None:- """A short, non-blocking note to append to a message's body — the- in-chat indicator for ALERTED and a degraded/errored check. Reuses the- message's own body rather than a separate notice or a platform reaction:- `mark_activity` (the existing "working"/"queued" badge) is scoped to a+ """A short, non-blocking note — the in-chat indicator for ALERTED and a+ degraded/errored check. A person's message carries it appended to its own+ body; an agent's send gets it as a separate notice threaded under the send+ (`AgentCore._post_trust_alert_notice`). Text rather than a platform+ reaction: `mark_activity` (the "working"/"queued" badge) is scoped to aspecific agent's identity on platforms that track per-agent reactions, and- a Switch Trust verdict belongs to no agent — retrofitting it would mean a- new cross-adapter primitive, out of proportion to a quiet heads-up.+ a Switch Trust verdict belongs to no agent.`None` for every other outcome, including BLOCKED (handled separately) andREDACTED (the redaction itself is the signal)."""if result.outcome == "alerted":diff --git a/core/tests/switch_core/bridges/agent/test_command_targeting.py b/core/tests/switch_core/bridges/agent/test_command_targeting.pynew file mode 100644index 000000000..c36f73439--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_command_targeting.py@@ -0,0 +1,112 @@+from __future__ import annotations++import re+from contextlib import asynccontextmanager+from types import SimpleNamespace+from typing import Any++import switch_core.bridges.agent.commands as commands+++@asynccontextmanager+async def _session_factory(): # type: ignore[no-untyped-def]+ yield object()+++def _addr_client(name: str, held_role: str | None = None) -> SimpleNamespace:+ """Fake client exposing the two predicates the targeting helpers call."""++ def _tag(token: str, text: str) -> bool:+ return (+ re.search(re.escape(f"@{token}") + r"(?![A-Za-z0-9._-])", text) is not None+ )++ def _args_tag_my_name(text: str) -> bool:+ return _tag(name, text)++ async def _text_tags_my_role(_session: Any, text: str, _room_id: str) -> bool:+ return held_role is not None and _tag(held_role, text)++ async def _text_tags_my_alias(_session: Any, _text: str, _room_id: str) -> bool:+ return False++ return SimpleNamespace(+ agent=SimpleNamespace(name=name),+ session_factory=_session_factory,+ _args_tag_my_name=_args_tag_my_name,+ _text_tags_my_role=_text_tags_my_role,+ _text_tags_my_alias=_text_tags_my_alias,+ )+++class TestResetTargeting:+ """`!reset` requires an explicit target so a bare `!reset` never resets the+ whole room; `!reset-all-agents` is the explicit fan-out to everyone."""++ async def test_bare_reset_addresses_no_one(self) -> None:+ client = _addr_client("alice")+ assert (+ await commands._addressed_by_required_first_mention(client, "", "r")+ is False+ )++ async def test_reset_first_token_addresses_named_agent(self) -> None:+ assert (+ await commands._addressed_by_required_first_mention(+ _addr_client("alice"), "@alice", "r"+ )+ is True+ )+ assert (+ await commands._addressed_by_required_first_mention(+ _addr_client("bob"), "@alice", "r"+ )+ is False+ )++ async def test_reset_first_token_role_addresses_holder(self) -> None:+ client = _addr_client("bob", held_role="manager")+ assert (+ await commands._addressed_by_required_first_mention(client, "@manager", "r")+ is True+ )++ async def test_reset_all_addresses_everyone(self) -> None:+ # No args and irrelevant args alike always fan out to every agent.+ client = _addr_client("alice")+ assert await commands._addressed_everyone(client, "", "r") is True+ assert await commands._addressed_everyone(client, "@bob", "r") is True++ def test_control_command_pairs_are_registered(self) -> None:+ # Each control command has a target-required variant and an explicit+ # "-all-agents" fan-out variant.+ for one, allv in (+ ("reset", "reset-all-agents"),+ ("compact", "compact-all-agents"),+ ("interrupt", "interrupt-all-agents"),+ ):+ assert one in commands.COMMANDS_BY_NAME+ assert allv in commands.COMMANDS_BY_NAME+ assert (+ commands.COMMANDS_BY_NAME[one].addressed+ is commands._addressed_by_required_first_mention+ )+ assert (+ commands.COMMANDS_BY_NAME[allv].addressed+ is commands._addressed_everyone+ )+++class TestStripEmphasis:+ def test_strips_bold_around_mention(self) -> None:+ assert commands._mention_tokens("@*claude-code.test-cc.jdoe*") == [+ "claude-code.test-cc.jdoe"+ ]+ assert commands._mention_tokens("@**alice**") == ["alice"]++ def test_keeps_underscore_in_names(self) -> None:+ # "_" is a valid name char and must survive stripping.+ assert commands._mention_tokens("@cc_bug_fixing") == ["cc_bug_fixing"]++ def test_bold_second_token_still_parsed(self) -> None:+ assert commands._mention_tokens("@*alice* @*manager*") == ["alice", "manager"]diff --git a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py b/core/tests/switch_core/bridges/agent/test_commands_run_cmd.pydeleted file mode 100644index 8727edcef..000000000--- a/core/tests/switch_core/bridges/agent/test_commands_run_cmd.py+++ /dev/null@@ -1,294 +0,0 @@-from __future__ import annotations--import re-from contextlib import asynccontextmanager-from types import SimpleNamespace-from typing import Any--import pytest--import switch_core.bridges.agent.commands as commands-from switch_core.bridges.agent.commands import (- _addressed_by_first_mention,- _cmd_run_cmd,- _role_arg,-)-from switch_core.events import CommandEvent---@asynccontextmanager-async def _session_factory(): # type: ignore[no-untyped-def]- yield object()---class TestRoleArg:- """The role to name in the output is the SECOND @token; the first targets- the agent (see _addressed_by_first_mention)."""-- def test_no_args_returns_none(self) -> None:- assert _role_arg("") is None-- def test_only_one_token_returns_none(self) -> None:- # A single token is the target (agent name or role), not a role-to-name.- assert _role_arg("@cc-bug-fixing") is None- assert _role_arg("@manager") is None-- def test_second_token_is_the_role(self) -> None:- assert _role_arg("@cc-bug-fixing @manager") == "manager"- assert _role_arg("@CC-Bug-Fixing @worker") == "worker"---def _addr_client(name: str, held_role: str | None = None) -> SimpleNamespace:- """Fake client exposing the two predicates the targeting helpers call."""-- def _tag(token: str, text: str) -> bool:- return (- re.search(re.escape(f"@{token}") + r"(?![A-Za-z0-9._-])", text) is not None- )-- def _args_tag_my_name(text: str) -> bool:- return _tag(name, text)-- async def _text_tags_my_role(_session: Any, text: str, _room_id: str) -> bool:- return held_role is not None and _tag(held_role, text)-- async def _text_tags_my_alias(_session: Any, _text: str, _room_id: str) -> bool:- return False-- return SimpleNamespace(- agent=SimpleNamespace(name=name),- session_factory=_session_factory,- _args_tag_my_name=_args_tag_my_name,- _text_tags_my_role=_text_tags_my_role,- _text_tags_my_alias=_text_tags_my_alias,- )---class TestRunCmdTargeting:- """`_addressed_by_first_mention`: only the first @token addresses an agent;- the second (the role to name in the output) does NOT pull in role holders."""-- async def test_first_token_name_addresses(self) -> None:- client = _addr_client("alice")- assert await _addressed_by_first_mention(client, "@alice @manager", "r") is True-- async def test_second_token_role_does_not_address(self) -> None:- # bob holds manager, but manager is only the SECOND token → not addressed.- client = _addr_client("bob", held_role="manager")- assert (- await _addressed_by_first_mention(client, "@alice @manager", "r") is False- )-- async def test_first_token_role_addresses_holder(self) -> None:- # `!run-cmd @manager` → the manager holder is addressed.- client = _addr_client("bob", held_role="manager")- assert await _addressed_by_first_mention(client, "@manager", "r") is True-- async def test_no_tokens_addresses_everyone(self) -> None:- client = _addr_client("alice")- assert await _addressed_by_first_mention(client, "", "r") is True-- async def test_other_agent_first_token_not_addressed(self) -> None:- client = _addr_client("alice")- assert await _addressed_by_first_mention(client, "@bob", "r") is False-- async def test_bold_mention_addresses_named_agent_only(self) -> None:- # A bolded mention arrives as "@*alice*" (Slack mrkdwn). Emphasis markers- # must be stripped so it still targets exactly alice — not everyone.- assert (- await _addressed_by_first_mention(_addr_client("alice"), "@*alice*", "r")- is True- )- assert (- await _addressed_by_first_mention(_addr_client("bob"), "@*alice*", "r")- is False- )---class TestResetTargeting:- """`!reset` requires an explicit target so a bare `!reset` never resets the- whole room; `!reset-all-agents` is the explicit fan-out to everyone."""-- async def test_bare_reset_addresses_no_one(self) -> None:- client = _addr_client("alice")- assert (- await commands._addressed_by_required_first_mention(client, "", "r")- is False- )-- async def test_reset_first_token_addresses_named_agent(self) -> None:- assert (- await commands._addressed_by_required_first_mention(- _addr_client("alice"), "@alice", "r"- )- is True- )- assert (- await commands._addressed_by_required_first_mention(- _addr_client("bob"), "@alice", "r"- )- is False- )-- async def test_reset_first_token_role_addresses_holder(self) -> None:- client = _addr_client("bob", held_role="manager")- assert (- await commands._addressed_by_required_first_mention(client, "@manager", "r")- is True- )-- async def test_reset_all_addresses_everyone(self) -> None:- # No args and irrelevant args alike always fan out to every agent.- client = _addr_client("alice")- assert await commands._addressed_everyone(client, "", "r") is True- assert await commands._addressed_everyone(client, "@bob", "r") is True-- def test_control_command_pairs_are_registered(self) -> None:- # Each control command has a target-required variant and an explicit- # "-all-agents" fan-out variant.- for one, allv in (- ("reset", "reset-all-agents"),- ("compact", "compact-all-agents"),- ("interrupt", "interrupt-all-agents"),- ):- assert one in commands.COMMANDS_BY_NAME- assert allv in commands.COMMANDS_BY_NAME- assert (- commands.COMMANDS_BY_NAME[one].addressed- is commands._addressed_by_required_first_mention- )- assert (- commands.COMMANDS_BY_NAME[allv].addressed- is commands._addressed_everyone- )---class TestStripEmphasis:- def test_strips_bold_around_mention(self) -> None:- assert commands._mention_tokens("@*claude-code.test-cc.jdoe*") == [- "claude-code.test-cc.jdoe"- ]- assert commands._mention_tokens("@**alice**") == ["alice"]-- def test_keeps_underscore_in_names(self) -> None:- # "_" is a valid name char and must survive stripping.- assert commands._mention_tokens("@cc_bug_fixing") == ["cc_bug_fixing"]-- def test_bold_second_token_role_still_parsed(self) -> None:- assert _role_arg("@*alice* @*manager*") == "manager"---def _event(args: str) -> CommandEvent:- return CommandEvent(- type="command",- room_id="!m:switch.local",- command="run-cmd",- args=args,- user_id="u1",- user_name="louisa",- )---def _fake_client(*, role_exists: bool) -> SimpleNamespace:- sent: list[str] = []-- async def _resolve_room_meta(_transport_room_id: str): # type: ignore[no-untyped-def]- return SimpleNamespace(room_id="room-1", name="Feature Room", bridge_id=None)-- async def _agent_get(_session, _agent_id): # type: ignore[no-untyped-def]- return None # fall back to client.agent-- async def _get_role(_session, _room_id, name): # type: ignore[no-untyped-def]- return SimpleNamespace(name=name) if role_exists else None-- async def _send_message(_room_id, body, **_kw): # type: ignore[no-untyped-def]- sent.append(body)-- async def _owner_handle_in(_session, _agent, _bridge_id): # type: ignore[no-untyped-def]- # No linked owner: these cover the connect command, not the mention.- return None-- client = SimpleNamespace(- agent=SimpleNamespace(id="a1", name="cc-bug-fixing"),- session_factory=_session_factory,- _resolve_room_meta=_resolve_room_meta,- _agent_store=SimpleNamespace(get=_agent_get),- _room_role_store=SimpleNamespace(get_role=_get_role),- send_message=_send_message,- reply_command=_send_message,- owner_handle_in=_owner_handle_in,- sent=sent,- )- return client---def _patch_known_agent(monkeypatch: pytest.MonkeyPatch) -> None:- class _Spec:- @staticmethod- def start_session_instructions(- _options: Any,- _agent: Any,- room_name: str,- _owner_handle: str | None,- assume_role: str | None = None,- ) -> str:- prompt = f"connect to switch room {room_name}"- if assume_role:- prompt += f" and assume the role {assume_role}"- return f'claude "{prompt}"'-- def _known_agent_for(_agent: Any) -> tuple[Any, Any]:- return (_Spec, object())-- monkeypatch.setattr(commands, "known_agent_for", _known_agent_for)---class TestRunCmdRolePrompt:- async def test_role_folded_into_prompt_when_it_exists(- self, monkeypatch: pytest.MonkeyPatch- ) -> None:- _patch_known_agent(monkeypatch)- client = _fake_client(role_exists=True)- await _cmd_run_cmd(- client,- SimpleNamespace(room_id="!m"),- _event("@cc-bug-fixing @manager"),- False,- )-- assert len(client.sent) == 1- msg = client.sent[0]- # The role is part of the claude prompt itself, not a trailing note.- assert (- 'claude "connect to switch room Feature Room and assume the role manager"'- in msg- )- assert "⚠️" not in msg-- async def test_warns_and_omits_when_role_missing(- self, monkeypatch: pytest.MonkeyPatch- ) -> None:- _patch_known_agent(monkeypatch)- client = _fake_client(role_exists=False)- await _cmd_run_cmd(- client,- SimpleNamespace(room_id="!m"),- _event("@cc-bug-fixing @ghost"),- False,- )-- msg = client.sent[0]- # Unknown role is left out of the prompt and flagged.- assert "assume the role" not in msg- assert "no role named **ghost**" in msg-- async def test_no_role_arg_plain_prompt(- self, monkeypatch: pytest.MonkeyPatch- ) -> None:- _patch_known_agent(monkeypatch)- client = _fake_client(role_exists=True)- await _cmd_run_cmd(- client, SimpleNamespace(room_id="!m"), _event("@cc-bug-fixing"), False- )-- assert client.sent == ['claude "connect to switch room Feature Room"']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.pyindex 0b02867a7..7f8c8aa11 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@@ -163,8 +163,8 @@ def _indexed_tools(skill: Path) -> list[str]:One tool per bullet, opening with the backticked name. Read from the bodyrather than the frontmatter: the `description:` is always-resident context- on the hosts that load it as a skill (and Codex truncates it to fit a- budget), so it carries a trigger rather than an inventory.+ on a host that loads it as a skill file, so it carries a trigger rather+ than an inventory.Every bullet in the section must parse. A tool silently dropping outbecause someone bolded it, indented it, or folded two onto one line is thediff --git a/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py b/core/tests/switch_core/bridges/collaboration/test_discord_chunking.pyindex e4af10d00..bf4a5512e 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_chunking.py@@ -103,19 +103,20 @@ def test_round_trips_at_a_range_of_sizes(size: int) -> None:assert _rejoin(chunks) == body-def test_help_output_now_fits() -> None:+def test_help_shaped_output_over_the_cap_splits() -> None:# The concrete regression: `!help` / `/help` renders every command and# overshot Discord's cap, so the send was rejected and the user saw- # nothing at all.+ # nothing at all. Today's list fits in one message, so the command lines+ # are repeated to keep a help-shaped body over the cap.lines = ["**Available commands:**"]for command in COMMANDS:if command.hidden:continuelines.append(f"- `!{command.name}` — {command.description}")- body = "\n".join(lines)+ body = "\n".join(lines + lines[1:])assert len(body) > MAX_MESSAGEchunks = chunk_message(body)- assert len(chunks) == 2+ assert len(chunks) >= 2assert all(len(c) <= MAX_MESSAGE for c in chunks)assert _rejoin(chunks) == bodydiff --git a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.pyindex 147928ca0..e2c41e33d 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_slash_commands.py@@ -305,8 +305,14 @@ def test_at_prefix_is_optional_and_never_doubled() -> None:assert reassemble_args(spec, {"agent": " @worker ", "alias": "w "}) == expected+_TWO_OPTIONAL = (+ CommandArg("agent", "An agent", required=False),+ CommandArg("role", "A role for that agent", required=False),+)++def test_omitted_trailing_optional_is_dropped() -> None:- spec = COMMANDS_BY_NAME["run-cmd"].args_spec+ spec = _TWO_OPTIONALassert reassemble_args(spec, {"agent": "worker", "role": None}) == "@worker"assert reassemble_args(spec, {"agent": None, "role": None}) == ""@@ -314,8 +320,8 @@ def test_omitted_trailing_optional_is_dropped() -> None:def test_value_after_omitted_optional_is_rejected() -> None:# Discord submits options by name and allows role-without-agent, but the# positional form cannot express it: `@manager` would land in the agent- # slot and run-cmd would answer for the wrong target.- spec = COMMANDS_BY_NAME["run-cmd"].args_spec+ # slot and the command would act on the wrong target.+ spec = _TWO_OPTIONALwith pytest.raises(SlashArgError) as excinfo:reassemble_args(spec, {"agent": None, "role": "manager"})assert "agent" in str(excinfo.value)@@ -442,7 +448,7 @@ def test_bad_arguments_rejected_ephemerally_without_dispatch() -> None:commands = _capture_commands(adapter)interaction = _FakeInteraction(_FakeChannel())- _invoke(adapter, interaction, "run-cmd", agent=None, role="manager")+ _invoke(adapter, interaction, "set-alias", agent="worker", alias=None)# Refused before anything is dispatched, and privately: it is the# invoker's typo, not something the whole channel needs to watch fail.diff --git a/core/tests/switch_core/clients/test_command_consumer.py b/core/tests/switch_core/clients/test_command_consumer.pyindex 964692689..f9f394f4c 100644--- a/core/tests/switch_core/clients/test_command_consumer.py+++ b/core/tests/switch_core/clients/test_command_consumer.py@@ -415,9 +415,9 @@ class TestAdminCommandDispatch:assert sent[0]["body"].startswith("**Available commands:**")async def test_agent_owned_command_is_ignored(self) -> None:- # run-cmd is agent-owned — the admin client must not respond to it.+ # agents-greet is agent-owned — the admin client must not respond to it.host, sent = _command_host()- await dispatch_admin_command(host, _room(), _cmd_event("run-cmd", "@agent"))+ await dispatch_admin_command(host, _room(), _cmd_event("agents-greet"))assert sent == []async def test_unknown_command_gets_a_notice(self) -> None:diff --git a/core/tests/switch_core/db/stores/test_agent_session_store.py b/core/tests/switch_core/db/stores/test_agent_session_store.pyindex 1e607621e..3274b3b64 100644--- a/core/tests/switch_core/db/stores/test_agent_session_store.py+++ b/core/tests/switch_core/db/stores/test_agent_session_store.py@@ -274,7 +274,7 @@ class TestHasRoomBinding:self, session_factory: async_sessionmaker[AsyncSession]) -> None:"""A bound-but-not-live session (stale heartbeat) still counts — this is- exactly the dev-channels-flag-missing case the warning targets."""+ exactly the "connected but not live" case the reply describes."""store = AgentSessionStore()async with session_factory() as session:agent = await _make_agent(session, "stale-bound")diff --git a/core/tests/switch_core/delivery/test_mention_routing.py b/core/tests/switch_core/delivery/test_mention_routing.pyindex 510dc9b0b..43d2b76f6 100644--- a/core/tests/switch_core/delivery/test_mention_routing.py+++ b/core/tests/switch_core/delivery/test_mention_routing.py@@ -126,7 +126,7 @@ class TestPrefixCollision:assert _is_mentioned("cc-bug-fixing-2", "@cc-bug-fixing-2 please run") is Trueasync def test_command_does_not_address_prefix_name(self) -> None:- # `!run-cmd @cc-bug-fixing-2` must not trigger cc-bug-fixing.+ # `!reset @cc-bug-fixing-2` must not trigger cc-bug-fixing.assert await _command_addresses("cc-bug-fixing", "@cc-bug-fixing-2") is Falseasync def test_command_addresses_exact_name(self) -> None:@@ -356,7 +356,7 @@ class TestAliasMentionRouting:class TestCommandRoleTargeting:- """`!run-cmd @<role>` / `!reset @<role>` target the role's holder.+ """`!reset @<role>` / `!interrupt @<role>` target the role's holder.on_command lets an agent through when the command args tag a role itholds; that gate is `_text_tags_my_role(args, room_id)`.@@ -399,7 +399,7 @@ def _unavailable_client(`live_rooms`: room ids where the agent currently has a live, room-boundsession (live_connected_rooms). `role_here`: whether the agent holds a liverole in the room it was addressed from (agent_room_role). `connection_model`- drives the dev-channels-warning branch; `bound_here` is what+ drives the connected-but-not-live branch; `bound_here` is whathas_room_binding returns for the addressed room. `watching` is theroom-agnostic heartbeat an un-migrated connector keeps up, and `connected`/ `spawns` are the connection arm (see `_no_connections`).@@ -489,8 +489,8 @@ class TestUnavailableHereReply:async def test_no_role_lists_other_sessions(self, db: AsyncSession) -> None:# No role here, but the agent has live sessions in two other rooms.- # Defers to the known-agent reply (paste-ready connect command) with- # the other rooms threaded in, rather than the role-flavoured wording.+ # Defers to the Switch Console reply with the other rooms named,+ # rather than the role-flavoured wording.client = _unavailable_client(live_rooms=["room-B", "room-C"], role_here=False)msg = await AgentRecipient._reply_when_unavailable_here(client, db, client.agent, _here(), "asker"@@ -542,7 +542,8 @@ class TestConnectedNotLive:async def test_passive_never_says_connected_not_live(self, db: AsyncSession) -> None:- # session_passive has no dev-channels flag; this branch must not apply.+ # A session_passive agent is never live in real time, so "connected+ # but not live" must not apply.client = _unavailable_client(live_rooms=[],role_here=False,diff --git a/core/tests/switch_core/delivery/test_no_session_reply_threading.py b/core/tests/switch_core/delivery/test_no_session_reply_threading.pyindex f05b618ac..64dbf40f9 100644--- a/core/tests/switch_core/delivery/test_no_session_reply_threading.py+++ b/core/tests/switch_core/delivery/test_no_session_reply_threading.py@@ -177,7 +177,8 @@ async def test_no_session_reply_does_not_double_tag_the_asker() -> None:send_message = _Recorder()await _deliver(_fake_self(- send_message, unavailable_reply="@louisa\n\nmy operator should run …"+ send_message,+ unavailable_reply="@louisa — I'm not online in this room. Open Switch Console …",),_event(thread_id=None),)@@ -195,7 +196,8 @@ async def test_no_session_reply_tags_distinct_asker_and_operator() -> None:send_message = _Recorder()await _deliver(_fake_self(- send_message, unavailable_reply="@operator\n\nmy operator should run …"+ send_message,+ unavailable_reply="@operator — I'm not online in this room. Open Switch Console …",),_event(thread_id=None),)@@ -249,9 +251,9 @@ class TestTerminalReplyThreadsOffTheTrigger:"""Where an "I can't help right now" reply lands (CHOO-2344).Unlike the starting-session notice, nothing follows it — it IS the answer.- And it is bulky: an owner mention plus a paste-ready connect command, for- something only one person can act on. At the conversation root that is a- wall of text dropped into the channel, so it threads off the message that+ And it is addressed to one person: an owner mention and an instruction+ only they can act on. At the conversation root that is noise dropped into+ the channel for everyone else, so it threads off the message thattriggered it instead."""diff --git a/core/tests/switch_core/delivery/test_offline_owner_reply.py b/core/tests/switch_core/delivery/test_offline_owner_reply.pyindex 4bce42283..a149c0d8d 100644--- a/core/tests/switch_core/delivery/test_offline_owner_reply.py+++ b/core/tests/switch_core/delivery/test_offline_owner_reply.py@@ -2,7 +2,14 @@ from __future__ import annotationsfrom types import SimpleNamespace-from switch_core.delivery.recipient import AgentRecipient, _offline_owner_message+from switch_core.delivery.recipient import (+ _CONNECTED_NOT_LIVE_MESSAGE,+ _UNAVAILABLE_MESSAGES,+ AgentRecipient,+ _offline_owner_message,+ _passive_message,+ _start_from_console_message,+)"""The reply an auto_session agent gives when it is addressed and nothing isthere to bring it online (CHOO-2344).@@ -66,7 +73,7 @@ async def _reply(class TestOfflineOwnerMessage:def test_owner_leads_and_is_the_one_asked(self) -> None:- msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude …")+ msg = _offline_owner_message("ownerhandle", "louisa")# The owner is first, because they are the only person who can act.assert msg.startswith("@ownerhandle — ")assert "Open Switch Console" in msg@@ -76,32 +83,30 @@ class TestOfflineOwnerMessage:def test_never_says_session(self) -> None:# Which process is attached to which room is Switch's business, not# something to put in front of a reader in a chat channel.- msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude …")+ msg = _offline_owner_message("ownerhandle", "louisa")assert "session" not in msg.lower()assert "I'm not online in this room" in msgdef test_unmentionable_owner_still_names_who_must_act(self) -> None:# No claimed account on this platform → nobody to tag. The message must# not read as something the room at large can resolve.- msg = _offline_owner_message(None, "louisa", "cd /x && claude …")+ msg = _offline_owner_message(None, "louisa")assert not msg.startswith("@ownerhandle")assert "**My owner needs to open Switch Console**" in msgassert "@louisa needs me" in msgassert "session" not in msg.lower()- def test_command_is_offered_as_the_alternative(self) -> None:- msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude go")- assert "```\ncd /x && claude go\n```" in msg-def test_owner_asking_their_own_agent_is_not_named_twice(self) -> None:# The common case. "@louisa — … and @louisa needs me" reads as a stutter.- msg = _offline_owner_message("louisa", "louisa", "cd /x && claude …")+ msg = _offline_owner_message("louisa", "louisa")assert msg.count("@louisa") == 1assert "needs me" not in msgassert msg.startswith("@louisa — I'm not online in this room. ")- def test_no_command_leaves_no_empty_code_block(self) -> None:- msg = _offline_owner_message("ownerhandle", "louisa", None)+ def test_offers_no_terminal_command(self) -> None:+ # A CLI started by hand gets none of the Switch tools, so the reply+ # must not suggest one.+ msg = _offline_owner_message("ownerhandle", "louisa")assert "```" not in msgassert "Open Switch Console" in msg@@ -112,12 +117,10 @@ class TestUnavailableReplyRouting:assert msg.startswith("@ownerhandle — ")assert "session" not in msg.lower()- async def test_the_command_names_the_agent(self) -> None:- # A directory can hold several provisioned agents, in which case the- # started session is asked which one it is.+ async def test_no_terminal_command_even_with_a_working_directory(self) -> None:msg = await _reply(_client("ownerhandle"), _auto_session_claude_agent())- assert "you are cc-bug-fixing" in msg- assert "cd /srv/work && claude " in msg+ assert "```" not in msg+ assert "claude " not in msgasync def test_a_live_session_elsewhere_still_wins(self) -> None:# Somewhere the asker can go right now beats asking the owner to start@@ -128,9 +131,10 @@ class TestUnavailableReplyRouting:other_room_names=["Hub"],)assert "**Hub**" in msg- assert "Open Switch Console" not in msg+ assert "you can ask me there" in msg+ assert "```" not in msg- async def test_session_addressable_is_untouched(self) -> None:+ async def test_session_addressable_points_at_switch_console(self) -> None:agent = _agent("session_addressable",{@@ -140,11 +144,192 @@ class TestUnavailableReplyRouting:)msg = await _reply(_client("ownerhandle"), agent)assert "I don't have a session connected to this room." in msg- assert "Open Switch Console" not in msg+ assert "in Switch Console" in msg+ assert "```" not in msgasync def test_auto_session_without_a_known_agent_still_answers(self) -> None:- # Registered via `register-other`: no connect command exists, but the- # owner still has to open the app.+ # Registered via `register-other`: no known-agent spec, but the owner+ # still has to open the app.msg = await _reply(_client("ownerhandle"), _agent("auto_session", {}))assert "Open Switch Console" in msgassert "```" not in msg++ async def test_a_passive_agent_is_not_told_it_has_no_session(self) -> None:+ # A passive agent is never live in real time, even while a session is+ # open and working, so "I don't have a session" would be wrong.+ agent = _agent(+ "session_passive",+ {+ "known_agent_type": "claude-code",+ "known_agent_options": {"channels_enabled": False},+ },+ )+ for kwargs in ({}, {"other_room_names": ["Hub"]}):+ msg = await _reply(_client("ownerhandle"), agent, **kwargs)+ assert "I read room messages asynchronously" in msg+ assert "I don't have a session" not in msg+ # The owner is the only one who can trigger it, so they are+ # mentioned and notified.+ assert "@ownerhandle has to trigger me" in msg++ async def test_a_passive_agent_without_a_known_agent_names_its_owner(self) -> None:+ # Registered via `register-other`: no known-agent spec, same reply.+ msg = await _reply(_client("ownerhandle"), _agent("session_passive", {}))+ assert "I read room messages asynchronously" in msg+ assert "@ownerhandle has to trigger me" in msg++ async def test_a_session_here_that_is_not_live_points_at_switch_console(+ self,+ ) -> None:+ agent = _agent(+ "session_addressable",+ {+ "known_agent_type": "claude-code",+ "known_agent_options": {"repo_dir": "/srv/work"},+ },+ )+ msg = await _reply(_client("ownerhandle"), agent, connected_not_live=True)+ assert "isn't reporting as live" in msg+ assert "@ownerhandle can restart it" in msg+ assert "in Switch Console" in msg+ assert "```" not in msg++ async def test_every_provider_names_the_room_and_its_own_sign_in(self) -> None:+ sign_in = {+ "claude-code": "claude auth login",+ "codex": "codex login",+ "opencode": "opencode auth login",+ "antigravity": "antigravity-acp --login",+ "cursor": "agent login",+ }+ for agent_type, command in sign_in.items():+ agent = _agent(+ "session_addressable",+ {"known_agent_type": agent_type, "known_agent_options": {}},+ )+ msg = await _reply(_client("ownerhandle"), agent)+ assert "I don't have a session connected to this room." in msg, agent_type+ assert "connected to **Some Room**" in msg, agent_type+ assert "in Switch Console" in msg, agent_type+ assert f"`{command}`" in msg, agent_type+ assert "```" not in msg, agent_type++ async def test_an_always_on_known_agent_says_its_connector_is_down(self) -> None:+ # `connection_model` can be edited through the gateway. An always_on+ # agent is offline because its connector is, so it is not told to+ # start a session from Switch Console, whatever spec it registered+ # through.+ for agent_type in ("claude-code", "codex", "cursor"):+ agent = _agent(+ "always_on",+ {"known_agent_type": agent_type, "known_agent_options": {}},+ )+ msg = await _reply(_client("ownerhandle"), agent)+ assert msg == _UNAVAILABLE_MESSAGES["always_on"], agent_type++ async def test_an_always_on_agent_with_sessions_elsewhere_keeps_its_text(+ self,+ ) -> None:+ agent = _agent(+ "always_on",+ {"known_agent_type": "codex", "known_agent_options": {}},+ )+ msg = await _reply(_client("ownerhandle"), agent, other_room_names=["Hub"])+ assert msg == _UNAVAILABLE_MESSAGES["always_on"]++ async def test_an_agent_with_no_known_spec_gets_the_static_text(self) -> None:+ for model in ("always_on", "session_addressable"):+ msg = await _reply(_client("ownerhandle"), _agent(model, {}))+ assert msg == _UNAVAILABLE_MESSAGES[model], model++ async def test_an_agent_with_no_known_spec_bound_here_is_told_to_restart(+ self,+ ) -> None:+ msg = await _reply(+ _client("ownerhandle"),+ _agent("session_addressable", {}),+ connected_not_live=True,+ )+ assert msg == _CONNECTED_NOT_LIVE_MESSAGE++ async def test_an_unknown_connection_model_is_treated_as_passive(self) -> None:+ msg = await _reply(_client("ownerhandle"), _agent("not_a_model", {}))+ assert "I read room messages asynchronously" in msg+++class TestPassiveMessage:+ def test_names_the_owner_so_they_are_notified(self) -> None:+ msg = _passive_message("ownerhandle", "louisa")+ assert "@ownerhandle has to trigger me" in msg++ def test_the_owner_asking_is_called_you(self) -> None:+ msg = _passive_message("louisa", "louisa")+ assert "you have to trigger me" in msg+ assert "@louisa" not in msg++ def test_an_unlinked_owner_is_named_without_a_mention(self) -> None:+ msg = _passive_message(None, "louisa")+ assert "my owner has to trigger me" in msg+ assert "@" not in msg+++class TestStartFromConsoleMessage:+ """The reply for a Console-run agent with sessions elsewhere, or a session+ here that is not live. It always points at Switch Console and never offers+ a terminal command, since a CLI started by hand gets none of the Switch+ tools."""++ @staticmethod+ def _msg(+ owner: str | None,+ asker: str,+ other_room_names: list[str] | None = None,+ connected_not_live: bool = False,+ ) -> str:+ return _start_from_console_message(+ "worker.test",+ "Payments",+ "agent login",+ owner,+ asker,+ other_room_names,+ connected_not_live,+ )++ def test_no_session_names_the_owner_room_and_sign_in(self) -> None:+ assert self._msg("cmcd", "louisa") == (+ "I don't have a session connected to this room. "+ "@cmcd can start one connected to **Payments** by opening "+ "**worker.test** in Switch Console. If Switch Console says I'm "+ "signed out, sign me in first with `agent login` on the machine I "+ "run on."+ )++ def test_the_owner_asking_is_called_you(self) -> None:+ msg = self._msg("cmcd", "cmcd")+ assert (+ "You can start one connected to **Payments** by opening "+ "**worker.test** in Switch Console." in msg+ )+ assert "@cmcd" not in msg++ def test_an_unlinked_owner_is_named_without_a_mention(self) -> None:+ msg = self._msg(None, "louisa")+ assert "My owner can start one" in msg+ assert "@" not in msg++ def test_sessions_elsewhere_are_offered_first(self) -> None:+ msg = self._msg("cmcd", "louisa", ["Hub", "Ops", "Triage"])+ assert (+ "I'm working in **Hub**, **Ops** and **Triage**, so you can ask me there."+ in msg+ )+ assert "Or @cmcd can start one connected to **Payments**" in msg+ assert "`agent login`" in msg+ assert "```" not in msg++ def test_a_session_here_that_is_not_live_asks_for_a_restart(self) -> None:+ msg = self._msg("cmcd", "cmcd", connected_not_live=True)+ assert "isn't reporting as live" in msg+ assert "You can restart it by opening **worker.test** in Switch Console." in msg+ assert "`agent login`" in msgdiff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.pyindex 49a87f7e8..781f52966 100644--- a/core/tests/switch_core/gateway/test_known_agents.py+++ b/core/tests/switch_core/gateway/test_known_agents.py@@ -28,19 +28,6 @@ def _agent(metadata: dict | None) -> SimpleNamespace:return SimpleNamespace(name="claude-code.test", metadata_=metadata)-def _agent_named(name: str) -> SimpleNamespace:- """An agent whose name does not contain "claude" — the Codex and OpenCode- suites assert a `claude` binary is never suggested, and the connect prompt- now carries the agent's own name."""- return SimpleNamespace(name=name, metadata_={})---def _identity(agent_name: str) -> str:- """The trailing clause the connect prompt carries so a session started in a- directory holding several agents knows which one it is."""- return f" — if you are asked which agent you are, you are {agent_name}"--class TestBuildProfileConnectionModel:def test_channels_enabled_defaults_to_session_addressable(self) -> None:profile = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=True))@@ -81,177 +68,6 @@ class TestBuildProfileCommandCapabilities:assert caps.interrupt == "session_dependent"-class TestStartSessionInstructions:- def test_channels_enabled_appends_dev_flag_after_prompt(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/Users/x/aq-switch")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- # The flag must come AFTER the prompt argument so claude treats the- # quoted text as the initial prompt, not as a value for the flag.- assert (- f'claude "connect to switch room hub{_identity("claude-code.test")}" '- "--dangerously-load-development-channels "- "plugin:switch-connector@switch-plugins"- ) in msg- assert "cd /Users/x/aq-switch" in msg-- def test_channels_disabled_passive_message_shape(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/srv/agent")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)- assert msg is not None- assert "--dangerously-load-development-channels" not in msg- # The connect prompt itself instructs a pull (passive sessions get no- # pushed events), and the message frames reading as asynchronous.- assert (- 'cd /srv/agent && claude "connect to switch room ops '- f'and pull the latest messages{_identity("claude-code.test")}"'- ) in msg- assert "asynchronously" in msg- # Real-time delivery requires an API-key / subscription Claude Code.- assert "Anthropic API key or subscription" in msg-- def test_channels_enabled_is_not_passive_shaped(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)- assert msg is not None- assert "pull the latest messages" not in msg- assert "Anthropic API key or subscription" not in msg-- def test_channels_disabled_auto_session_keeps_pull_based_message(self) -> None:- # A channels-off auto_session agent falls back to the pull-based- # onboarding message when no connector is watching — the onboarding- # command depends only on channels_enabled, not the connection model.- opts = ClaudeCodeOptions(- channels_enabled=False, auto_session=True, repo_dir="/srv/agent"- )- msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)- assert msg is not None- assert "--dangerously-load-development-channels" not in msg- assert (- 'cd /srv/agent && claude "connect to switch room ops '- f'and pull the latest messages{_identity("claude-code.test")}"'- ) in msg-- def test_connected_not_live_opening(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")- msg = CLAUDE.start_session_instructions(- opts, _agent({}), "ops", None, connected_not_live=True- )- assert msg is not None- # Acknowledges a connected-but-not-live session and steers to relaunch- # with live channels (the flag is in the command), rather than implying- # there is no session.- assert "isn't reporting as live" in msg- assert "I don't have a session connected to this room." not in msg- assert "--dangerously-load-development-channels" in msg-- def test_no_repo_dir_uses_placeholder(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir=None)- msg = CLAUDE.start_session_instructions(opts, _agent({}), "triage", None)- assert msg is not None- assert "cd <claude-dir>" in msg- # Still the channels flag because channels_enabled is True.- assert "--dangerously-load-development-channels" in msg- # No user-facing mention of the option name.- assert "repo_dir" not in msg-- def test_empty_string_repo_dir_normalised_to_none(self) -> None:- # The gateway edit form submits "" when the field is cleared.- opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="")- assert opts.repo_dir is None- msg = CLAUDE.start_session_instructions(opts, _agent({}), "triage", None)- assert msg is not None- assert "cd <claude-dir>" in msg-- def test_the_owner_is_prepended_as_an_at_mention(self) -> None:- # The handle is the owner's account on the platform this room is- # bridged to, resolved by the caller (CHOO-2137) — it used to be a- # single string configured on the agent, which could only ever be- # right on one platform.- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", "louisa")- assert msg is not None- assert msg.startswith("@louisa\n\n")-- def test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:- # Nobody to mention is not a reason to withhold the instructions.- opts = ClaudeCodeOptions(channels_enabled=True)- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert not msg.startswith("@")-- def test_passive_mentions_operator_inline(self) -> None:- # Passive message names the operator inline ("my operator @louisa")- # rather than as a leading prefix, so they still get pinged to pull.- opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", "louisa")- assert msg is not None- assert "my operator @louisa" in msg-- def test_passive_without_a_linked_owner_says_my_operator(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert "my operator has to trigger me" in msg- assert "@" not in msg-- def test_subagent_name_appends_agent_and_settings_flags(self) -> None:- opts = ClaudeCodeOptions(- channels_enabled=True,- repo_dir="/Users/x/repo",- subagent_name="seo-writer",- )- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- # --agent / --settings come after the quoted prompt and before the- # dev-channels flag; the settings path matches what the configure skill- # writes the subagent credentials to.- assert (- f'claude "connect to switch room hub{_identity("claude-code.test")}" '- "--agent seo-writer "- "--settings .claude/switch-subagents/seo-writer.settings.json "- "--dangerously-load-development-channels "- "plugin:switch-connector@switch-plugins"- ) in msg-- def test_subagent_flags_present_without_channels(self) -> None:- opts = ClaudeCodeOptions(- channels_enabled=False, repo_dir="/r", subagent_name="reviewer"- )- msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)- assert msg is not None- assert "--agent reviewer" in msg- assert "--settings .claude/switch-subagents/reviewer.settings.json" in msg- assert "--dangerously-load-development-channels" not in msg-- def test_no_subagent_name_omits_agent_flag(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/r")- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert "--agent" not in msg- assert "switch-subagents" not in msg-- def test_empty_string_subagent_name_normalised_to_none(self) -> None:- opts = ClaudeCodeOptions(channels_enabled=True, subagent_name="")- assert opts.subagent_name is None- msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert "--agent" not in msg-- def test_message_does_not_interpolate_room_name(self) -> None:- # We refer to "this room" in the lead-in rather than naming it, so the- # message reads the same regardless of where it's posted.- opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")- msg = CLAUDE.start_session_instructions(- opts, _agent({}), "Some Long Room Name", None- )- assert msg is not None- # The room name still appears once inside the quoted `connect to switch- # room ...` command — that's where the operator actually needs it.- assert msg.count("Some Long Room Name") == 1- assert "I don't have a session connected to this room." in msg--class TestCodexKnownAgent:def test_registered_under_codex_key(self) -> None:assert isinstance(CODEX, GenericKnownAgent)@@ -283,93 +99,6 @@ class TestCodexKnownAgent:assert caps.compact == "session_dependent"assert caps.interrupt == "session_dependent"- def test_start_session_instructions_emit_codex_not_claude(self) -> None:- opts = GenericAgentOptions(repo_dir="/Users/x/repo")- msg = CODEX.start_session_instructions(- opts, _agent_named("codex.test"), "hub", None- )- assert msg is not None- # The path is quoted so a repo_dir with spaces still produces a valid- # paste command.- assert (- 'cd "/Users/x/repo" && codex "connect to switch room hub'- f'{_identity("codex.test")}"'- ) in msg- # It must NOT suggest a claude command or Claude-specific flags.- assert "claude" not in msg- assert "--dangerously-load-development-channels" not in msg- # The footer must not falsely promise auto-start (this message only shows- # when no session is being auto-spawned); it points at a manual start.- assert "auto-starts one when I'm addressed" not in msg- assert "start Codex manually" in msg-- def test_repo_dir_with_spaces_stays_quoted(self) -> None:- opts = GenericAgentOptions(repo_dir="/Users/alice/my project")- msg = CODEX.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert 'cd "/Users/alice/my project" && codex' in msg-- def test_connected_not_live_opening(self) -> None:- opts = GenericAgentOptions(repo_dir="/r")- msg = CODEX.start_session_instructions(- opts, _agent_named("codex.test"), "ops", None, connected_not_live=True- )- assert msg is not None- assert "isn't reporting" in msg- assert "I don't have a session connected to this room." not in msg- assert "claude" not in msg-- def test_other_room_names_branch(self) -> None:- opts = GenericAgentOptions(repo_dir="/r")- msg = CODEX.start_session_instructions(- opts,- _agent_named("codex.test"),- "ops",- None,- other_room_names=["hub", "triage"],- )- assert msg is not None- assert "**hub**" in msg- assert "**triage**" in msg- assert "claude" not in msg-- def test_assume_role_folded_into_prompt(self) -> None:- opts = GenericAgentOptions(repo_dir="/r")- msg = CODEX.start_session_instructions(- opts, _agent_named("codex.test"), "ops", None, assume_role="reviewer"- )- assert msg is not None- assert (- 'codex "connect to switch room ops and assume the role reviewer'- f'{_identity("codex.test")}"'- ) in msg-- def test_empty_string_repo_dir_normalised_to_placeholder(self) -> None:- opts = GenericAgentOptions(repo_dir="")- assert opts.repo_dir is None- msg = CODEX.start_session_instructions(opts, _agent({}), "triage", None)- assert msg is not None- assert 'cd "<codex-dir>"' in msg-- def test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:- opts = GenericAgentOptions()- msg = CODEX.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert not msg.startswith("@")-- def test_no_repo_dir_uses_codex_placeholder(self) -> None:- msg = CODEX.start_session_instructions(- GenericAgentOptions(repo_dir=None), _agent({}), "triage", None- )- assert msg is not None- assert 'cd "<codex-dir>"' in msg-- def test_the_owner_is_prepended_as_an_at_mention(self) -> None:- opts = GenericAgentOptions(repo_dir="/x")- msg = CODEX.start_session_instructions(opts, _agent({}), "hub", "cmcd")- assert msg is not None- assert msg.startswith("@cmcd\n\n")-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 Codex has no channel, so it is not a field.@@ -432,76 +161,6 @@ class TestOpenCodeKnownAgent: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 = GenericAgentOptions(repo_dir="/Users/x/repo")- msg = OPENCODE.start_session_instructions(- opts, _agent_named("opencode.test"), "hub", None- )- assert msg is not None- assert (- 'cd "/Users/x/repo" && opencode --prompt "connect to switch room hub'- f'{_identity("opencode.test")}"'- ) in msg- assert 'opencode "connect' not in msg-- def test_start_session_instructions_emit_opencode_only(self) -> None:- opts = GenericAgentOptions(repo_dir="/Users/x/repo")- msg = OPENCODE.start_session_instructions(- opts, _agent_named("opencode.test"), "hub", None- )- 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 = GenericAgentOptions(repo_dir="/Users/alice/my project")- msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", None)- 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 = GenericAgentOptions(repo_dir="/r")- msg = OPENCODE.start_session_instructions(- opts, _agent_named("opencode.test"), "ops", None, assume_role="reviewer"- )- assert msg is not None- assert (- '--prompt "connect to switch room ops and assume the role reviewer'- f'{_identity("opencode.test")}"'- ) in msg-- def test_blank_repo_dir_uses_placeholder(self) -> None:- msg = OPENCODE.start_session_instructions(- GenericAgentOptions(repo_dir=""), _agent({}), "triage", None- )- assert msg is not None- assert 'cd "<opencode-dir>"' in msg-- def test_no_repo_dir_uses_placeholder(self) -> None:- msg = OPENCODE.start_session_instructions(- GenericAgentOptions(repo_dir=None), _agent({}), "triage", None- )- assert msg is not None- assert 'cd "<opencode-dir>"' in msg-- def test_an_unlinked_owner_produces_no_mention(self) -> None:- opts = GenericAgentOptions()- msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", None)- assert msg is not None- assert not msg.startswith("@")-- def test_the_owner_is_mentioned(self) -> None:- opts = GenericAgentOptions(repo_dir="/x")- msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", "cmcd")- 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@@ -611,17 +270,6 @@ class TestAntigravityKnownAgent:assert profile.command_capabilities.interrupt == "session_dependent"assert profile.pre_invocation_mediation == []- def test_onboarding_requires_console_runtime(self) -> None:- options = ANTIGRAVITY.parse_options({"repo_dir": " "})- assert options.repo_dir is None- agent = _agent_named("antigravity.test")- assert ANTIGRAVITY.connect_command(options, agent, "hub", None) is None- text = ANTIGRAVITY.start_session_instructions(options, agent, "hub", None)- assert "Antigravity CLI" in text- assert "`agy`" in text- assert "local session" in text- assert "antigravity.test" in text-class TestCursorKnownAgent:def test_registry_and_profile(self) -> None:@@ -638,15 +286,19 @@ class TestCursorKnownAgent:assert profile.command_capabilities.interrupt == "session_dependent"assert profile.pre_invocation_mediation == []- def test_onboarding_requires_console_acp(self) -> None:- options = CURSOR.parse_options({"repo_dir": " "})- assert options.repo_dir is None- agent = _agent_named("cursor.test")- assert CURSOR.connect_command(options, agent, "hub", None) is None- text = CURSOR.start_session_instructions(options, agent, "hub", None)- assert "Cursor CLI ACP" in text- assert "local session" in text- assert "cursor.test" in text++class TestBlankOptionsAreNormalised:+ @pytest.mark.parametrize(+ ("options_cls", "field"),+ [+ (ClaudeCodeOptions, "repo_dir"),+ (ClaudeCodeOptions, "subagent_name"),+ (GenericAgentOptions, "repo_dir"),+ ],+ )+ def test_blank_string_becomes_none(self, options_cls: type, field: str) -> None:+ # The gateway edit form submits "" when a field is cleared.+ assert getattr(options_cls.model_validate({field: " "}), field) is None_SESSION_DEPENDENT = CommandCapabilities(diff --git a/core/tests/switch_core/providers/test_provider_registry.py b/core/tests/switch_core/providers/test_provider_registry.pyindex 5ce8db701..7a5a9a15c 100644--- a/core/tests/switch_core/providers/test_provider_registry.py+++ b/core/tests/switch_core/providers/test_provider_registry.py@@ -3,6 +3,8 @@ depends on which providers exist."""from __future__ import annotations+import re+from pathlib import Pathfrom types import SimpleNamespaceimport httpx@@ -28,7 +30,6 @@ from switch_core.management.service import _known_agent_registrationfrom switch_core.providers import registryfrom switch_core.providers.registry import (AgentProvider,- ConsoleStart,UnknownProvider,agent_provider,agent_providers,@@ -73,6 +74,31 @@ def test_the_stored_identifiers_of_existing_providers_are_unchanged() -> None:}+_AGENT_PROVIDERS_SRC = (+ Path(__file__).resolve().parents[4] / "console/packages/agent-providers/src"+)++# Where Switch Console defines each provider's `loginCommand`.+_CONSOLE_SIGN_IN = {+ "claude": ("claude/sign-in.ts", r"CLAUDE_LOGIN = '([^']+)'"),+ "codex": ("codex/sign-in.ts", r"CODEX_LOGIN = '([^']+)'"),+ "opencode": ("opencode/sign-in.ts", r"OPENCODE_LOGIN = '([^']+)'"),+ "antigravity": ("antigravity/antigravity-adapter.ts", r"loginCommand: '([^']+)'"),+ "cursor": ("cursor/cursor-adapter.ts", r"CURSOR_LOGIN = '([^']+)'"),+}+++def test_each_sign_in_command_is_the_one_switch_console_runs() -> None:+ # An offline reply tells the owner to sign the CLI in with this command,+ # and Switch Console tells them the same thing from its own table.+ assert set(_CONSOLE_SIGN_IN) == set(provider_ids())+ for provider in agent_providers():+ path, pattern = _CONSOLE_SIGN_IN[provider.id]+ found = re.search(pattern, (_AGENT_PROVIDERS_SRC / path).read_text())+ assert found is not None, provider.id+ assert provider.sign_in_command == found.group(1), provider.id++def test_an_unknown_provider_is_refused_with_the_ones_there_are() -> None:with pytest.raises(UnknownProvider) as raised:agent_provider("gemini")@@ -92,7 +118,7 @@ def test_only_claude_has_a_known_agent_of_its_own() -> None:)-NEW = AgentProvider(id="newcli", label="New CLI")+NEW = AgentProvider(id="newcli", label="New CLI", sign_in_command="newcli login")@pytest.fixture@@ -109,9 +135,6 @@ class TestANewProvider:assert new_provider.connector_type == "New CLI"assert new_provider.advanced_fields == ()assert new_provider.tools == ()- assert new_provider.session_start == ConsoleStart(- runtime=None, sign_in_command=None- )assert provider_ids()[-1] == "newcli"async def test_it_is_served_in_the_provider_list(@@ -160,10 +183,6 @@ class TestANewProvider:name="new.agent",metadata_={"known_agent_type": "newcli", "known_agent_options": {}},)- assert spec.connect_command(options, agent, "hub", None) is None # type: ignore[arg-type]- assert spec.start_session_instructions(options, agent, "hub", None) == ( # type: ignore[arg-type]- "open **new.agent** in Switch Console and start a local session in **hub**."- )resolved = known_agent_for(agent) # type: ignore[arg-type]assert resolved is not Noneassert resolved[0].provider is new_providerdiff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex 1e30a6f35..2376d4b12 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -109,15 +109,15 @@ id, no IP field, no Switch identity.| `update_downloaded` | `outcome`: `success` / `failure` || `update_install_started` | `outcome`: `success` / `failure` || `telemetry_consent_changed` | `source`: `first_run` / `settings` · `install_kind`: as on `app_launched`, or `unknown` if the launch could not be recorded |-| `setting_changed` | `setting_key`, one of exactly 15: `theme`, `notifications`, `terminal`, `defaultAgent`, `sessions`, `location`, `localLocation`, `openIn`, `interface`, `browser`, `browserPreview`, `changesViewMode`, `remote`, `onboarding`, `telemetry`. **The new value is never sent** — we learn that someone changed their theme, not to what. |+| `setting_changed` | `setting_key`, one of exactly 12: `localLocation`, `sessions`, `defaultAgent`, `notifications`, `theme`, `openIn`, `interface`, `browserPreview`, `browser`, `changesViewMode`, `onboarding`, `telemetry`. **The new value is never sent** — we learn that someone changed their theme, not to what. || `search_performed` | `status`: `ok` / `recents` / `query-too-short` / `failed` · `result_count`: `0`, `3`, `17`. **The query is never sent.** |**Navigation and onboarding**| Event | Fields, with example values ||---|---|-| `view_opened` | `view_id`, one of exactly 18: `home`, `location`, `session`, `managedAgent`, `room`, `settings`, `server`, `managedServer`, `serverAgents`, `connectors`, `serverRooms`, `remoteHosts`, `remoteHost`, `templateImport`, `templates`, `templateDetail`, `templateUse`, `templateCapture` |-| `command_executed` | `command_id`, one of 28 known commands: `app.settings`, `app.newSession`, `app.addServer`, `app.toggleTheme`, `session.newTerminal`, `session.gitPush`, … · `invoked_by`: `palette` / `shortcut` |+| `view_opened` | `view_id`, one of exactly 21: `home`, `location`, `session`, `chat`, `managedAgent`, `room`, `settings`, `server`, `managedServer`, `serverAgents`, `connectors`, `serverRooms`, `remoteHosts`, `remoteHost`, `templateImport`, `templates`, `templateDetail`, `templateUse`, `templateCapture`, `switchBuddy`, `admin` |+| `command_executed` | `command_id`, one of exactly 9: `app.settings`, `app.newLocation`, `app.addServer`, `app.toggleTheme`, `app.navigateBack`, `app.navigateForward`, `session.pin`, `session.nextSession`, `session.prevSession` · `invoked_by`: `palette` / `shortcut` || `deeplink_opened` | `resolved`: `true` / `false` · `cold_start`: `true` / `false`. **The URL is never sent.** || `onboarding_step_started` | `step_id`, one of exactly 4: `addServer`, `agentProviders`, `onboardAgents`, `createRoom` || `onboarding_checklist_dismissed` | *(no fields)* |diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.mdindex 6ffe2ef61..e6d64ba51 100644--- a/docs/TEMPLATES.md+++ b/docs/TEMPLATES.md@@ -147,7 +147,7 @@ is the name; keep it a plain identifier.| `bridge` | The display name of a messaging app set up on the server. | The server checks it exists. || `room` | The name of a room on the server. | The server checks it exists. || `user` | A username on the room's messaging app. | The server looks it up on the app. |-| `provider` | A coding agent id: `claude`, `codex` or `opencode`. | Read when the agents are created; never in the room document. |+| `provider` | A coding agent id: `claude`, `codex`, `opencode`, `antigravity` or `cursor`. | Read when the agents are created; never in the room document. || `location` | Where an agent runs: `local`, or an SSH host name the Console knows. | Switch Console; never in the room document. || `machine` | One of the deployer's machines on the server, by name or id. | Read when the agents are created; never in the room document. || `directory` | An agent's working directory, on the machine it runs on. | Read when the agents are created; never in the room document. |@@ -267,7 +267,7 @@ agent:icon_url: https URLdescription: textinstructions: text- provider: claude | codex | opencode | "{param}"+ provider: claude | codex | opencode | antigravity | cursor | "{param}"machine: machine name or id | "{param}"location: local | ssh host | "{param}"directory: path | "{param}"diff --git a/docs/design/agent-controllers-v1.md b/docs/design/agent-controllers-v1.mdindex 033bc6604..ee6645fd4 100644--- a/docs/design/agent-controllers-v1.md+++ b/docs/design/agent-controllers-v1.md@@ -510,7 +510,7 @@ stream. The flag and everything else above stay as they are.owner stopped it and has to set it running, or its machine (thecontroller's name, carried on the binding) is offline or reconnecting, orhas been removed once it is revoked. A controller-backed agent is never- offered the terminal command or told to open Switch Console.+ told to open Switch Console.In-room session commands (`!reset`, `!compact`) are still relayed on thecontroller's stream with the room, and the controller picks the session.- **Liveness** is "socket attached and a pong within 6 s"; the connection sweepdiff --git a/docs/messaging-platforms/README.md b/docs/messaging-platforms/README.mdindex 228fc6ab1..a1dfb63f5 100644--- a/docs/messaging-platforms/README.md+++ b/docs/messaging-platforms/README.md@@ -7,6 +7,6 @@ the platform: what to create on the platform side, the permissions it needs,what each connection field means and what the platform can't do.The platforms Switch shipped with are documented on the published docs site,-under [Deploy → Messaging apps](https://docs.switchagents.ai/flintai/switch/deploy/messaging-apps).+under [Deploy → Messaging apps](https://docs.switchagents.ai/switch-rooms/deploy/messaging-apps).A page here moves there once it's published, and the adapter's `docs_slug` isthen set so Console links to it.diff --git a/docs/old/ARCHITECTURE.md b/docs/old/ARCHITECTURE.mdindex 09884c321..59275df7c 100644--- a/docs/old/ARCHITECTURE.md+++ b/docs/old/ARCHITECTURE.md@@ -1,5 +1,11 @@# Switch — Architecture & Design+> **Out of date.** This document describes an earlier design of Switch, when it+> ran on a Matrix homeserver. Matrix was removed in switch-core 0.25.0, and many+> sections no longer match the code. For how Switch works today, read+> [`docs/official/internals/`](../official/internals/index.md) and the code;+> [`CLAUDE.md`](../../CLAUDE.md) lists where to start. It is kept for history.+This document describes how Switch is built: its components, how they fittogether, and what each part is responsible for. It is meant as a map — areviewer or new contributor should be able to read it and know **where in thediff --git a/docs/old/LOCAL_DEVELOPMENT.md b/docs/old/LOCAL_DEVELOPMENT.mdindex 5b9bad6d3..6c0942142 100644--- a/docs/old/LOCAL_DEVELOPMENT.md+++ b/docs/old/LOCAL_DEVELOPMENT.md@@ -230,7 +230,7 @@ just local-cloud-console # the Console, with Switch Cloud at http://localhost:80| --- | --- || `just local-cloud` / `just local-cloud-console` | Run switch-core as a stand-in for Switch Cloud, and the Console pointed at it (see above) || `just format` / `just check` | Format with ruff / lint-check in CI mode (no changes) |-| `just typecheck` | mypy over `core/switch_core/` and `connectors/` |+| `just typecheck` | mypy over `core/switch_core/` || `just test` / `just test -k name` | Run the test suite / a single test || `just test-integration` | Integration tests against a real Postgres via testcontainers || `just migration "message"` | Autogenerate a new Alembic migration |diff --git a/docs/old/api/AGENT_PROTOCOL.md b/docs/old/api/AGENT_PROTOCOL.mdindex 0b6b1ede5..d0ca2704a 100644--- a/docs/old/api/AGENT_PROTOCOL.md+++ b/docs/old/api/AGENT_PROTOCOL.md@@ -1,5 +1,14 @@# Agent Bridge Protocol+> **Partly out of date.** Some sections describe the protocol as first designed+> and no longer match the code: there is no Matrix server, agents now connect+> over a WebSocket (protocol revision 8) with server-sent events kept only for+> older runtimes, and sessions get the Switch tools from Switch Console's+> session host rather than from connector plugins started with `npx`. Where+> this document and the code disagree, the code in+> [`core/switch_core/bridges/agent/`](../../../core/switch_core/bridges/agent/)+> is right.+Status: **Stages A and B implemented; Stage C outstanding** (CHOO-1857, closed)This began as a design proposal and is now largely built. The connection model,diff --git a/docs/old/bridges/README.md b/docs/old/bridges/README.mdindex e7a658978..fb6f8ffb4 100644--- a/docs/old/bridges/README.md+++ b/docs/old/bridges/README.md@@ -1,7 +1,7 @@# Collaboration bridge setupA **collaboration bridge** is a two-way relay between an external chat platform-(Slack, Mattermost, Microsoft Teams, Discord, Telegram) and Switch's internal Matrix+(Slack, Mattermost, Microsoft Teams, Discord, Telegram) and Switch's internalrooms. Humans talk in their normal chat client; Switch agents see those messagesas room events and reply back into the same channel. Each external channel mapsto a Switch room, and each Switch agent is presented in the channel under thediff --git a/docs/old/bridges/SLACK_DISTRIBUTED_APP.md b/docs/old/bridges/SLACK_DISTRIBUTED_APP.mdindex 4f4a32e64..022f8e438 100644--- a/docs/old/bridges/SLACK_DISTRIBUTED_APP.md+++ b/docs/old/bridges/SLACK_DISTRIBUTED_APP.md@@ -127,7 +127,6 @@ the same job once installed — the differences are all in `settings` and{ "command": "/invite-agent", "url": "https://HOST/messaging/slack/commands", "description": "Add an existing agent to this room", "usage_hint": "@agent-name", "should_escape": true },{ "command": "/rename-agent", "url": "https://HOST/messaging/slack/commands", "description": "Rename an agent (owner or admin)", "usage_hint": "@agent-name new-name [Display Name]", "should_escape": true },{ "command": "/delete-agent", "url": "https://HOST/messaging/slack/commands", "description": "Delete an agent (owner or admin)", "usage_hint": "@agent-name [confirm]", "should_escape": true },- { "command": "/run-cmd", "url": "https://HOST/messaging/slack/commands", "description": "Show the terminal command to start a session for an agent", "usage_hint": "@agent-name [@role]", "should_escape": true },{ "command": "/agents-greet", "url": "https://HOST/messaging/slack/commands", "description": "Have agents in the room introduce themselves", "should_escape": false },{ "command": "/room-url", "url": "https://HOST/messaging/slack/commands", "description": "Show the frontend URL for this room", "should_escape": false },{ "command": "/follow-ups", "url": "https://HOST/messaging/slack/commands", "description": "Turn follow-ups without an @ on or off for this room", "usage_hint": "on | off", "should_escape": false },diff --git a/docs/old/bridges/SLACK_SETUP.md b/docs/old/bridges/SLACK_SETUP.mdindex d136de24a..6c4f8c21c 100644--- a/docs/old/bridges/SLACK_SETUP.md+++ b/docs/old/bridges/SLACK_SETUP.md@@ -76,7 +76,6 @@ You need one Slack app for the whole bridge. There are two ways to create it —{ "command": "/invite-agent", "description": "Add an existing agent to this room", "usage_hint": "@agent-name", "should_escape": true },{ "command": "/rename-agent", "description": "Rename an agent (owner or admin)", "usage_hint": "@agent-name new-name [Display Name]", "should_escape": true },{ "command": "/delete-agent", "description": "Delete an agent (owner or admin)", "usage_hint": "@agent-name [confirm]", "should_escape": true },- { "command": "/run-cmd", "description": "Show the terminal command to start a session for an agent", "usage_hint": "@agent-name [@role]", "should_escape": true },{ "command": "/agents-greet", "description": "Have agents in the room introduce themselves", "should_escape": false },{ "command": "/room-url", "description": "Show the frontend URL for this room", "should_escape": false },{ "command": "/follow-ups", "description": "Turn follow-ups without an @ on or off for this room", "usage_hint": "on | off", "should_escape": false },diff --git a/docs/old/bridges/TEAMS_SETUP.md b/docs/old/bridges/TEAMS_SETUP.mdindex ab081265e..b1dcdb1fb 100644--- a/docs/old/bridges/TEAMS_SETUP.md+++ b/docs/old/bridges/TEAMS_SETUP.md@@ -314,6 +314,10 @@ which you need either way."title": "/invite-agent","description": "Add an existing agent: /invite-agent @agent-name"},+ {+ "title": "/remove-agent",+ "description": "Remove an agent from this room: /remove-agent @agent-name"+ },{"title": "/agents-greet","description": "Have the agents here introduce themselves"@@ -341,10 +345,6 @@ which you need either way.{"title": "/list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "/room-url",- "description": "Show this room's address in Switch"}]},@@ -374,6 +374,10 @@ which you need either way."title": "invite-agent","description": "Add an existing agent: /invite-agent @agent-name"},+ {+ "title": "remove-agent",+ "description": "Remove an agent from this room: /remove-agent @agent-name"+ },{"title": "agents-greet","description": "Have the agents here introduce themselves"@@ -401,10 +405,6 @@ which you need either way.{"title": "list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "room-url",- "description": "Show this room's address in Switch"}]}diff --git a/docs/old/bridges/teams-app/manifest.json b/docs/old/bridges/teams-app/manifest.jsonindex d821660c3..f85438c09 100644--- a/docs/old/bridges/teams-app/manifest.json+++ b/docs/old/bridges/teams-app/manifest.json@@ -61,6 +61,10 @@"title": "/invite-agent","description": "Add an existing agent: /invite-agent @agent-name"},+ {+ "title": "/remove-agent",+ "description": "Remove an agent from this room: /remove-agent @agent-name"+ },{"title": "/agents-greet","description": "Have the agents here introduce themselves"@@ -88,10 +92,6 @@{"title": "/list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "/room-url",- "description": "Show this room's address in Switch"}]},@@ -121,6 +121,10 @@"title": "invite-agent","description": "Add an existing agent: /invite-agent @agent-name"},+ {+ "title": "remove-agent",+ "description": "Remove an agent from this room: /remove-agent @agent-name"+ },{"title": "agents-greet","description": "Have the agents here introduce themselves"@@ -148,10 +152,6 @@{"title": "list-switch-agents","description": "List every agent on this Switch, to find one to invite"- },- {- "title": "room-url",- "description": "Show this room's address in Switch"}]}diff --git a/docs/old/observability.md b/docs/old/observability.mdindex 23eea617d..0b216c766 100644--- a/docs/old/observability.md+++ b/docs/old/observability.md@@ -47,7 +47,7 @@ python scripts/otlp_sink.py# Another: the server, reporting to it.DB_HOST=localhost DB_PORT=55432 DB_USER=postgres DB_PASSWORD=check DB_NAME=switch \DB_REQUIRE_RESTRICTED_ROLE=false \-MATRIX_SERVER_NAME=switch.local \+ID_SERVER_NAME=switch.local \AGENT_REGISTRATION_TOKEN=check SECRET_KEYS=check:check-secret-key-long-enough-for-32 \[email protected] GATEWAY_ADMIN_PASSWORD=check \SERVER_PORT=8099 LOG_FORMAT=json ENVIRONMENT=local \diff --git a/switch-expert/AGENT.md b/switch-expert/AGENT.mdindex f9fa5a191..16b1951cb 100644--- a/switch-expert/AGENT.md+++ b/switch-expert/AGENT.md@@ -90,7 +90,7 @@ Switch runs on many servers and the details differ per server. You ship with **nthem. At the start of a setup conversation, ask for what you need and remember it for theconversation:-- The server's Gateway and API URLs.+- The server's address.- How they sign in.- Any network prerequisite to reach it (a VPN, an allow-list, nothing at all).- Which chat platform their rooms are bridged to, if any.@@ -182,9 +182,9 @@ properly, and the person will hit the gaps later rather than sooner.again there. Get this one right the first time.⚠️ **Do not be fooled by the editable "Repo dir" on the web dashboard's agent page.**- That field exists, and changing it changes nothing about where the agent runs — it only- feeds the ready-to-paste command the dashboard shows for starting a session by hand. Edit- it and you have simply made the dashboard disagree with reality. The same goes for setting+ That field exists, and changing it changes nothing about where the agent runs. Switch+ Console only uses it as a hint when it looks for agents it can load from a remote host.+ Edit it and you have simply made the dashboard disagree with reality. The same goes for setting`repo_dir` through the agent-update tool.2. **Give it its expertise through its Agent instructions.** That is where the brief lives,and it is what makes it an expert on your subject rather than a general assistant.diff --git a/switch-expert/CORRECTIONS.md b/switch-expert/CORRECTIONS.mdindex 347e50be4..115abef3b 100644--- a/switch-expert/CORRECTIONS.md+++ b/switch-expert/CORRECTIONS.md@@ -35,12 +35,17 @@ and describe what was asked.it can be set; the agent's settings expose instructions, auto-approve,addressing and advanced provider configuration, and show the directory read-only at most.Moving an agent means removing it and adding it again. The editable "Repo dir" on the web- dashboard's agent page (and via the agent-update tool) is metadata for the generated- copy-and-paste session command only — editing it does not relocate anything, it just makes+ dashboard's agent page (and via the agent-update tool) does not decide where the agent+ runs. Switch Console only uses it as a hint when looking for agents it can load from a+ remote host. It used to also feed a copy-and-paste session command in the agent's offline+ reply, which has since been removed. Editing it does not relocate anything, it just makesthe dashboard disagree with where the agent actually runs.- **Confirmed by:** Switch Console's new-agent dialog and settings panel in `console/`, which- has no directory field or update path after creation; and `repo_dir`'s only consumer being- the generated connect command in `core/switch_core/gateway/known_agents.py`.+ has no directory field or update path after creation; and the only reader of `repo_dir`+ that changes behaviour being Console's remote-host discovery+ (`console/apps/switch-console-desktop/src/main/core/agents/discover-loadable-agents.ts`).+ The server also copies it to an agent's subagents when they register+ (`core/switch_core/gateway/subagent_registration.py`), but never acts on it.- **Fixed in:** `AGENT.md` (Switch Console steps) and `knowledge/GOTCHAS.md` (new entry).### 2026-08-24 — "who can talk to your agent" has four choices, and it is in the settingsdiff --git a/switch-expert/knowledge/GOTCHAS.md b/switch-expert/knowledge/GOTCHAS.mdindex 3ee37e64a..dba911e3c 100644--- a/switch-expert/knowledge/GOTCHAS.md+++ b/switch-expert/knowledge/GOTCHAS.md@@ -222,9 +222,9 @@ and add it again in the new place.What makes this confusing is that a **"Repo dir" field does exist and is editable** — on theagent's page in the web dashboard, and through the agent-update tool. It is not the same-thing. It only feeds the copy-and-paste command the dashboard offers for starting a session-by hand. Change it and the agent carries on exactly where it was, with the dashboard now-telling you something untrue.+thing. Switch Console only uses it as a hint when looking for agents it can load from a+remote host. Change it and the agent carries on exactly where it was, with the dashboard+now telling you something untrue.So: pick the directory carefully at creation, and treat that field as a display detail.