Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(console): refuse a credentials file another install owns (CHOO-1960) (#217)
Christian McDermott906c9f9891b4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9ecdb0896..a8d1a5402 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -645,6 +645,21 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Fixed++- Two Switch Console installs sharing a host no longer destroy each other's+ agents. Per-agent credentials live at `.switch/agents/<name>.json`, keyed by+ name alone, and each install's uniqueness check only sees its own database —+ so an agent created with a name another install had already used in that+ directory overwrote its credentials file. Because the write merged into what+ was there, the result was one file carrying the new agent's identity and the+ old one's remaining keys: the displaced agent's sessions authenticated as the+ new agent rather than failing, and its API token, issued once, was gone.+ Creating, provisioning and renaming an agent now refuse a name whose+ credentials in that directory belong to a different Switch server, and say+ which one. Refusal happens before the identity is minted, so nothing is left+ stranded on the server.+### [0.27.1] - 2026-08-17#### Changed@@ -2046,6 +2061,15 @@ manifest history.### [Unreleased]+#### Fixed++- 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.+### [0.3.5] - 2026-08-15#### Changeddiff --git a/connectors/codex-plugin/skills/configure/SKILL.md b/connectors/codex-plugin/skills/configure/SKILL.mdindex 616883874..bc1b78117 100644--- a/connectors/codex-plugin/skills/configure/SKILL.md+++ b/connectors/codex-plugin/skills/configure/SKILL.md@@ -336,6 +336,23 @@ set -eumkdir -p .switch/agentsprintf '*\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)http_status=$(curl -s -o "$resp" -w '%{http_code}' -X POST "$ENDPOINT/agents/register-known" \-H "Authorization: Bearer $SWITCH_REGISTRATION_TOKEN" \@@ -359,8 +376,15 @@ 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 resulting-file is the same shape Switch Console writes:+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{diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex 72a3da4e7..012a03585 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -167,6 +167,33 @@ describe('addAgent', () => {expect(h.createAgent).not.toHaveBeenCalled();});+ it('refuses a name another Switch Console install already provisioned here, without minting an identity', async () => {+ // A second install has its own database, so `agentNameTaken` cannot see its+ // agent; the credentials file it left in the directory is the only trace.+ // Refusing after registration would be too late — this agent's token is+ // returned once, so it would already be lost (CHOO-1960).+ const theirs = JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://their-switch.example.com',+ SWITCH_API_TOKEN: 'their-token',+ SWITCH_AGENT_ID: 'their-agent',+ },+ });+ h.state.workspace = fakeFs({ [agentSettingsRelativePath('codex-hoot')]: theirs });++ const result = await addAgent(params());++ expect(result).toEqual({+ kind: 'credentials-conflict',+ endpoint: 'https://their-switch.example.com',+ });+ expect(h.registerAgentIdentity).not.toHaveBeenCalled();+ expect(h.createAgent).not.toHaveBeenCalled();+ expect(+ await (h.state.workspace as PluginFs).read(agentSettingsRelativePath('codex-hoot'))+ ).toBe(theirs);+ });+it('refuses a name already taken in the location, without minting an identity', async () => {// The gateway's 409 is scoped to the Switch server, so it cannot see a name// that is free there and taken in this directory — where both agents woulddiff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex 76d1cb775..2b599339d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts@@ -11,6 +11,7 @@ import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-conimport type { Agent } from '@shared/core/agents/agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { basenameFromAnyPath } from '@shared/path-name';+import { foreignCredentialsOwner } from './agent-credentials-slot';import { agentEvents } from './agent-events';import { agentNameTaken } from './agent-name-taken';import { resolveWorkspaceFsFor } from './agent-workspace-fs';@@ -54,6 +55,7 @@ export type AddAgentResult =| { kind: 'created'; agent: Agent }| { kind: 'unauthenticated' }| { kind: 'name-conflict' }+ | { kind: 'credentials-conflict'; endpoint: string }| { kind: 'invalid-name'; message: string }| { kind: 'error'; message: string };@@ -86,6 +88,20 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>return { kind: 'name-conflict' };}+ // And the check above only sees agents THIS install manages. A second Switch+ // Console on the same host, pointed at a different Switch server, has its own+ // database and its own agents in this same directory — so the only thing that+ // knows about its agent is the credentials file it left here (CHOO-1960).+ // Refuse before minting: the writer refuses too, but by then this agent's+ // token has been minted and is unrecoverable.+ const foreignEndpoint = await foreignCredentialsOwner(+ params.sshHost,+ params.dir,+ params.name,+ server.apiUrl+ );+ if (foreignEndpoint !== null) return { kind: 'credentials-conflict', endpoint: foreignEndpoint };+const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.tsnew file mode 100644index 000000000..1c66c3c23--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-credentials-slot.ts@@ -0,0 +1,30 @@+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { foreignCredentialsOwnerFs } from './write-switch-settings';++/**+ * The Switch deployment that already owns `.switch/agents/<slug>.json` in a+ * working directory, when that is a different deployment from `apiEndpoint` —+ * otherwise null.+ *+ * A create path calls this BEFORE minting an identity. The writer refuses the+ * same collision, but a refusal there comes after registration: the agent exists+ * on the server and its API key, returned once, is already lost. Checking first+ * turns that into a clean "pick another name" (CHOO-1960).+ *+ * Opens the working directory (local disk, or the repo dir over SFTP) for the+ * read alone and closes it again, so nothing is held across the registration+ * call that follows.+ */+export async function foreignCredentialsOwner(+ sshHost: string | null,+ dir: string,+ slug: string,+ apiEndpoint: string+): Promise<string | null> {+ const workspace = await resolveWorkspaceFsFor(sshHost, dir);+ try {+ return await foreignCredentialsOwnerFs(workspace.fs, slug, apiEndpoint);+ } finally {+ workspace.close();+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.tsindex cd9c403c1..4cfd9f92d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts@@ -1,6 +1,6 @@import type { KnownAgentType } from '@main/core/agents/known-agent-type';import { GatewayError, registerKnownAgent } from '@main/core/switch-servers/gateway-client';-import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';+import type { RegisterIdentityFailure } from '@shared/core/switch-servers/switch-servers';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';export type RegisterAgentInput = {@@ -34,10 +34,7 @@ export type RegisterAgentInput = {export async function registerAgentIdentity(server: SwitchServer,input: RegisterAgentInput-): Promise<- | { kind: 'created'; id: string; apiKey: string }- | Exclude<ProvisionAgentResult, { kind: 'created' }>-> {+): Promise<{ kind: 'created'; id: string; apiKey: string } | RegisterIdentityFailure> {try {const registered = await registerKnownAgent(server, {name: input.name,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.tsindex a9ac50e5e..e508b0524 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts@@ -198,6 +198,38 @@ describe('renameAgent', () => {expect(h.writeDefinition).not.toHaveBeenCalled();});+ it('refuses a name whose credentials belong to another Switch Console install', async () => {+ // `agentNameTaken` queries this install's database, so a second install's+ // agent in the same directory is invisible to it — and the move clobbers+ // rather than merges, so its token would simply be gone (CHOO-1960).+ const THEIRS = JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://their-switch.example.com',+ SWITCH_API_TOKEN: 'their-token',+ SWITCH_AGENT_ID: 'their-agent',+ },+ });+ const fs = fakeFs({+ [agentSettingsRelativePath('old-name')]: CREDS,+ [agentSettingsRelativePath('new-name')]: THEIRS,+ });+ h.state.fs = fs;++ const result = await renameAgent({ agentId: 'agent-1', newName: 'new-name' });++ expect(result).toEqual({+ success: false,+ error: {+ type: 'credentials-conflict',+ name: 'new-name',+ endpoint: 'https://their-switch.example.com',+ },+ });+ expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(THEIRS);+ expect(await fs.read(agentSettingsRelativePath('old-name'))).toBe(CREDS);+ expect(h.writeDefinition).not.toHaveBeenCalled();+ });+it('returns the renamed agent on success', async () => {h.state.fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });diff --git a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.tsindex a47ed4537..7c5bffa38 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts@@ -1,3 +1,4 @@+import type { PluginFs } from '@switch-console/core/agents/plugins';import { type Result, err, ok } from '@switch-console/shared';import { eq, sql } from 'drizzle-orm';import {@@ -5,6 +6,7 @@ import {killSidecarSession,} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import { getPlugin } from '@main/core/providers/plugin-registry';+import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';import { db } from '@main/db/client';import { agents } from '@main/db/schema';import { log } from '@main/lib/logger';@@ -19,6 +21,7 @@ import { ensureRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';import { agentSettingsRelativePath } from './switch-settings-paths';import { mapAgentRowToAgent } from './utils';+import { foreignCredentialsEndpoint } from './write-switch-settings';/*** Tear down the remote sidecar the agent ran under its previous name, then bring@@ -51,6 +54,59 @@ async function moveSidecarToNewName(previous: Agent, renamed: Agent): Promise<vo}}+/**+ * The Switch deployment that owns the credentials already sitting at the new+ * name, when it is a different one from the agent being renamed — otherwise+ * null. `credsRaw` is the agent's own credentials file, which names its server.+ *+ * A file with no readable credentials in it is not treated as an owner: the+ * rename merges nothing, and an unparseable leftover is not an identity anyone+ * is using.+ */+async function foreignCredentialsOwnerForMove(+ workspaceFs: PluginFs,+ credsRaw: string,+ to: string+): Promise<string | null> {+ const source = parseSwitchAgentCredentials(credsRaw, log);+ if (!source) return null;+ return foreignCredentialsEndpoint(+ await workspaceFs.read(agentSettingsRelativePath(to)),+ source.apiEndpoint+ );+}++/**+ * Check, before the rename is committed, whether the new name's credentials slot+ * in the agent's directory is already another Switch deployment's — a second+ * Switch Console install's agent, which `agentNameTaken` cannot see because it+ * queries this install's database (CHOO-1960).+ *+ * A directory that cannot be read yields null: nothing can be written there+ * either, so the move that follows fails in the log rather than overwriting+ * anything.+ */+async function foreignCredentialsAtNewName(agent: Agent, to: string): Promise<string | null> {+ if ((agent.name ?? agent.id) === to) return null;+ try {+ const location = await getAgentLocation(agent);+ const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ const creds = await ctx.fs.read(agentSettingsRelativePath(agent.name ?? agent.id));+ return creds === null ? null : await foreignCredentialsOwnerForMove(ctx.fs, creds, to);+ } finally {+ ctx.close();+ }+ } catch (error) {+ log.warn('renameAgent: could not check the new name for another install of Switch Console', {+ agentId: agent.id,+ to,+ error: String(error),+ });+ return null;+ }+}+/*** Move the agent's on-disk state to its new name.*@@ -79,7 +135,21 @@ async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<voconst ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {const creds = await ctx.fs.read(agentSettingsRelativePath(from));- if (creds !== null) await ctx.fs.write(agentSettingsRelativePath(to), creds);+ if (creds !== null) {+ // The destination slot is checked again here, after the pre-rename check+ // in `renameAgent`, because this is the write that would do the damage:+ // it clobbers rather than merges, so another install's token would be+ // gone with no trace. Throwing lands in the catch below, which leaves+ // the agent on its old name — recoverable — rather than destroying a+ // credential (CHOO-1960).+ const owner = await foreignCredentialsOwnerForMove(ctx.fs, creds, to);+ if (owner !== null) {+ throw new Error(+ `${agentSettingsRelativePath(to)} belongs to the Switch server at ${owner}; refusing to overwrite another install's credentials`+ );+ }+ await ctx.fs.write(agentSettingsRelativePath(to), creds);+ }const behavior = getPlugin(previous.providerId).behavior.repoAgents;const definition = behavior ? await behavior.readDefinition(ctx.fs, from) : null;@@ -108,7 +178,12 @@ async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<vo}}-export type RenameAgentError = { type: 'agent-not-found' } | { type: 'name-taken'; name: string };+export type RenameAgentError =+ | { type: 'agent-not-found' }+ | { type: 'name-taken'; name: string }+ /** The new name's credentials file in this directory is another Switch+ * deployment's — see {@link foreignCredentialsAtNewName}. Nothing was renamed. */+ | { type: 'credentials-conflict'; name: string; endpoint: string };/*** Rename an agent and move the on-disk state keyed by its old name.@@ -128,6 +203,15 @@ export async function renameAgent(return err({ type: 'name-taken', name: params.newName });}+ const foreignEndpoint = await foreignCredentialsAtNewName(previous, params.newName);+ if (foreignEndpoint !== null) {+ return err({+ type: 'credentials-conflict',+ name: params.newName,+ endpoint: foreignEndpoint,+ });+ }+const [row] = await db.update(agents).set({ name: params.newName, updatedAt: sql`CURRENT_TIMESTAMP` })diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.tsindex 3c41cb566..d3722681d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -10,6 +10,9 @@ import {SWITCH_SETTINGS_RELATIVE_PATH,} from './switch-settings-paths';import {+ ForeignAgentCredentialsError,+ foreignCredentialsEndpoint,+ foreignCredentialsOwnerFs,mergeSwitchApiEndpoint,mergeSwitchSettings,removeSwitchSettings,@@ -174,6 +177,106 @@ describe('writeNeutralAgentSettingsFs', () => {});});+describe('writeNeutralAgentSettingsFs, against another install of Switch Console', () => {+ const otherInstall = {+ env: {+ SWITCH_API_ENDPOINT: 'https://other-switch.example.com',+ SWITCH_API_TOKEN: 'their-token',+ SWITCH_AGENT_ID: 'their-agent',+ },+ };++ async function seed(slug: string, content: unknown): Promise<string> {+ const relPath = agentSettingsRelativePath(slug);+ await fs.mkdir(path.dirname(path.join(dir, relPath)), { recursive: true });+ await fs.writeFile(path.join(dir, relPath), JSON.stringify(content), 'utf8');+ return path.join(dir, relPath);+ }++ it('refuses a name whose credentials belong to a different Switch server, leaving them intact', async () => {+ const filePath = await seed('shared-name', otherInstall);++ await expect(+ writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'shared-name',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'our-token',+ agentId: 'our-agent',+ })+ ).rejects.toBeInstanceOf(ForeignAgentCredentialsError);++ // The victim's token is minted once and stored nowhere else, so "not+ // overwritten" is the whole point of the check.+ expect(JSON.parse(await fs.readFile(filePath, 'utf8'))).toEqual(otherInstall);+ });++ it('still rewrites its own agent when the server matches, trailing slash and all', async () => {+ await seed('ours', {+ env: {+ SWITCH_API_ENDPOINT: 'https://switch.example.com/',+ SWITCH_API_TOKEN: 'old-token',+ SWITCH_AGENT_ID: 'old-agent',+ },+ });++ await writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'ours',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'new-token',+ agentId: 'new-agent',+ });++ const raw = await fs.readFile(path.join(dir, agentSettingsRelativePath('ours')), 'utf8');+ expect((JSON.parse(raw) as { env: Record<string, string> }).env).toEqual({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'new-token',+ SWITCH_AGENT_ID: 'new-agent',+ });+ });++ it('reports the owning server through foreignCredentialsOwnerFs, for a caller checking before it registers', async () => {+ await seed('shared-name', otherInstall);+ const workspaceFs = createPluginFs(dir);++ expect(+ await foreignCredentialsOwnerFs(workspaceFs, 'shared-name', 'https://switch.example.com')+ ).toBe('https://other-switch.example.com');+ expect(+ await foreignCredentialsOwnerFs(+ workspaceFs,+ 'shared-name',+ 'https://other-switch.example.com'+ )+ ).toBeNull();+ expect(await foreignCredentialsOwnerFs(workspaceFs, 'absent', 'https://switch.example.com')) //+ .toBeNull();+ });+});++describe('foreignCredentialsEndpoint', () => {+ const ours = 'https://switch.example.com';++ it('names the other server only when the file actually belongs to one', () => {+ const withEndpoint = (endpoint: string) =>+ JSON.stringify({ env: { SWITCH_API_ENDPOINT: endpoint } });++ expect(foreignCredentialsEndpoint(withEndpoint('https://other.example.com'), ours)).toBe(+ 'https://other.example.com'+ );+ expect(foreignCredentialsEndpoint(withEndpoint(`${ours}//`), ours)).toBeNull();+ expect(foreignCredentialsEndpoint(null, ours)).toBeNull();+ });++ it('treats a file that names no Switch server as free, however malformed', () => {+ // Nothing here identifies an agent, so there is no identity to destroy — the+ // writer's existing merge-or-replace behaviour is right for all of them.+ expect(foreignCredentialsEndpoint('{not json', ours)).toBeNull();+ expect(foreignCredentialsEndpoint('[]', ours)).toBeNull();+ expect(foreignCredentialsEndpoint('{"env":{}}', ours)).toBeNull();+ expect(foreignCredentialsEndpoint('{"env":{"SWITCH_API_ENDPOINT":" "}}', ours)).toBeNull();+ });+});+describe('writeAgentNeutralSettings', () => {it('produces the same file as the PluginFs writer, for a plain directory path', async () => {await writeAgentNeutralSettings({diff --git a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.tsindex 3de284c16..3ca57d23c 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/write-switch-settings.ts@@ -6,6 +6,7 @@ import {} from '@switch-console/core/agents/plugins';import type { PluginFs } from '@switch-console/core/agents/plugins';import { createPluginFs } from '@main/core/providers/plugin-fs';+import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';import {agentSettingsRelativePath,SWITCH_AGENTS_GITIGNORE_RELATIVE,@@ -296,6 +297,92 @@ export async function writeAgentNeutralSettings(await writeNeutralAgentSettingsFs(createPluginFs(params.dir), params);}+/**+ * The Switch deployment an existing per-agent credentials file belongs to, when+ * that is a DIFFERENT deployment from the one about to be written — otherwise+ * null (no file, not a provisioned agent, or the same deployment).+ *+ * The endpoint is the discriminator because the gateway's name check is global+ * per deployment: two Switch Console installs can only mint the same agent name+ * when they point at different servers, and every credentials file already+ * carries its endpoint. Same server, same name is this install rewriting its own+ * agent (or replacing one deleted on the server) and is left alone.+ *+ * Compared with {@link sameApiEndpoint}, the same match the import path uses to+ * decide which server a discovered agent belongs to — the two have to agree, or+ * an agent that cannot be imported here could still be overwritten here.+ *+ * Pure: takes the existing file text (or null when absent/unreadable).+ */+export function foreignCredentialsEndpoint(+ existingRaw: string | null,+ apiEndpoint: string+): string | null {+ if (existingRaw === null) return null;++ let parsed: unknown;+ try {+ parsed = JSON.parse(existingRaw);+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;++ const env = (parsed as Record<string, unknown>).env;+ if (!env || typeof env !== 'object' || Array.isArray(env)) return null;++ const existingEndpoint = (env as Record<string, unknown>).SWITCH_API_ENDPOINT;+ if (typeof existingEndpoint !== 'string' || existingEndpoint.trim() === '') return null;++ return sameApiEndpoint(existingEndpoint, apiEndpoint) ? null : existingEndpoint;+}++/**+ * The credentials file for this agent name is already another Switch+ * deployment's. Writing would merge this install's identity over it, leaving one+ * file that carries the new identity and the old file's other keys — so the+ * displaced agent's sessions authenticate as this one instead of failing, and+ * its API token, minted once, is gone.+ */+export class ForeignAgentCredentialsError extends Error {+ readonly slug: string;+ readonly relPath: string;+ readonly existingEndpoint: string;+ readonly incomingEndpoint: string;++ constructor(params: {+ slug: string;+ relPath: string;+ existingEndpoint: string;+ incomingEndpoint: string;+ }) {+ super(+ `${params.relPath} in this directory belongs to the Switch server at ${params.existingEndpoint}, but this agent is on ${params.incomingEndpoint}. Writing it would overwrite that agent's identity and destroy its API token, which cannot be recovered. Use a different agent name, or a different working directory.`+ );+ this.name = 'ForeignAgentCredentialsError';+ this.slug = params.slug;+ this.relPath = params.relPath;+ this.existingEndpoint = params.existingEndpoint;+ this.incomingEndpoint = params.incomingEndpoint;+ }+}++/**+ * Read the per-agent credentials slot for `slug` and report the Switch+ * deployment it already belongs to, when that is a different one. Callers use+ * this BEFORE minting an identity, so a collision is refused without leaving an+ * orphaned agent (and an unrecoverable token) behind on the server; the writer+ * below re-checks, so a path that skips this one still cannot clobber.+ */+export async function foreignCredentialsOwnerFs(+ workspaceFs: PluginFs,+ slug: string,+ apiEndpoint: string+): Promise<string | null> {+ const existingRaw = await workspaceFs.read(agentSettingsRelativePath(slug));+ return foreignCredentialsEndpoint(existingRaw, apiEndpoint);+}+/*** Write an agent's provider-neutral per-agent Switch credentials over a* {@link PluginFs} (local disk or a remote repo dir via SFTP), keyed by `slug`@@ -304,17 +391,33 @@ export async function writeAgentNeutralSettings(* provider and every transport; providers with repo-agent definitions (Claude)* layer their definition on top.*- * The `.gitignore` is written first: it is what keeps `SWITCH_API_TOKEN` out of- * version control, so it must already be in place before the token reaches disk.+ * Being the single writer is what makes it the place to refuse a slot that is+ * another deployment's: every create path funnels through here, so none of them+ * can overwrite one (CHOO-1960). It throws {@link ForeignAgentCredentialsError}+ * rather than writing.+ *+ * The `.gitignore` is written before the credentials: it is what keeps+ * `SWITCH_API_TOKEN` out of version control, so it must already be in place+ * before the token reaches disk.*/export async function writeNeutralAgentSettingsFs(workspaceFs: PluginFs,params: { slug: string } & SwitchSettingsCredentials): Promise<void> {+ const relPath = agentSettingsRelativePath(params.slug);+ const existingRaw = await workspaceFs.read(relPath);+ const existingEndpoint = foreignCredentialsEndpoint(existingRaw, params.apiEndpoint);+ if (existingEndpoint !== null) {+ throw new ForeignAgentCredentialsError({+ slug: params.slug,+ relPath,+ existingEndpoint,+ incomingEndpoint: params.apiEndpoint,+ });+ }+if (!(await workspaceFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}- const relPath = agentSettingsRelativePath(params.slug);- const merged = mergeAgentCredentials(await workspaceFs.read(relPath), params);- await workspaceFs.write(relPath, merged);+ await workspaceFs.write(relPath, mergeAgentCredentials(existingRaw, params));}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.tsindex f7e3a0a13..75c4a9785 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -1,4 +1,5 @@import type { Result } from '@switch-console/shared';+import { foreignCredentialsOwner } from '@main/core/agents/agent-credentials-slot';import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';import { resolveWorkspaceFsFor } from '@main/core/agents/agent-workspace-fs';import { knownAgentTypeForProvider } from '@main/core/agents/known-agent-type';@@ -473,6 +474,9 @@ export const switchServersController = createRPCController({provisionAgent: async (params: ProvisionAgentParams): Promise<ProvisionAgentResult> => {const server = await requireServer(params.serverId);+ const conflict = await foreignCredentialsOwner(null, params.dir, params.name, server.apiUrl);+ if (conflict !== null) return { kind: 'credentials-conflict', endpoint: conflict };+const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,@@ -521,6 +525,14 @@ export const switchServersController = createRPCController({): Promise<ProvisionAgentResult> => {const server = await requireServer(params.serverId);+ const conflict = await foreignCredentialsOwner(+ params.sshHost,+ params.remoteRepoDir,+ params.name,+ server.apiUrl+ );+ if (conflict !== null) return { kind: 'credentials-conflict', endpoint: conflict };+const registered = await registerAgentIdentity(server, {name: params.name,description: params.description,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex f1d1e92d0..e8ee337d5 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -241,6 +241,14 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoc});return;}+ if (result.kind === 'credentials-conflict') {+ toast({+ title: 'That name belongs to another Switch server here',+ description: `This directory already holds credentials for an agent of that name on ${result.endpoint}. Overwriting them would destroy that agent's API token, so nothing was created — pick another name, or a different directory.`,+ variant: 'destructive',+ });+ return;+ }if (result.kind === 'invalid-name') {toast({ title: 'Invalid agent name', description: result.message, variant: 'destructive' });return;diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex c7829d73f..c334f1599 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -684,13 +684,26 @@ export type ProvisionRemoteAgentParams = {* message the modal can act on (re-login, rename) rather than a raw throw. The* minted API token is written to disk by the main process and never returned.*/-export type ProvisionAgentResult =- | { kind: 'created'; agentId: string }+/**+ * The recoverable ways minting an identity on the gateway can fail. Separate+ * from {@link ProvisionAgentResult} because provisioning can also fail for+ * reasons the gateway never sees — the working directory, so far — and a caller+ * handling a registration result should not have to consider those.+ */+export type RegisterIdentityFailure =| { kind: 'unauthenticated' }| { kind: 'name-conflict' }| { kind: 'invalid-name'; message: string }| { kind: 'error'; message: string };+export type ProvisionAgentResult =+ | { kind: 'created'; agentId: string }+ /** The working directory already holds credentials for this name belonging to+ * the Switch deployment at `endpoint` — another install's agent. Refused+ * before minting, so nothing was created. */+ | { kind: 'credentials-conflict'; endpoint: string }+ | RegisterIdentityFailure;+/*** Parameters for creating a room on a server from inside Switch Console* (CHOO-1875) — the minimal set that gets a user to a working room. The wider