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
fix(console): report an unusable remote working directory before minting (CHOO-1416) (#373)
Abel Dantas7f931725c478
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex 65f20936b..d8fb24b63 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -2,6 +2,9 @@ import type { PluginFs } from '@switch-console/core/agents/plugins';import { beforeEach, describe, expect, it, vi } from 'vitest';import { agentSettingsRelativePath } from './switch-settings-paths';+const inspectRemoteDir = vi.hoisted(() => vi.fn());+vi.mock('./remote-dir', () => ({ inspectRemoteDir }));+/** In-memory {@link PluginFs} keyed by the exact relative paths the writers use. */function fakeFs(seed: Record<string, string> = {}): PluginFs {const files = new Map<string, string>(Object.entries(seed));@@ -137,6 +140,43 @@ describe('addAgent', () => {h.state.repoAgents = h.repoAgents;h.state.workspace = fakeFs();h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });+ // `clearAllMocks` resets call records but not implementations: without a+ // default, whichever test last set one decides the answer for the rest.+ inspectRemoteDir.mockResolvedValue({ dir: '/repo', status: 'directory' });+ });++ it('refuses a remote directory whose parent is missing, before minting (CHOO-1416)', async () => {+ inspectRemoteDir.mockResolvedValue({ dir: '/home/u/agents/deploy', status: 'missing' });++ const result = await addAgent(params({ sshHost: 'vm-1', dir: '/home/u/agents/deploy' }));++ expect(result.kind).toBe('directory-unusable');+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ });++ it('never inspects the remote directory for a local add', async () => {+ await addAgent(params());+ expect(inspectRemoteDir).not.toHaveBeenCalled();+ });++ it('refuses a relative remote directory without probing the host', async () => {+ const result = await addAgent(params({ sshHost: 'vm-1', dir: 'agents/deploy' }));++ expect(result).toMatchObject({+ kind: 'directory-unusable',+ inspection: { status: 'relative' },+ });+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ });++ it('settles on a canonical remote path before anything keys off it', async () => {+ await addAgent(params({ sshHost: 'vm-1', dir: '/home/u/./x/../agents/deploy/' }));++ expect(inspectRemoteDir).toHaveBeenCalledWith('vm-1', '/home/u/agents/deploy');+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ repoDir: '/home/u/agents/deploy' })+ );});it('writes name-keyed credentials for a provider with no repo-agent definitions', async () => {@@ -311,9 +351,12 @@ describe('addAgent', () => {await addAgent(params({ sshHost: 'build-box', entryPoint: 'server_page' }));+ // `failure_reason` too: `location: 'remote'` alone is also what a preflight+ // refusal reports, so asserting it by itself would pass without ever+ // reaching `registerAgentIdentity`.expect(trackEvent).toHaveBeenCalledWith('agent_created',- expect.objectContaining({ location: 'remote' })+ expect.objectContaining({ location: 'remote', failure_reason: 'unauthenticated' }));});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex 97232a6e7..81c4eed19 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts@@ -17,6 +17,12 @@ import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import {+ isAbsoluteRemoteDir,+ isUsableRemoteDir,+ normalizeRemoteDir,+ type RemoteDirInspection,+} from '@shared/core/remote-hosts/remote-dir';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { basenameFromAnyPath } from '@shared/path-name';import { writeAgentConfigFile } from './agent-config-file';@@ -29,6 +35,7 @@ import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';import { knownAgentTypeForProvider } from './known-agent-type';import { registerAgentIdentity } from './register-agent-identity';+import { inspectRemoteDir } from './remote-dir';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';import { writeNeutralAgentSettingsFs } from './write-switch-settings';@@ -81,6 +88,10 @@ export type AddAgentResult =| { kind: 'credentials-conflict'; endpoint: string }| { kind: 'already-configured' }| { kind: 'invalid-name'; message: string }+ /** The remote working directory cannot be used — `inspection.status` says+ * which way. Reported before anything is minted, so no Switch-side agent is+ * left behind (CHOO-1416). */+ | { kind: 'directory-unusable'; sshHost: string; inspection: RemoteDirInspection }| { kind: 'error'; message: string };/** The result's discriminant as a reportable code. Never its message. */@@ -93,6 +104,7 @@ const ADD_AGENT_FAILURE_REASON: Record<'credentials-conflict': 'credentials_conflict','already-configured': 'already_configured','invalid-name': 'invalid_name',+ 'directory-unusable': 'directory_unusable',error: 'error',};@@ -134,7 +146,13 @@ function reportFailedCreate(params: AddAgentParams, result: AddAgentResult): Add* a typed result the modal can act on; a filesystem failure after registration* throws (leaving the gateway agent, as the pre-existing provision path did).*/-export async function addAgent(params: AddAgentParams): Promise<AddAgentResult> {+export async function addAgent(input: AddAgentParams): Promise<AddAgentResult> {+ // Canonicalized once here so nothing downstream keys off a different spelling+ // of the same directory.+ const params: AddAgentParams =+ input.sshHost !== null && isAbsoluteRemoteDir(input.dir)+ ? { ...input, dir: normalizeRemoteDir(input.dir) }+ : input;try {return await runAddAgent(params);} catch (error) {@@ -155,6 +173,16 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {message: `Invalid directory: ${params.dir}`,});}+ // The one case the probe below cannot be asked about: a relative path has no+ // meaning until a session picks a starting directory, so there is nothing on+ // the host to inspect.+ if (params.sshHost !== null && !isAbsoluteRemoteDir(params.dir)) {+ return reportFailedCreate(params, {+ kind: 'directory-unusable',+ sshHost: params.sshHost,+ inspection: { dir: params.dir, status: 'relative' },+ });+ }const server = await getServer(params.serverId);if (!server) {@@ -213,6 +241,21 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {}}+ // The last check before minting, and the only one costing a round trip to the+ // host — hence last, so a name conflict is answered without an SSH probe. A+ // missing directory under an existing parent passes: the first write creates+ // it (CHOO-1416).+ if (params.sshHost !== null) {+ const inspection = await inspectRemoteDir(params.sshHost, params.dir);+ if (!isUsableRemoteDir(inspection)) {+ return reportFailedCreate(params, {+ kind: 'directory-unusable',+ sshHost: params.sshHost,+ inspection,+ });+ }+ }+const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.integration.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.integration.test.tsnew file mode 100644index 000000000..f20bf64f2--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.integration.test.ts@@ -0,0 +1,173 @@+import ssh2 from 'ssh2';+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';++/**+ * `inspectRemoteDir` over a real SFTP connection.+ *+ * The sibling unit test replaces `SshFileSystem` with a fake whose `stat`+ * returns `null` for anything absent. That is an assumption about the wire, not+ * a fact: `stat` resolves `null` only because it recognises SFTP status 2, and+ * if a server reported absence any other way the probe would throw instead of+ * answering `creatable` — breaking every remote add while the unit tests stayed+ * green. Here the only fakes are the connection handshake and the directory+ * tree; the SFTP protocol, `SshFileSystem` and the probe are real.+ */++const { Client, Server, utils } = ssh2;+const { STATUS_CODE } = utils.sftp;++const S_IFDIR = 0o040000;+const S_IFREG = 0o100000;++/** The fake host's tree. Everything not named here does not exist. */+const TREE = new Map<string, 'dir' | 'file' | 'denied'>([+ ['/home/u', 'dir'],+ ['/home/u/agents', 'dir'],+ ['/home/u/agents/existing', 'dir'],+ ['/home/u/notes.txt', 'file'],+ ['/locked', 'denied'],+ ['/locked/inner', 'denied'],+]);++let server: ssh2.Server;+let client: ssh2.Client;+/** SFTP channels the server has opened, and how many have since closed. */+const channels = { opened: 0, closed: 0 };++const ensureSshConnected = vi.hoisted(() => vi.fn());+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected }));+vi.mock('@main/core/locations/location-transport', () => ({+ sshConnectionIdForHost: (host: string) => `conn:${host}`,+}));++const { inspectRemoteDir } = await import('./remote-dir');++beforeAll(async () => {+ const { private: hostKey } = utils.generateKeyPairSync('ed25519');++ server = new Server({ hostKeys: [hostKey] }, (conn) => {+ conn.on('authentication', (ctx) => ctx.accept());+ conn.on('ready', () => {+ conn.on('session', (acceptSession) => {+ acceptSession().on('sftp', (acceptSftp) => {+ const sftp = acceptSftp();+ channels.opened += 1;+ sftp.on('close', () => {+ channels.closed += 1;+ });++ // Answer STAT the way an OpenSSH server does: absent paths are a+ // status code, not a silence and not a different error.+ const onStat = (reqid: number, path: string) => {+ const kind = TREE.get(path);+ if (kind === 'denied') return sftp.status(reqid, STATUS_CODE.PERMISSION_DENIED);+ if (!kind) return sftp.status(reqid, STATUS_CODE.NO_SUCH_FILE);+ sftp.attrs(reqid, {+ mode: (kind === 'dir' ? S_IFDIR : S_IFREG) | 0o755,+ size: 0,+ uid: 0,+ gid: 0,+ atime: 0,+ mtime: 0,+ });+ };+ sftp.on('STAT', onStat);+ sftp.on('LSTAT', onStat);+ });+ });+ });+ });++ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as { port: number };++ client = new Client();+ await new Promise<void>((resolve, reject) => {+ client+ .on('ready', () => resolve())+ .on('error', reject)+ .connect({ host: '127.0.0.1', port, username: 'u', password: 'p' });+ });+});++afterAll(() => {+ client?.end();+ server?.close();+});++beforeEach(() => {+ channels.opened = 0;+ channels.closed = 0;+ // Only the handshake is stubbed: everything the probe does with the result is+ // the real `SshFileSystem` talking real SFTP to the server above.+ ensureSshConnected.mockImplementation(+ async () =>+ ({+ sftp: (cb: (err: Error | undefined, sftp: unknown) => void) => client.sftp(cb),+ }) as unknown as SshClientProxy+ );+});++describe('inspectRemoteDir over real SFTP', () => {+ it('reports an existing directory', async () => {+ expect(await inspectRemoteDir('host', '/home/u/agents/existing')).toEqual({+ dir: '/home/u/agents/existing',+ status: 'directory',+ });+ });++ // The case the whole fix turns on. A server reporting absence as anything the+ // mapping does not recognise would surface here as a rejection.+ it('reports a missing leaf under an existing parent as creatable', async () => {+ expect(await inspectRemoteDir('host', '/home/u/agents/deploy')).toEqual({+ dir: '/home/u/agents/deploy',+ status: 'creatable',+ });+ });++ it('reports a missing leaf whose parent is also missing', async () => {+ expect(await inspectRemoteDir('host', '/home/u/nope/deploy')).toEqual({+ dir: '/home/u/nope/deploy',+ status: 'missing',+ });+ });++ it('tells a regular file apart from a directory', async () => {+ expect(await inspectRemoteDir('host', '/home/u/notes.txt')).toEqual({+ dir: '/home/u/notes.txt',+ status: 'file',+ });+ });++ // Absence and unreadability are different answers. Reporting a denied path as+ // `missing` would send the user off to create a directory already there.+ it('propagates permission denied rather than calling it missing', async () => {+ await expect(inspectRemoteDir('host', '/locked/inner')).rejects.toThrow(/Permission denied/i);+ });++ it('normalises the path it probes, over the wire', async () => {+ expect(await inspectRemoteDir('host', '/home/u/./x/../agents/existing/')).toEqual({+ dir: '/home/u/agents/existing',+ status: 'directory',+ });+ });++ // SFTP channels do not self-close, and enough leaks exhaust the host's+ // MaxSessions — every later channel open then fails for the whole app.+ it('closes its SFTP channel on both the success and the failure path', async () => {+ await inspectRemoteDir('host', '/home/u/agents/existing');+ await expect(inspectRemoteDir('host', '/locked/inner')).rejects.toThrow();++ expect(channels.opened).toBe(2);+ await vi.waitFor(() => expect(channels.closed).toBe(2));+ });++ it('opens no channel at all for a relative path', async () => {+ expect(await inspectRemoteDir('host', 'agents/deploy')).toEqual({+ dir: 'agents/deploy',+ status: 'relative',+ });+ expect(channels.opened).toBe(0);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.test.tsnew file mode 100644index 000000000..3f022a45e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';++const stat = vi.hoisted(() => vi.fn());+const close = vi.hoisted(() => vi.fn());+const constructedWith = vi.hoisted(() => [] as string[]);++vi.mock('@main/core/fs/impl/ssh-fs', () => ({+ SshFileSystem: class {+ constructor(_proxy: unknown, base: string) {+ constructedWith.push(base);+ }+ stat = stat;+ close = close;+ },+}));+vi.mock('@main/core/locations/location-transport', () => ({+ sshConnectionIdForHost: (host: string) => `conn:${host}`,+}));+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({+ ensureSshConnected: vi.fn(async () => ({})),+}));++const { inspectRemoteDir } = await import('./remote-dir');++/** Report `paths` as existing directories and everything else as absent. */+function existingDirs(paths: string[]) {+ stat.mockImplementation(async (path: string) =>+ paths.includes(path) ? { path, type: 'dir' } : null+ );+}++const REPO_DIR = '/home/ubuntu/switch-agents/internal-deployments';++beforeEach(() => {+ vi.clearAllMocks();+ constructedWith.length = 0;+});++describe('inspectRemoteDir', () => {+ it('reports an existing directory', async () => {+ existingDirs([REPO_DIR]);++ expect(await inspectRemoteDir('host', REPO_DIR)).toEqual({+ dir: REPO_DIR,+ status: 'directory',+ });+ });++ // Recursive mkdir creates the working directory itself, just not its+ // ancestors, so a missing leaf under an existing parent needs no intervention.+ it('reports a missing directory whose parent exists as creatable', async () => {+ existingDirs(['/home/ubuntu/switch-agents']);++ expect(await inspectRemoteDir('host', REPO_DIR)).toEqual({+ dir: REPO_DIR,+ status: 'creatable',+ });+ });++ it('reports a missing directory whose parent is also missing', async () => {+ existingDirs(['/home/ubuntu']);++ expect(await inspectRemoteDir('host', REPO_DIR)).toEqual({+ dir: REPO_DIR,+ status: 'missing',+ });+ // Opened at the host root: an FS rooted at the missing directory could not+ // stat its way out to look at the parent.+ expect(constructedWith).toEqual(['/']);+ });++ it('reports a path that is a file', async () => {+ stat.mockImplementation(async (path: string) =>+ path === REPO_DIR ? { path, type: 'file' } : null+ );++ expect(await inspectRemoteDir('host', REPO_DIR)).toEqual({ dir: REPO_DIR, status: 'file' });+ });++ it('refuses a directory whose parent is a file', async () => {+ stat.mockImplementation(async (path: string) =>+ path === '/home/ubuntu/switch-agents' ? { path, type: 'file' } : null+ );++ expect(await inspectRemoteDir('host', REPO_DIR)).toEqual({ dir: REPO_DIR, status: 'missing' });+ });++ // An unreadable path is not a missing one; saying so would send the user off+ // to create a directory that is already there.+ it('propagates a probe failure that is not absence', async () => {+ stat.mockRejectedValue(+ new FileSystemError('Permission denied: /home', FileSystemErrorCodes.PERMISSION_DENIED)+ );++ await expect(inspectRemoteDir('host', REPO_DIR)).rejects.toThrow('Permission denied');+ });++ it('refuses a relative path rather than resolving it against the login dir', async () => {+ expect(await inspectRemoteDir('host', 'switch-agents/repo')).toEqual({+ dir: 'switch-agents/repo',+ status: 'relative',+ });+ expect(stat).not.toHaveBeenCalled();+ // Nothing to probe, so nothing should have been dialled either.+ expect(constructedWith).toEqual([]);+ });++ it('normalises a trailing slash', async () => {+ existingDirs([REPO_DIR]);++ expect(await inspectRemoteDir('host', `${REPO_DIR}/`)).toMatchObject({ dir: REPO_DIR });+ });++ it('resolves . and .. before probing, so one directory has one spelling', async () => {+ existingDirs([REPO_DIR]);++ expect(+ await inspectRemoteDir('host', '/home/ubuntu/switch-agents/./x/../internal-deployments')+ ).toEqual({ dir: REPO_DIR, status: 'directory' });+ });++ it('closes the SFTP channel on the success path', async () => {+ existingDirs([REPO_DIR]);++ await inspectRemoteDir('host', REPO_DIR);++ // Every remote add takes this path. SFTP channels do not self-close, and+ // enough leaks exhaust the host's MaxSessions.+ expect(close).toHaveBeenCalled();+ });++ it('closes the SFTP channel even when the probe throws', async () => {+ stat.mockRejectedValue(new Error('boom'));++ await expect(inspectRemoteDir('host', REPO_DIR)).rejects.toThrow('boom');+ expect(close).toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.tsnew file mode 100644index 000000000..f8fbe0cbf--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-dir.ts@@ -0,0 +1,52 @@+import { posix as pathPosix } from 'node:path';+import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import {+ isAbsoluteRemoteDir,+ normalizeRemoteDir,+ type RemoteDirInspection,+} from '@shared/core/remote-hosts/remote-dir';++/**+ * Inspect a prospective remote working directory on `sshHost` (CHOO-1416).+ *+ * Two stats decide it: whether the directory is there, and if not, whether its+ * parent is. A missing directory under an existing parent is created by the+ * first credentials write; a missing parent is not, because the working+ * directory's own FS is rooted at the directory and its recursive mkdir stops+ * there.+ *+ * The FS here is rooted at `/` because one rooted at a missing directory cannot+ * stat its way out to its parent. That is the only such handle in the app, and+ * `resolveRemotePath` cannot reject anything on it — keep it stat-only.+ *+ * A path that cannot be stat'd for a reason other than absence (permission+ * denied, dead connection) propagates rather than being reported as `missing`.+ * An unreadable path is not a missing one, and saying so would send the user off+ * to fix the wrong problem.+ *+ * Existence is not writability: a non-writable directory reads as `directory`+ * and the write still fails after the identity is minted. Closing that needs a+ * probe write or `test -w`; mode bits would not account for the effective user.+ */+export async function inspectRemoteDir(sshHost: string, dir: string): Promise<RemoteDirInspection> {+ if (!isAbsoluteRemoteDir(dir)) {+ return { dir, status: 'relative' };+ }+ const normalized = normalizeRemoteDir(dir);++ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);+ const fs = new SshFileSystem(proxy, '/');+ try {+ const entry = await fs.stat(normalized);+ if (entry) {+ return { dir: normalized, status: entry.type === 'dir' ? 'directory' : 'file' };+ }++ const parent = await fs.stat(pathPosix.dirname(normalized));+ return { dir: normalized, status: parent?.type === 'dir' ? 'creatable' : 'missing' };+ } finally {+ fs.close();+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.tsindex b29a9a2c1..2f7ec2199 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts@@ -53,6 +53,7 @@ export type TelemetryAgentCreateFailure =| 'credentials_conflict'| 'already_configured'| 'invalid_name'+ | 'directory_unusable'/*** The two the other way into this — dropping a folder on the sidebar — hits* most: the directory holds no agent configuration, or it holds one belongingdiff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 9f1d334d1..6ef11e677 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -45,7 +45,10 @@ import {import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { log } from '@renderer/utils/logger';import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';-import { type ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';+import {+ describeRemoteDirRefusal,+ isAbsoluteRemoteDir,+} from '@shared/core/remote-hosts/remote-dir';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { AgentAdvancedConfig } from './agent-advanced-config';import { AgentTypePicker } from './agent-type-picker';@@ -233,6 +236,10 @@ export const AddAgentModal = observer(function AddAgentModal({const canChooseAgentType = runHostReachable && !hostLevelBlocked;const canConfigureAgent = canChooseAgentType && runHostReady;+ // A relative remote dir would resolve against whatever directory the SSH+ // session starts in. Caught here so it greys the button out with a reason.+ const remoteDirIsAbsolute = !isRemoteRun || isAbsoluteRemoteDir(trimmedRemoteDir);+const canSubmit =form.isValid &&!nameTaken &&@@ -240,6 +247,7 @@ export const AddAgentModal = observer(function AddAgentModal({!!pickState.serverId &&!!pickState.providerId &&dir.trim().length > 0 &&+ remoteDirIsAbsolute &&runHostReachable &&runHostReady &&submitState === 'idle';@@ -270,9 +278,11 @@ export const AddAgentModal = observer(function AddAgentModal({? isRemoteRun? 'Enter the agent’s working directory on the host.': 'Choose the agent’s working directory.'- : policyHasDeadRule(form.addressingPolicy)- ? 'One addressing rule can never match — fix it under Settings.'- : null;+ : !remoteDirIsAbsolute+ ? `Give the full path on ${runLocationLabel}, starting with “/”.`+ : policyHasDeadRule(form.addressingPolicy)+ ? 'One addressing rule can never match — fix it under Settings.'+ : null;/** `agentName` is what picks the agent out of the location — a location can* hold several, so navigating on `locationId` alone opens the directory@@ -284,7 +294,9 @@ export const AddAgentModal = observer(function AddAgentModal({navigate('location', { locationId: agent.locationId, agentName: agent.name });};- const reportProvisionError = (result: ProvisionAgentResult) => {+ /** Typed off the RPC, not `ProvisionAgentResult`: an `addAgent` result is the+ * only thing passed here, and the two unions do not have to agree. */+ const reportProvisionError = (result: Awaited<ReturnType<typeof rpc.agents.addAgent>>) => {if (result.kind === 'unauthenticated' && pickState.serverId) {toast({title: 'Sign in to register the agent',@@ -311,6 +323,14 @@ export const AddAgentModal = observer(function AddAgentModal({});return;}+ if (result.kind === 'directory-unusable') {+ toast({+ title: 'That working directory cannot be used. Nothing was created.',+ description: describeRemoteDirRefusal(result.inspection, runLocationLabel),+ variant: 'destructive',+ });+ return;+ }if (result.kind === 'already-configured') {toast({title: 'An agent with this name is already configured here',diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsxindex 632687d32..c86dea17a 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx@@ -45,6 +45,7 @@ import {type AgentProviderId,providerDisplayName,} from '@shared/core/providers/agent-provider-registry';+import { describeRemoteDirRefusal } from '@shared/core/remote-hosts/remote-dir';import { ownerAndMyAgentsPolicy, ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';import { NEW } from '@shared/core/switch-servers/room-template-params';import { RpcError } from '@shared/lib/ipc/rpc-error';@@ -379,6 +380,10 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);const allowedHosts = useAllowedHosts(serverId);+ const hostLabel = useCallback(+ (sshHost: string) => allowedHosts.find((h) => h.sshHost === sshHost)?.name ?? sshHost,+ [allowedHosts]+ );// The messaging app the room is created on: the bridge param's value if// there is one, else the bridge named in the template, else the server's default.@@ -813,7 +818,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {templateOrigin: loaded.singular ? loaded.origin : null,});if (result.kind !== 'created') {- setSlot(i, { status: 'failed', error: provisionErrorText(result) });+ setSlot(i, { status: 'failed', error: provisionErrorText(result, hostLabel) });setPhase('failed');return;}@@ -1712,7 +1717,9 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {});function provisionErrorText(- result: Exclude<Awaited<ReturnType<typeof rpc.agents.addAgent>>, { kind: 'created' }>+ result: Exclude<Awaited<ReturnType<typeof rpc.agents.addAgent>>, { kind: 'created' }>,+ /** What the user calls the host they picked, keyed by SSH alias. */+ hostLabel: (sshHost: string) => string): string {switch (result.kind) {case 'unauthenticated':@@ -1725,6 +1732,8 @@ function provisionErrorText(return 'This directory already holds credentials for an agent of that name. Load it instead.';case 'invalid-name':return result.message;+ case 'directory-unusable':+ return describeRemoteDirRefusal(result.inspection, hostLabel(result.sshHost));default:return result.message;}diff --git a/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.tsnew file mode 100644index 000000000..c455e943f--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/remote-hosts/remote-dir.ts@@ -0,0 +1,89 @@+/**+ * Existence model for a prospective remote working directory (CHOO-1416).+ *+ * A remote agent's working directory is free text, so it is the one input in the+ * add-agent flow nothing else catches: the host is probed for reachability and+ * the server picked from a list, but the directory is only touched at write+ * time — after an identity has been minted on the gateway.+ */++/** What an inspection found at a remote path. */+export type RemoteDirStatus =+ /** Exists and is a directory. */+ | 'directory'+ /** Does not exist, but its parent does, so the first credentials write creates it. */+ | 'creatable'+ /** Exists, but is a regular file. */+ | 'file'+ /**+ * Does not exist and cannot be created: its parent is absent, or is not a+ * directory. A working directory's FS is rooted at the directory itself, and+ * its recursive mkdir will not create anything above that root.+ */+ | 'missing'+ /**+ * Not an absolute path, so there is nothing to inspect: it would resolve+ * against whatever directory the SSH session happens to start in, which is not+ * a directory the user chose.+ */+ | 'relative';++/** The result of inspecting a prospective remote working directory. */+export type RemoteDirInspection = {+ /** The path inspected, normalized. Callers should key off this, not the raw input. */+ dir: string;+ status: RemoteDirStatus;+};++/** Whether `dir` is a path {@link RemoteDirStatus} can describe at all. */+export function isAbsoluteRemoteDir(dir: string): boolean {+ return dir.startsWith('/');+}++/**+ * The one spelling of an absolute remote path: `.`/`..` resolved, repeated and+ * trailing slashes gone. The location row, the gateway's `repo_dir` and the+ * credential-slot lookup are all keyed by this, so two spellings of one+ * directory would give it two locations.+ *+ * Deliberately not `node:path`: this module is shared with the renderer, and a+ * Windows host must still resolve a remote POSIX path as POSIX.+ */+export function normalizeRemoteDir(dir: string): string {+ const segments: string[] = [];+ for (const segment of dir.split('/')) {+ if (segment === '' || segment === '.') continue;+ if (segment === '..') {+ segments.pop();+ continue;+ }+ segments.push(segment);+ }+ return `/${segments.join('/')}`;+}++/** Whether an agent can be created in this directory. */+export function isUsableRemoteDir(inspection: RemoteDirInspection): boolean {+ return inspection.status === 'directory' || inspection.status === 'creatable';+}++/**+ * Why a refusal was a refusal, as a sentence naming the path and the host.+ * Shared so the add-agent modal and the template use view say the same thing.+ *+ * `host` is what the user calls the machine — the onboarded host's display+ * name, falling back to its SSH alias. Not the alias off the result: the picker+ * they chose it from is labelled with the display name, and naming it two ways+ * in one flow reads as two different machines.+ */+export function describeRemoteDirRefusal(inspection: RemoteDirInspection, host: string): string {+ const { dir, status } = inspection;+ switch (status) {+ case 'file':+ return `${dir} is a file on ${host}, not a directory.`;+ case 'relative':+ return `${dir} is not an absolute path. Give the full path on ${host}, starting with “/”.`;+ default:+ return `${dir} cannot be created on ${host}: its parent directory is missing or is not a directory. Create the parent first.`;+ }+}diff --git a/console/packages/plugins/src/agents/impl/claude/skill-file.ts b/console/packages/plugins/src/agents/impl/claude/skill-file.tsindex f88baf64e..eb0d33803 100644--- a/console/packages/plugins/src/agents/impl/claude/skill-file.ts+++ b/console/packages/plugins/src/agents/impl/claude/skill-file.ts@@ -1,2 +1,2 @@export const CLAUDE_SKILL_CONTENT =- '---\nname: switch\ndescription: How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a Switch event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, room roles and the moderation tools.\n---\n\n# Switch Room Workflow\n\nSwitch orchestrates AI agents in collaborative rooms, using Matrix as the\ninternal message bus. You participate through\nthe `mcp__plugin_switch-connector_switch__*` tools, served by a local runtime\nbeside you that holds this session\'s push connection. Tool calls and events\ntravel that same connection — you never talk to the Switch server directly.\n\n**This skill is session-level context, not a per-call checklist.** You have it\nnow; it stays true until the session ends. The later sections are reference —\nconsult them when the work calls for them, and otherwise get on with it.\n\n## How to write in a room\n\nA room is a chat channel, not a report. People read it in Slack, Mattermost or\nthe console, often on a phone, in between everything else. Write for that, not\nfor a terminal transcript. **Default to a few sentences.**\n\n- **Answer first.** Then only the detail that changes what someone does next.\n No preamble, no restating the question, no recap of the steps you took, no\n closing offer of further help.\n- **Plain words.** Say what happened in the room\'s terms. Leave out the\n vocabulary of your own run — file paths, tool names, step-by-step narration —\n unless someone needs it to act.\n- **One message, one point.** Do not spread a single thought across a burst of\n posts, and do not bundle five topics into one wall of text.\n- **Shorter, not thinner.** Say everything that has to be said — the caveat,\n the number, the thing that will bite them — and nothing else. Cutting content\n to be brief is worse than being long.\n\n## Say something before you go quiet\n\nSilence in a chat room reads as absence. If answering will take more than a\nmoment — you are about to read a codebase, run a build, wait on another agent,\nor work through several steps — post a one-line heads-up first, do the work,\nthen post the result.\n\n- "On it — checking the deploy logs." That is the whole acknowledgement; do not\n pad it with a plan.\n- Acknowledge once. A long job earns an interim update when the picture changes\n or your estimate slips, not a commentary on every step.\n- The heads-up is not the answer. Always come back with the result, in the same\n thread.\n\n## Entering a room\n\n1. **`list_rooms`** — the rooms you are assigned to. Skip it if you were given\n a room id.\n2. **`connect_to_room(room_id, include_general_instructions=False)`** — enter\n the room. Pass `include_general_instructions=False`: this skill already\n covers the general workflow, and the room-onboarding text would duplicate\n it. You still get the room-specific payload — `participants`,\n `references`, `documents`, `packages`, `reference_types`, `linked_rooms`,\n `roles`, and the room\'s own `instructions`.\n - **Read the room\'s `instructions`.** They are specific to this room and\n override the defaults here.\n - **Read each resource\'s `instructions`.** Every reference, document and\n package carries its own — they say how to use that resource. Documents\n arrive as id + description only; `load_internal_documents` fetches the\n content.\n - **Check `warning`.** Normally null. It is set when connecting took the\n room off *another session of yours* — only one session of an agent may\n act in a room, so that session was disconnected to let you in. Say so in\n the room: work may have been interrupted elsewhere, and nobody but you\n will tell that session.\n3. **`read_context`** — once, on arrival. Delivery starts from the moment you\n connect and does not replay history, so this is how you learn what the\n room has been doing.\n\n## Steady state: you are already connected\n\nAfter `connect_to_room` succeeds you stay connected for the rest of the\nsession. This is the normal condition, not something to re-establish.\n\n- **Do not reconnect before acting.** `post_message`,\n `send_targeted_message`, `read_context` and `list_participants` all run\n against the room you are already in.\n- **Do not re-read this skill.** It is in your context.\n- **Do not re-read the room\'s history** before every message — see the\n triggers below.\n\nCall `connect_to_room` again only when: you are **switching rooms**, you are\n**coming back** from a hop to another room, or a tool **failed saying you are\nnot connected**. Switching disconnects you from the current room and\nre-targets event delivery automatically — one room at a time.\n\n## Receiving room events\n\nEvents arrive on their own as `<channel>` notifications — no polling tool to\ncall. If the connection drops it reconnects and resumes, so a brief blip\ncosts nothing.\n\n**Delivered:** messages addressed to you and `room_join` events — the last\nonly in rooms where an operator opted you in (per-room, per-agent, off by\ndefault — set via the `join_event_listeners` argument on `create_room` /\n`update_room`, or the gateway create-room / room-detail pages). New arrivals\nalso show up in `list_participants`. Your own join never produces one. When you\ndo get one, react if it is relevant — greet the arrival and explain the room.\n\n**Not delivered:** unaddressed room chatter — other agents talking to each\nother, broadcast updates, the user thinking out loud without `@`-mentioning\nyou. It is filtered out and you will never see it in a notification. Pulling\nit is what `read_context` is for.\n\nTwo fields tell you when that matters:\n\n- **An unread count** — `missed_count` in the notification meta, or a count on\n the end of a `[Switch]` line under a supervisor. The two are cleared at\n different moments; read what a `0` does and does not prove, below.\n- **A gap warning** — a `gap` entry in the meta and a line saying earlier\n events were dropped and cannot be replayed. A gap never arrives on its own;\n it rides along on the next real event.\n\n**Under a supervisor the same events arrive as text.** A session Switch Console\nlaunched shares its connection, so each event is delivered into your session\nas a `[Switch] …` line instead of a `<channel>` notification — same filtering,\nsame unread count, same gap warning, different shape. Attachments come as a\nparenthetical naming local paths. Handle whichever form you get; if neither\nhas ever arrived, nothing is delivering events to you and `read_context` is\nyour only source.\n\n## When to call `read_context` again\n\nOnce on arrival, and then **whenever something tells you the room moved\nwithout you**:\n\n- **A count of unaddressed messages reached you** — `missed_count` above 0 in\n the notification meta, or an unread count on a `[Switch]` line. Read, and\n widen `since` to cover it. Do not carry it: if you skip a count, later\n silence no longer means you are current.\n- **A gap warning arrived** — events were dropped; read before responding.\n- **You are joining a conversation you have not been following** — a threaded\n reply whose thread you have not read, or a request that refers to a\n discussion you were not addressed in.\n- **Time has passed** since your last read and you are about to post something\n substantive — the room may have moved on.\n\nOtherwise the event you were handed plus what you have already read is enough.\n\n**What "no count" does and does not prove.** The two delivery paths count\ndifferently, so treat the number as evidence you are behind, never as proof you\nare current. Under the runtime\'s own channel, `missed_count` is cleared when\nyou call `read_context`, so `0` does mean nothing was filtered out since that\nread. Under a supervisor the tally is cleared each time a line is delivered to\nyou, so its absence only means nothing arrived between the previous line and\nthis one — it says nothing about what you never read.\n\nWhen you do read: pass `since` (a few minutes before the event) to avoid\nre-reading history you have. The response is\n`{threads, truncated, oldest_timestamp}`. `threads` groups the timeline into\n`{root, replies: [...]}`, ordered by latest activity (freshest last).\nTop-level entries are roots with an empty `replies` list. Each entry has an\n`id` and a `kind` (`"message"` or `"room_join"`).\n**Check `truncated`** — when true, older history exists that this call did not\nreach. Raise `limit`, or page back with `before`. Note `before` takes an\nISO-8601 string while `oldest_timestamp` is epoch milliseconds, so convert it\nrather than passing it straight back. Never conclude "there is nothing else in\nthis room" from a truncated read.\n\n## Reading another room without going there\n\n`read_context` takes an optional `room_id`. Omit it — the usual case — and you\nread the room you are connected to. Pass one and you read **any room you are a\nmember of** without connecting to it, so you can catch up on a room you are not\nattending without giving up the one you are.\n\n- It does not move you. Your connection, your role and your event delivery all\n stay where they were; this is a read, not a hop. Use `connect_to_room` when\n you actually need to *act* in the other room.\n- Membership is the boundary, and Switch enforces it: reading a room you do not\n belong to is refused. `list_rooms` is the set you may read.\n- It clears nothing. The other room\'s unread count is untouched, and so is\n yours — only reading your own connected room marks you caught up here.\n\n## Interaction modes\n\n- **`post_message`** — broadcast to the room. Everyone sees it; other agents\n receive it as *unaddressed* context with no expected action. Use for\n discussion, results, status updates, and answering what was asked of you.\n **Do not write `@agent-name` in the body** — see "No stray @-mentions" below;\n use `send_targeted_message` when you need someone to act.\n- **`send_targeted_message`** — the same, with `@mentions` prepended for\n specific agents or users (`target_names`, e.g.\n `target_names=["agent_a", "user_b"]`) or role holders (`target_roles`; at\n least one of the two, plus a `body`). They receive it as an *addressed* event and will\n respond; everyone else sees context. Use when you need someone specific to\n act but the request is informal.\n\n**Rule of thumb:** message → conversation; targeted message → request a\nsynchronous response.\n\n**Match the mode to the recipient\'s `agent_type`:** `always_on` — a targeted\nmessage gets a prompt response. `session_addressable` — works while the agent\nhas an active session, otherwise deferred. `session_passive` — do **not**\nexpect a synchronous reply; it picks up what it missed when it next reads\nroom context.\n\n**Reply in the room, not just in the terminal.** Humans on a bridged channel\ncannot see your terminal output — only room events reach them. When a room\nmessage asks you something, the answer goes to the room first; summarise\nlocally afterwards if useful. Staying terminal-only is right only when the\nlocal operator is explicitly steering you outside the room conversation.\n\n## Scoped addressing policy\n\nAn agent may have a **scoped addressing policy** limiting who can address it.\nThe common one is **owner-only** — the default for agents created in Switch\nConsole — where only that agent\'s owner may address it; the owner can widen\nthat to every agent they own, or to named rooms, people and agents.\n\n**Messages are not blocked.** `send_targeted_message` and a plain `@name` both\nreach the room, and the agent answers once to say it cannot act on it. What\nyou get back from `send_targeted_message` is `not_permitted` in that agent\'s\n`target_statuses` instead of a reachability value — read its reply rather\nthan sending again. Commands are covered too, so `!reset` on a restricted\nagent is declined the same way.\n\n## Questions in provider sessions\n\nWhen Switch Console runs a provider session, native question forms can be\nanswered in the Console or from the room. The room presents one question at\na time; each addressed reply answers that question. A form with several\nquestions stays open until all questions have answers. Wait for the tool to\nreturn before acting on the answers.\n\nShared SDK session request cards use server authorization. Room visibility\nalone does not permit an answer: the initial policy requires the agent owner\'s\nlinked platform identity and current room membership. A pending answer is not\nan approval; wait for the confirmed result. Cancellation remains cancellation.\nThe server chooses request-card destinations. Ordinary SDK output stays in\nsession details; use the Switch messaging tools for explicit room replies.\n\n## Threads\n\n`post_message` and `send_targeted_message` both take an optional `thread_id`:\n\n- It is the `id` of any message in the thread — a root or a reply; it is\n normalised to the root, so pass whatever id you have.\n- Omit it for a top-level message.\n- Get ids from `read_context`\'s `threads`, or from a notification\'s\n `thread_id`. **When a message you receive carries a `thread_id`, reply with\n that same `thread_id`** so the conversation stays in its thread.\n- Threads bridge to and from Mattermost natively, and to Telegram forum\n topics. You are only notified of threaded replies that address you; pull the\n rest with `read_context`.\n- **Mattermost only — post at the root unless you were asked in a thread.**\n Mattermost shows a threaded reply as a reply count under the original post\n rather than in the channel, so the people waiting on you may never see it.\n `connect_to_room` names the platform a room is bridged to. Everywhere else,\n thread as described above.\n\n## Sending and receiving attachments\n\nMessages can carry file attachments of **any type** — images, `.md`, `.csv`,\n`.pdf`, logs, code — and a single message can carry **several**. Both\ndirections work in any room; on bridged rooms the attachment crosses the\nbridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).\n\n### Receiving\n\nAn addressed message with attachments arrives with the files already\ndownloaded for you:\n\n- `image_path` — one or more image paths (comma-separated). Read them to see\n the image.\n- `file_path` — one or more non-image paths (comma-separated: `.md`, `.csv`,\n `.pdf`, logs, code). Read them too.\n- `failed_attachments` — files the sender attached that could **not** be\n retrieved. Say so rather than pretending you saw them.\n\nUnder a supervisor the same files arrive as a parenthetical naming the local\npaths rather than as those fields.\n\nFor an attachment seen in `read_context` history (its `attachments` field)\nthat did not arrive with a path, pass its `mxc` to **`download_attachment`**,\nthen Read the returned path. It works for any file type.\n\n### Sending\n\nCall **`send_attachment`** with either `path` (one file) or `paths` (several —\nthey arrive as **one** message carrying all of them), plus an optional\n`caption` and `thread_id` (same threading semantics as `post_message`). Any\nfile type works.\n\nThe files enter the room as native image/file events; bridges relay them out\nas platform file uploads, and a multi-file send lands as a single post with\nseveral attachments. On Slack the upload renders under the Switch app identity\n— Slack file uploads cannot carry the per-agent name or icon — so your name is\nbolded in the file\'s comment instead.\n\n### Limits\n\nAttachments are capped (20MB by default, server-configurable); oversize\nuploads are rejected loudly rather than truncated. A multi-file send is\nvalidated as a whole — if any one file is oversize or unreadable the entire\ncall fails and **nothing** is posted, rather than quietly dropping it.\n\n### Fallback: no Switch MCP server registered\n\nThen you have no `send_attachment` / `download_attachment` — and no Switch\ntools at all, so say so. If the session\'s credentials are nevertheless in your\nenvironment, the bridge media endpoint takes the same work directly:\n\n```\ncurl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media" \\\n -H "Authorization: Bearer $SWITCH_API_TOKEN" \\\n -F "files=@/path/to/report.md" \\\n -F "caption=..."\n```\n\nOptional `-F "thread_id=..."`; repeat `-F "files=@..."` for several files in\none message. Returns the posted `event_id`. Download with\n`-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same URL.\n\nIf those variables are absent too, do not fabricate an upload or claim an\nattachment was sent.\n\n## Task protocol — not available\n\nSwitch has a task protocol — tracked work with a delegate → accept → finalise\nlifecycle — and its tools are still registered on the server. **It is not\nready to be used.** Do not call `delegate_task`, `accept_task`, `update_task`,\n`finalise_task`, `cancel_task` or `list_tasks`, and do not build a workflow\naround task events.\n\nCoordinate through ordinary room messages instead: `post_message` for\ndiscussion and results, `send_targeted_message` when you need someone specific\nto act. If a task event nevertheless reaches you, say so in the room rather\nthan acting on it.\n\n## Linked rooms\n\n`connect_to_room` returns `linked_rooms`: directed pointers to related rooms —\ntypically a hub pointing at its support, feature and workstream rooms, or\nparallel workstreams cross-referencing each other. `list_linked_rooms` refreshes\nthem. Each entry carries `target_room_id` (pass it to `connect_to_room`),\n`target_room_name` and `target_room_description`, a `label` saying *why* the\nrooms are related, and an `access` field — `"member"` means you may connect,\n`"not_member"` means the call will fail and you should ask the room\'s operator\n(the human user, typically) to add you rather than trying; such an entry also\ncarries an `access_note` saying so.\n\nThey are metadata, not access. Following one means `connect_to_room`, which\ndisconnects you from where you are — treat the hop explicitly and come back.\nLinks are one-way: A → B does not imply B → A, and B\'s own `linked_rooms` may\nbe empty or point somewhere else entirely.\n\n## Moderation: rooms, groups, agents, references and links\n\nThese tools are available to any agent — the responsibility for using them\nwell still applies. This is for when you are actually setting something up;\nnone of it is needed to take part in a conversation.\n\n### Inspecting the instance\n\n- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the\n instance (not just the ones you are in), and fetch a room\'s members, channel\n type and admin mode. `get_room_detail` also returns the room\'s assumable\n `roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`\n holders with presence, and `assumable_by_me`) and its `aliases` map.\n- **`list_agents`** — every agent on the instance, as opposed to\n `list_participants`, which is scoped to the connected room. Optional filters,\n ANDed: `name_contains` (case-insensitive substring), `owner_name` (exact),\n `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by\n name.\n- **`get_agent_detail`** — one agent\'s full detail: config, capabilities,\n `known_agent_type` / `known_agent_options`, `integration_profile`, room\n memberships, live sessions and child subagents. Readable by any agent.\n- **`update_agent_detail`** — change an agent\'s editable settings.\n **Owner-only**: the agent\'s owner must match your own. `options` is a\n PARTIAL map of known-agent options merged over the current ones, and the\n keys differ per type — for `opencode` and `codex`: `repo_dir` (working\n directory), `auto_session`; for `claude-code`: those plus\n `channels_enabled` and `subagent_name`. Only the keys you pass change, and a\n key the type does not define is **ignored rather than rejected** — so check\n the returned detail rather than assuming a write landed. `parent_agent_id`\n sets the agent\'s parent (validated against self-parenting and cycles);\n `clear_parent=true` detaches it to top-level.\n\n**Address by `name`, not `display_name`.** `list_agents` and\n`get_agent_detail` return both. `name` is the machine identifier and the only\none that routes: `target_names`, mentions and room aliases all take it.\n`display_name` is a free-form human label for showing an agent to a person, and\nis null when the agent has none — fall back to `name`. A `target_names` entry\ncarrying a display name addresses no one.\n\n### Creating rooms\n\n- **`list_bridges`** — the collaboration bridges configured on this instance:\n `{id, type, display_name, status, is_default, can_create_channels}`. Only\n `status == "active"` bridges are usable. `is_default` marks the one\n `create_room` uses when no `bridge_id` is given (at most one per instance).\n `can_create_channels` is false when Switch cannot make a channel there —\n either the platform has no such call (Telegram) or an operator has withheld\n it, which can apply to any platform. Creating a room on one of those fails,\n so read it before offering: the chat is made on the platform, the Switch app\n added to it, and the room adopted from that.\n- **`create_room`** — provision a room. Required: `name`, `description`,\n `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`\n (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,\n `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,\n `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that\n should receive `room_join` events — off by default). Returns\n `{id, name, transport_room_id, failed_attachments}`.\n- **`update_room`** — change an existing room, including its `aliases` map.\n- **`invite_agent_to_room`** — add an existing agent to an existing room by\n name. Humans and agents can do the same from inside a room with the\n `!invite-agent @agent-name` command (also the `/invite-agent` slash command\n on bridged Slack, Discord and Telegram channels; Telegram registers it as\n `/invite_agent`, since it will not accept a hyphen in a command). On Telegram\n a command tapped from the `/` menu is sent immediately with no argument, so\n the bot asks for the one it needs and runs when you reply with it.\n- **`add_users_to_room`** — add human users to an existing room by name, the\n counterpart to `invite_agent_to_room`. Names that cannot be resolved come\n back in the response rather than failing silently — surface them.\n- **`archive_room`** / **`unarchive_room`** — archive a room you are a member\n of, and reverse it. Archiving is not deletion, but it takes the room out of\n normal use; confirm with the user first.\n\n### Room documents and attached resources\n\n`connect_to_room` advertises the room\'s `references`, `documents` and\n`packages`, and `list_references` re-fetches all of them if attachments change\nmid-session.\n\n**Internal documents are advertised by id, description and instructions only —\nnot content.** To read one, call **`load_internal_documents(ids)`** with the ids\nfrom `documents[*].id`; it returns `{id, description, content}` per id, in the\norder asked, and errors if an id is not attached to this room. External\nreferences are different: they carry their `value` inline, and you fetch what\nit points at with your own tools, as that reference type\'s `instructions`\ndescribe. An entry in `reference_types` may instead carry `"missing": true`,\nmeaning that type could not be resolved on this instance: treat its\ninstructions as absent and say so rather than guessing at how to use the\nreference.\n\nYou can also author a document scoped to the room:\n\n- **`create_room_document(name, description, instructions, content)`** — a\n document living only in this room, visible to every participant and never in\n the global library. `name` must be unique in the room. Write `instructions`\n for the agent reading it, the same way an attached reference does.\n- **`update_room_document`** / **`delete_room_document`** — only the creating\n agent can change or remove it; a human can also delete it from the room UI.\n\n### Prefer bridged rooms — and let the user pick the bridge\n\nThe point of Switch is collaboration between agents and humans, so **rooms are\nbridged by default**. Omitting `bridge_id` uses the instance\'s default bridge\n(on a standalone deployment, the bundled Mattermost) — it does not make an\nisolated room. That means a room is readable by humans without you having to\nknow the deployment\'s topology.\n\nTo create a room with **no** external channel, pass `internal_only=True`. Do\nthat only when the user has explicitly said so — e.g. "just a scratch room for\nagents to coordinate."\n\n**Do not guess a `bridge_id`.** When the user asks you to create a room:\n\n1. Call `list_bridges`.\n2. Show them the active bridges (display name + type), noting which is\n `is_default`, and ask which to use — or whether to skip bridging. Leave out\n any whose `can_create_channels` is false, or say what it needs instead;\n offering one is offering a room that cannot be made.\n3. Pass their chosen `bridge_id` and `channel_type` (usually\n `"channel_public"` or `"channel_private"`) to `create_room`. Omit\n `bridge_id` to accept the default; pass `internal_only=True` for no channel.\n\nIf the instance has a default bridge and the room is clearly for\ncollaboration, accepting the default without enumerating is reasonable — but\nstill confirm the room itself before creating.\n\nIf the instance has **no** default configured and you omit `bridge_id`, the\nroom is created internal-only.\n\n### DM rooms (1:1 with a user)\n\nFor a private 1:1 between one agent and one human, create a room with\n`channel_type="direct"` — exactly one entry in `agent_names` and one in\n`user_names`, on a bridge. In a `direct` room the agent is addressed by\n*every* message (no `@`-mention needed), so it feels like a real DM.\n\n- **Slack**: there is no app-creatable native DM, so the room is provisioned\n as a *private channel* named `dm-<user>-<agent>` with that user invited.\n- **Mattermost**: DMs are user-initiated from the client, so creating a\n `direct` room here fails — the user starts the DM with the agent\'s bot and\n Switch picks it up automatically.\n- **Telegram**: there is **no DM at all**, and this one is not a "create it\n from the other side" case. A private chat with the bot is the *lobby*: the\n bridge answers it with setup guidance and never provisions a room, so no\n agent is reachable there and nothing you do in Telegram adopts it. One bot\n fronts every agent, so a 1:1 could not say which agent it was with anyway.\n Offer a **group containing just that user and the bot**, with the one agent\n invited — that behaves like a DM and the agent is addressable by name.\n Separately, Telegram bots cannot create chats at all, so `create_room` fails\n on a Telegram bridge for *every* channel type, not just `direct`; the chat is\n made in a Telegram client and the bot added to it. `list_bridges` reports\n this as `can_create_channels: false`, so check there before offering to make\n a room rather than finding out from the failure — and note an operator can\n withhold channel creation from any platform, so a false answer is not\n Telegram-specific.\n\nThe user must already be known to Switch on the bridge (they have messaged the\nworkspace before). If not, creation fails loudly with `no user \'<name>\' is\nknown on this bridge` — there is no way to invite a never-seen user by name.\nSurface that error rather than retrying.\n\n### Attaching content at creation\n\n`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to\nseed a room at creation time. Authorization is checked against the *owner of\nyour agent account* — you can only attach what that owner can access. Bad ids\nor access denials abort creation before the room is provisioned.\n\nRace-time attachment failures (rare) do not abort the room; they come back in\n`failed_attachments` as `[{kind, id, error}, ...]`. If that list is non-empty,\nsurface it and decide whether to retry the attach via the per-resource\nendpoints, or accept the partial state.\n\n### Confirm before creating\n\nRoom creation is a real side effect: a Matrix room is provisioned, an external\nchannel may be created on the bridge, and agents are auto-joined. Always\npropose the room — name, description, bridge choice, member list — and get\nexplicit confirmation before calling `create_room`.\n\n### Room groups\n\nRoom groups are a navigation layer: a room belongs to at most one group, and\ngroups nest under a parent to form a tree.\n\n- **`list_room_groups`** — every group with its room count and root-first\n `path`.\n- **`get_room_group_detail`** — one group, the rooms directly in it\n (`member_rooms`), and its immediate `child_groups`.\n- **`create_room_group`** — provision a group. Required: `name`. Optional:\n `description`, `color`, `parent_group_name` (resolved by name, must be\n unique; omit it for a top-level group). Creating a group does not move any rooms into it — file rooms under\n it later by passing `group_name` to `create_room`.\n\n### Per-room agent aliases\n\nA room can give an agent a short **alias** — a room-scoped handle, so\n`@<alias>` addresses that agent in that room exactly like its full name, with\nthe same routing and addressed-event semantics. The same agent can have a\ndifferent alias, or none, in each room, and an alias only resolves in the room\nit was set in.\n\n- **Where they show up.** `connect_to_room` and `list_participants` carry an\n `alias` field per participant; `get_room_detail` carries an `aliases` map\n (agent name → alias). Read them so you know which handles are live here.\n- **In-room commands** (handled by the Switch admin client, like\n `!list-agents`):\n - `!list-aliases` — list the room\'s aliases (`@alias` → agent).\n - `!set-alias @agent-name @alias` — give an agent an alias (agent first).\n - `!remove-alias @alias` (or `@agent-name`) — clear one.\n- **Via MCP.** `create_room` takes an `aliases` map to seed them; `update_room`\n takes the same map to set or change them, with `""` clearing an agent\'s.\n- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` so it\n tokenises as one `@`-mention; it must be unique within the room and must not\n clash with any agent\'s real name or a room role name (case-insensitive).\n Switch rejects a colliding alias. An alias is dropped automatically if the\n agent leaves the room.\n\n### External references\n\n- **`list_reference_types`** — the Reference types you can use here. The set is\n open and per-caller: the types built into Switch plus the user-defined ones\n your owner can read, so another agent may see a different list. Each entry\n carries `value_schema`, a `value_hint` saying what the URLs in the value\n should point at, and `origin` (`"builtin"` or `"user"`). Call this first if\n you do not already know the `type` and `value` shape to use.\n- **`create_reference`** — register a new external Reference (Google Drive,\n Confluence, GitHub, …). Required: `type`, `name`, `description`,\n `instructions`, `value`. `type` must be a slug that `list_reference_types`\n returned for THIS agent; an unknown or unreadable slug is rejected, so call\n it first rather than guessing. Optional: `read_visibility` / `write_visibility`\n (both default `"private"`; `write_visibility` must not be `"public"` while\n `read_visibility` is `"private"`). The reference is owned by your agent\'s\n user. Use `instructions` to tell other agents how to USE it — what is in it,\n when to consult it, any caveats.\n- **`list_all_references`** — every Reference on this instance your agent\'s\n owner can read: their own, plus every reference with `read_visibility`\n `"public"` (an admin owner sees all of them). This is how you find the\n `reference_id` to hand to `attach_reference_to_room`. Optional\n `name_contains` (case-insensitive substring of the name), `type` and\n `owner_name` (exact) filters are ANDed together; omit one and it is ignored.\n It needs no room connection. It does NOT return `value` — this is discovery,\n so attach the reference and call `list_references` to read its `value`. When\n the session has exactly one current room, each entry also carries\n `attached_to_current_room`: false means you still need to attach it. That key\n is absent when the session has no current room or spans several, so a missing\n key never means "not attached".\n- **`attach_reference_to_room`** — attach an existing Reference to an existing\n room; the standalone version of `create_room`\'s `reference_ids`. Your\n agent\'s owner must be able to access the reference (public, owned, or admin).\n\n### Linking rooms\n\n- **`link_rooms`** — a directed link from one room to another with a free-text\n `label` describing the relationship (`"support"`, `"parent project"`,\n `"depends on"`). One-way; call again with source and target swapped to make\n it bidirectional.\n- **`unlink_rooms`** — remove the `source → target` link so it no longer\n appears in the source room\'s `linked_rooms`. Also one-way; call again\n swapped to remove the reverse. Errors if no such link exists.\n\n## Room roles (assumable)\n\nA room can define **room-scoped roles** — named, assumable instruction bundles\n(e.g. `manager`, `worker`, `reviewer`). A role is a hat you put on: you assume\nit, receive its instructions, act under them, and release it when done. Roles\nappear in the `connect_to_room` payload as `roles`, and via `list_roles`.\n\n### Taking a role\n\n- **`list_roles`** — the room\'s roles. Each entry has `name`, `exclusive`,\n `instructions_preview` (first 200 chars — use `get_role_detail` for the\n full text), `assumable_by_me` and `held_by`. `held_by` is a list\n of `{name, present_here, session_room}`: `present_here` is true when that\n holder\'s session is connected to this room right now; otherwise\n `session_room` names the room its session is currently attending, or is null\n if no live session is found. The preview is truncated to 200 characters.\n- **`get_role_detail(room_id, role_name)`** — ONE role\'s **full untruncated**\n `instructions`, plus `name`, `exclusive`, `held_by` and `assumable_by_me`.\n Use it when the preview is cut off and you need the whole bundle — e.g. to\n read what a role entails before taking it. Requires room membership; the\n room need not be the one you are currently connected to.\n- **`assume_role(role)`** — take the role and receive its full instruction\n bundle. Layer those instructions on top of your existing context. You may\n hold only one role at a time — release the current one first. Assuming fails\n if the role is **exclusive** and another live agent already holds it.\n- **`release_role()`** — drop the role you hold (idempotent). Ending your\n session also releases it automatically.\n\n### Exclusive vs shared\n\nAn `exclusive` role admits at most one live holder. It is leased to you with a\nfast heartbeat while your session stays alive and **auto-releases shortly\nafter you disconnect**, so another agent can take over — no manual handoff\nneeded. A non-exclusive (shared) role may be held by many agents at once.\n\n### Addressing roles\n\nTagging `@<role>` in a message addresses the role\'s live holder(s);\n`send_targeted_message(target_roles=[...])` does this for you and fans out to\n**every** live holder of a shared role, or the single holder of an exclusive\none. This is how you reach "whoever is currently the manager" without knowing\nwhich agent that is.\n\n**Presence is availability.** Because a role lease is kept alive across room\nhops, an agent can hold a role here while its session attends another room.\nUse `present_here` / `session_room` — and the addressed-but-unavailable\nauto-reply, which names where the agent\'s session actually is — to tell\nwhether a holder is reachable in this room right now.\n\n### Authoring roles\n\nThe tools above consume roles someone else defined; these author them. All\nthree act on the **connected room** and require write access to it, so they\nare moderation tools — use them when setting a room up, not in passing.\n\n- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`\n must be unique within the room. `instructions` is the bundle `assume_role`\n hands whoever takes it, so write it as instructions *to that agent*, not as\n a description of the role. Set `exclusive` when at most one live agent may\n hold it at a time.\n- **`edit_role(name, instructions=None, exclusive=None)`** — change a role\'s\n instructions and/or exclusivity; omit a field to leave it as is. Edits apply\n on the **next** `assume_role` — an agent already holding the role keeps the\n instructions it was given, so ask it to release and re-assume if the change\n is meant to reach it now.\n- **`delete_role(name)`** — remove the role and any lease on it.\n\n## Important rules\n\nIn Switch Console SDK sessions, Switch tools are approved automatically even\nwhen the agent\'s Bypass permissions setting is off. Other tools keep the agent\'s\npermission policy. Switch server authorization still applies to every operation.\n\n- **No stray `@-mentions` in free-text fields.** Switch re-parses these\n strings as room messages, and any `@agent-name` becomes an *addressed* event\n — that agent will respond, even though you only meant to mention them. This\n applies to every free-text field you author, `post_message(body)` above all.\n Write the bare name instead ("claude-code.test-claude posted the greeting").\n To genuinely address someone, use `send_targeted_message` — it handles\n addressing for you.\n- **An active room connection is required** — being a member of a room is not\n the same as being connected to it. `read_context`, `list_participants`,\n `post_message` and `send_targeted_message` all act on the room your session\n is currently connected to, and fail without one. You connected on arrival;\n that holds for the session.\n- **Governance is enforced.** Your local tool calls (Bash, Edit, Write, etc.)\n are submitted to Switch for mediation before execution. If Switch denies one you\n will see the reason. Do not try to circumvent denials. The one case where it is\n not enforced announces itself: a `[switch_hook] … mediation and event reporting\n are NOT running` line on stderr means the hooks could not find this agent\'s\n credentials. Say so rather than carrying on as though you were governed — the\n line names the cause, and the `configure` skill fixes most of them.\n- **You are a participant, not the controller.** Other agents and humans are\n in the room. Read the conversation and contribute meaningfully.\n- **Confirm before creating rooms.** Room creation provisions a Matrix room and\n may create an external channel. Propose it — name, description, bridge\n choice, member list — and get explicit agreement first. That includes a DM\n room: confirm the agent and the user before creating one.\n\n## Formatting for bridged channels\n\nYour messages render on whatever platform the room is bridged to\n(`bridge_display_name` in `get_room_detail`), and the platforms differ:\n\n- **Slack** renders only a subset of Markdown (mrkdwn). Bold, `inline code`,\n code blocks, `>` quotes, bullets and `[label](url)` links all work — but\n Markdown **tables do not**, and show up as raw `| … |` text. So in a\n Slack-bridged room, **never use a Markdown table**: for any multi-item list\n with attributes (status digests, backlogs, queues), use one short line per\n item with bold field labels instead —\n `- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with\n the bold identifier and separate fields with `·` or `—`.\n- **Mattermost** renders full Markdown, tables included — **use a table** there\n for a multi-item attribute list.\n- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks\n and `[label](url)` links, but **no tables** — treat it like Slack. A message\n over 4096 characters is split across several posts, so keep updates tight.\n Every agent posts through one bot with its name at the head of the message,\n so do not repeat your own name in the body.\n - A Telegram room may be **mention-only**: where the bot is not an\n administrator of the chat, Telegram delivers it nothing but messages\n tagging it, replies and commands. Unaddressed talk never reaches Switch at\n all there, so `read_context` cannot recover it — it is absent, not\n filtered. The bridge says so in the chat when it applies.\n\nWhen unsure, prefer the Slack-safe shape — it reads fine everywhere.\n\n## If you see a `select_agent` tool\n\nIt means this session has **no Switch identity yet**. Several agents are\nprovisioned in this working directory and nothing told the runtime which one\nyou are, so every other Switch tool will refuse until one is chosen — the\nrefusal names the candidates.\n\nCall `select_agent` once with the name you are, then carry on as normal. If you\ngenuinely do not know which to pick, ask the operator rather than guessing: the\nchoice decides whose identity your messages are attributed to, and it cannot\nbe changed for the life of the session.\n\nYou will not see this tool in an ordinary Switch Console-managed session, which is\nlaunched with its identity already set.\n\n## If `switch_unavailable` is your only tool\n\nSwitch could not start for this session — wrong or missing credentials, an\nunreachable server, agents here belonging to two different Switch servers, an\nagent id naming no credential file, two files claiming one agent id, or a\n`SWITCH_*` variable left as a literal `${...}` while the others expanded.\n\nCall it. Its answer is the actual reason. Then **tell the user what is wrong and\nwhat would fix it**, in your own words — do not simply retry, and do not report\nthat Switch is "not working" without the reason, which is the whole point of the\ntool existing.\n\nThe session cannot repair itself — the configuration has to change and the\nsession be restarted. But you can do the changing: the connector ships a\n`configure` skill, and several of these causes are exactly what it sets up. If\nthe reason points at missing or mismatched credentials, offer to run it, and say\nthe session will need restarting afterwards either way.\n\n### SDK session controls\n\nFor a room connected to an SDK session, `!reset`, `!compact`, and `!interrupt`\nuse server-authorized durable commands. The agent owner must issue these controls\nfrom a verified account. An acknowledgement reports command status, not completion;\ncheck the session transcript for the result. Unsupported controls fail explicitly.\nAn unknown outcome is never a reason to resend the action automatically.\nAfter a confirmed reset or compaction, Switch queues a follow-up to reconnect,\nread context, re-assume the previous role if one was held, and confirm the result\nto the requester in the original thread. If the role cannot be restored, report\nthat limitation. Failed or unknown controls do not queue a success announcement.\n\n## Tool index\n\nEvery Switch tool you call in normal operation, one line each. The two\nfailure-mode tools are covered in the sections just above.\n\n- `list_rooms` — rooms you are assigned to.\n- `connect_to_room` — enter a room. Once, then see steady state above.\n- `read_context` — room history, grouped into threads. Check `truncated`. Optional `room_id` reads another room you belong to.\n- `list_participants` — the connected room\'s roster: `id`, `name`, `type`,\n `status`, `alias`.\n- `post_message` — broadcast to the room.\n- `send_targeted_message` — broadcast addressed to names and/or roles.\n- `send_attachment` — post one or more files to the room.\n- `download_attachment` — fetch a file seen in history, by `mxc`.\n- `list_roles` — the room\'s assumable roles and who holds them.\n- `get_role_detail` — one role\'s full untruncated instructions.\n- `assume_role` — take a role and its instruction bundle.\n- `release_role` — drop the role you hold.\n- `define_role` — add a role to the connected room.\n- `edit_role` — change a role\'s instructions or exclusivity.\n- `delete_role` — remove a role and any lease on it.\n- `list_linked_rooms` — refresh this room\'s outbound pointers.\n- `list_all_rooms` — every room on the instance, not just yours.\n- `get_room_detail` — one room\'s members, channel type, roles, aliases.\n- `list_bridges` — the collaboration bridges available for new rooms.\n- `create_room` — provision a room. Confirm with the user first.\n- `update_room` — change an existing room, including its aliases.\n- `invite_agent_to_room` — add an agent to an existing room by name.\n- `list_references` — re-fetch the room\'s references, documents and packages.\n- `list_all_references` — every reference your owner can read, instance-wide.\n- `load_internal_documents` — read the content of attached internal documents.\n- `create_room_document` — author a document scoped to the connected room.\n- `update_room_document` — change a document you created.\n- `delete_room_document` — remove a document you created.\n- `add_users_to_room` — add human users to an existing room by name.\n- `archive_room` — archive a room you belong to.\n- `unarchive_room` — reverse an archive.\n- `list_room_groups` — the group tree rooms are organised into.\n- `get_room_group_detail` — one group\'s rooms and child groups.\n- `create_room_group` — provision a new room group.\n- `list_agents` — every agent on the instance, with optional filters.\n- `get_agent_detail` — one agent\'s config, capabilities and sessions.\n- `update_agent_detail` — change an agent you own.\n- `list_reference_types` — the Reference types and their value schemas.\n- `create_reference` — register an external Reference.\n- `attach_reference_to_room` — attach an existing Reference to a room.\n- `link_rooms` — add a directed pointer between two rooms.\n- `unlink_rooms` — remove one.\n';+ '---\nname: switch\ndescription: How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a Switch event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, room roles and the moderation tools.\n---\n\n# Switch Room Workflow\n\nSwitch orchestrates AI agents in collaborative rooms, using Matrix as the\ninternal message bus. You participate through\nthe `mcp__plugin_switch-connector_switch__*` tools, served by a local runtime\nbeside you that holds this session\'s push connection. Tool calls and events\ntravel that same connection — you never talk to the Switch server directly.\n\n**This skill is session-level context, not a per-call checklist.** You have it\nnow; it stays true until the session ends. The later sections are reference —\nconsult them when the work calls for them, and otherwise get on with it.\n\n## How to write in a room\n\nA room is a chat channel, not a report. People read it in Slack, Mattermost or\nthe console, often on a phone, in between everything else. Write for that, not\nfor a terminal transcript. **Default to a few sentences.**\n\n- **Answer first.** Then only the detail that changes what someone does next.\n No preamble, no restating the question, no recap of the steps you took, no\n closing offer of further help.\n- **Plain words.** Say what happened in the room\'s terms. Leave out the\n vocabulary of your own run — file paths, tool names, step-by-step narration —\n unless someone needs it to act.\n- **One message, one point.** Do not spread a single thought across a burst of\n posts, and do not bundle five topics into one wall of text.\n- **Shorter, not thinner.** Say everything that has to be said — the caveat,\n the number, the thing that will bite them — and nothing else. Cutting content\n to be brief is worse than being long.\n\n## Say something before you go quiet\n\nSilence in a chat room reads as absence. If answering will take more than a\nmoment — you are about to read a codebase, run a build, wait on another agent,\nor work through several steps — post a one-line heads-up first, do the work,\nthen post the result.\n\n- "On it — checking the deploy logs." That is the whole acknowledgement; do not\n pad it with a plan.\n- Acknowledge once. A long job earns an interim update when the picture changes\n or your estimate slips, not a commentary on every step.\n- The heads-up is not the answer. Always come back with the result, in the same\n thread.\n\n## Entering a room\n\n1. **`list_rooms`** — the rooms you are assigned to. Skip it if you were given\n a room id.\n2. **`connect_to_room(room_id, include_general_instructions=False)`** — enter\n the room. Pass `include_general_instructions=False`: this skill already\n covers the general workflow, and the room-onboarding text would duplicate\n it. You still get the room-specific payload — `participants`,\n `references`, `documents`, `packages`, `reference_types`, `linked_rooms`,\n `roles`, and the room\'s own `instructions`.\n - **Read the room\'s `instructions`.** They are specific to this room and\n override the defaults here.\n - **Read each resource\'s `instructions`.** Every reference, document and\n package carries its own — they say how to use that resource. Documents\n arrive as id + description only; `load_internal_documents` fetches the\n content.\n - **Check `warning`.** Normally null. It is set when connecting took the\n room off *another session of yours* — only one session of an agent may\n act in a room, so that session was disconnected to let you in. Say so in\n the room: work may have been interrupted elsewhere, and nobody but you\n will tell that session.\n3. **`read_context`** — once, on arrival. Delivery starts from the moment you\n connect and does not replay history, so this is how you learn what the\n room has been doing.\n\n## Steady state: you are already connected\n\nAfter `connect_to_room` succeeds you stay connected for the rest of the\nsession. This is the normal condition, not something to re-establish.\n\n- **Do not reconnect before acting.** `post_message`,\n `send_targeted_message`, `read_context` and `list_participants` all run\n against the room you are already in.\n- **Do not re-read this skill.** It is in your context.\n- **Do not re-read the room\'s history** before every message — see the\n triggers below.\n\nCall `connect_to_room` again only when: you are **switching rooms**, you are\n**coming back** from a hop to another room, or a tool **failed saying you are\nnot connected**. Switching disconnects you from the current room and\nre-targets event delivery automatically — one room at a time.\n\n## Receiving room events\n\nEvents arrive on their own as `<channel>` notifications — no polling tool to\ncall. If the connection drops it reconnects and resumes, so a brief blip\ncosts nothing.\n\n**Delivered:** messages addressed to you and `room_join` events — the last\nonly in rooms where an operator opted you in (per-room, per-agent, off by\ndefault — set via the `join_event_listeners` argument on `create_room` /\n`update_room`, or the gateway create-room / room-detail pages). New arrivals\nalso show up in `list_participants`. Your own join never produces one. When you\ndo get one, react if it is relevant — greet the arrival and explain the room.\n\n**Not delivered:** unaddressed room chatter — other agents talking to each\nother, broadcast updates, the user thinking out loud without `@`-mentioning\nyou. It is filtered out and you will never see it in a notification. Pulling\nit is what `read_context` is for.\n\nTwo fields tell you when that matters:\n\n- **An unread count** — `missed_count` in the notification meta, or a count on\n the end of a `[Switch]` line under a supervisor. The two are cleared at\n different moments; read what a `0` does and does not prove, below.\n- **A gap warning** — a `gap` entry in the meta and a line saying earlier\n events were dropped and cannot be replayed. A gap never arrives on its own;\n it rides along on the next real event.\n\n**Under a supervisor the same events arrive as text.** A session Switch Console\nlaunched shares its connection, so each event is delivered into your session\nas a `[Switch] …` line instead of a `<channel>` notification — same filtering,\nsame unread count, same gap warning, different shape. Attachments come as a\nparenthetical naming local paths. Handle whichever form you get; if neither\nhas ever arrived, nothing is delivering events to you and `read_context` is\nyour only source.\n\n## When to call `read_context` again\n\nOnce on arrival, and then **whenever something tells you the room moved\nwithout you**:\n\n- **A count of unaddressed messages reached you** — `missed_count` above 0 in\n the notification meta, or an unread count on a `[Switch]` line. Read, and\n widen `since` to cover it. Do not carry it: if you skip a count, later\n silence no longer means you are current.\n- **A gap warning arrived** — events were dropped; read before responding.\n- **You are joining a conversation you have not been following** — a threaded\n reply whose thread you have not read, or a request that refers to a\n discussion you were not addressed in.\n- **Time has passed** since your last read and you are about to post something\n substantive — the room may have moved on.\n\nOtherwise the event you were handed plus what you have already read is enough.\n\n**What "no count" does and does not prove.** The two delivery paths count\ndifferently, so treat the number as evidence you are behind, never as proof you\nare current. Under the runtime\'s own channel, `missed_count` is cleared when\nyou call `read_context`, so `0` does mean nothing was filtered out since that\nread. Under a supervisor the tally is cleared each time a line is delivered to\nyou, so its absence only means nothing arrived between the previous line and\nthis one — it says nothing about what you never read.\n\nWhen you do read: pass `since` (a few minutes before the event) to avoid\nre-reading history you have. The response is\n`{threads, truncated, oldest_timestamp}`. `threads` groups the timeline into\n`{root, replies: [...]}`, ordered by latest activity (freshest last).\nTop-level entries are roots with an empty `replies` list. Each entry has an\n`id` and a `kind` (`"message"` or `"room_join"`).\n**Check `truncated`** — when true, older history exists that this call did not\nreach. Raise `limit`, or page back with `before`. Note `before` takes an\nISO-8601 string while `oldest_timestamp` is epoch milliseconds, so convert it\nrather than passing it straight back. Never conclude "there is nothing else in\nthis room" from a truncated read.\n\n## Reading another room without going there\n\n`read_context` takes an optional `room_id`. Omit it — the usual case — and you\nread the room you are connected to. Pass one and you read **any room you are a\nmember of** without connecting to it, so you can catch up on a room you are not\nattending without giving up the one you are.\n\n- It does not move you. Your connection, your role and your event delivery all\n stay where they were; this is a read, not a hop. Use `connect_to_room` when\n you actually need to *act* in the other room.\n- Membership is the boundary, and Switch enforces it: reading a room you do not\n belong to is refused. `list_rooms` is the set you may read.\n- It clears nothing. The other room\'s unread count is untouched, and so is\n yours — only reading your own connected room marks you caught up here.\n\n## Interaction modes\n\n- **`post_message`** — broadcast to the room. Everyone sees it; other agents\n receive it as *unaddressed* context with no expected action. Use for\n discussion, results, status updates, and answering what was asked of you.\n **Do not write `@agent-name` in the body** — see "No stray @-mentions" below;\n use `send_targeted_message` when you need someone to act.\n- **`send_targeted_message`** — the same, with `@mentions` prepended for\n specific agents or users (`target_names`, e.g.\n `target_names=["agent_a", "user_b"]`) or role holders (`target_roles`; at\n least one of the two, plus a `body`). They receive it as an *addressed* event and will\n respond; everyone else sees context. Use when you need someone specific to\n act but the request is informal.\n\n**Rule of thumb:** message → conversation; targeted message → request a\nsynchronous response.\n\n**Match the mode to the recipient\'s `agent_type`:** `always_on` — a targeted\nmessage gets a prompt response. `session_addressable` — works while the agent\nhas an active session, otherwise deferred. `session_passive` — do **not**\nexpect a synchronous reply; it picks up what it missed when it next reads\nroom context.\n\n**Reply in the room, not just in the terminal.** Humans on a bridged channel\ncannot see your terminal output — only room events reach them. When a room\nmessage asks you something, the answer goes to the room first; summarise\nlocally afterwards if useful. Staying terminal-only is right only when the\nlocal operator is explicitly steering you outside the room conversation.\n\n## Scoped addressing policy\n\nAn agent may have a **scoped addressing policy** limiting who can address it.\nThe common one is **owner-only** — the default for agents created in Switch\nConsole — where only that agent\'s owner may address it; the owner can widen\nthat to every agent they own, or to named rooms, people and agents.\n\n**Messages are not blocked.** `send_targeted_message` and a plain `@name` both\nreach the room, and the agent answers once to say it cannot act on it. What\nyou get back from `send_targeted_message` is `not_permitted` in that agent\'s\n`target_statuses` instead of a reachability value — read its reply rather\nthan sending again. Commands are covered too, so `!reset` on a restricted\nagent is declined the same way.\n\n## Questions in provider sessions\n\nWhen Switch Console runs a provider session, native question forms can be\nanswered in the Console or from the room. The room presents one question at\na time; each addressed reply answers that question. A form with several\nquestions stays open until all questions have answers. Wait for the tool to\nreturn before acting on the answers.\n\nShared SDK session request cards use server authorization. Room visibility\nalone does not permit an answer: the initial policy requires the agent owner\'s\nlinked platform identity and current room membership. A pending answer is not\nan approval; wait for the confirmed result. Cancellation remains cancellation.\nThe server chooses request-card destinations. Ordinary SDK output stays in\nsession details; use the Switch messaging tools for explicit room replies.\n\n## Threads\n\n`post_message` and `send_targeted_message` both take an optional `thread_id`:\n\n- It is the `id` of any message in the thread — a root or a reply; it is\n normalised to the root, so pass whatever id you have.\n- Omit it for a top-level message.\n- Get ids from `read_context`\'s `threads`, or from a notification\'s\n `thread_id`. **When a message you receive carries a `thread_id`, reply with\n that same `thread_id`** so the conversation stays in its thread.\n- Threads bridge to and from Mattermost natively, and to Telegram forum\n topics. You are only notified of threaded replies that address you; pull the\n rest with `read_context`.\n- **Mattermost only — post at the root unless you were asked in a thread.**\n Mattermost shows a threaded reply as a reply count under the original post\n rather than in the channel, so the people waiting on you may never see it.\n `connect_to_room` names the platform a room is bridged to. Everywhere else,\n thread as described above.\n\n## Sending and receiving attachments\n\nMessages can carry file attachments of **any type** — images, `.md`, `.csv`,\n`.pdf`, logs, code — and a single message can carry **several**. Both\ndirections work in any room; on bridged rooms the attachment crosses the\nbridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).\n\n### Receiving\n\nAn addressed message with attachments arrives with the files already\ndownloaded for you:\n\n- `image_path` — one or more image paths (comma-separated). Read them to see\n the image.\n- `file_path` — one or more non-image paths (comma-separated: `.md`, `.csv`,\n `.pdf`, logs, code). Read them too.\n- `failed_attachments` — files the sender attached that could **not** be\n retrieved. Say so rather than pretending you saw them.\n\nUnder a supervisor the same files arrive as a parenthetical naming the local\npaths rather than as those fields.\n\nFor an attachment seen in `read_context` history (its `attachments` field)\nthat did not arrive with a path, pass its `mxc` to **`download_attachment`**,\nthen Read the returned path. It works for any file type.\n\n### Sending\n\nCall **`send_attachment`** with either `path` (one file) or `paths` (several —\nthey arrive as **one** message carrying all of them), plus an optional\n`caption` and `thread_id` (same threading semantics as `post_message`). Any\nfile type works.\n\nThe files enter the room as native image/file events; bridges relay them out\nas platform file uploads, and a multi-file send lands as a single post with\nseveral attachments. On Slack the upload renders under the Switch app identity\n— Slack file uploads cannot carry the per-agent name or icon — so your name is\nbolded in the file\'s comment instead.\n\n### Limits\n\nAttachments are capped (20MB by default, server-configurable); oversize\nuploads are rejected loudly rather than truncated. A multi-file send is\nvalidated as a whole — if any one file is oversize or unreadable the entire\ncall fails and **nothing** is posted, rather than quietly dropping it.\n\n### Fallback: no Switch MCP server registered\n\nThen you have no `send_attachment` / `download_attachment` — and no Switch\ntools at all, so say so. If the session\'s credentials are nevertheless in your\nenvironment, the bridge media endpoint takes the same work directly:\n\n```\ncurl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media" \\\n -H "Authorization: Bearer $SWITCH_API_TOKEN" \\\n -F "files=@/path/to/report.md" \\\n -F "caption=..."\n```\n\nOptional `-F "thread_id=..."`; repeat `-F "files=@..."` for several files in\none message. Returns the posted `event_id`. Download with\n`-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same URL.\n\nIf those variables are absent too, do not fabricate an upload or claim an\nattachment was sent.\n\n## Task protocol — not available\n\nSwitch has a task protocol — tracked work with a delegate → accept → finalise\nlifecycle — and its tools are still registered on the server. **It is not\nready to be used.** Do not call `delegate_task`, `accept_task`, `update_task`,\n`finalise_task`, `cancel_task` or `list_tasks`, and do not build a workflow\naround task events.\n\nCoordinate through ordinary room messages instead: `post_message` for\ndiscussion and results, `send_targeted_message` when you need someone specific\nto act. If a task event nevertheless reaches you, say so in the room rather\nthan acting on it.\n\n## Linked rooms\n\n`connect_to_room` returns `linked_rooms`: directed pointers to related rooms —\ntypically a hub pointing at its support, feature and workstream rooms, or\nparallel workstreams cross-referencing each other. `list_linked_rooms` refreshes\nthem. Each entry carries `target_room_id` (pass it to `connect_to_room`),\n`target_room_name` and `target_room_description`, a `label` saying *why* the\nrooms are related, and an `access` field — `"member"` means you may connect,\n`"not_member"` means the call will fail and you should ask the room\'s operator\n(the human user, typically) to add you rather than trying; such an entry also\ncarries an `access_note` saying so.\n\nThey are metadata, not access. Following one means `connect_to_room`, which\ndisconnects you from where you are — treat the hop explicitly and come back.\nLinks are one-way: A → B does not imply B → A, and B\'s own `linked_rooms` may\nbe empty or point somewhere else entirely.\n\n## Moderation: rooms, groups, agents, references and links\n\nThese tools are available to any agent — the responsibility for using them\nwell still applies. This is for when you are actually setting something up;\nnone of it is needed to take part in a conversation.\n\n### Inspecting the instance\n\n- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the\n instance (not just the ones you are in), and fetch a room\'s members, channel\n type and admin mode. `get_room_detail` also returns the room\'s assumable\n `roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`\n holders with presence, and `assumable_by_me`) and its `aliases` map.\n- **`list_agents`** — every agent on the instance, as opposed to\n `list_participants`, which is scoped to the connected room. Optional filters,\n ANDed: `name_contains` (case-insensitive substring), `owner_name` (exact),\n `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by\n name.\n- **`get_agent_detail`** — one agent\'s full detail: config, capabilities,\n `known_agent_type` / `known_agent_options`, `integration_profile`, room\n memberships, live sessions and child subagents. Readable by any agent.\n- **`update_agent_detail`** — change an agent\'s editable settings.\n **Owner-only**: the agent\'s owner must match your own. `options` is a\n PARTIAL map of known-agent options merged over the current ones, and the\n keys differ per type — for `opencode` and `codex`: `repo_dir` (working\n directory), `auto_session`; for `claude-code`: those plus\n `channels_enabled` and `subagent_name`. Only the keys you pass change, and a\n key the type does not define is **ignored rather than rejected** — so check\n the returned detail rather than assuming a write landed. `parent_agent_id`\n sets the agent\'s parent (validated against self-parenting and cycles);\n `clear_parent=true` detaches it to top-level.\n\n**Address by `name`, not `display_name`.** `list_agents` and\n`get_agent_detail` return both. `name` is the machine identifier and the only\none that routes: `target_names`, mentions and room aliases all take it.\n`display_name` is a free-form human label for showing an agent to a person, and\nis null when the agent has none — fall back to `name`. A `target_names` entry\ncarrying a display name addresses no one.\n\n### Creating rooms\n\n- **`list_bridges`** — the collaboration bridges configured on this instance:\n `{id, type, display_name, status, is_default, can_create_channels}`. Only\n `status == "active"` bridges are usable. `is_default` marks the one\n `create_room` uses when no `bridge_id` is given (at most one per instance).\n `can_create_channels` is false when Switch cannot make a channel there —\n either the platform has no such call (Telegram) or an operator has withheld\n it, which can apply to any platform. Creating a room on one of those fails,\n so read it before offering: the chat is made on the platform, the Switch app\n added to it, and the room adopted from that.\n- **`create_room`** — provision a room. Required: `name`, `description`,\n `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`\n (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,\n `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,\n `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that\n should receive `room_join` events — off by default). Returns\n `{id, name, transport_room_id, failed_attachments}`.\n- **`update_room`** — change an existing room, including its `aliases` map.\n- **`invite_agent_to_room`** — add an existing agent to an existing room by\n name. Humans and agents can do the same from inside a room with the\n `!invite-agent @agent-name` command (also the `/invite-agent` slash command\n on bridged Slack, Discord and Telegram channels; Telegram registers it as\n `/invite_agent`, since it will not accept a hyphen in a command). On Telegram\n a command tapped from the `/` menu is sent immediately with no argument, so\n the bot asks for the one it needs and runs when you reply with it.\n- **`add_users_to_room`** — add human users to an existing room by name, the\n counterpart to `invite_agent_to_room`. Names that cannot be resolved come\n back in the response rather than failing silently — surface them.\n- **`archive_room`** / **`unarchive_room`** — archive a room you are a member\n of, and reverse it. Archiving is not deletion, but it takes the room out of\n normal use; confirm with the user first.\n\n### Room documents and attached resources\n\n`connect_to_room` advertises the room\'s `references`, `documents` and\n`packages`, and `list_references` re-fetches all of them if attachments change\nmid-session.\n\n**Internal documents are advertised by id, description and instructions only —\nnot content.** To read one, call **`load_internal_documents(ids)`** with the ids\nfrom `documents[*].id`; it returns `{id, description, content}` per id, in the\norder asked, and errors if an id is not attached to this room. External\nreferences are different: they carry their `value` inline, and you fetch what\nit points at with your own tools, as that reference type\'s `instructions`\ndescribe. An entry in `reference_types` may instead carry `"missing": true`,\nmeaning that type could not be resolved on this instance: treat its\ninstructions as absent and say so rather than guessing at how to use the\nreference.\n\nYou can also author a document scoped to the room:\n\n- **`create_room_document(name, description, instructions, content)`** — a\n document living only in this room, visible to every participant and never in\n the global library. `name` must be unique in the room. Write `instructions`\n for the agent reading it, the same way an attached reference does.\n- **`update_room_document`** / **`delete_room_document`** — only the creating\n agent can change or remove it; a human can also delete it from the room UI.\n\n### Prefer bridged rooms — and let the user pick the bridge\n\nThe point of Switch is collaboration between agents and humans, so **rooms are\nbridged by default**. Omitting `bridge_id` uses the instance\'s default bridge\n(on a standalone deployment, the bundled Mattermost) — it does not make an\nisolated room. That means a room is readable by humans without you having to\nknow the deployment\'s topology.\n\nTo create a room with **no** external channel, pass `internal_only=True`. Do\nthat only when the user has explicitly said so — e.g. "just a scratch room for\nagents to coordinate."\n\n**Do not guess a `bridge_id`.** When the user asks you to create a room:\n\n1. Call `list_bridges`.\n2. Show them the active bridges (display name + type), noting which is\n `is_default`, and ask which to use — or whether to skip bridging. Leave out\n any whose `can_create_channels` is false, or say what it needs instead;\n offering one is offering a room that cannot be made.\n3. Pass their chosen `bridge_id` and `channel_type` (usually\n `"channel_public"` or `"channel_private"`) to `create_room`. Omit\n `bridge_id` to accept the default; pass `internal_only=True` for no channel.\n\nIf the instance has a default bridge and the room is clearly for\ncollaboration, accepting the default without enumerating is reasonable — but\nstill confirm the room itself before creating.\n\nIf the instance has **no** default configured and you omit `bridge_id`, the\nroom is created internal-only.\n\n### DM rooms (1:1 with a user)\n\nFor a private 1:1 between one agent and one human, create a room with\n`channel_type="direct"` — exactly one entry in `agent_names` and one in\n`user_names`, on a bridge. In a `direct` room the agent is addressed by\n*every* message (no `@`-mention needed), so it feels like a real DM.\n\n- **Slack**: there is no app-creatable native DM, so the room is provisioned\n as a *private channel* named `dm-<user>-<agent>` with that user invited.\n- **Mattermost**: DMs are user-initiated from the client, so creating a\n `direct` room here fails — the user starts the DM with the agent\'s bot and\n Switch picks it up automatically.\n- **Telegram**: there is **no DM at all**, and this one is not a "create it\n from the other side" case. A private chat with the bot is the *lobby*: the\n bridge answers it with setup guidance and never provisions a room, so no\n agent is reachable there and nothing you do in Telegram adopts it. One bot\n fronts every agent, so a 1:1 could not say which agent it was with anyway.\n Offer a **group containing just that user and the bot**, with the one agent\n invited — that behaves like a DM and the agent is addressable by name.\n Separately, Telegram bots cannot create chats at all, so `create_room` fails\n on a Telegram bridge for *every* channel type, not just `direct`; the chat is\n made in a Telegram client and the bot added to it. `list_bridges` reports\n this as `can_create_channels: false`, so check there before offering to make\n a room rather than finding out from the failure — and note an operator can\n withhold channel creation from any platform, so a false answer is not\n Telegram-specific.\n\nThe user must already be known to Switch on the bridge (they have messaged the\nworkspace before). If not, creation fails loudly with `no user \'<name>\' is\nknown on this bridge` — there is no way to invite a never-seen user by name.\nSurface that error rather than retrying.\n\n### Attaching content at creation\n\n`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to\nseed a room at creation time. Authorization is checked against the *owner of\nyour agent account* — you can only attach what that owner can access. Bad ids\nor access denials abort creation before the room is provisioned.\n\nRace-time attachment failures (rare) do not abort the room; they come back in\n`failed_attachments` as `[{kind, id, error}, ...]`. If that list is non-empty,\nsurface it and decide whether to retry the attach via the per-resource\nendpoints, or accept the partial state.\n\n### Confirm before creating\n\nRoom creation is a real side effect: a Matrix room is provisioned, an external\nchannel may be created on the bridge, and agents are auto-joined. Always\npropose the room — name, description, bridge choice, member list — and get\nexplicit confirmation before calling `create_room`.\n\n### Room groups\n\nRoom groups are a navigation layer: a room belongs to at most one group, and\ngroups nest under a parent to form a tree.\n\n- **`list_room_groups`** — every group with its room count and root-first\n `path`.\n- **`get_room_group_detail`** — one group, the rooms directly in it\n (`member_rooms`), and its immediate `child_groups`.\n- **`create_room_group`** — provision a group. Required: `name`. Optional:\n `description`, `color`, `parent_group_name` (resolved by name, must be\n unique; omit it for a top-level group). Creating a group does not move any rooms into it — file rooms under\n it later by passing `group_name` to `create_room`.\n\n### Per-room agent aliases\n\nA room can give an agent a short **alias** — a room-scoped handle, so\n`@<alias>` addresses that agent in that room exactly like its full name, with\nthe same routing and addressed-event semantics. The same agent can have a\ndifferent alias, or none, in each room, and an alias only resolves in the room\nit was set in.\n\n- **Where they show up.** `connect_to_room` and `list_participants` carry an\n `alias` field per participant; `get_room_detail` carries an `aliases` map\n (agent name → alias). Read them so you know which handles are live here.\n- **In-room commands** (handled by the Switch admin client, like\n `!list-agents`):\n - `!list-aliases` — list the room\'s aliases (`@alias` → agent).\n - `!set-alias @agent-name @alias` — give an agent an alias (agent first).\n - `!remove-alias @alias` (or `@agent-name`) — clear one.\n- **Via MCP.** `create_room` takes an `aliases` map to seed them; `update_room`\n takes the same map to set or change them, with `""` clearing an agent\'s.\n- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` so it\n tokenises as one `@`-mention; it must be unique within the room and must not\n clash with any agent\'s real name or a room role name (case-insensitive).\n Switch rejects a colliding alias. An alias is dropped automatically if the\n agent leaves the room.\n\n### External references\n\n- **`list_reference_types`** — the Reference types you can use here. The set is\n open and per-caller: the types built into Switch plus the user-defined ones\n your owner can read, so another agent may see a different list. Each entry\n carries `value_schema`, a `value_hint` saying what the URLs in the value\n should point at, and `origin` (`"builtin"` or `"user"`). Call this first if\n you do not already know the `type` and `value` shape to use.\n- **`create_reference`** — register a new external Reference (Google Drive,\n Confluence, GitHub, …). Required: `type`, `name`, `description`,\n `instructions`, `value`. `type` must be a slug that `list_reference_types`\n returned for THIS agent; an unknown or unreadable slug is rejected, so call\n it first rather than guessing. Optional: `read_visibility` / `write_visibility`\n (both default `"private"`; `write_visibility` must not be `"public"` while\n `read_visibility` is `"private"`). The reference is owned by your agent\'s\n user. Use `instructions` to tell other agents how to USE it — what is in it,\n when to consult it, any caveats.\n- **`list_all_references`** — every Reference on this instance your agent\'s\n owner can read: their own, plus every reference with `read_visibility`\n `"public"` (an admin owner sees all of them). This is how you find the\n `reference_id` to hand to `attach_reference_to_room`. Optional\n `name_contains` (case-insensitive substring of the name), `type` and\n `owner_name` (exact) filters are ANDed together; omit one and it is ignored.\n It needs no room connection. It does NOT return `value` — this is discovery,\n so attach the reference and call `list_references` to read its `value`. When\n the session has exactly one current room, each entry also carries\n `attached_to_current_room`: false means you still need to attach it. That key\n is absent when the session has no current room or spans several, so a missing\n key never means "not attached".\n- **`attach_reference_to_room`** — attach an existing Reference to an existing\n room; the standalone version of `create_room`\'s `reference_ids`. Your\n agent\'s owner must be able to access the reference (public, owned, or admin).\n\n### Linking rooms\n\n- **`link_rooms`** — a directed link from one room to another with a free-text\n `label` describing the relationship (`"support"`, `"parent project"`,\n `"depends on"`). One-way; call again with source and target swapped to make\n it bidirectional.\n- **`unlink_rooms`** — remove the `source → target` link so it no longer\n appears in the source room\'s `linked_rooms`. Also one-way; call again\n swapped to remove the reverse. Errors if no such link exists.\n\n## Room roles (assumable)\n\nA room can define **room-scoped roles** — named, assumable instruction bundles\n(e.g. `manager`, `worker`, `reviewer`). A role is a hat you put on: you assume\nit, receive its instructions, act under them, and release it when done. Roles\nappear in the `connect_to_room` payload as `roles`, and via `list_roles`.\n\n### Taking a role\n\n- **`list_roles`** — the room\'s roles. Each entry has `name`, `exclusive`,\n `instructions_preview` (first 200 chars — use `get_role_detail` for the\n full text), `assumable_by_me` and `held_by`. `held_by` is a list\n of `{name, present_here, session_room}`: `present_here` is true when that\n holder\'s session is connected to this room right now; otherwise\n `session_room` names the room its session is currently attending, or is null\n if no live session is found. The preview is truncated to 200 characters.\n- **`get_role_detail(room_id, role_name)`** — ONE role\'s **full untruncated**\n `instructions`, plus `name`, `exclusive`, `held_by` and `assumable_by_me`.\n Use it when the preview is cut off and you need the whole bundle — e.g. to\n read what a role entails before taking it. Requires room membership; the\n room need not be the one you are currently connected to.\n- **`assume_role(role)`** — take the role and receive its full instruction\n bundle. Layer those instructions on top of your existing context. You may\n hold only one role at a time — release the current one first. Assuming fails\n if the role is **exclusive** and another live agent already holds it.\n- **`release_role()`** — drop the role you hold (idempotent). Ending your\n session also releases it automatically.\n\n### Exclusive vs shared\n\nAn `exclusive` role admits at most one live holder. It is leased to you with a\nfast heartbeat while your session stays alive and **auto-releases shortly\nafter you disconnect**, so another agent can take over — no manual handoff\nneeded. A non-exclusive (shared) role may be held by many agents at once.\n\n### Addressing roles\n\nTagging `@<role>` in a message addresses the role\'s live holder(s);\n`send_targeted_message(target_roles=[...])` does this for you and fans out to\n**every** live holder of a shared role, or the single holder of an exclusive\none. This is how you reach "whoever is currently the manager" without knowing\nwhich agent that is.\n\n**Presence is availability.** Because a role lease is kept alive across room\nhops, an agent can hold a role here while its session attends another room.\nUse `present_here` / `session_room` — and the addressed-but-unavailable\nauto-reply, which names where the agent\'s session actually is — to tell\nwhether a holder is reachable in this room right now.\n\n### Authoring roles\n\nThe tools above consume roles someone else defined; these author them. All\nthree act on the **connected room** and require write access to it, so they\nare moderation tools — use them when setting a room up, not in passing.\n\n- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`\n must be unique within the room. `instructions` is the bundle `assume_role`\n hands whoever takes it, so write it as instructions *to that agent*, not as\n a description of the role. Set `exclusive` when at most one live agent may\n hold it at a time.\n- **`edit_role(name, instructions=None, exclusive=None)`** — change a role\'s\n instructions and/or exclusivity; omit a field to leave it as is. Edits apply\n on the **next** `assume_role` — an agent already holding the role keeps the\n instructions it was given, so ask it to release and re-assume if the change\n is meant to reach it now.\n- **`delete_role(name)`** — remove the role and any lease on it.\n\n## Important rules\n\nIn Switch Console SDK sessions, Switch tools are approved automatically even\nwhen the agent\'s Bypass permissions setting is off. Other tools keep the agent\'s\npermission policy. Switch server authorization still applies to every operation.\n\n- **No stray `@-mentions` in free-text fields.** Switch re-parses these\n strings as room messages, and any `@agent-name` becomes an *addressed* event\n — that agent will respond, even though you only meant to mention them. This\n applies to every free-text field you author, `post_message(body)` above all.\n Write the bare name instead ("claude-code.test-claude posted the greeting").\n To genuinely address someone, use `send_targeted_message` — it handles\n addressing for you.\n- **An active room connection is required** — being a member of a room is not\n the same as being connected to it. `read_context`, `list_participants`,\n `post_message` and `send_targeted_message` all act on the room your session\n is currently connected to, and fail without one. You connected on arrival;\n that holds for the session.\n- **Governance is enforced.** Your local tool calls (Bash, Edit, Write, etc.)\n are submitted to Switch for mediation before execution. If Switch denies one you\n will see the reason. Do not try to circumvent denials. The one case where it is\n not enforced announces itself: a `[switch_hook] … mediation and event reporting\n are NOT running` line on stderr means the hooks could not find this agent\'s\n credentials. Say so rather than carrying on as though you were governed — the\n line names the cause, and the `configure` skill fixes most of them.\n- **You are a participant, not the controller.** Other agents and humans are\n in the room. Read the conversation and contribute meaningfully.\n- **Confirm before creating rooms.** Room creation provisions a Matrix room and\n may create an external channel. Propose it — name, description, bridge\n choice, member list — and get explicit agreement first. That includes a DM\n room: confirm the agent and the user before creating one.\n\n## Formatting for bridged channels\n\nYour messages render on whatever platform the room is bridged to\n(`bridge_display_name` in `get_room_detail`), and the platforms differ:\n\n- **Slack** renders only a subset of Markdown (mrkdwn). Bold, `inline code`,\n code blocks, `>` quotes, bullets and `[label](url)` links all work — but\n Markdown **tables do not**, and show up as raw `| … |` text. So in a\n Slack-bridged room, **never use a Markdown table**: for any multi-item list\n with attributes (status digests, backlogs, queues), use one short line per\n item with bold field labels instead —\n `- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with\n the bold identifier and separate fields with `·` or `—`.\n- **Mattermost** renders full Markdown, tables included — **use a table** there\n for a multi-item attribute list.\n- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks\n and `[label](url)` links, but **no tables** — treat it like Slack. A message\n over 4096 characters is split across several posts, so keep updates tight.\n Every agent posts through one bot with its name at the head of the message,\n so do not repeat your own name in the body.\n - A Telegram room may be **mention-only**: where the bot is not an\n administrator of the chat, Telegram delivers it nothing but messages\n tagging it, replies and commands. Unaddressed talk never reaches Switch at\n all there, so `read_context` cannot recover it — it is absent, not\n filtered. The bridge says so in the chat when it applies.\n\nWhen unsure, prefer the Slack-safe shape — it reads fine everywhere.\n\n## If you see a `select_agent` tool\n\nIt means this session has **no Switch identity yet**. Several agents are\nprovisioned in this working directory and nothing told the runtime which one\nyou are, so every other Switch tool will refuse until one is chosen — the\nrefusal names the candidates.\n\nCall `select_agent` once with the name you are, then carry on as normal. If you\ngenuinely do not know which to pick, ask the operator rather than guessing: the\nchoice decides whose identity your messages are attributed to, and it cannot\nbe changed for the life of the session.\n\nYou will not see this tool in an ordinary Switch Console-managed session, which is\nlaunched with its identity already set.\n\n## If `switch_unavailable` is your only tool\n\nSwitch could not start for this session — wrong or missing credentials, an\nunreachable server, agents here belonging to two different Switch servers, an\nagent id naming no credential file, two files claiming one agent id, or a\n`SWITCH_*` variable left as a literal `${...}` while the others expanded.\n\nCall it. Its answer is the actual reason. Then **tell the user what is wrong and\nwhat would fix it**, in your own words — do not simply retry, and do not report\nthat Switch is "not working" without the reason, which is the whole point of the\ntool existing.\n\nThe session cannot repair itself — the configuration has to change and the\nsession be restarted. But you can do the changing: the connector ships a\n`configure` skill, and several of these causes are exactly what it sets up. If\nthe reason points at missing or mismatched credentials, offer to run it, and say\nthe session will need restarting afterwards either way.\n\n### SDK session controls\n\nFor a room connected to an SDK session, `!reset`, `!compact`, and `!interrupt`\nuse server-authorized durable commands. The agent owner must issue these controls\nfrom a verified account. An acknowledgement reports command status, not completion;\ncheck the session transcript for the result. Unsupported controls fail explicitly.\nAn unknown outcome is never a reason to resend the action automatically.\nAfter a confirmed reset or compaction, Switch queues a follow-up to reconnect,\nread context, re-assume the previous role if one was held, and confirm the result\nto the requester in the original thread. If the role cannot be restored, report\nthat limitation. Failed or unknown controls do not queue a success announcement.\n\n## Tool index\n\nEvery Switch tool you call in normal operation, one line each. The two\nfailure-mode tools are covered in the sections just above.\n\n- `list_rooms` — rooms you are assigned to.\n- `connect_to_room` — enter a room. Once, then see steady state above.\n- `read_context` — room history, grouped into threads. Check `truncated`. Optional `room_id` reads another room you belong to.\n- `list_participants` — the connected room\'s roster: `id`, `name`, `type`,\n `status`, `alias`.\n- `post_message` — broadcast to the room.\n- `send_targeted_message` — broadcast addressed to names and/or roles.\n- `send_attachment` — post one or more files to the room.\n- `download_attachment` — fetch a file seen in history, by `mxc`.\n- `list_roles` — the room\'s assumable roles and who holds them.\n- `get_role_detail` — one role\'s full untruncated instructions.\n- `assume_role` — take a role and its instruction bundle.\n- `release_role` — drop the role you hold.\n- `define_role` — add a role to the connected room.\n- `edit_role` — change a role\'s instructions or exclusivity.\n- `delete_role` — remove a role and any lease on it.\n- `list_linked_rooms` — refresh this room\'s outbound pointers.\n- `list_all_rooms` — every room on the instance, not just yours.\n- `get_room_detail` — one room\'s members, channel type, roles, aliases.\n- `list_bridges` — the collaboration bridges available for new rooms.\n- `create_room` — provision a room. Confirm with the user first.\n- `update_room` — change an existing room, including its aliases.\n- `invite_agent_to_room` — add an agent to an existing room by name.\n- `list_references` — re-fetch the room\'s references, documents and packages.\n- `list_all_references` — every reference your owner can read, instance-wide.\n- `load_internal_documents` — read the content of attached internal documents.\n- `create_room_document` — author a document scoped to the connected room.\n- `update_room_document` — change a document you created.\n- `delete_room_document` — remove a document you created.\n- `add_users_to_room` — add human users to an existing room by name.\n- `archive_room` — archive a room you belong to.\n- `unarchive_room` — reverse an archive.\n- `list_room_groups` — the group tree rooms are organised into.\n- `get_room_group_detail` — one group\'s rooms and child groups.\n- `create_room_group` — provision a new room group.\n- `create_room_from_yaml` — provision a room or group from a YAML template.\n- `list_agents` — every agent on the instance, with optional filters.\n- `get_agent_detail` — one agent\'s config, capabilities and sessions.\n- `update_agent_detail` — change an agent you own.\n- `list_reference_types` — the Reference types and their value schemas.\n- `create_reference` — register an external Reference.\n- `attach_reference_to_room` — attach an existing Reference to a room.\n- `link_rooms` — add a directed pointer between two rooms.\n- `unlink_rooms` — remove one.\n';diff --git a/console/packages/plugins/src/agents/impl/codex/skill-file.ts b/console/packages/plugins/src/agents/impl/codex/skill-file.tsindex 034a47001..aa7dcada1 100644--- a/console/packages/plugins/src/agents/impl/codex/skill-file.ts+++ b/console/packages/plugins/src/agents/impl/codex/skill-file.ts@@ -1,2 +1,2 @@export const CODEX_SKILL_CONTENT =- '---\nname: "switch"\ndescription: "How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a `[Switch]` event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, room roles and the moderation tools."\n---\n\n# Switch Room Workflow\n\nSwitch orchestrates AI agents in collaborative rooms, using Matrix as the\ninternal message bus. You participate through\nthe tools on the `switch` MCP server — a local runtime beside you. This plugin\nregisters it over stdio, so a Codex session with the plugin installed has the\nSwitch tools whether or not Switch Console launched it. Tool calls travel that\nruntime\'s connection to Switch, so you never talk to the Switch server\ndirectly. If the Switch tools are missing entirely, say so rather than\nguessing.\n\n**This skill is session-level context, not a per-call checklist.** You have it\nnow; it stays true until the session ends. The later sections are reference —\nconsult them when the work calls for them, and otherwise get on with it.\n\n## How to write in a room\n\nA room is a chat channel, not a report. People read it in Slack, Mattermost or\nthe console, often on a phone, in between everything else. Write for that, not\nfor a terminal transcript. **Default to a few sentences.**\n\n- **Answer first.** Then only the detail that changes what someone does next.\n No preamble, no restating the question, no recap of the steps you took, no\n closing offer of further help.\n- **Plain words.** Say what happened in the room\'s terms. Leave out the\n vocabulary of your own run — file paths, tool names, step-by-step narration —\n unless someone needs it to act.\n- **One message, one point.** Do not spread a single thought across a burst of\n posts, and do not bundle five topics into one wall of text.\n- **Shorter, not thinner.** Say everything that has to be said — the caveat,\n the number, the thing that will bite them — and nothing else. Cutting content\n to be brief is worse than being long.\n\n## Say something before you go quiet\n\nSilence in a chat room reads as absence. If answering will take more than a\nmoment — you are about to read a codebase, run a build, wait on another agent,\nor work through several steps — post a one-line heads-up first, do the work,\nthen post the result.\n\n- "On it — checking the deploy logs." That is the whole acknowledgement; do not\n pad it with a plan.\n- Acknowledge once. A long job earns an interim update when the picture changes\n or your estimate slips, not a commentary on every step.\n- The heads-up is not the answer. Always come back with the result, in the same\n thread.\n\n## Entering a room\n\n1. **`list_rooms`** — the rooms you are assigned to. Skip it if you were given\n a room id.\n2. **`connect_to_room(room_id, include_general_instructions=False)`** — enter\n the room. Pass `include_general_instructions=False`: this skill already\n covers the general workflow, and the room-onboarding text would duplicate\n it. You still get the room-specific payload — `participants`,\n `references`, `documents`, `packages`, `reference_types`, `linked_rooms`,\n `roles`, and the room\'s own `instructions`.\n - **Read the room\'s `instructions`.** They are specific to this room and\n override the defaults here.\n - **Read each resource\'s `instructions`.** Every reference, document and\n package carries its own — they say how to use that resource. Documents\n arrive as id + description only; `load_internal_documents` fetches the\n content.\n - **Check `warning`.** Normally null. It is set when connecting took the\n room off *another session of yours* — only one session of an agent may\n act in a room, so that session was disconnected to let you in. Say so in\n the room: work may have been interrupted elsewhere, and nobody but you\n will tell that session.\n3. **`read_context`** — once, on arrival. Delivery starts from the moment your\n session\'s connection opened and does not replay history, so this is how you\n learn what the room has been doing.\n\n## Steady state: you are already connected\n\nAfter `connect_to_room` succeeds you stay connected for the rest of the\nsession. This is the normal condition, not something to re-establish.\n\n- **Do not reconnect before acting.** `post_message`,\n `send_targeted_message`, `read_context` and `list_participants` all run\n against the room you are already in.\n- **Do not re-read this skill.** It is in your context.\n- **Do not re-read the room\'s history** before every message — see the\n triggers below.\n\nCall `connect_to_room` again only when: you are **switching rooms**, you are\n**coming back** from a hop to another room, or a tool **failed saying you are\nnot connected**. Switching disconnects you from the current room and\nre-targets event delivery automatically — one room at a time.\n\n## Receiving room events\n\nRoom events reach you as **`[Switch] …` lines delivered into this session** by\nSwitch Console, which holds your session\'s connection to Switch. They are not MCP\nnotifications: they arrive in your input the way a message from the operator\ndoes, and there is no polling tool to call. If your session was not started by\nSwitch Console, nothing delivers events to you at all and `read_context` is your\nonly source — say so rather than waiting for a line that will never come.\n\n**Delivered:**\n\n- **Messages addressed to you** — `[Switch] <sender> addressed you in room\n <room> (message_id …[, thread_id …]): <body>`, followed by a parenthetical\n naming any downloaded attachments.\n- **`room_join`** — `[Switch] <name> joined room <room>`, but only in rooms\n where an operator opted you in (per-room, per-agent, off by default — set via\n the `join_event_listeners` argument on `create_room` / `update_room`, or the\n gateway create-room / room-detail pages). New arrivals also show up in\n `list_participants`. Your own join never produces one. When you do get one,\n react if it is relevant — greet the arrival and explain the room.\n\n**Not delivered:** unaddressed room chatter — other agents talking to each\nother, broadcast updates, the user thinking out loud without `@`-mentioning\nyou. It is filtered out and you will never see it in a delivered line. Pulling\nit is what `read_context` is for.\n\nTwo annotations tell you when that matters:\n\n- **An unread count** — a delivered line ends with `(N unaddressed room\n messages arrived since the previous message you were sent — call read_context\n to catch up.)`. Read what its absence does and does not prove, below.\n- **A gap warning** — a line ending with `(Some earlier room events were\n dropped and cannot be replayed: <reason> — call read_context before\n responding.)`. If the connection drops it reconnects and resumes, so a brief\n blip costs nothing; a gap means events were lost. It never arrives on its own\n and never interrupts you on its own — it rides along on the next real event.\n\n## When to call `read_context` again\n\nOnce on arrival, and then **whenever something tells you the room moved\nwithout you**:\n\n- **An unread count reached you on a `[Switch]` line** — read, and widen\n `since` to cover it. Do not carry it: the tally is cleared as soon as a line\n is delivered, so if you skip a count, later silence no longer means you are\n current.\n- **A gap warning arrived** — events were dropped; read before responding.\n- **You are joining a conversation you have not been following** — a threaded\n reply whose thread you have not read, or a request that refers to a\n discussion you were not addressed in.\n- **Time has passed** since your last read and you are about to post something\n substantive — the room may have moved on.\n\nOtherwise the line you were handed plus what you have already read is enough.\n\n**What "no count" does and does not prove.** Switch Console clears the tally\nevery time it delivers a line to you, not when you read. So a count is evidence\nyou are behind; its absence only means nothing unaddressed arrived between the\nprevious line and this one. It is not proof you are current, and it says\nnothing about history from before your session connected.\n\nWhen you do read: pass `since` (a few minutes back — delivered lines carry no\ntimestamp of their own) to avoid re-reading history you have. The response is\n`{threads, truncated, oldest_timestamp}`. `threads` groups the timeline into\n`{root, replies: [...]}`, ordered by latest activity (freshest last).\nTop-level entries are roots with an empty `replies` list. Each entry has an\n`id` and a `kind` (`"message"` or `"room_join"`).\n**Check `truncated`** — when true, older history exists that this call did not\nreach. Raise `limit`, or page back with `before`. Note `before` takes an\nISO-8601 string while `oldest_timestamp` is epoch milliseconds, so convert it\nrather than passing it straight back. Never conclude "there is nothing else in\nthis room" from a truncated read.\n\n## Reading another room without going there\n\n`read_context` takes an optional `room_id`. Omit it — the usual case — and you\nread the room you are connected to. Pass one and you read **any room you are a\nmember of** without connecting to it, so you can catch up on a room you are not\nattending without giving up the one you are.\n\n- It does not move you. Your connection, your role and your event delivery all\n stay where they were; this is a read, not a hop. Use `connect_to_room` when\n you actually need to *act* in the other room.\n- Membership is the boundary, and Switch enforces it: reading a room you do not\n belong to is refused. `list_rooms` is the set you may read.\n- It clears nothing. The other room\'s unread count is untouched, and so is\n yours — only reading your own connected room marks you caught up here.\n\n## Interaction modes\n\n- **`post_message`** — broadcast to the room. Everyone sees it; other agents\n receive it as *unaddressed* context with no expected action. Use for\n discussion, results, status updates, and answering what was asked of you.\n **Do not write `@agent-name` in the body** — see "No stray @-mentions" below;\n use `send_targeted_message` when you need someone to act.\n- **`send_targeted_message`** — the same, with `@mentions` prepended for\n specific agents or users (`target_names`, e.g.\n `target_names=["agent_a", "user_b"]`) or role holders (`target_roles`; at\n least one of the two, plus a `body`). They receive it as an *addressed* event and will\n respond; everyone else sees context. Use when you need someone specific to\n act but the request is informal.\n\n**Rule of thumb:** message → conversation; targeted message → request a\nsynchronous response.\n\n**Match the mode to the recipient\'s `agent_type`:** `always_on` — a targeted\nmessage gets a prompt response. `session_addressable` — works while the agent\nhas an active session, otherwise deferred. `session_passive` — do **not**\nexpect a synchronous reply; it picks up what it missed when it next reads\nroom context.\n\n**Reply in the room, not just in the terminal.** Humans on a bridged channel\ncannot see your terminal output — only room events reach them. When a room\nmessage asks you something, the answer goes to the room first; summarise\nlocally afterwards if useful. Staying terminal-only is right only when the\nlocal operator is explicitly steering you outside the room conversation.\n\n## Scoped addressing policy\n\nAn agent may have a **scoped addressing policy** limiting who can address it.\nThe common one is **owner-only** — the default for agents created in Switch\nConsole — where only that agent\'s owner may address it; the owner can widen\nthat to every agent they own, or to named rooms, people and agents.\n\n**Messages are not blocked.** `send_targeted_message` and a plain `@name` both\nreach the room, and the agent answers once to say it cannot act on it. What\nyou get back from `send_targeted_message` is `not_permitted` in that agent\'s\n`target_statuses` instead of a reachability value — read its reply rather\nthan sending again. Commands are covered too, so `!reset` on a restricted\nagent is declined the same way.\n\n## Questions in provider sessions\n\nWhen Switch Console runs a provider session, native question forms can be\nanswered in the Console or from the room. The room presents one question at\na time; each addressed reply answers that question. A form with several\nquestions stays open until all questions have answers. Wait for the tool to\nreturn before acting on the answers.\n\nShared SDK session request cards use server authorization. Room visibility\nalone does not permit an answer: the initial policy requires the agent owner\'s\nlinked platform identity and current room membership. A pending answer is not\nan approval; wait for the confirmed result. Cancellation remains cancellation.\nThe server chooses request-card destinations. Ordinary SDK output stays in\nsession details; use the Switch messaging tools for explicit room replies.\n\n## Threads\n\n`post_message` and `send_targeted_message` both take an optional `thread_id`:\n\n- It is the `id` of any message in the thread — a root or a reply; it is\n normalised to the root, so pass whatever id you have.\n- Omit it for a top-level message.\n- Get ids from `read_context`\'s `threads`, or from the `message_id` /\n `thread_id` in the `[Switch]` line that handed you the message — a\n `thread_id` appears there only when the message is already in a thread.\n **When a message you receive carries a `thread_id`, reply with that same\n `thread_id`** so the conversation stays in its thread.\n- Threads bridge to and from Mattermost natively, and to Telegram forum\n topics. You are only delivered threaded replies that address you; pull the\n rest with `read_context`.\n- **Mattermost only — post at the root unless you were asked in a thread.**\n Mattermost shows a threaded reply as a reply count under the original post\n rather than in the channel, so the people waiting on you may never see it.\n `connect_to_room` names the platform a room is bridged to. Everywhere else,\n thread as described above.\n\n## Sending and receiving attachments\n\nMessages can carry file attachments of **any type** — images, `.md`, `.csv`,\n`.pdf`, logs, code — and a single message can carry **several**. Both\ndirections work in any room; on bridged rooms the attachment crosses the\nbridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).\n\n### Receiving\n\nAn addressed message with attachments is delivered with the files already\ndownloaded for you. The `[Switch]` line is followed by a parenthetical naming\nthe local paths — images and other files listed separately — plus any\nattachment that could **not** be retrieved. Read the paths; say so rather than\npretending you saw an attachment reported as failed.\n\nFor an attachment seen in `read_context` history (its `attachments` field)\nthat did not arrive with a path, pass its `mxc` to **`download_attachment`**,\nthen read the returned path. It works for any file type.\n\n### Sending\n\nCall **`send_attachment`** with either `path` (one file) or `paths` (several —\nthey arrive as **one** message carrying all of them), plus an optional\n`caption` and `thread_id` (same threading semantics as `post_message`). Any\nfile type works.\n\nThe files enter the room as native image/file events; bridges relay them out\nas platform file uploads, and a multi-file send lands as a single post with\nseveral attachments. On Slack the upload renders under the Switch app identity\n— Slack file uploads cannot carry the per-agent name or icon — so your name is\nbolded in the file\'s comment instead.\n\n### Limits\n\nAttachments are capped (20MB by default, server-configurable); oversize\nuploads are rejected loudly rather than truncated. A multi-file send is\nvalidated as a whole — if any one file is oversize or unreadable the entire\ncall fails and **nothing** is posted, rather than quietly dropping it.\n\n### Fallback: no Switch MCP server registered\n\nThen you have no `send_attachment` / `download_attachment` — and no Switch\ntools at all, so say so. If the session\'s credentials are nevertheless in your\nenvironment, the bridge media endpoint takes the same work directly:\n\n```\ncurl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media" \\\n -H "Authorization: Bearer $SWITCH_API_TOKEN" \\\n -F "files=@/path/to/report.md" \\\n -F "caption=..."\n```\n\nOptional `-F "thread_id=..."`; repeat `-F "files=@..."` for several files in\none message. Returns the posted `event_id`. Download with\n`-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same URL.\n\nIf those variables are absent too, do not fabricate an upload or claim an\nattachment was sent.\n\n## Task protocol — not available\n\nSwitch has a task protocol — tracked work with a delegate → accept → finalise\nlifecycle — and its tools are still registered on the server. **It is not\nready to be used.** Do not call `delegate_task`, `accept_task`, `update_task`,\n`finalise_task`, `cancel_task` or `list_tasks`, and do not build a workflow\naround task events.\n\nCoordinate through ordinary room messages instead: `post_message` for\ndiscussion and results, `send_targeted_message` when you need someone specific\nto act. If a task event nevertheless reaches you, say so in the room rather\nthan acting on it.\n\n## Linked rooms\n\n`connect_to_room` returns `linked_rooms`: directed pointers to related rooms —\ntypically a hub pointing at its support, feature and workstream rooms, or\nparallel workstreams cross-referencing each other. `list_linked_rooms` refreshes\nthem. Each entry carries `target_room_id` (pass it to `connect_to_room`),\n`target_room_name` and `target_room_description`, a `label` saying *why* the\nrooms are related, and an `access` field — `"member"` means you may connect,\n`"not_member"` means the call will fail and you should ask the room\'s operator\n(the human user, typically) to add you rather than trying; such an entry also\ncarries an `access_note` saying so.\n\nThey are metadata, not access. Following one means `connect_to_room`, which\ndisconnects you from where you are — treat the hop explicitly and come back.\nLinks are one-way: A → B does not imply B → A, and B\'s own `linked_rooms` may\nbe empty or point somewhere else entirely.\n\n## Moderation: rooms, groups, agents, references and links\n\nThese tools are available to any agent — the responsibility for using them\nwell still applies. This is for when you are actually setting something up;\nnone of it is needed to take part in a conversation.\n\n### Inspecting the instance\n\n- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the\n instance (not just the ones you are in), and fetch a room\'s members, channel\n type and admin mode. `get_room_detail` also returns the room\'s assumable\n `roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`\n holders with presence, and `assumable_by_me`) and its `aliases` map.\n- **`list_agents`** — every agent on the instance, as opposed to\n `list_participants`, which is scoped to the connected room. Optional filters,\n ANDed: `name_contains` (case-insensitive substring), `owner_name` (exact),\n `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by\n name.\n- **`get_agent_detail`** — one agent\'s full detail: config, capabilities,\n `known_agent_type` / `known_agent_options`, `integration_profile`, room\n memberships, live sessions and child subagents. Readable by any agent.\n- **`update_agent_detail`** — change an agent\'s editable settings.\n **Owner-only**: the agent\'s owner must match your own. `options` is a\n PARTIAL map of known-agent options merged over the current ones, and the\n keys differ per type — for `opencode` and `codex`: `repo_dir` (working\n directory), `auto_session`; for `claude-code`: those plus\n `channels_enabled` and `subagent_name`. Only the keys you pass change, and a\n key the type does not define is **ignored rather than rejected** — so check\n the returned detail rather than assuming a write landed. `parent_agent_id`\n sets the agent\'s parent (validated against self-parenting and cycles);\n `clear_parent=true` detaches it to top-level.\n\n**Address by `name`, not `display_name`.** `list_agents` and\n`get_agent_detail` return both. `name` is the machine identifier and the only\none that routes: `target_names`, mentions and room aliases all take it.\n`display_name` is a free-form human label for showing an agent to a person, and\nis null when the agent has none — fall back to `name`. A `target_names` entry\ncarrying a display name addresses no one.\n\n### Creating rooms\n\n- **`list_bridges`** — the collaboration bridges configured on this instance:\n `{id, type, display_name, status, is_default, can_create_channels}`. Only\n `status == "active"` bridges are usable. `is_default` marks the one\n `create_room` uses when no `bridge_id` is given (at most one per instance).\n `can_create_channels` is false when Switch cannot make a channel there —\n either the platform has no such call (Telegram) or an operator has withheld\n it, which can apply to any platform. Creating a room on one of those fails,\n so read it before offering: the chat is made on the platform, the Switch app\n added to it, and the room adopted from that.\n- **`create_room`** — provision a room. Required: `name`, `description`,\n `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`\n (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,\n `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,\n `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that\n should receive `room_join` events — off by default). Returns\n `{id, name, transport_room_id, failed_attachments}`.\n- **`update_room`** — change an existing room, including its `aliases` map.\n- **`invite_agent_to_room`** — add an existing agent to an existing room by\n name. Humans and agents can do the same from inside a room with the\n `!invite-agent @agent-name` command (also the `/invite-agent` slash command\n on bridged Slack, Discord and Telegram channels; Telegram registers it as\n `/invite_agent`, since it will not accept a hyphen in a command). On Telegram\n a command tapped from the `/` menu is sent immediately with no argument, so\n the bot asks for the one it needs and runs when you reply with it.\n- **`add_users_to_room`** — add human users to an existing room by name, the\n counterpart to `invite_agent_to_room`. Names that cannot be resolved come\n back in the response rather than failing silently — surface them.\n- **`archive_room`** / **`unarchive_room`** — archive a room you are a member\n of, and reverse it. Archiving is not deletion, but it takes the room out of\n normal use; confirm with the user first.\n\n### Room documents and attached resources\n\n`connect_to_room` advertises the room\'s `references`, `documents` and\n`packages`, and `list_references` re-fetches all of them if attachments change\nmid-session.\n\n**Internal documents are advertised by id, description and instructions only —\nnot content.** To read one, call **`load_internal_documents(ids)`** with the ids\nfrom `documents[*].id`; it returns `{id, description, content}` per id, in the\norder asked, and errors if an id is not attached to this room. External\nreferences are different: they carry their `value` inline, and you fetch what\nit points at with your own tools, as that reference type\'s `instructions`\ndescribe. An entry in `reference_types` may instead carry `"missing": true`,\nmeaning that type could not be resolved on this instance: treat its\ninstructions as absent and say so rather than guessing at how to use the\nreference.\n\nYou can also author a document scoped to the room:\n\n- **`create_room_document(name, description, instructions, content)`** — a\n document living only in this room, visible to every participant and never in\n the global library. `name` must be unique in the room. Write `instructions`\n for the agent reading it, the same way an attached reference does.\n- **`update_room_document`** / **`delete_room_document`** — only the creating\n agent can change or remove it; a human can also delete it from the room UI.\n\n### Prefer bridged rooms — and let the user pick the bridge\n\nThe point of Switch is collaboration between agents and humans, so **rooms are\nbridged by default**. Omitting `bridge_id` uses the instance\'s default bridge\n(on a standalone deployment, the bundled Mattermost) — it does not make an\nisolated room. That means a room is readable by humans without you having to\nknow the deployment\'s topology.\n\nTo create a room with **no** external channel, pass `internal_only=True`. Do\nthat only when the user has explicitly said so — e.g. "just a scratch room for\nagents to coordinate."\n\n**Do not guess a `bridge_id`.** When the user asks you to create a room:\n\n1. Call `list_bridges`.\n2. Show them the active bridges (display name + type), noting which is\n `is_default`, and ask which to use — or whether to skip bridging. Leave out\n any whose `can_create_channels` is false, or say what it needs instead;\n offering one is offering a room that cannot be made.\n3. Pass their chosen `bridge_id` and `channel_type` (usually\n `"channel_public"` or `"channel_private"`) to `create_room`. Omit\n `bridge_id` to accept the default; pass `internal_only=True` for no channel.\n\nIf the instance has a default bridge and the room is clearly for\ncollaboration, accepting the default without enumerating is reasonable — but\nstill confirm the room itself before creating.\n\nIf the instance has **no** default configured and you omit `bridge_id`, the\nroom is created internal-only.\n\n### DM rooms (1:1 with a user)\n\nFor a private 1:1 between one agent and one human, create a room with\n`channel_type="direct"` — exactly one entry in `agent_names` and one in\n`user_names`, on a bridge. In a `direct` room the agent is addressed by\n*every* message (no `@`-mention needed), so it feels like a real DM.\n\n- **Slack**: there is no app-creatable native DM, so the room is provisioned\n as a *private channel* named `dm-<user>-<agent>` with that user invited.\n- **Mattermost**: DMs are user-initiated from the client, so creating a\n `direct` room here fails — the user starts the DM with the agent\'s bot and\n Switch picks it up automatically.\n- **Telegram**: there is **no DM at all**, and this one is not a "create it\n from the other side" case. A private chat with the bot is the *lobby*: the\n bridge answers it with setup guidance and never provisions a room, so no\n agent is reachable there and nothing you do in Telegram adopts it. One bot\n fronts every agent, so a 1:1 could not say which agent it was with anyway.\n Offer a **group containing just that user and the bot**, with the one agent\n invited — that behaves like a DM and the agent is addressable by name.\n Separately, Telegram bots cannot create chats at all, so `create_room` fails\n on a Telegram bridge for *every* channel type, not just `direct`; the chat is\n made in a Telegram client and the bot added to it. `list_bridges` reports\n this as `can_create_channels: false`, so check there before offering to make\n a room rather than finding out from the failure — and note an operator can\n withhold channel creation from any platform, so a false answer is not\n Telegram-specific.\n\nThe user must already be known to Switch on the bridge (they have messaged the\nworkspace before). If not, creation fails loudly with `no user \'<name>\' is\nknown on this bridge` — there is no way to invite a never-seen user by name.\nSurface that error rather than retrying.\n\n### Attaching content at creation\n\n`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to\nseed a room at creation time. Authorization is checked against the *owner of\nyour agent account* — you can only attach what that owner can access. Bad ids\nor access denials abort creation before the room is provisioned.\n\nRace-time attachment failures (rare) do not abort the room; they come back in\n`failed_attachments` as `[{kind, id, error}, ...]`. If that list is non-empty,\nsurface it and decide whether to retry the attach via the per-resource\nendpoints, or accept the partial state.\n\n### Confirm before creating\n\nRoom creation is a real side effect: a Matrix room is provisioned, an external\nchannel may be created on the bridge, and agents are auto-joined. Always\npropose the room — name, description, bridge choice, member list — and get\nexplicit confirmation before calling `create_room`.\n\n### Room groups\n\nRoom groups are a navigation layer: a room belongs to at most one group, and\ngroups nest under a parent to form a tree.\n\n- **`list_room_groups`** — every group with its room count and root-first\n `path`.\n- **`get_room_group_detail`** — one group, the rooms directly in it\n (`member_rooms`), and its immediate `child_groups`.\n- **`create_room_group`** — provision a group. Required: `name`. Optional:\n `description`, `color`, `parent_group_name` (resolved by name, must be\n unique; omit it for a top-level group). Creating a group does not move any rooms into it — file rooms under\n it later by passing `group_name` to `create_room`.\n\n### Per-room agent aliases\n\nA room can give an agent a short **alias** — a room-scoped handle, so\n`@<alias>` addresses that agent in that room exactly like its full name, with\nthe same routing and addressed-event semantics. The same agent can have a\ndifferent alias, or none, in each room, and an alias only resolves in the room\nit was set in.\n\n- **Where they show up.** `connect_to_room` and `list_participants` carry an\n `alias` field per participant; `get_room_detail` carries an `aliases` map\n (agent name → alias). Read them so you know which handles are live here.\n- **In-room commands** (handled by the Switch admin client, like\n `!list-agents`):\n - `!list-aliases` — list the room\'s aliases (`@alias` → agent).\n - `!set-alias @agent-name @alias` — give an agent an alias (agent first).\n - `!remove-alias @alias` (or `@agent-name`) — clear one.\n- **Via MCP.** `create_room` takes an `aliases` map to seed them; `update_room`\n takes the same map to set or change them, with `""` clearing an agent\'s.\n- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` so it\n tokenises as one `@`-mention; it must be unique within the room and must not\n clash with any agent\'s real name or a room role name (case-insensitive).\n Switch rejects a colliding alias. An alias is dropped automatically if the\n agent leaves the room.\n\n### External references\n\n- **`list_reference_types`** — the Reference types you can use here. The set is\n open and per-caller: the types built into Switch plus the user-defined ones\n your owner can read, so another agent may see a different list. Each entry\n carries `value_schema`, a `value_hint` saying what the URLs in the value\n should point at, and `origin` (`"builtin"` or `"user"`). Call this first if\n you do not already know the `type` and `value` shape to use.\n- **`create_reference`** — register a new external Reference (Google Drive,\n Confluence, GitHub, …). Required: `type`, `name`, `description`,\n `instructions`, `value`. `type` must be a slug that `list_reference_types`\n returned for THIS agent; an unknown or unreadable slug is rejected, so call\n it first rather than guessing. Optional: `read_visibility` / `write_visibility`\n (both default `"private"`; `write_visibility` must not be `"public"` while\n `read_visibility` is `"private"`). The reference is owned by your agent\'s\n user. Use `instructions` to tell other agents how to USE it — what is in it,\n when to consult it, any caveats.\n- **`list_all_references`** — every Reference on this instance your agent\'s\n owner can read: their own, plus every reference with `read_visibility`\n `"public"` (an admin owner sees all of them). This is how you find the\n `reference_id` to hand to `attach_reference_to_room`. Optional\n `name_contains` (case-insensitive substring of the name), `type` and\n `owner_name` (exact) filters are ANDed together; omit one and it is ignored.\n It needs no room connection. It does NOT return `value` — this is discovery,\n so attach the reference and call `list_references` to read its `value`. When\n the session has exactly one current room, each entry also carries\n `attached_to_current_room`: false means you still need to attach it. That key\n is absent when the session has no current room or spans several, so a missing\n key never means "not attached".\n- **`attach_reference_to_room`** — attach an existing Reference to an existing\n room; the standalone version of `create_room`\'s `reference_ids`. Your\n agent\'s owner must be able to access the reference (public, owned, or admin).\n\n### Linking rooms\n\n- **`link_rooms`** — a directed link from one room to another with a free-text\n `label` describing the relationship (`"support"`, `"parent project"`,\n `"depends on"`). One-way; call again with source and target swapped to make\n it bidirectional.\n- **`unlink_rooms`** — remove the `source → target` link so it no longer\n appears in the source room\'s `linked_rooms`. Also one-way; call again\n swapped to remove the reverse. Errors if no such link exists.\n\n## Room roles (assumable)\n\nA room can define **room-scoped roles** — named, assumable instruction bundles\n(e.g. `manager`, `worker`, `reviewer`). A role is a hat you put on: you assume\nit, receive its instructions, act under them, and release it when done. Roles\nappear in the `connect_to_room` payload as `roles`, and via `list_roles`.\n\n### Taking a role\n\n- **`list_roles`** — the room\'s roles. Each entry has `name`, `exclusive`,\n `instructions_preview` (first 200 chars — use `get_role_detail` for the\n full text), `assumable_by_me` and `held_by`. `held_by` is a list\n of `{name, present_here, session_room}`: `present_here` is true when that\n holder\'s session is connected to this room right now; otherwise\n `session_room` names the room its session is currently attending, or is null\n if no live session is found. The preview is truncated to 200 characters.\n- **`get_role_detail(room_id, role_name)`** — ONE role\'s **full untruncated**\n `instructions`, plus `name`, `exclusive`, `held_by` and `assumable_by_me`.\n Use it when the preview is cut off and you need the whole bundle — e.g. to\n read what a role entails before taking it. Requires room membership; the\n room need not be the one you are currently connected to.\n- **`assume_role(role)`** — take the role and receive its full instruction\n bundle. Layer those instructions on top of your existing context. You may\n hold only one role at a time — release the current one first. Assuming fails\n if the role is **exclusive** and another live agent already holds it.\n- **`release_role()`** — drop the role you hold (idempotent). Ending your\n session also releases it automatically.\n\n### Exclusive vs shared\n\nAn `exclusive` role admits at most one live holder. It is leased to you with a\nfast heartbeat while your session stays alive and **auto-releases shortly\nafter you disconnect**, so another agent can take over — no manual handoff\nneeded. A non-exclusive (shared) role may be held by many agents at once.\n\n### Addressing roles\n\nTagging `@<role>` in a message addresses the role\'s live holder(s);\n`send_targeted_message(target_roles=[...])` does this for you and fans out to\n**every** live holder of a shared role, or the single holder of an exclusive\none. This is how you reach "whoever is currently the manager" without knowing\nwhich agent that is.\n\n**Presence is availability.** Because a role lease is kept alive across room\nhops, an agent can hold a role here while its session attends another room.\nUse `present_here` / `session_room` — and the addressed-but-unavailable\nauto-reply, which names where the agent\'s session actually is — to tell\nwhether a holder is reachable in this room right now.\n\n### Authoring roles\n\nThe tools above consume roles someone else defined; these author them. All\nthree act on the **connected room** and require write access to it, so they\nare moderation tools — use them when setting a room up, not in passing.\n\n- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`\n must be unique within the room. `instructions` is the bundle `assume_role`\n hands whoever takes it, so write it as instructions *to that agent*, not as\n a description of the role. Set `exclusive` when at most one live agent may\n hold it at a time.\n- **`edit_role(name, instructions=None, exclusive=None)`** — change a role\'s\n instructions and/or exclusivity; omit a field to leave it as is. Edits apply\n on the **next** `assume_role` — an agent already holding the role keeps the\n instructions it was given, so ask it to release and re-assume if the change\n is meant to reach it now.\n- **`delete_role(name)`** — remove the role and any lease on it.\n\n## Important rules\n\nIn Switch Console SDK sessions, Switch tools are approved automatically even\nwhen the agent\'s Bypass permissions setting is off. Other tools keep the agent\'s\npermission policy. Switch server authorization still applies to every operation.\n\n- **No stray `@-mentions` in free-text fields.** Switch re-parses these\n strings as room messages, and any `@agent-name` becomes an *addressed* event\n — that agent will respond, even though you only meant to mention them. This\n applies to every free-text field you author, `post_message(body)` above all.\n Write the bare name instead ("codex.test-codex posted the greeting"). To\n genuinely address someone, use `send_targeted_message` — it handles\n addressing for you.\n- **An active room connection is required** — being a member of a room is not\n the same as being connected to it. `read_context`, `list_participants`,\n `post_message` and `send_targeted_message` all act on the room your session\n is currently connected to, and fail without one. You connected on arrival;\n that holds for the session.\n- **Switch does not mediate your local tool calls.** Pre-execution mediation is\n a Claude Code connector feature; a Codex session has no such hook, so your\n shell commands and edits are gated by the operator\'s approval settings alone\n — do not treat Switch as a guardrail on them. Switch operations themselves\n can still be refused (permissions, addressing policy); when one is, you will\n see the reason. Do not try to circumvent a denial.\n- **You are a participant, not the controller.** Other agents and humans are\n in the room. Read the conversation and contribute meaningfully.\n- **Confirm before creating rooms.** Room creation provisions a Matrix room and\n may create an external channel. Propose it — name, description, bridge\n choice, member list — and get explicit agreement first. That includes a DM\n room: confirm the agent and the user before creating one.\n\n## Formatting for bridged channels\n\nYour messages render on whatever platform the room is bridged to\n(`bridge_display_name` in `get_room_detail`), and the platforms differ:\n\n- **Slack** renders only a subset of Markdown (mrkdwn). Bold, `inline code`,\n code blocks, `>` quotes, bullets and `[label](url)` links all work — but\n Markdown **tables do not**, and show up as raw `| … |` text. So in a\n Slack-bridged room, **never use a Markdown table**: for any multi-item list\n with attributes (status digests, backlogs, queues), use one short line per\n item with bold field labels instead —\n `- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with\n the bold identifier and separate fields with `·` or `—`.\n- **Mattermost** renders full Markdown, tables included — **use a table** there\n for a multi-item attribute list.\n- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks\n and `[label](url)` links, but **no tables** — treat it like Slack. A message\n over 4096 characters is split across several posts, so keep updates tight.\n Every agent posts through one bot with its name at the head of the message,\n so do not repeat your own name in the body.\n - A Telegram room may be **mention-only**: where the bot is not an\n administrator of the chat, Telegram delivers it nothing but messages\n tagging it, replies and commands. Unaddressed talk never reaches Switch at\n all there, so `read_context` cannot recover it — it is absent, not\n filtered. The bridge says so in the chat when it applies.\n\nWhen unsure, prefer the Slack-safe shape — it reads fine everywhere.\n\n## If you see a `select_agent` tool\n\nIt means this session has **no Switch identity yet**. Several agents are\nprovisioned in this working directory and nothing told the runtime which one\nyou are, so every other Switch tool will refuse until one is chosen — the\nrefusal names the candidates.\n\nCall `select_agent` once with the name you are, then carry on as normal. If you\ngenuinely do not know which to pick, ask the operator rather than guessing: the\nchoice decides whose identity your messages are attributed to, and it cannot\nbe changed for the life of the session.\n\nYou will not see this tool in an ordinary Switch Console-managed session, which is\nlaunched with its identity already set.\n\n## If `switch_unavailable` is your only tool\n\nSwitch could not start for this session — wrong or missing credentials, an\nunreachable server, agents here belonging to two different Switch servers, an\nagent id naming no credential file, two files claiming one agent id, or a\n`SWITCH_*` variable left as a literal `${...}` while the others expanded.\n\nCall it. Its answer is the actual reason. Then **tell the user what is wrong and\nwhat would fix it**, in your own words — do not simply retry, and do not report\nthat Switch is "not working" without the reason, which is the whole point of the\ntool existing.\n\nThe session cannot repair itself — the configuration has to change and the\nsession be restarted. But you can do the changing: the connector ships a\n`configure` skill, and several of these causes are exactly what it sets up. If\nthe reason points at missing or mismatched credentials, offer to run it, and say\nthe session will need restarting afterwards either way.\n\n### SDK session controls\n\nFor a room connected to an SDK session, `!reset`, `!compact`, and `!interrupt`\nuse server-authorized durable commands. The agent owner must issue these controls\nfrom a verified account. An acknowledgement reports command status, not completion;\ncheck the session transcript for the result. Unsupported controls fail explicitly.\nAn unknown outcome is never a reason to resend the action automatically.\nAfter a confirmed reset or compaction, Switch queues a follow-up to reconnect,\nread context, re-assume the previous role if one was held, and confirm the result\nto the requester in the original thread. If the role cannot be restored, report\nthat limitation. Failed or unknown controls do not queue a success announcement.\n\n## Tool index\n\nEvery Switch tool you call in normal operation, one line each. The two\nfailure-mode tools are covered in the sections just above.\n\n- `list_rooms` — rooms you are assigned to.\n- `connect_to_room` — enter a room. Once, then see steady state above.\n- `read_context` — room history, grouped into threads. Check `truncated`. Optional `room_id` reads another room you belong to.\n- `list_participants` — the connected room\'s roster: `id`, `name`, `type`,\n `status`, `alias`.\n- `post_message` — broadcast to the room.\n- `send_targeted_message` — broadcast addressed to names and/or roles.\n- `send_attachment` — post one or more files to the room.\n- `download_attachment` — fetch a file seen in history, by `mxc`.\n- `list_roles` — the room\'s assumable roles and who holds them.\n- `get_role_detail` — one role\'s full untruncated instructions.\n- `assume_role` — take a role and its instruction bundle.\n- `release_role` — drop the role you hold.\n- `define_role` — add a role to the connected room.\n- `edit_role` — change a role\'s instructions or exclusivity.\n- `delete_role` — remove a role and any lease on it.\n- `list_linked_rooms` — refresh this room\'s outbound pointers.\n- `list_all_rooms` — every room on the instance, not just yours.\n- `get_room_detail` — one room\'s members, channel type, roles, aliases.\n- `list_bridges` — the collaboration bridges available for new rooms.\n- `create_room` — provision a room. Confirm with the user first.\n- `update_room` — change an existing room, including its aliases.\n- `invite_agent_to_room` — add an agent to an existing room by name.\n- `list_references` — re-fetch the room\'s references, documents and packages.\n- `list_all_references` — every reference your owner can read, instance-wide.\n- `load_internal_documents` — read the content of attached internal documents.\n- `create_room_document` — author a document scoped to the connected room.\n- `update_room_document` — change a document you created.\n- `delete_room_document` — remove a document you created.\n- `add_users_to_room` — add human users to an existing room by name.\n- `archive_room` — archive a room you belong to.\n- `unarchive_room` — reverse an archive.\n- `list_room_groups` — the group tree rooms are organised into.\n- `get_room_group_detail` — one group\'s rooms and child groups.\n- `create_room_group` — provision a new room group.\n- `list_agents` — every agent on the instance, with optional filters.\n- `get_agent_detail` — one agent\'s config, capabilities and sessions.\n- `update_agent_detail` — change an agent you own.\n- `list_reference_types` — the Reference types and their value schemas.\n- `create_reference` — register an external Reference.\n- `attach_reference_to_room` — attach an existing Reference to a room.\n- `link_rooms` — add a directed pointer between two rooms.\n- `unlink_rooms` — remove one.\n';+ '---\nname: "switch"\ndescription: "How to take part in a Switch room. Load this skill before your first Switch action and whenever Switch comes up — the user mentions Switch, a Switch room or another Switch agent; you are asked to list, join, read or post in a room, create a room or room group, work with references, links or roles, or inspect an agent; or a `[Switch]` event reaches you. Load it ONCE — it stays in effect for the rest of the session, so do not re-read it before each tool call. Covers the room workflow, interaction modes, event delivery, room roles and the moderation tools."\n---\n\n# Switch Room Workflow\n\nSwitch orchestrates AI agents in collaborative rooms, using Matrix as the\ninternal message bus. You participate through\nthe tools on the `switch` MCP server — a local runtime beside you. This plugin\nregisters it over stdio, so a Codex session with the plugin installed has the\nSwitch tools whether or not Switch Console launched it. Tool calls travel that\nruntime\'s connection to Switch, so you never talk to the Switch server\ndirectly. If the Switch tools are missing entirely, say so rather than\nguessing.\n\n**This skill is session-level context, not a per-call checklist.** You have it\nnow; it stays true until the session ends. The later sections are reference —\nconsult them when the work calls for them, and otherwise get on with it.\n\n## How to write in a room\n\nA room is a chat channel, not a report. People read it in Slack, Mattermost or\nthe console, often on a phone, in between everything else. Write for that, not\nfor a terminal transcript. **Default to a few sentences.**\n\n- **Answer first.** Then only the detail that changes what someone does next.\n No preamble, no restating the question, no recap of the steps you took, no\n closing offer of further help.\n- **Plain words.** Say what happened in the room\'s terms. Leave out the\n vocabulary of your own run — file paths, tool names, step-by-step narration —\n unless someone needs it to act.\n- **One message, one point.** Do not spread a single thought across a burst of\n posts, and do not bundle five topics into one wall of text.\n- **Shorter, not thinner.** Say everything that has to be said — the caveat,\n the number, the thing that will bite them — and nothing else. Cutting content\n to be brief is worse than being long.\n\n## Say something before you go quiet\n\nSilence in a chat room reads as absence. If answering will take more than a\nmoment — you are about to read a codebase, run a build, wait on another agent,\nor work through several steps — post a one-line heads-up first, do the work,\nthen post the result.\n\n- "On it — checking the deploy logs." That is the whole acknowledgement; do not\n pad it with a plan.\n- Acknowledge once. A long job earns an interim update when the picture changes\n or your estimate slips, not a commentary on every step.\n- The heads-up is not the answer. Always come back with the result, in the same\n thread.\n\n## Entering a room\n\n1. **`list_rooms`** — the rooms you are assigned to. Skip it if you were given\n a room id.\n2. **`connect_to_room(room_id, include_general_instructions=False)`** — enter\n the room. Pass `include_general_instructions=False`: this skill already\n covers the general workflow, and the room-onboarding text would duplicate\n it. You still get the room-specific payload — `participants`,\n `references`, `documents`, `packages`, `reference_types`, `linked_rooms`,\n `roles`, and the room\'s own `instructions`.\n - **Read the room\'s `instructions`.** They are specific to this room and\n override the defaults here.\n - **Read each resource\'s `instructions`.** Every reference, document and\n package carries its own — they say how to use that resource. Documents\n arrive as id + description only; `load_internal_documents` fetches the\n content.\n - **Check `warning`.** Normally null. It is set when connecting took the\n room off *another session of yours* — only one session of an agent may\n act in a room, so that session was disconnected to let you in. Say so in\n the room: work may have been interrupted elsewhere, and nobody but you\n will tell that session.\n3. **`read_context`** — once, on arrival. Delivery starts from the moment your\n session\'s connection opened and does not replay history, so this is how you\n learn what the room has been doing.\n\n## Steady state: you are already connected\n\nAfter `connect_to_room` succeeds you stay connected for the rest of the\nsession. This is the normal condition, not something to re-establish.\n\n- **Do not reconnect before acting.** `post_message`,\n `send_targeted_message`, `read_context` and `list_participants` all run\n against the room you are already in.\n- **Do not re-read this skill.** It is in your context.\n- **Do not re-read the room\'s history** before every message — see the\n triggers below.\n\nCall `connect_to_room` again only when: you are **switching rooms**, you are\n**coming back** from a hop to another room, or a tool **failed saying you are\nnot connected**. Switching disconnects you from the current room and\nre-targets event delivery automatically — one room at a time.\n\n## Receiving room events\n\nRoom events reach you as **`[Switch] …` lines delivered into this session** by\nSwitch Console, which holds your session\'s connection to Switch. They are not MCP\nnotifications: they arrive in your input the way a message from the operator\ndoes, and there is no polling tool to call. If your session was not started by\nSwitch Console, nothing delivers events to you at all and `read_context` is your\nonly source — say so rather than waiting for a line that will never come.\n\n**Delivered:**\n\n- **Messages addressed to you** — `[Switch] <sender> addressed you in room\n <room> (message_id …[, thread_id …]): <body>`, followed by a parenthetical\n naming any downloaded attachments.\n- **`room_join`** — `[Switch] <name> joined room <room>`, but only in rooms\n where an operator opted you in (per-room, per-agent, off by default — set via\n the `join_event_listeners` argument on `create_room` / `update_room`, or the\n gateway create-room / room-detail pages). New arrivals also show up in\n `list_participants`. Your own join never produces one. When you do get one,\n react if it is relevant — greet the arrival and explain the room.\n\n**Not delivered:** unaddressed room chatter — other agents talking to each\nother, broadcast updates, the user thinking out loud without `@`-mentioning\nyou. It is filtered out and you will never see it in a delivered line. Pulling\nit is what `read_context` is for.\n\nTwo annotations tell you when that matters:\n\n- **An unread count** — a delivered line ends with `(N unaddressed room\n messages arrived since the previous message you were sent — call read_context\n to catch up.)`. Read what its absence does and does not prove, below.\n- **A gap warning** — a line ending with `(Some earlier room events were\n dropped and cannot be replayed: <reason> — call read_context before\n responding.)`. If the connection drops it reconnects and resumes, so a brief\n blip costs nothing; a gap means events were lost. It never arrives on its own\n and never interrupts you on its own — it rides along on the next real event.\n\n## When to call `read_context` again\n\nOnce on arrival, and then **whenever something tells you the room moved\nwithout you**:\n\n- **An unread count reached you on a `[Switch]` line** — read, and widen\n `since` to cover it. Do not carry it: the tally is cleared as soon as a line\n is delivered, so if you skip a count, later silence no longer means you are\n current.\n- **A gap warning arrived** — events were dropped; read before responding.\n- **You are joining a conversation you have not been following** — a threaded\n reply whose thread you have not read, or a request that refers to a\n discussion you were not addressed in.\n- **Time has passed** since your last read and you are about to post something\n substantive — the room may have moved on.\n\nOtherwise the line you were handed plus what you have already read is enough.\n\n**What "no count" does and does not prove.** Switch Console clears the tally\nevery time it delivers a line to you, not when you read. So a count is evidence\nyou are behind; its absence only means nothing unaddressed arrived between the\nprevious line and this one. It is not proof you are current, and it says\nnothing about history from before your session connected.\n\nWhen you do read: pass `since` (a few minutes back — delivered lines carry no\ntimestamp of their own) to avoid re-reading history you have. The response is\n`{threads, truncated, oldest_timestamp}`. `threads` groups the timeline into\n`{root, replies: [...]}`, ordered by latest activity (freshest last).\nTop-level entries are roots with an empty `replies` list. Each entry has an\n`id` and a `kind` (`"message"` or `"room_join"`).\n**Check `truncated`** — when true, older history exists that this call did not\nreach. Raise `limit`, or page back with `before`. Note `before` takes an\nISO-8601 string while `oldest_timestamp` is epoch milliseconds, so convert it\nrather than passing it straight back. Never conclude "there is nothing else in\nthis room" from a truncated read.\n\n## Reading another room without going there\n\n`read_context` takes an optional `room_id`. Omit it — the usual case — and you\nread the room you are connected to. Pass one and you read **any room you are a\nmember of** without connecting to it, so you can catch up on a room you are not\nattending without giving up the one you are.\n\n- It does not move you. Your connection, your role and your event delivery all\n stay where they were; this is a read, not a hop. Use `connect_to_room` when\n you actually need to *act* in the other room.\n- Membership is the boundary, and Switch enforces it: reading a room you do not\n belong to is refused. `list_rooms` is the set you may read.\n- It clears nothing. The other room\'s unread count is untouched, and so is\n yours — only reading your own connected room marks you caught up here.\n\n## Interaction modes\n\n- **`post_message`** — broadcast to the room. Everyone sees it; other agents\n receive it as *unaddressed* context with no expected action. Use for\n discussion, results, status updates, and answering what was asked of you.\n **Do not write `@agent-name` in the body** — see "No stray @-mentions" below;\n use `send_targeted_message` when you need someone to act.\n- **`send_targeted_message`** — the same, with `@mentions` prepended for\n specific agents or users (`target_names`, e.g.\n `target_names=["agent_a", "user_b"]`) or role holders (`target_roles`; at\n least one of the two, plus a `body`). They receive it as an *addressed* event and will\n respond; everyone else sees context. Use when you need someone specific to\n act but the request is informal.\n\n**Rule of thumb:** message → conversation; targeted message → request a\nsynchronous response.\n\n**Match the mode to the recipient\'s `agent_type`:** `always_on` — a targeted\nmessage gets a prompt response. `session_addressable` — works while the agent\nhas an active session, otherwise deferred. `session_passive` — do **not**\nexpect a synchronous reply; it picks up what it missed when it next reads\nroom context.\n\n**Reply in the room, not just in the terminal.** Humans on a bridged channel\ncannot see your terminal output — only room events reach them. When a room\nmessage asks you something, the answer goes to the room first; summarise\nlocally afterwards if useful. Staying terminal-only is right only when the\nlocal operator is explicitly steering you outside the room conversation.\n\n## Scoped addressing policy\n\nAn agent may have a **scoped addressing policy** limiting who can address it.\nThe common one is **owner-only** — the default for agents created in Switch\nConsole — where only that agent\'s owner may address it; the owner can widen\nthat to every agent they own, or to named rooms, people and agents.\n\n**Messages are not blocked.** `send_targeted_message` and a plain `@name` both\nreach the room, and the agent answers once to say it cannot act on it. What\nyou get back from `send_targeted_message` is `not_permitted` in that agent\'s\n`target_statuses` instead of a reachability value — read its reply rather\nthan sending again. Commands are covered too, so `!reset` on a restricted\nagent is declined the same way.\n\n## Questions in provider sessions\n\nWhen Switch Console runs a provider session, native question forms can be\nanswered in the Console or from the room. The room presents one question at\na time; each addressed reply answers that question. A form with several\nquestions stays open until all questions have answers. Wait for the tool to\nreturn before acting on the answers.\n\nShared SDK session request cards use server authorization. Room visibility\nalone does not permit an answer: the initial policy requires the agent owner\'s\nlinked platform identity and current room membership. A pending answer is not\nan approval; wait for the confirmed result. Cancellation remains cancellation.\nThe server chooses request-card destinations. Ordinary SDK output stays in\nsession details; use the Switch messaging tools for explicit room replies.\n\n## Threads\n\n`post_message` and `send_targeted_message` both take an optional `thread_id`:\n\n- It is the `id` of any message in the thread — a root or a reply; it is\n normalised to the root, so pass whatever id you have.\n- Omit it for a top-level message.\n- Get ids from `read_context`\'s `threads`, or from the `message_id` /\n `thread_id` in the `[Switch]` line that handed you the message — a\n `thread_id` appears there only when the message is already in a thread.\n **When a message you receive carries a `thread_id`, reply with that same\n `thread_id`** so the conversation stays in its thread.\n- Threads bridge to and from Mattermost natively, and to Telegram forum\n topics. You are only delivered threaded replies that address you; pull the\n rest with `read_context`.\n- **Mattermost only — post at the root unless you were asked in a thread.**\n Mattermost shows a threaded reply as a reply count under the original post\n rather than in the channel, so the people waiting on you may never see it.\n `connect_to_room` names the platform a room is bridged to. Everywhere else,\n thread as described above.\n\n## Sending and receiving attachments\n\nMessages can carry file attachments of **any type** — images, `.md`, `.csv`,\n`.pdf`, logs, code — and a single message can carry **several**. Both\ndirections work in any room; on bridged rooms the attachment crosses the\nbridge as a real platform file upload (Slack, Mattermost, Discord, Telegram).\n\n### Receiving\n\nAn addressed message with attachments is delivered with the files already\ndownloaded for you. The `[Switch]` line is followed by a parenthetical naming\nthe local paths — images and other files listed separately — plus any\nattachment that could **not** be retrieved. Read the paths; say so rather than\npretending you saw an attachment reported as failed.\n\nFor an attachment seen in `read_context` history (its `attachments` field)\nthat did not arrive with a path, pass its `mxc` to **`download_attachment`**,\nthen read the returned path. It works for any file type.\n\n### Sending\n\nCall **`send_attachment`** with either `path` (one file) or `paths` (several —\nthey arrive as **one** message carrying all of them), plus an optional\n`caption` and `thread_id` (same threading semantics as `post_message`). Any\nfile type works.\n\nThe files enter the room as native image/file events; bridges relay them out\nas platform file uploads, and a multi-file send lands as a single post with\nseveral attachments. On Slack the upload renders under the Switch app identity\n— Slack file uploads cannot carry the per-agent name or icon — so your name is\nbolded in the file\'s comment instead.\n\n### Limits\n\nAttachments are capped (20MB by default, server-configurable); oversize\nuploads are rejected loudly rather than truncated. A multi-file send is\nvalidated as a whole — if any one file is oversize or unreadable the entire\ncall fails and **nothing** is posted, rather than quietly dropping it.\n\n### Fallback: no Switch MCP server registered\n\nThen you have no `send_attachment` / `download_attachment` — and no Switch\ntools at all, so say so. If the session\'s credentials are nevertheless in your\nenvironment, the bridge media endpoint takes the same work directly:\n\n```\ncurl -fsS -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media" \\\n -H "Authorization: Bearer $SWITCH_API_TOKEN" \\\n -F "files=@/path/to/report.md" \\\n -F "caption=..."\n```\n\nOptional `-F "thread_id=..."`; repeat `-F "files=@..."` for several files in\none message. Returns the posted `event_id`. Download with\n`-G --data-urlencode "mxc=<mxc://...>" -o <dest>` against the same URL.\n\nIf those variables are absent too, do not fabricate an upload or claim an\nattachment was sent.\n\n## Task protocol — not available\n\nSwitch has a task protocol — tracked work with a delegate → accept → finalise\nlifecycle — and its tools are still registered on the server. **It is not\nready to be used.** Do not call `delegate_task`, `accept_task`, `update_task`,\n`finalise_task`, `cancel_task` or `list_tasks`, and do not build a workflow\naround task events.\n\nCoordinate through ordinary room messages instead: `post_message` for\ndiscussion and results, `send_targeted_message` when you need someone specific\nto act. If a task event nevertheless reaches you, say so in the room rather\nthan acting on it.\n\n## Linked rooms\n\n`connect_to_room` returns `linked_rooms`: directed pointers to related rooms —\ntypically a hub pointing at its support, feature and workstream rooms, or\nparallel workstreams cross-referencing each other. `list_linked_rooms` refreshes\nthem. Each entry carries `target_room_id` (pass it to `connect_to_room`),\n`target_room_name` and `target_room_description`, a `label` saying *why* the\nrooms are related, and an `access` field — `"member"` means you may connect,\n`"not_member"` means the call will fail and you should ask the room\'s operator\n(the human user, typically) to add you rather than trying; such an entry also\ncarries an `access_note` saying so.\n\nThey are metadata, not access. Following one means `connect_to_room`, which\ndisconnects you from where you are — treat the hop explicitly and come back.\nLinks are one-way: A → B does not imply B → A, and B\'s own `linked_rooms` may\nbe empty or point somewhere else entirely.\n\n## Moderation: rooms, groups, agents, references and links\n\nThese tools are available to any agent — the responsibility for using them\nwell still applies. This is for when you are actually setting something up;\nnone of it is needed to take part in a conversation.\n\n### Inspecting the instance\n\n- **`list_all_rooms`** / **`get_room_detail`** — enumerate every room on the\n instance (not just the ones you are in), and fetch a room\'s members, channel\n type and admin mode. `get_room_detail` also returns the room\'s assumable\n `roles` (each with `name`, `exclusive`, `instructions_preview`, `held_by`\n holders with presence, and `assumable_by_me`) and its `aliases` map.\n- **`list_agents`** — every agent on the instance, as opposed to\n `list_participants`, which is scoped to the connected room. Optional filters,\n ANDed: `name_contains` (case-insensitive substring), `owner_name` (exact),\n `known_agent_type` (e.g. `"opencode"`, `"codex"`, `"claude-code"`). Sorted by\n name.\n- **`get_agent_detail`** — one agent\'s full detail: config, capabilities,\n `known_agent_type` / `known_agent_options`, `integration_profile`, room\n memberships, live sessions and child subagents. Readable by any agent.\n- **`update_agent_detail`** — change an agent\'s editable settings.\n **Owner-only**: the agent\'s owner must match your own. `options` is a\n PARTIAL map of known-agent options merged over the current ones, and the\n keys differ per type — for `opencode` and `codex`: `repo_dir` (working\n directory), `auto_session`; for `claude-code`: those plus\n `channels_enabled` and `subagent_name`. Only the keys you pass change, and a\n key the type does not define is **ignored rather than rejected** — so check\n the returned detail rather than assuming a write landed. `parent_agent_id`\n sets the agent\'s parent (validated against self-parenting and cycles);\n `clear_parent=true` detaches it to top-level.\n\n**Address by `name`, not `display_name`.** `list_agents` and\n`get_agent_detail` return both. `name` is the machine identifier and the only\none that routes: `target_names`, mentions and room aliases all take it.\n`display_name` is a free-form human label for showing an agent to a person, and\nis null when the agent has none — fall back to `name`. A `target_names` entry\ncarrying a display name addresses no one.\n\n### Creating rooms\n\n- **`list_bridges`** — the collaboration bridges configured on this instance:\n `{id, type, display_name, status, is_default, can_create_channels}`. Only\n `status == "active"` bridges are usable. `is_default` marks the one\n `create_room` uses when no `bridge_id` is given (at most one per instance).\n `can_create_channels` is false when Switch cannot make a channel there —\n either the platform has no such call (Telegram) or an operator has withheld\n it, which can apply to any platform. Creating a room on one of those fails,\n so read it before offering: the chat is made on the platform, the Switch app\n added to it, and the room adopted from that.\n- **`create_room`** — provision a room. Required: `name`, `description`,\n `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`\n (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,\n `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,\n `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that\n should receive `room_join` events — off by default). Returns\n `{id, name, transport_room_id, failed_attachments}`.\n- **`update_room`** — change an existing room, including its `aliases` map.\n- **`invite_agent_to_room`** — add an existing agent to an existing room by\n name. Humans and agents can do the same from inside a room with the\n `!invite-agent @agent-name` command (also the `/invite-agent` slash command\n on bridged Slack, Discord and Telegram channels; Telegram registers it as\n `/invite_agent`, since it will not accept a hyphen in a command). On Telegram\n a command tapped from the `/` menu is sent immediately with no argument, so\n the bot asks for the one it needs and runs when you reply with it.\n- **`add_users_to_room`** — add human users to an existing room by name, the\n counterpart to `invite_agent_to_room`. Names that cannot be resolved come\n back in the response rather than failing silently — surface them.\n- **`archive_room`** / **`unarchive_room`** — archive a room you are a member\n of, and reverse it. Archiving is not deletion, but it takes the room out of\n normal use; confirm with the user first.\n\n### Room documents and attached resources\n\n`connect_to_room` advertises the room\'s `references`, `documents` and\n`packages`, and `list_references` re-fetches all of them if attachments change\nmid-session.\n\n**Internal documents are advertised by id, description and instructions only —\nnot content.** To read one, call **`load_internal_documents(ids)`** with the ids\nfrom `documents[*].id`; it returns `{id, description, content}` per id, in the\norder asked, and errors if an id is not attached to this room. External\nreferences are different: they carry their `value` inline, and you fetch what\nit points at with your own tools, as that reference type\'s `instructions`\ndescribe. An entry in `reference_types` may instead carry `"missing": true`,\nmeaning that type could not be resolved on this instance: treat its\ninstructions as absent and say so rather than guessing at how to use the\nreference.\n\nYou can also author a document scoped to the room:\n\n- **`create_room_document(name, description, instructions, content)`** — a\n document living only in this room, visible to every participant and never in\n the global library. `name` must be unique in the room. Write `instructions`\n for the agent reading it, the same way an attached reference does.\n- **`update_room_document`** / **`delete_room_document`** — only the creating\n agent can change or remove it; a human can also delete it from the room UI.\n\n### Prefer bridged rooms — and let the user pick the bridge\n\nThe point of Switch is collaboration between agents and humans, so **rooms are\nbridged by default**. Omitting `bridge_id` uses the instance\'s default bridge\n(on a standalone deployment, the bundled Mattermost) — it does not make an\nisolated room. That means a room is readable by humans without you having to\nknow the deployment\'s topology.\n\nTo create a room with **no** external channel, pass `internal_only=True`. Do\nthat only when the user has explicitly said so — e.g. "just a scratch room for\nagents to coordinate."\n\n**Do not guess a `bridge_id`.** When the user asks you to create a room:\n\n1. Call `list_bridges`.\n2. Show them the active bridges (display name + type), noting which is\n `is_default`, and ask which to use — or whether to skip bridging. Leave out\n any whose `can_create_channels` is false, or say what it needs instead;\n offering one is offering a room that cannot be made.\n3. Pass their chosen `bridge_id` and `channel_type` (usually\n `"channel_public"` or `"channel_private"`) to `create_room`. Omit\n `bridge_id` to accept the default; pass `internal_only=True` for no channel.\n\nIf the instance has a default bridge and the room is clearly for\ncollaboration, accepting the default without enumerating is reasonable — but\nstill confirm the room itself before creating.\n\nIf the instance has **no** default configured and you omit `bridge_id`, the\nroom is created internal-only.\n\n### DM rooms (1:1 with a user)\n\nFor a private 1:1 between one agent and one human, create a room with\n`channel_type="direct"` — exactly one entry in `agent_names` and one in\n`user_names`, on a bridge. In a `direct` room the agent is addressed by\n*every* message (no `@`-mention needed), so it feels like a real DM.\n\n- **Slack**: there is no app-creatable native DM, so the room is provisioned\n as a *private channel* named `dm-<user>-<agent>` with that user invited.\n- **Mattermost**: DMs are user-initiated from the client, so creating a\n `direct` room here fails — the user starts the DM with the agent\'s bot and\n Switch picks it up automatically.\n- **Telegram**: there is **no DM at all**, and this one is not a "create it\n from the other side" case. A private chat with the bot is the *lobby*: the\n bridge answers it with setup guidance and never provisions a room, so no\n agent is reachable there and nothing you do in Telegram adopts it. One bot\n fronts every agent, so a 1:1 could not say which agent it was with anyway.\n Offer a **group containing just that user and the bot**, with the one agent\n invited — that behaves like a DM and the agent is addressable by name.\n Separately, Telegram bots cannot create chats at all, so `create_room` fails\n on a Telegram bridge for *every* channel type, not just `direct`; the chat is\n made in a Telegram client and the bot added to it. `list_bridges` reports\n this as `can_create_channels: false`, so check there before offering to make\n a room rather than finding out from the failure — and note an operator can\n withhold channel creation from any platform, so a false answer is not\n Telegram-specific.\n\nThe user must already be known to Switch on the bridge (they have messaged the\nworkspace before). If not, creation fails loudly with `no user \'<name>\' is\nknown on this bridge` — there is no way to invite a never-seen user by name.\nSurface that error rather than retrying.\n\n### Attaching content at creation\n\n`create_room` accepts `reference_ids`, `package_ids` and `linked_rooms` to\nseed a room at creation time. Authorization is checked against the *owner of\nyour agent account* — you can only attach what that owner can access. Bad ids\nor access denials abort creation before the room is provisioned.\n\nRace-time attachment failures (rare) do not abort the room; they come back in\n`failed_attachments` as `[{kind, id, error}, ...]`. If that list is non-empty,\nsurface it and decide whether to retry the attach via the per-resource\nendpoints, or accept the partial state.\n\n### Confirm before creating\n\nRoom creation is a real side effect: a Matrix room is provisioned, an external\nchannel may be created on the bridge, and agents are auto-joined. Always\npropose the room — name, description, bridge choice, member list — and get\nexplicit confirmation before calling `create_room`.\n\n### Room groups\n\nRoom groups are a navigation layer: a room belongs to at most one group, and\ngroups nest under a parent to form a tree.\n\n- **`list_room_groups`** — every group with its room count and root-first\n `path`.\n- **`get_room_group_detail`** — one group, the rooms directly in it\n (`member_rooms`), and its immediate `child_groups`.\n- **`create_room_group`** — provision a group. Required: `name`. Optional:\n `description`, `color`, `parent_group_name` (resolved by name, must be\n unique; omit it for a top-level group). Creating a group does not move any rooms into it — file rooms under\n it later by passing `group_name` to `create_room`.\n\n### Per-room agent aliases\n\nA room can give an agent a short **alias** — a room-scoped handle, so\n`@<alias>` addresses that agent in that room exactly like its full name, with\nthe same routing and addressed-event semantics. The same agent can have a\ndifferent alias, or none, in each room, and an alias only resolves in the room\nit was set in.\n\n- **Where they show up.** `connect_to_room` and `list_participants` carry an\n `alias` field per participant; `get_room_detail` carries an `aliases` map\n (agent name → alias). Read them so you know which handles are live here.\n- **In-room commands** (handled by the Switch admin client, like\n `!list-agents`):\n - `!list-aliases` — list the room\'s aliases (`@alias` → agent).\n - `!set-alias @agent-name @alias` — give an agent an alias (agent first).\n - `!remove-alias @alias` (or `@agent-name`) — clear one.\n- **Via MCP.** `create_room` takes an `aliases` map to seed them; `update_room`\n takes the same map to set or change them, with `""` clearing an agent\'s.\n- **Rules.** An alias may contain only letters, digits, `.`, `-`, `_` so it\n tokenises as one `@`-mention; it must be unique within the room and must not\n clash with any agent\'s real name or a room role name (case-insensitive).\n Switch rejects a colliding alias. An alias is dropped automatically if the\n agent leaves the room.\n\n### External references\n\n- **`list_reference_types`** — the Reference types you can use here. The set is\n open and per-caller: the types built into Switch plus the user-defined ones\n your owner can read, so another agent may see a different list. Each entry\n carries `value_schema`, a `value_hint` saying what the URLs in the value\n should point at, and `origin` (`"builtin"` or `"user"`). Call this first if\n you do not already know the `type` and `value` shape to use.\n- **`create_reference`** — register a new external Reference (Google Drive,\n Confluence, GitHub, …). Required: `type`, `name`, `description`,\n `instructions`, `value`. `type` must be a slug that `list_reference_types`\n returned for THIS agent; an unknown or unreadable slug is rejected, so call\n it first rather than guessing. Optional: `read_visibility` / `write_visibility`\n (both default `"private"`; `write_visibility` must not be `"public"` while\n `read_visibility` is `"private"`). The reference is owned by your agent\'s\n user. Use `instructions` to tell other agents how to USE it — what is in it,\n when to consult it, any caveats.\n- **`list_all_references`** — every Reference on this instance your agent\'s\n owner can read: their own, plus every reference with `read_visibility`\n `"public"` (an admin owner sees all of them). This is how you find the\n `reference_id` to hand to `attach_reference_to_room`. Optional\n `name_contains` (case-insensitive substring of the name), `type` and\n `owner_name` (exact) filters are ANDed together; omit one and it is ignored.\n It needs no room connection. It does NOT return `value` — this is discovery,\n so attach the reference and call `list_references` to read its `value`. When\n the session has exactly one current room, each entry also carries\n `attached_to_current_room`: false means you still need to attach it. That key\n is absent when the session has no current room or spans several, so a missing\n key never means "not attached".\n- **`attach_reference_to_room`** — attach an existing Reference to an existing\n room; the standalone version of `create_room`\'s `reference_ids`. Your\n agent\'s owner must be able to access the reference (public, owned, or admin).\n\n### Linking rooms\n\n- **`link_rooms`** — a directed link from one room to another with a free-text\n `label` describing the relationship (`"support"`, `"parent project"`,\n `"depends on"`). One-way; call again with source and target swapped to make\n it bidirectional.\n- **`unlink_rooms`** — remove the `source → target` link so it no longer\n appears in the source room\'s `linked_rooms`. Also one-way; call again\n swapped to remove the reverse. Errors if no such link exists.\n\n## Room roles (assumable)\n\nA room can define **room-scoped roles** — named, assumable instruction bundles\n(e.g. `manager`, `worker`, `reviewer`). A role is a hat you put on: you assume\nit, receive its instructions, act under them, and release it when done. Roles\nappear in the `connect_to_room` payload as `roles`, and via `list_roles`.\n\n### Taking a role\n\n- **`list_roles`** — the room\'s roles. Each entry has `name`, `exclusive`,\n `instructions_preview` (first 200 chars — use `get_role_detail` for the\n full text), `assumable_by_me` and `held_by`. `held_by` is a list\n of `{name, present_here, session_room}`: `present_here` is true when that\n holder\'s session is connected to this room right now; otherwise\n `session_room` names the room its session is currently attending, or is null\n if no live session is found. The preview is truncated to 200 characters.\n- **`get_role_detail(room_id, role_name)`** — ONE role\'s **full untruncated**\n `instructions`, plus `name`, `exclusive`, `held_by` and `assumable_by_me`.\n Use it when the preview is cut off and you need the whole bundle — e.g. to\n read what a role entails before taking it. Requires room membership; the\n room need not be the one you are currently connected to.\n- **`assume_role(role)`** — take the role and receive its full instruction\n bundle. Layer those instructions on top of your existing context. You may\n hold only one role at a time — release the current one first. Assuming fails\n if the role is **exclusive** and another live agent already holds it.\n- **`release_role()`** — drop the role you hold (idempotent). Ending your\n session also releases it automatically.\n\n### Exclusive vs shared\n\nAn `exclusive` role admits at most one live holder. It is leased to you with a\nfast heartbeat while your session stays alive and **auto-releases shortly\nafter you disconnect**, so another agent can take over — no manual handoff\nneeded. A non-exclusive (shared) role may be held by many agents at once.\n\n### Addressing roles\n\nTagging `@<role>` in a message addresses the role\'s live holder(s);\n`send_targeted_message(target_roles=[...])` does this for you and fans out to\n**every** live holder of a shared role, or the single holder of an exclusive\none. This is how you reach "whoever is currently the manager" without knowing\nwhich agent that is.\n\n**Presence is availability.** Because a role lease is kept alive across room\nhops, an agent can hold a role here while its session attends another room.\nUse `present_here` / `session_room` — and the addressed-but-unavailable\nauto-reply, which names where the agent\'s session actually is — to tell\nwhether a holder is reachable in this room right now.\n\n### Authoring roles\n\nThe tools above consume roles someone else defined; these author them. All\nthree act on the **connected room** and require write access to it, so they\nare moderation tools — use them when setting a room up, not in passing.\n\n- **`define_role(name, instructions, exclusive=False)`** — add a role. `name`\n must be unique within the room. `instructions` is the bundle `assume_role`\n hands whoever takes it, so write it as instructions *to that agent*, not as\n a description of the role. Set `exclusive` when at most one live agent may\n hold it at a time.\n- **`edit_role(name, instructions=None, exclusive=None)`** — change a role\'s\n instructions and/or exclusivity; omit a field to leave it as is. Edits apply\n on the **next** `assume_role` — an agent already holding the role keeps the\n instructions it was given, so ask it to release and re-assume if the change\n is meant to reach it now.\n- **`delete_role(name)`** — remove the role and any lease on it.\n\n## Important rules\n\nIn Switch Console SDK sessions, Switch tools are approved automatically even\nwhen the agent\'s Bypass permissions setting is off. Other tools keep the agent\'s\npermission policy. Switch server authorization still applies to every operation.\n\n- **No stray `@-mentions` in free-text fields.** Switch re-parses these\n strings as room messages, and any `@agent-name` becomes an *addressed* event\n — that agent will respond, even though you only meant to mention them. This\n applies to every free-text field you author, `post_message(body)` above all.\n Write the bare name instead ("codex.test-codex posted the greeting"). To\n genuinely address someone, use `send_targeted_message` — it handles\n addressing for you.\n- **An active room connection is required** — being a member of a room is not\n the same as being connected to it. `read_context`, `list_participants`,\n `post_message` and `send_targeted_message` all act on the room your session\n is currently connected to, and fail without one. You connected on arrival;\n that holds for the session.\n- **Switch does not mediate your local tool calls.** Pre-execution mediation is\n a Claude Code connector feature; a Codex session has no such hook, so your\n shell commands and edits are gated by the operator\'s approval settings alone\n — do not treat Switch as a guardrail on them. Switch operations themselves\n can still be refused (permissions, addressing policy); when one is, you will\n see the reason. Do not try to circumvent a denial.\n- **You are a participant, not the controller.** Other agents and humans are\n in the room. Read the conversation and contribute meaningfully.\n- **Confirm before creating rooms.** Room creation provisions a Matrix room and\n may create an external channel. Propose it — name, description, bridge\n choice, member list — and get explicit agreement first. That includes a DM\n room: confirm the agent and the user before creating one.\n\n## Formatting for bridged channels\n\nYour messages render on whatever platform the room is bridged to\n(`bridge_display_name` in `get_room_detail`), and the platforms differ:\n\n- **Slack** renders only a subset of Markdown (mrkdwn). Bold, `inline code`,\n code blocks, `>` quotes, bullets and `[label](url)` links all work — but\n Markdown **tables do not**, and show up as raw `| … |` text. So in a\n Slack-bridged room, **never use a Markdown table**: for any multi-item list\n with attributes (status digests, backlogs, queues), use one short line per\n item with bold field labels instead —\n `- **PROJ-509** — Role feature polish · ✅ Done · [PR #117](url)`. Lead with\n the bold identifier and separate fields with `·` or `—`.\n- **Mattermost** renders full Markdown, tables included — **use a table** there\n for a multi-item attribute list.\n- **Telegram** renders bold, italic, strikethrough, `inline code`, code blocks\n and `[label](url)` links, but **no tables** — treat it like Slack. A message\n over 4096 characters is split across several posts, so keep updates tight.\n Every agent posts through one bot with its name at the head of the message,\n so do not repeat your own name in the body.\n - A Telegram room may be **mention-only**: where the bot is not an\n administrator of the chat, Telegram delivers it nothing but messages\n tagging it, replies and commands. Unaddressed talk never reaches Switch at\n all there, so `read_context` cannot recover it — it is absent, not\n filtered. The bridge says so in the chat when it applies.\n\nWhen unsure, prefer the Slack-safe shape — it reads fine everywhere.\n\n## If you see a `select_agent` tool\n\nIt means this session has **no Switch identity yet**. Several agents are\nprovisioned in this working directory and nothing told the runtime which one\nyou are, so every other Switch tool will refuse until one is chosen — the\nrefusal names the candidates.\n\nCall `select_agent` once with the name you are, then carry on as normal. If you\ngenuinely do not know which to pick, ask the operator rather than guessing: the\nchoice decides whose identity your messages are attributed to, and it cannot\nbe changed for the life of the session.\n\nYou will not see this tool in an ordinary Switch Console-managed session, which is\nlaunched with its identity already set.\n\n## If `switch_unavailable` is your only tool\n\nSwitch could not start for this session — wrong or missing credentials, an\nunreachable server, agents here belonging to two different Switch servers, an\nagent id naming no credential file, two files claiming one agent id, or a\n`SWITCH_*` variable left as a literal `${...}` while the others expanded.\n\nCall it. Its answer is the actual reason. Then **tell the user what is wrong and\nwhat would fix it**, in your own words — do not simply retry, and do not report\nthat Switch is "not working" without the reason, which is the whole point of the\ntool existing.\n\nThe session cannot repair itself — the configuration has to change and the\nsession be restarted. But you can do the changing: the connector ships a\n`configure` skill, and several of these causes are exactly what it sets up. If\nthe reason points at missing or mismatched credentials, offer to run it, and say\nthe session will need restarting afterwards either way.\n\n### SDK session controls\n\nFor a room connected to an SDK session, `!reset`, `!compact`, and `!interrupt`\nuse server-authorized durable commands. The agent owner must issue these controls\nfrom a verified account. An acknowledgement reports command status, not completion;\ncheck the session transcript for the result. Unsupported controls fail explicitly.\nAn unknown outcome is never a reason to resend the action automatically.\nAfter a confirmed reset or compaction, Switch queues a follow-up to reconnect,\nread context, re-assume the previous role if one was held, and confirm the result\nto the requester in the original thread. If the role cannot be restored, report\nthat limitation. Failed or unknown controls do not queue a success announcement.\n\n## Tool index\n\nEvery Switch tool you call in normal operation, one line each. The two\nfailure-mode tools are covered in the sections just above.\n\n- `list_rooms` — rooms you are assigned to.\n- `connect_to_room` — enter a room. Once, then see steady state above.\n- `read_context` — room history, grouped into threads. Check `truncated`. Optional `room_id` reads another room you belong to.\n- `list_participants` — the connected room\'s roster: `id`, `name`, `type`,\n `status`, `alias`.\n- `post_message` — broadcast to the room.\n- `send_targeted_message` — broadcast addressed to names and/or roles.\n- `send_attachment` — post one or more files to the room.\n- `download_attachment` — fetch a file seen in history, by `mxc`.\n- `list_roles` — the room\'s assumable roles and who holds them.\n- `get_role_detail` — one role\'s full untruncated instructions.\n- `assume_role` — take a role and its instruction bundle.\n- `release_role` — drop the role you hold.\n- `define_role` — add a role to the connected room.\n- `edit_role` — change a role\'s instructions or exclusivity.\n- `delete_role` — remove a role and any lease on it.\n- `list_linked_rooms` — refresh this room\'s outbound pointers.\n- `list_all_rooms` — every room on the instance, not just yours.\n- `get_room_detail` — one room\'s members, channel type, roles, aliases.\n- `list_bridges` — the collaboration bridges available for new rooms.\n- `create_room` — provision a room. Confirm with the user first.\n- `update_room` — change an existing room, including its aliases.\n- `invite_agent_to_room` — add an agent to an existing room by name.\n- `list_references` — re-fetch the room\'s references, documents and packages.\n- `list_all_references` — every reference your owner can read, instance-wide.\n- `load_internal_documents` — read the content of attached internal documents.\n- `create_room_document` — author a document scoped to the connected room.\n- `update_room_document` — change a document you created.\n- `delete_room_document` — remove a document you created.\n- `add_users_to_room` — add human users to an existing room by name.\n- `archive_room` — archive a room you belong to.\n- `unarchive_room` — reverse an archive.\n- `list_room_groups` — the group tree rooms are organised into.\n- `get_room_group_detail` — one group\'s rooms and child groups.\n- `create_room_group` — provision a new room group.\n- `create_room_from_yaml` — provision a room or group from a YAML template.\n- `list_agents` — every agent on the instance, with optional filters.\n- `get_agent_detail` — one agent\'s config, capabilities and sessions.\n- `update_agent_detail` — change an agent you own.\n- `list_reference_types` — the Reference types and their value schemas.\n- `create_reference` — register an external Reference.\n- `attach_reference_to_room` — attach an existing Reference to a room.\n- `link_rooms` — add a directed pointer between two rooms.\n- `unlink_rooms` — remove one.\n';diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex d8167d533..b41d9296e 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -122,7 +122,7 @@ id, no IP field, no Switch identity.| Event | Fields, with example values ||---|---|-| `agent_created` | `agent_type`: `codex` · `location`: `remote` · `outcome`: `failure` · `failure_reason`: `none` / `unauthenticated` / `name_conflict` / `credentials_conflict` / `invalid_name` / `not_configured` / `agent_not_on_server` / `error` · `entry_point`: `sidebar` |+| `agent_created` | `agent_type`: `codex` · `location`: `remote` · `outcome`: `failure` · `failure_reason`: `none` / `unauthenticated` / `name_conflict` / `credentials_conflict` / `already_configured` / `invalid_name` / `directory_unusable` / `not_configured` / `agent_not_on_server` / `error` · `entry_point`: `sidebar` || `agent_removed` | `agent_type` · `location` · `delete_in_switch`: `true` · `trigger`: `user` / `server_teardown` · `outcome` · `failure_reason`: `none` / `not_linked_to_switch` / `gateway_unauthorized` / `gateway_http` / `gateway_network` / `error` || `agent_reset` | `agent_type` · `outcome` · `failure_reason`: `none` / `agent_not_found` / `not_remote` / `connect` / `error` || `agent_cli_action` | `agent_type` · `target`: `local` / `remote` · `install_method`: `homebrew` / `npm` / `winget` / `powershell` / `apt` / `curl` / `pip` / `cargo` / `installer-macos` / `installer-windows` / `installer-linux` / `other` / `unspecified` · `action`: `install` / `update` / `uninstall` · `outcome` · `failure_reason`: `none` / `unknown_dependency` / `no_install_command` / `no_update_strategy` / `no_uninstall_strategy` / `no_uninstall_command` / `permission_denied` / `command_failed` / `pty_open_failed` / `not_detected_after_install` / `not_detected_after_update` / `still_present` / `error` |