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(claude): the configure skill's own output left standalone agents unable to connect (CHOO-1862) (#205)
Christian McDermott5ee87f949279
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e6403e3b3..d8d75f60e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -692,6 +692,13 @@ version of their own to them without also giving them a release of their own.#### Fixed+- A directory configured by the connector's `configure` skill is recognised as+ an agent again. Detection read the identity only out of+ `.claude/settings.local.json`, which the skill deliberately no longer writes+ into — writing two of the three `SWITCH_*` values there is what broke+ standalone sessions. It now falls back to the credentials store, and names no+ agent when the store holds several, since choosing between them is+ `select_agent`'s job and not detection's.- An auto-started session now receives the message it was started for. Its roomconnection opens before the terminal is spawned, so the replayed trigger hadnowhere to go and — unlike the other wait paths — never retried: the agent@@ -1862,6 +1869,33 @@ The Switch protocol client and MCP runtime### [Unreleased]+#### Fixed+- An environment naming an agent but carrying no token now resolves against the+ local agent store instead of refusing to start. Any partial `SWITCH_*`+ environment was treated as a broken config, but that is the exact shape a host+ settings file produces when the credential is deliberately kept out of the+ working tree — and Claude Code exports its settings `env` block into the+ process, MCP subprocesses included. Switch Console writes exactly that shape for its own+ agents, so a session started by hand in a directory it set up degraded to+ `switch_unavailable` with a perfectly good store on disk beside it. The+ `configure` skill used to write it too; it no longer does, so this is a safety+ net for the Switch Console case rather than how the standalone path works.++ The agent id makes the lookup exact, so nothing is guessed: an id that matches+ no store entry, one belonging to a different server, or one claimed by two+ entries at once all still refuse. A token missing either of the others also+ still refuses — inferring where to send a credential is a different order of+ risk from inferring which one to send.+- Refuses a *partly* expanded environment instead of filling the gap from disk.+ Some `${SWITCH_*}` still literal while others resolved means a substitution+ step did not finish, which is not the same as a value deliberately omitted —+ and silently completing it from the store would authenticate as whatever is on+ disk without saying so. All three unexpanded is still the host's ordinary+ pre-expansion spawn.+- `normalizeEndpoint` folds scheme and host case. It went from grouping+ endpoints for display to gating whether an identity binds, and a+ differently-cased host is the same server.+### [0.3.1] - 2026-08-12#### Changed@@ -2017,6 +2051,78 @@ compatibility signal. History for those is in the git log.### [Unreleased]+#### Fixed+- **The `configure` skill no longer breaks the standalone path it exists to set+ up.** It wrote `SWITCH_API_ENDPOINT` and `SWITCH_AGENT_ID` into+ `.claude/settings.local.json`, and Claude Code turns that `env` block into real+ environment variables for everything it spawns — so every session it configured+ started with two of the three values set. The runtime takes a complete+ environment or none at all and refuses anything in between, deliberately, so+ those sessions got no Switch tools whatsoever while the token sat unread in+ `.switch/agents/<name>.json` beside them. The skill now writes the store and+ nothing else, which is the mode the runtime already supports on every published+ version; Step 1 strips any `SWITCH_*` an earlier run left in either settings+ file, and Step 9 writes `permissions.allow` alone.+- The hook no longer skips mediation on a standalone install. It read its+ credentials from the environment only, and the `configure` skill deliberately+ keeps the token out of there, so it reported itself unconfigured and returned+ without reporting or mediating anything — silently, on every tool call. It now+ falls back to the same `.switch/agents/*.json` store the runtime reads, keyed+ on the agent id the session recorded when it joined a room, and names the+ cause on stderr when it cannot resolve one instead of skipping quietly.+- The runtime resolves an agent id carrying no token against the store rather+ than refusing outright. The skill no longer produces that state, but Switch+ Console writes the same two keys for its own agents, so a session started by+ hand in a directory Switch Console set up hit the identical dead end.+- The `configure` skill read a `401` from the health probe as the wrong server+ and sent the user off to find a different URL. The bridge authenticates+ everything but a few public routes, so a path left on the end of an otherwise+ correct base URL answers 401 rather than 404 — the host was right and only+ needed stripping back.+- The hook resolves an identity the same way the runtime does in three more+ cases, each of which let a session run while its governance quietly did not.+ It folds endpoint case, as the runtime does, so a differently-cased host no+ longer binds in one and matches nothing in the other. It refuses a partly+ unexpanded `${SWITCH_*}` environment instead of completing it from disk. And+ it refuses a token that is missing either of the other two, rather than+ substituting a different credential from the store while the session itself+ refuses to start — a test had asserted that substitution as correct.+- A failed mediation check says so. Any error reaching the bridge — a revoked+ token, an unreachable server, a timeout — was swallowed and the tool call+ proceeded with nothing printed, which is indistinguishable from approval. The+ call still proceeds, because a bridge outage must not wedge a session, but it+ now says on stderr that it was not checked.+- The `configure` skill no longer overwrites a credentials file that belongs to+ another Switch setup. Its script writes `.switch/agents/<name>.json` by name+ alone and truncated whatever was there, which in a directory shared with a+ Switch Console install (or an earlier run against a different server) destroyed+ a token that is issued once and stored nowhere else. It now stops before+ registering if that file names a different Switch server, and reports which —+ the same guard the Codex skill and Switch Console's own write paths got. The+ subagent step gets it too, over+ `.claude/switch-subagents/<name>.settings.json`: that path is Claude-only, so+ it was outside that sweep, and it is checked across the whole batch before the+ bulk registration, since refusing afterwards would strand every agent in it.++#### Changed+- The `configure` skill is rebuilt on the standalone shape the Codex connector+ uses: registering and writing the credentials are separate steps that still run+ as one command (the API key is returned once), the env-var expansion pitfall+ sits beside the request it applies to rather than after the script that trips+ on it, the heredoc wrapper is shown rather than described, and the server URL is+ probed before anything depends on it. It also writes `permissions.allow` for the+ connector's tools, which Switch Console always did and a skill-configured+ install went without — so every room action stopped for an approval prompt.+- The per-project vs global scope choice is gone. Global wrote the identity+ machine-wide, but credentials are only ever read from the session's working+ directory, so it behaved as per-project with extra steps.+- The skill no longer asks for or sends `notify_user`, which left the platform+ when owner-linked addressing arrived. It had survived here as a step collecting+ a value the server no longer reads.+- Both room-workflow skills list the full set of reasons `switch_unavailable`+ can be the only tool, and both now point at the `configure` skill as the remedy+ for the ones it can fix.+### [0.9.5] - 2026-08-18#### Changed@@ -2106,8 +2212,10 @@ compatibility signal. History for those is in the git log.conclude anything from a truncated read.#### Removed-- Dropped the bundled `configure` skill as part of removing the private-repo /- `gh` setup machinery now that the repository is public (CHOO-2023).+- Dropped the `configure` skill's Step 0, which installed the private-repo /+ `gh` setup machinery, now that the repository is public. The skill itself+ stays; an earlier version of this entry said it had been removed wholesale,+ which it had not.### [0.7.9] - 2026-08-09@@ -2150,6 +2258,14 @@ manifest history.a token that is issued once and stored nowhere else. It now stops beforeregistering if that file names a different Switch server, and reports which.+#### Changed+- Skill: list the full set of reasons `switch_unavailable` can be the only tool.+ The runtime is shared, so the identity failures added there apply here too;+ three of the six were missing.+- Skill: point at the `configure` skill as the remedy for the causes it can fix,+ rather than saying the state is unfixable from inside the session — the Codex+ `configure` skill shipped in 0.3.2, so the remedy now exists on both hosts.+### [0.3.5] - 2026-08-15#### Changeddiff --git a/connectors/claude-code-plugin/hooks/switch_hook.py b/connectors/claude-code-plugin/hooks/switch_hook.pyindex 19d080d63..663251f3b 100644--- a/connectors/claude-code-plugin/hooks/switch_hook.py+++ b/connectors/claude-code-plugin/hooks/switch_hook.py@@ -4,11 +4,14 @@Reads the hook event payload from stdin, manages session state, and calls theSwitch Agent Bridge HTTP API for pre/post tool mediation and event reporting.-Config is read from environment variables set in the user's-`.claude/settings.local.json` env block (the same values consumed by the MCP-server in `.mcp.json`):+Credentials come from the environment when a host injects one (Switch Console+does), and otherwise from the same local agent store the Switch runtime reads,+`<project>/.switch/agents/*.json`. Both sources matter: a session started by+hand has only the store, and a hook that read the environment alone reported+itself unconfigured and skipped every mediation check in silence.SWITCH_API_ENDPOINT — Switch server URLSWITCH_API_TOKEN — Agent API key+ SWITCH_AGENT_ID — Which stored agent to use, when the store holds severalCLAUDE_PLUGIN_DATA — Persistent plugin data directory (auto-injected)"""@@ -16,15 +19,261 @@ from __future__ import annotationsimport jsonimport os+import reimport sysimport timeimport urllib.requestimport uuid-API_ENDPOINT = os.environ.get("SWITCH_API_ENDPOINT", "").rstrip("/")-API_TOKEN = os.environ.get("SWITCH_API_TOKEN", "")++def _looks_unresolved(value: str) -> bool:+ """A host may spawn this before expanding its settings env block, leaving+ `${VAR}` literals. Those are not values — and taken as values they become a+ URL nothing can be fetched from, failing every call in silence."""+ return value.startswith("${") and value.endswith("}")+++def _env_value(name: str) -> str:+ raw = os.environ.get(name, "")+ return "" if _looks_unresolved(raw) else raw.strip()+++def _normalize_endpoint(endpoint: str) -> str:+ """Fold the parts of a URL that are defined to be case-insensitive.++ Scheme and host fold; the path does not, because it is case-sensitive and+ folding it would call two different resources the same. This decides whether+ the hook resolves the same agent the runtime bound, so it must match+ `normalizeEndpoint` in the runtime's `credentials.ts` exactly — where they+ disagree, a session authenticates as one agent and is mediated as another,+ or is not mediated at all.+ """+ trimmed = endpoint.strip().rstrip("/")+ return re.sub(+ r"^([a-zA-Z][a-zA-Z0-9+.\-]*://)([^/?#]*)",+ lambda m: m.group(1).lower() + m.group(2).lower(),+ trimmed,+ )+++_IDENTITY_VARS = ("SWITCH_API_ENDPOINT", "SWITCH_API_TOKEN", "SWITCH_AGENT_ID")+++def _partially_unresolved() -> list[str]:+ """`SWITCH_*` names left as a literal `${...}` while others expanded.++ Mirrors `partiallyUnresolved()` in the runtime's `bin.ts`. A substitution+ step that did not finish is not the same as a value deliberately omitted,+ and completing the rest from the store would authenticate as whatever is on+ disk without saying so. All three unexpanded is the host's ordinary+ pre-expansion spawn and is not this case.+ """+ raw = [(n, os.environ.get(n, "")) for n in _IDENTITY_VARS]+ unresolved = [n for n, v in raw if _looks_unresolved(v)]+ resolved = [n for n, v in raw if v != "" and not _looks_unresolved(v)]+ return unresolved if unresolved and resolved else []+++UNRESOLVED = _partially_unresolved()+API_ENDPOINT = _normalize_endpoint(_env_value("SWITCH_API_ENDPOINT"))+API_TOKEN = _env_value("SWITCH_API_TOKEN")+ENV_AGENT_ID = _env_value("SWITCH_AGENT_ID")PLUGIN_DATA = os.environ.get("CLAUDE_PLUGIN_DATA", "")+# Every SWITCH_* variable this reads, and where the runtime reads it from, are+# the same — so where they disagree the session is mediated as one agent and+# acts as another. The two are kept deliberately in step; see+# `resolveIdentity()` in the runtime's `bin.ts`.+#+# The store is per working directory, and the runtime reads it from the+# process's. `CLAUDE_PROJECT_DIR` names the same directory explicitly, but only+# cwd is guaranteed to be what the runtime used, so cwd is tried first and the+# other only stands in when it holds nothing.+_STORE_DIRS = [+ os.path.join(d, ".switch", "agents")+ for d in dict.fromkeys(+ p for p in (os.getcwd(), os.environ.get("CLAUDE_PROJECT_DIR", "")) if p+ )+]+AGENTS_DIR = _STORE_DIRS[0] if _STORE_DIRS else ".switch/agents"++_STORE_CACHE: list[dict] | None = None+++def _read_agent_store() -> list[dict]:+ """Every usable agent provisioned in this working directory.++ Mirrors the runtime's reader: the `{"env": {...}}` shape Switch Console+ writes, plus the flat field names that are the obvious thing to write by+ hand. An entry missing any of the three is not usable and is skipped —+ the caller's job is to pick between agents, not to repair them.++ Cached: this runs per hook event, several times, and the process is too+ short-lived for the directory to change underneath it.+ """+ global _STORE_CACHE+ if _STORE_CACHE is not None:+ return _STORE_CACHE++ agents: list[dict] = []+ for directory in _STORE_DIRS:+ try:+ filenames = sorted(f for f in os.listdir(directory) if f.endswith(".json"))+ except OSError:+ continue++ for filename in filenames:+ try:+ with open(os.path.join(directory, filename)) as f:+ data = json.load(f)+ except (OSError, ValueError):+ continue+ if not isinstance(data, dict):+ continue+ env = data.get("env")+ env = env if isinstance(env, dict) else {}+ agent = {+ "agent_id": str(+ data.get("agent_id") or env.get("SWITCH_AGENT_ID") or ""+ ).strip(),+ "endpoint": _normalize_endpoint(+ str(data.get("endpoint") or env.get("SWITCH_API_ENDPOINT") or "")+ ),+ "token": str(+ data.get("token") or env.get("SWITCH_API_TOKEN") or ""+ ).strip(),+ }+ if agent["agent_id"] and agent["endpoint"] and agent["token"]:+ agents.append(agent)+ if agents:+ break++ _STORE_CACHE = agents+ return agents+++_CREDENTIALS_CACHE: dict[str, tuple[str, str]] = {}+++def _credentials(agent_id: str = "") -> tuple[str, str]:+ """`(endpoint, token)` to act as `agent_id`, or `("", "")` if unresolvable.++ `agent_id` is the agent the session actually bound, recorded when it joined+ a room. It is what makes the lookup exact when a directory provisions+ several agents — without it the only safe answer there is to give up,+ since mediating as the wrong agent is worse than not mediating.+ """+ if agent_id in _CREDENTIALS_CACHE:+ return _CREDENTIALS_CACHE[agent_id]++ resolved = _resolve_credentials(agent_id)+ _CREDENTIALS_CACHE[agent_id] = resolved+ return resolved+++def _resolve_credentials(agent_id: str) -> tuple[str, str]:+ # A substitution that did not finish is not a deliberate omission, and the+ # runtime refuses it rather than filling the gap from disk. Resolving here+ # where the runtime refused would mediate a session that has no identity.+ if UNRESOLVED:+ return "", ""++ # A token in the environment that is missing either of the others is a broken+ # config, and the runtime refuses it outright rather than completing it from+ # the store. Falling back here would mediate with a credential nobody asked+ # for, while the session itself is refusing to start.+ if API_TOKEN and not (API_ENDPOINT and ENV_AGENT_ID):+ return "", ""++ # A complete environment wins: it is what Switch Console injects per session,+ # and it is chosen for that session deliberately. "Complete" must mean the+ # same three values the runtime requires — the two resolve the same directory+ # and the same environment, and a session whose tool calls are mediated as a+ # different agent than it acts as is worse than one that is not mediated.+ #+ # And it wins only for the agent it names. `agent_id` is who the session+ # actually bound; if the environment names someone else, using its token+ # would authenticate agent B's credential against agent A's URL, which is+ # the one outcome this function exists to prevent.+ if API_ENDPOINT and API_TOKEN and ENV_AGENT_ID:+ if not agent_id or agent_id == ENV_AGENT_ID:+ return API_ENDPOINT, API_TOKEN++ candidates = _read_agent_store()+ wanted = agent_id or ENV_AGENT_ID+ if wanted:+ candidates = [a for a in candidates if a["agent_id"] == wanted]+ # Narrow by endpoint before counting, so an explicit endpoint can break a+ # tie — the same order the runtime resolves in.+ if API_ENDPOINT:+ candidates = [a for a in candidates if a["endpoint"] == API_ENDPOINT]++ if len(candidates) == 1:+ return candidates[0]["endpoint"], candidates[0]["token"]+ return "", ""+++def _configured() -> bool:+ """Whether this directory has any Switch identity for the hook to use."""+ return bool(API_ENDPOINT and API_TOKEN) or bool(_read_agent_store())+++def _has_credentials(agent_id: str) -> bool:+ """Whether this agent can be mediated for — saying so when it cannot.++ Reaching here means the session is in a room, so it resolved an identity+ somehow and this hook could not follow it. Mediation is then not happening,+ and the one thing worse than that is it not happening quietly.+ """+ if _credentials(agent_id)[1]:+ return True++ # Which of these it is decides the fix, so name it rather than reporting+ # every case as "missing credentials" and sending the reader after a token+ # that may be sitting right there.+ if UNRESOLVED:+ names = " and ".join(UNRESOLVED)+ why = (+ f"{names} {'are' if len(UNRESOLVED) > 1 else 'is'} still a literal ${{...}} while other "+ "SWITCH_* variables expanded, so a substitution step did not finish. "+ f"Fix the expansion, or unset {names} to use the agent store deliberately"+ )+ print(f"[switch_hook] {why}", file=sys.stderr)+ print(+ "[switch_hook] mediation and event reporting are NOT running for this session",+ file=sys.stderr,+ )+ return False++ if API_TOKEN and not (API_ENDPOINT and ENV_AGENT_ID):+ why = (+ "SWITCH_API_TOKEN is set but "+ f"{'SWITCH_API_ENDPOINT' if not API_ENDPOINT else 'SWITCH_AGENT_ID'} is not. "+ "A token needs all three, and the runtime refuses this too — set the "+ "missing one, or unset SWITCH_API_TOKEN to use the agent store"+ )+ print(f"[switch_hook] {why}", file=sys.stderr)+ print(+ "[switch_hook] mediation and event reporting are NOT running for this session",+ file=sys.stderr,+ )+ return False++ claiming = [a for a in _read_agent_store() if a["agent_id"] == agent_id]+ if len(claiming) > 1:+ why = f"{len(claiming)} entries in {AGENTS_DIR} claim agent {agent_id}, so which token is current is unknowable — leave exactly one"+ elif claiming:+ why = f"agent {agent_id} is in {AGENTS_DIR} but belongs to {claiming[0]['endpoint']}, while this session expects {API_ENDPOINT}"+ else:+ why = f"no entry for agent {agent_id} in {AGENTS_DIR}, and no complete SWITCH_* environment — run the connector's `configure` skill in this directory"++ print(+ f"[switch_hook] {why}. Tool mediation and event reporting are NOT running "+ "for this session.",+ file=sys.stderr,+ )+ return False+def _state_path(session_id: str) -> str:return os.path.join(PLUGIN_DATA, f"session_{session_id}.json")@@ -45,15 +294,19 @@ def _save_state(session_id: str, state: dict) -> None:json.dump(state, f)-def _api_call(method: str, path: str, body: dict) -> dict:- url = f"{API_ENDPOINT}{path}"+def _api_call(method: str, path: str, body: dict, agent_id: str = "") -> dict:+ endpoint, token = _credentials(agent_id)+ if not endpoint or not token:+ raise RuntimeError(f"no Switch credentials for agent {agent_id or '(unknown)'}")++ url = f"{endpoint}{path}"data = json.dumps(body).encode()req = urllib.request.Request(url,data=data,method=method,headers={- "Authorization": f"Bearer {API_TOKEN}",+ "Authorization": f"Bearer {token}","Content-Type": "application/json",},)@@ -154,6 +407,8 @@ def handle_pre_tool_use(event: dict) -> None:state = _load_state(event["session_id"])if state is None:return+ if not _has_credentials(state["agent_id"]):+ returnrequest_id = str(uuid.uuid4())body = {@@ -165,9 +420,21 @@ def handle_pre_tool_use(event: dict) -> None:try:resp = _api_call(- "POST", f"/agents/{state['agent_id']}/mediation/pre-tool-call", body+ "POST",+ f"/agents/{state['agent_id']}/mediation/pre-tool-call",+ body,+ state["agent_id"],+ )+ except Exception as exc:+ # The call is allowed to proceed — a bridge that is down or slow must not+ # wedge the session. But it proceeds UNMEDIATED, and that has to be said:+ # a revoked token or an unreachable server looks exactly like approval+ # otherwise, which is the silence this hook exists to end.+ print(+ f"[switch_hook] mediation check failed ({type(exc).__name__}: {exc}); "+ "this tool call is proceeding WITHOUT being checked by Switch",+ file=sys.stderr,)- except Exception:returnverdict = resp.get("verdict", "proceed")@@ -206,11 +473,16 @@ def handle_post_tool_use(event: dict) -> None:request_id = str(uuid.uuid4())# Reading context means the agent caught up on room history, so clear the- # channel's missed-message tally. read_context still flows through the- # normal reporting/mediation below — this only piggybacks the reset signal.+ # channel's missed-message tally. This goes to the runtime on localhost and+ # needs no Switch credentials, so it happens before the check below — an+ # agent whose mediation cannot run still reads its room, and leaving the+ # tally climbing would tell it it is behind when it is not.if tool_name.endswith("read_context"):_notify_channel("/read-context", {})+ if not _has_credentials(agent_id):+ return+try:_api_call("POST",@@ -229,6 +501,7 @@ def handle_post_tool_use(event: dict) -> None:}],},+ agent_id,)except Exception:pass@@ -243,6 +516,7 @@ def handle_post_tool_use(event: dict) -> None:"result": tool_output,"request_id": request_id,},+ agent_id,)except Exception:return@@ -272,19 +546,23 @@ def main() -> None:file=sys.stderr,)print(f"[switch_hook] PLUGIN_DATA={PLUGIN_DATA!r}", file=sys.stderr)+ print(+ f"[switch_hook] store={AGENTS_DIR!r} agents={len(_read_agent_store())}",+ file=sys.stderr,+ )# "Not configured" is an expected state for a freshly-installed plugin# — the user hasn't run `/configure` yet, or is in the middle of doing# so. Don't spam every tool call with a hook error during setup; just- # exit cleanly and let the tool proceed. Once the env vars are set,- # real failures (network, auth, mediation denials) will still surface.- if not API_ENDPOINT or not API_TOKEN or not PLUGIN_DATA:+ # exit cleanly and let the tool proceed. Once an identity exists, in the+ # environment or the store, real failures (network, auth, mediation+ # denials) will still surface.+ if not PLUGIN_DATA or not _configured():if debug:missing = [namefor name, value in (- ("SWITCH_API_ENDPOINT", API_ENDPOINT),- ("SWITCH_API_TOKEN", API_TOKEN),+ ("a Switch identity (environment or agent store)", _configured()),("CLAUDE_PLUGIN_DATA", PLUGIN_DATA),)if not valuediff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.mdindex ab09b9090..fca3c132b 100644--- a/connectors/claude-code-plugin/skills/configure/SKILL.md+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md@@ -1,281 +1,365 @@----name: configure-description: Set up the Switch connector — register this Claude Code instance as a Switch agent and write the credentials so the MCP server and channel can connect. Use when the user asks to configure Switch, set up the plugin, register with a Switch server, or when the switch MCP tools fail because credentials are missing.+name: "configure"+description: "Set up the Switch connector for Claude Code — register this Claude Code instance as a Switch agent and write the credentials the bundled MCP server and hooks read. Use when the user asks to configure Switch, set up the plugin, register with a Switch server, or when the Switch tools report no identity."----# Configure the Switch connector+# Configure the Switch connector (Claude Code)This skill registers the current Claude Code instance as a Switch agent and-writes the resulting credentials into Claude Code settings so the `switch`-local Switch runtime can connect.+writes its credentials where the Switch runtime looks for them, so a session+started from a plain terminal acts as that agent.++**This is the standalone path.** Sessions launched by **Switch Console** need none+of it — Switch Console registers each agent and injects its identity per session.+Run this skill when there is no Switch Console: install the plugin, run this once+in the directory you work from, and `claude` connects to Switch on its own.+Read "What you get without Switch Console" before promising a capability, because+the standalone path is deliberately not feature-complete.++## What this skill does and does not touch++The plugin already ships both halves of the integration: `.mcp.json` declares+`mcpServers.switch` with the runtime and its version pin, and `hooks/hooks.json`+registers the mediation hooks.++> ⚠️ **Never write an `mcpServers.switch` entry of your own.** Not in+> `.mcp.json`, not in `.claude/settings.local.json`, not in+> `~/.claude/settings.json`. The plugin's declaration is the single definition of+> how the runtime is launched — a second one does not extend it, it competes with+> it, and the session ends up with either two runtimes or one started on terms the+> plugin never set. The same goes for `hooks/hooks.json`: the mediation hooks are+> the plugin's, and an agent that rewrites them is disabling its own governance.+> This skill supplies only the *identity*.++Two things read that identity, and they read it the same way:++1. **`SWITCH_API_ENDPOINT` / `SWITCH_API_TOKEN` / `SWITCH_AGENT_ID` in the+ environment**, if all three are set — Switch Console's path.+2. **Otherwise the local agent store**, `.switch/agents/*.json`, read from the+ **session's working directory**. That is what this skill writes.++**Those are the two modes to aim for. A half-set environment is neither, and+what happens to it depends on the runtime you have.** Older runtimes — including+the one most installs are pinned to — refuse any partial `SWITCH_*` outright and+serve nothing but `switch_unavailable`, with a perfectly good store on disk+beside them. Newer ones recover some cases: an agent id with no token is read as+a pointer into the store, and an endpoint alone narrows it to one server. A+*token* missing either of the others always refuses, on every version.++**So this skill writes the store and nothing else, and does not rely on that+recovery.** It never puts a `SWITCH_*` variable into a settings file, a wrapper+script or a shell profile. Mode two works identically on every runtime that reads+the store at all; the half-set state works on some and not others, which is not+something to build a setup path on. Every session this skill configures starts+with none of the three set and reads all three from the store.++**Identity is per working directory**, not per machine. A different directory+with its own `.switch/agents/` is a different agent, and several entries in one+directory are chosen between at session start with `select_agent`. There is no+machine-wide Switch identity to configure — if the user asks for one, explain+that the store is read from the session's working directory, so a "global"+identity would be found only in whichever directory happened to hold it.++## Step 1 — Check what is already there++The store is read from the **working directory**, so check the directory the+user will start Claude Code in:-## How the plugin reads config+```bash+ls .switch/agents/*.json 2>/dev/null+```-The plugin no longer uses Claude Code's `userConfig` block (which is global-and can't be overridden per-project). Instead, both pieces of the plugin-read three values at startup:+- **Nothing** — continue to Step 2.+- **One entry** — this directory already has an identity. Report the agent name+ and server, and ask whether to keep it. **Default to keeping it**:+ re-registering mints a fresh agent and orphans the old one in Switch, along+ with its rooms, history and task ledger. Adding a *second* agent here is a+ legitimate separate answer — see the next bullet.+- **Several entries** — the runtime cannot pick between them on its own. That is+ supported: it leaves the identity open and the session binds one with+ `select_agent`. Only add another if the user actually wants a choice at+ session start.++**Also check the environment, because it silently wins.** A complete `SWITCH_*`+environment takes precedence over the store, so a shell that already exports one+makes everything this skill writes inert — the session runs as whatever that+environment names, with no warning:-- `SWITCH_API_ENDPOINT` — Switch server URL-- `SWITCH_AGENT_ID` — the agent's ID (returned at registration)-- `SWITCH_API_TOKEN` — the agent's API key (returned at registration)+```bash+for v in SWITCH_API_ENDPOINT SWITCH_API_TOKEN SWITCH_AGENT_ID; do+ eval "printf '%s=%s\n' \"$v\" \"\${$v:+set}\""+done+```-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. By-choosing project-local vs. user-global settings, the user decides whether-this Switch identity is tied to one repo or shared across all of them.-This skill walks through registration and writes that block.+(One lookup per variable, deliberately. `printenv A B C` is not portable for+this: BSD/macOS `printenv` only reports on the **first** name, so a partial+leak — say `SWITCH_AGENT_ID` alone — prints nothing and reads as a clean+environment, when it is in fact the case that decides which agent the session+becomes.)+If all three are set, tell the user before going further: either they are+already configured and don't need this skill, or those variables are leaking in+from somewhere (a Switch Console-spawned terminal exports them) and Claude Code+must be started from a shell without them for the store to be used at all.-## Step 1 — Check existing config+**If only one or two are set, say so and stop.** That is the state this whole+skill exists to avoid, and it is the case the loop above is really looking for:+whatever you write to the store afterwards, the session inherits the half-set+environment and may never read it. Find what exports them — a shell profile, a+wrapper script, a parent process — and have the user start from a shell with none+of the three before continuing.-Read both possible settings files to see whether the plugin is already-configured:+Finally, check the settings files, which is where an older setup put things:- Project-local: `.claude/settings.local.json` (in the current workingdirectory; do not create it yet)- User-global: `~/.claude/settings.json`-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, agent-id, which file) and use `AskUserQuestion` to offer three choices:+**Any `SWITCH_*` name under `env` in either file has to go.** Claude Code turns+that block into real environment variables, so a leftover `SWITCH_AGENT_ID` or+`SWITCH_API_ENDPOINT` puts every session in this directory into the half-set+state — which on the runtime most installs are pinned to means no Switch tools at+all, whatever this skill writes afterwards. An earlier version of this skill+wrote those two keys deliberately, and Switch Console writes them for its own+agents; either is where they came from. Remove them and say you have.-- **Keep it** — stop the skill. Re-registering would mint a fresh agent- and orphan the old one in Switch.+**A `SWITCH_API_TOKEN` there is worse.** It completes the environment, which beats+the store outright, so the session runs as that token's agent no matter what is in+`.switch/agents/`. Remove it too, and because it has been sitting in a settings+file treat it as exposed and tell the user to rotate it.++Report which file held what before changing anything. Then use `AskUserQuestion`,+and offer a third option when `.claude/agents/*.md` subagents exist:++- **Keep it** — stop the skill.- **Add subagents** — keep the existing main agent and jump straight to- Step 11 to bring in `.claude/agents/*.md` subagents under it. The- parent is the already-configured agent: use its id (`env.SWITCH_AGENT_ID`- from the settings file / environment) as `parent_agent_id`. Skip steps- 2–11 entirely — you are not re-registering the main agent, only adding- children to it.-- **Reconfigure** — proceed through the normal flow below to replace the- identity.--Pick this branch when the user's intent is clearly "I have a new-subagent" rather than "set up Switch from scratch" — adding a subagent to-an already-configured dir does not require the registration of a new main-agent.--## Step 2 — Switch server URL--Use `AskUserQuestion` to confirm or override the Switch server URL — this-is the agent-bridge endpoint, written to `SWITCH_API_ENDPOINT`. If-`SWITCH_API_ENDPOINT` is already set in the environment, default to it;-otherwise ask the user for their deployment's hostname (e.g.-`http://localhost:8000` for local dev, or the URL of a hosted deployment).+ Step 11 to bring in `.claude/agents/*.md` subagents under it. The parent is the+ already-configured agent: use its id as `parent_agent_id`. Skip Steps 2–10+ entirely — you are not re-registering the main agent, only adding children.+- **Reconfigure** — proceed through the flow below to replace the identity.++If entries exist for **different Switch servers**, say so plainly: the runtime+**refuses to bind an identity** in that case, because the operation catalog is+fetched before the handshake and picking a server arbitrarily would bootstrap a+tool surface from a deployment the agent may not belong to. It still starts, and+serves one tool that explains the problem. **Fix it by keeping only one server's+agents in the directory.** Setting `SWITCH_API_ENDPOINT` alone also narrows the+store on newer runtimes, but it is a half-set environment — on the runtime most+installs are pinned to that refuses outright, so it trades one failure for+another.++The same is true of two entries claiming the **same** agent id: the runtime+cannot tell which token is current, so it refuses rather than guessing. Leave+exactly one.++## Step 2 — Switch server URL, and prove it before going on++Confirm the Switch server URL — the **agent-bridge** endpoint, written as+`SWITCH_API_ENDPOINT`. If it is already set in the environment, offer that as+the default; otherwise ask for the deployment's base URL, **with a scheme** (e.g.+`http://localhost:8000` for local dev).++**It is not the gateway URL, and that is the most common way this goes wrong.**+The gateway is the web UI the user mints their token in; the agent bridge is the+API this agent talks to. They are often the same host and often not. Take a bare+scheme-and-host: strip any path (`/gateway`, `/agents/register-known`, a trailing+`/`) before using it, because every later step appends its own.++Hold the agreed value as `ENDPOINT` — later steps all build on it — and prove it+now, with the bridge's public health route, rather than discovering at Step 8+that it was wrong:++```bash+ENDPOINT="https://switch.example" # the value confirmed above, no trailing slash+curl -s -w '\n%{http_code}\n' --max-time 10 "$ENDPOINT/health"+```++**Both halves of the first bullet matter.** A gateway serves a single-page app on+every path, so it answers `/health` with `200` and an HTML page — measured on a+real deployment. A check that reads only the status code passes it and sends you+on to fail at registration, which is the exact waste this probe exists to+prevent.++- **`{"status":"ok"}` and `200`** — this is the agent bridge. Continue.+- **`401`** — right host, **wrong path**: a path was left on the end. The bridge+ authenticates everything except a few public routes, `/health` among them, so a+ bad path answers 401 rather than 404. Strip back to scheme-and-host and probe+ again. Do **not** read this as the wrong server and ask for another URL — the+ host was right.+- **`404`, `405`, or an HTML body** — wrong host: the gateway or a static server,+ not the bridge. Ask for the bridge URL; do not go hunting for another path on+ this one. `/gateway/agents/register-known` is **not** it — the gateway's+ registration route is session-authenticated and will not accept a registration+ token.+- **`000`** — nothing answered: wrong host or port, the server is not running, or+ a proxy is in the way. Show the user the URL you tried and stop.++Use `/health` specifically, not the registration route. An unauthenticated POST+to `/agents/register-known` returns 401 on the correct host *and* on a wrong path+on that host, so it cannot tell you the base URL is right — measured on a live+deployment.++Do not skip this because the user sounded confident. Getting the URL wrong is the+single most likely way this skill wastes someone's time: the mistake would+otherwise surface at Step 8, several steps after the user handed over a token,+and a wrong-but-reachable host fails there in ways that read as a bad token+rather than a bad URL.## Step 3 — Registration token-Registration is gated by a token the user mints in the Switch gateway UI-under the **API keys** tab (it's a server-side `api_key` of type-`"registration"` owned by that user; the bridge resolves it to the-owning user when minting the agent, so the new Claude Code agent ends-up owned by whoever issued the token).--Check the current environment for `SWITCH_REGISTRATION_TOKEN` (run-`printenv SWITCH_REGISTRATION_TOKEN` via Bash). If unset, ask the user-to paste it, telling them exactly where to get it: **"Open the Switch-gateway UI for your deployment, go to the API keys tab, and create (or copy-an existing) registration token."** Don't just say "from the admin" — point-them at the concrete UI surface.--**Treat the token as sensitive.** It lets the holder mint agents owned by-its user. Never echo it back, never write it to any file, never include-it inline in a Bash command (it would land in shell history). Pass it via-the existing environment variable only — see step 7.--## Step 4 — Scope--Each Switch agent is a durable identity in the Switch server: it owns-rooms it's joined, conversation history with other agents and humans,-and a task ledger. The scope choice here decides whether that identity-follows the **repo** or follows the **Claude Code installation**.--Before asking, explain the choice to the user in plain terms. Then use-`AskUserQuestion` with these two options. Make the descriptions concrete-about what it means in practice — not just which file gets written.--- **Per-project** *(default)* —- Label: `Per-project (recommended)`- Description: `This repo gets its own Switch agent. Other repos you- open won't share its rooms, history, or tasks — when teammates see- the agent in Switch they'll know it's the one working on this- codebase. Credentials are written to <cwd>/.claude/settings.local.json- (git-ignored).`--- **Global** —- Label: `Global (one identity everywhere)`- Description: `One Switch agent shared by every Claude Code session on- this machine, regardless of which repo you open. Use this if you only- really work in one place, or if you want a single "this is me"- identity in Switch. Credentials are written to- ~/.claude/settings.json.`--Per-project is the right default for most setups because:-- Each repo is usually a distinct working context (different teammates,- different rooms, different tasks). Mixing them under one agent makes- Switch's history and room views harder to read.-- The API token lives in the repo's git-ignored local settings, so it- doesn't leak into your home directory and isn't visible to other- projects.-- If the user later wants a shared identity, they can re-run this- skill and pick Global; the reverse (extracting one repo from a global- identity) is harder.--Choose Global only when the user clearly wants one identity (e.g.-personal laptop with no team setup, or a single-project machine).--## Step 5 — Agent name and description--Switch validates the agent name against `^[a-z0-9][a-z0-9._-]*$` —-lowercase letters, digits, dots (`.`), hyphens (`-`), and underscores-(`_`) only. Must start with a letter or digit. **No spaces, no `@`, no-uppercase.** The constraint exists because the name is used in Matrix-room handles and `@mention` syntax inside rooms.--Suggest a default that **identifies the user**, not just the repo or-machine. Switch agent names are visible to everyone in the rooms this-agent joins — teammates, the moderator, other AI agents. If two-developers at the same company both register a Claude Code agent from a-popular shared repo (e.g. `my-project`), a repo-only name like-`claude-code.my-project` collides for both of them and nobody can tell-which human is behind which agent. Always include a per-user identifier:--- per-project: `claude-code.<slug-of-repo-name>.<slug-of-username>`- (e.g. for repo `my-project` on user `alice` →- `claude-code.my-project.alice`). Get the repo name from- `basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"` and- the username from `$USER` or `whoami`.-- global: `claude-code.<slug-of-username>`. Get the username from- `$USER` or `whoami`.--To slugify: lowercase the string, replace any character not in-`[a-z0-9._-]` with `-`, collapse consecutive `-`, strip leading and-trailing `-`.--Use `AskUserQuestion` to confirm the suggested name or accept a custom-one. If the user wants a different identifier (full name, team prefix,-email local-part), accept it — the goal is just that the name-disambiguates *which person's Claude Code* this is, not that it has any-specific shape. If the user supplies a name that does not match the-regex, explain why (so they can fix it themselves next time) and ask-again. If the user proposes a name without any obvious user identifier-in a per-project setup, flag the collision risk once and let them decide-— don't override their choice.--Also ask for a one-line description — it shows up in Switch room-participant lists, so it should help other agents and humans recognise-this one. Default: `Claude Code running in <repo-name-or-hostname>`.--## Step 6 — Channel support--Switch's Claude Code connector can deliver inbound room events into the-session via a *channel* — an MCP notification stream that only works-when Claude Code is launched with+Registration is gated by a token the user mints in the Switch gateway UI under+the **API keys** tab (a server-side `api_key` of type `"registration"`; the+bridge resolves it to the owning user, so the new agent is owned by whoever+issued it).++Check the environment for `SWITCH_REGISTRATION_TOKEN` (`printenv+SWITCH_REGISTRATION_TOKEN`). If unset, ask the user to paste it and tell them+exactly where to get it: **"Open the Switch gateway UI for your deployment, go+to the API keys tab, and create (or copy an existing) registration token."**+Don't just say "from the admin" — point at the concrete UI surface.++**Treat the token as sensitive.** It mints agents owned by its user. Never echo+it, never write it to any file, never inline it in a shell command (it would+land in shell history). Pass it via the environment variable only — `export` it+in one command, then reference it by name in the next.++> ⚠️ **If the user pastes the token into the conversation, it is already+> exposed** — it is in the transcript, and wherever that transcript is stored or+> logged. Anything you do next cannot unspill it. Do not compound it by putting+> the value on a command line, where it also lands in shell history and process+> listings. Instead:+>+> - Ask the user to export it in their own shell and re-run, so it reaches you+> only as `$SWITCH_REGISTRATION_TOKEN`: `export SWITCH_REGISTRATION_TOKEN=...`+> (a leading space keeps it out of history in most shells).+> - If they would rather continue with the pasted value, say plainly that you are+> going to use it. Every remaining way to get it into the script puts it+> somewhere else as well — an assignment prefix+> (`SWITCH_REGISTRATION_TOKEN=... bash /tmp/register.sh`) reaches shell history+> and process listings, and an `export` reaches every later command in the+> session. Prefer the prefix: its exposure ends with that one command, and the+> token is being rotated anyway. It is *not* the inline trap Step 7 warns about,+> which breaks only when the same command also expands+> `$SWITCH_REGISTRATION_TOKEN` in its own arguments — here the script is a child+> process that reads the variable itself.+>+> **Either way it must be rotated.** The paste already exposed it, so tell them+> once, plainly, to revoke it in the gateway's API keys tab when setup is done —+> whichever branch you took. A token pasted into a chat window and then used+> without comment is the failure nobody notices until it matters.++## Step 4 — Agent name and description++Switch validates the name against `^[a-z0-9][a-z0-9._-]*$` — lowercase letters,+digits, dots, hyphens, underscores; must start with a letter or digit. **No+spaces, no `@`, no uppercase.** The name is used in Matrix room handles and+`@mention` syntax.++Suggest a default that **identifies the user**, not just the repo. Agent names+are visible to everyone in the rooms the agent joins. If two developers both+register from a shared repo, a repo-only name like `claude-code.my-project`+collides and nobody can tell which human is behind which agent:++- `claude-code.<slug-of-repo-name>.<slug-of-username>` — repo name from+ `basename "$(git rev-parse --show-toplevel 2>/dev/null || pwd)"`, username+ from `$USER` or `whoami`.++To slugify: lowercase, replace anything outside `[a-z0-9._-]` with `-`, collapse+repeats, strip leading/trailing `-`.++Confirm the name or accept a custom one; if it fails the regex, explain why and+ask again. If it carries no user identifier, flag the collision risk once and+let the user decide.++Also ask for a one-line description — it appears in room participant lists.+Default: `Claude Code running in <repo-name-or-hostname>`.++## Step 5 — Channel support++Switch's Claude Code connector can deliver inbound room events into the session+via a *channel* — an MCP notification stream that only works when Claude Code is+launched with`--dangerously-load-development-channels plugin:switch-connector@switch-plugins`.-**That flag is only honored on Claude Code installations that go through-an Anthropic subscription (claude.ai login, Anthropic Console, or-Anthropic API key). Third-party providers — Vertex AI, AWS Bedrock, and-similar — silently ignore the flag.** On those installations the agent-must be registered as `session_passive`; declaring `session_addressable`-would leave other participants expecting responses you cannot send.+**That flag is only honored on Claude Code installations that go through an+Anthropic subscription (claude.ai login, Anthropic Console, or Anthropic API+key). Third-party providers — Vertex AI, AWS Bedrock, and similar — silently+ignore the flag.** On those installations the agent must be registered as+`session_passive`; declaring `session_addressable` would leave other+participants expecting responses it cannot send.This choice changes the integration profile Switch records:- **Anthropic subscription / API key** → `channels_enabled = true` →- `session_addressable`. Other participants can `@`-mention this agent- and expect a synchronous response; tasks delegated to it surface as- notifications.-- **Third-party provider** → `channels_enabled = false` →- `session_passive`. Inbound events do not appear unless the user- explicitly asks Claude to `read_context`. Other agents know not to- expect a synchronous reply.--**You MUST call `AskUserQuestion` here.** Do not pick a default and-move on — the wrong value silently corrupts the agent's profile and-other room participants will misbehave (expecting synchronous replies-that never come, or failing to address a session_addressable agent).-There is no safe default; only the user knows which provider their-Claude Code talks to.--This is a capability check, not a preference. Phrase it as **how the-user runs Claude Code**, not as "do you want channels":--- **Anthropic subscription / API key** *(sets- `channels_enabled = true`)* —- Label: `Anthropic (claude.ai / Console / API key)`- Description: `I run Claude Code with an Anthropic login or an- ANTHROPIC_API_KEY. The development-channels flag works, so the agent- can be session_addressable.`--- **Third-party provider** *(sets `channels_enabled = false`)* —- Label: `Third-party provider (Vertex AI / Bedrock / other)`- Description: `I run Claude Code through Vertex AI, AWS Bedrock, or- another non-Anthropic provider. Those providers ignore the- development-channels flag, so the agent must be session_passive.`--Do not advance to step 7 without an explicit user selection. If the-user invoked the skill non-interactively or with auto-mode flags that-suppress questions, still ask — there is no acceptable inferred-default.--The answer is passed as `options.channels_enabled` in the register-payload.--## Step 7 — Repository directory (`repo_dir`)--Switch can show room participants a **ready-to-paste terminal command**-that spins this Claude Code agent up and connects it to the current-room (e.g. `cd <repo_dir> && claude "connect to switch room <name>"`).-That message is shown automatically whenever someone addresses this-agent while no session is active, and on demand via the `!run-cmd-@<agent-name>` room command. For the command to be useful Switch needs-to know the directory the operator runs Claude Code from — that's-`repo_dir`.--Use `AskUserQuestion` to ask whether to record `repo_dir`. Explain in-plain terms: *"If you set this, room participants who try to reach this-agent while it's offline will see a copy-pastable terminal command they-can run to start it. If you skip, they get a generic 'not connected'-message instead."*--If the user opts in, derive the value from the **scope chosen in-step 4**:--- **Per-project**: the per-project identity is tied to the directory the- skill is being run from (that's where `.claude/settings.local.json`- lives), so use the current working directory — `pwd`. Do not ask the- user; that directory *is* the project.-- **Global**: there is no sensible default to suggest — `pwd` is just- wherever the user happened to be when they ran the skill, and the- global identity isn't tied to any one repo. Ask the user explicitly- for an absolute path (a `claude` invocation should make sense from- there).--Validate that the value is an absolute path (`startswith("/")`) and-that the directory exists (`test -d "$PATH"`). If either check fails,-re-ask or let the user skip.--If the user opts out, omit `repo_dir` from the options payload (do not-pass an empty string — leave the key out so the schema default of-`None` applies).--The answer is passed as `options.repo_dir` in the register payload.--## Step 8 — Register--Call the bridge endpoint `POST /agents/register-known`. It takes the-registration token in the `Authorization` header, looks up the-`claude-code` known-agent spec in Switch (which knows the right tool-list and capabilities for Claude Code), derives the integration profile-from `options.channels_enabled`, and returns the new agent's `id` and-`api_key`.--Run from Bash with the registration token in the environment — do not-inline the token in the command itself, since command lines end up in-shell history and process listings:+ `session_addressable`. Other participants can `@`-mention this agent and+ expect a synchronous response; tasks delegated to it surface as notifications.+- **Third-party provider** → `channels_enabled = false` → `session_passive`.+ Inbound events do not appear unless the user explicitly asks Claude to+ `read_context`. Other agents know not to expect a synchronous reply.++**You MUST call `AskUserQuestion` here.** Do not pick a default and move on — the+wrong value silently corrupts the agent's profile and other room participants+will misbehave. There is no safe default; only the user knows which provider+their Claude Code talks to.++Phrase it as **how the user runs Claude Code**, not as "do you want channels":++- Label: `Anthropic (claude.ai / Console / API key)` — Description: `I run Claude+ Code with an Anthropic login or an ANTHROPIC_API_KEY. The development-channels+ flag works, so the agent can be session_addressable.`+- Label: `Third-party provider (Vertex AI / Bedrock / other)` — Description: `I+ run Claude Code through Vertex AI, AWS Bedrock, or another non-Anthropic+ provider. Those providers ignore the development-channels flag, so the agent+ must be session_passive.`++Do not advance without an explicit selection. If the user invoked the skill+non-interactively or with auto-mode flags that suppress questions, still ask.++The answer is passed as `options.channels_enabled` in the register payload.++## Step 6 — Repository directory++Switch shows room participants a paste-ready command when the agent is addressed+with no live session. It is built from what you record here and in Step 5, so it+carries the channels flag when you said channels work:++```+cd <repo_dir> && claude "connect to switch room <name>" \+ --dangerously-load-development-channels plugin:switch-connector@switch-plugins+```++(without the flag when `channels_enabled` is false).++**Note the path is not quoted** in what Switch generates, so a `repo_dir`+containing a space produces a command that breaks when pasted. If the directory+has one, say so and let the user choose a different one or accept that the+posted command needs hand-editing.++`repo_dir` is what makes it useful — **and it matters twice over**, because the+runtime reads the agent store from the session's working directory. `repo_dir`+should therefore be **the directory this skill writes the credentials into**, or+the pasted command starts Claude Code somewhere the store isn't and the session+has no identity.++Ask whether to record it, defaulting to the current working directory. Validate+that it is absolute (`startswith("/")`) and exists (`test -d`).++Omit the key entirely if the user opts out — leave it out rather than passing an+empty string, so the schema default applies.++**There is no `notify_user` to record.** Pinging the operator is now driven by+the agent's *owner*, linked to a messaging account, rather than a free-text+handle nobody validated. Do not ask for one and do not send the key.++**Do not set `auto_session`.** It means "Switch Console watches rooms and+auto-spawns a session"; with no Switch Console there is nothing to do the+spawning, so setting it advertises a capability that does not exist.++## Step 7 — Register++`POST /agents/register-known` with the registration token in the header. It looks+up the `claude-code` known-agent spec, derives the integration profile from+`options.channels_enabled`, and returns the agent's `id` and `api_key`. Do not+inline the token — command lines reach shell history and process listings:```bashcurl -sf -X POST "$ENDPOINT/agents/register-known" \@@ -290,224 +374,411 @@ curl -sf -X POST "$ENDPOINT/agents/register-known" \overwrite:false}')"```-`$CHANNELS_ENABLED` must be the JSON literal `true` or `false` (passed-via `--argjson`, not `--arg`). Set `$REPO_DIR` to the absolute path-from step 7 (or empty to omit).--**Pitfall — env-var expansion order.** Do NOT prefix the curl command-with `SWITCH_REGISTRATION_TOKEN=... curl ...` while also referencing-`$SWITCH_REGISTRATION_TOKEN` in the same command. The shell expands-`$SWITCH_REGISTRATION_TOKEN` against the *parent* shell's environment-*before* the inline assignment takes effect, so if the variable wasn't-already exported you'll send `Authorization: Bearer ` (empty), curl-drops the header, and the bridge returns `401 Missing or invalid-Authorization header` — which looks like a bad token but isn't. Either-`export` the variable first (`export SWITCH_REGISTRATION_TOKEN=...; curl-...`) or assign to a local shell variable on a preceding line-(`TOKEN='...'` then `-H "Authorization: Bearer ${TOKEN}"`). If you see-that exact 401 message, suspect this before assuming the token is-wrong.--The response is `{"id":"...","api_key":"..."}`. If `curl` exits non-zero,-re-run without `-sf` (use `-i` to capture the status line and body) and-show the user the HTTP status and response body, then stop.--**Handle the responses:**--- `401` — bad registration token; tell the user and stop.-- `400` — bad name (regex violation); show the error and re-ask name in- step 5.-- `409` — an agent with this name already exists. By default the bridge- refuses to clobber it because re-registering mints a new API key,- replaces the integration profile, and leaves the previous credentials- invalid. Use `AskUserQuestion` to confirm intent (recommended option:- "Pick a different name"). Only if the user explicitly wants to- overwrite, re-run the curl with `overwrite:true` in the body. Never- retry with `overwrite:true` silently.-- Any other non-2xx — show the status and body, then stop.--## Step 9 — 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):+**Pitfall — env-var expansion order.** Do NOT prefix the command with+`SWITCH_REGISTRATION_TOKEN=... curl ...` while also referencing+`$SWITCH_REGISTRATION_TOKEN` in it. The shell expands the variable against the+*parent* environment *before* the inline assignment applies, so you send+`Authorization: Bearer ` with nothing after it. The header is still well-formed,+so the bridge gets past its "missing header" check, finds no key matching the+empty token, and answers **`401 Invalid credentials`** — the same response a+genuinely wrong or expired token gets. There is nothing in the reply to tell the+two apart, so on any 401 rule this out first: `export` the token, or assign it to+a shell variable on a preceding line, and try again before concluding the token+is bad.++The response is `{"id":"...","api_key":"..."}`. Note that `-f` suppresses the+error body, so this shape cannot satisfy the ladder below on its own — the Step 8+script captures the status with `-w '%{http_code}'` and keeps the body, which is+what the ladder is written against. If you do run this shape and it exits+non-zero, re-run it with `-i` in place of `-sf` to see the status and body before+deciding anything.++> ⚠️ **Register and write the credentials file in ONE shell command.** This is+> the single most important instruction in this skill, and getting it wrong is+> the one way to leave things worse than you found them.+>+> The `api_key` is returned by that one call and **never again** — it cannot be+> read back from the server. And **each command you run is a separate shell+> process**, so a variable set in one does not exist in the next. Register in one+> command and try to use `$api_key` in another and it is empty: the agent now+> exists on the server with a token nobody holds, and re-registering to recover+> returns `409`.+>+> So do not split them. Do the curl and the file write in a **single**+> invocation, as Step 8 shows, or at minimum redirect the response body to a file+> (`--output`) in the same command that makes the request, and read it back from+> there. The curl above is the shape of the request, not a command to run on its+> own.+>+> Two shell details, both from real runs: `status` is a **reserved variable in+> zsh** — use `http_status` — and a `$(...)` capture of the body must not swallow+> the exit code you intend to branch on.++**Responses:**++- `401` — bad registration token (or the pitfall above); stop.+- `400 Unknown agent type: claude-code` — the server predates Claude Code+ support. Say so and stop; do not fall back to another type.+- `400` with a name validation error — re-ask in Step 4.+- `409` — that name already exists. The bridge refuses to clobber it because+ re-registering rotates the API key and invalidates the old credentials.+ **First work out which case this is**, because the fix differs:+ - **You created it moments ago, in this run** (a retry, or a re-run after a+ later step failed). The agent is yours but its token is gone — it was only+ ever returned once. The only recoveries are to re-run with `overwrite:true`+ (mints a fresh key for the same name) or to pick a new name and leave the+ orphan behind. Say plainly which you are doing and why; do not present this+ as a clean success.+ - **It pre-dates this run** — someone else's agent, or the user's own from an+ earlier setup. Ask before touching it; the recommended answer is a different+ name. Overwriting rotates a key that a live session may be using.++ Only use `overwrite:true` on an explicit decision. Never silently.+- Any other non-2xx — show status and body, then stop.++## Step 8 — Write the credentials file++**Do this in the same command as Step 7's registration** — see the warning there.++> ⚠️ **Write these lines to a file and run that file.** Do not paste them inside+> `bash -lc '…'`. The `jq` filter is single-quoted and contains its own quotes and+> newlines; wrapped in another layer of single quotes it collapses and `jq` fails+> with `syntax error, unexpected ':'` — which reads as a bad payload rather than a+> quoting accident.+>+> ```bash+> cat > /tmp/register.sh <<'SCRIPT'+> ...the script below...+> SCRIPT+> bash /tmp/register.sh+> ```+>+> The **quoted** heredoc (`<<'SCRIPT'`) is what keeps the body intact — the shell+> expands nothing on the way in. Delete the file afterwards.++**Define every variable in the same script**, before the code below — `set -eu`+aborts on the first unset one with `ENDPOINT: unbound variable` and no+registration happens:++- `ENDPOINT` — from Step 2. `NAME`, `DESC` — from Step 4.+- `CHANNELS_ENABLED` — from Step 5, the bare JSON literal `true` or `false`+ (passed with `--argjson`, not `--arg`).+- `REPO_DIR` — from Step 6. **Set it to the empty string** when the user opted+ out; leaving it unset trips `set -u`.+- `SWITCH_REGISTRATION_TOKEN` — from Step 3, already exported into the+ environment. Do not assign it inside the script; that puts it in the file.++The whole sequence, gitignore first so the token is never briefly tracked:++```bash+set -eu+mkdir -p .switch/agents+printf '*\n' > .switch/agents/.gitignore++# This file is keyed by name alone, so a directory shared with another Switch+# setup — a Switch Console install, or an earlier run of this skill against a+# different server — can already have one under this name. Writing over it+# destroys a token that was returned once and exists nowhere else, and the+# displaced agent's sessions then authenticate as this one. A different endpoint+# is what makes it someone else's: the same server would have refused the name+# at registration.+creds=".switch/agents/$NAME.json"+if [ -f "$creds" ]; then+ owner=$(jq -r '.env.SWITCH_API_ENDPOINT // empty' "$creds" 2>/dev/null || true)+ if [ -n "$owner" ] && [ "${owner%/}" != "${ENDPOINT%/}" ]; then+ printf '%s already holds credentials for the Switch server at %s.\n' "$creds" "$owner" >&2+ printf 'Refusing to overwrite them. Choose a different agent name, or a different directory.\n' >&2+ exit 1+ fi+fi++resp=$(mktemp)+trap 'rm -f "$resp"' EXIT++# -S so curl reports why it failed, and --max-time so it fails at all: with -s+# alone a refused connection or a hung host kills the script under `set -eu`+# with no output whatsoever, and the status check below never runs.+http_status=$(curl -sS --max-time 30 -o "$resp" -w '%{http_code}' -X POST "$ENDPOINT/agents/register-known" \+ -H "Authorization: Bearer $SWITCH_REGISTRATION_TOKEN" \+ -H "Content-Type: application/json" \+ -d "$(jq -nc --arg name "$NAME" --arg desc "$DESC" \+ --argjson channels "$CHANNELS_ENABLED" \+ --arg repo_dir "$REPO_DIR" \+ '{agent_type:"claude-code", name:$name, description:$desc,+ options:({channels_enabled:$channels}+ + (if $repo_dir == "" then {} else {repo_dir:$repo_dir} end)),+ overwrite:false}')")++if [ "$http_status" != "200" ]; then+ printf 'registration failed (%s): ' "$http_status"; cat "$resp"; exit 1+fi++jq --arg ep "$ENDPOINT" \+ '{env: {SWITCH_API_ENDPOINT: $ep, SWITCH_API_TOKEN: .api_key, SWITCH_AGENT_ID: .id}}' \+ "$resp" > ".switch/agents/$NAME.json"+chmod 600 ".switch/agents/$NAME.json"+jq -r '"registered " + .id' "$resp"+rm -f "$resp"+```++The token goes from the response straight into the file without ever being+echoed or held in a variable that a later command would need.++The guard runs **before** the registration, not just before the write: refusing+afterwards would leave an agent on the server whose key nobody holds. If it+fires, tell the user which server already owns that name here and let them+choose — a different name, or a different directory. Do not delete the file and+retry.++The resulting file is the same shape Switch Console writes:```json{"env": {"SWITCH_API_ENDPOINT": "<url from step 2>",- "SWITCH_AGENT_ID": "<id from step 7>"+ "SWITCH_API_TOKEN": "<api_key>",+ "SWITCH_AGENT_ID": "<id>"}}```-**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.+Write it in the directory the user will start Claude Code from — the same one+used for `repo_dir` in Step 6. The runtime reads the store from the session's+working directory, so a file in the wrong directory is simply not found.++Add `.switch/` to the repo's own `.gitignore` too if it is not already covered.+The token lives in this file in plaintext, inside the working tree; say so+plainly rather than leaving the user to find it.++No MCP config is touched. The plugin's `.mcp.json` already declares the server,+and the runtime reads this file itself.-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.+## Step 9 — Settings: auto-approve the tools-**10b — the credentials file.** Write `.switch/agents/<agent name>.json` in the-working directory, in the same shape switchdash writes:+Read `.claude/settings.local.json` (create with `{}` if absent), merge, and write+the whole file back. Use `Read` → parse → `Write`; do not edit it with a regex.+JSON formatting and adjacent keys matter, and a bad merge breaks unrelated Claude+Code config. Preserve every key the user already has.++Union this into `permissions.allow` so the connector's tools never prompt:```json{- "env": {- "SWITCH_API_ENDPOINT": "<url from step 2>",- "SWITCH_API_TOKEN": "<api_key from step 7>",- "SWITCH_AGENT_ID": "<id from step 7>"+ "permissions": {+ "allow": ["mcp__plugin_switch-connector_switch"]}}```-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.--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.+This is the Claude Code equivalent of the `default_tools_approval_mode` the Codex+connector ships in its own MCP config, and it is the same rule Switch Console+writes. Without it the agent is interrupted for approval on every room action,+which for an agent acting on someone else's message means it simply stops.++> ⚠️ **`permissions` is the only thing this step writes. Do not add an `env`+> block.** Not `SWITCH_AGENT_ID`, not `SWITCH_API_ENDPOINT`, not any other+> `SWITCH_*` name, in this file or in `~/.claude/settings.json`.+>+> Claude Code turns that block into real environment variables for everything it+> spawns, the Switch runtime included. Naming two of the three values there puts+> the runtime in the half-set state — see the top of this skill — which on the+> runtime most installs are pinned to means the session gets no Switch tools at+> all, with the token sitting unread in the store the whole time. An earlier+> version of this skill wrote exactly that and broke every standalone install it+> touched.+>+> The store already carries the endpoint and the id. Nothing needs to repeat them.++**A token in a settings file is the same failure, and worse.** An API token+belongs in exactly two places: `.switch/agents/<name>.json`, and for subagents+`.claude/switch-subagents/<name>.settings.json`. Nowhere else, ever. If either+settings file has one from an older setup, strip it and treat it as exposed —+combined with an endpoint and an id it forms a *complete* environment, which+outranks the store entirely, so the session silently runs as whatever agent that+token belongs to.## Step 10 — ConfirmReport to the user:-- The agent name and ID that were registered with Switch.-- Which settings file was written.-- 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.+- The agent name and ID registered with Switch.+- That credentials went to `.switch/agents/<name>.json` (git-ignored), and that+ the **token is stored there in plaintext** inside the working tree — a+ credential at rest in a directory they may archive or copy.+- That Claude Code must be **restarted** to pick up the identity, and that it+ must be started **from this directory**.+- If they chose channels in Step 5, the launch flag they need:+ `--dangerously-load-development-channels plugin:switch-connector@switch-plugins`.+ Without it the session still works but receives no pushed events.+- How to check: start `claude` here and ask it to `list_rooms`.-Do **not** print the API token. Echoing secrets into the transcript is a-common way they leak into logs or screenshots.+Do **not** print the API token. Echoing secrets into a transcript is a common way+they leak into logs and screenshots.## Step 11 — Bring in existing Claude Code subagents (optional)-A user may already have **Claude Code subagents** defined as-`.claude/agents/*.md` files (a `name`, `description`, optional `tools`-and `model` in YAML frontmatter). Switch can register the selected ones-as their own agents — children of the main agent you just registered —-so each can be launched as its own session and participate in rooms-under its own identity. This avoids re-running this skill once per-subagent.--Reach this step in one of two ways:--- as the tail of a fresh registration, once the main-agent registration- above **succeeded**, or-- directly from Step 1 when the dir already has a configured agent and- the user just wants to add subagents to it (parent =- `env.SWITCH_AGENT_ID`).--Either way the install must be `channels_enabled = true` (a-`session_passive` install can't drive a `--agent` session interactively-anyway). It is always optional — never register subagents without the-user's go-ahead.--### 12a — Discover subagent definitions--Scan both scopes for subagent files:--- **Project**: `.claude/agents/` walking up from the cwd to the repo- root (recurse into subfolders).-- **User**: `~/.claude/agents/` (recurse).--For each `*.md`, parse the YAML frontmatter and read `name`,-`description`, and (if present) `tools` and `model`. Identity comes from-the `name` field, not the filename. If two files declare the same-`name`, keep the higher-priority one (project over user) and ignore the-duplicate. If no subagent files exist, skip this whole step silently.--### 12b — Filter out subagents that can't participate--A subagent launched via `--agent` adopts that file's `tools` allowlist.-If the allowlist excludes the Switch MCP tools and the `Skill` tool, the-launched session **cannot** load the Switch skill or call-`connect_to_room` / `post_message`, so it can't participate in a room.--Mark a subagent **eligible** when either:--- it has **no** `tools` field (it inherits every tool, including the- Switch MCP tools and `Skill`), **or**-- its `tools` allowlist explicitly includes `Skill` **and** the Switch- MCP tools (an entry naming the switch MCP server / a- `mcp__*switch*` tool).--Otherwise mark it **skipped** and record the reason ("restricted-`tools` allowlist excludes the Switch MCP tools — can't talk in a-room"). Do not try to rewrite the user's subagent files to add tools.--### 12c — Present and select--Show the user the **eligible** set (name, one-line description, model-tier, and a short tools summary) and, separately, any **skipped** ones-with their reason so the user knows why they're excluded. Use-`AskUserQuestion` (multi-select) to let the user choose which eligible-subagents to bring into Switch — default to all eligible. If the user-declines all, skip the rest of this step.--### 12d — Bulk-register under the main agent--Call `POST /agents/register-known-bulk` with the same registration-token as Step 8. The Switch agent name for each child is derived-server-side as `<main-agent-name>.<subagent_name>`, so you only send the-bare `subagent_name` and `description`. `options` is the shared base-applied to every subagent; the server merges each `subagent_name` in on-top.--**`parent_agent_id` is the dir's main agent — read it from the-environment, don't ask.** The running session's own agent id is in-`$SWITCH_AGENT_ID` (the same value written into the settings `env` block-in Step 10). That is exactly the parent these subagents belong under, so-default `parent_agent_id` to `$SWITCH_AGENT_ID`. When you registered the-main agent earlier in *this same run* (Step 8), use that id instead — it-is the same agent. Only ask the user if neither is available.--**Subagents inherit the parent's settings automatically.** The server-reads the parent agent's recorded `channels_enabled` and `repo_dir` and-applies them as the base for every subagent (so they run in the same-channels mode and share the repo dir) — you do **not** need to recover-these from the parent or pass them. Only set a key in `options` to deliberately *override* the-inherited value; otherwise omit it.+A user may already have **Claude Code subagents** defined as `.claude/agents/*.md`+files (a `name`, `description`, optional `tools` and `model` in YAML+frontmatter). Switch can register the selected ones as their own agents —+children of the main agent — so each can be launched as its own session and+participate in rooms under its own identity.++Reach this step either as the tail of a successful registration, or directly from+Step 1 when the directory is already configured and the user just wants to add+subagents (the parent is the agent already in the store — see 11c).++Either way the install must be `channels_enabled = true` — a `session_passive`+install can't drive a `--agent` session interactively anyway. It is always+optional; never register subagents without the user's go-ahead.++### 11a — Discover and filter++Scan both scopes, recursing: **project** `.claude/agents/` walking up from the cwd+to the repo root, and **user** `~/.claude/agents/`. For each `*.md`, parse the+frontmatter for `name`, `description`, and any `tools` / `model`. Identity comes+from the `name` field, not the filename; on a duplicate name keep the+higher-priority one (project over user).++A subagent launched via `--agent` adopts that file's `tools` allowlist. If the+allowlist excludes the Switch MCP tools, the launched session **cannot** call+`connect_to_room` or `post_message`, so it can't participate in a room. Mark a+subagent **eligible** when either it has **no** `tools` field (it inherits+everything), or its allowlist contains an entry beginning+`mcp__plugin_switch-connector_switch`. Otherwise mark it **skipped** with the+reason. Do not rewrite the user's subagent files to add tools.++This is deliberately the same test Switch Console applies, so the two agree on+which subagents are usable. Note it does **not** require `Skill` — a session can+call the Switch tools without loading the room-workflow skill first; it just+does so with less guidance.++If no subagent files exist, skip this whole step silently.++### 11b — Present and select++Show the **eligible** set (name, one-line description, model tier, short tools+summary) and, separately, any **skipped** ones with their reason so the user+knows why they're excluded. Use `AskUserQuestion` (multi-select) to choose,+defaulting to all eligible. If the user declines all, skip the rest.++### 11c — Bulk-register under the main agent++`POST /agents/register-known-bulk` with the same registration token. The Switch+name for each child is derived server-side as `<main-agent-name>.<subagent_name>`,+so send only the bare `subagent_name` and `description`.++**`parent_agent_id` is this directory's main agent.** Set `PARENT_AGENT_ID`+explicitly, from whichever of these applies:++- You registered the main agent earlier **in this run** — use the id Step 8+ printed.+- You came here from Step 1 on an already-configured directory — read the id out+ of that directory's `.switch/agents/<name>.json`.++**Do not use `$SWITCH_AGENT_ID` for this.** In a correctly configured standalone+directory it is unset by design — that is the whole point of the store — so you+would send `parent_agent_id: ""` and get `404 Parent agent not found`. The store+file is the source, in both cases.++**Subagents inherit the parent's settings automatically.** The server reads the+parent's recorded `channels_enabled` and `repo_dir` and applies them as the base+for every subagent, so you do not need to pass them. Set a key in `options` only+to deliberately *override* an inherited value.++**Define every variable in this script too**, as Step 8 does — it opens `set -eu`+and aborts on the first unset one. `PARENT_AGENT_ID` as above; `SUBS_JSON` from+the block below; `ENDPOINT` and `SWITCH_REGISTRATION_TOKEN` as in Steps 2 and 3.+**Those last two matter most when you arrived here straight from Step 1**, having+skipped Steps 2–10: nothing has set them in this run, so read the endpoint out of+the same store entry you took the parent id from, and ask the user for a fresh+registration token. Do not assume either survived from an earlier session — each+command is its own shell.++`SUBS_JSON` is a JSON array of the selected subagents, built with `jq` rather+than by hand so descriptions containing quotes survive:```bash-curl -sf -X POST "$ENDPOINT/agents/register-known-bulk" \+SUBS_JSON=$(jq -nc '[+ {subagent_name: "reviewer", description: "Reviews diffs"},+ {subagent_name: "test-writer", description: "Writes tests"}+]')+```++Then register **and write the credential files in the same command** — every+`api_key` in the response is returned once, exactly as in Steps 7–8, and the same+heredoc rule applies:++```bash+set -eu+mkdir -p .claude/switch-subagents+printf '*\n' > .claude/switch-subagents/.gitignore++# The same collision as Step 8, once per subagent: these files are keyed by the+# subagent's name alone. Check the whole batch before registering — a refusal+# after the bulk call would leave every agent in it on the server with a key+# nobody holds, not just the one that clashed.+conflicts=""+for sub in $(printf '%s' "$SUBS_JSON" | jq -r '.[].subagent_name'); do+ sub_creds=".claude/switch-subagents/$sub.settings.json"+ [ -f "$sub_creds" ] || continue+ sub_owner=$(jq -r '.env.SWITCH_API_ENDPOINT // empty' "$sub_creds" 2>/dev/null || true)+ if [ -n "$sub_owner" ] && [ "${sub_owner%/}" != "${ENDPOINT%/}" ]; then+ conflicts="$conflicts+ $sub_creds (Switch server at $sub_owner)"+ fi+done+if [ -n "$conflicts" ]; then+ printf 'These files already hold credentials for a different Switch server:%s\n' "$conflicts" >&2+ printf 'Refusing to overwrite them. Deselect those subagents, or use a different directory.\n' >&2+ exit 1+fi++resp=$(mktemp)+trap 'rm -f "$resp"' EXIT++# -S so curl reports why it failed, and --max-time so it fails at all: with -s+# alone a refused connection or a hung host kills the script under `set -eu`+# with no output whatsoever, and the status check below never runs.+http_status=$(curl -sS --max-time 30 -o "$resp" -w '%{http_code}' -X POST "$ENDPOINT/agents/register-known-bulk" \-H "Authorization: Bearer $SWITCH_REGISTRATION_TOKEN" \-H "Content-Type: application/json" \- -d "$(jq -nc \- --arg parent "$SWITCH_AGENT_ID" \- --argjson subs "$SUBS_JSON" \+ -d "$(jq -nc --arg parent "$PARENT_AGENT_ID" --argjson subs "$SUBS_JSON" \'{agent_type:"claude-code", parent_agent_id:$parent,- options:{}, subagents:$subs, overwrite:false}')"+ options:{}, subagents:$subs, overwrite:false}')")++if [ "$http_status" != "200" ]; then+ printf 'bulk registration failed (%s): ' "$http_status"; cat "$resp"; exit 1+fi++jq -r --arg ep "$ENDPOINT" '.results[]+ | "\(.subagent_name)\t" + ({env: {SWITCH_API_ENDPOINT: $ep,+ SWITCH_API_TOKEN: .api_key,+ SWITCH_AGENT_ID: .id}} | tostring)' "$resp" \+| while IFS="$(printf '\t')" read -r sub body; do+ printf '%s\n' "$body" > ".claude/switch-subagents/$sub.settings.json"+ chmod 600 ".claude/switch-subagents/$sub.settings.json"+ done++jq -r '.results[] | "registered " + .name + " (" + .id + ")"' "$resp"+rm -f "$resp"```-`$SUBS_JSON` is a JSON array of `{"subagent_name": "...",-"description": "..."}` for the selected subagents. `$SWITCH_AGENT_ID` is-the parent agent id read from the environment (or the id from Step 8 if-you just registered the main agent in this run). The same-env-var-expansion pitfall and the token-handling rules from Step 8 apply-— never inline the token.+The guard reports the **whole** batch rather than stopping at the first clash, so+the user deselects once instead of rediscovering the problem one subagent at a+time. As in Step 8, it runs before the request, and the answer is a different+name or a different directory — not deleting the files.-The response is `{"results": [{"subagent_name","name","id","api_key"},-...]}`. Handle a `409` (one or more derived names already exist) by-telling the user which ones and asking whether to re-run with-`overwrite:true`; never overwrite silently.+**Responses:** `404 Parent agent not found` — `PARENT_AGENT_ID` is wrong or+empty (see above). `400 No subagents provided` — `SUBS_JSON` was an empty array.+`400 Duplicate subagent in batch` — two selected files declare the same `name`;+the 11a de-duplication did not run. `409` — one or more derived names already+exist; name which, and ask. Never overwrite silently.-### 12e — Write per-subagent credential files+### 11d — What those credential files are-For each result, write a settings file at-`<repo>/.claude/switch-subagents/<subagent_name>.settings.json` — this-is exactly the path the offline-session command points `--settings` at:+The loop above writes one file per subagent at+`<repo>/.claude/switch-subagents/<subagent_name>.settings.json` — the exact path+the offline-session command points `--settings` at:```json{@@ -519,16 +790,24 @@ is exactly the path the offline-session command points `--settings` at:}```-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.+These carry **per-subagent API tokens**, which is why the `.gitignore` goes in+before the request rather than after.++Note this file carries a *complete* identity — all three values — and that is+correct here rather than a contradiction of Step 9. A `--settings` launch replaces+the session's environment outright, so this is mode one: everything set, nothing+half-set. What Step 9 forbids is naming *some* of the three in a settings file+that applies to every session in the directory.++This is also the one Claude-specific credential location Switch Console has+since moved on from: it writes subagent credentials to `.switch/agents/` like+everything else. The server-side launch command still points at this path, so it+is the right one to write today, but expect it to migrate.-### 12f — Tell the user how to launch a subagent+### 11e — Tell the user how to launch a subagent-Report the registered subagents (Switch name + id; not the token) and-explain that each runs as its own session. To activate one:+Report the registered subagents (Switch name + id; not the token) and explain+that each runs as its own session:```cd <repo> && claude "connect to switch room <name>" \@@ -538,29 +817,78 @@ 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.--Switch also posts this exact command automatically whenever someone-addresses the subagent in a room while it has no live session (it's-generated from the subagent's recorded `subagent_name`), so the user-doesn't have to memorise it.--## Errors and safety--- If `SWITCH_REGISTRATION_TOKEN` is empty or whitespace, stop and tell- the user to open the Switch gateway's **API keys** tab and create or- copy a registration token. The skill can't proceed without it.-- If the server URL is unreachable, surface the curl error and stop —- most likely the server isn't running or the URL is wrong.-- If the bridge returns 401, the registration token is invalid or- expired — say so and stop.-- If the bridge returns 400 with a name validation error, the slug step- produced something that still doesn't match the regex (e.g. an empty- string after stripping). Show the error and re-ask.-- Never write the registration token to disk.-- Never write the API token anywhere other than the chosen settings file.+> 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.++Switch posts this exact command automatically whenever someone addresses the+subagent while it has no live session, so the user doesn't have to memorise it.++## What you get without Switch Console++Be straight with the user; do not imply parity.++**Works:** the full Switch tool surface (including `send_attachment` /+`download_attachment`), room participation, threads, tasks, roles, moderation,+tool mediation and event reporting via the plugin's hooks, and the offline run+command Switch posts. **Pushed inbound events also work** — unlike the Codex+connector — provided the session is launched with+`--dangerously-load-development-channels plugin:switch-connector@switch-plugins`+on an Anthropic-subscription install, which is what Step 5 was deciding.++**Does not work, or works differently:**++- **No auto-spawned sessions.** `auto_session` depends on Switch Console watching+ rooms; the user starts Claude Code themselves.+- **No `[Switch] …` injection into a running session.** Switch Console can push+ prompts into a live TUI; nothing does that here. Without the channels flag,+ treat the session as pull-based and call `read_context` to catch up.+- **No per-agent model or instruction overrides.** Those live in the+ configuration Switch Console writes.++## Troubleshooting++- **"no Switch identity" / tools present but unusable** — the runtime found no+ usable environment and no usable store entry. Check you started Claude Code+ from the directory holding `.switch/agents/`, and that the entry parses as JSON+ with an endpoint, token and agent id.+- **It reports an incomplete `SWITCH_*` environment** — something is setting some+ of the three. The exact wording varies by runtime version; what matters is that+ the environment is half-set. Almost always an `env` block in+ `.claude/settings.local.json` or `~/.claude/settings.json`, left by an older+ version of this skill or written by Switch Console. **This is the single most+ common way standalone breaks.** Remove every `SWITCH_*` key from both files and+ restart; the store supplies all three on its own. Check the shell too+ (`env | grep SWITCH`) — a Switch Console-spawned terminal exports them.+- **Startup refuses, naming several servers** — the store spans more than one+ Switch deployment. Keep only that server's agents in the directory — setting+ `SWITCH_API_ENDPOINT` alone half-sets the environment, which older runtimes+ refuse.+- **Tools refuse and name a list of agents** — several agents in one directory and+ no identity bound yet. Call `select_agent` with one of the names first.+- **Rooms work but nothing is mediated** — the hooks resolve credentials the same+ way the runtime does; if they cannot, they say so on stderr. Run with+ `SWITCH_HOOK_DEBUG=1` to see which source they found.+- **Every room action asks for approval** — Step 9 did not land. Check+ `permissions.allow` in `.claude/settings.local.json`.+- **Tools missing entirely** — the plugin is not installed or not enabled+ (`/plugin` lists what is), or its pinned runtime is too old to read the store.+ Restart Claude Code after any change.+- **It names a variable still written `${...}`** — a settings or wrapper script+ expanded some `SWITCH_*` values and not others. The runtime refuses that rather+ than filling the gap from disk, because a failed substitution and a deliberate+ omission would otherwise look identical. Fix the expansion, or unset the+ variable to use the store on purpose.+- **It names two files claiming one agent id** — a reconfigure left an old entry+ behind. Two entries mean two tokens and no way to tell which is current, so+ both the runtime and the hooks refuse. Delete the stale one.+- **`connection closed: initialize response`** — the runtime died before the+ handshake; the reason is in `~/.switch/sessions/<ppid>/startup-error.log`. Read+ it rather than guessing: the host reports every cause identically.+- **404 fetching the runtime** — the runtime is on the public npm registry, so+ this is a reachability problem (offline, proxy, or a registry override in an+ `.npmrc`), not an authentication one. `npm view @sandboxaq/switch-agent-runtime+ version` should print a version.diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex 924cc938c..4ea4f25d3 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -630,7 +630,11 @@ are moderation tools — use them when setting a room up, not in passing.that holds for the session.- **Governance is enforced.** Your local tool calls (Bash, Edit, Write, etc.)are submitted to Switch for mediation before execution. If Switch denies one you- will see the reason. Do not try to circumvent denials.+ will see the reason. Do not try to circumvent denials. The one case where it is+ not enforced announces itself: a `[switch_hook] … mediation and event reporting+ are NOT running` line on stderr means the hooks could not find this agent's+ credentials. Say so rather than carrying on as though you were governed — the+ line names the cause, and the `configure` skill fixes most of them.- **You are a participant, not the controller.** Other agents and humans arein the room. Read the conversation and contribute meaningfully.- **Confirm before creating rooms.** Room creation provisions a Matrix room and@@ -684,15 +688,20 @@ launched with its identity already set.## If `switch_unavailable` is your only toolSwitch could not start for this session — wrong or missing credentials, an-unreachable server, or agents here belonging to two different Switch servers.+unreachable server, agents here belonging to two different Switch servers, an+agent id naming no credential file, two files claiming one agent id, or a+`SWITCH_*` variable left as a literal `${...}` while the others expanded.Call it. Its answer is the actual reason. Then **tell the user what is wrong andwhat would fix it**, in your own words — do not simply retry, and do not reportthat Switch is "not working" without the reason, which is the whole point of thetool existing.-Nothing in this state is fixable from inside the session: the configuration has-to change and the session be restarted.+The session cannot repair itself — the configuration has to change and the+session be restarted. But you can do the changing: the connector ships a+`configure` skill, and several of these causes are exactly what it sets up. If+the reason points at missing or mismatched credentials, offer to run it, and say+the session will need restarting afterwards either way.## Tool indexdiff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.mdindex c748e898b..cb5793a78 100644--- a/connectors/codex-plugin/skills/switch/SKILL.md+++ b/connectors/codex-plugin/skills/switch/SKILL.md@@ -685,15 +685,20 @@ launched with its identity already set.## If `switch_unavailable` is your only toolSwitch could not start for this session — wrong or missing credentials, an-unreachable server, or agents here belonging to two different Switch servers.+unreachable server, agents here belonging to two different Switch servers, an+agent id naming no credential file, two files claiming one agent id, or a+`SWITCH_*` variable left as a literal `${...}` while the others expanded.Call it. Its answer is the actual reason. Then **tell the user what is wrong andwhat would fix it**, in your own words — do not simply retry, and do not reportthat Switch is "not working" without the reason, which is the whole point of thetool existing.-Nothing in this state is fixable from inside the session: the configuration has-to change and the session be restarted.+The session cannot repair itself — the configuration has to change and the+session be restarted. But you can do the changing: the connector ships a+`configure` skill, and several of these causes are exactly what it sets up. If+the reason points at missing or mismatched credentials, offer to run it, and say+the session will need restarting afterwards either way.## Tool indexdiff --git a/console/AGENTS.md b/console/AGENTS.mdindex a0b742882..ee686385c 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -428,14 +428,36 @@ pnpm run lintexport 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- `@sandboxaq/switch-agent-runtime` (which reads it directly when- nothing sets `SWITCH_*` in the environment). Changing the shape means- changing all three.+ containing `*`. For the agents **Switch Console** manages it also writes+ `.claude/settings.local.json` carrying the endpoint and agent id only — Claude+ Code's own file, read by every session in the directory, which 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.+ - **That write is Switch Console's alone.** The connector's `configure` skill+ deliberately writes no `SWITCH_*` into any settings file — a directory it+ sets up carries the store and nothing else, which is the resolution path that+ works on every runtime. Do not "restore" the env block there to match this+ layout; the skill strips it on sight.+ - **Where Switch Console does write it, Claude Code makes it live.** Its `env`+ block becomes real process environment for everything a session spawns, the+ Switch runtime and the connector's hooks included — so the agent id in it+ decides who a hand-started session is, and an id naming no entry under+ `.switch/agents/` fails every session in that directory rather than falling+ back. Keep the two in step; changing one means changing the other.+ - Four consumers read this layout: switchdash, the sidecar,+ `@sandboxaq/switch-agent-runtime`, and the Claude connector's+ `hooks/switch_hook.py`. The runtime and the hook read it whenever the+ environment does not already carry a complete identity — including when it+ carries a *partial* one, which is the ordinary case above. Changing the+ shape means changing all four.+ - The runtime and the hook are the same resolution written twice, in two+ languages, over the same directory. They must agree: where they don't, a+ session acts as one agent and is mediated as another, and nothing fails to+ say so. The hook keys on the agent id the session recorded when it joined a+ room — not on the settings file — so a directory holding several agents+ still resolves exactly. Change one and change the other, and keep the paired+ cases in `bin.handshake.test.ts` and `test_claude_connector_hook.py`+ matching.- 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 bydiff --git a/console/apps/switch-console-desktop/src/main/core/agents/detect.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/detect.test.tsindex f81ff586e..9d7164a85 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/detect.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/detect.test.ts@@ -10,6 +10,16 @@ async function writeSettings(dir: string, contents: string): Promise<void> {await fs.writeFile(path.join(claudeDir, 'settings.local.json'), contents, 'utf8');}+async function writeStoreEntry(+ dir: string,+ name: string,+ env: Record<string, string>+): Promise<void> {+ const storeDir = path.join(dir, '.switch', 'agents');+ await fs.mkdir(storeDir, { recursive: true });+ await fs.writeFile(path.join(storeDir, `${name}.json`), JSON.stringify({ env }), 'utf8');+}+describe('detectSwitchAgent', () => {let dir: string;@@ -87,4 +97,79 @@ describe('detectSwitchAgent', () => {);expect(await detectSwitchAgent(dir)).toBeNull();});++ it('finds an agent the configure skill set up, which writes no settings env', async () => {+ // The standalone path deliberately leaves `.claude/settings.local.json`+ // without a SWITCH_* block: a half-set environment is what breaks those+ // sessions. Reading the settings file alone made such a directory invisible.+ await writeStoreEntry(dir, 'claude-code.solo', {+ SWITCH_API_ENDPOINT: 'https://switch-api.example.ts.net',+ SWITCH_API_TOKEN: 'secret-token-should-not-leak',+ SWITCH_AGENT_ID: '4dc89d57-6a12-41c9-814e-946a78ea419c',+ });++ expect(await detectSwitchAgent(dir)).toEqual({+ agentId: '4dc89d57-6a12-41c9-814e-946a78ea419c',+ apiEndpoint: 'https://switch-api.example.ts.net',+ dir,+ });+ });++ it('prefers the settings file when both name an agent', async () => {+ // It is what Claude Code exports into the session, so it is what the+ // directory actually resolves as.+ await writeSettings(+ dir,+ JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://from-settings.example',+ SWITCH_AGENT_ID: 'id-settings',+ },+ })+ );+ await writeStoreEntry(dir, 'claude-code.solo', {+ SWITCH_API_ENDPOINT: 'https://from-store.example',+ SWITCH_API_TOKEN: 'tok',+ SWITCH_AGENT_ID: 'id-store',+ });++ expect(await detectSwitchAgent(dir)).toEqual({+ agentId: 'id-settings',+ apiEndpoint: 'https://from-settings.example',+ dir,+ });+ });++ it('names no agent when the store holds several', async () => {+ // Supported: the session picks one with `select_agent`. Nothing here can+ // make that choice, so it must not guess which agent the directory is.+ await writeStoreEntry(dir, 'one', {+ SWITCH_API_ENDPOINT: 'https://a.example',+ SWITCH_API_TOKEN: 'tok-a',+ SWITCH_AGENT_ID: 'id-a',+ });+ await writeStoreEntry(dir, 'two', {+ SWITCH_API_ENDPOINT: 'https://a.example',+ SWITCH_API_TOKEN: 'tok-b',+ SWITCH_AGENT_ID: 'id-b',+ });++ expect(await detectSwitchAgent(dir)).toBeNull();+ });++ it('ignores an unparseable store entry and still finds the good one', async () => {+ await fs.mkdir(path.join(dir, '.switch', 'agents'), { recursive: true });+ await fs.writeFile(path.join(dir, '.switch', 'agents', 'broken.json'), '{ nope', 'utf8');+ await writeStoreEntry(dir, 'good', {+ SWITCH_API_ENDPOINT: 'https://a.example',+ SWITCH_API_TOKEN: 'tok',+ SWITCH_AGENT_ID: 'id-good',+ });++ expect(await detectSwitchAgent(dir)).toEqual({+ agentId: 'id-good',+ apiEndpoint: 'https://a.example',+ dir,+ });+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/detect.ts b/console/apps/switch-console-desktop/src/main/core/agents/detect.tsindex bcbddf73a..ad25df37d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/detect.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/detect.ts@@ -2,7 +2,7 @@ import { promises as fs } from 'node:fs';import path from 'node:path';import { log } from '@main/lib/logger';import type { SwitchAgentConfig } from '@shared/switch-agents';-import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import { SWITCH_AGENTS_DIR_RELATIVE, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';interface ClaudeSettingsEnv {SWITCH_API_ENDPOINT?: unknown;@@ -50,23 +50,76 @@ export function parseSwitchAgentSettings(raw: string, dir: string): SwitchAgentC}/**- * Detect whether `dir` is configured as a Switch agent by reading its- * `.claude/settings.local.json` and extracting the `SWITCH_*` env block.+ * The identity in a credentials file, without its token.*- * Returns `null` when the directory has no settings file, the file is- * unparseable, or it lacks a usable `SWITCH_AGENT_ID` / `SWITCH_API_ENDPOINT`.- * Missing/unreadable files are normal (most directories are not agents) and are- * not logged; only a malformed settings file is surfaced as a warning.+ * `SWITCH_API_TOKEN` is in the file and is deliberately not read: recognising a+ * directory needs no secret, and keeping it unread is what makes detection a+ * non-destructive, credential-free operation.+ */+async function readStoreIdentity(dir: string): Promise<SwitchAgentConfig | null> {+ const storeDir = path.join(dir, SWITCH_AGENTS_DIR_RELATIVE);++ let entries: string[];+ try {+ entries = (await fs.readdir(storeDir)).filter((f) => f.endsWith('.json'));+ } catch {+ return null;+ }++ const found: SwitchAgentConfig[] = [];+ for (const entry of entries) {+ let raw: string;+ try {+ raw = await fs.readFile(path.join(storeDir, entry), 'utf8');+ } catch {+ continue;+ }+ let env: Record<string, unknown> | undefined;+ try {+ env = (JSON.parse(raw) as { env?: Record<string, unknown> })?.env;+ } catch {+ log.warn('switch-agents: unparseable credentials file', { dir, entry });+ continue;+ }+ const agentId = asNonEmptyString(env?.SWITCH_AGENT_ID);+ const apiEndpoint = asNonEmptyString(env?.SWITCH_API_ENDPOINT);+ if (agentId && apiEndpoint) found.push({ agentId, apiEndpoint, dir });+ }++ // Several agents in one directory is a supported setup — the session picks one+ // with `select_agent`. Nothing here can make that choice, so report no single+ // identity rather than guessing which one the directory "is".+ return found.length === 1 ? found[0] : null;+}++/**+ * Detect whether `dir` is configured as a Switch agent.+ *+ * Two layouts count, because two things configure a directory. Switch Console+ * writes the identity into `.claude/settings.local.json`; the connector's+ * `configure` skill deliberately writes no `SWITCH_*` there at all and leaves+ * only the credentials store, since a half-set environment is what breaks a+ * standalone session. Reading the settings file alone would make every+ * skill-configured directory invisible here.+ *+ * The settings file wins when both exist: it is what Claude Code exports into+ * the session, so it is what that directory actually resolves as.+ *+ * Returns `null` when neither names a usable `SWITCH_AGENT_ID` /+ * `SWITCH_API_ENDPOINT`, or when the store holds several agents and no single+ * identity can be named. Missing files are normal and are not logged; only a+ * malformed one is surfaced as a warning.*/export async function detectSwitchAgent(dir: string): Promise<SwitchAgentConfig | null> {const settingsPath = path.join(dir, SWITCH_SETTINGS_RELATIVE_PATH);- let raw: string;+ let raw: string | null = null;try {raw = await fs.readFile(settingsPath, 'utf8');} catch {- return null;+ raw = null;}- return parseSwitchAgentSettings(raw, dir);+ const fromSettings = raw === null ? null : parseSwitchAgentSettings(raw, dir);+ return fromSettings ?? (await readStoreIdentity(dir));}diff --git a/console/packages/switch-agent-runtime/src/bin.handshake.test.ts b/console/packages/switch-agent-runtime/src/bin.handshake.test.tsindex 27e695100..151962a86 100644--- a/console/packages/switch-agent-runtime/src/bin.handshake.test.ts+++ b/console/packages/switch-agent-runtime/src/bin.handshake.test.ts@@ -71,6 +71,27 @@ async function opsServer(): Promise<string> {return `http://127.0.0.1:${port}`;}+/**+ * An ops endpoint that remembers who asked.+ *+ * Which agent the runtime *bound* is only observable in the credentials it then+ * uses: the agent id is in the ops path and the token is in its Authorization+ * header. Asserting on those is what distinguishes "resolved the agent the+ * environment named" from "picked one and carried on".+ */+async function recordingOpsServer(): Promise<{ endpoint: string; calls: () => string[] }> {+ const calls: string[] = [];+ const server = http.createServer((req, res) => {+ calls.push(`${req.url} ${req.headers.authorization ?? ''}`);+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ operations: {} }));+ });+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as { port: number };+ return { endpoint: `http://127.0.0.1:${port}`, calls: () => calls };+}+/** An endpoint that accepts the connection and then never answers. */async function blackHoleServer(): Promise<string> {const server = http.createServer(() => {@@ -388,9 +409,48 @@ describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () =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.+ it('completes a token-less environment from the store rather than refusing', async () => {+ // The shape a host settings file produces: it names the agent and leaves the+ // credential on disk. Claude Code exports that block into this process, so+ // treating it as half a config stranded every hand-started session — the+ // exact case the store exists for.+ const { endpoint, calls } = await recordingOpsServer();+ const run = start({ SWITCH_API_ENDPOINT: endpoint, SWITCH_AGENT_ID: 'uuid-solo' }, (root) =>+ provision(root, { slug: 'solo', agentId: 'uuid-solo', endpoint, token: 'tok-solo' })+ );++ await handshake(run);+ const listed = (await request(run, 2, 'tools/list')) as {+ result?: { tools?: { name: string }[] };+ };++ expect((listed.result?.tools ?? []).map((t) => t.name)).not.toContain('switch_unavailable');+ // The store's token, against the id the environment named — on the ops call+ // and on everything that follows it.+ expect(calls()).toContain('/agents/uuid-solo/ops Bearer tok-solo');+ expect(+ calls().every((c) => c.startsWith('/agents/uuid-solo/') && c.endsWith('Bearer tok-solo'))+ ).toBe(true);+ });++ it('binds the agent the environment names, not whichever the store lists first', async () => {+ // With several provisioned, "it worked" is not evidence: the guarantee is+ // that the id in the environment decides, so the wrong pick must be visible.+ const { endpoint, calls } = await recordingOpsServer();+ const run = start({ SWITCH_AGENT_ID: 'uuid-b' }, (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);++ expect(calls()).toContain('/agents/uuid-b/ops Bearer tok-b');+ expect(calls().some((c) => c.includes('uuid-a') || c.includes('tok-a'))).toBe(false);+ });++ it('refuses when the environment names an agent the store does not hold', async () => {+ // Falling through to a general store search here would bind somebody else,+ // which is the failure the old blanket refusal was right to prevent.const endpoint = await opsServer();const run = start({ SWITCH_AGENT_ID: 'uuid-env' }, (root) =>provision(root, { slug: 'solo', agentId: 'uuid-solo', endpoint, token: 'tok-solo' })@@ -399,7 +459,126 @@ describe.skipIf(!existsSync(BIN))('the Switch runtime as a host spawns it', () =const { tools, text } = await degradedAnswer(run);expect(tools).toEqual(['switch_unavailable']);- expect(text).toContain('incomplete SWITCH_* environment');+ expect(text).toContain('uuid-env');+ expect(text).toContain('uuid-solo');+ });++ it('refuses when the named agent belongs to a different server', async () => {+ const endpoint = await opsServer();+ const run = start(+ { SWITCH_API_ENDPOINT: 'https://elsewhere.example', SWITCH_AGENT_ID: 'uuid-solo' },+ (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('elsewhere.example');+ });++ it('still refuses a token that names no agent', async () => {+ // Unchanged, and for the original reason: every request is addressed to an+ // agent id, and a bare token gives nothing to infer one from.+ const endpoint = await opsServer();+ const run = start({ SWITCH_API_ENDPOINT: endpoint, SWITCH_API_TOKEN: 'tok-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('agent_id=MISSING');+ });++ it('reports which piece is missing when a token comes without an endpoint', async () => {+ // The diagnostic has to name the variable actually absent. Saying "agent_id+ // is not set" while it plainly is sends the reader after the wrong thing.+ const endpoint = await opsServer();+ const run = start({ SWITCH_API_TOKEN: 'tok-env', 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('endpoint=MISSING');+ expect(text).toContain('agent_id=uuid-env');+ expect(text).not.toContain('agent_id=MISSING');+ });++ it('refuses when only some ${SWITCH_*} expanded, rather than filling the gap from disk', async () => {+ // A templating step that resolved two of three and left the token literal+ // meant to supply a credential and failed. Treating the literal as "absent"+ // would authenticate with whatever the store holds and never mention it.+ const endpoint = await opsServer();+ const run = start(+ {+ SWITCH_API_ENDPOINT: endpoint,+ SWITCH_AGENT_ID: 'uuid-solo',+ SWITCH_API_TOKEN: '${SWITCH_API_TOKEN}',+ },+ (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('SWITCH_API_TOKEN');+ });++ it('says the store was unreadable rather than empty when it is', async () => {+ // "Nothing provisioned" and "one entry that will not parse" need different+ // fixes, and reporting the second as the first sends the reader nowhere.+ const endpoint = await opsServer();+ const run = start({ SWITCH_API_ENDPOINT: endpoint, SWITCH_AGENT_ID: 'uuid-solo' }, (root) => {+ const dir = join(root, '.switch', 'agents');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'solo.json'), '{ not json');+ });++ const { tools, text } = await degradedAnswer(run);++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain('solo');+ expect(text).not.toContain('the store is empty');+ });++ it('lets an explicit endpoint break a tie between two entries sharing an id', async () => {+ const wanted = await recordingOpsServer();+ const other = await opsServer();+ const run = start(+ { SWITCH_API_ENDPOINT: wanted.endpoint, SWITCH_AGENT_ID: 'uuid-dup' },+ (root) => {+ provision(root, {+ slug: 'here',+ agentId: 'uuid-dup',+ endpoint: wanted.endpoint,+ token: 'tok-here',+ });+ provision(root, { slug: 'away', agentId: 'uuid-dup', endpoint: other, token: 'tok-away' });+ }+ );++ await handshake(run);++ expect(wanted.calls()).toContain('/agents/uuid-dup/ops Bearer tok-here');+ });++ it('refuses when two store entries claim the same agent id', async () => {+ // Two files, two tokens, nothing saying which is current. Taking the first+ // would leave the session working while the hook — which refuses on this+ // same condition — quietly stops mediating it.+ const endpoint = await opsServer();+ const run = start({ SWITCH_AGENT_ID: 'uuid-dup' }, (root) => {+ provision(root, { slug: 'a-first', agentId: 'uuid-dup', endpoint, token: 'tok-a' });+ provision(root, { slug: 'b-second', agentId: 'uuid-dup', endpoint, token: 'tok-b' });+ });++ const { tools, text } = await degradedAnswer(run);++ expect(tools).toEqual(['switch_unavailable']);+ expect(text).toContain('a-first.json');+ expect(text).toContain('b-second.json');});it(diff --git a/console/packages/switch-agent-runtime/src/bin.ts b/console/packages/switch-agent-runtime/src/bin.tsindex 03f1d5075..9460cf377 100644--- a/console/packages/switch-agent-runtime/src/bin.ts+++ b/console/packages/switch-agent-runtime/src/bin.ts@@ -21,12 +21,15 @@* from its own getppid(), so each session's hook reaches its own runtime* without any cross-session coordination.*- * Identity is resolved in two steps, environment first. Switch Console 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.+ * Identity is resolved from the environment and the local agent store together,+ * environment first. Switch Console puts all three `SWITCH_*` vars in a session+ * it launches itself, and that is taken whole. Short of that the environment is+ * read as a pointer rather than a credential: an agent id with no token names+ * the store entry to complete from disk, an endpoint narrows the store to one+ * server, and neither is guessed past — an id matching nothing still refuses.+ * The store is the working tree's `.switch/agents/`, one file per agent+ * carrying its own token, 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@@ -151,6 +154,28 @@ const ENV = {agentId: envValue(ENV_AGENT_ID),};+const ENV_RAW: [string, string][] = [+ ['SWITCH_API_ENDPOINT', ENV_ENDPOINT],+ ['SWITCH_API_TOKEN', ENV_TOKEN],+ ['SWITCH_AGENT_ID', ENV_AGENT_ID],+];++/**+ * Variables a host left as `${VAR}` while expanding others.+ *+ * All of them unexpanded is Claude Code's pre-expansion spawn, which is+ * ordinary and handled by treating the values as absent. *Some* of them is not:+ * it means a templating step ran and one substitution did not resolve. Left+ * alone that reads as "this variable was deliberately omitted", which for the+ * token means quietly authenticating with whatever the store holds instead of+ * the credential the environment was trying to supply.+ */+function partiallyUnresolved(): string[] {+ const unresolved = ENV_RAW.filter(([, raw]) => looksUnresolved(raw));+ const resolved = ENV_RAW.filter(([, raw]) => raw !== '' && !looksUnresolved(raw));+ return unresolved.length > 0 && resolved.length > 0 ? unresolved.map(([name]) => name) : [];+}+/*** Agents provisioned here when startup could not pick between them.*@@ -174,37 +199,99 @@ function bindIdentity(agent: { endpoint: string; token: string; agentId: string;/*** 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.+ * A complete environment wins unconditionally: switchdash launches the majority+ * of sessions and injects the identity it has already chosen for each one, and+ * that path predates the store.+ *+ * Short of that, the environment is read as a *pointer* rather than a+ * credential. An agent id with no token names an entry in the store to complete+ * from disk; an endpoint on its own narrows the store to one server. Only an+ * environment saying nothing at all leaves the choice entirely to the store.*/function resolveIdentity(): void {+ const stuck = partiallyUnresolved();+ if (stuck.length > 0) {+ return degrade(+ `${stuck.join(' and ')} ${stuck.length > 1 ? 'are' : 'is'} still a literal \${...} while other SWITCH_* variables expanded, so a substitution step did not finish\n` ++ `Resolving the rest from the agent store would authenticate as whatever is on disk and hide that, so this refuses instead.\n` ++ `Fix the expansion, or unset ${stuck.join(' and ')} to use the store deliberately.`+ );+ }+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) {+ // A token that names nobody is a broken config however the store looks, and+ // it is not completed from disk the way a bare agent id is: the missing piece+ // would be the endpoint, and inferring where to send a credential is a+ // different order of risk from inferring which credential to send.+ if (ENV.token) {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` ++ `incomplete SWITCH_* environment — a token was supplied, so all three are required\n` +` endpoint=${ENV.endpoint || 'MISSING'}\n` +- ` token=${ENV.token ? 'set' : 'MISSING'}\n` ++ ` token=set\n` +` agent_id=${ENV.agentId || 'MISSING'}\n` +- `Set the missing ones, or unset all three to use the local agent store instead.`+ `Set the missing one, or unset SWITCH_API_TOKEN to resolve against the agent store instead.`);}const store = readAgentStore(process.cwd());+ // An environment that names an agent but carries no token is not half a+ // config, it is a pointer: a host settings file that says which agent this+ // directory is while deliberately keeping the credential out of the working+ // tree. Claude Code exports such a block into this process, so refusing it+ // outright stranded exactly the sessions the store was built to serve.+ //+ // Completing it from disk keeps the guarantee the refusal was protecting.+ // The agent id makes the lookup exact — the entry it matches is the agent the+ // environment asked for, not one picked for it — so there is no way to end up+ // authenticated as somebody else. A miss stays fatal for that same reason:+ // falling through to a general store search could bind a different agent than+ // the one named, which is the failure the check exists to prevent.+ if (ENV.agentId) {+ const byId = store.agents.filter((a) => a.agentId === ENV.agentId);+ // An explicit endpoint narrows first, so it can break a tie rather than+ // only confirming or rejecting a choice already made.+ const claiming = ENV.endpoint+ ? byId.filter((a) => normalizeEndpoint(a.endpoint) === normalizeEndpoint(ENV.endpoint))+ : byId;++ // Two files still claiming one agent hold two tokens, and nothing in the+ // store says which is current. Refuse rather than take the first: the hook+ // that mediates this session's tool calls refuses on exactly this+ // condition, so binding here would produce a session that works while its+ // governance is silently switched off — the worst outcome available.+ if (claiming.length > 1) {+ return degrade(+ `SWITCH_AGENT_ID is ${ENV.agentId}, but ${claiming.length} entries in ${store.projectDir} claim it:\n` ++ claiming.map((a) => ` ${a.slug}.json`).join('\n') ++ `\nLeave exactly one of them, or set SWITCH_API_TOKEN to say which credential to use.`+ );+ }++ if (claiming.length === 1) {+ bindIdentity(claiming[0]);+ return;+ }++ // "No agents" and "agents that could not be read" need different fixes, so+ // the unusable entries are named rather than collapsed into "empty".+ const unusable = store.unusable.length+ ? `\nEntries found but unusable:\n${store.unusable.map((u) => ` ${u.slug}: ${u.reason}`).join('\n')}`+ : '';++ return degrade(+ `SWITCH_AGENT_ID is ${ENV.agentId} and SWITCH_API_TOKEN is not set, so the token has to come from ${store.projectDir} — and no agent there matches\n` ++ (byId.length > 0+ ? ` ${byId.map((a) => `${a.name} has that id but belongs to ${normalizeEndpoint(a.endpoint)}`).join('\n ')}, while SWITCH_API_ENDPOINT is ${normalizeEndpoint(ENV.endpoint)}\n`+ : ` ${store.agents.length === 0 ? 'no usable agent is provisioned there' : `known: ${store.agents.map((a) => `${a.name} (${a.agentId})`).join(', ')}`}\n`) ++ `Set SWITCH_API_TOKEN as well, or unset SWITCH_AGENT_ID to pick from the store, or run the connector's \`configure\` skill in this directory.${unusable}`+ );+ }+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')}`diff --git a/console/packages/switch-agent-runtime/src/credentials.test.ts b/console/packages/switch-agent-runtime/src/credentials.test.tsindex b0819988d..50b51eab8 100644--- a/console/packages/switch-agent-runtime/src/credentials.test.ts+++ b/console/packages/switch-agent-runtime/src/credentials.test.ts@@ -2,7 +2,12 @@ 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';+import {+ AGENTS_DIR_RELATIVE,+ distinctEndpoints,+ normalizeEndpoint,+ readAgentStore,+} from './credentials';const roots: string[] = [];@@ -141,3 +146,25 @@ describe('distinctEndpoints', () => {expect(distinctEndpoints(agents)).toEqual(['https://switch.example']);});});++describe('normalizeEndpoint', () => {+ it('folds the case of the parts that are defined to be case-insensitive', () => {+ // This gates whether an identity binds, not just how endpoints are grouped+ // for display, so a differently-cased host must not read as another server.+ expect(normalizeEndpoint('HTTPS://Switch.Example')).toBe('https://switch.example');+ expect(normalizeEndpoint('https://switch.example/')).toBe('https://switch.example');+ expect(normalizeEndpoint(' https://Switch.Example:8000/ ')).toBe(+ 'https://switch.example:8000'+ );+ });++ it('leaves the path alone, which is case-sensitive', () => {+ expect(normalizeEndpoint('https://Switch.Example/Api/V1')).toBe(+ 'https://switch.example/Api/V1'+ );+ });++ it('passes through a value with no authority to fold', () => {+ expect(normalizeEndpoint('localhost:8000')).toBe('localhost:8000');+ });+});diff --git a/console/packages/switch-agent-runtime/src/credentials.ts b/console/packages/switch-agent-runtime/src/credentials.tsindex 579d3860d..b94c1de06 100644--- a/console/packages/switch-agent-runtime/src/credentials.ts+++ b/console/packages/switch-agent-runtime/src/credentials.ts@@ -2,9 +2,11 @@* 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.+ * A session Switch Console launched gets all three `SWITCH_*` vars injected and+ * never reaches any of this. Everything else — a connector plugin installed by+ * hand, a Codex session started from a shell — needs the disk, either for the+ * whole identity or to complete an environment that names an agent without+ * carrying its token.** 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@@ -123,9 +125,21 @@ export function readAgentStore(projectDir: string): AgentStore {return { agents, unusable, projectDir: dir };}-/** Compare endpoints without tripping over a trailing slash. */+/**+ * Compare endpoints without tripping over a trailing slash or the casing of the+ * parts that are defined to be case-insensitive.+ *+ * Scheme and host fold; the path does not, because it is case-sensitive and+ * folding it would call two different resources the same. This decides whether+ * an identity binds, not just how endpoints are grouped for display, so a+ * cosmetic difference must not read as a different server.+ */export function normalizeEndpoint(endpoint: string): string {- return endpoint.trim().replace(/\/+$/, '');+ const trimmed = endpoint.trim().replace(/\/+$/, '');+ return trimmed.replace(+ /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#]*)/,+ (_all, scheme, authority) => `${scheme.toLowerCase()}${authority.toLowerCase()}`+ );}/** The distinct Switch endpoints a set of agents belongs to. */diff --git a/core/tests/test_claude_connector_hook.py b/core/tests/test_claude_connector_hook.pynew file mode 100644index 000000000..9762ff8e7--- /dev/null+++ b/core/tests/test_claude_connector_hook.py@@ -0,0 +1,510 @@+"""Tests for the Claude connector hook's credential resolution.++The hook authenticates to the agent bridge to mediate a session's tool calls, so+which agent it resolves has to be the same agent the Switch runtime bound. The+two are separate implementations in separate languages reading the same+directory, and they only stay in step deliberately — a divergence does not fail+anywhere, it just mediates the wrong agent, or stops mediating and says nothing.++The runtime's half of these cases lives in `bin.handshake.test.ts`; the shapes+asserted here are chosen to match it.+"""++from __future__ import annotations++import importlib.util+import json+import sys+from pathlib import Path+from types import ModuleType++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+HOOK_PATH = REPO_ROOT / "connectors/claude-code-plugin/hooks/switch_hook.py"++SWITCH_ENV_VARS = ("SWITCH_API_ENDPOINT", "SWITCH_API_TOKEN", "SWITCH_AGENT_ID")+++def load_hook(+ monkeypatch: pytest.MonkeyPatch, project_dir: Path, **env: str+) -> ModuleType:+ """Import the hook fresh, with a chosen environment and project directory.++ The hook reads its environment at module scope, which is what a real+ invocation does — it is a short-lived process, spawned per event. So each+ case needs its own import rather than a shared module whose constants were+ fixed by whichever test ran first.+ """+ for name in SWITCH_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(project_dir))+ # The hook reads the store from the working directory first, as the runtime+ # does. Without this the cases would resolve against whatever directory the+ # suite happens to be run from, and pass or fail on that.+ monkeypatch.chdir(project_dir)++ spec = importlib.util.spec_from_file_location("switch_hook_under_test", HOOK_PATH)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ # Registered so dataclass/typing machinery in the module resolves normally;+ # removed again so the next case gets a clean import.+ sys.modules["switch_hook_under_test"] = module+ try:+ spec.loader.exec_module(module)+ finally:+ sys.modules.pop("switch_hook_under_test", None)+ return module+++def provision(+ project_dir: Path,+ slug: str,+ *,+ agent_id: str,+ endpoint: str = "https://switch.example",+ token: str | None = "tok",+) -> None:+ """Write one store entry, in the shape Switch Console writes."""+ agents_dir = project_dir / ".switch" / "agents"+ agents_dir.mkdir(parents=True, exist_ok=True)+ env = {"SWITCH_API_ENDPOINT": endpoint, "SWITCH_AGENT_ID": agent_id}+ if token is not None:+ env["SWITCH_API_TOKEN"] = token+ (agents_dir / f"{slug}.json").write_text(json.dumps({"env": env}))+++def test_complete_environment_wins_over_the_store(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Switch Console injects an identity per session; it outranks the disk."""+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="https://env.example",+ SWITCH_API_TOKEN="tok-env",+ SWITCH_AGENT_ID="uuid-env",+ )++ assert hook._credentials("uuid-env") == ("https://env.example", "tok-env")+++def test_environment_without_an_agent_id_is_not_complete(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Must match the runtime, which requires all three before trusting the env.++ Short-circuiting on endpoint+token alone would mediate as whatever that token+ belongs to while the runtime refused the same environment outright.++ Nor may it fall through to the store. This test used to assert exactly that,+ under the heading of matching the runtime — but the runtime *refuses* a token+ that names nobody rather than completing it from disk, so resolving here+ meant mediating with a credential the session never bound while the session+ itself served nothing but `switch_unavailable`.+ """+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="https://switch.example",+ SWITCH_API_TOKEN="tok-env",+ )++ assert hook._credentials("uuid-solo") == ("", "")+++def test_single_store_entry_resolves_with_no_environment(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The standalone case: a hand-started session with only the store."""+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._configured() is True+ assert hook._credentials("") == ("https://switch.example", "tok-store")+++def test_several_agents_resolve_by_the_id_the_session_bound(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ provision(tmp_path, "alice", agent_id="uuid-a", token="tok-a")+ provision(tmp_path, "bob", agent_id="uuid-b", token="tok-b")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("uuid-b") == ("https://switch.example", "tok-b")+ assert hook._credentials("uuid-a") == ("https://switch.example", "tok-a")+++def test_several_agents_and_no_id_refuses(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Nothing names the agent, so any pick would be a guess at whose calls+ these are. The runtime leaves the identity unbound in the same situation."""+ provision(tmp_path, "alice", agent_id="uuid-a", token="tok-a")+ provision(tmp_path, "bob", agent_id="uuid-b", token="tok-b")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("") == ("", "")+++def test_duplicate_agent_id_refuses(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Two files, one id, two tokens, nothing saying which is current.++ The runtime refuses this too. It used to take the first by filename, which+ left the session working while its mediation quietly stopped.+ """+ provision(tmp_path, "a-first", agent_id="uuid-dup", token="tok-a")+ provision(tmp_path, "b-second", agent_id="uuid-dup", token="tok-b")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("uuid-dup") == ("", "")+++def test_unknown_agent_id_refuses(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("uuid-nobody") == ("", "")+++def test_endpoint_in_the_environment_narrows_the_store(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ provision(+ tmp_path,+ "here",+ agent_id="uuid-here",+ endpoint="https://a.example",+ token="tok-a",+ )+ provision(+ tmp_path,+ "away",+ agent_id="uuid-away",+ endpoint="https://b.example",+ token="tok-b",+ )+ hook = load_hook(monkeypatch, tmp_path, SWITCH_API_ENDPOINT="https://a.example")++ assert hook._credentials("") == ("https://a.example", "tok-a")+ # The named agent belongs to the other server: refuse rather than cross it.+ assert hook._credentials("uuid-away") == ("", "")+++def test_entries_missing_a_field_are_skipped_not_repaired(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A token-less entry is not a usable identity, and must not shadow one."""+ provision(tmp_path, "broken", agent_id="uuid-broken", token=None)+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(monkeypatch, tmp_path)++ assert [a["agent_id"] for a in hook._read_agent_store()] == ["uuid-solo"]+ assert hook._credentials("") == ("https://switch.example", "tok-store")+++def test_malformed_json_does_not_break_resolution(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ agents_dir = tmp_path / ".switch" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "junk.json").write_text("{not json")+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("") == ("https://switch.example", "tok-store")+++def test_flat_field_names_are_accepted(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The runtime accepts these too — they are the obvious hand-written shape."""+ agents_dir = tmp_path / ".switch" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "flat.json").write_text(+ json.dumps(+ {+ "endpoint": "https://switch.example",+ "token": "tok-flat",+ "agent_id": "uuid-flat",+ }+ )+ )+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._credentials("uuid-flat") == ("https://switch.example", "tok-flat")+++def test_unconfigured_directory_is_an_ordinary_answer(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A freshly installed plugin has no store and no environment; that is not an+ error, and the hook must not treat it as one."""+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._read_agent_store() == []+ assert hook._configured() is False+++def test_environment_naming_another_agent_does_not_lend_its_token(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The session bound agent A; the environment is complete for agent B.++ Reachable by resuming an old conversation under a reconfigured identity —+ the session state still names A. Using B's token against A's URL is the one+ thing taking `agent_id` as a parameter exists to prevent.+ """+ provision(tmp_path, "alice", agent_id="uuid-a", token="tok-a")+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="https://switch.example",+ SWITCH_API_TOKEN="tok-b",+ SWITCH_AGENT_ID="uuid-b",+ )++ # Resolves A from the store, never B's token.+ assert hook._credentials("uuid-a") == ("https://switch.example", "tok-a")+ # And refuses outright for an agent that is in neither.+ assert hook._credentials("uuid-c") == ("", "")+++def test_unexpanded_placeholders_are_not_credentials(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A host may spawn this before expanding its settings env block.++ Taken literally, `${SWITCH_API_ENDPOINT}` becomes the base of every URL the+ hook builds — so each call raises, gets swallowed, and mediation stops with+ no signal at all, which is the bug this fallback exists to remove.++ The runtime treats all-three-unexpanded the same way, in `resolveIdentity`.+ It has no test of its own for it — the runtime suite covers the handshake,+ not this — so do not read this docstring as evidence the pair is checked on+ both sides.+ """+ provision(tmp_path, "solo", agent_id="uuid-solo", token="tok-store")+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="${SWITCH_API_ENDPOINT}",+ SWITCH_API_TOKEN="${SWITCH_API_TOKEN}",+ SWITCH_AGENT_ID="${SWITCH_AGENT_ID}",+ )++ assert hook.API_ENDPOINT == ""+ assert hook._credentials("") == ("https://switch.example", "tok-store")+++def test_endpoint_breaks_a_tie_between_entries_sharing_an_id(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Matches the runtime, which narrows by endpoint before counting."""+ provision(+ tmp_path,+ "here",+ agent_id="uuid-dup",+ endpoint="https://a.example",+ token="tok-here",+ )+ provision(+ tmp_path,+ "away",+ agent_id="uuid-dup",+ endpoint="https://b.example",+ token="tok-away",+ )+ hook = load_hook(monkeypatch, tmp_path, SWITCH_API_ENDPOINT="https://a.example")++ assert hook._credentials("uuid-dup") == ("https://a.example", "tok-here")+++def test_endpoint_case_does_not_decide_whether_mediation_runs(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Scheme and host fold, exactly as `normalizeEndpoint` does in the runtime.++ The two readers must agree on this or the failure is invisible: the runtime+ folds, binds the agent and the session works, while the hook compares raw+ strings, matches nothing, and skips every mediation check. A session that+ runs ungoverned looks identical to one that is governed.+ """+ provision(+ tmp_path,+ "solo",+ agent_id="uuid-solo",+ endpoint="https://Switch.Example.COM",+ token="tok-solo",+ )+ hook = load_hook(+ monkeypatch, tmp_path, SWITCH_API_ENDPOINT="https://switch.example.com"+ )++ assert hook._credentials("uuid-solo") == ("https://switch.example.com", "tok-solo")+++def test_a_partly_expanded_environment_refuses_like_the_runtime(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Some `${...}` left literal while others expanded means a substitution did+ not finish. The runtime refuses rather than completing from disk; if the hook+ completed it anyway, the session would serve `switch_unavailable` while its+ tool calls were mediated with a token nobody chose.+ """+ provision(+ tmp_path,+ "solo",+ agent_id="uuid-solo",+ endpoint="https://switch.example",+ token="tok-store",+ )+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="https://switch.example",+ SWITCH_AGENT_ID="uuid-solo",+ SWITCH_API_TOKEN="${SWITCH_API_TOKEN}",+ )++ assert hook._credentials("uuid-solo") == ("", "")+++def test_all_three_unexpanded_is_the_ordinary_pre_expansion_spawn(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Not the partial case: nothing expanded, so nothing half-finished. The+ store is the deliberate answer here, as it is in the runtime."""+ provision(+ tmp_path,+ "solo",+ agent_id="uuid-solo",+ endpoint="https://switch.example",+ token="tok-store",+ )+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="${SWITCH_API_ENDPOINT}",+ SWITCH_AGENT_ID="${SWITCH_AGENT_ID}",+ SWITCH_API_TOKEN="${SWITCH_API_TOKEN}",+ )++ assert hook._credentials("uuid-solo") == ("https://switch.example", "tok-store")+++def test_a_token_without_the_others_refuses_instead_of_using_the_store(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The runtime refuses a token that names nobody. The hook must not quietly+ substitute a different credential from disk while the session is refusing to+ start — that is mediating as one agent while acting as none.+ """+ provision(+ tmp_path,+ "solo",+ agent_id="uuid-solo",+ endpoint="https://switch.example",+ token="tok-store",+ )+ hook = load_hook(+ monkeypatch,+ tmp_path,+ SWITCH_API_ENDPOINT="https://switch.example",+ SWITCH_API_TOKEN="tok-env",+ )++ assert hook._credentials("uuid-solo") == ("", "")+++def test_it_says_why_it_cannot_mediate(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ """The whole point of the fallback is that failure stops being silent, and+ each cause needs a different fix — so the reason has to be named, not just+ the fact."""+ provision(tmp_path, "a-first", agent_id="uuid-dup", token="tok-a")+ provision(tmp_path, "b-second", agent_id="uuid-dup", token="tok-b")+ hook = load_hook(monkeypatch, tmp_path)++ assert hook._has_credentials("uuid-dup") is False+ duplicate = capsys.readouterr().err+ assert "2 entries" in duplicate+ assert "NOT running" in duplicate++ assert hook._has_credentials("uuid-absent") is False+ assert "no entry for agent uuid-absent" in capsys.readouterr().err+++def test_handlers_do_nothing_when_credentials_cannot_be_resolved(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]+) -> None:+ """Covers the wiring, not just the resolver: a handler that skipped the+ check would try the call and swallow the failure silently."""+ plugin_data = tmp_path / "plugin-data"+ plugin_data.mkdir()+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(plugin_data))+ hook = load_hook(monkeypatch, tmp_path)+ (plugin_data / "session_s1.json").write_text(+ json.dumps({"room_id": "!room:switch.local", "agent_id": "uuid-nobody"})+ )++ event = {+ "hook_event_name": "PreToolUse",+ "tool_name": "Bash",+ "tool_input": {"command": "ls"},+ "session_id": "s1",+ }+ hook.handle_pre_tool_use(event)+ hook.handle_post_tool_use(+ {**event, "hook_event_name": "PostToolUse", "tool_response": {}}+ )++ captured = capsys.readouterr()+ # No verdict emitted on stdout — the tool proceeds unmediated — and the+ # reason is on stderr rather than nowhere.+ assert captured.out == ""+ assert "NOT running" in captured.err+++def test_reading_the_room_still_clears_the_unread_tally_without_credentials(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The reset goes to the local runtime, not to Switch, so it must not be+ gated on credentials the way mediation is.++ An agent whose mediation cannot run still reads its room; leaving the tally+ climbing would keep telling it it is behind when it is not.+ """+ plugin_data = tmp_path / "plugin-data"+ plugin_data.mkdir()+ monkeypatch.setenv("CLAUDE_PLUGIN_DATA", str(plugin_data))+ hook = load_hook(monkeypatch, tmp_path)+ (plugin_data / "session_s1.json").write_text(+ json.dumps({"room_id": "!room:switch.local", "agent_id": "uuid-nobody"})+ )++ notified: list[str] = []+ monkeypatch.setattr(+ hook, "_notify_channel", lambda path, body: notified.append(path)+ )++ hook.handle_post_tool_use(+ {+ "hook_event_name": "PostToolUse",+ "tool_name": "mcp__plugin_switch-connector_switch__read_context",+ "tool_input": {},+ "tool_response": {},+ "session_id": "s1",+ }+ )++ assert notified == ["/read-context"]diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.mdindex 544c2dcab..507e6917e 100644--- a/docs/api/AGENT_PROTOCOL.md+++ b/docs/api/AGENT_PROTOCOL.md@@ -702,7 +702,31 @@ server's registry **plus** three tools the runtime serves itself:directory names more than one agent. If the fetch fails the runtime does notrefuse to start — it **degrades**, serving a single `switch_unavailable` toolthat reports why. Dying before the MCP handshake left the session with no-explanation at all, which is worse than an honest one-tool surface.+explanation at all, which is worse than an honest one-tool surface. The same+degrade carries every identity failure below, for the same reason.++**Identity resolution reads the environment as a pointer, not only as a+credential.** All three of `SWITCH_API_ENDPOINT` / `SWITCH_API_TOKEN` /+`SWITCH_AGENT_ID` present is taken whole — that is what Switch Console injects+per session. Short of that, what is present narrows what is read from+`.switch/agents/`: an agent id with no token names the entry to take the token+from, and an endpoint on its own selects the server when the directory spans+more than one. Nothing is guessed past — an id matching no entry, two entries+claiming one id, and a token missing its endpoint or agent id all degrade rather+than resolve, because binding an identity nobody named is worse than not+starting.++That matters because a host settings file is a live part of the environment.+Switch Console writes `.claude/settings.local.json` for the agents it manages,+naming the directory's agent and deliberately keeping the token out, and Claude+Code exports that block into every process it spawns. Treating such an+environment as merely incomplete stranded any session started by hand in one of+those directories.++The connector's `configure` skill does **not** write that block — it writes the+agent store alone, so a directory it sets up presents no `SWITCH_*` at all and+takes the store path outright. The resolution above is what covers the Switch+Console-managed case; it is not how the standalone path is meant to work.Planned second mode off the same code: *daemon* (long-lived, `scope: all`,`spawn_capable`) alongside today's *session* mode (child of the agent,