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
feat(switch): runtime resolves its own Switch credentials, and the token leaves the working tree (CHOO-1962) (#141)
Christian McDermottfebfcdae5752
diff --git a/artifacts.yaml b/artifacts.yamlindex d55f2b633..d18655805 100644--- a/artifacts.yaml+++ b/artifacts.yaml@@ -82,7 +82,7 @@ artifacts:agent-runtime:description: The Switch protocol client and MCP runtime, published to a registry.- version: 0.1.6+ version: 0.2.0declared_in: dash/packages/switch-agent-runtime/package.jsonsidecar:@@ -127,12 +127,12 @@ artifacts:switch-connector:description: The Claude Code connector plugin.- version: 0.7.9+ version: 0.8.0declared_in: connectors/claude-code-plugin/.claude-plugin/plugin.jsonswitch-connector-codex:description: The Codex connector plugin.- version: 0.2.1+ version: 0.2.2declared_in: connectors/codex-plugin/.codex-plugin/plugin.jsoncontracts:diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.jsonindex 5a4f41ce8..5a0fd165e 100644--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json@@ -1,5 +1,5 @@{"name": "switch-connector",- "version": "0.7.9",+ "version": "0.8.0","description": "Connect Claude Code to a Switch platform instance as a participating agent"}diff --git a/connectors/claude-code-plugin/.mcp.json b/connectors/claude-code-plugin/.mcp.jsonindex 4e898198e..b498ff6fa 100644--- a/connectors/claude-code-plugin/.mcp.json+++ b/connectors/claude-code-plugin/.mcp.json@@ -2,12 +2,7 @@"mcpServers": {"switch": {"command": "npx",- "args": ["-y", "@sandbox-quantum/[email protected]"],- "env": {- "SWITCH_API_ENDPOINT": "${SWITCH_API_ENDPOINT}",- "SWITCH_API_TOKEN": "${SWITCH_API_TOKEN}",- "SWITCH_AGENT_ID": "${SWITCH_AGENT_ID}"- }+ "args": ["-y", "@sandbox-quantum/[email protected]"]}}}diff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.mdindex 4e3a2cafb..b625d827e 100644--- a/connectors/claude-code-plugin/skills/configure/SKILL.md+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md@@ -13,13 +13,16 @@ local Switch runtime can connect.The plugin no longer uses Claude Code's `userConfig` block (which is globaland can't be overridden per-project). Instead, both pieces of the plugin-read three environment variables at startup:+read three values at startup:- `SWITCH_API_ENDPOINT` — Switch server URL-- `SWITCH_API_TOKEN` — the agent's API key (returned at registration)- `SWITCH_AGENT_ID` — the agent's ID (returned at registration)+- `SWITCH_API_TOKEN` — the agent's API key (returned at registration)-Claude Code populates these from the `env` block in a settings file. By+They reach the runtime one of two ways: from the environment, when something+(switchdash) sets it, or read by the runtime itself from the per-agent+`.switch/agents/<name>.json`. The settings file carries only the first two, so+the token sits in exactly one place. Bychoosing project-local vs. user-global settings, the user decides whetherthis Switch identity is tied to one repo or shared across all of them.This skill walks through registration and writes that block.@@ -109,8 +112,9 @@ configured:directory; do not create it yet)- User-global: `~/.claude/settings.json`-If either contains `env.SWITCH_API_TOKEN` **and** `env.SWITCH_AGENT_ID`-the plugin is already wired up. Report what's there (server URL, agent+If either contains `env.SWITCH_AGENT_ID` **and** `env.SWITCH_API_ENDPOINT`+the plugin is already wired up. (Do not look for `env.SWITCH_API_TOKEN` —+a correctly configured agent has none there; its token is under `$HOME`.) Report what's there (server URL, agentid, which file) and use `AskUserQuestion` to offer three choices:- **Keep it** — stop the skill. Re-registering would mint a fresh agent@@ -429,12 +433,38 @@ show the user the HTTP status and response body, then stop.retry with `overwrite:true` silently.- Any other non-2xx — show the status and body, then stop.-## Step 10 — Write settings+## Step 10 — Write settings, and the agent's credentials++Two files, with different jobs. The settings file is Claude Code's own and is+read by **every** session in the directory, so it carries no credential — only+which agent this directory is. The per-agent credentials file is what+authenticates one specific agent, and is what the Switch runtime reads when+nothing sets `SWITCH_*` in the environment.++**10a — the settings file.** Read the target settings file (create with `{}` if+absent). Merge into the top-level `env` object, preserving any other keys (the+user may have unrelated settings there — permissions, keybindings, plugin+toggles):++```json+{+ "env": {+ "SWITCH_API_ENDPOINT": "<url from step 2>",+ "SWITCH_AGENT_ID": "<id from step 7>"+ }+}+```++**Do not put `SWITCH_API_TOKEN` here.** If the file already has one from an+older setup, remove it — the credential belongs in one place, and this is not+it.++Use `Read` to load the existing JSON, parse it, merge, then `Write` the full+result back. Do not edit the file blindly with a regex — JSON formatting and+adjacent keys matter, and a bad merge can break unrelated Claude Code config.-Read the target settings file (create with `{}` if absent). Merge the new-values into the top-level `env` object, preserving any other keys in the-file (the user may have unrelated settings there — permissions,-keybindings, plugin toggles):+**10b — the credentials file.** Write `.switch/agents/<agent name>.json` in the+working directory, in the same shape switchdash writes:```json{@@ -446,13 +476,12 @@ keybindings, plugin toggles):}```-If `env` does not exist, add it. If the keys already exist with-different values, overwrite them — the user already confirmed in step 1.+Create `.switch/agents/.gitignore` containing `*` **before** writing it, so the+token is never briefly tracked. Add `.switch/` to the repo's own `.gitignore`+too if it is not already covered.-Use `Read` to load the existing JSON, parse it, merge, then `Write` the-full result back. Do not edit the file blindly with a regex — JSON-formatting and adjacent keys matter, and a bad merge can break unrelated-Claude Code config.+The runtime reads this file itself (`switch-agent-runtime` 0.2.0+), so no `env`+block in any MCP config is needed to carry the credentials.## Step 11 — Confirm@@ -460,14 +489,14 @@ Report to the user:- The agent name and ID that were registered with Switch.- Which settings file was written.-- That they need to **restart Claude Code** (or reload the session) for- the new `env` block to take effect — the `switch` MCP server and- Switch runtime only reads environment variables at startup,- so an active session won't see the new values.+- Which settings file was written, and that the credentials went to+ `.switch/agents/<name>.json` (git-ignored) rather than into the settings file.+- That they need to **restart Claude Code** (or reload the session) —+ the runtime resolves its identity once at startup, so an active+ session won't see the new credentials.-Do **not** print the API token. It's now in the settings file; the user-can find it there if they need it. Echoing secrets into the transcript-is a common way they leak into logs or screenshots.+Do **not** print the API token. Echoing secrets into the transcript is a+common way they leak into logs or screenshots.## Step 12 — Bring in existing Claude Code subagents (optional)@@ -598,11 +627,11 @@ is exactly the path the offline-session command points `--settings` at:}```-These files hold **per-subagent API tokens** — treat them exactly like-the main settings file: write the token only here, never echo it. Ensure-the directory is git-ignored: create `.claude/switch-subagents/.gitignore`-containing `*` (or add the directory to the repo's `.gitignore`) so the-tokens never get committed.+These files hold **per-subagent API tokens** — treat them exactly like the+per-agent credentials file: write the token only here, never echo it. Ensure the+directory is git-ignored: create `.claude/switch-subagents/.gitignore`+containing `*` (or add the directory to the repo's `.gitignore`) so the tokens+never get committed.### 12f — Tell the user how to launch a subagent@@ -619,10 +648,10 @@ cd <repo> && claude "connect to switch room <name>" \> ⚠️ **Both `--agent` and `--settings` are required — together.** `--agent`> adopts the subagent persona; `--settings` supplies *that subagent's own*> Switch credentials. Dropping `--settings` does **not** error — the session-> launches and silently authenticates as the **parent** agent, so the-> subagent's actions get attributed to the wrong identity. Always pass both.-> (Likewise, the settings file alone without `--agent` just runs the parent-> persona with the subagent's token.) Tell the user this explicitly.+> launches and silently authenticates as the **parent** agent, so the subagent's+> actions get attributed to the wrong identity. Always pass both. (Likewise, the+> settings file alone without `--agent` just runs the parent persona with the+> subagent's token.) Tell the user this explicitly.Switch also posts this exact command automatically whenever someoneaddresses the subagent in a room while it has no live session (it'sdiff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex aa288aeaa..30650668c 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -684,3 +684,31 @@ tell whether a holder is reachable in this room right now.with a `label`.- `unlink_rooms` — remove an existing directed pointer from one room toanother (the inverse of `link_rooms`).++## If you see a `select_agent` tool++It means this session has **no Switch identity yet**. Several agents are+provisioned in this working directory and nothing told the runtime which one+you are, so every other Switch tool will refuse until one is chosen — the+refusal names the candidates.++Call `select_agent` once with the name you are, then carry on as normal. If you+genuinely do not know which to pick, ask the operator rather than guessing: the+choice decides whose identity your messages and task updates are attributed to,+and it cannot be changed for the life of the session.++You will not see this tool in an ordinary switchdash-managed session, which is+launched with its identity already set.++## If `switch_unavailable` is your only tool++Switch could not start for this session — wrong or missing credentials, an+unreachable server, or agents here belonging to two different Switch servers.++Call it. Its answer is the actual reason. Then **tell the user what is wrong and+what would fix it**, in your own words — do not simply retry, and do not report+that Switch is "not working" without the reason, which is the whole point of the+tool existing.++Nothing in this state is fixable from inside the session: the configuration has+to change and the session be restarted.diff --git a/connectors/codex-plugin/.codex-plugin/plugin.json b/connectors/codex-plugin/.codex-plugin/plugin.jsonindex c05b4747f..1acd88815 100644--- a/connectors/codex-plugin/.codex-plugin/plugin.json+++ b/connectors/codex-plugin/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "switch-connector-codex",- "version": "0.2.1",+ "version": "0.2.2","description": "Connect Codex to a Switch platform instance as a participating agent","skills": "./skills/","mcpServers": "./.mcp.json"diff --git a/connectors/codex-plugin/README.md b/connectors/codex-plugin/README.mdindex 2946c910e..89e186cee 100644--- a/connectors/codex-plugin/README.md+++ b/connectors/codex-plugin/README.md@@ -72,6 +72,14 @@ switchdash's remaining job for the server is to put the credentials this confignames into the session's environment, read from the agent's`.switch/agents/<slug>.json`.+Standalone — no switchdash — nothing populates that environment, and since+`switch-agent-runtime` 0.2.0 the runtime reads that same file itself rather than+exiting. Where a working directory names several agents it serves a+`select_agent` tool and refuses the rest until the session picks one; where it+can find no usable agent at all it serves a single `switch_unavailable` tool+that reports why, rather than dying before the MCP handshake and leaving the+session with no explanation.+Because a plugin is only upgraded when a user clicks Update in switchdash'ssettings, and Codex caches each version in its own directory, an install on aplugin older than this one has no Switch tools until it is upgraded.diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.mdindex b86aab18b..040e347fb 100644--- a/connectors/codex-plugin/skills/switch/SKILL.md+++ b/connectors/codex-plugin/skills/switch/SKILL.md@@ -695,3 +695,31 @@ tell whether a holder is reachable in this room right now.with a `label`.- `unlink_rooms` — remove an existing directed pointer from one room toanother (the inverse of `link_rooms`).++## If you see a `select_agent` tool++It means this session has **no Switch identity yet**. Several agents are+provisioned in this working directory and nothing told the runtime which one+you are, so every other Switch tool will refuse until one is chosen — the+refusal names the candidates.++Call `select_agent` once with the name you are, then carry on as normal. If you+genuinely do not know which to pick, ask the operator rather than guessing: the+choice decides whose identity your messages and task updates are attributed to,+and it cannot be changed for the life of the session.++You will not see this tool in an ordinary switchdash-managed session, which is+launched with its identity already set.++## If `switch_unavailable` is your only tool++Switch could not start for this session — wrong or missing credentials, an+unreachable server, or agents here belonging to two different Switch servers.++Call it. Its answer is the actual reason. Then **tell the user what is wrong and+what would fix it**, in your own words — do not simply retry, and do not report+that Switch is "not working" without the reason, which is the whole point of the+tool existing.++Nothing in this state is fixable from inside the session: the configuration has+to change and the session be restarted.diff --git a/core/switch_core/artifacts.py b/core/switch_core/artifacts.pyindex 5862e1471..e728988ed 100644--- a/core/switch_core/artifacts.py+++ b/core/switch_core/artifacts.py@@ -22,14 +22,14 @@ class ContractRange(NamedTuple):ARTIFACT_VERSIONS: Final[dict[str, str]] = {"switch-core": "0.12.4","switchdash": "0.19.3",- "agent-runtime": "0.1.6",+ "agent-runtime": "0.2.0","sidecar": "1.8.0","gateway": "0.12.4","setup": "0.12.4","helm-chart": "0.12.4","compose": "0.12.4",- "switch-connector": "0.7.9",- "switch-connector-codex": "0.2.1",+ "switch-connector": "0.8.0",+ "switch-connector-codex": "0.2.2",}CONTRACTS: Final[dict[str, dict[str, ContractRange]]] = {diff --git a/dash/AGENTS.md b/dash/AGENTS.mdindex 8320ceb71..5ddae8fdd 100644--- a/dash/AGENTS.md+++ b/dash/AGENTS.md@@ -333,6 +333,20 @@ pnpm run lintscrubbing it on write; that reinstates the problem this split exists to solve.- Anything contributed via `registerDiagnosticSection()` passes through the sameexport scrub. Never read the raw log file from outside `file-logger.ts`.+- **An agent's Switch API token lives in exactly one file:**+ `<working dir>/.switch/agents/<slug>.json`, beside a generated `.gitignore`+ containing `*`. `.claude/settings.local.json` carries the endpoint and agent+ id only — it is Claude Code's own file, read by every session in the+ directory, and does not need the credential. Do not add a token back to it:+ two copies is how one goes stale and authenticates as the wrong agent.+ - Three consumers read this layout: switchdash, the sidecar, and+ `@sandbox-quantum/switch-agent-runtime` (which reads it directly when+ nothing sets `SWITCH_*` in the environment). Changing the shape means+ changing all three.+ - The token being in a working tree at all is a known exposure — a+ `.gitignore` stops `git add` and not an archive, a sync or `git add -f`.+ Moving it out is tracked separately; it is deliberately not solved by+ writing it to a second location as well.- PTY environment passthrough must use the allowlist in `src/main/core/pty/pty-env.ts`.- Treat shell escaping and PTY spawning as security-sensitive.- Do not bypass path-safety, shell escaping, or validation helpers.diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.tsindex 1ab4a3b3d..c105a8746 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.test.ts@@ -31,7 +31,6 @@ describe('removeSwitchCredentials (default .claude teardown)', () => {const fs = fakeFs({[SETTINGS_PATH]: mergeSwitchSettings(null, {apiEndpoint: 'https://switch.example.com',- apiToken: 'secret-token',agentId: 'agent-123',}),});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.test.tsindex 21219f67e..78ba09ce0 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.test.ts@@ -9,16 +9,15 @@ import { mergeSwitchSettings } from './write-switch-settings';const CREDS = {apiEndpoint: 'https://switch.example.com',- apiToken: 'secret-token',agentId: 'agent-123',};describe('mergeSwitchSettings', () => {it('produces the SWITCH_* env block and connector allow rules from scratch', () => {const merged = JSON.parse(mergeSwitchSettings(null, CREDS)) as Record<string, unknown>;+ // No token: it goes to the home-side store, not into a working tree.expect(merged.env).toEqual({SWITCH_API_ENDPOINT: 'https://switch.example.com',- SWITCH_API_TOKEN: 'secret-token',SWITCH_AGENT_ID: 'agent-123',});expect((merged.permissions as { allow: string[] }).allow).toContain(@@ -34,7 +33,9 @@ describe('mergeSwitchSettings', () => {});const merged = JSON.parse(mergeSwitchSettings(existing, CREDS)) as Record<string, unknown>;expect(merged.somethingElse).toBe(1);- expect(merged.env).toMatchObject({ EXISTING_KEY: 'keep-me', SWITCH_API_TOKEN: 'secret-token' });+ expect(merged.env).toMatchObject({ EXISTING_KEY: 'keep-me' });+ // A token left over from before the split is removed, not carried forward.+ expect(merged.env).not.toHaveProperty('SWITCH_API_TOKEN');expect((merged.permissions as { allow: string[] }).allow).toContain('Bash');});@@ -78,7 +79,10 @@ describe('writeRemoteSwitchSettings', () => {expect(writes).toHaveLength(1);expect(writes[0]!.path).toBe('.claude/settings.local.json');const parsed = JSON.parse(writes[0]!.content) as { env: Record<string, string> };- expect(parsed.env.SWITCH_API_TOKEN).toBe('secret-token');+ expect(parsed.env.SWITCH_AGENT_ID).toBe('agent-123');+ // Nothing secret crosses to the remote working tree; the token is written+ // separately, to that host's `$HOME` at 0600.+ expect(writes[0]!.content).not.toContain('secret-token');});it('fails loud when the remote write is rejected', async () => {diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.tsindex 60a07b3d9..a1eb62583 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts@@ -4,7 +4,7 @@ import {type FileSystemProvider,} from '@main/core/fs/types';import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';-import { mergeSwitchSettings, type SwitchSettingsCredentials } from './write-switch-settings';+import { mergeSwitchSettings } from './write-switch-settings';const REMOTE_SETTINGS_DIR = '.claude';@@ -18,11 +18,12 @@ const REMOTE_SETTINGS_DIR = '.claude';* `fs` is the session's remote FileSystemProvider, rooted at the agent's remote* repo dir. The merge is byte-identical to the local writer's.*- * `apiToken` is the agent's secret — written here and never returned/logged.+ * No token: it goes to the home-side secret store on the VM, written by the+ * caller that provisions the agent.*/export async function writeRemoteSwitchSettings(fs: FileSystemProvider,- creds: SwitchSettingsCredentials+ creds: { apiEndpoint: string; agentId: string }): Promise<void> {let existingRaw: string | null = null;try {diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.tsindex cb573d725..5fadd62de 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -34,18 +34,18 @@ async function readSettings(): Promise<Record<string, unknown>> {}describe('writeSwitchSettings', () => {- it('creates .claude/settings.local.json with the SWITCH_* env block', async () => {+ it('creates .claude/settings.local.json naming the agent, with no token in it', async () => {await writeSwitchSettings({dir,apiEndpoint: 'https://switch.example.com',- apiToken: 'secret-token',agentId: 'agent-123',});const settings = await readSettings();+ // Claude Code reads this file natively, so the identity belongs here — but+ // it is in the working tree, so the token does not (CHOO-1962).expect(settings.env).toEqual({SWITCH_API_ENDPOINT: 'https://switch.example.com',- SWITCH_API_TOKEN: 'secret-token',SWITCH_AGENT_ID: 'agent-123',});// The Switch connector tools are auto-approved ("don't ask").@@ -77,7 +77,6 @@ describe('writeSwitchSettings', () => {await writeSwitchSettings({dir,apiEndpoint: 'https://switch.example.com',- apiToken: 'new-token',agentId: 'agent-999',});@@ -89,14 +88,13 @@ describe('writeSwitchSettings', () => {expect(settings.env).toEqual({EXISTING_KEY: 'keep-me',SWITCH_API_ENDPOINT: 'https://switch.example.com',- SWITCH_API_TOKEN: 'new-token',SWITCH_AGENT_ID: 'agent-999',});});});describe('writeNeutralAgentSettingsFs', () => {- it('writes the provider-neutral per-agent creds keyed by slug, with a gitignore', async () => {+ it('writes the per-agent credentials, token included, with a gitignore', async () => {await writeNeutralAgentSettingsFs(createPluginFs(dir), {slug: 'agent-abc',apiEndpoint: 'https://switch.example.com',@@ -105,14 +103,14 @@ describe('writeNeutralAgentSettingsFs', () => {});const raw = await fs.readFile(path.join(dir, agentSettingsRelativePath('agent-abc')), 'utf8');- const settings = JSON.parse(raw) as Record<string, unknown>;- expect(settings.env).toEqual({+ // This is the one file that carries the token: `settings.local.json` names+ // the agent, this authenticates it.+ expect((JSON.parse(raw) as { env: Record<string, string> }).env).toEqual({SWITCH_API_ENDPOINT: 'https://switch.example.com',SWITCH_API_TOKEN: 'secret-token',SWITCH_AGENT_ID: 'switch-agent-1',});- // The credentials directory is git-ignored so the token never enters VCS.const ignore = await fs.readFile(path.join(dir, SWITCH_AGENTS_GITIGNORE_RELATIVE), 'utf8');expect(ignore).toBe('*\n');});@@ -231,14 +229,30 @@ describe('mergeSwitchApiEndpoint', () => {expect(mergeSwitchApiEndpoint('{not json', 'https://new.example.com')).toBeNull();// No env block.expect(mergeSwitchApiEndpoint('{}', 'https://new.example.com')).toBeNull();- // Partial creds (no token) -> not provisioned, skip rather than half-write.+ // An endpoint with no agent id names nobody -> skip rather than half-write.expect(mergeSwitchApiEndpoint(- JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://old', SWITCH_AGENT_ID: 'a' } }),+ JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://old' } }),'https://new.example.com')).toBeNull();});++ it('cascades to an agent whose token has moved to the home store', () => {+ // Requiring a token here would silently skip every agent the CHOO-1962+ // migration has already moved — their endpoint would then never be updated+ // when the server URL changes, and they would quietly point at the old one.+ const merged = mergeSwitchApiEndpoint(+ JSON.stringify({ env: { SWITCH_API_ENDPOINT: 'https://old', SWITCH_AGENT_ID: 'a' } }),+ 'https://new.example.com'+ );++ expect(merged).not.toBeNull();+ expect(JSON.parse(merged as string).env).toEqual({+ SWITCH_API_ENDPOINT: 'https://new.example.com',+ SWITCH_AGENT_ID: 'a',+ });+ });});describe('removeSwitchSettings', () => {@@ -247,7 +261,6 @@ describe('removeSwitchSettings', () => {// alone, so tearing it down should leave nothing behind.const provisioned = mergeSwitchSettings(null, {apiEndpoint: 'https://switch.example.com',- apiToken: 'secret-token',agentId: 'agent-123',});@@ -323,7 +336,6 @@ describe('removeSwitchSettings', () => {await writeSwitchSettings({dir,apiEndpoint: 'https://switch.example.com',- apiToken: 'secret-token',agentId: 'agent-123',});const raw = await fs.readFile(path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH), 'utf8');diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.tsindex 45767d070..af77212fe 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts@@ -19,13 +19,21 @@ export interface SwitchSettingsCredentials {}/**- * Merge the `SWITCH_*` env block (and the connector tool-allow rules) into the- * contents of a `.claude/settings.local.json`, returning the new file text.+ * Merge the `SWITCH_*` env block (and the connector tool-allow rules) into a+ * settings file, returning the new file text.*- * The file is merged, not clobbered: any unrelated top-level keys and any other- * `env` entries the user already has are preserved, and only the three- * `SWITCH_*` keys are set/overwritten. The connector MCP tools are unioned into- * `permissions.allow` so they are auto-approved ("don't ask").+ * The file is merged, not clobbered: unrelated top-level keys and any other+ * `env` entries the user already has are preserved. The connector MCP tools are+ * unioned into `permissions.allow` so they are auto-approved ("don't ask").+ *+ * **No token is written, and one already present is removed** (CHOO-1962). This+ * produces `.claude/settings.local.json`, which Claude Code reads natively and+ * which every session in the directory sees — it only needs to say who the agent+ * is. The credential lives in exactly one file, the per-agent+ * `.switch/agents/<slug>.json` that {@link mergeAgentCredentials} writes.+ *+ * Removing rather than merging forward matters: a merge would carry a token+ * written by an older switchdash forward into a file that no longer needs one.** Pure: takes the existing file text (or null when absent/unreadable) and* returns the text to write. Shared by the local writer and the remote (SFTP)@@ -33,7 +41,7 @@ export interface SwitchSettingsCredentials {*/export function mergeSwitchSettings(existingRaw: string | null,- creds: SwitchSettingsCredentials+ creds: { apiEndpoint: string; agentId: string }): string {let existing: Record<string, unknown> = {};if (existingRaw !== null) {@@ -63,30 +71,50 @@ export function mergeSwitchSettings(? (currentPerms.allow as unknown[]).map(String): [];+ const env: Record<string, unknown> = {+ ...currentEnv,+ SWITCH_API_ENDPOINT: creds.apiEndpoint,+ SWITCH_AGENT_ID: creds.agentId,+ };+ delete env.SWITCH_API_TOKEN;+const merged = {...existing,permissions: {...currentPerms,allow: [...new Set([...currentAllow, ...SWITCH_CONNECTOR_TOOL_RULES])],},- env: {- ...currentEnv,- SWITCH_API_ENDPOINT: creds.apiEndpoint,- SWITCH_API_TOKEN: creds.apiToken,- SWITCH_AGENT_ID: creds.agentId,- },+ env,};return `${JSON.stringify(merged, null, 2)}\n`;}+/**+ * The same merge for the provider-neutral per-agent file, which DOES carry the+ * token.+ *+ * The two files are not interchangeable. `.claude/settings.local.json` is+ * Claude Code's own, read by any session in the directory, and it only needs to+ * say who the agent is — the runtime resolves the rest. `.switch/agents/<slug>.json`+ * is the per-agent credential switchdash injects at launch and the runtime falls+ * back to, so the token lives here, in exactly one place.+ */+export function mergeAgentCredentials(+ existingRaw: string | null,+ creds: SwitchSettingsCredentials+): string {+ const merged = JSON.parse(mergeSwitchSettings(existingRaw, creds)) as Record<string, unknown>;+ const env = { ...(merged.env as Record<string, unknown>), SWITCH_API_TOKEN: creds.apiToken };+ return `${JSON.stringify({ ...merged, env }, null, 2)}\n`;+}+/*** Update ONLY `SWITCH_API_ENDPOINT` in an already-provisioned settings file,* returning the new file text — or `null` when the file is not a provisioned- * Switch agent (missing/unparseable, or its `env` lacks the full `SWITCH_*`- * credential block). Used to cascade a server's API-URL edit to its agents- * without ever reading or rewriting the agent's `SWITCH_API_TOKEN`: the token,- * agent id, permissions, and every other key are left byte-for-byte untouched.+ * Switch agent (missing/unparseable, or its `env` names no endpoint and agent+ * id). Used to cascade a server's API-URL edit to its agents; the agent id,+ * permissions, and every other key are left byte-for-byte untouched.** Returning `null` (rather than writing) for an unprovisioned file is deliberate* — the caller skips it instead of creating a token-less config that would look@@ -116,12 +144,13 @@ export function mergeSwitchApiEndpoint(? (existing.env as Record<string, unknown>): null;- // Only a fully provisioned agent (endpoint + token + id all present) is- // propagated to; anything else is "not a Switch agent here" -> skip.+ // Only a provisioned agent (endpoint + id present) is propagated to; anything+ // else is "not a Switch agent here" -> skip. A token is NOT required: since+ // CHOO-1962 a provisioned agent's token lives under `$HOME`, so demanding one+ // here would silently skip every agent the migration has already moved.if (!env ||typeof env.SWITCH_API_ENDPOINT !== 'string' ||- typeof env.SWITCH_API_TOKEN !== 'string' ||typeof env.SWITCH_AGENT_ID !== 'string') {return null;@@ -221,13 +250,13 @@ export function removeSwitchSettings(existingRaw: string | null): RemoveSwitchSe* `.claude/settings.local.json`, the same file the switch-connector* `configure` skill writes.*- * `apiToken` is the agent's secret API key — it is written here and nowhere- * else, and must never be returned to the renderer or logged.+ * No token: it lives in the per-agent `.switch/agents/<slug>.json` alone. Claude+ * Code reads this file natively, so the endpoint and agent id being here is what+ * lets a session started by hand know which agent it is.*/export async function writeSwitchSettings(params: {dir: string;apiEndpoint: string;- apiToken: string;agentId: string;}): Promise<void> {const settingsPath = path.join(params.dir, SWITCH_SETTINGS_RELATIVE_PATH);@@ -286,6 +315,6 @@ export async function writeNeutralAgentSettingsFs(await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}const relPath = agentSettingsRelativePath(params.slug);- const merged = mergeSwitchSettings(await workspaceFs.read(relPath), params);+ const merged = mergeAgentCredentials(await workspaceFs.read(relPath), params);await workspaceFs.write(relPath, merged);}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex 7db2f00f7..0cadb24e6 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -1,11 +1,15 @@import type { Result } from '@switchdash/shared';import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';+import { resolveWorkspaceFsFor } from '@main/core/agents/agent-workspace-fs';import { knownAgentTypeForProvider } from '@main/core/agents/known-agent-type';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';import { registerAgentIdentity } from '@main/core/agents/register-agent-identity';import { resolveAgentServers } from '@main/core/agents/resolve-servers';import { writeRemoteSwitchSettings } from '@main/core/agents/write-remote-switch-settings';-import { writeSwitchSettings } from '@main/core/agents/write-switch-settings';+import {+ writeNeutralAgentSettingsFs,+ writeSwitchSettings,+} from '@main/core/agents/write-switch-settings';import { appService } from '@main/core/app/service';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';@@ -352,10 +356,23 @@ export const switchServersController = createRPCController({await writeSwitchSettings({dir: params.dir,apiEndpoint: server.apiUrl,- apiToken: registered.apiKey,agentId: registered.id,});+ // The settings file above carries no token (CHOO-1962), so the per-agent+ // credentials file is what actually provisions this agent.+ const workspace = await resolveWorkspaceFsFor(null, params.dir);+ try {+ await writeNeutralAgentSettingsFs(workspace.fs, {+ slug: params.name,+ apiEndpoint: server.apiUrl,+ apiToken: registered.apiKey,+ agentId: registered.id,+ });+ } finally {+ workspace.close();+ }+return { kind: 'created', agentId: registered.id };},@@ -385,13 +402,27 @@ export const switchServersController = createRPCController({try {await writeRemoteSwitchSettings(fs, {apiEndpoint: server.apiUrl,- apiToken: registered.apiKey,agentId: registered.id,});} finally {fs.close();}+ // As locally: the settings file names the agent, the per-agent credentials+ // file carries its token — here in the VM's own working directory, which is+ // where its sessions will look.+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.remoteRepoDir);+ try {+ await writeNeutralAgentSettingsFs(workspace.fs, {+ slug: params.name,+ apiEndpoint: server.apiUrl,+ apiToken: registered.apiKey,+ agentId: registered.id,+ });+ } finally {+ workspace.close();+ }+return { kind: 'created', agentId: registered.id };},});diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.tsindex 16181a086..0b7539ccd 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.test.ts@@ -98,27 +98,19 @@ describe('the pinned runtime version', () => {});describe('the credentials the runtime needs', () => {- it('are declared identically by the Claude connector and this module', () => {- // Both hosts must route the same required credentials; neither side may add- // one without the other, or that host's sessions start without it.- const declared = Object.keys(claudeSwitchServer().env ?? {}).sort();- expect(declared).toEqual([...SWITCH_RUNTIME_REQUIRED_ENV].sort());+ it('are declared by the Claude connector not at all, so a standalone session can start', () => {+ // Claude expands ${VAR} and fails the WHOLE server when one resolves to+ // nothing. Declaring a credential there therefore makes it mandatory — and+ // since CHOO-1962 the runtime can resolve its own from the on-disk store,+ // so declaring them would break precisely the case the store exists for.+ // switchdash's own sessions are unaffected: it sets real env vars, which+ // reach the MCP child whether or not the config mentions them.+ expect(claudeSwitchServer().env).toBeUndefined();});- it('are expanded by the Claude connector under their own names', () => {- // Catches a transposed pair — ${SWITCH_API_TOKEN} filed under- // SWITCH_API_ENDPOINT — which no other assertion here would see.- for (const [name, value] of Object.entries(claudeSwitchServer().env ?? {})) {- expect(value).toBe(`\${${name}}`);- }- });-- it('keep the optional ones out of the Claude connector, where declaring is requiring', () => {- // Claude expands ${VAR} and fails the whole server when one resolves to- // nothing, so an optional variable declared there costs every standalone- // session its tools. Codex forwards names, so an unset one is just skipped.+ it('keep every optional one out of the Claude connector too, for the same reason', () => {const declared = Object.keys(claudeSwitchServer().env ?? {});- for (const name of SWITCH_RUNTIME_OPTIONAL_ENV) {+ for (const name of [...SWITCH_RUNTIME_OPTIONAL_ENV, ...SWITCH_RUNTIME_REQUIRED_ENV]) {expect(declared).not.toContain(name);}});diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.tsindex 5969703c4..1cda5174c 100644--- a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-agent-runtime.ts@@ -23,12 +23,18 @@ export const SWITCH_AGENT_RUNTIME_PACKAGE = '@sandbox-quantum/switch-agent-runtiexport const SWITCH_AGENT_RUNTIME_VERSION = '0.1.6';/**- * Credentials the runtime refuses to start without: it reads all three at- * `bin.ts` module scope and exits before answering `initialize` if any is- * missing, which a host reports only as a closed connection.+ * The credentials switchdash injects into a session it launches. The runtime+ * takes all three together as its identity and asks no further questions —+ * this is the first branch of its resolution chain, and the one the majority+ * of sessions take.*- * This tier is the contract with the Claude Code connector, whose `.mcp.json`- * declares the same three for `${VAR}` expansion.+ * Since CHOO-1962 they are no longer *required*: a session nobody configured+ * this way falls back to the on-disk agent store rather than exiting. What+ * follows from that is that the Claude connector's `.mcp.json` declares **no+ * `env` block at all** — a `${VAR}` there is mandatory once declared, so+ * declaring these would break exactly the standalone case the fallback exists+ * for. Codex still lists them under `env_vars`, which forwards by name and+ * skips whatever is unset.*/export const SWITCH_RUNTIME_REQUIRED_ENV = ['SWITCH_API_ENDPOINT',diff --git a/dash/packages/shared/src/artifacts.ts b/dash/packages/shared/src/artifacts.tsindex 5282b45ac..48db34903 100644--- a/dash/packages/shared/src/artifacts.ts+++ b/dash/packages/shared/src/artifacts.ts@@ -22,14 +22,14 @@ export interface ContractRange {export const ARTIFACT_VERSIONS = {'switch-core': '0.12.4',switchdash: '0.19.3',- 'agent-runtime': '0.1.6',+ 'agent-runtime': '0.2.0',sidecar: '1.8.0',gateway: '0.12.4',setup: '0.12.4','helm-chart': '0.12.4',compose: '0.12.4',- 'switch-connector': '0.7.9',- 'switch-connector-codex': '0.2.1',+ 'switch-connector': '0.8.0',+ 'switch-connector-codex': '0.2.2',} as const satisfies Record<string, string>;export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;diff --git a/dash/packages/switch-agent-runtime/package.json b/dash/packages/switch-agent-runtime/package.jsonindex a4663937f..cde49f1c1 100644--- a/dash/packages/switch-agent-runtime/package.json+++ b/dash/packages/switch-agent-runtime/package.json@@ -1,6 +1,6 @@{"name": "@sandbox-quantum/switch-agent-runtime",- "version": "0.1.6",+ "version": "0.2.0","description": "Switch agent protocol client, and the local MCP runtime built on it","license": "Apache-2.0","author": {diff --git a/dash/packages/switch-agent-runtime/src/artifacts.ts b/dash/packages/switch-agent-runtime/src/artifacts.tsindex 5282b45ac..48db34903 100644--- a/dash/packages/switch-agent-runtime/src/artifacts.ts+++ b/dash/packages/switch-agent-runtime/src/artifacts.ts@@ -22,14 +22,14 @@ export interface ContractRange {export const ARTIFACT_VERSIONS = {'switch-core': '0.12.4',switchdash: '0.19.3',- 'agent-runtime': '0.1.6',+ 'agent-runtime': '0.2.0',sidecar: '1.8.0',gateway: '0.12.4',setup: '0.12.4','helm-chart': '0.12.4',compose: '0.12.4',- 'switch-connector': '0.7.9',- 'switch-connector-codex': '0.2.1',+ 'switch-connector': '0.8.0',+ 'switch-connector-codex': '0.2.2',} as const satisfies Record<string, string>;export type ArtifactName = keyof typeof ARTIFACT_VERSIONS;diff --git a/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts b/dash/packages/switch-agent-runtime/src/bin.handshake.test.tsindex 36f4e3876..27e695100 100644--- a/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts+++ b/dash/packages/switch-agent-runtime/src/bin.handshake.test.ts@@ -1,6 +1,7 @@import { type ChildProcess, spawn } from 'node:child_process';-import { existsSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';import * as http from 'node:http';+import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, describe, expect, it } from 'vitest';@@ -35,14 +36,27 @@ const INITIALIZE = {},};-type Running = { child: ChildProcess; stdout: () => string; stderr: () => string };+type Running = {+ child: ChildProcess;+ root: string;+ stdout: () => string;+ stderr: () => string;+};const running: ChildProcess[] = [];const servers: http.Server[] = [];+const sandboxes: string[] = [];afterEach(() => {for (const child of running.splice(0)) child.kill('SIGKILL');for (const server of servers.splice(0)) server.close();+ for (const dir of sandboxes.splice(0)) {+ try {+ rmSync(dir, { recursive: true, force: true });+ } catch {+ // A just-killed child may still hold a file open; the OS reclaims tmp.+ }+ }});/** An endpoint serving the operation list the runtime loads before serving. */@@ -68,10 +82,46 @@ async function blackHoleServer(): Promise<string> {return `http://127.0.0.1:${port}`;}-function start(env: Record<string, string>): Running {+/**+ * A throwaway working directory and `HOME` for one spawn.+ *+ * Credential resolution reads `./.switch/agents/`, and the runtime keeps its+ * session state under `$HOME` — so a shared root would let whatever the+ * developer happens to have configured decide whether these tests pass.+ */+function sandbox(): string {+ const dir = mkdtempSync(join(tmpdir(), 'switch-runtime-test-'));+ sandboxes.push(dir);+ return dir;+}++/** Provision an agent in a sandbox, in the shape switchdash writes. */+function provision(+ root: string,+ agent: { slug: string; name?: string; agentId: string; endpoint: string; token?: string }+): void {+ const dir = join(root, '.switch', 'agents');+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, `${agent.slug}.json`),+ JSON.stringify({+ name: agent.name ?? agent.slug,+ env: {+ SWITCH_API_ENDPOINT: agent.endpoint,+ SWITCH_AGENT_ID: agent.agentId,+ ...(agent.token === undefined ? {} : { SWITCH_API_TOKEN: agent.token }),+ },+ })+ );+}++function start(env: Record<string, string>, setup?: (root: string) => void): Running {+ const root = sandbox();+ setup?.(root);const child = spawn(process.execPath, [BIN], {+ cwd: root,// A fixed environment, as a host gives it: nothing leaks in from this runner.- env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '', ...env },+ env: { PATH: process.env.PATH ?? '', HOME: root, ...env },stdio: ['pipe', 'pipe', 'pipe'],});running.push(child);@@ -84,41 +134,83 @@ function start(env: Record<string, string>): Running {child.stderr.on('data', (c: Buffer) => {err += c.toString();});- return { child, stdout: () => out, stderr: () => err };+ return { child, root, stdout: () => out, stderr: () => err };}-/** Resolve with the exit code, or reject if the process outlives the deadline. */-function exitWithin(child: ChildProcess, ms: number): Promise<number | null> {- return new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error(`process still running after ${ms}ms`)), ms);- child.on('exit', (code) => {- clearTimeout(timer);- resolve(code);- });- });-}+/** Resolve with the JSON-RPC response carrying `id`. */+function responseWithin(run: Running, id: number, ms: number): Promise<Record<string, unknown>> {+ const seek = (): Record<string, unknown> | null => {+ for (const line of run.stdout().split('\n')) {+ if (!line.trim()) continue;+ try {+ const message = JSON.parse(line) as { id?: number };+ if (message.id === id) return message as Record<string, unknown>;+ } catch {+ // Partial line; wait for the rest.+ }+ }+ return null;+ };-/** Resolve with the JSON-RPC response to `initialize`. */-function responseWithin(run: Running, ms: number): Promise<Record<string, unknown>> {return new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error(`no initialize response within ${ms}ms`)), ms);+ // The answer may already be buffered from an earlier read, in which case no+ // further 'data' event is coming and waiting for one would hang.+ const already = seek();+ if (already) return resolve(already);++ const timer = setTimeout(() => reject(new Error(`no response to ${id} within ${ms}ms`)), ms);run.child.stdout!.on('data', () => {- for (const line of run.stdout().split('\n')) {- if (!line.trim()) continue;- try {- const message = JSON.parse(line) as { id?: number };- if (message.id === 1) {- clearTimeout(timer);- resolve(message as Record<string, unknown>);- }- } catch {- // Partial line; wait for the rest.- }+ const found = seek();+ if (found) {+ clearTimeout(timer);+ resolve(found);}});});}+/** Complete `initialize` and the follow-up notification, leaving the server live. */+async function handshake(run: Running): Promise<void> {+ run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);+ await responseWithin(run, 1, DEADLINE_MS);+ run.child.stdin!.write(+ `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`+ );+}++/** Send one request and resolve with its response. */+async function request(+ run: Running,+ id: number,+ method: string,+ params: Record<string, unknown> = {}+): Promise<Record<string, unknown>> {+ run.child.stdin!.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`);+ return responseWithin(run, id, DEADLINE_MS);+}++/**+ * Complete the handshake and return the single degraded tool plus what it says.+ *+ * Asserting on stderr alone would prove nothing here: the point of degraded mode+ * is that the reason reaches the SESSION, over the protocol, rather than to a+ * log nobody opens.+ */+async function degradedAnswer(run: Running): Promise<{ tools: string[]; text: string }> {+ await handshake(run);+ const listed = (await request(run, 2, 'tools/list')) as {+ result?: { tools?: { name: string }[] };+ };+ const called = (await request(run, 3, 'tools/call', {+ name: 'switch_unavailable',+ arguments: {},+ })) as { result?: { content?: { text?: string }[] } };+ return {+ tools: (listed.result?.tools ?? []).map((t) => t.name),+ text: called.result?.content?.[0]?.text ?? '',+ };+}+describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () => {it('answers initialize when its credentials are present', async () => {const endpoint = await opsServer();@@ -129,7 +221,7 @@ describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () =});run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);- const response = (await responseWithin(run, DEADLINE_MS)) as {+ const response = (await responseWithin(run, 1, DEADLINE_MS)) as {result?: { protocolVersion?: string; serverInfo?: { name?: string } };};@@ -137,35 +229,198 @@ describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () =expect(response.result?.serverInfo?.name).toBeTruthy();});- it('exits rather than hanging when the host forwarded it no credentials', async () => {- // The failure this whole change exists to fix: a host that forwards nothing- // leaves the runtime blind, and exiting is what makes that legible.+ it('serves the reason, rather than exiting, when nothing configures it at all', async () => {+ // Exiting made this the quietest failure available: the host shows a closed+ // connection and the session is told nothing. Starting anyway with one tool+ // is what puts the reason where someone will read it.+ const { tools, text } = await degradedAnswer(start({}));++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain('.switch/agents');+ expect(text).toContain('configure');+ });++ it('publishes no port while degraded, so a pre-expansion spawn cannot race', async () => {+ // The `${SWITCH_*}` spawn used to exit on sight for exactly this reason.+ // Now nothing exits, so the guard is that degraded mode writes no port file+ // — it starts no hook listener to advertise.const run = start({});+ await degradedAnswer(run);++ const sessions = join(run.root, '.switch', 'sessions');+ const ports = existsSync(sessions)+ ? readdirSync(sessions).filter((d) => existsSync(join(sessions, d, 'port')))+ : [];+ expect(ports).toEqual([]);++ // The directory itself is expected: the diagnostic is also written to+ // `startup-error.log` there, for an operator who does go looking.+ expect(+ readdirSync(sessions).some((d) => existsSync(join(sessions, d, 'startup-error.log')))+ ).toBe(true);+ });++ it('starts from the local store when the host forwarded nothing', async () => {+ const endpoint = await opsServer();+ const run = start({}, (root) =>+ provision(root, { slug: 'solo', agentId: 'uuid-solo', endpoint, token: 'tok-solo' })+ );run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);- expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);- for (const name of ['SWITCH_API_ENDPOINT', 'SWITCH_API_TOKEN', 'SWITCH_AGENT_ID']) {- expect(run.stderr()).toContain(name);- }- expect(run.stdout()).toBe('');+ const response = (await responseWithin(run, 1, DEADLINE_MS)) as {+ result?: { protocolVersion?: string };+ };++ expect(response.result?.protocolVersion).toBeTruthy();+ expect(run.stderr()).toContain('agent_id=uuid-solo');+ });++ it('treats an unexpanded ${SWITCH_*} as absent and falls through to the store', async () => {+ // Claude spawns the server once before expanding its settings env block.+ // Literals must not be mistaken for credentials, nor suppress the store.+ const endpoint = await opsServer();+ const run = start(+ {+ SWITCH_API_ENDPOINT: '${SWITCH_API_ENDPOINT}',+ SWITCH_API_TOKEN: '${SWITCH_API_TOKEN}',+ SWITCH_AGENT_ID: '${SWITCH_AGENT_ID}',+ },+ (root) => provision(root, { slug: 'solo', agentId: 'uuid-solo', endpoint, token: 'tok-solo' })+ );+ run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);++ const response = (await responseWithin(run, 1, DEADLINE_MS)) as {+ result?: { protocolVersion?: string };+ };++ expect(response.result?.protocolVersion).toBeTruthy();+ expect(run.stderr()).toContain('agent_id=uuid-solo');+ });++ it('refuses to guess which server it belongs to when the store spans two', async () => {+ const run = start({}, (root) => {+ provision(root, {+ slug: 'dev',+ agentId: 'uuid-dev',+ endpoint: 'https://dev.example',+ token: 't1',+ });+ provision(root, {+ slug: 'prod',+ agentId: 'uuid-prod',+ endpoint: 'https://prod.example',+ token: 't2',+ });+ });++ const { tools, text } = await degradedAnswer(run);++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain('span 2 Switch servers');+ // The fix has to travel with the diagnosis, or the agent can only relay+ // that something is broken.+ expect(text).toContain('SWITCH_API_ENDPOINT');+ expect(text).toContain('dev.example');+ expect(text).toContain('prod.example');+ });++ it('offers select_agent, and refuses everything else, until an identity is bound', async () => {+ const endpoint = await opsServer();+ const run = start({}, (root) => {+ provision(root, { slug: 'alice', agentId: 'uuid-a', endpoint, token: 'tok-a' });+ provision(root, { slug: 'bob', agentId: 'uuid-b', endpoint, token: 'tok-b' });+ });++ await handshake(run);++ const listed = (await request(run, 2, 'tools/list')) as {+ result?: { tools?: { name: string }[] };+ };+ const names = (listed.result?.tools ?? []).map((t) => t.name);+ expect(names).toContain('select_agent');++ const refused = (await request(run, 3, 'tools/call', {+ name: 'download_attachment',+ arguments: { mxc: 'mxc://example/1' },+ })) as { result?: { isError?: boolean; content?: { text?: string }[] } };++ expect(refused.result?.isError).toBe(true);+ const text = refused.result?.content?.[0]?.text ?? '';+ expect(text).toContain('select_agent');+ expect(text).toContain('alice');+ expect(text).toContain('bob');+ });++ it('binds the chosen agent when select_agent names one', async () => {+ const endpoint = await opsServer();+ const run = start({}, (root) => {+ provision(root, { slug: 'alice', agentId: 'uuid-a', endpoint, token: 'tok-a' });+ provision(root, { slug: 'bob', agentId: 'uuid-b', endpoint, token: 'tok-b' });+ });++ await handshake(run);++ const bound = (await request(run, 2, 'tools/call', {+ name: 'select_agent',+ arguments: { name: 'bob' },+ })) as { result?: { isError?: boolean; structuredContent?: { agent_id?: string } } };++ expect(bound.result?.isError).toBeFalsy();+ expect(bound.result?.structuredContent?.agent_id).toBe('uuid-b');+ expect(run.stderr()).toContain('bound to bob');+ });++ it('names the agents it knows when select_agent names one it does not', async () => {+ const endpoint = await opsServer();+ const run = start({}, (root) => {+ provision(root, { slug: 'alice', agentId: 'uuid-a', endpoint, token: 'tok-a' });+ provision(root, { slug: 'bob', agentId: 'uuid-b', endpoint, token: 'tok-b' });+ });++ await handshake(run);++ const answer = (await request(run, 2, 'tools/call', {+ name: 'select_agent',+ arguments: { name: 'carol' },+ })) as { result?: { isError?: boolean; content?: { text?: string }[] } };++ expect(answer.result?.isError).toBe(true);+ expect(answer.result?.content?.[0]?.text).toContain('alice');+ });++ it('does not fall back to the store on half an identity, and says so', async () => {+ // Being the wrong agent is worse than being no agent: a partial environment+ // is a broken config, and quietly using the store instead would hide it.+ const endpoint = await opsServer();+ const run = start({ SWITCH_AGENT_ID: 'uuid-env' }, (root) =>+ provision(root, { slug: 'solo', agentId: 'uuid-solo', endpoint, token: 'tok-solo' })+ );++ const { tools, text } = await degradedAnswer(run);++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain('incomplete SWITCH_* environment');});it(- 'exits rather than hanging when Switch never answers',+ 'answers, rather than hanging, when Switch never replies',async () => {+ // Credentials were fine; the server was not. Indistinguishable from "no+ // credentials" if the process just dies, which is why this degrades too.const endpoint = await blackHoleServer();const run = start({SWITCH_API_ENDPOINT: endpoint,SWITCH_API_TOKEN: 'tok-123',SWITCH_AGENT_ID: 'agent-1',});- run.child.stdin!.write(`${JSON.stringify(INITIALIZE)}\n`);- expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);- expect(run.stderr()).toContain(endpoint);+ const { tools, text } = await degradedAnswer(run);++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain(endpoint);},// Must outlast the runtime's own fetch bound, which is the thing under test.- DEADLINE_MS + 5_000+ DEADLINE_MS + 15_000);it('names the endpoint it could not reach, not just that it failed', async () => {@@ -175,7 +430,23 @@ describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () =SWITCH_AGENT_ID: 'agent-1',});- expect(await exitWithin(run.child, DEADLINE_MS)).not.toBe(0);- expect(run.stderr()).toMatch(/cannot reach Switch at http:\/\/127\.0\.0\.1:1/);+ const { text } = await degradedAnswer(run);++ expect(text).toMatch(/cannot reach Switch at http:\/\/127\.0\.0\.1:1/);+ });++ it('answers any tool name while degraded, not just its own', async () => {+ // A host that cached a fuller list from an earlier session will call one of+ // those; "Unknown tool" would tell the session nothing.+ const run = start({});+ await handshake(run);++ const called = (await request(run, 2, 'tools/call', {+ name: 'list_rooms',+ arguments: {},+ })) as { result?: { isError?: boolean; content?: { text?: string }[] } };++ expect(called.result?.isError).toBe(true);+ expect(called.result?.content?.[0]?.text).toContain('Switch is unavailable');});});diff --git a/dash/packages/switch-agent-runtime/src/bin.ts b/dash/packages/switch-agent-runtime/src/bin.tsindex 6c4b00355..10c3cdd75 100644--- a/dash/packages/switch-agent-runtime/src/bin.ts+++ b/dash/packages/switch-agent-runtime/src/bin.ts@@ -21,9 +21,17 @@* from its own getppid(), so each session's hook reaches its own runtime* without any cross-session coordination.*- * Config comes from `SWITCH_*` env vars: the Claude connector sets them in its- * `.mcp.json` env block, the Codex profile in `env_vars`, and switchdash puts- * them in the session's environment when it launches one itself.+ * Identity is resolved in two steps, environment first. switchdash puts the+ * `SWITCH_*` vars in the session's environment when it launches one itself, and+ * that path is taken whole whenever all three are present. Otherwise the local+ * agent store decides — the working tree says which agents are provisioned+ * here, `$HOME` holds their secrets — and where it names more than one, the+ * session picks with `select_agent` before anything else will answer.+ *+ * Endpoints are the one ambiguity that cannot be deferred: the tool surface is+ * fetched before the handshake, so the server has to be known by then. A store+ * spanning two Switch deployments is therefore refused at startup rather than+ * resolved by guessing.*/import { randomUUID } from 'node:crypto';@@ -34,11 +42,27 @@ import * as path from 'node:path';import { Server } from '@modelcontextprotocol/sdk/server/index.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';+import {+ AGENTS_DIR_RELATIVE,+ distinctEndpoints,+ normalizeEndpoint,+ readAgentStore,+ type ResolvedAgent,+} from './credentials';import { readSse, type SseFrame } from './sse';-const API_ENDPOINT = process.env.SWITCH_API_ENDPOINT ?? '';-const API_TOKEN = process.env.SWITCH_API_TOKEN ?? '';-const AGENT_ID = process.env.SWITCH_AGENT_ID ?? '';+const ENV_ENDPOINT = process.env.SWITCH_API_ENDPOINT ?? '';+const ENV_TOKEN = process.env.SWITCH_API_TOKEN ?? '';+const ENV_AGENT_ID = process.env.SWITCH_AGENT_ID ?? '';++// The identity every request below is made as. Mutable because it is not always+// known at startup: a standalone session with several agents provisioned in the+// same working tree binds one through `select_agent`, and each request builder+// reads these at call time rather than capturing them.+let API_ENDPOINT = '';+let API_TOKEN = '';+let AGENT_ID = '';+let AGENT_NAME = '';// When this session is managed by switchdash, switchdash reads the agent// bridge itself and injects addressed messages into the PTY. Reads are no@@ -72,6 +96,11 @@ let serving = false;* looks identical from the outside. The file is what makes them tell apart.*/function failStartup(reason: string): never {+ recordStartupFailure(reason);+ process.exit(1);+}++function recordStartupFailure(reason: string): void {process.stderr.write(`switch: ${reason}\n`);try {fs.mkdirSync(SESSION_DIR, { recursive: true });@@ -79,27 +108,163 @@ function failStartup(reason: string): never {} catch {// Best effort: stderr already carries the reason.}- process.exit(1);}-if (- !API_ENDPOINT ||- !API_TOKEN ||- !AGENT_ID ||- looksUnresolved(API_ENDPOINT) ||- looksUnresolved(API_TOKEN) ||- looksUnresolved(AGENT_ID)-) {- failStartup(- `missing or unresolved config — need SWITCH_API_ENDPOINT, SWITCH_API_TOKEN, and SWITCH_AGENT_ID\n` +- ` endpoint=${API_ENDPOINT || 'MISSING'}\n` +- ` token=${API_TOKEN ? 'set' : 'MISSING'}\n` +- ` agent_id=${AGENT_ID || 'MISSING'}\n` +- `If these look like \`\${SWITCH_*}\`, the env block in \`.claude/settings.local.json\` has not been expanded — run the \`configure\` skill.\n` +- `If they are simply absent, the host did not pass them through: Codex forwards only the names listed in \`env_vars\` on its \`mcp_servers\` entry.`- );+/**+ * Why this process has no Switch identity, when it has none.+ *+ * Null in the ordinary case. When set, the server still starts and answers the+ * handshake — it just has one tool, which reports this.+ */+let degradedReason: string | null = null;++function isDegraded(): boolean {+ return degradedReason !== null;}+/**+ * Come up with no identity, able to say why, instead of exiting.+ *+ * Exiting looks like nothing at all from where the user sits: the host reports a+ * server that dies before the handshake as a closed connection and does not show+ * its stderr, so "no credentials", "two servers, pick one" and "the binary is+ * broken" are one symptom — Switch tools silently missing. The runtime is the+ * only thing that knows which it was, and the agent is the only channel back to+ * the user, so it has to survive long enough to be asked.+ *+ * The stderr line and `startup-error.log` are still written, for whoever does go+ * looking.+ */+function degrade(reason: string): void {+ recordStartupFailure(reason);+ degradedReason = reason;+}++/** An env var a host left as a literal `${VAR}` is not a value; treat it as absent. */+function envValue(raw: string): string {+ return looksUnresolved(raw) ? '' : raw.trim();+}++const ENV = {+ endpoint: envValue(ENV_ENDPOINT),+ token: envValue(ENV_TOKEN),+ agentId: envValue(ENV_AGENT_ID),+};++/**+ * Agents provisioned here when startup could not pick between them.+ *+ * Non-empty only while the choice is open: `select_agent` binds one and clears+ * it. Until then every other tool call is refused with the list.+ */+let unboundCandidates: ResolvedAgent[] = [];++function isBound(): boolean {+ return AGENT_ID !== '';+}++function bindIdentity(agent: { endpoint: string; token: string; agentId: string; name: string }) {+ API_ENDPOINT = normalizeEndpoint(agent.endpoint);+ API_TOKEN = agent.token;+ AGENT_ID = agent.agentId;+ AGENT_NAME = agent.name;+ unboundCandidates = [];+}++/**+ * Work out who this process is.+ *+ * Environment first, unconditionally: switchdash launches the majority of+ * sessions and injects the identity it has already chosen for each one, and+ * that path predates the store. Only a session nobody configured that way falls+ * through to disk.+ */+function resolveIdentity(): void {+ if (ENV.endpoint && ENV.token && ENV.agentId) {+ bindIdentity({ ...ENV, name: '' });+ return;+ }++ // Half an identity is a broken config, not a reason to go looking on disk:+ // silently authenticating as some other agent is worse than not starting.+ if (ENV.token || ENV.agentId) {+ return degrade(+ `incomplete SWITCH_* environment — got ${[+ ENV.endpoint ? 'endpoint' : null,+ ENV.token ? 'token' : null,+ ENV.agentId ? 'agent_id' : null,+ ]+ .filter(Boolean)+ .join(' + ')}, need all three\n` ++ ` endpoint=${ENV.endpoint || 'MISSING'}\n` ++ ` token=${ENV.token ? 'set' : 'MISSING'}\n` ++ ` agent_id=${ENV.agentId || 'MISSING'}\n` ++ `Set the missing ones, or unset all three to use the local agent store instead.`+ );+ }++ const store = readAgentStore(process.cwd());++ if (store.agents.length === 0) {+ const unusable = store.unusable.length+ ? `\nEntries found but unusable:\n${store.unusable.map((u) => ` ${u.slug}: ${u.reason}`).join('\n')}`+ : '';+ return degrade(+ `no Switch identity: no SWITCH_* environment, and no usable agent in ${store.projectDir}\n` ++ `Run the connector's \`configure\` skill here to register an agent, or start the session from a directory that has ${AGENTS_DIR_RELATIVE}/.${unusable}\n` ++ `If you expected the host to pass credentials: Claude expands \`\${SWITCH_*}\` from its settings env block, and Codex forwards only the names listed in \`env_vars\`.`+ );+ }++ // An endpoint on its own is not an identity, but it is a way to say which+ // server you meant when the store spans more than one.+ let candidates = store.agents;+ if (ENV.endpoint) {+ const want = normalizeEndpoint(ENV.endpoint);+ candidates = candidates.filter((a) => normalizeEndpoint(a.endpoint) === want);+ if (candidates.length === 0) {+ return degrade(+ `SWITCH_API_ENDPOINT is ${want}, but no agent in ${store.projectDir} belongs to it\n` ++ `Known: ${distinctEndpoints(store.agents).join(', ')}`+ );+ }+ }++ const endpoints = distinctEndpoints(candidates);++ // The operation catalog is fetched from the server before this process can+ // serve anything, and which server that is has to be settled first. Picking+ // one arbitrarily would bootstrap a tool surface from a deployment the agent+ // may not even belong to, so refuse instead and say how to disambiguate.+ if (endpoints.length > 1) {+ return degrade(+ `agents in ${store.projectDir} span ${endpoints.length} Switch servers, so this session cannot tell which one it belongs to:\n` ++ candidates.map((a) => ` ${a.name} → ${normalizeEndpoint(a.endpoint)}`).join('\n') ++ `\nSet SWITCH_API_ENDPOINT to the one you meant, or leave only that server's agents in ${AGENTS_DIR_RELATIVE}/.`+ );+ }++ if (candidates.length === 1) {+ bindIdentity(candidates[0]);+ return;+ }++ // Several agents, one server: the catalog is knowable, the identity is not.+ API_ENDPOINT = endpoints[0];+ unboundCandidates = candidates;+}++// Before resolution, not after: `unpublishPort` clears the whole session+// directory, and resolution may write `startup-error.log` into it. While a+// failure exited immediately the order was invisible; now that it survives, a+// later wipe would delete the one artefact the operator is meant to find.+unpublishPort();++resolveIdentity();++/** Whether `select_agent` is offered, fixed at startup so the catalog is static. */+const OFFERS_SELECT_AGENT = !isBound();+process.stderr.write(`switch: ppid=${SESSION_PPID} session_dir=${SESSION_DIR}\n`);// Before the transport is serving these must be fatal. A listener that only@@ -328,6 +493,119 @@ const mcp = new Server(});+/**+ * The whole tool surface when startup could not produce an identity.+ *+ * Named and described for the reader that matters — the agent, which will be+ * asked "why can't you reach Switch?" and needs to know that calling this is how+ * it finds out. The answer is the diagnostic verbatim, for it to translate.+ */+const UNAVAILABLE_TOOL = {+ name: 'switch_unavailable',+ description:+ 'Switch is NOT available in this session — this is the only Switch tool ' ++ 'you have. Call it to get the reason, then explain that reason to the user ' ++ 'in plain language. Call it whenever the user asks about Switch, about a ' ++ 'room, or about why the Switch tools are missing. It takes no arguments and ' ++ 'is safe to call more than once.',+ inputSchema: { type: 'object', properties: {} },+};++function handleUnavailable() {+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text:+ `Switch is unavailable in this session.\n\n${degradedReason}\n\n` ++ `Nothing here is retryable from inside the session — the configuration ` ++ `has to change and the session be restarted. Tell the user what is wrong ` ++ `and what would fix it.`,+ },+ ],+ };+}++// Offered only when startup found several agents provisioned here and could not+// choose between them. Served locally: the server will not hand out a catalog,+// or anything else, without an agent credential — which is the very thing this+// tool exists to establish.+const SELECT_AGENT_TOOL = {+ name: 'select_agent',+ description:+ 'Choose which Switch agent this session acts as. Several are provisioned ' ++ 'in this working directory and no identity was supplied, so every other ' ++ 'Switch tool is unavailable until one is selected. Call this once with the ' ++ 'name of the agent you are.',+ inputSchema: {+ type: 'object',+ properties: {+ name: {+ type: 'string',+ description: 'The agent to act as, as named in the refusal message.',+ },+ },+ required: ['name'],+ },+};++/** The sentence every other tool answers with while the identity is open. */+function unboundRefusal(): string {+ return (+ `No Switch identity selected. This session has ${unboundCandidates.length} agents ` ++ `provisioned in ${path.join(process.cwd(), AGENTS_DIR_RELATIVE)}:\n` ++ unboundCandidates.map((a) => ` ${a.name}`).join('\n') ++ `\nCall select_agent with one of those names first.`+ );+}++function handleSelectAgent(rawArgs: Record<string, unknown>) {+ if (isBound()) {+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text: `Already acting as ${AGENT_NAME || AGENT_ID}; an identity cannot be changed mid-session.`,+ },+ ],+ };+ }++ const wanted = typeof rawArgs.name === 'string' ? rawArgs.name.trim() : '';+ const chosen = unboundCandidates.find((a) => a.name === wanted || a.slug === wanted);+ if (!chosen) {+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text: `No agent named ${wanted || '(nothing)'} is provisioned here. Available:\n${unboundCandidates+ .map((a) => ` ${a.name}`)+ .join('\n')}`,+ },+ ],+ };+ }++ bindIdentity(chosen);+ // Deferred at startup because there was no identity to open a connection as.+ startStream();+ startHeartbeat();+ process.stderr.write(`switch: bound to ${chosen.name} (agent_id=${AGENT_ID})\n`);++ return {+ content: [+ {+ type: 'text',+ text: `Now acting as ${chosen.name} on ${API_ENDPOINT}. The Switch tools are live — call list_rooms to see where you belong.`,+ },+ ],+ structuredContent: { name: chosen.name, agent_id: chosen.agentId, endpoint: API_ENDPOINT },+ };+}+// Addressed images are auto-downloaded and surfaced as image_path on the// notification. This tool lets the agent fetch ANY attachment on demand — e.g.// an image seen in read_context history that arrived unaddressed (no@@ -438,9 +716,18 @@ let operations: SwitchOperation[] = [];*/const OPERATIONS_FETCH_TIMEOUT_MS = 15_000;-async function loadOperations(): Promise<void> {- const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/ops`, {- headers: { Authorization: `Bearer ${API_TOKEN}` },+/**+ * Fetch the operation list.+ *+ * Credentials are passed rather than read from the module state because the+ * catalog has to exist before an identity necessarily does. The server scopes+ * this route to an agent for authentication only — it answers from the same+ * static registry whichever agent asks — so any credential valid for `endpoint`+ * yields the catalog every agent on that server would get.+ */+async function loadOperations(endpoint: string, agentId: string, token: string): Promise<void> {+ const resp = await fetch(`${endpoint}/agents/${agentId}/ops`, {+ headers: { Authorization: `Bearer ${token}` },signal: AbortSignal.timeout(OPERATIONS_FETCH_TIMEOUT_MS),});if (!resp.ok) {@@ -570,20 +857,43 @@ async function callOperation(}}+// Fixed for the life of the process. `select_agent` stays listed after it has+// bound an identity — the alternative is a catalog that changes underneath a+// host mid-session, which costs a `tools/list_changed` round trip to announce+// and is not honoured everywhere. A second call answers that it is spoken for.mcp.setRequestHandler(ListToolsRequestSchema, async () => ({- tools: [- ...operations.map((op) => ({- name: op.name,- description: op.description,- inputSchema: op.input_schema,- })),- DOWNLOAD_ATTACHMENT_TOOL,- SEND_ATTACHMENT_TOOL,- ],+ // Degraded, the catalog was never fetched — there were no credentials to+ // fetch it with. One tool that explains itself beats fifty that are silently+ // absent.+ tools: isDegraded()+ ? [UNAVAILABLE_TOOL]+ : [+ ...operations.map((op) => ({+ name: op.name,+ description: op.description,+ inputSchema: op.input_schema,+ })),+ ...(OFFERS_SELECT_AGENT ? [SELECT_AGENT_TOOL] : []),+ DOWNLOAD_ATTACHMENT_TOOL,+ SEND_ATTACHMENT_TOOL,+ ],}));mcp.setRequestHandler(CallToolRequestSchema, async (req) => {const name = req.params.name;+ // Any name, not just the tool's own: a host that cached a fuller list from a+ // previous session would otherwise get "Unknown tool", which says nothing.+ if (isDegraded()) {+ return handleUnavailable();+ }+ if (name === 'select_agent') {+ return handleSelectAgent(req.params.arguments ?? {});+ }+ // Every route below stamps the agent id into a URL, so none of them mean+ // anything yet. One guard here covers the whole surface.+ if (!isBound()) {+ return { isError: true, content: [{ type: 'text', text: unboundRefusal() }] };+ }if (name === 'download_attachment') {return handleDownloadAttachment(req.params.arguments ?? {});}@@ -1454,30 +1764,67 @@ transport.onclose = () => {process.exit(0);};-// Wipe any stale port file left by a crashed previous process for the same ppid.-// Safe: the previous process for this ppid is gone (we are it now); a live-// sibling would be a different ppid.-unpublishPort();--// Load the operation list before serving: a tool surface that is empty-// because a fetch failed is worse than a process that refuses to start.-try {- await loadOperations();-} catch (err) {- failStartup(- `cannot reach Switch at ${API_ENDPOINT} to load its operations: ${err instanceof Error ? err.message : err}`- );+// Load the operation list before serving, so the tool surface is whole the+// first time a host asks for it.+//+// Unbound, any candidate's credentials will do — they all target the one+// server this store resolved to. They are tried in turn so a single revoked+// token does not present itself as an unreachable Switch.+//+// An unreachable server degrades rather than exiting, for the same reason a+// missing identity does: "Switch is down" and "you have no credentials" are the+// same closed pipe from the host's side, and only this process can tell them+// apart.+if (!isDegraded()) {+ try {+ if (isBound()) {+ await loadOperations(API_ENDPOINT, AGENT_ID, API_TOKEN);+ } else {+ let lastError: unknown;+ for (const candidate of unboundCandidates) {+ try {+ await loadOperations(API_ENDPOINT, candidate.agentId, candidate.token);+ lastError = undefined;+ break;+ } catch (err) {+ lastError = err;+ process.stderr.write(+ `switch: could not load operations as ${candidate.name}: ${err instanceof Error ? err.message : err}\n`+ );+ }+ }+ if (lastError !== undefined) throw lastError;+ }+ } catch (err) {+ degrade(+ `cannot reach Switch at ${API_ENDPOINT} to load its operations: ${err instanceof Error ? err.message : err}`+ );+ }}await mcp.connect(transport);serving = true;-startHookListener();--// The connection exists for the life of this process, not just while a room is-// attached: it is what correlates every tool call, and what the server uses to-// know this agent is reachable at all.-startStream();-startHeartbeat();--process.stderr.write(`switch: running (agent_id=${AGENT_ID})\n`);+// Degraded, none of the machinery below has anything to act on: no identity to+// open a connection as, no room to route a hook to. Publishing no port also+// keeps a pre-expansion spawn — which used to exit on sight — from racing the+// real one for the port file, since there is now nothing for it to write.+if (isDegraded()) {+ process.stderr.write(`switch: running degraded — serving only ${UNAVAILABLE_TOOL.name}\n`);+} else {+ startHookListener();++ // The connection exists for the life of this process, not just while a room is+ // attached: it is what correlates every tool call, and what the server uses to+ // know this agent is reachable at all. With no identity yet there is nothing to+ // open it as — `select_agent` starts both once it binds one.+ if (isBound()) {+ startStream();+ startHeartbeat();+ process.stderr.write(`switch: running (agent_id=${AGENT_ID})\n`);+ } else {+ process.stderr.write(+ `switch: running unbound — ${unboundCandidates.length} agents provisioned here, awaiting select_agent\n`+ );+ }+}diff --git a/dash/packages/switch-agent-runtime/src/credentials.test.ts b/dash/packages/switch-agent-runtime/src/credentials.test.tsnew file mode 100644index 000000000..b0819988d--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/credentials.test.ts@@ -0,0 +1,143 @@+import * as fs from 'node:fs';+import { tmpdir } from 'node:os';+import * as path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { AGENTS_DIR_RELATIVE, distinctEndpoints, readAgentStore } from './credentials';++const roots: string[] = [];++afterEach(() => {+ for (const dir of roots.splice(0)) fs.rmSync(dir, { recursive: true, force: true });+});++function root(): string {+ const dir = fs.mkdtempSync(path.join(tmpdir(), 'switch-store-test-'));+ roots.push(dir);+ return dir;+}++function writeEntry(base: string, name: string, body: unknown): void {+ const dir = path.join(base, AGENTS_DIR_RELATIVE);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, name), JSON.stringify(body));+}++/** The shape switchdash writes, and that Claude Code reads natively. */+function credsEnv(agentId: string, token = 'tok-abc', endpoint = 'https://switch.example') {+ return {+ env: { SWITCH_API_ENDPOINT: endpoint, SWITCH_API_TOKEN: token, SWITCH_AGENT_ID: agentId },+ };+}++describe('readAgentStore', () => {+ it('is empty, not an error, when the directory has no store at all', () => {+ const store = readAgentStore(root());++ expect(store.agents).toEqual([]);+ expect(store.unusable).toEqual([]);+ });++ it('resolves an agent from the file switchdash writes', () => {+ const project = root();+ writeEntry(project, 'reviewer.json', credsEnv('agent-uuid-1'));++ expect(readAgentStore(project).agents).toEqual([+ {+ slug: 'reviewer',+ name: 'reviewer',+ agentId: 'agent-uuid-1',+ endpoint: 'https://switch.example',+ token: 'tok-abc',+ },+ ]);+ });++ it('accepts flat field names as well as the env block', () => {+ const project = root();+ writeEntry(project, 'flat.json', {+ name: 'reviewer',+ agent_id: 'agent-uuid-2',+ endpoint: 'https://switch.example',+ token: 'tok-flat',+ });++ expect(readAgentStore(project).agents[0]).toMatchObject({+ name: 'reviewer',+ agentId: 'agent-uuid-2',+ token: 'tok-flat',+ });+ });++ it('reports an entry missing its token, rather than dropping it', () => {+ const project = root();+ writeEntry(project, 'orphan.json', {+ env: { SWITCH_API_ENDPOINT: 'https://switch.example', SWITCH_AGENT_ID: 'agent-uuid-3' },+ });++ const store = readAgentStore(project);++ expect(store.agents).toEqual([]);+ expect(store.unusable).toHaveLength(1);+ expect(store.unusable[0].slug).toBe('orphan');+ expect(store.unusable[0].reason).toContain('no API token');+ });++ it('reports a malformed entry instead of skipping it silently', () => {+ const project = root();+ const dir = path.join(project, AGENTS_DIR_RELATIVE);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'broken.json'), '{not json');++ const store = readAgentStore(project);++ expect(store.agents).toEqual([]);+ expect(store.unusable[0]).toMatchObject({ slug: 'broken' });+ expect(store.unusable[0].reason).toContain('malformed');+ });++ it('reads every agent provisioned in the directory', () => {+ const project = root();+ writeEntry(project, 'alice.json', credsEnv('uuid-a', 'tok-a'));+ writeEntry(project, 'bob.json', credsEnv('uuid-b', 'tok-b'));++ expect(+ readAgentStore(project)+ .agents.map((a) => a.token)+ .sort()+ ).toEqual(['tok-a', 'tok-b']);+ });++ it('ignores non-JSON files in the store directory', () => {+ const project = root();+ const dir = path.join(project, AGENTS_DIR_RELATIVE);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, '.gitignore'), '*\n');++ const store = readAgentStore(project);++ expect(store.agents).toEqual([]);+ expect(store.unusable).toEqual([]);+ });+});++describe('distinctEndpoints', () => {+ it('separates agents belonging to different servers', () => {+ const project = root();+ writeEntry(project, 'dev.json', credsEnv('uuid-dev', 'tok-dev', 'https://dev.example'));+ writeEntry(project, 'prod.json', credsEnv('uuid-prod', 'tok-prod', 'https://prod.example'));++ expect(distinctEndpoints(readAgentStore(project).agents)).toEqual([+ 'https://dev.example',+ 'https://prod.example',+ ]);+ });++ it('collapses trailing-slash variants of the same server', () => {+ const agents = [+ { endpoint: 'https://switch.example' },+ { endpoint: 'https://switch.example/' },+ ] as Parameters<typeof distinctEndpoints>[0];++ expect(distinctEndpoints(agents)).toEqual(['https://switch.example']);+ });+});diff --git a/dash/packages/switch-agent-runtime/src/credentials.ts b/dash/packages/switch-agent-runtime/src/credentials.tsnew file mode 100644index 000000000..579d3860d--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/credentials.ts@@ -0,0 +1,134 @@+/**+ * The local agent store: who this machine can be, and the credentials to prove+ * it.+ *+ * A session switchdash launched gets its identity from the environment and never+ * reaches any of this. Everything else — a connector plugin installed by hand, a+ * Codex session started from a shell — has only what is on disk.+ *+ * One file per agent, in the working directory switchdash already writes to, in+ * the shape it already writes. Keeping the token out of the working tree is a+ * real improvement and a separate change: two credential locations is a thing+ * every reader, writer, migration and teardown path then has to hold in its+ * head, and that cost belongs to the change that buys it, not to this one.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/** Where the store lives, relative to the working directory. */+export const AGENTS_DIR_RELATIVE = path.join('.switch', 'agents');++/** An agent this machine is provisioned for. */+export type ResolvedAgent = {+ /** The store's own handle for the agent — the file's name. */+ slug: string;+ /** The agent's name on the Switch server. */+ name: string;+ agentId: string;+ endpoint: string;+ token: string;+};++/**+ * A file that named an agent but could not be used, and why.+ *+ * Kept rather than dropped: "you have no agents" and "you have one that is+ * broken" call for completely different fixes, and a store that silently skips+ * the broken entry tells you the first when it means the second.+ */+export type UnusableAgent = { slug: string; reason: string };++export type AgentStore = {+ agents: ResolvedAgent[];+ unusable: UnusableAgent[];+ /** The directory scanned, for error messages. */+ projectDir: string;+};++function readJson(file: string): Record<string, unknown> | null {+ let raw: string;+ try {+ raw = fs.readFileSync(file, 'utf8');+ } catch {+ return null;+ }+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;+ return parsed as Record<string, unknown>;+ } catch {+ return null;+ }+}++function str(value: unknown): string {+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : '';+}++/**+ * Read one entry.+ *+ * The `{ env: { SWITCH_* } }` shape is what switchdash writes and what Claude+ * Code reads natively from the same file, so it is the shape here. The flat+ * field names are accepted too, since they are the obvious thing to write by+ * hand and cost one line to support.+ */+function parseEntry(file: string, slug: string): ResolvedAgent | { error: string } {+ const data = readJson(file);+ if (data === null) return { error: `unreadable or malformed JSON: ${file}` };++ const env = (data.env ?? {}) as Record<string, unknown>;+ const name = str(data.name) || slug;+ const agentId = str(data.agent_id) || str(env.SWITCH_AGENT_ID);+ const endpoint = str(data.endpoint) || str(env.SWITCH_API_ENDPOINT);+ const token = str(data.token) || str(env.SWITCH_API_TOKEN);++ if (!agentId) return { error: `no agent id in ${file}` };+ if (!endpoint) return { error: `no endpoint in ${file}` };+ if (!token) return { error: `no API token in ${file}` };++ return { slug, name, agentId, endpoint, token };+}++/**+ * Enumerate the agents this working directory is provisioned for.+ *+ * The directory not existing is an ordinary answer — an empty store, not an+ * error — because that is what an unconfigured directory legitimately looks+ * like.+ */+export function readAgentStore(projectDir: string): AgentStore {+ const dir = path.join(projectDir, AGENTS_DIR_RELATIVE);+ const agents: ResolvedAgent[] = [];+ const unusable: UnusableAgent[] = [];++ let files: string[];+ try {+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'));+ } catch {+ return { agents, unusable, projectDir: dir };+ }++ for (const file of files.sort()) {+ const slug = file.slice(0, -'.json'.length);+ const parsed = parseEntry(path.join(dir, file), slug);+ if ('error' in parsed) {+ unusable.push({ slug, reason: parsed.error });+ continue;+ }+ agents.push(parsed);+ }++ return { agents, unusable, projectDir: dir };+}++/** Compare endpoints without tripping over a trailing slash. */+export function normalizeEndpoint(endpoint: string): string {+ return endpoint.trim().replace(/\/+$/, '');+}++/** The distinct Switch endpoints a set of agents belongs to. */+export function distinctEndpoints(agents: ResolvedAgent[]): string[] {+ return [...new Set(agents.map((a) => normalizeEndpoint(a.endpoint)))].sort();+}