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): make the agent config file the only record of an agent's settings (#563)
Louis Amaudruzd3a7f5140c12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ab1b18018..9ddc3248e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1345,6 +1345,19 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Fixed+- **An agent's instructions and settings can no longer be blanked or reverted+ by the Console itself.** The agent's config file (`.switch/config/<name>.json`)+ is now the only record: opening an agent's page never writes anything, Claude+ Code sessions get their agent definition from the config file directly instead+ of from `.claude/agents/<name>.md`, and that file is no longer written or read+ back. A missing config file is reported as an error rather than treated as an+ agent with no instructions. A one-time migration gives every existing agent a+ config file, taking over its description and any hand edits from the old+ definition file; attaching to an agent, or adopting a subagent, creates one+ when it is missing. Deleting an agent's provisioned files now removes its+ config file too, so an agent re-created under the same name starts clean.+### [0.37.0] - 2026-09-25#### Added@@ -3068,6 +3081,11 @@ published on its own.### [Unreleased]+#### Changed+- Claude Code sessions accept their agent definition in the launch spec and pass+ it to the SDK, rather than reading `.claude/agents/<name>.md` on the host.+ Sessions saved by an earlier Console, which name the file, still relaunch.+### [1.9.10] - 2026-09-25#### Changeddiff --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 d8fb24b63..444714b29 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@@ -197,15 +197,16 @@ describe('addAgent', () => {expect(await fs.read('.claude/agents/codex-hoot.md')).toBeNull();});- it('writes both credentials and an on-disk definition for a repo-agents provider', async () => {+ it('writes credentials and a config file, and no provider definition', async () => {const fs = h.state.workspace as PluginFs;await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));expect((await credsOf(fs, 'cc-hoot')).SWITCH_API_TOKEN).toBe('tok-123');- const definition = await fs.read('.claude/agents/cc-hoot.md');- expect(definition).toContain('name: cc-hoot');- expect(definition).toContain('description: Codex running in repo');+ const config = JSON.parse((await fs.read('.switch/config/cc-hoot.json')) ?? '{}');+ expect(config.description).toBe('Codex running in repo');+ // Launch builds the definition from the config file; nothing reads this.+ expect(await fs.read('.claude/agents/cc-hoot.md')).toBeNull();});it('records the agent’s instructions in its committed config file', async () => {@@ -215,8 +216,22 @@ describe('addAgent', () => {const config = JSON.parse((await fs.read('.switch/config/cc-hoot.json')) ?? '{}');expect(config.instructions).toBe('Be careful.');- // And it reaches the provider's own file, which is what actually runs.- expect(await fs.read('.claude/agents/cc-hoot.md')).toContain('Be careful.');+ });++ it('starts from what it was created with, whatever an earlier agent left behind', async () => {+ // A leftover definition under the same name used to be taken as a hand+ // edit, replacing everything typed into the form.+ const fs = h.state.workspace as PluginFs;+ await fs.write(+ '.claude/agents/cc-hoot.md',+ '---\nname: cc-hoot\ndescription: Old\n---\n\nOld instructions.\n'+ );++ await addAgent(params({ providerId: 'claude', name: 'cc-hoot', instructions: 'New.' }));++ const config = JSON.parse((await fs.read('.switch/config/cc-hoot.json')) ?? '{}');+ expect(config.instructions).toBe('New.');+ expect(config.description).toBe('Codex running in repo');});it('git-ignores the credentials directory so the token never enters VCS', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex 81c4eed19..9ba1d1f1a 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@@ -27,12 +27,12 @@ import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { basenameFromAnyPath } from '@shared/path-name';import { writeAgentConfigFile } from './agent-config-file';import type { AgentTemplateOrigin } from './agent-config-file';-import { syncAgentConfig } from './agent-config-sync';import { foreignCredentialsOwner, sameEndpointAgentId } from './agent-credentials-slot';import { agentEvents } from './agent-events';import { agentNameTaken } from './agent-name-taken';import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';+import { acknowledgeDefinition } from './import-agent-config';import { knownAgentTypeForProvider } from './known-agent-type';import { registerAgentIdentity } from './register-agent-identity';import { inspectRemoteDir } from './remote-dir';@@ -135,11 +135,11 @@ function reportFailedCreate(params: AddAgentParams, result: AddAgentResult): Add/*** Add a new agent to a location: mint its Switch identity on the gateway, write- * its provider definition (`.claude/agents/<name>.md`) and its per-agent Switch- * credentials (`.switch/agents/<name>.json`, keyed by name), then create the- * agent row. Every Switch Console-managed agent is a flat, repository-defined agent- * — for a provider that supports definitions it launches as `--agent <name>`- * with its own identity; there is no "main" agent and no parent (CHOO-1440).+ * its config file (`.switch/config/<name>.json`) and its per-agent Switch+ * credentials (`.switch/agents/<name>.json`), both keyed by name, then create the+ * agent row. Every Switch Console-managed agent is a flat, named agent — for a+ * provider that supports definitions each session runs as `<name>` with its own+ * identity; there is no "main" agent and no parent (CHOO-1440).** Works for local and remote (SSH) run locations. The minted API token is* written to disk and never returned. A recoverable gateway failure is mapped to@@ -267,14 +267,12 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {});if (registered.kind !== 'created') return reportFailedCreate(params, registered);- const behavior = getPlugin(params.providerId).behavior.repoAgents;const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {// Writing the per-agent Switch credentials is unconditional core behavior for// every provider, keyed by the agent's `name` — the single key-space every// reader (launch path, auto-session watcher, notification poller) uses- // (CHOO-1440). Providers with repo-agent definitions (Claude) layer their- // on-disk definition on top; that's the only provider-specific extra.+ // (CHOO-1440).await writeNeutralAgentSettingsFs(workspace.fs, {slug: params.name,apiEndpoint: server.apiUrl,@@ -282,19 +280,25 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {agentId: registered.id,expectedAgentId: slotAgentId ?? undefined,});- // The config file is the agent's configuration; the provider's own file is- // generated from it, here and on every later edit.- await writeAgentConfigFile(workspace.fs, params.name, {- instructions: params.instructions,- settings: params.definitionAttributes,- ...(params.templateOrigin ? { template: params.templateOrigin } : {}),- });- await syncAgentConfig({- workspaceFs: workspace.fs,- repoAgents: behavior ?? null,- name: params.name,- description: params.description,- });+ // The config file is the agent's whole configuration: each launch builds+ // what the provider needs from it. A definition an earlier agent of this+ // name left behind is recorded as accounted for, so nothing takes it for an+ // edit to this one.+ await writeAgentConfigFile(+ workspace.fs,+ params.name,+ await acknowledgeDefinition({+ workspaceFs: workspace.fs,+ repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,+ name: params.name,+ config: {+ description: params.description,+ instructions: params.instructions,+ settings: params.definitionAttributes,+ ...(params.templateOrigin ? { template: params.templateOrigin } : {}),+ },+ })+ );} finally {workspace.close();}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.tsindex a55b21458..11b98cecc 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts@@ -10,12 +10,10 @@ import { getAgentById } from './getAgentById';* without the caller knowing where the provider keeps it.** All of it is stored in one place — the agent's committed config file — and- * rendered from there into whatever the provider actually reads: a repo-agent- * definition on disk (Claude Code: `.claude/agents/<name>.md`), or a launch- * profile built at spawn (Codex: `~/.codex/<name>.config.toml`). Which of those- * a provider uses still matters to the caller, because only the second is read- * once at spawn and so cannot reach a running session, but it is no longer- * where the values live.+ * turned into whatever the provider takes when a session launches: the agent+ * definition the session runs as (Claude Code), or a launch profile (Codex:+ * `~/.codex/<name>.config.toml`). Either way a change reaches the next session,+ * not one already running.** A provider with neither has no advanced configuration and the section renders* nothing.diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.tsindex 4c3b06e1d..5d2b636ae 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts@@ -17,14 +17,16 @@ import { agentConfigRelativePath } from './switch-settings-paths';* explicitly would freeze today's defaults into every user's repository and* make a later change to them invisible.*- * This is the source of truth for an agent's configuration. Each provider's- * own file — a Claude Code subagent definition, a Codex profile, an OpenCode- * config — is generated from it, so those are outputs rather than places to- * edit. The one exception is deliberate: a hand-edited Claude Code definition- * is read back in rather than overwritten, which `rendered` below is what- * makes decidable.+ * This is the source of truth for an agent's configuration, and the only one:+ * each launch builds what its provider needs from this file directly, so+ * nothing else on disk is generated from it or read back into it.*/export type AgentConfigFile = {+ /**+ * What the agent is for, in one line. Claude Code carries it in the agent+ * definition it runs as. Absent when none is set.+ */+ description?: string;/** The agent's provider-agnostic system prompt. Absent when none is set. */instructions?: string;/**@@ -36,15 +38,15 @@ export type AgentConfigFile = {*/settings?: RepoAgentAttributes;/**- * Fingerprint of the provider artifact as this app last generated it, keyed- * by the artifact's path relative to the working directory.+ * Fingerprint of each provider definition this config already accounts for —+ * as an earlier version of this app generated it, or as it was when its+ * contents were taken over — keyed by the file's path relative to the working+ * directory.*- * This is what makes the round trip decidable. Comparing an artifact to what- * the config would generate right now cannot distinguish "the config- * changed" from "someone edited the file"; comparing it to what was last- * written can. A match means the file is untouched and the config should be- * written out; a mismatch means it was hand-edited and those edits should be- * read back in.+ * This version no longer reads or writes those files. The fingerprints are+ * kept for the import (to tell a hand edit from a file left as generated) and+ * for an older Switch Console sharing the directory, which reconciles the two+ * on every read and would otherwise take a stale definition for a hand edit.*/rendered?: Record<string, string>;/**@@ -93,6 +95,7 @@ export function parseAgentConfigFile(raw: string): AgentConfigFile {const record = parsed as Record<string, unknown>;const config: AgentConfigFile = {};+ if (typeof record.description === 'string') config.description = record.description;if (typeof record.instructions === 'string') config.instructions = record.instructions;if (isPlainObject(record.settings)) config.settings = record.settings as RepoAgentAttributes;const template = parseTemplateOrigin(record.template);@@ -123,11 +126,16 @@ export function serialiseAgentConfigFile(unknownKeys: Record<string, unknown> = {}): string {const out: Record<string, unknown> = { ...unknownKeys };+ delete out.description;delete out.instructions;delete out.settings;delete out.rendered;delete out.template;+ if (config.description !== undefined && config.description !== '') {+ out.description = config.description;+ }+// Blank is how the owner says "none", and none is the absent state — the// value itself is written exactly as given, never trimmed, because trimming// would quietly reshape a system prompt whose whitespace is deliberate.diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.tsdeleted file mode 100644index 8066db2c1..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import { promises as fs } from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { createPluginFs } from '@main/core/providers/plugin-fs';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { readAgentConfigFile, writeAgentConfigFile } from './agent-config-file';-import { syncAgentConfig } from './agent-config-sync';--let dir: string;--beforeEach(async () => {- dir = await fs.mkdtemp(path.join(os.tmpdir(), 'switch-console-config-sync-'));-});--afterEach(async () => {- await fs.rm(dir, { recursive: true, force: true });-});--const NAME = 'reviewer';-const DESCRIPTION = 'Reviews diffs';-const DEF_PATH = '.claude/agents/reviewer.md';--const claudeRepoAgents = getPlugin('claude').behavior.repoAgents ?? null;--function sync(pluginFs = createPluginFs(dir)) {- return syncAgentConfig({- workspaceFs: pluginFs,- repoAgents: claudeRepoAgents,- name: NAME,- description: DESCRIPTION,- });-}--async function readDefinition(): Promise<string> {- return fs.readFile(path.join(dir, DEF_PATH), 'utf8');-}--describe('syncAgentConfig', () => {- it('does nothing for a provider whose files are rebuilt at launch', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, { instructions: 'be terse' });-- const result = await syncAgentConfig({- workspaceFs: pluginFs,- repoAgents: null,- name: NAME,- description: DESCRIPTION,- });-- expect(result.action).toBe('not-applicable');- expect(result.config.instructions).toBe('be terse');- });-- it('generates the definition from the config', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, {- instructions: 'Be careful.',- settings: { model: 'opus' },- });-- const result = await sync(pluginFs);-- expect(result.action).toBe('written');- const definition = await readDefinition();- expect(definition).toContain('model: opus');- expect(definition).toContain('Be careful.');- });-- it('reports in-sync on a second run, rather than rewriting', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Be careful.' });- await sync(pluginFs);-- expect((await sync(pluginFs)).action).toBe('in-sync');- });-- it('regenerates when the config changed and nobody touched the definition', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, { instructions: 'First.' });- await sync(pluginFs);-- const config = (await readAgentConfigFile(pluginFs, NAME)) ?? {};- await writeAgentConfigFile(pluginFs, NAME, { ...config, instructions: 'Second.' });- const result = await sync(pluginFs);-- expect(result.action).toBe('written');- expect(await readDefinition()).toContain('Second.');- });-- it('reads a hand-edited definition back into the config instead of overwriting it', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Generated.' });- await sync(pluginFs);-- // Somebody edits the subagent file directly, as they always could.- await pluginFs.write(- DEF_PATH,- `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\nmodel: haiku\n---\n\nHand written.\n`- );- const result = await sync(pluginFs);-- expect(result.action).toBe('adopted');- expect(result.config.instructions).toBe('Hand written.');- expect(result.config.settings).toMatchObject({ model: 'haiku' });- expect(await readDefinition()).toContain('Hand written.');- });-- it('settles after adopting, rather than reporting a hand edit forever', async () => {- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Generated.' });- await sync(pluginFs);- await pluginFs.write(- DEF_PATH,- `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\n---\n\nHand written.\n`- );-- expect((await sync(pluginFs)).action).toBe('adopted');- expect((await sync(pluginFs)).action).toBe('in-sync');- });-- it('adopts a definition that already existed before this app ever wrote one', async () => {- // An agent onboarded from a directory someone else set up. Overwriting it- // would discard a prompt this app never wrote.- const pluginFs = createPluginFs(dir);- await pluginFs.write(- DEF_PATH,- `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\n---\n\nTheirs, not ours.\n`- );-- const result = await sync(pluginFs);-- expect(result.action).toBe('adopted');- expect(result.config.instructions).toBe('Theirs, not ours.');- });-- it('picks up the config an agent already carries when onboarded elsewhere', async () => {- // The whole point of the file being committed: a second machine opening the- // same working directory gets the same agent.- const pluginFs = createPluginFs(dir);- await writeAgentConfigFile(pluginFs, NAME, {- instructions: 'Set on another machine.',- settings: { model: 'opus' },- });-- const result = await sync(pluginFs);-- expect(result.config.instructions).toBe('Set on another machine.');- expect(await readDefinition()).toContain('Set on another machine.');- });-- it('writes the definition when there is no config at all', async () => {- const result = await sync();-- expect(result.action).toBe('written');- // No instructions set, so the description stands in as the prompt.- expect(await readDefinition()).toContain(DESCRIPTION);- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.tsdeleted file mode 100644index bff18ec81..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts+++ /dev/null@@ -1,147 +0,0 @@-import type {- IRepoAgentsBehavior,- PluginFs,- RepoAgentAttributes,-} from '@switch-console/core/agents/plugins';-import type { AgentConfigFile } from './agent-config-file';-import {- decideArtifactSync,- fingerprintArtifact,- readAgentConfigFile,- writeAgentConfigFile,-} from './agent-config-file';--/**- * Reconcile an agent's config file with the provider definition generated from- * it (CHOO-2228).- *- * The config file is the source of truth, so normally the definition is- * generated from it. The exception is deliberate: Claude Code's subagent file- * is a normal repository file that people edit directly, and those edits are- * read back into the config rather than overwritten.- *- * Which of the two happened is decided by the fingerprint recorded the last- * time this app generated the definition — see `decideArtifactSync`. Comparing- * the file against what the config generates *now* cannot tell the two apart.- *- * Providers whose per-agent files are rebuilt from scratch at every launch- * (Codex, OpenCode) have nothing to reconcile: their files live outside the- * repository and are outputs only, so this is a no-op for them.- */-export type AgentConfigSyncResult = {- /** The config after reconciliation — what callers should read from. */- config: AgentConfigFile;- /** What was done, for logging and for telling the user when edits were taken- * from the definition rather than written to it. */- action: 'written' | 'adopted' | 'in-sync' | 'not-applicable';-};--export async function syncAgentConfig(params: {- workspaceFs: PluginFs;- /** Null for a provider with no repository definitions (Codex, OpenCode). */- repoAgents: IRepoAgentsBehavior | null;- /** The agent's name, which is both its config-file key and its definition stem. */- name: string;- /** The agent's description, which the definition carries in its frontmatter. */- description: string;-}): Promise<AgentConfigSyncResult> {- const { workspaceFs, repoAgents, name, description } = params;-- const config = (await readAgentConfigFile(workspaceFs, name)) ?? {};- if (!repoAgents) return { config, action: 'not-applicable' };-- const definitionPath = repoAgents.definitionPath(name);- const generated = repoAgents.renderDefinition(- definitionAttributes({ config, name, description })- );- const current = await workspaceFs.read(definitionPath);-- const action = decideArtifactSync({- current,- generated,- lastRendered: config.rendered?.[definitionPath],- });-- if (action === 'in-sync') return { config, action };-- if (action === 'adopt') {- const adopted = await adoptDefinition({ workspaceFs, repoAgents, name, config });- return { config: adopted, action: 'adopted' };- }-- await workspaceFs.write(definitionPath, generated);- const written: AgentConfigFile = {- ...config,- rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },- };- await writeAgentConfigFile(workspaceFs, name, written);- return { config: written, action: 'written' };-}--/**- * Take a hand-edited definition as the new truth: read it back into the config,- * then regenerate so the two agree again and the fingerprint matches.- *- * Regenerating rather than leaving the file alone matters — the definition may- * hold things the config cannot express (frontmatter this app does not model),- * and writing the round-tripped version is what makes the next comparison- * meaningful instead of reporting a hand edit forever.- */-async function adoptDefinition(params: {- workspaceFs: PluginFs;- repoAgents: IRepoAgentsBehavior;- name: string;- config: AgentConfigFile;-}): Promise<AgentConfigFile> {- const { workspaceFs, repoAgents, name, config } = params;-- const attributes = await repoAgents.readDefinition(workspaceFs, name);- if (attributes === null) {- throw new Error(`Agent ${name} has a definition that could not be read back.`);- }-- const { name: _name, description, instructions, ...settings } = attributes;- const adopted: AgentConfigFile = {- ...config,- instructions: typeof instructions === 'string' ? instructions : '',- settings,- };-- const definitionPath = repoAgents.definitionPath(name);- const generated = repoAgents.renderDefinition(- definitionAttributes({- config: adopted,- name,- description: typeof description === 'string' ? description : '',- })- );- await workspaceFs.write(definitionPath, generated);-- const result: AgentConfigFile = {- ...adopted,- rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },- };- await writeAgentConfigFile(workspaceFs, name, result);- return result;-}--/**- * The attribute map a provider renders from: the agent's settings, plus the- * three things that are the agent's own rather than a setting.- *- * `instructions` is passed under that name for every provider — each renders it- * into whatever mechanism it has, so the key is canonical here and provider- * -specific only inside the provider.- */-export function definitionAttributes(params: {- config: AgentConfigFile;- name: string;- description: string;-}): RepoAgentAttributes {- return {- ...params.config.settings,- name: params.name,- description: params.description,- instructions: params.config.instructions ?? '',- };-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.tsindex e8a5c332d..5f359cb4c 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts@@ -1,26 +1,27 @@import type { PluginFs } from '@switch-console/core/agents/plugins';/**- * Changing an agent's configuration has to reach the thing that launches it —- * which, for a remote agent, is a launch spec sitting on the VM (CHOO-2228).- *- * Writing the config file alone is enough for a provider whose CLI reads its- * definition at every spawn (Claude Code), and not enough for one whose- * settings are handed over as a generated profile: there the spec has to be- * rebuilt, or an auto-started session keeps running on the previous- * instructions while the app shows the new ones.+ * An agent's configuration is its config file and nothing else (CHOO-2228):+ * reading it never writes, a missing file is an error rather than a blank+ * agent, and a change reaches whatever launches the agent's next session —+ * which, for an automatic session, is a launch spec built earlier.*/import { beforeEach, describe, expect, it, vi } from 'vitest';const setAgentProviderConfig = vi.hoisted(() => vi.fn(async (_params: unknown) => {}));+const ensureRemoteWatcher = vi.hoisted(() => vi.fn(async (_agentId: string) => {}));const state = vi.hoisted(() => ({providerId: 'codex',+ providerConfig: null as unknown,+ autoSession: [] as string[],files: new Map<string, string>(),+ writes: [] as string[],}));const fakeFs = vi.hoisted(() => (): PluginFs => ({read: async (path: string) => state.files.get(path) ?? null,write: async (path: string, content: string) => {+ state.writes.push(path);state.files.set(path, content);},delete: async (path: string) => {@@ -36,6 +37,7 @@ vi.mock('./getAgentById', () => ({id: agentId,name: 'agent-one',providerId: state.providerId,+ providerConfig: state.providerConfig,locationId: 'loc-1',}),}));@@ -48,31 +50,141 @@ vi.mock('./agent-workspace-fs', () => ({vi.mock('./setAgentProviderConfig', () => ({setAgentProviderConfig: (params: unknown) => setAgentProviderConfig(params),}));+vi.mock('./remote-watcher', () => ({+ ensureRemoteWatcher: (agentId: string) => ensureRemoteWatcher(agentId),+}));+vi.mock('@main/lib/logger', () => ({+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));+vi.mock('@main/core/switch-rooms/auto-session-store', () => ({+ listAutoSessionAgentIds: async () => state.autoSession,+}));vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: (id: string) => ({behavior:id === 'claude'- ? {- repoAgents: {- definitionPath: (name: string) => `.claude/agents/${name}.md`,- renderDefinition: (attributes: Record<string, unknown>) =>- `---\nname: ${String(attributes.name)}\n---\n\n${String(attributes.instructions)}\n`,- readDefinition: async () => null,- },- }+ ? { repoAgents: { launchDefinition: () => ({}) } }: { mcp: { launchProfileFields: () => [] } },}),}));-import { setAgentInstructions } from './agent-config';+import { readAgentInstructions, setAgentInstructions, setAgentSettings } from './agent-config';+import { AgentConfigMissingError, agentLaunchConfig } from './agent-launch-config';+import {+ isAgentUnmigrated,+ markAgentUnmigrated,+ setAgentStorageMigrationReady,+} from './agent-storage-migration-ready';++const CONFIG_PATH = '.switch/config/agent-one.json';beforeEach(() => {setAgentProviderConfig.mockClear();+ ensureRemoteWatcher.mockClear();state.files.clear();+ state.writes = [];+ state.autoSession = [];state.providerId = 'codex';+ state.providerConfig = null;+ state.files.set(CONFIG_PATH, '{}\n');+ setAgentStorageMigrationReady(Promise.resolve());});-describe('setAgentInstructions', () => {+describe('reading', () => {+ it('never writes', async () => {+ state.providerId = 'claude';+ state.files.set(CONFIG_PATH, JSON.stringify({ instructions: 'Be careful.' }));+ state.files.set('.claude/agents/agent-one.md', '---\nname: agent-one\n---\n\nStale.\n');++ expect(await readAgentInstructions('agent-1')).toBe('Be careful.');+ expect(state.writes).toEqual([]);+ });++ it('treats a missing config file as an error, not a blank agent', async () => {+ state.files.delete(CONFIG_PATH);++ await expect(readAgentInstructions('agent-1')).rejects.toBeInstanceOf(AgentConfigMissingError);+ expect(state.writes).toEqual([]);+ });++ it('waits for the boot migration before calling the file missing', async () => {+ state.files.delete(CONFIG_PATH);+ let finish = () => {};+ setAgentStorageMigrationReady(+ new Promise<void>((resolve) => {+ finish = () => {+ state.files.set(CONFIG_PATH, JSON.stringify({ instructions: 'Migrated.' }));+ resolve();+ };+ })+ );++ const read = readAgentInstructions('agent-1');+ finish();++ expect(await read).toBe('Migrated.');+ });+ it('reads after the boot migration, not before it', async () => {+ // The migration may be about to take over a hand edit to the old definition+ // file; reading first would show, and a save would keep, the value before it.+ state.files.set(CONFIG_PATH, JSON.stringify({ instructions: 'Old.' }));+ let finish = () => {};+ setAgentStorageMigrationReady(+ new Promise<void>((resolve) => {+ finish = () => {+ state.files.set(CONFIG_PATH, JSON.stringify({ instructions: 'Taken over.' }));+ resolve();+ };+ })+ );++ const read = readAgentInstructions('agent-1');+ finish();++ expect(await read).toBe('Taken over.');+ });++ it('migrates an agent the boot migration could not reach', async () => {+ // Its host was down at boot; it is reachable now, since this read got here.+ state.files.delete(CONFIG_PATH);+ state.providerConfig = {+ version: '2',+ providerId: 'codex',+ values: { instructions: 'From the row.' },+ };+ markAgentUnmigrated('agent-1');++ expect(await readAgentInstructions('agent-1')).toBe('From the row.');+ expect(isAgentUnmigrated('agent-1')).toBe(false);+ });+});++describe('saving', () => {+ it('refuses to save into an agent whose config file is missing', async () => {+ state.files.delete(CONFIG_PATH);++ await expect(+ setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' })+ ).rejects.toBeInstanceOf(AgentConfigMissingError);+ expect(state.writes).toEqual([]);+ });++ it('changes only what was saved', async () => {+ state.files.set(+ CONFIG_PATH,+ JSON.stringify({ description: 'Reviews', instructions: 'Old.', settings: { model: 'opus' } })+ );++ await setAgentInstructions({ agentId: 'agent-1', instructions: 'New.' });++ expect(JSON.parse(state.files.get(CONFIG_PATH) ?? '')).toEqual({+ description: 'Reviews',+ instructions: 'New.',+ settings: { model: 'opus' },+ });+ expect(state.writes).toEqual([CONFIG_PATH]);+ });+it('rebuilds the launch profile for a provider that reads one', async () => {// Codex takes its instructions as a generated profile file, baked into the// remote launch spec. Without this the VM keeps the old prompt.@@ -85,16 +197,6 @@ describe('setAgentInstructions', () => {});});- it('does not for a provider whose CLI reads the definition itself', async () => {- // Claude Code launches with `--agent <name>` and reads the definition file- // fresh each time, which the write above already updated.- state.providerId = 'claude';-- await setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' });-- expect(setAgentProviderConfig).not.toHaveBeenCalled();- });-it('carries a cleared prompt through too, not just a set one', async () => {await setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' });setAgentProviderConfig.mockClear();@@ -107,4 +209,41 @@ describe('setAgentInstructions', () => {config: null,});});++ it('rebuilds the automatic-session spec for an agent that runs as a definition', async () => {+ // Claude Code gets its definition in the launch spec now, so an automatic+ // session would otherwise start on the previous one.+ state.providerId = 'claude';+ state.autoSession = ['agent-1'];++ await setAgentSettings({ agentId: 'agent-1', settings: { model: 'opus' } });++ expect(ensureRemoteWatcher).toHaveBeenCalledWith('agent-1');+ expect(setAgentProviderConfig).not.toHaveBeenCalled();+ });++ it('leaves the controller alone when automatic sessions are off', async () => {+ state.providerId = 'claude';++ await setAgentSettings({ agentId: 'agent-1', settings: { model: 'opus' } });++ expect(ensureRemoteWatcher).not.toHaveBeenCalled();+ });+});++describe('launching', () => {+ it('runs as a definition when the config describes the agent', async () => {+ state.providerId = 'claude';+ state.files.set(CONFIG_PATH, JSON.stringify({ description: 'Reviews diffs' }));++ expect((await agentLaunchConfig('agent-1')).definition).toBeDefined();+ });++ it('runs the provider as it is when the config says nothing', async () => {+ // As an agent with no definition file on disk always did, rather than as a+ // definition whose prompt is its own name.+ state.providerId = 'claude';++ expect((await agentLaunchConfig('agent-1')).definition).toBeUndefined();+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.tsindex c1c37ccb3..c3ecd069d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts@@ -1,55 +1,26 @@-import type { PluginFs, RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';+import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';import { providerConfigFromAttributes } from '@shared/core/agents/agent-provider-config';-import type { Agent } from '@shared/core/agents/agents';import type { AgentConfigFile } from './agent-config-file';import { writeAgentConfigFile, type AgentTemplateOrigin } from './agent-config-file';-import { syncAgentConfig } from './agent-config-sync';-import { withAgentWorkspace } from './agent-launch-config';+import { readRequiredAgentConfig, withAgentWorkspace } from './agent-launch-config';import { getAgentById } from './getAgentById';+import { ensureRemoteWatcher } from './remote-watcher';import { setAgentProviderConfig } from './setAgentProviderConfig';/**- * An agent's configuration, read and written where it actually lives: the- * committed config file in its working directory (CHOO-2228).+ * An agent's configuration, read and written where it lives: the committed+ * config file in its working directory (CHOO-2228).*- * Every caller goes through here rather than touching the file, so the- * reconciliation with the provider's own generated file happens on every read- * — which is what makes a hand-edited Claude Code subagent definition show up- * in the app rather than being quietly replaced the next time anything saves.- *- * The working directory is where the agent runs, so the file is reachable- * whenever launching is possible, including over SFTP for a remote agent.+ * The file is the only record. Nothing is generated from it on disk and nothing+ * is read back into it: each launch builds what the provider needs from the file+ * directly. So reading never writes, and the only writes are the ones a person+ * asked for.*/-/**- * The agent's current configuration, reconciled with its provider definition.- *- * Reading has a side effect by design: if the definition was edited by hand the- * edits are adopted into the config, and if the config moved on the definition- * is regenerated. Doing this on read is what keeps the app from showing a value- * that is not what the agent will actually launch with.- */export async function readAgentConfig(agentId: string): Promise<AgentConfigFile> {- return withAgentWorkspace(agentId, (agent, fs) => reconcile(agent, fs));-}--/**- * Replace the agent's configuration and regenerate whatever its provider reads.- *- * Write-then-generate, in that order: the config file is the record of what the- * user chose, and the provider's file is derived from it. A failure part-way- * leaves the choice recorded and the generated file stale, which the next read- * repairs — the other order would lose the choice.- */-export async function writeAgentConfig(params: {- agentId: string;- config: AgentConfigFile;-}): Promise<AgentConfigFile> {- return withAgentWorkspace(params.agentId, async (agent, fs) => {- await writeAgentConfigFile(fs, agent.name, params.config);- return reconcile(agent, fs);- });+ return withAgentWorkspace(agentId, (agent, fs) => readRequiredAgentConfig(agent, fs));}/** The template the agent was created from, or null for an agent created without one. */@@ -91,77 +62,53 @@ export async function setAgentSettings(params: {}));}-/**- * Read, change, write — in one workspace session.- *- * Not read-then-write through the public helpers: over SSH that opens the- * working directory twice, and it would reconcile twice for one edit.- */+/** Read, change, write — in one workspace session. */async function updateAgentConfig(agentId: string,change: (config: AgentConfigFile) => AgentConfigFile): Promise<AgentConfigFile> {const config = await withAgentWorkspace(agentId, async (agent, fs) => {- const current = await reconcile(agent, fs);- await writeAgentConfigFile(fs, agent.name, change(current));- return reconcile(agent, fs);+ const next = change(await readRequiredAgentConfig(agent, fs));+ await writeAgentConfigFile(fs, agent.name, next);+ return next;});- await propagateToLaunchProfile(agentId, config);+ await propagateToLaunch(agentId, config);return config;}/**- * Carry a config change into the launch profile, for the providers that read- * one.+ * Carry a config change to what launches the agent's next session.*- * A provider with repository definitions (Claude Code) needs nothing here: its- * CLI reads the definition file itself at every spawn, and the write above- * already put it in place — on a remote host too, over SFTP.+ * A session the Console starts itself reads the file at that moment and needs+ * nothing here. An automatic session does not: it is started by the agent's+ * controller from a launch spec built earlier, with the config baked in, so the+ * controller is re-applied to rebuild that spec. Otherwise the next automatic+ * session would run on the previous instructions while the app showed the new+ * ones.*- * The others do. Their settings reach a session as a generated profile file,- * and on a remote host that file is baked into the launch spec the on-VM- * sidecar holds. Writing the config file alone would leave that spec stale, so- * an auto-started session would keep running on the previous instructions while- * the app showed the new ones. This is what rewrites it.+ * The launch-profile providers also keep a copy on the agent row.** Done for every write rather than by each caller, so a new way to change the- * config cannot forget it and quietly reintroduce that gap.+ * config cannot forget it.*/-async function propagateToLaunchProfile(agentId: string, config: AgentConfigFile): Promise<void> {+async function propagateToLaunch(agentId: string, config: AgentConfigFile): Promise<void> {const agent = await getAgentById(agentId);if (!agent) throw new Error(`No agent with id ${agentId}`);const behavior = getPlugin(agent.providerId).behavior;- if (behavior.repoAgents || !behavior.mcp?.launchProfileFields) return;-- await setAgentProviderConfig({- agentId,- config: providerConfigFromAttributes(agent.providerId, {- ...config.settings,- instructions: config.instructions ?? '',- }),- });-}+ if (!behavior.repoAgents && behavior.mcp?.launchProfileFields) {+ // Re-applies the controller itself when it has to.+ await setAgentProviderConfig({+ agentId,+ config: providerConfigFromAttributes(agent.providerId, {+ ...config.settings,+ instructions: config.instructions ?? '',+ }),+ });+ return;+ }-/**- * Bring the config file and the provider's generated file into agreement.- *- * The description comes from the definition rather than from the agent's Switch- * server: it is the server's to own, and this must not blank it when the server- * is unreachable. It round-trips through the definition anyway, so reading it- * from there is both correct and one fewer thing that can fail at launch.- */-async function reconcile(agent: Agent, fs: PluginFs): Promise<AgentConfigFile> {- const repoAgents = getPlugin(agent.providerId).behavior.repoAgents ?? null;- const existing = repoAgents ? await repoAgents.readDefinition(fs, agent.name) : null;- const description = typeof existing?.description === 'string' ? existing.description : '';-- const { config } = await syncAgentConfig({- workspaceFs: fs,- repoAgents,- name: agent.name,- description,- });- return config;+ if (!(await listAutoSessionAgentIds()).includes(agentId)) return;+ await ensureRemoteWatcher(agentId);}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.tsdeleted file mode 100644index 255f3c594..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-definition.ts+++ /dev/null@@ -1,62 +0,0 @@-import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { getAgentLocation } from './agent-location';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getAgentById } from './getAgentById';--/**- * Read an agent's on-disk definition attributes (model, effort, tools, system- * prompt, …) so the Settings tab can prefill its editable Advanced section.- * Returns null when the provider has no definition concept, the agent carries no- * definition name, or the definition file is absent — the caller renders an- * empty form in that case (CHOO-1440).- */-export async function readAgentDefinition(agentId: string): Promise<RepoAgentAttributes | null> {- const agent = await getAgentById(agentId);- if (!agent) throw new Error(`No agent with id ${agentId}`);-- const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (!behavior || !agent.name) return null;-- const location = await getAgentLocation(agent);- const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);- try {- return await behavior.readDefinition(workspace.fs, agent.name);- } finally {- workspace.close();- }-}--/**- * Rewrite an agent's on-disk definition with new Advanced attributes, preserving- * its identity (name) and description. The name is immutable — it is the agent's- * `--agent <name>` handle and its Switch identity — so only the provider's- * advanced attributes change. Fails loud for a provider without definitions or an- * agent with no definition name (there is nothing to edit).- */-export async function updateAgentDefinition(params: {- agentId: string;- attributes: RepoAgentAttributes;-}): Promise<void> {- const agent = await getAgentById(params.agentId);- if (!agent) throw new Error(`No agent with id ${params.agentId}`);-- const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (!behavior || !agent.name) {- throw new Error(`Agent ${params.agentId} has no editable on-disk definition.`);- }-- const location = await getAgentLocation(agent);- const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);- try {- const current = await behavior.readDefinition(workspace.fs, agent.name);- const description = typeof current?.description === 'string' ? current.description : '';- await behavior.writeDefinition(workspace.fs, {- ...params.attributes,- name: agent.name,- description,- });- } finally {- workspace.close();- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.tsindex 1fe040bba..e079ebc82 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts@@ -1,10 +1,22 @@-import type { PluginFs, SwitchLaunchSpecialization } from '@switch-console/core/agents/plugins';+import type {+ PluginFs,+ RepoAgentLaunchDefinition,+ SwitchLaunchSpecialization,+} from '@switch-console/core/agents/plugins';+import { getPlugin } from '@main/core/providers/plugin-registry';import type { Agent } from '@shared/core/agents/agents';import type { AgentConfigFile } from './agent-config-file';import { readAgentConfigFile } from './agent-config-file';import { getAgentLocation } from './agent-location';+import {+ agentStorageMigrationReady,+ isAgentUnmigrated,+ markAgentMigrated,+} from './agent-storage-migration-ready';import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgentById } from './getAgentById';+import { importAgentConfig } from './import-agent-config';+import { agentConfigRelativePath } from './switch-settings-paths';/*** Reading an agent's configuration in order to launch it (CHOO-2228).@@ -16,22 +28,90 @@ import { getAgentById } from './getAgentById';* it only reads a file.*/-/** Read launch settings from the execution host; transport failures must stop launch. */-export async function readAgentConfigForLaunch(agentId: string): Promise<AgentConfigFile> {- return withAgentWorkspace(- agentId,- async (agent, fs) => (await readAgentConfigFile(fs, agent.name)) ?? {}- );+/**+ * Every agent has a config file from the moment it is created, so one that has+ * none is broken, not blank. Treating it as empty would launch the agent with+ * no instructions, and the next save would write that emptiness back.+ */+export class AgentConfigMissingError extends Error {+ constructor(agentName: string) {+ super(+ `Agent ${agentName} has no settings file (${agentConfigRelativePath(agentName)}) in its working directory.`+ );+ this.name = 'AgentConfigMissingError';+ }+}++/**+ * The agent's config file, which must exist.+ *+ * Waits for the boot migration first, since that is what creates the file for+ * agents that predate it. An agent the migration could not reach at boot is+ * migrated here instead: its working directory is reachable now.+ */+export async function readRequiredAgentConfig(+ agent: Agent,+ fs: PluginFs+): Promise<AgentConfigFile> {+ await agentStorageMigrationReady();+ if (isAgentUnmigrated(agent.id)) {+ await importAgentConfig({+ workspaceFs: fs,+ repoAgents: getPlugin(agent.providerId).behavior.repoAgents ?? null,+ name: agent.name,+ providerConfig: agent.providerConfig,+ });+ markAgentMigrated(agent.id);+ }+ const config = await readAgentConfigFile(fs, agent.name);+ if (config) return config;+ throw new AgentConfigMissingError(agent.name);}/**- * The values a provider's launch profile is built from: the agent's settings- * plus its instructions, under the canonical key every provider renders.+ * What a session is launched with, from the agent's config file:+ * - `specialization`, the values a provider's launch profile is built from —+ * the agent's settings plus its instructions, under the canonical key every+ * provider renders;+ * - `definition`, for a provider that runs a session as a named agent, the+ * definition it runs as.*/-export async function agentLaunchSpecialization(- agentId: string-): Promise<SwitchLaunchSpecialization | undefined> {- const config = await readAgentConfigForLaunch(agentId);+export type AgentLaunchConfig = {+ specialization: SwitchLaunchSpecialization | undefined;+ definition: RepoAgentLaunchDefinition | undefined;+};++export async function agentLaunchConfig(agentId: string): Promise<AgentLaunchConfig> {+ return withAgentWorkspace(agentId, async (agent, fs) => {+ const config = await readRequiredAgentConfig(agent, fs);+ const repoAgents = getPlugin(agent.providerId).behavior.repoAgents;+ return {+ specialization: launchSpecialization(config),+ definition:+ repoAgents && definesAgent(config)+ ? repoAgents.launchDefinition({+ ...config.settings,+ name: agent.name,+ description: config.description || agent.name,+ instructions: config.instructions ?? '',+ })+ : undefined,+ };+ });+}++/**+ * Whether the config says anything a definition would carry. One that says+ * nothing runs the provider as it is, as an agent with no definition file on+ * disk always did, rather than as a definition whose prompt is its own name.+ */+function definesAgent(config: AgentConfigFile): boolean {+ return (+ !!config.description || !!config.instructions || Object.keys(config.settings ?? {}).length > 0+ );+}++function launchSpecialization(config: AgentConfigFile): SwitchLaunchSpecialization | undefined {const specialization: SwitchLaunchSpecialization = {};for (const [key, value] of Object.entries(config.settings ?? {})) {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-name-taken.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-name-taken.tsindex a45399fc4..16e227e85 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-name-taken.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-name-taken.ts@@ -6,8 +6,8 @@ import { agents } from '@main/db/schema';* Whether another agent in the same location already answers to `name`.** Everything Switch Console provisions per agent is keyed by the name rather than the- * id — `.switch/agents/<name>.json` carries the Switch token, `.claude/agents/<name>.md`- * the definition — so two agents sharing a name in one directory share one+ * id — `.switch/agents/<name>.json` carries the Switch token, `.switch/config/<name>.json`+ * the configuration — so two agents sharing a name in one directory share one* credentials file, and whoever writes last decides which identity both of them* present. The gateway's own uniqueness check cannot stand in for this one: it is* scoped to a Switch server, and a name can be free there while taken here.diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.tsindex 534f8f6ec..1a3b83e03 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-marker.ts@@ -17,6 +17,8 @@ const MARKER_KEY = 'agentStorageMigrationComplete';* - `1` — the original pass. Providers without a `repoAgents` behavior returned* "complete" without being looked at, so only Claude agents were migrated.* - `2` — the credential collapse runs for every provider.+ * - `3` — every agent gets a config file, taking over what a Claude Code agent+ * kept in its definition and what other providers kept on the agent row.** Bump this whenever the migration learns to fix something it previously* skipped, so installs that latched an earlier generation run the new pass@@ -24,7 +26,7 @@ const MARKER_KEY = 'agentStorageMigrationComplete';* it says. Then teach `migrateAgentStorage` which agents the new generation can* actually change, so the re-run does not re-open workspaces it cannot fix.*/-export const AGENT_STORAGE_MIGRATION_GENERATION = 2;+export const AGENT_STORAGE_MIGRATION_GENERATION = 3;/** The generation last completed on this install; 0 when it has never run. */export async function completedAgentStorageMigrationGeneration(): Promise<number> {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-ready.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-ready.tsnew file mode 100644index 000000000..3402f6186--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-storage-migration-ready.ts@@ -0,0 +1,34 @@+/**+ * The boot-time agent storage migration, as something to wait on.+ *+ * The migration runs off the boot path, so a settings page or a launch can reach+ * an agent before its config file has been created. Those readers wait on this+ * before concluding a missing file is an error, rather than failing for an agent+ * the migration is about to fix.+ *+ * An agent the migration could not reach (its host was down) is remembered, so+ * the first reader to reach it later finishes the job instead of waiting for+ * the next boot.+ */+let ready: Promise<void> = Promise.resolve();+const unmigrated = new Set<string>();++export function setAgentStorageMigrationReady(migration: Promise<void>): void {+ ready = migration;+}++export function agentStorageMigrationReady(): Promise<void> {+ return ready;+}++export function markAgentUnmigrated(agentId: string): void {+ unmigrated.add(agentId);+}++export function markAgentMigrated(agentId: string): void {+ unmigrated.delete(agentId);+}++export function isAgentUnmigrated(agentId: string): boolean {+ return unmigrated.has(agentId);+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.tsindex bf6e13a6a..e199ac243 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts@@ -2,15 +2,23 @@ import type { PluginFs } from '@switch-console/core/agents/plugins';import { beforeEach, describe, expect, it, vi } from 'vitest';/**- * A {@link PluginFs} that fails any write. Attaching adopts another install's- * directory, so every write is a bug — this turns "should not write" into a- * test failure at the point of the write rather than an assertion after it.+ * A {@link PluginFs} that fails any write but an agent config file. Attaching+ * adopts another install's directory, so any other write is a bug — this turns+ * "should not write" into a test failure at the point of the write rather than+ * an assertion after it.*/-function readOnlyFs(seed: Record<string, string>): PluginFs {+function readOnlyFs(seed: Record<string, string>): PluginFs & { files: Map<string, string> } {const files = new Map<string, string>(Object.entries(seed));return {+ files,read: (p) => Promise.resolve(files.get(p) ?? null),- write: (p) => Promise.reject(new Error(`attach wrote to the workspace: ${p}`)),+ write: (p, content) => {+ if (!p.startsWith('.switch/config/')) {+ return Promise.reject(new Error(`attach wrote to the workspace: ${p}`));+ }+ files.set(p, content);+ return Promise.resolve();+ },delete: (p) => Promise.reject(new Error(`attach deleted from the workspace: ${p}`)),exists: (p) => Promise.resolve(files.has(p)),list: (dir) => {@@ -82,6 +90,7 @@ vi.mock('./agent-workspace-fs', () => ({}));vi.mock('@main/core/providers/plugin-registry', () => ({listPlugins: () => [{ metadata: { id: 'codex' }, behavior: {} }],+ getPlugin: () => ({ behavior: {} }),}));vi.mock('@main/core/switch-servers/gateway-client', () => ({agentExistsOnServer: h.agentExistsOnServer,@@ -136,12 +145,26 @@ describe('attachConfiguredAgents', () => {);});- it('writes nothing to the working directory', async () => {- // The workspace belongs to whichever install set the agent up. Any write- // here rejects, so this passing means attach touched none of their state.+ it('writes nothing to the working directory but a missing config file', async () => {+ // The workspace belongs to whichever install set the agent up. Any other+ // write here rejects, so this passing means attach touched none of their+ // state — and every agent has a config file.await expect(attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]))).resolves.toMatchObject({ success: true });+ expect(await h.state.workspace?.read('.switch/config/theirs.json')).not.toBeNull();+ });++ it('leaves an existing config file alone', async () => {+ const existing = JSON.stringify({ instructions: 'Theirs.', rendered: { x: 'y' } });+ h.state.workspace = readOnlyFs({+ '.switch/agents/theirs.json': creds('sw-theirs'),+ '.switch/config/theirs.json': existing,+ });++ await attachConfiguredAgents(params([{ name: 'theirs', providerId: 'codex' }]));++ expect(await h.state.workspace.read('.switch/config/theirs.json')).toBe(existing);});it('fails loudly when the identity no longer exists on the server', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.tsindex a56bb053a..423b5c790 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts@@ -4,6 +4,7 @@ import type { Result } from '@switch-console/shared';import { locationManager } from '@main/core/locations/location-manager';import { checkIsValidDirectory } from '@main/core/locations/path-utils';import { ensureLocation } from '@main/core/locations/store';+import { getPlugin } from '@main/core/providers/plugin-registry';import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';import { log } from '@main/lib/logger';@@ -12,9 +13,12 @@ import type { OnboardAgentError } from '@shared/core/agents/onboarding';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { sameApiEndpoint } from '@shared/core/switch-servers/switch-servers';import { basenameFromAnyPath } from '@shared/path-name';+import { readAgentConfigFile } from './agent-config-file';import { agentEvents } from './agent-events';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';import { discoverConfiguredAgents } from './discover-configured-agents';+import { importAgentConfig } from './import-agent-config';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';export type AttachConfiguredAgentsParams = {@@ -43,12 +47,12 @@ export type AttachConfiguredAgentsResult = Result<Agent[], OnboardAgentError>;* rather than trusted from the caller, so a stale scan cannot mint a row* pointing at the wrong agent.*- * **Writes nothing to the working directory.** No credentials, no definition, no- * provider config — the directory is another install's state and this operation- * treats it as read-only. That is possible because the API token is never needed- * here: it stays where it already is, and the launch path reads it from disk when- * a session spawns. This module deliberately imports no workspace writer, so the- * guarantee is structural rather than a matter of care.+ * **Writes no credentials.** The API token is never needed here: it stays where+ * it already is, and the launch path reads it from disk when a session spawns.+ * The one thing written is an agent's config file, and only when it has none —+ * every agent has one, and one set up by an older Console may not yet. It is+ * built from the agent's own definition, so it holds nothing the directory did+ * not already say.** An identity that no longer exists on the chosen server fails the attach loudly* instead of falling back to minting a fresh one — a silent mint is exactly the@@ -151,6 +155,8 @@ export async function attachConfiguredAgents(});}+ await ensureAgentConfig({ sshHost: params.sshHost, dir: params.dir, name, providerId });+const agent = await createAgent({id: randomUUID(),locationId: location.id,@@ -192,3 +198,24 @@ export async function attachConfiguredAgents(return ok(created);}++/** Create the agent's config file from its definition when it has none; leave an existing one alone. */+async function ensureAgentConfig(params: {+ sshHost: string | null;+ dir: string;+ name: string;+ providerId: AgentProviderId;+}): Promise<void> {+ const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);+ try {+ if ((await readAgentConfigFile(workspace.fs, params.name)) !== null) return;+ await importAgentConfig({+ workspaceFs: workspace.fs,+ repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,+ name: params.name,+ providerConfig: null,+ });+ } finally {+ workspace.close();+ }+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.tsindex 15378d295..a7a07625f 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts@@ -35,7 +35,7 @@ import { stopRemoteWatcher } from './remote-watcher';import { removeAgentLaunchProfile } from './remove-launch-profile';import { removeSwitchCredentials } from './remove-switch-settings';import { stopSharedAgentSessions } from './stop-shared-agent-sessions';-import { agentSettingsRelativePath } from './switch-settings-paths';+import { agentConfigRelativePath, agentSettingsRelativePath } from './switch-settings-paths';export type DeleteAgentOptions = {/**@@ -116,8 +116,8 @@ async function deleteAgentInSwitch(agent: Agent): Promise<void> {/*** Reverse the on-disk state Switch Console provisioned for this one agent: its- * provider definition (`.claude/agents/<name>.md`) and its per-agent Switch- * credentials. Runs against the agent's local dir or its remote SSH host+ * per-agent Switch credentials, its config file, and any provider definition+ * (`.claude/agents/<name>.md`) an earlier version wrote. Runs against the agent's local dir or its remote SSH host* transparently. Only THIS agent's files are removed — sibling agents sharing the* directory are untouched (CHOO-1440).*@@ -152,6 +152,15 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promiseerror: String(error),});});+ // The config file goes too: an agent created later under the same name must+ // start from what it was created with, not from this one's settings.+ await ctx.fs.delete(agentConfigRelativePath(agent.name ?? agent.id)).catch((error) => {+ log.warn('deleteAgent: failed to remove the agent config file', {+ agentId: agent.id,+ name: agent.name,+ error: String(error),+ });+ });await removeSwitchCredentials(ctx.fs);// A provider that registers the Switch server itself (Codex) leaves a// per-agent launch profile under the user's home — a different scope thandiff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.tsindex 0682e4ac7..1dd4d01d8 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/discover-configured-agents.ts@@ -99,13 +99,9 @@ async function definitionOwners(workspaceFs: PluginFs): Promise<Map<string, Agen* keyed on the provider-neutral `.switch/agents/<name>.json` credentials every* provider writes at create time (CHOO-1937).*- * This is the counterpart to `discoverLocationAgents`, and answers a different- * question. That one asks a provider which of *its* definitions in the directory- * could become an agent — a Claude-only answer today, since Claude is the only- * provider with a definition concept. This one asks which agents already *are*- * configured here, whoever set them up and whichever provider runs them, so an- * agent someone else onboarded on a shared host is visible to every Switch Console- * that can reach the directory.+ * It asks which agents already *are* configured here, whoever set them up and+ * whichever provider runs them, so an agent someone else onboarded on a shared+ * host is visible to every Switch Console that can reach the directory.** Deliberately pure disk IO: it does not verify the identities against a Switch* server. That check needs a server the caller has chosen and belongs to thediff --git a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.tsdeleted file mode 100644index a15565afe..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/discover-location-agents.ts+++ /dev/null@@ -1,72 +0,0 @@-import { getLocationByHostDir } from '@main/core/locations/store';-import { getPlugin } from '@main/core/providers/plugin-registry';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getLocationAgentsOnServer } from './getAgents';--export type DiscoveredLocationAgent = {- /** The definition/launch name (`.claude/agents/<name>.md` stem, `--agent <name>`). */- name: string;- description: string | null;- /** Whether the definition already carries Switch credentials on disk. */- registered: boolean;- /** The Switch endpoint those credentials name, when they carry one. This is- * which server the existing identity belongs to — an identity can only be- * imported into the server that issued it, so the modal needs it to tell an- * importable row from one that belongs elsewhere (CHOO-2044). Null for a plain- * definition with no Switch setup, which is adoptable anywhere. */- credentialEndpoint: string | null;- /** Whether the definition can join Switch (its tools allowlist keeps the- * Switch MCP tools, or it inherits all tools). */- eligible: boolean;- /** Whether Switch Console already has an agent row for this definition in this dir,- * on the server being onboarded to. */- alreadyAgent: boolean;-};--/**- * Read-only scan of a working directory for the provider's on-disk agent- * definitions (`.claude/agents/*.md`) — used by the Add Agent modal to suggest- * onboarding a directory's existing agents (CHOO-1440). It surfaces BOTH agents- * already set up for Switch (carrying credentials) and plain provider subagents a- * user created directly (no Switch setup yet), so either can be adopted as a- * Switch agent. `alreadyAgent` marks definitions Switch Console already has a row for- * *on `serverId`*, so the modal never offers to re-add them there — while the same- * definition stays offerable to a different server, which is a separate agent- * (CHOO-2044). Works for local and remote (SSH) directories. Returns an empty list- * for a provider with no definition concept.- */-export async function discoverLocationAgents(params: {- sshHost: string | null;- dir: string;- providerId: AgentProviderId;- /** The Switch server being onboarded to — what `alreadyAgent` is judged against. */- serverId: string;-}): Promise<DiscoveredLocationAgent[]> {- const behavior = getPlugin(params.providerId).behavior.repoAgents;- if (!behavior) return [];-- const location = await getLocationByHostDir(params.sshHost, params.dir);- const existing = location- ? new Set((await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name))- : new Set<string>();-- const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);- try {- const definitions = await behavior.discoverDefinitions(workspace.fs);- const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);- const credentialled = new Map(- local.filter((l) => l.switchAgentId !== null).map((l) => [l.name, l.apiEndpoint])- );- return definitions.map((def) => ({- name: def.name,- description: def.description,- registered: def.registered || credentialled.has(def.name),- credentialEndpoint: credentialled.get(def.name) ?? null,- eligible: def.eligible,- alreadyAgent: existing.has(def.name),- }));- } finally {- workspace.close();- }-}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.tsnew file mode 100644index 000000000..1cccb1c9c--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.test.ts@@ -0,0 +1,265 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createPluginFs } from '@main/core/providers/plugin-fs';+import { getPlugin } from '@main/core/providers/plugin-registry';+import {+ decideArtifactSync,+ fingerprintArtifact,+ readAgentConfigFile,+ writeAgentConfigFile,+} from './agent-config-file';+import { acknowledgeDefinition, importAgentConfig } from './import-agent-config';++vi.mock('@main/lib/logger', () => ({+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++let dir: string;++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'switch-console-config-import-'));+});++afterEach(async () => {+ await fs.rm(dir, { recursive: true, force: true });+});++const NAME = 'reviewer';+const DEF_PATH = '.claude/agents/reviewer.md';+const CONFIG_PATH = '.switch/config/reviewer.json';++const claudeRepoAgents = getPlugin('claude').behavior.repoAgents!;++function importClaude(pluginFs = createPluginFs(dir)) {+ return importAgentConfig({+ workspaceFs: pluginFs,+ repoAgents: claudeRepoAgents,+ name: NAME,+ providerConfig: null,+ });+}++/** What an earlier version left behind: the definition it generated, and a+ * config file carrying that definition's fingerprint. */+async function writeGenerated(params: {+ instructions: string;+ description: string;+ settings?: RepoAgentAttributes;+}) {+ const generated = claudeRepoAgents.renderDefinition({+ ...params.settings,+ name: NAME,+ description: params.description,+ instructions: params.instructions,+ });+ await write(DEF_PATH, generated);+ await write(+ CONFIG_PATH,+ JSON.stringify({+ instructions: params.instructions,+ ...(params.settings ? { settings: params.settings } : {}),+ rendered: { [DEF_PATH]: fingerprintArtifact(generated) },+ })+ );+}++async function write(relPath: string, content: string) {+ await fs.mkdir(path.dirname(path.join(dir, relPath)), { recursive: true });+ await fs.writeFile(path.join(dir, relPath), content, 'utf8');+}++async function readRaw(relPath: string) {+ return fs.readFile(path.join(dir, relPath), 'utf8');+}++describe('importAgentConfig', () => {+ it('takes over a definition that predates the config file', async () => {+ await write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: Reviews diffs\nmodel: haiku\n---\n\nBe thorough.\n`+ );++ expect(await importClaude()).toBe(true);++ const config = await readAgentConfigFile(createPluginFs(dir), NAME);+ expect(config?.description).toBe('Reviews diffs');+ expect(config?.instructions).toBe('Be thorough.');+ expect(config?.settings).toMatchObject({ model: 'haiku' });+ });++ it('keeps the config when the definition is still what was generated from it', async () => {+ await writeGenerated({+ instructions: 'From the config.',+ description: 'Reviews diffs',+ settings: { model: 'opus' },+ });++ await importClaude();++ const config = await readAgentConfigFile(createPluginFs(dir), NAME);+ expect(config?.instructions).toBe('From the config.');+ expect(config?.settings).toMatchObject({ model: 'opus' });+ // The description only ever lived in the definition.+ expect(config?.description).toBe('Reviews diffs');+ });++ it('takes over a hand edit made to the definition since it was generated', async () => {+ await writeGenerated({ instructions: 'Generated.', description: 'Reviews diffs' });+ await write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: Reviews diffs\nmodel: haiku\n---\n\nHand written.\n`+ );++ await importClaude();++ const config = await readAgentConfigFile(createPluginFs(dir), NAME);+ expect(config?.instructions).toBe('Hand written.');+ expect(config?.settings).toMatchObject({ model: 'haiku' });+ });++ it('changes nothing when run again over what it already took over', async () => {+ await writeGenerated({ instructions: 'Generated.', description: 'Reviews diffs' });+ await importClaude();+ const first = await readRaw(CONFIG_PATH);++ expect(await importClaude()).toBe(false);+ expect(await readRaw(CONFIG_PATH)).toBe(first);+ });++ it('records the definition it left behind, so an older Console regenerates it', async () => {+ // An older Console still reconciles the two on every read. Without the+ // fingerprint it would take the stale definition for a hand edit and copy+ // it over the config.+ await writeGenerated({ instructions: 'Generated.', description: 'Reviews diffs' });+ await importClaude();+ const pluginFs = createPluginFs(dir);+ const saved = (await readAgentConfigFile(pluginFs, NAME))!;+ await writeAgentConfigFile(pluginFs, NAME, { ...saved, instructions: 'Saved later.' });++ const config = (await readAgentConfigFile(pluginFs, NAME))!;+ expect(+ decideArtifactSync({+ current: await readRaw(DEF_PATH),+ generated: claudeRepoAgents.renderDefinition({+ name: NAME,+ description: config.description ?? '',+ instructions: config.instructions ?? '',+ }),+ lastRendered: config.rendered?.[DEF_PATH],+ })+ ).toBe('write');+ });++ it('leaves alone a config file written over an acknowledged leftover definition', async () => {+ // What adding an agent under a name an earlier agent used writes.+ const pluginFs = createPluginFs(dir);+ await write(DEF_PATH, `---\nname: ${NAME}\ndescription: Stale\n---\n\nStale.\n`);+ await writeAgentConfigFile(+ pluginFs,+ NAME,+ await acknowledgeDefinition({+ workspaceFs: pluginFs,+ repoAgents: claudeRepoAgents,+ name: NAME,+ config: { description: 'Mine', instructions: 'Mine.' },+ })+ );++ await importClaude();++ const config = await readAgentConfigFile(pluginFs, NAME);+ expect(config).toMatchObject({ instructions: 'Mine.' });+ });++ it('drops a hand-typed value this app would not offer', async () => {+ await write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: Reviews diffs\neffort: High\nmaxTurns: 2.5\nmodel: opus\n---\n\nBe thorough.\n`+ );++ await importClaude();++ const config = await readAgentConfigFile(createPluginFs(dir), NAME);+ expect(config?.settings).toMatchObject({ model: 'opus' });+ expect(config?.settings).not.toHaveProperty('effort');+ expect(config?.settings).not.toHaveProperty('maxTurns');+ });++ it('does not take over an empty definition', async () => {+ // A definition cut off mid-write reads as a file with nothing in it; taking+ // that over is what used to blank agents' instructions.+ await writeGenerated({+ instructions: 'Keep me.',+ description: 'Reviews diffs',+ settings: { model: 'opus' },+ });+ await write(DEF_PATH, '');++ await importClaude();++ const config = await readAgentConfigFile(createPluginFs(dir), NAME);+ expect(config?.instructions).toBe('Keep me.');+ expect(config?.settings).toMatchObject({ model: 'opus' });+ });++ it('gives an agent with nothing on disk an empty config file', async () => {+ expect(await importClaude()).toBe(true);+ expect(await readAgentConfigFile(createPluginFs(dir), NAME)).toEqual({});+ });++ it('never writes the definition', async () => {+ const definition = `---\nname: ${NAME}\ndescription: Reviews diffs\n---\n\nTheirs.\n`;+ await write(DEF_PATH, definition);++ await importClaude();++ expect(await readRaw(DEF_PATH)).toBe(definition);+ });++ it('refuses to write over a config file it cannot parse', async () => {+ await write(CONFIG_PATH, '{ not json');++ await expect(importClaude()).rejects.toThrow(/not valid JSON/);+ expect(await readRaw(CONFIG_PATH)).toBe('{ not json');+ });++ it('seeds a config file from the agent row for a provider without definitions', async () => {+ const pluginFs = createPluginFs(dir);+ await importAgentConfig({+ workspaceFs: pluginFs,+ repoAgents: null,+ name: NAME,+ providerConfig: {+ version: '2',+ providerId: 'codex',+ values: { model: 'gpt-5', instructions: 'Be brief.' },+ },+ });++ const config = await readAgentConfigFile(pluginFs, NAME);+ expect(config?.instructions).toBe('Be brief.');+ expect(config?.settings).toEqual({ model: 'gpt-5' });+ });++ it('prefers an existing config file over the agent row', async () => {+ const pluginFs = createPluginFs(dir);+ await write(CONFIG_PATH, JSON.stringify({ instructions: 'From the file.' }));++ expect(+ await importAgentConfig({+ workspaceFs: pluginFs,+ repoAgents: null,+ name: NAME,+ providerConfig: {+ version: '2',+ providerId: 'codex',+ values: { instructions: 'From the row.' },+ },+ })+ ).toBe(false);+ expect((await readAgentConfigFile(pluginFs, NAME))?.instructions).toBe('From the file.');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.tsnew file mode 100644index 000000000..27c7be4d1--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/import-agent-config.ts@@ -0,0 +1,188 @@+import type {+ IRepoAgentsBehavior,+ PluginFs,+ RepoAgentAttributes,+ RepoAgentField,+} from '@switch-console/core/agents/plugins';+import { log } from '@main/lib/logger';+import {+ attributesFromProviderConfig,+ type AgentProviderConfig,+} from '@shared/core/agents/agent-provider-config';+import type { AgentConfigFile } from './agent-config-file';+import {+ decideArtifactSync,+ fingerprintArtifact,+ readAgentConfigFile,+ serialiseAgentConfigFile,+ writeAgentConfigFile,+} from './agent-config-file';+import { agentConfigRelativePath } from './switch-settings-paths';++/**+ * Give an existing agent its config file, taking over whatever an earlier+ * version of this app kept elsewhere.+ *+ * Before the config file was the only record, a Claude Code agent's+ * instructions, settings and description lived in its definition+ * (`.claude/agents/<name>.md`), and a hand edit there was read back into the+ * config on every read. That file is no longer read at launch, so this brings+ * it over:+ * - an edit made there by hand since this app last generated it is taken over,+ * as the old read-back would have;+ * - the description comes from there, since that is the only place it was kept;+ * - a definition with no frontmatter (empty, or cut off mid-write) is not+ * taken over, since there is nothing in it to tell an edit from damage;+ * - a setting whose value this app would not offer (a hand-typed `effort:+ * High`) is left out rather than carried into every launch.+ *+ * The definition file is left where it is, and recorded as accounted for (see+ * {@link acknowledgeDefinition}).+ *+ * A provider without definitions kept its settings on the agent row, which+ * seeds a config file only when there is none.+ *+ * Returns whether the config file was written. Throws when an existing config+ * file cannot be parsed — writing over it would lose what it holds.+ */+export async function importAgentConfig(params: {+ workspaceFs: PluginFs;+ /** Null for a provider with no repository definitions. */+ repoAgents: IRepoAgentsBehavior | null;+ name: string;+ providerConfig: AgentProviderConfig | null;+}): Promise<boolean> {+ const { workspaceFs, repoAgents, name, providerConfig } = params;+ const existing = await readAgentConfigFile(workspaceFs, name);++ const imported = repoAgents+ ? await importDefinition({ workspaceFs, repoAgents, name, existing })+ : (existing ?? fromProviderConfig(providerConfig));++ if (existing && serialiseAgentConfigFile(imported) === serialiseAgentConfigFile(existing)) {+ return false;+ }+ await writeAgentConfigFile(workspaceFs, name, imported);+ return true;+}++/**+ * Record a provider definition left on disk as already reflected in the config.+ *+ * The definition is no longer written, so it goes stale. An older Switch+ * Console sharing the working directory still reconciles the two on every read,+ * and would take a stale definition it has no fingerprint for as a hand edit+ * and copy it over the config. With its fingerprint recorded, that Console sees+ * a definition it generated itself and regenerates it from the config instead.+ */+export async function acknowledgeDefinition(params: {+ workspaceFs: PluginFs;+ repoAgents: IRepoAgentsBehavior | null;+ name: string;+ config: AgentConfigFile;+}): Promise<AgentConfigFile> {+ const { workspaceFs, repoAgents, name, config } = params;+ if (!repoAgents) return config;+ const definitionPath = repoAgents.definitionPath(name);+ const current = await workspaceFs.read(definitionPath);+ if (current === null) return config;+ return {+ ...config,+ rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(current) },+ };+}++async function importDefinition(params: {+ workspaceFs: PluginFs;+ repoAgents: IRepoAgentsBehavior;+ name: string;+ existing: AgentConfigFile | null;+}): Promise<AgentConfigFile> {+ const { workspaceFs, repoAgents, name, existing } = params;+ const config = existing ?? {};+ const acknowledge = (next: AgentConfigFile) =>+ acknowledgeDefinition({ workspaceFs, repoAgents, name, config: next });++ const definitionPath = repoAgents.definitionPath(name);+ const current = await workspaceFs.read(definitionPath);+ if (current === null) return config;++ const attributes = await repoAgents.readDefinition(workspaceFs, name);+ if (attributes === null || !hasFrontmatter(current)) {+ log.warn('importAgentConfig: agent definition has no frontmatter; not importing it', {+ name,+ definitionPath,+ });+ return acknowledge(config);+ }++ const { name: _name, description, instructions, ...settings } = attributes;+ const withDescription: AgentConfigFile = {+ ...config,+ description: typeof description === 'string' ? description : '',+ };++ const action = decideArtifactSync({+ current,+ generated: repoAgents.renderDefinition({+ ...config.settings,+ name,+ description: withDescription.description ?? '',+ instructions: config.instructions ?? '',+ }),+ lastRendered: config.rendered?.[definitionPath],+ });+ if (action !== 'adopt') return acknowledge(withDescription);++ return acknowledge({+ ...withDescription,+ instructions: typeof instructions === 'string' ? instructions : '',+ settings: offeredSettings(name, settings, repoAgents.attributeFields()),+ });+}++/**+ * The settings this app would let someone choose: a choice-list value that is+ * one of its choices, a count that is a positive whole number. Anything else in+ * a hand-edited definition is dropped, and said so.+ */+function offeredSettings(+ name: string,+ settings: RepoAgentAttributes,+ fields: RepoAgentField[]+): RepoAgentAttributes {+ const byKey = new Map(fields.map((field) => [field.key, field]));+ const kept: RepoAgentAttributes = {};+ for (const [key, value] of Object.entries(settings)) {+ const field = byKey.get(key);+ const offered =+ field?.type === 'select'+ ? value === '' || (field.options ?? []).some((option) => option.value === value)+ : field?.type === 'number'+ ? value === null || (typeof value === 'number' && Number.isInteger(value) && value > 0)+ : true;+ if (offered) {+ kept[key] = value;+ } else {+ log.warn('importAgentConfig: dropping a setting this app would not offer', {+ name,+ configPath: agentConfigRelativePath(name),+ key,+ value,+ });+ }+ }+ return kept;+}++function hasFrontmatter(content: string): boolean {+ return /^\uFEFF?---\r?\n[\s\S]*?\r?\n---/.test(content);+}++function fromProviderConfig(providerConfig: AgentProviderConfig | null): AgentConfigFile {+ const { instructions, ...settings } = attributesFromProviderConfig(providerConfig);+ return {+ ...(typeof instructions === 'string' ? { instructions } : {}),+ settings,+ };+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex eb7780a03..7cd9842d6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -80,6 +80,7 @@ const h = vi.hoisted(() => {writeDefinition,discoverLocal,updateAgent: vi.fn(async () => undefined),+ importAgentConfig: vi.fn(async (_params: Record<string, unknown>) => false),completedGeneration: vi.fn(async () => 0),markComplete: vi.fn(async () => undefined),};@@ -100,11 +101,12 @@ vi.mock('./agent-workspace-fs', () => ({}));vi.mock('./getAgents', () => ({ getAgents: vi.fn(async () => h.state.agents) }));vi.mock('./updateAgent', () => ({ updateAgent: h.updateAgent }));+vi.mock('./import-agent-config', () => ({ importAgentConfig: h.importAgentConfig }));vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: vi.fn() }));vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));vi.mock('./agent-storage-migration-marker', () => ({- AGENT_STORAGE_MIGRATION_GENERATION: 2,+ AGENT_STORAGE_MIGRATION_GENERATION: 3,completedAgentStorageMigrationGeneration: h.completedGeneration,markAgentStorageMigrationComplete: h.markComplete,}));@@ -289,7 +291,7 @@ describe('migrateAgentStorage', () => {});it('skips the whole pass (no workspace opened) once the current generation is latched', async () => {- h.completedGeneration.mockResolvedValueOnce(2);+ h.completedGeneration.mockResolvedValueOnce(3);const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;await migrateAgentStorage();@@ -298,19 +300,53 @@ describe('migrateAgentStorage', () => {expect(h.markComplete).not.toHaveBeenCalled();});- it('re-running for generation 2 opens no workspace for a provider generation 1 already did', async () => {- // Generation 2 only broadened the credential step to providers WITHOUT a- // behavior, so re-opening a Claude agent's workspace — an SSH connect and an- // SFTP channel for a remote one — could not change anything.- h.completedGeneration.mockResolvedValueOnce(1);- const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;+ it('re-running after generation 2 skips the credential step but gives every agent a config file', async () => {+ h.completedGeneration.mockResolvedValueOnce(2);+ h.state.workspace = fakeFs({ '.claude/settings.local.json': credsJson('sw-1') });await migrateAgentStorage();- expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();+ expect(h.readLaunchEnv).not.toHaveBeenCalled();+ expect(await h.state.workspace.exists('.switch/agents/cc-hoot-main.json')).toBe(false);+ expect(h.importAgentConfig).toHaveBeenCalledTimes(1);expect(h.markComplete).toHaveBeenCalledTimes(1);});+ it('imports each agent’s config from its definition, or from the row without one', async () => {+ const providerConfig = { version: '2', providerId: 'codex', values: { model: 'gpt-5' } };+ h.state.agents = [{ ...baseAgent, providerConfig: null }];+ h.state.workspace = fakeFs({});++ await migrateAgentStorage();++ expect(h.importAgentConfig.mock.calls[0]?.[0]).toMatchObject({+ name: 'cc-hoot-main',+ repoAgents: h.defaultRepoAgents,+ providerConfig: null,+ });++ vi.clearAllMocks();+ h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot', providerConfig }];+ h.state.repoAgents = null;++ await migrateAgentStorage();++ expect(h.importAgentConfig.mock.calls[0]?.[0]).toMatchObject({+ name: 'codex-hoot',+ repoAgents: null,+ providerConfig,+ });+ });++ it('never writes a provider definition, even for an agent without one', async () => {+ h.state.workspace = fakeFs({ '.switch/agents/cc-hoot-main.json': credsJson('sw-1') });++ await migrateAgentStorage();++ expect(h.writeDefinition).not.toHaveBeenCalled();+ expect(await h.state.workspace.exists('.claude/agents/cc-hoot-main.md')).toBe(false);+ });+it('re-running for generation 2 still migrates a provider generation 1 skipped', async () => {h.completedGeneration.mockResolvedValueOnce(1);h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];@@ -339,7 +375,7 @@ describe('migrateAgentStorage', () => {'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',});- h.readDefinition.mockRejectedValueOnce(new Error('host unreachable'));+ h.importAgentConfig.mockRejectedValueOnce(new Error('host unreachable'));await migrateAgentStorage();diff --git a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.tsindex 51a370cdc..173e72957 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -1,3 +1,4 @@+import type { IRepoAgentsBehavior, PluginFs } from '@switch-console/core/agents/plugins';import { getLocationById } from '@main/core/locations/store';import { getPlugin } from '@main/core/providers/plugin-registry';import {@@ -11,15 +12,17 @@ import {completedAgentStorageMigrationGeneration,markAgentStorageMigrationComplete,} from './agent-storage-migration-marker';+import { markAgentUnmigrated } from './agent-storage-migration-ready';import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgents } from './getAgents';+import { importAgentConfig } from './import-agent-config';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';import { writeNeutralAgentSettingsFs } from './write-switch-settings';/**- * Migrate existing Switch Console-managed agents to the current storage/definition- * layout (CHOO-1440): every agent is a repository-defined agent with a per-agent- * credentials file at `.switch/agents/<name>.json` and an on-disk definition,+ * Migrate existing Switch Console-managed agents to the current storage layout+ * (CHOO-1440): every agent has a per-agent credentials file at+ * `.switch/agents/<name>.json` and a config file at `.switch/config/<name>.json`,* both keyed by the agent's single `name`. Pre-CHOO-1440 installs kept* credentials in the legacy `.claude/switch-subagents/<name>.settings.json` (or* the shared `.claude/settings.local.json`).@@ -45,6 +48,7 @@ export async function migrateAgentStorage(): Promise<void> {if (await migrateOne(agent, completed)) migrated += 1;} catch (error) {allComplete = false;+ markAgentUnmigrated(agent.id);log.warn('migrateAgentStorage: failed to migrate agent', {agentId: agent.id,error: String(error),@@ -72,14 +76,13 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// A provider may have no repo-agent behavior (e.g. Codex): it has no on-disk// definition and no `readLaunchEnv` hook, but its provider-neutral credentials// still need collapsing onto the one name-keyed key-space. So the credential- // migration runs for every provider; its Claude-specific sources, and the- // definition step (2), are behavior-gated.+ // migration runs for every provider; its Claude-specific sources are+ // behavior-gated.const behavior = getPlugin(agent.providerId).behavior.repoAgents;// Generation 2 only broadened step 1 to providers WITHOUT a behavior; for one- // that has it, every step is what generation 1 already ran. Skipping here is- // what keeps the generation bump from re-opening a workspace per Claude agent.- if (completedGeneration >= 1 && behavior) return false;+ // that has it, step 1 is what generation 1 already ran.+ const credentialsDone = completedGeneration >= 2 || (completedGeneration >= 1 && !!behavior);const location = await getLocationById(agent.locationId);if (!location) return false;@@ -90,69 +93,22 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo// stem on disk. It is authoritative — earlier migrations, and the 0041 SQL// backfill, have already collapsed the former `definitionName` onto it.const name = agent.name;- const description = agent.name;let changed = false;-- // 1. Credentials: if the name-keyed neutral file is absent, adopt whatever- // complete credentials already exist on disk *for this agent*, in priority- // order:- // a. a stale ID-keyed neutral file `.switch/agents/<agentId>.json` — an- // earlier layout keyed the neutral file by agent id, not name (this- // includes Codex agents added on the pre-rework id-keyed scheme);- // b. the legacy per-agent file (via readLaunchEnv: name-keyed neutral- // then `.claude/switch-subagents/<name>.settings.json`);- // c. the shared `.claude/settings.local.json` (legacy "main" agent).- // (b) and (c) are Claude-only sources, hence behavior-gated: the shared- // settings file is written solely by `provisionAgent`/`provisionRemoteAgent`,- // always as the Claude "main" agent, so for any other provider it holds a- // *different* agent's identity and token.- // The token is minted once and lives only on disk, so this is the only way- // to recover it — nothing can reconstruct it from the gateway.- const idKeyedRelPath = agentSettingsRelativePath(agent.id);- const namedRelPath = agentSettingsRelativePath(name);- const neutral = name === agent.id ? null : await workspace.fs.read(namedRelPath);- if (neutral === null) {- const recovered =- parseSwitchAgentCredentials(await workspace.fs.read(idKeyedRelPath), log) ??- (behavior ? toCreds(await behavior.readLaunchEnv(workspace.fs, name)) : null) ??- (behavior- ? parseSwitchAgentCredentials(await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log)- : null);- if (recovered && !belongsToAgent(agent, recovered)) {- log.warn('migrateAgentStorage: recovered credentials name a different Switch agent', {- agentId: agent.id,- agentName: name,- providerId: agent.providerId,- expectedSwitchAgentId: agent.switchAgentId,- foundSwitchAgentId: recovered.agentId,- });- } else if (recovered) {- await writeNeutralAgentSettingsFs(workspace.fs, {- slug: name,- apiEndpoint: recovered.apiEndpoint,- apiToken: recovered.token,- agentId: recovered.agentId,- });- changed = true;- }- }-- // Remove the stale ID-keyed neutral file once the name-keyed one is in place:- // an incomplete leftover there otherwise shadows the real creds in the- // session preflight (which scans both), and a complete one is now redundant.- if (name !== agent.id && (await workspace.fs.read(namedRelPath)) !== null) {- if ((await workspace.fs.read(idKeyedRelPath)) !== null) {- await workspace.fs.delete(idKeyedRelPath);- changed = true;- }+ if (!credentialsDone && (await migrateCredentials(agent, workspace.fs, behavior))) {+ changed = true;}- // 2. Definition: ensure the provider has an on-disk definition for this agent- // so it runs as a named repository-defined agent. Behavior providers only —- // a provider without definitions (Codex) has nothing to write here.- if (behavior && (await behavior.readDefinition(workspace.fs, name)) === null) {- await behavior.writeDefinition(workspace.fs, { name, description });+ // 2. Config file: every agent has one, holding what an earlier version kept+ // in its provider definition or on its row.+ if (+ await importAgentConfig({+ workspaceFs: workspace.fs,+ repoAgents: behavior ?? null,+ name,+ providerConfig: agent.providerConfig,+ })+ ) {changed = true;}@@ -162,6 +118,71 @@ async function migrateOne(agent: Agent, completedGeneration: number): Promise<bo}}+async function migrateCredentials(+ agent: Agent,+ fs: PluginFs,+ behavior: IRepoAgentsBehavior | undefined+): Promise<boolean> {+ const name = agent.name;+ let changed = false;++ // 1. Credentials: if the name-keyed neutral file is absent, adopt whatever+ // complete credentials already exist on disk *for this agent*, in priority+ // order:+ // a. a stale ID-keyed neutral file `.switch/agents/<agentId>.json` — an+ // earlier layout keyed the neutral file by agent id, not name (this+ // includes Codex agents added on the pre-rework id-keyed scheme);+ // b. the legacy per-agent file (via readLaunchEnv: name-keyed neutral+ // then `.claude/switch-subagents/<name>.settings.json`);+ // c. the shared `.claude/settings.local.json` (legacy "main" agent).+ // (b) and (c) are Claude-only sources, hence behavior-gated: the shared+ // settings file is written solely by `provisionAgent`/`provisionRemoteAgent`,+ // always as the Claude "main" agent, so for any other provider it holds a+ // *different* agent's identity and token.+ // The token is minted once and lives only on disk, so this is the only way+ // to recover it — nothing can reconstruct it from the gateway.+ const idKeyedRelPath = agentSettingsRelativePath(agent.id);+ const namedRelPath = agentSettingsRelativePath(name);+ const neutral = name === agent.id ? null : await fs.read(namedRelPath);+ if (neutral === null) {+ const recovered =+ parseSwitchAgentCredentials(await fs.read(idKeyedRelPath), log) ??+ (behavior ? toCreds(await behavior.readLaunchEnv(fs, name)) : null) ??+ (behavior+ ? parseSwitchAgentCredentials(await fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log)+ : null);+ if (recovered && !belongsToAgent(agent, recovered)) {+ log.warn('migrateAgentStorage: recovered credentials name a different Switch agent', {+ agentId: agent.id,+ agentName: name,+ providerId: agent.providerId,+ expectedSwitchAgentId: agent.switchAgentId,+ foundSwitchAgentId: recovered.agentId,+ });+ } else if (recovered) {+ await writeNeutralAgentSettingsFs(fs, {+ slug: name,+ apiEndpoint: recovered.apiEndpoint,+ apiToken: recovered.token,+ agentId: recovered.agentId,+ });+ changed = true;+ }+ }++ // Remove the stale ID-keyed neutral file once the name-keyed one is in place:+ // an incomplete leftover there otherwise shadows the real creds in the+ // session preflight (which scans both), and a complete one is now redundant.+ if (name !== agent.id && (await fs.read(namedRelPath)) !== null) {+ if ((await fs.read(idKeyedRelPath)) !== null) {+ await fs.delete(idKeyedRelPath);+ changed = true;+ }+ }++ return changed;+}+/*** Whether recovered credentials are this agent's own. The row's `switchAgentId`* is the authority on which Switch identity the agent has, so a file naming adiff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.tsindex fde36e2f4..41ced4b9c 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts@@ -11,6 +11,7 @@ const { h } = vi.hoisted(() => ({h: {trackEvent: vi.fn(),emit: vi.fn(),+ importAgentConfig: vi.fn(async (_params: Record<string, unknown>) => true),validDirectory: true,detected: { agentId: 'sw-1', apiEndpoint: 'https://switch.example.com' } as {agentId: string;@@ -71,6 +72,13 @@ vi.mock('./setAgentAutoSession', () => ({reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),}));vi.mock('./write-switch-settings', () => ({ writeAgentNeutralSettings: vi.fn(async () => {}) }));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({ fs: {}, close: () => {} })),+}));+vi.mock('./import-agent-config', () => ({ importAgentConfig: h.importAgentConfig }));+vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({ behavior: { repoAgents: { definitionPath: () => '' } } }),+}));const { onboardAgent } = await import('./onboard-agent');@@ -180,3 +188,21 @@ describe('what a failed onboarding reports', () => {expect(JSON.stringify(h.trackEvent.mock.calls)).not.toContain('secret-project');});});++describe('the onboarded agent’s config file', () => {+ it('is created, since every agent has one', async () => {+ const result = await onboardAgent(params());++ expect(result.success).toBe(true);+ expect(h.importAgentConfig).toHaveBeenCalledTimes(1);+ expect(h.importAgentConfig.mock.calls[0]?.[0]).toMatchObject({ name: 'repo' });+ });++ it('is not touched when onboarding fails', async () => {+ h.detected = null;++ await onboardAgent(params());++ expect(h.importAgentConfig).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.tsindex 8aa129be6..17057180d 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts@@ -3,6 +3,7 @@ import { err, ok } from '@switch-console/shared';import { locationManager } from '@main/core/locations/location-manager';import { checkIsValidDirectory } from '@main/core/locations/path-utils';import { ensureLocation } from '@main/core/locations/store';+import { getPlugin } from '@main/core/providers/plugin-registry';import { readSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';@@ -19,9 +20,11 @@ import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';import { detectSwitchAgent } from './detect';import { detectSwitchAgentRemote } from './detect-remote';+import { importAgentConfig } from './import-agent-config';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';import { writeAgentNeutralSettings } from './write-switch-settings';@@ -185,12 +188,30 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA}}+ const name = basenameFromAnyPath(params.dir) || params.providerId;++ // Every agent has a config file. This directory was set up outside this+ // Console, so whatever its Claude Code definition holds becomes the config.+ // Written before the agent row, so a failure here leaves no agent behind that+ // has none.+ const workspace = await resolveWorkspaceFsFor(sshHost, params.dir);+ try {+ await importAgentConfig({+ workspaceFs: workspace.fs,+ repoAgents: getPlugin(params.providerId).behavior.repoAgents ?? null,+ name,+ providerConfig: null,+ });+ } finally {+ workspace.close();+ }+const location = await ensureLocation({ sshHost, dir: params.dir, name: params.name });const agent = await createAgent({id: params.id ?? randomUUID(),locationId: location.id,- name: basenameFromAnyPath(params.dir) || params.providerId,+ name,providerId: params.providerId,switchAgentId: switchAgent.agentId,apiEndpoint: switchAgent.apiEndpoint,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.tsdeleted file mode 100644index 3c8e2304a..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.test.ts+++ /dev/null@@ -1,236 +0,0 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';-import { beforeEach, describe, expect, it, vi } from 'vitest';--const h = vi.hoisted(() => {- class GatewayError extends Error {- constructor(readonly kind: string) {- super(kind);- }- }- const state: {- /** Agent-row names already in the directory, per Switch server. */- agentNamesByServer: Record<string, string[]>;- definitions: Array<{- name: string;- description: string | null;- eligible: boolean;- registered: boolean;- }>;- /** On-disk credentials per definition name. */- local: Array<{ name: string; switchAgentId: string | null; apiEndpoint: string | null }>;- /** Switch agent ids the target server admits to having. */- idsOnServer: string[];- } = { agentNamesByServer: {}, definitions: [], local: [], idsOnServer: [] };- return {- state,- GatewayError,- warn: vi.fn(),- createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input, id: 'agent-row' })),- agentExistsOnServer: vi.fn(async (_server: unknown, agentId: string) =>- h.state.idsOnServer.includes(agentId)- ),- registerAgentIdentity: vi.fn(async () => ({- kind: 'created' as const,- id: 'sw-fresh',- apiKey: 'tok-fresh',- })),- writeNeutralAgentSettings: vi.fn(async () => {}),- openLocation: vi.fn(async () => {}),- emit: vi.fn(),- };-});--vi.mock('@main/core/locations/store', () => ({- ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),-}));-vi.mock('./getAgents', () => ({- getLocationAgentsOnServer: vi.fn(async (_locationId: string, serverId: string) =>- (h.state.agentNamesByServer[serverId] ?? []).map((name) => ({ name }))- ),-}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({- fs: {} as PluginFs,- homeFs: {} as PluginFs,- close: vi.fn(),- })),-}));-vi.mock('@main/core/providers/plugin-registry', () => ({- getPlugin: () => ({- behavior: {- repoAgents: {- discoverDefinitions: async () => h.state.definitions,- discoverLocal: async () => h.state.local,- },- },- }),-}));-vi.mock('@main/core/switch-servers/gateway-client', () => ({- agentExistsOnServer: h.agentExistsOnServer,- GatewayError: h.GatewayError,-}));-vi.mock('@main/core/switch-servers/servers-store', () => ({- getServer: vi.fn(async () => ({- id: 'srv-b',- name: 'Server B',- apiUrl: 'https://b.example.com',- })),- findServerByEndpoint: vi.fn(async (endpoint: string) =>- endpoint === 'https://a.example.com'- ? { id: 'srv-a', name: 'Server A', apiUrl: 'https://a.example.com' }- : null- ),-}));-vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));-vi.mock('./register-agent-identity', () => ({ registerAgentIdentity: h.registerAgentIdentity }));-vi.mock('./write-switch-settings', () => ({- writeNeutralAgentSettingsFs: h.writeNeutralAgentSettings,-}));-vi.mock('./known-agent-type', () => ({ knownAgentTypeForProvider: () => 'claude-code' }));-vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));-vi.mock('@main/core/locations/location-manager', () => ({- locationManager: { openLocation: h.openLocation },-}));-vi.mock('./setAgentAutoSession', () => ({- reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),-}));-vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));-vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: h.warn, error: vi.fn() } }));--const { onboardLocationAgents } = await import('./onboard-location-agents');--const onboard = (names: string[]) =>- onboardLocationAgents({- sshHost: null,- dir: '/repo',- providerId: 'claude',- serverId: 'srv-b',- names,- });--function definition(name: string, registered: boolean) {- return { name, description: null, eligible: true, registered };-}--describe('onboardLocationAgents identity resolution', () => {- beforeEach(() => {- vi.clearAllMocks();- h.state.agentNamesByServer = {};- h.state.definitions = [];- h.state.local = [];- h.state.idsOnServer = [];- });-- it('refuses an identity registered with another server, and writes nothing (CHOO-2044)', async () => {- // The credentials name server A. Server B does not have that id, and the- // tempting fallback — mint a fresh identity — writes back over the same- // credentials file, breaking the agent server A is still running.- h.state.definitions = [definition('test-1', true)];- h.state.local = [- { name: 'test-1', switchAgentId: 'sw-on-a', apiEndpoint: 'https://a.example.com' },- ];- h.state.idsOnServer = [];-- const result = await onboard(['test-1']);-- expect(result.success).toBe(false);- expect(h.registerAgentIdentity).not.toHaveBeenCalled();- expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();- expect(h.createAgent).not.toHaveBeenCalled();- });-- it('names the owning server, not its URL, when Switch Console has it registered', async () => {- h.state.definitions = [definition('test-1', true)];- h.state.local = [- { name: 'test-1', switchAgentId: 'sw-on-a', apiEndpoint: 'https://a.example.com' },- ];-- const result = await onboard(['test-1']);-- expect(result.success).toBe(false);- if (result.success) return;- expect(result.error).toMatchObject({ type: 'error' });- const message = 'message' in result.error ? result.error.message : '';- expect(message).toContain('Server A');- expect(message).toContain('Server B');- expect(message).not.toContain('https://a.example.com');- });-- it('says "another Switch server" rather than a URL for a server it does not know', async () => {- h.state.definitions = [definition('test-1', true)];- h.state.local = [- { name: 'test-1', switchAgentId: 'sw-elsewhere', apiEndpoint: 'https://unknown.example.com' },- ];-- const result = await onboard(['test-1']);-- expect(result.success).toBe(false);- if (result.success) return;- const message = 'message' in result.error ? result.error.message : '';- expect(message).toContain('another Switch server');- expect(message).not.toContain('https://unknown.example.com');- });-- it('imports an identity the target server does have', async () => {- h.state.definitions = [definition('mine', true)];- h.state.local = [- { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },- ];- h.state.idsOnServer = ['sw-on-b'];-- const result = await onboard(['mine']);-- expect(result.success).toBe(true);- expect(h.registerAgentIdentity).not.toHaveBeenCalled();- expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();- expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'mine', switchAgentId: 'sw-on-b', serverId: 'srv-b' })- );- });-- it('still adopts a plain definition that carries no Switch identity', async () => {- // The case adoption exists for: nothing on disk to overwrite, so minting is- // the only way in and is safe.- h.state.definitions = [definition('plain', false)];- h.state.local = [{ name: 'plain', switchAgentId: null, apiEndpoint: null }];-- const result = await onboard(['plain']);-- expect(result.success).toBe(true);- expect(h.registerAgentIdentity).toHaveBeenCalled();- expect(h.writeNeutralAgentSettings).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ slug: 'plain', agentId: 'sw-fresh' })- );- });-- it('reports an unauthenticated server rather than minting past it', async () => {- h.state.definitions = [definition('mine', true)];- h.state.local = [- { name: 'mine', switchAgentId: 'sw-on-b', apiEndpoint: 'https://b.example.com' },- ];- h.agentExistsOnServer.mockRejectedValueOnce(new h.GatewayError('unauthorized'));-- const result = await onboard(['mine']);-- expect(result.success).toBe(false);- if (result.success) return;- expect(result.error).toMatchObject({ type: 'switch-server-unauthenticated' });- expect(h.registerAgentIdentity).not.toHaveBeenCalled();- expect(h.writeNeutralAgentSettings).not.toHaveBeenCalled();- });-- it('offers a definition already onboarded onto another server', async () => {- // Same directory, same name, different server — a separate agent.- h.state.agentNamesByServer = { 'srv-a': ['shared'] };- h.state.definitions = [definition('shared', false)];- h.state.local = [{ name: 'shared', switchAgentId: null, apiEndpoint: null }];-- const result = await onboard(['shared']);-- expect(result.success).toBe(true);- expect(h.createAgent).toHaveBeenCalledWith(- expect.objectContaining({ name: 'shared', serverId: 'srv-b' })- );- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.tsdeleted file mode 100644index e7a5d0218..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-location-agents.ts+++ /dev/null@@ -1,280 +0,0 @@-import { randomUUID } from 'node:crypto';-import { err, ok } from '@switch-console/shared';-import type { Result } from '@switch-console/shared';-import { knownAgentTypeForProvider } from '@main/core/agents/known-agent-type';-import { locationManager } from '@main/core/locations/location-manager';-import { checkIsValidDirectory } from '@main/core/locations/path-utils';-import { ensureLocation } from '@main/core/locations/store';-import { getPlugin } from '@main/core/providers/plugin-registry';-import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';-import { findServerByEndpoint, getServer } from '@main/core/switch-servers/servers-store';-import { log } from '@main/lib/logger';-import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';-import type { Agent } from '@shared/core/agents/agents';-import type { OnboardAgentError } from '@shared/core/agents/onboarding';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';-import { basenameFromAnyPath } from '@shared/path-name';-import { agentEvents } from './agent-events';-import { resolveWorkspaceFsFor, type WorkspaceFs } from './agent-workspace-fs';-import { createAgent } from './createAgent';-import { getLocationAgentsOnServer } from './getAgents';-import { registerAgentIdentity } from './register-agent-identity';-import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';-import { writeNeutralAgentSettingsFs } from './write-switch-settings';--export type OnboardLocationParams = {- sshHost: string | null;- dir: string;- locationName?: string;- providerId: AgentProviderId;- /** The registered Switch server the discovered agents belong to (or are- * adopted onto, for plain provider subagents with no Switch setup yet). */- serverId: string;- /** Definition names to onboard. When omitted, every onboardable definition in- * the directory is onboarded; when given, only these are (the modal's- * multi-select). Names not currently onboardable are ignored. */- names?: string[];-};--export type OnboardLocationResult = Result<Agent[], OnboardAgentError>;--/** The Switch identity an onboarded definition should run under. */-type ResolvedIdentity = { switchAgentId: string; apiEndpoint: string };--/** Map a recoverable registration failure to an onboard error. */-function registrationError(- kind: 'unauthenticated' | 'name-conflict' | 'invalid-name' | 'error',- message: string,- name: string,- server: SwitchServer,- dir: string-): OnboardAgentError {- if (kind === 'unauthenticated') {- return {- type: 'switch-server-unauthenticated',- dir,- serverId: server.id,- serverName: server.name,- };- }- if (kind === 'name-conflict') {- return {- type: 'error',- message: `An agent named "${name}" already exists on ${server.name}. Rename the definition or delete the conflicting agent.`,- };- }- return { type: 'error', message };-}--/**- * Resolve the Switch identity to onboard a definition under: reuse existing- * credentials when their identity still exists on the server, otherwise register- * a fresh identity and write the credentials (adopting a plain subagent).- *- * A definition that already carries credentials naming an identity this server- * does not have belongs to a *different* Switch server, and is refused. Minting a- * fresh identity for it would be the natural-looking fallback and is exactly the- * wrong move: the credentials are written back under the same name, so the other- * server's agent is overwritten on disk and stops working, silently (CHOO-2044).- * Adoption is for definitions with no Switch identity at all.- */-async function resolveIdentity(- name: string,- description: string | null,- ctx: {- server: SwitchServer;- workspace: WorkspaceFs;- credsByName: Map<string, { switchAgentId: string | null; apiEndpoint: string | null }>;- dir: string;- }-): Promise<{ ok: true; identity: ResolvedIdentity } | { ok: false; error: OnboardAgentError }> {- const creds = ctx.credsByName.get(name);- if (creds?.switchAgentId && creds.apiEndpoint) {- try {- if (await agentExistsOnServer(ctx.server, creds.switchAgentId)) {- return {- ok: true,- identity: { switchAgentId: creds.switchAgentId, apiEndpoint: creds.apiEndpoint },- };- }- } catch (cause) {- if (cause instanceof GatewayError && cause.kind === 'unauthorized') {- return {- ok: false,- error: {- type: 'switch-server-unauthenticated',- dir: ctx.dir,- serverId: ctx.server.id,- serverName: ctx.server.name,- },- };- }- throw cause;- }- const owner = await findServerByEndpoint(creds.apiEndpoint);- return {- ok: false,- error: {- type: 'error',- message: `"${name}" is already registered with ${owner ? owner.name : 'another Switch server'} and cannot be imported into ${ctx.server.name}. Onboard it from that server, or create a new agent here under a different name.`,- },- };- }-- // No usable credentials — adopt: mint a fresh identity and write its creds,- // keeping the existing definition file untouched.- const registered = await registerAgentIdentity(ctx.server, {- name,- description: description ?? `Claude Code agent ${name}`,- repoDir: ctx.dir,- autoSession: true,- // This path onboards `.claude/agents/*.md` definitions, so the identity is a- // Claude Code one by construction.- agentType: knownAgentTypeForProvider('claude'),- // Nobody is at a form to choose one, so it starts with the avatar its name- // generates — the same picture it would be shown with anyway.- iconUrl: agentAvatarUrlForName(name),- // The definition file carries no human label, so there is none to adopt.- displayName: null,- });- if (registered.kind !== 'created') {- const message = 'message' in registered ? registered.message : '';- return {- ok: false,- error: registrationError(registered.kind, message, name, ctx.server, ctx.dir),- };- }-- await writeNeutralAgentSettingsFs(ctx.workspace.fs, {- slug: name,- apiEndpoint: ctx.server.apiUrl,- apiToken: registered.apiKey,- agentId: registered.id,- });- return { ok: true, identity: { switchAgentId: registered.id, apiEndpoint: ctx.server.apiUrl } };-}--/**- * Onboard the provider agents defined in a working directory. Every- * `.claude/agents/<name>.md` definition that can join Switch and isn't already a- * Switch Console agent is brought in as a flat agent row (CHOO-1440):- *- * - A definition that already carries valid Switch credentials (registered, and- * its identity still exists on the server) is imported under that identity.- * - A plain provider subagent (a definition with no Switch setup — e.g. one a- * user created directly in Claude Code) is *adopted*: Switch Console mints a Switch- * identity for it and writes its per-agent credentials, leaving the existing- * definition file untouched.- *- * There is no "main" agent — the directory is a flat container of- * repository-defined agents. Local and remote (SSH) directories are both- * supported.- */-export async function onboardLocationAgents(- params: OnboardLocationParams-): Promise<OnboardLocationResult> {- if (params.sshHost === null && !checkIsValidDirectory(params.dir)) {- return err({ type: 'invalid-directory', dir: params.dir, message: 'Invalid directory' });- }-- const server = await getServer(params.serverId);- if (!server) throw new Error(`No Switch server with id ${params.serverId}`);-- const behavior = getPlugin(params.providerId).behavior.repoAgents;- if (!behavior) {- return err({- type: 'invalid-directory',- dir: params.dir,- message: `Provider ${params.providerId} does not define repository agents.`,- });- }-- const location = await ensureLocation({- sshHost: params.sshHost,- dir: params.dir,- name: params.locationName ?? basenameFromAnyPath(params.dir) ?? params.providerId,- });-- const existing = new Set(- (await getLocationAgentsOnServer(location.id, params.serverId)).map((a) => a.name)- );-- const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);- const created: Agent[] = [];- try {- const definitions = await behavior.discoverDefinitions(workspace.fs);- const local = await behavior.discoverLocal(workspace.fs, workspace.homeFs);- const credsByName = new Map(local.map((l) => [l.name, l]));-- // Onboardable = a definition that can join Switch and isn't already a row.- const onboardable = definitions.filter((d) => d.eligible && !existing.has(d.name));- if (onboardable.length === 0) {- return err({- type: 'invalid-directory',- dir: params.dir,- message: `No Claude agents available to onboard in this directory onto ${server.name}.`,- });- }-- // Restrict to the caller's selection (the modal's multi-select) when given;- // otherwise onboard every onboardable definition.- const requested = params.names;- const selected = requested- ? onboardable.filter((d) => requested.includes(d.name))- : onboardable;- if (selected.length === 0) {- return err({- type: 'invalid-directory',- dir: params.dir,- message: 'None of the selected agents are available to onboard in this directory.',- });- }-- for (const def of selected) {- const resolved = await resolveIdentity(def.name, def.description, {- server,- workspace,- credsByName,- dir: params.dir,- });- if (!resolved.ok) return err(resolved.error);-- const agent = await createAgent({- id: randomUUID(),- locationId: location.id,- name: def.name,- providerId: params.providerId,- switchAgentId: resolved.identity.switchAgentId,- apiEndpoint: resolved.identity.apiEndpoint,- serverId: params.serverId,- autoApprove: params.sshHost !== null,- });- existing.add(def.name);- created.push(agent);-- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {- log.warn('onboardLocationAgents: failed to reconcile auto_session', {- agentId: agent.id,- error: String(error),- });- });- }- } finally {- workspace.close();- }-- if (created.length === 0) {- return err({- type: 'invalid-directory',- dir: params.dir,- message: `Every agent in this directory is already onboarded onto ${server.name}.`,- });- }-- await locationManager.openLocation(location);- // Nothing on the way here names a control, and a directory's worth of- // definitions can arrive in one call, so `unknown` is what these are.- for (const agent of created) agentEvents._emit('agent:created', agent, 'unknown');- return ok(created);-}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.tsdeleted file mode 100644index 373e53201..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.test.ts+++ /dev/null@@ -1,239 +0,0 @@-import type { PluginFs } from '@switch-console/core/agents/plugins';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { agentSettingsRelativePath } from './switch-settings-paths';--function fakeFs(seed: Record<string, string> = {}): PluginFs {- const files = new Map(Object.entries(seed));- return {- read: async (p) => files.get(p) ?? null,- write: async (p, c) => void files.set(p, c),- delete: async (p) => void files.delete(p),- exists: async (p) => files.has(p),- list: async () => [...files.keys()],- };-}--const h = vi.hoisted(() => {- const readDefinition = vi.fn(async (fs: PluginFs, name: string) =>- (await fs.read(`.claude/agents/${name}.md`)) === null ? null : { name, description: 'd' }- );- const writeDefinition = vi.fn(async (fs: PluginFs, attrs: { name: string }) => {- await fs.write(`.claude/agents/${attrs.name}.md`, `# ${attrs.name}`);- });- const removeLocal = vi.fn(async (fs: PluginFs, name: string) => {- await fs.delete(`.claude/agents/${name}.md`);- });- const state: {- row: Record<string, unknown> | undefined;- fs: PluginFs;- repoAgents: object | null;- nameTaken: boolean;- } = {- row: undefined,- fs: fakeFs(),- repoAgents: { readDefinition, writeDefinition, removeLocal },- nameTaken: false,- };- return { state, readDefinition, writeDefinition, removeLocal };-});--vi.mock('@main/core/providers/plugin-registry', () => ({- getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),-}));-vi.mock('./agent-location', () => ({- getAgentLocation: vi.fn(async () => ({ sshHost: null, dir: '/repo' })),- getRemoteAgentLocation: vi.fn(async () => null),-}));-vi.mock('./agent-workspace-fs', () => ({- resolveWorkspaceFsFor: vi.fn(async () => ({ fs: h.state.fs, close: vi.fn() })),-}));-vi.mock('./getAgentById', () => ({- getAgentById: vi.fn(async () => ({- id: 'agent-1',- name: 'old-name',- providerId: 'claude',- locationId: 'loc-1',- })),-}));-vi.mock('./agent-name-taken', () => ({- agentNameTaken: vi.fn(async () => h.state.nameTaken),-}));-vi.mock('./connect-remote-agent', () => ({ connectRemoteAgent: vi.fn() }));-vi.mock('./remote-watcher', () => ({ ensureRemoteWatcher: vi.fn(async () => {}) }));-vi.mock('@main/core/agent-runtime/impl/remote-sidecar-launcher', () => ({- killSidecarSession: vi.fn(async () => {}),-}));-vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));-vi.mock('@main/db/client', () => ({- db: {- update: () => ({- set: () => ({ where: () => ({ returning: async () => (h.state.row ? [h.state.row] : []) }) }),- }),- },-}));-vi.mock('@main/db/schema', () => ({ agents: {} }));-vi.mock('./utils', () => ({- mapAgentRowToAgent: (row: Record<string, unknown>) => row,-}));--const { renameAgent } = await import('./renameAgent');--const CREDS = JSON.stringify({- env: { SWITCH_API_ENDPOINT: 'https://s', SWITCH_API_TOKEN: 'tok-123', SWITCH_AGENT_ID: 'sw-1' },-});--describe('renameAgent', () => {- beforeEach(() => {- vi.clearAllMocks();- h.state.nameTaken = false;- h.state.row = { id: 'agent-1', name: 'new-name', providerId: 'claude' };- h.state.repoAgents = {- readDefinition: h.readDefinition,- writeDefinition: h.writeDefinition,- removeLocal: h.removeLocal,- };- });-- it('moves the credentials onto the new name so the minted token is not lost', async () => {- // The token is minted once and lives only in this file; every reader resolves- // it from the agent's current name.- const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });- h.state.fs = fs;-- await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(CREDS);- expect(await fs.exists(agentSettingsRelativePath('old-name'))).toBe(false);- });-- it('moves the credentials for a provider with no repo-agent definitions', async () => {- h.state.repoAgents = null;- const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });- h.state.fs = fs;-- await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(CREDS);- expect(await fs.exists(agentSettingsRelativePath('old-name'))).toBe(false);- });-- it('moves the definition too, so the CLI can still launch as --agent <new name>', async () => {- const fs = fakeFs({- [agentSettingsRelativePath('old-name')]: CREDS,- '.claude/agents/old-name.md': '# old-name',- });- h.state.fs = fs;-- await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- expect(await fs.exists('.claude/agents/new-name.md')).toBe(true);- expect(await fs.exists('.claude/agents/old-name.md')).toBe(false);- });-- it('writes the new files before removing the old ones', async () => {- const order: string[] = [];- const fs = fakeFs({- [agentSettingsRelativePath('old-name')]: CREDS,- '.claude/agents/old-name.md': '# old-name',- });- const write = fs.write.bind(fs);- const del = fs.delete.bind(fs);- fs.write = async (p, c) => {- order.push(`write ${p}`);- return write(p, c);- };- fs.delete = async (p) => {- order.push(`delete ${p}`);- return del(p);- };- h.state.fs = fs;-- await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- // An interruption must leave a recoverable duplicate, never nothing.- const firstDelete = order.findIndex((o) => o.startsWith('delete'));- const lastWrite = order.map((o) => o.startsWith('write')).lastIndexOf(true);- expect(firstDelete).toBeGreaterThan(lastWrite);- });-- it('does not touch the filesystem when the name is unchanged', async () => {- h.state.row = { id: 'agent-1', name: 'old-name', providerId: 'claude' };- const fs = fakeFs({ [agentSettingsRelativePath('old-name')]: CREDS });- h.state.fs = fs;-- await renameAgent({ agentId: 'agent-1', newName: 'old-name' });-- expect(await fs.read(agentSettingsRelativePath('old-name'))).toBe(CREDS);- expect(h.removeLocal).not.toHaveBeenCalled();- });-- it('refuses a name a sibling in the same location already holds', async () => {- // Nothing keys agent state by id: the credentials live at- // `.switch/agents/<name>.json`. Renaming onto a sibling would overwrite that- // sibling's token with this agent's and then delete the original, leaving the- // sibling authenticating to Switch as somebody else.- const SIBLING = JSON.stringify({- env: {- SWITCH_API_ENDPOINT: 'https://s',- SWITCH_API_TOKEN: 'tok-sib',- SWITCH_AGENT_ID: 'sw-2',- },- });- h.state.nameTaken = true;- const fs = fakeFs({- [agentSettingsRelativePath('old-name')]: CREDS,- [agentSettingsRelativePath('new-name')]: SIBLING,- });- h.state.fs = fs;-- const result = await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- expect(result).toEqual({- success: false,- error: { type: 'name-taken', name: 'new-name' },- });- expect(await fs.read(agentSettingsRelativePath('new-name'))).toBe(SIBLING);- expect(await fs.read(agentSettingsRelativePath('old-name'))).toBe(CREDS);- 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 });-- const result = await renameAgent({ agentId: 'agent-1', newName: 'new-name' });-- expect(result.success).toBe(true);- });-});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.tsdeleted file mode 100644index 0e3b3122f..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/renameAgent.ts+++ /dev/null@@ -1,197 +0,0 @@-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 { 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';-import type { Agent, RenameAgentParams } from '@shared/core/agents/agents';-import { agentEvents } from './agent-events';-import { getAgentLocation } from './agent-location';-import { agentNameTaken } from './agent-name-taken';-import { resolveWorkspaceFsFor } from './agent-workspace-fs';-import { getAgentById } from './getAgentById';-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';--async function moveSidecarToNewName(_previous: Agent, renamed: Agent): Promise<void> {- await ensureRemoteWatcher(renamed.id);-}--/**- * 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.- *- * Everything Switch Console writes per agent is keyed by the agent's `name` — the- * Switch credentials at `.switch/agents/<name>.json` and, for a provider with- * repo-agent definitions, the definition the CLI is launched against- * (`--agent <name>`). A rename that only updates the row leaves both behind- * under the old key, and the credentials are unrecoverable: the token is minted- * once and lives nowhere else, so the agent would silently fall back to the- * shared `.claude/settings.local.json` identity — possibly another agent's.- *- * The new files are written before the old ones are removed, so an interruption- * leaves a recoverable duplicate rather than nothing.- *- * Best-effort — a rename must not fail because the VM is unreachable. A failure- * here leaves the agent on its old key, which the next launch reports as missing- * credentials rather than silently mis-authenticating.- */-async function moveProvisionedFiles(previous: Agent, renamed: Agent): Promise<void> {- const from = previous.name ?? previous.id;- const to = renamed.name ?? renamed.id;- if (from === to) return;-- try {- const location = await getAgentLocation(previous);- const ctx = await resolveWorkspaceFsFor(location.sshHost, location.dir);- try {- const creds = await ctx.fs.read(agentSettingsRelativePath(from));- 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;- if (behavior && definition) {- await behavior.writeDefinition(ctx.fs, { ...definition, name: to });- }-- if (creds !== null) await ctx.fs.delete(agentSettingsRelativePath(from));- if (behavior && definition) await behavior.removeLocal(ctx.fs, from);- } finally {- ctx.close();- }-- // A launch profile (Codex) is keyed on the agent name, so the rename orphans- // the old-named one; it is rewritten under the new name on the next launch,- // so just drop the stale file. Reached through its own home filesystem (the- // repo-dir workspace fs above has no writable home for a remote agent).- await removeAgentLaunchProfile(previous, location, from);- } catch (error) {- log.warn('renameAgent: failed to move the agent files to the new name', {- agentId: previous.id,- from,- to,- error: String(error),- });- }-}--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.- *- * The name must be free in the agent's location before anything is written:- * {@link moveProvisionedFiles} writes the credentials to the destination- * unconditionally, so renaming onto a sibling would hand that sibling this- * agent's Switch token and then delete the original.- */-export async function renameAgent(- params: RenameAgentParams-): Promise<Result<Agent, RenameAgentError>> {- const previous = await getAgentById(params.agentId);- if (!previous) return err({ type: 'agent-not-found' });-- if (await agentNameTaken(previous.locationId, params.newName, previous.id)) {- 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` })- .where(eq(agents.id, params.agentId))- .returning();- if (!row) return err({ type: 'agent-not-found' });-- const renamed = mapAgentRowToAgent(row);- if (previous.name !== renamed.name) {- await moveProvisionedFiles(previous, renamed);- await moveSidecarToNewName(previous, renamed);- }- agentEvents._emit('agent:updated', renamed);- return ok(renamed);-}diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.tsindex b7a2dbe99..2cb0acec4 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.test.ts@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({create: vi.fn(),emit: vi.fn(),start: vi.fn(),+ importConfig: vi.fn(),}));vi.mock('@main/core/agents/agent-events', () => ({ agentEvents: { _emit: mocks.emit } }));vi.mock('@main/core/agents/createAgent', () => ({ createAgent: mocks.create }));@@ -18,6 +19,16 @@ vi.mock('@main/core/agents/remote-session-reconciler', () => ({}));vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: mocks.remote }));vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.server }));+vi.mock('@main/core/agents/agent-location', () => ({+ getAgentLocation: async () => ({ id: 'location', dir: '/repo', sshHost: 'vm-1' }),+}));+vi.mock('@main/core/agents/agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: async () => ({ fs: {}, close: () => {} }),+}));+vi.mock('@main/core/agents/import-agent-config', () => ({ importAgentConfig: mocks.importConfig }));+vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({ behavior: { repoAgents: { definitionPath: () => '' } } }),+}));const parent = {id: 'parent',locationId: 'location',@@ -80,3 +91,22 @@ it('surfaces server verification failure before starting the child watcher', asyexpect(mocks.create).not.toHaveBeenCalled();expect(mocks.start).not.toHaveBeenCalled();});++it('gives the subagent a config file from its own definition before creating it', async () => {+ const order: string[] = [];+ mocks.importConfig.mockImplementation(async () => {+ order.push('config');+ return true;+ });+ mocks.create.mockImplementation(async (value) => {+ order.push('row');+ return { ...value, id: 'local-child' };+ });++ await adoptSubagent(parent, 'reviewer', 'child');++ expect(mocks.importConfig).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'reviewer', providerConfig: parent.providerConfig })+ );+ expect(order).toEqual(['config', 'row']);+});diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.tsindex d0f6552ee..5babc8c3b 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/adopt-subagent.ts@@ -1,8 +1,12 @@import { randomUUID } from 'node:crypto';import { agentEvents } from '@main/core/agents/agent-events';+import { getAgentLocation } from '@main/core/agents/agent-location';+import { resolveWorkspaceFsFor } from '@main/core/agents/agent-workspace-fs';import { createAgent } from '@main/core/agents/createAgent';import { getLocationAgentsOnServer } from '@main/core/agents/getAgents';+import { importAgentConfig } from '@main/core/agents/import-agent-config';import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';+import { getPlugin } from '@main/core/providers/plugin-registry';import { fetchAgentDetail } from '@main/core/switch-servers/gateway-client';import { getServer } from '@main/core/switch-servers/servers-store';import type { Agent } from '@shared/core/agents/agents';@@ -28,6 +32,20 @@ export async function adoptSubagent(const remote = await fetchAgentDetail(server, switchAgentId);if (remote.id !== switchAgentId)throw new Error('Switch returned a different subagent identity.');+ // Every agent has a config file; a subagent's comes from its own definition.+ // Written before the row, so a failure leaves no agent behind that has none.+ const location = await getAgentLocation(parent);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ await importAgentConfig({+ workspaceFs: workspace.fs,+ repoAgents: getPlugin(parent.providerId).behavior.repoAgents ?? null,+ name,+ providerConfig: parent.providerConfig,+ });+ } finally {+ workspace.close();+ }const agent = await createAgent({id: randomUUID(),locationId: parent.locationId,diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.tsindex 5876dbed3..8603f44e0 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({readFailure: vi.fn(),exec: vi.fn(),specialization: vi.fn(),+ definition: vi.fn(),+ behavior: {} as Record<string, unknown>,ready: vi.fn(),}));@@ -75,12 +77,17 @@ vi.mock('@main/core/agent-runtime/impl/provider-adapter-registry', () => ({},}));vi.mock('@main/core/agents/agent-launch-config', () => ({- agentLaunchSpecialization: mocks.specialization,+ agentLaunchConfig: async (agentId: string) => ({+ specialization: await mocks.specialization(agentId),+ definition: await mocks.definition(agentId),+ }),}));vi.mock('@main/core/dependencies/host-dependency-store', () => ({hostDependencyStore: { getSelection: async () => undefined },}));-vi.mock('@main/core/providers/plugin-registry', () => ({ getPlugin: () => ({ behavior: {} }) }));+vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({ behavior: mocks.behavior }),+}));vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn() } }));const { SharedAgentRuntime, buildSharedHostConfig } = await import('./shared-agent-runtime');@@ -104,6 +111,8 @@ beforeEach(() => {mocks.persistedRoom.mockResolvedValue(null);vi.clearAllMocks();mocks.specialization.mockResolvedValue({});+ mocks.definition.mockResolvedValue(undefined);+ mocks.behavior = {};mocks.agent.mockResolvedValue({id: 'agent-1',name: 'scout',@@ -252,6 +261,49 @@ it('reads updated model, effort and instructions for each launch', async () => {expect(second.execution?.context).not.toContain('First instructions');});+it('runs a session as the agent definition built from its config file', async () => {+ mocks.definition.mockResolvedValue({ description: 'Reviews diffs', prompt: 'Be careful.' });+ const config = await buildSharedHostConfig(+ session,+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ );+ expect(config.start.input.agentDefinition).toEqual({+ description: 'Reviews diffs',+ prompt: 'Be careful.',+ });+ expect(config.start.input.agentName).toBeTruthy();+ // Nothing on the host's disk is named: the definition file is not read.+ expect(config.execution?.agentDefinition).toBeUndefined();+});++it('runs a subagent watched under its parent from its own definition file', async () => {+ // The parent's config describes the parent, not the subagent.+ mocks.behavior = {+ repoAgents: { definitionPath: (name: string) => `.claude/agents/${name}.md` },+ };+ mocks.definition.mockResolvedValue({ description: 'Parent', prompt: 'Parent prompt.' });+ const config = await buildSharedHostConfig(+ { ...session, agentName: 'helper' },+ { sessionPath: '/work', sessionEnvVars: {} },+ { kind: 'local' } as LocationTransport+ );+ expect(config.start.input.agentDefinition).toBeUndefined();+ expect(config.execution?.agentDefinition).toEqual({+ name: 'helper',+ path: '.claude/agents/helper.md',+ });+});++it('names the agent and the setting when a value cannot be launched with', async () => {+ mocks.definition.mockResolvedValue({ description: 'd', prompt: 'p', effort: 'High' });+ await expect(+ buildSharedHostConfig(session, { sessionPath: '/work', sessionEnvVars: {} }, {+ kind: 'local',+ } as LocationTransport)+ ).rejects.toThrow(/Agent scout has settings its session cannot start with \(effort:/);+});+it('opens the session while auth is pending and submits the initial prompt only after readiness', async () => {let ready = false;mocks.snapshot.mockImplementation(async () => ({diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.tsindex 6bfc96b51..89fb92b33 100644--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts@@ -16,6 +16,7 @@ import { randomUUID } from 'node:crypto';import { join, posix } from 'node:path';import { setTimeout as delay } from 'node:timers/promises';import {+ agentLaunchDefinitionSchema,SessionHostFailedError,sharedConfigSchema,sharedSessionRoot,@@ -25,7 +26,7 @@ import { SWITCH_SKILL_CONTEXT, SWITCH_SKILL_FILE } from '@switch-console/pluginsimport { commandStatusSchema, type Snapshot } from '@switch-console/shared/session-v1';import { providerAdapterRegistry } from '@main/core/agent-runtime/impl/provider-adapter-registry';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';-import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';+import { agentLaunchConfig } from '@main/core/agents/agent-launch-config';import { getAgentById } from '@main/core/agents/getAgentById';import { agentSettingsRelativePath } from '@main/core/agents/switch-settings-paths';import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';@@ -378,7 +379,8 @@ export async function buildSharedHostConfig(): Promise<SharedHostConfig> {const agent = await getAgentById(session.agentId);if (!agent?.switchAgentId) throw new Error('Link the agent to Switch before launching its host.');- const specialization = (await agentLaunchSpecialization(session.agentId)) ?? {};+ const launch = await agentLaunchConfig(session.agentId);+ const specialization = launch.specialization ?? {};if (!providerAdapterRegistry.supports(session.providerId))throw new Error('SDK sessions support Claude Code, Codex, OpenCode, Antigravity and Cursor. Choose one of these providers.'@@ -402,6 +404,8 @@ export async function buildSharedHostConfig(: undefined;const capabilities = providerAdapterRegistry.get(provider).capabilities;const slug = session.agentName ?? agent.name ?? agent.id;+ const subagent = slug !== agent.name;+ const repoAgents = getPlugin(provider).behavior.repoAgents;const profile =provider === 'codex'? getPlugin(provider).behavior.mcp?.launchProfile?.({@@ -445,6 +449,12 @@ export async function buildSharedHostConfig(...(session.providerSessionId? { resume: { nativeSessionId: session.providerSessionId } }: {}),+ ...(launch.definition && !subagent+ ? {+ agentName: slug,+ agentDefinition: parseLaunchDefinition(slug, launch.definition),+ }+ : {}),...(specialization.model? {model: {@@ -482,13 +492,10 @@ export async function buildSharedHostConfig(],...(binaryPath ? { binaryPath } : {}),...(params.shellSetup ? { shellSetup: params.shellSetup } : {}),- ...(getPlugin(provider).behavior.repoAgents- ? {- agentDefinition: {- name: slug,- path: getPlugin(provider).behavior.repoAgents!.definitionPath(slug),- },- }+ // A subagent watched under its parent is Claude Code's own: it has no+ // Switch config of its own yet, so it runs from its definition file.+ ...(subagent && repoAgents+ ? { agentDefinition: { name: slug, path: repoAgents.definitionPath(slug) } }: {}),codexConfig: profile?.files.map((file) => file.content).join('\n') ?? '',// OpenCode loads the skill as a file through its own skill tool; the@@ -512,3 +519,17 @@ async function journalEpoch(agentId: string, sessionId: string): Promise<stringthrow error;}}++/**+ * The launch definition, checked against what the host accepts. A value the+ * host would refuse fails here, naming the agent and the setting, rather than+ * as a validation error from inside the host.+ */+function parseLaunchDefinition(name: string, definition: unknown) {+ const parsed = agentLaunchDefinitionSchema.safeParse(definition);+ if (parsed.success) return parsed.data;+ const problems = parsed.error.issues+ .map((issue) => `${issue.path.join('.') || 'definition'}: ${issue.message}`)+ .join('; ');+ throw new Error(`Agent ${name} has settings its session cannot start with (${problems}).`);+}diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex a21936552..caf6b57d3 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -11,6 +11,7 @@ import { setupApplicationMenu } from './app/menu';import { registerAppScheme, setupAppProtocol } from './app/protocol';import { createMainWindow, getMainWindow } from './app/window';import { bridgeAgentEventsToRenderer } from './core/agents/agent-events-renderer-bridge';+import { setAgentStorageMigrationReady } from './core/agents/agent-storage-migration-ready';import { migrateAgentStorage } from './core/agents/migrate-agent-storage';import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agents/remote-watcher';import { resolveAgentServers } from './core/agents/resolve-servers';@@ -156,6 +157,7 @@ void app.whenReady().then(async () => {const migrationReady = migrateAgentStorage().catch((e) => {log.warn('switch-agents: failed to migrate agent storage layout at boot', { error: e });});+ setAgentStorageMigrationReady(migrationReady);controlService.initialize().catch((e) => {log.error('Failed to start control API service:', e);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 b206cd4bb..711f3b496 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@@ -357,8 +357,8 @@ export const AddAgentModal = observer(function AddAgentModal({};/** Create a brand-new flat agent in the chosen directory (local or remote):- * mint its identity, write its `.claude/agents/<name>.md` definition + its- * per-agent credentials, and create the row — all via `addAgent`. */+ * mint its identity, write its config file + its per-agent credentials, and+ * create the row — all via `addAgent`. */const createNewAgent = async () => {if (!pickState.serverId || !pickState.providerId) return;setCloseGuard(true);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsxindex 6f94cc8d9..96ea0f4b3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/delete-agent-modal.tsx@@ -44,7 +44,7 @@ export function DeleteAgentModal({ agentLabel, sshHost, dir, onSuccess, onClose<span className="font-medium text-foreground">{agentLabel}</span> will be removed fromSwitch Console.{' '}{onThisMachine- ? 'Its sessions stop, and the credentials and definition files Console provisioned for it are deleted. The working directory itself, and everything else in it, are left alone.'+ ? 'Its sessions stop, and the credentials and settings files Console provisioned for it are deleted. The working directory itself, and everything else in it, are left alone.': 'Its working directory, the credentials stored there, and any running sidecar are untouched unless you choose below.'}</p>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsxindex b285b317c..2835a3dc9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx@@ -34,7 +34,7 @@ export function AgentInstructionsSection({const queryClient = useQueryClient();const fieldId = useId();- const { data: saved } = useQuery({+ const { data: saved, error: readError } = useQuery({queryKey: ['agent-instructions', agentId],queryFn: () =>agentId ? rpc.agents.readInstructions({ agentId }) : Promise.resolve<string>(''),@@ -109,8 +109,7 @@ export function AgentInstructionsSection({rpc.agents.updateInstructions({ agentId: agentId as string, instructions }),onSuccess: () => {void queryClient.invalidateQueries({ queryKey: ['agent-instructions', agentId] });- // The instructions are written into the same file as the advanced- // settings, and saving them regenerates the provider's own file.+ // The instructions are written into the same file as the advanced settings.void queryClient.invalidateQueries({ queryKey: ['agent-advanced-config', agentId] });void queryClient.invalidateQueries({ queryKey: ['location-agents', locationId] });},@@ -141,6 +140,24 @@ export function AgentInstructionsSection({if (!agentId) return null;+ // No editor over settings that could not be read: whatever was typed would be+ // saved over a file nobody has seen, or fail to save at all.+ if (readError) {+ const { headline, detail } = describeFailure(+ readError,+ 'Could not read this agent’s settings.'+ );+ return (+ <Field>+ <FieldLabel>Agent instructions</FieldLabel>+ <p role="alert" className="text-sm text-foreground-destructive">+ {headline}+ {detail ? <span className="block text-foreground-muted">{detail}</span> : null}+ </p>+ </Field>+ );+ }+return (<Field><div className="flex items-center justify-between gap-2">diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsxindex d31df1076..0e067d160 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx@@ -163,3 +163,19 @@ describe('an agent’s instructions', () => {expect(updateInstructions).toHaveBeenCalledWith({ agentId: 'agent-1', instructions: '' });});});++describe('when the settings cannot be read', () => {+ it('says so instead of offering an empty box to type over them', async () => {+ readInstructions.mockRejectedValue(+ new Error(+ 'Agent agent-one has no settings file (.switch/config/agent-one.json) in its working directory.'+ )+ );++ const el = await renderPage();++ expect(field(el)).toBeNull();+ expect(el.querySelector('[role="alert"]')?.textContent).toContain('has no settings file');+ expect(updateInstructions).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agents.tsindex 58d073034..2b31eba5a 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agents.ts@@ -55,8 +55,3 @@ export type CreateAgentParams = {/** Optional per-agent provider config set at creation. */providerConfig?: AgentProviderConfig | null;};--export type RenameAgentParams = {- agentId: string;- newName: string;-};diff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex ef739e340..b5a8c373f 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -6,6 +6,23 @@ import type {UserInputAnswers,} from './events';+/**+ * An agent definition in the shape Claude Code's SDK takes it (`AgentDefinition`),+ * restricted to what a Switch agent's settings can set.+ */+export type AgentLaunchDefinition = {+ description: string;+ prompt: string;+ tools?: string[];+ disallowedTools?: string[];+ model?: string;+ effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';+ permissionMode?: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';+ maxTurns?: number;+ background?: boolean;+ memory?: 'user' | 'project' | 'local';+};+/*** How much the agent may do without asking. Maps onto each vendor's own* permission model inside the adapter; orchestration only ever sees this.@@ -49,14 +66,17 @@ export interface ProviderSessionStartInput {/** Extra system-level context appended to whatever the vendor loads itself. */systemContext?: string;/**- * A named agent definition the vendor already knows, which the session should- * run *as* — its system prompt, tool restrictions and model.+ * A named agent definition the session should run *as* — its system prompt,+ * tool restrictions and model. Claude Code's `--agent <name>`.*- * Claude Code's `--agent <name>`, reading `.claude/agents/<name>.md`. Naming a- * definition the vendor cannot find is an error there, so a caller passes this- * only once it knows the definition exists.+ * Without {@link agentDefinition} the vendor must already know the name —+ * Claude Code reads `.claude/agents/<name>.md`, and naming a definition it+ * cannot find is an error there.*/agentName?: string;+ /** The definition of {@link agentName}, handed to the vendor directly instead+ * of read from its own files. */+ agentDefinition?: AgentLaunchDefinition;}export interface ProviderSession {diff --git a/console/packages/agent-providers/src/claude/claude-adapter.test.ts b/console/packages/agent-providers/src/claude/claude-adapter.test.tsindex 6e653964f..a1bdca5c9 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.test.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.test.ts@@ -227,6 +227,22 @@ describe('ClaudeAdapter session lifecycle', () => {expect(bare.options().agent).toBeUndefined();});+ it('hands a definition over directly when the caller carries one', async () => {+ const sdk = createFakeSdk();+ const adapter = new ClaudeAdapter({ query: sdk.query, claudeExecutablePath: '/bin/claude' });+ const definition = { description: 'Reviews diffs', prompt: 'Be careful.', model: 'opus' };+ await adapter.startSession(startInput({ agentName: 'reviewer', agentDefinition: definition }));+ expect(sdk.options().agent).toBe('reviewer');+ expect(sdk.options().agents).toEqual({ reviewer: definition });++ const named = createFakeSdk();+ await new ClaudeAdapter({+ query: named.query,+ claudeExecutablePath: '/bin/claude',+ }).startSession(startInput({ agentName: 'reviewer' }));+ expect(named.options().agents).toBeUndefined();+ });+it('forwards the model and its reasoning effort, ignoring an effort it does not know', async () => {const sdk = createFakeSdk();const adapter = new ClaudeAdapter({ query: sdk.query, claudeExecutablePath: '/bin/claude' });diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.tsindex ac2aec635..c15747c87 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts@@ -396,6 +396,9 @@ export class ClaudeAdapter implements ProviderAdapter {...(permissionMode === 'bypassPermissions' ? { allowDangerouslySkipPermissions: true } : {}),...(executable ? { pathToClaudeCodeExecutable: executable } : {}),...(input.agentName ? { agent: input.agentName } : {}),+ ...(input.agentName && input.agentDefinition+ ? { agents: { [input.agentName]: input.agentDefinition } }+ : {}),...(input.model ? { model: input.model.id } : {}),...(effort ? { effort } : {}),...(input.resume ? { resume: nativeSessionId } : { sessionId: nativeSessionId }),diff --git a/console/packages/agent-providers/src/host/server.ts b/console/packages/agent-providers/src/host/server.tsindex c1e2a2856..71573003a 100644--- a/console/packages/agent-providers/src/host/server.ts+++ b/console/packages/agent-providers/src/host/server.ts@@ -5,7 +5,7 @@ import { join } from 'node:path';import { commandSchema } from '@switch-console/shared/session-v1';import type { Command, Session } from '@switch-console/shared/session-v1';import { z } from 'zod';-import type { ProviderAdapter, ProviderSessionStartInput } from '../adapter';+import type { AgentLaunchDefinition, ProviderAdapter, ProviderSessionStartInput } from '../adapter';import { createAntigravityAdapter } from '../antigravity/antigravity-adapter';import { createClaudeAdapter } from '../claude/claude-adapter';import { createCodexAdapter } from '../codex/codex-adapter';@@ -25,6 +25,22 @@ const mcp = z.discriminatedUnion('transport', [}),z.object({ transport: z.literal('http'), url: z.string(), headers: env.optional() }),]);+/** {@link AgentLaunchDefinition}, checked where it arrives from the launch spec. */+export const agentLaunchDefinitionSchema = z.strictObject({+ description: z.string(),+ prompt: z.string(),+ tools: z.array(z.string()).optional(),+ disallowedTools: z.array(z.string()).optional(),+ model: z.string().min(1).optional(),+ effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).optional(),+ permissionMode: z+ .enum(['default', 'acceptEdits', 'bypassPermissions', 'plan', 'dontAsk', 'auto'])+ .optional(),+ maxTurns: z.number().int().positive().optional(),+ background: z.boolean().optional(),+ memory: z.enum(['user', 'project', 'local']).optional(),+}) satisfies z.ZodType<AgentLaunchDefinition>;+export const startSchema = z.strictObject({provider: z.enum(['claude', 'codex', 'opencode', 'antigravity', 'cursor']),input: z.strictObject({@@ -36,6 +52,7 @@ export const startSchema = z.strictObject({model: z.object({ id: z.string(), options: env.optional() }).optional(),systemContext: z.string().optional(),agentName: z.string().optional(),+ agentDefinition: agentLaunchDefinitionSchema.optional(),resume: z.object({ nativeSessionId: id }).optional(),}),});diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.tsindex 2eb6224cf..7b4636a9f 100644--- a/console/packages/agent-providers/src/host/shared-config.test.ts+++ b/console/packages/agent-providers/src/host/shared-config.test.ts@@ -1,7 +1,7 @@import { mkdtemp, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { expect, it, vi, afterEach } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { executionEnvironment, prepareSharedConfig, sharedConfigSchema } from './shared-config';afterEach(() => vi.unstubAllEnvs());@@ -154,3 +154,84 @@ it('gives Codex the Switch skill as instructions, like the other providers', asyawait rm(root, { recursive: true, force: true });}});++describe('agent definitions in the launch spec', () => {+ const base = (input: Record<string, unknown>, execution: Record<string, unknown> = {}) => ({+ session: {+ sessionId: 'session',+ agentId: 'agent',+ hostId: 'host',+ epoch: 'epoch',+ provider: 'claude',+ status: 'starting',+ connectivity: 'online',+ pendingRequestIds: [],+ capabilities: {+ input: 'queue',+ approvals: true,+ questions: true,+ interrupt: true,+ reset: false,+ compact: false,+ modelChange: false,+ attachmentMimeTypes: [],+ },+ },+ start: {+ provider: 'claude',+ input: {+ sessionId: 'session',+ cwd: '/repo',+ runtimeMode: 'approval-required',+ env: {},+ mcpServers: {},+ ...input,+ },+ },+ execution: {+ credentialsPath: '/repo/.switch/agents/reviewer.json',+ inheritEnv: [],+ codexConfig: '',+ skill: '',+ context: '',+ ...execution,+ },+ });++ it('carries a definition handed over directly', () => {+ const config = sharedConfigSchema.parse(+ base({+ agentName: 'reviewer',+ agentDefinition: { description: 'Reviews diffs', prompt: 'Be careful.', maxTurns: 3 },+ })+ );+ expect(config.start.input.agentDefinition).toEqual({+ description: 'Reviews diffs',+ prompt: 'Be careful.',+ maxTurns: 3,+ });+ });++ it('still reads a session saved by a Console that named a definition file', () => {+ // Sessions relaunch from the spec they were saved with, so the old shape has+ // to keep parsing after the host is upgraded.+ const config = sharedConfigSchema.parse(+ base({}, { agentDefinition: { name: 'reviewer', path: '.claude/agents/reviewer.md' } })+ );+ expect(config.execution?.agentDefinition).toEqual({+ name: 'reviewer',+ path: '.claude/agents/reviewer.md',+ });+ });++ it('rejects a definition field the SDK would not understand', () => {+ expect(() =>+ sharedConfigSchema.parse(+ base({+ agentName: 'reviewer',+ agentDefinition: { description: 'd', prompt: 'p', color: 'blue' },+ })+ )+ ).toThrow();+ });+});diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.tsindex 5e38fc236..fa555d542 100644--- a/console/packages/agent-providers/src/host/shared-config.ts+++ b/console/packages/agent-providers/src/host/shared-config.ts@@ -38,6 +38,11 @@ export const sharedConfigSchema = z.strictObject({codexConfig: z.string(),skill: z.string(),context: z.string(),+ /**+ * A definition on the host's disk to run as, named by an earlier Console.+ * Sessions saved then still relaunch from it; a current Console hands the+ * definition over in `start.input` instead.+ */agentDefinition: z.strictObject({ name: z.string().min(1), path: z.string().min(1) }).optional(),diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex cd009fbb5..a456e8106 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -1,4 +1,5 @@export type {+ AgentLaunchDefinition,HttpMcpServerSpec,McpServerSpec,ModelSelection,@@ -44,6 +45,7 @@ export type { CursorAdapterOptions } from './cursor/cursor-adapter';export { ChatProjector } from './session-v1/chat-projector';export { EventOutbox } from './session-v1/event-outbox';export { HostConnection } from './host/client';+export { agentLaunchDefinitionSchema } from './host/server';export type { HostEndpoint, HostStartRequest } from './host/server';export { connectHost } from './host/launcher';export { runSharedHost } from './host/shared-host';diff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 5bfc7052f..2e96fc14a 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -118,6 +118,13 @@ export type RepoAgentAttributeValue = string | string[] | number | boolean | nul* `name` and `description`; the rest are provider-defined. */export type RepoAgentAttributes = Record<string, RepoAgentAttributeValue>;+/**+ * The definition a session runs as, in the shape the provider's SDK takes it.+ * Provider-specific; JSON-serialisable, since it travels in the launch spec to+ * the host that starts the session.+ */+export type RepoAgentLaunchDefinition = Record<string, string | string[] | number | boolean>;+/*** How an agent provider creates, runs, and credentials the named agents defined* in a working directory. Switch Console has no notion of "subagents" — it just asks@@ -154,6 +161,11 @@ export type IRepoAgentsBehavior = {renderDefinition(attributes: RepoAgentAttributes): string;/** The definition file's path, relative to the working directory. */definitionPath(name: string): string;+ /**+ * The definition a session runs as, built from these attributes and handed to+ * the provider's SDK directly, so nothing is read from disk at launch. Pure.+ */+ launchDefinition(attributes: RepoAgentAttributes): RepoAgentLaunchDefinition;/** Create or overwrite a named agent's on-disk definition from its attributes* (workspace scope). `attributes.name` selects the agent. */writeDefinition(workspaceFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;diff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.tsindex 95cdda858..167f49d43 100644--- a/console/packages/core/src/agents/plugins/index.ts+++ b/console/packages/core/src/agents/plugins/index.ts@@ -82,6 +82,7 @@ export type {IRepoAgentsBehavior,LocalRepoAgent,RepoAgentAttributes,+ RepoAgentLaunchDefinition,RepoAgentAttributeValue,RepoAgentDefinition,RepoAgentField,diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 785b787db..367ca65ff 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -308,3 +308,69 @@ describe('claudeRepoAgentsBehavior.removeLocal', () => {expect(await workspaceFs.exists(neutralRel)).toBe(true);});});++describe('claudeRepoAgentsBehavior.launchDefinition', () => {+ it('builds the same agent the definition file described, for the SDK', () => {+ expect(+ claudeRepoAgentsBehavior.launchDefinition({+ name: 'reviewer',+ description: 'Reviews diffs',+ model: 'opus',+ effort: 'high',+ permissionMode: 'acceptEdits',+ maxTurns: 12,+ background: true,+ memory: 'project',+ instructions: 'You are a careful reviewer.',+ })+ ).toEqual({+ description: 'Reviews diffs',+ prompt: 'You are a careful reviewer.',+ model: 'opus',+ effort: 'high',+ permissionMode: 'acceptEdits',+ maxTurns: 12,+ background: true,+ memory: 'project',+ });+ });++ it('keeps the Switch tools in a tools allowlist and out of the deny list', () => {+ const definition = claudeRepoAgentsBehavior.launchDefinition({+ name: 'reviewer',+ description: 'Reviews diffs',+ tools: ['Read', 'Grep'],+ disallowedTools: ['Write', 'mcp__switch'],+ });++ expect(definition.tools).toEqual(['Read', 'Grep', 'mcp__switch']);+ expect(definition.disallowedTools).toEqual(['Write']);+ });++ it('leaves out what was not set, so the session keeps its own defaults', () => {+ expect(+ claudeRepoAgentsBehavior.launchDefinition({+ name: 'reviewer',+ description: 'Reviews diffs',+ model: '',+ tools: [],+ disallowedTools: [],+ maxTurns: null,+ background: false,+ color: 'blue',+ isolation: 'worktree',+ })+ ).toEqual({ description: 'Reviews diffs', prompt: 'Reviews diffs' });+ });++ it('uses the description as the prompt when there are no instructions', () => {+ // As the definition file did: its body could not be empty.+ expect(+ claudeRepoAgentsBehavior.launchDefinition({+ name: 'reviewer',+ description: 'Reviews\ndiffs',+ instructions: '',+ })+ ).toEqual({ description: 'Reviews diffs', prompt: 'Reviews diffs' });+ });+});diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.ts b/console/packages/plugins/src/agents/impl/claude/subagents.tsindex c15828049..1a62280a1 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.ts@@ -6,6 +6,7 @@ import {type RepoAgentAttributes,type RepoAgentDefinition,type RepoAgentField,+ type RepoAgentLaunchDefinition,RECOGNISED_SWITCH_TOOL_RULES,SWITCH_AGENT_SETTINGS_DIR,SWITCH_TOOL_RULES,@@ -246,6 +247,57 @@ function parseFrontmatter(content: string): SubagentFrontmatter {};}+/**+ * Frontmatter keys the SDK's agent definition has no equivalent for: `color`+ * only tints the agent's name in the terminal, and `isolation` gives a delegated+ * subagent its own worktree, which means nothing for the session's own thread.+ */+const TERMINAL_ONLY_KEYS = new Set(['color', 'isolation']);++/**+ * The SDK agent definition for these attributes — the same agent+ * {@link serializeDefinition} writes to disk, handed over directly instead.+ *+ * Mirrors it rule for rule: the Switch tools are merged into a non-empty+ * `tools` allowlist and never denied, empty values are left out so the+ * session's own defaults apply, and the description stands in as the prompt+ * when there are no instructions.+ */+function launchDefinitionFor(attributes: RepoAgentAttributes): RepoAgentLaunchDefinition {+ const description = toScalar(attributes.description).replace(/\s*\r?\n\s*/g, ' ');+ const definition: RepoAgentLaunchDefinition = {+ description,+ prompt: toScalar(attributes[BODY_KEY]) || description,+ };++ for (const key of FRONTMATTER_FIELD_KEYS) {+ if (TERMINAL_ONLY_KEYS.has(key)) continue;+ const raw = attributes[key];+ if (key === 'tools') {+ const list = toList(raw);+ if (list.length > 0) definition.tools = dedupe([...list, ...SWITCH_TOOL_RULES]);+ continue;+ }+ if (key === 'disallowedTools') {+ const list = toList(raw).filter((t) => !SWITCH_RULES.includes(t));+ if (list.length > 0) definition.disallowedTools = list;+ continue;+ }+ if (BOOLEAN_KEYS.has(key)) {+ if (raw === true || raw === 'true') definition[key] = true;+ continue;+ }+ if (NUMBER_KEYS.has(key)) {+ const n = typeof raw === 'number' ? raw : raw ? Number(raw) : NaN;+ if (Number.isFinite(n) && n > 0) definition[key] = n;+ continue;+ }+ const scalar = toScalar(raw);+ if (scalar.length > 0) definition[key] = scalar;+ }+ return definition;+}+/** The markdown body after the leading frontmatter fence (empty when none). */function extractBody(content: string): string {const normalised = content.replace(/^/, '');@@ -491,6 +543,10 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return definitionRelPath(name);},+ launchDefinition(attributes: RepoAgentAttributes): RepoAgentLaunchDefinition {+ return launchDefinitionFor(attributes);+ },+async writeDefinition(workspaceFs, attributes: RepoAgentAttributes): Promise<void> {const name = toScalar(attributes.name);await workspaceFs.write(definitionRelPath(name), serializeDefinition(attributes));