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
Make adding an agent CLI a plugin entry and ACP hooks (CHOO-3325) (#763)
Louis Amaudruz8a9721ebd26f
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 000000000..c14b725e6--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,33 @@+## What this changes++<!-- One or two sentences: what changes for someone using Switch, and why. -->++## How it was tested++<!-- What you ran or tried, and what you saw. -->++---++## Adding or changing an agent CLI++<!--+Only for a pull request that adds support for an agent CLI or changes one.+Otherwise delete this section. How to do each step:+console/docs/new-agent-cli.md+-->++**CLI and version:**++**Real-CLI test summary** (paste what+`pnpm exec vitest run src/<your-cli>/<your-cli>.integration.test.ts` prints at the end):++```+paste here+```++**Video** (link or attachment). It shows:++- [ ] the CLI marked as signed in, in Switch Console+- [ ] creating an agent with it and picking a model+- [ ] the agent replying in a room+- [ ] a shell command asking for permission firstdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b838973e7..5ddd47393 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -75,6 +75,13 @@ module structure and the key request flows.setting up bring-your-own OIDC sign-in for the gateway, including the WorkOSsetup path.+## Adding an agent CLI++Start with [Adding support for a new agent CLI](console/docs/new-agent-cli.md):+the steps in order, and what your pull request has to show (a real-CLI test+summary and a short video). The technical details are in+[Add an agent provider](console/docs/add-an-agent-provider.md).+## TestingTests live in `core/tests/switch_core/` and mirror the module structure. Thediff --git a/console/AGENTS.md b/console/AGENTS.mdindex 600b59202..dd2b873f9 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -592,8 +592,9 @@ and durable command receipts across redeployment.- Access mounted locations through `asMounted(getLocationStore(id))`, not inline guards.- Session selectors live in `src/renderer/features/sessions/stores/session-selectors.ts`.- Location selectors live in `src/renderer/features/locations/stores/location-selectors.ts`.-- For provider changes, update shared provider metadata, SDK host env passthrough if needed,- hook/plugin integrations, renderer assumptions, and tests for non-standard behavior.+- For provider changes, follow [Add an agent provider](docs/add-an-agent-provider.md): the+ plugin, the runtime registration (with its env passthrough), and tests for non-standard+ behavior. Nothing else should need to name the provider.- For MCP changes, keep canonical data in shared types and adapt provider formats at edges.- Run the local merge gate before merging:@@ -606,11 +607,13 @@ pnpm run test## Extensibility Hooks-- Agent providers are defined in `packages/plugins/src/agents/impl/<id>/index.ts`.- `src/shared/core/providers/agent-provider-registry.ts` holds the id list, per-provider- display metadata, and a mirror of each provider's argv shape. The mirror is- descriptive: nothing reads it at spawn time, so change the plugin first and update the- mirror to match. `provider-argv-parity.test.ts` pins Codex's.+- An agent provider registers in two places, each with one line: its plugin in+ `packages/plugins/src/agents/plugin-registry.ts` (display metadata, detection, install,+ icon) and its runtime in `packages/agent-providers/src/providers/registry.ts` (adapter,+ sign-in check, login command). An ACP CLI's runtime is made from its hooks on the generic+ ACP adapter. `src/shared/core/providers/agent-provider-registry.ts` is the catalogue the+ app builds from both at startup; nothing in the app lists provider ids. See+ [Add an agent provider](docs/add-an-agent-provider.md).- **The Switch skill every session receives** lives in`packages/plugins/src/switch-skill/SKILL.md`, the one copy Console pushes toevery host (system context for Claude Code, Cursor and Antigravity; adiff --git a/console/agents/architecture/shared.md b/console/agents/architecture/shared.mdindex af8a7f471..a05770e73 100644--- a/console/agents/architecture/shared.md+++ b/console/agents/architecture/shared.md@@ -45,9 +45,15 @@ Aliases are resolved at build time by electron-vite. No runtime monkey-patchingWhen adding a provider:-1. add the plugin under `packages/plugins/src/agents/impl/<id>/index.ts`-2. add the id to `AGENT_PROVIDER_IDS` and a display entry to `AGENT_PROVIDERS` in- `src/shared/core/providers/agent-provider-registry.ts`-3. add any required env passthrough in `packages/agent-providers/src/host/agent-env.ts`-4. update renderer surfaces that assume provider metadata-5. add tests for non-standard spawn or detection behavior+Follow [Add an agent provider](../../docs/add-an-agent-provider.md). In short:++1. add the plugin under `packages/plugins/src/agents/impl/<id>/` and register it in+ `packages/plugins/src/agents/plugin-registry.ts`+2. add the runtime to `PROVIDER_RUNTIMES` in `packages/agent-providers/src/providers/registry.ts`+ (for an ACP CLI, `acpProviderRuntime(<hooks>)`), including any env passthrough in its+ `inheritEnv`+3. add the provider to core's provider table+4. add the conformance suite and tests for non-standard spawn or detection behavior++`src/shared/core/providers/agent-provider-registry.ts` is a catalogue built at startup from+the plugins and runtimes; do not add ids or per-provider data to it.diff --git a/console/agents/integrations/providers.md b/console/agents/integrations/providers.mdindex 4bafbc080..be3d6dacc 100644--- a/console/agents/integrations/providers.md+++ b/console/agents/integrations/providers.md@@ -7,10 +7,16 @@ Local and SSH locations use the same persistent SDK host.## Source of truth- `packages/agent-providers/src/` owns native SDK/protocol execution.-- `packages/plugins/src/agents/impl/<id>/` owns CLI detection, installation,- native skills, MCP configuration and launch profiles.-- `src/shared/core/providers/agent-provider-registry.ts` owns supported IDs and- display metadata. Unsupported stored IDs must fail explicitly.+ `src/providers/registry.ts` (`PROVIDER_RUNTIMES`) is the list of providers the+ execution host runs, with each one's adapter, sign-in check, login command and+ env passthrough. ACP CLIs run on the generic adapter in `src/acp/`, with a+ hooks file each.+- `packages/plugins/src/agents/impl/<id>/` owns display metadata, CLI detection,+ installation, native skills, MCP configuration and launch profiles; the+ registration list is `plugin-registry.ts`.+- `src/shared/core/providers/agent-provider-registry.ts` is the catalogue built+ from both at startup. Unsupported stored IDs must fail explicitly.+- Adding a provider: [Add an agent provider](../../docs/add-an-agent-provider.md).- `src/main/core/sdk-host/` handles deployment and the desktop host client.- `packages/agent-providers/src/host/` owns persistent execution and recovery.@@ -23,8 +29,10 @@ reported explicitly rather than replaced with synthetic prompts.## Changing providers-Keep the adapter, plugin metadata, desktop registry, and host environment in-sync. The environment allowlist is `packages/agent-providers/src/host/agent-env.ts`, shared by Console and the headless agents controller.+The plugin and runtime registrations must name the same providers; Console and+the agents controller refuse to start otherwise. The shared environment+allowlist is `packages/agent-providers/src/host/agent-env.ts`, plus each+runtime's `inheritEnv`, used by Console and the headless agents controller.Keep MCP helpers shared when retained providers import them. Model cataloguescome from the provider on the execution host. Test both local and SSH setup;credentials and native configuration belong to that host.diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.tsindex 716eb898a..dcd5683b2 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/agent-migration.ts@@ -34,6 +34,7 @@ import { postRoomMessage } from '@main/core/switch-rooms/switch-room-client';import {AgentManagementUnavailableError,deleteManagedAgent,+ fetchAdvancedConfigSchema,fetchAgentDetail,fetchManagedAgent,fetchManagementControllers,@@ -50,6 +51,7 @@ import { withReachableWorkspaceSession } from '@main/core/workspaces/workspace-simport { events } from '@main/lib/events';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';+import type { AdvancedConfigField } from '@shared/core/managed-agents/managed-agents';import { agentMigrationChannel } from '@shared/events/agentMigrationEvents';import {AgentMigrationService,@@ -567,7 +569,25 @@ const credentials: MigrationCredentialsPort = {},};+/** The advanced configuration fields the agent's server takes for its provider. */+async function serverAdvancedFields(agent: MigrationAgent): Promise<AdvancedConfigField[]> {+ if (!agent.workspaceId)+ throw new Error(+ `${agent.name} belongs to no Switch workspace, so its server's advanced configuration fields cannot be read.`+ );+ const schema = await withReachableWorkspaceSession(agent.workspaceId, (server) =>+ fetchAdvancedConfigSchema(server)+ );+ const fields = schema[agent.providerId];+ if (!fields)+ throw new Error(+ `The Switch server does not list the provider ${agent.providerId}, so it cannot run ${agent.name}.`+ );+ return fields;+}+async function buildDefinition(agent: MigrationAgent) {+ const advancedFields = await serverAdvancedFields(agent);const row = await requireRow(agent.id);const location = await getAgentLocation(row);const transport = locationTransport(location);@@ -586,6 +606,7 @@ async function buildDefinition(agent: MigrationAgent) {);return buildManagedDefinition({providerId: agent.providerId,+ advancedFields,name: agent.name,specialization: launch.specialization,providerDefinition: launch.definition,diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.test.tsindex b7bcfd66d..e8b494eed 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.test.ts@@ -1,12 +1,40 @@import { describe, expect, it } from 'vitest';+import type { AdvancedConfigField } from '@shared/core/managed-agents/managed-agents';import {buildManagedDefinition,type DefinitionSource,MAX_INSTRUCTIONS_BYTES,} from './managed-definition';+const select = (key: string, label: string, values: string[]): AdvancedConfigField => ({+ key,+ label,+ type: 'select',+ options: [{ value: '', label: 'Default' }, ...values.map((value) => ({ value, label: value }))],+});++/** The server's fields for each provider, as far as these tests need them. */+const SERVER_FIELDS: Record<string, AdvancedConfigField[]> = {+ claude: [+ { key: 'tools', label: 'Tools', type: 'list' },+ select('permissionMode', 'Permission mode', ['default', 'acceptEdits', 'plan']),+ { key: 'maxTurns', label: 'Max turns', type: 'number' },+ { key: 'background', label: 'Always run in background', type: 'boolean' },+ select('effort', 'Effort', ['low', 'medium', 'high', 'xhigh', 'max']),+ ],+ codex: [+ select('effort', 'Reasoning effort', ['none', 'low', 'medium', 'high', 'xhigh', 'max']),+ select('verbosity', 'Verbosity', ['low', 'medium', 'high']),+ ],+ opencode: [+ { key: 'variant', label: 'Reasoning variant', type: 'text' },+ { key: 'temperature', label: 'Temperature', type: 'number' },+ ],+};+const SOURCE: DefinitionSource = {providerId: 'claude',+ advancedFields: SERVER_FIELDS.claude,name: 'builder',specialization: undefined,providerDefinition: undefined,@@ -66,6 +94,7 @@ describe('the managed definition of a Console agent', () => {buildManagedDefinition({...SOURCE,providerId: 'opencode',+ advancedFields: SERVER_FIELDS.opencode,specialization: { model: 'anthropic/claude', variant: 'max', temperature: '0.2' },}).definition.advanced_config).toEqual({ variant: 'max', temperature: 0.2 });@@ -75,16 +104,29 @@ describe('the managed definition of a Console agent', () => {const built = buildManagedDefinition({...SOURCE,providerId: 'codex',+ advancedFields: SERVER_FIELDS.codex,specialization: { effort: 'extreme', verbosity: 'low' },});expect(built.definition.advanced_config).toEqual({ verbosity: 'low' });expect(built.notCarried).toEqual([expect.stringContaining('Reasoning effort (“extreme”)')]);});+ it('carries no advanced configuration for a provider the server takes none for', () => {+ const built = buildManagedDefinition({+ ...SOURCE,+ providerId: 'cursor',+ advancedFields: [],+ specialization: { model: 'auto', instructions: 'Build.' },+ });+ expect(built.definition).toMatchObject({ model: 'auto', advanced_config: {} });+ expect(built.notCarried).toEqual([]);+ });+it('lists the other launch settings, shell setup and a chosen CLI', () => {const built = buildManagedDefinition({...SOURCE,providerId: 'codex',+ advancedFields: SERVER_FIELDS.codex,specialization: { sandbox: 'workspace-write', approval: 'never', empty: '' },shellSetup: true,chosenBinary: '/opt/codex/bin/codex',diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.tsindex a36212839..2f4879f97 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/managed-definition.ts@@ -1,14 +1,11 @@import { isDeepStrictEqual } from 'node:util';-import type {- RepoAgentField,- RepoAgentLaunchDefinition,-} from '@switch-console/core/agents/plugins';+import type { RepoAgentLaunchDefinition } from '@switch-console/core/agents/plugins';import {type AdvancedConfig,type AdvancedConfigValue,- advancedConfigFields,sessionLaunchConfig,} from '@switch-console/plugins/agents';+import type { AdvancedConfigField } from '@shared/core/managed-agents/managed-agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';/**@@ -42,7 +39,7 @@ export function assertInstructionsFit(instructions: string): void {const TOP_LEVEL_KEYS = new Set(['model', 'instructions']);/** A specialisation value (always a string) as the value its field takes, or null when it is not one. */-function fieldValue(field: RepoAgentField, text: string): AdvancedConfigValue | null {+function fieldValue(field: AdvancedConfigField, text: string): AdvancedConfigValue | null {switch (field.type) {case 'list': {const items = text@@ -69,14 +66,15 @@ function fieldValue(field: RepoAgentField, text: string): AdvancedConfigValue |/*** The advanced configuration an agent's launch specialisation amounts to, for- * the provider's fields, and what of it has no managed equivalent, said for a- * person.+ * the fields the server takes for its provider, and what of it has no managed+ * equivalent, said for a person.*/export function advancedConfigFromSpecialization(providerId: AgentProviderId,+ advancedFields: AdvancedConfigField[],specialization: Record<string, string | undefined>): { advancedConfig: AdvancedConfig; notCarried: string[] } {- const fields = new Map(advancedConfigFields(providerId).map((field) => [field.key, field]));+ const fields = new Map(advancedFields.map((field) => [field.key, field]));const advancedConfig: AdvancedConfig = {};const unknown: string[] = [];const notCarried: string[] = [];@@ -102,6 +100,8 @@ export function advancedConfigFromSpecialization(export type DefinitionSource = {providerId: AgentProviderId;+ /** The advanced configuration fields the server takes for the provider. */+ advancedFields: AdvancedConfigField[];/** The name the managed agent runs under. */name: string;/** The agent's launch specialisation (`agentLaunchConfig`), or undefined when it sets none. */@@ -140,6 +140,7 @@ export function buildManagedDefinition(source: DefinitionSource): BuiltDefinitioconst specialization = source.specialization ?? {};const { advancedConfig, notCarried } = advancedConfigFromSpecialization(source.providerId,+ source.advancedFields,specialization);if (source.shellSetup)diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.test.tsindex 3cc972109..5d8b16aed 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.test.ts@@ -140,14 +140,20 @@ describe('NewManagedAgentService.add', () => {});});- it('refuses an advanced configuration field the provider does not offer, naming it', async () => {+ it('leaves the advanced configuration for Switch to judge against its own fields', async () => {+ h.set({+ createOutcome: {+ kind: 'refused',+ message: "advanced_config: codex has no setting 'tools' (it takes effort, verbosity)",+ },+ });const result = await new NewManagedAgentService(h.deps).add({...PARAMS,providerId: 'codex',advancedConfig: { tools: ['Read'] },});+ expect(h.created).toHaveLength(1);expect(result).toEqual({ kind: 'error', message: expect.stringContaining("'tools'") });- expect(h.created).toEqual([]);});it('refuses instructions longer than a managed agent takes, before creating anything', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.tsindex 472dc2faa..12c0a1a46 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-migration/new-managed-agent-service.ts@@ -1,4 +1,4 @@-import { type AdvancedConfig, advancedConfigProblem } from '@switch-console/plugins/agents';+import type { AdvancedConfig } from '@switch-console/plugins/agents';import type { NewAgentMachine } from '@shared/core/agent-migration/agent-migration';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type { UiEntryPoint } from '@shared/core/telemetry/reporting';@@ -95,8 +95,6 @@ export class NewManagedAgentService {async add(input: AddManagedAgentParams): Promise<AddManagedAgentResult> {const workspaceId = await this.deps.workspaceFor(input.serverId);- const problem = advancedConfigProblem(input.providerId, input.advancedConfig);- if (problem) return { kind: 'error', message: problem };try {assertInstructionsFit(input.instructions);} catch (error) {diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-adapter-registry.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-adapter-registry.tsindex a1fcb1a39..3f48fedef 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-adapter-registry.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/provider-adapter-registry.ts@@ -1,11 +1,4 @@-import {- createClaudeAdapter,- createCodexAdapter,- createAntigravityAdapter,- createCursorAdapter,- createOpencodeAdapter,- type ProviderAdapter,-} from '@switch-console/agent-providers';+import { type ProviderAdapter, providerRuntime } from '@switch-console/agent-providers';import { log } from '@main/lib/logger';import { supportsProviderRuntime } from '@shared/core/agents/agent-provider-config';@@ -43,21 +36,11 @@ class ProviderAdapterRegistry {warn: (message: string, meta?: Record<string, unknown>) => log.warn(message, meta),error: (message: string, meta?: Record<string, unknown>) => log.error(message, meta),};- if (providerId === 'opencode') {- return createOpencodeAdapter({ logger });- }- if (providerId === 'claude') {- // No executable is configured, so the adapter takes the `claude` on the- // session's own PATH — the CLI the user logged in with. It falls back to- // the one the SDK bundles, and says so on the transcript when it does.- return createClaudeAdapter({ logger });- }- if (providerId === 'cursor') return createCursorAdapter({ logger });- if (providerId === 'antigravity') return createAntigravityAdapter({ logger });- if (providerId === 'codex') return createCodexAdapter({ logger });- throw new Error(- `No provider adapter for '${providerId}'. Supported providers are OpenCode, Claude Code, Codex, Cursor CLI and Antigravity CLI.`- );+ if (!this.supports(providerId))+ throw new Error(`No provider adapter for '${providerId}': this build has no such provider.`);+ // No executable is configured, so each adapter takes the CLI on the+ // session's own PATH — the one the user signed in with.+ return providerRuntime(providerId).createAdapter({ binaryPath: undefined, logger, skill: '' });}}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-types/availability.ts b/console/apps/switch-console-desktop/src/main/core/agent-types/availability.tsindex 016b49736..052f170c3 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-types/availability.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-types/availability.ts@@ -1,20 +1,10 @@-import type { CLIAgentPluginProvider } from '@switch-console/core/agents/plugins';import { resolveCommandPath } from '@switch-console/core/deps/runtime';import { providerAdapterRegistry } from '@main/core/agent-runtime/impl/provider-adapter-registry';import { getRemoteDependencyManager } from '@main/core/dependencies/remote-dependency-manager';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import { listPlugins } from '@main/core/providers/plugin-registry';import type { AgentTypeAvailability } from '@shared/core/agent-types/agent-type-availability';--/** What to tell someone to install, where the product name alone would be ambiguous. */-const CLI_LABELS: Record<string, string> = {- cursor: 'Cursor CLI',- antigravity: 'Antigravity ACP',-};--function cliLabel(plugin: CLIAgentPluginProvider): string {- return CLI_LABELS[plugin.metadata.id] ?? plugin.metadata.name;-}+import { requireProvider } from '@shared/core/providers/agent-provider-registry';function available(agentId: string): AgentTypeAvailability {return { agentId, available: true, blockedReason: null, blockedKind: null };@@ -55,7 +45,7 @@ export async function listLocalAgentTypeAvailability(): Promise<AgentTypeAvailab: {agentId,available: false,- blockedReason: `Install ${cliLabel(plugin)} on this computer.`,+ blockedReason: `Install ${requireProvider(agentId).cliLabel} on this computer.`,blockedKind: 'not-installed',});@@ -88,7 +78,7 @@ export async function listRemoteAgentTypeAvailability(? {agentId,available: false,- blockedReason: `Install ${cliLabel(plugin)} on ${sshHost}.`,+ blockedReason: `Install ${requireProvider(agentId).cliLabel} on ${sshHost}.`,blockedKind: 'not-installed',}: {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 11b98cecc..2c10c92c4 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@@ -1,13 +1,15 @@-import type { RepoAgentAttributes, RepoAgentField } from '@switch-console/core/agents/plugins';+import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import { advancedSettings } from '@switch-console/plugins/agents';import { getPlugin } from '@main/core/providers/plugin-registry';+import type { AgentAdvancedSettings } from '@shared/core/agents/agent-advanced-settings';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { readAgentConfig, setAgentSettings } from './agent-config';import { getAgentById } from './getAgentById';/**- * An agent's "advanced configuration" — its per-agent model, reasoning effort,- * system prompt and whatever else its provider exposes — read and written- * without the caller knowing where the provider keeps it.+ * An agent's "advanced configuration" — its per-agent model, reasoning effort+ * and whatever else its provider exposes — read and written without the caller+ * knowing where the provider keeps it.** All of it is stored in one place — the agent's committed config file — and* turned into whatever the provider takes when a session launches: the agent@@ -15,35 +17,19 @@ import { getAgentById } from './getAgentById';* `~/.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.+ * The fields the form shows are the Switch server's, for the agent's provider;+ * the provider's plugin says which of them it applies. A provider with neither+ * surface has no advanced configuration and the section renders nothing.*/-/** The fields this provider exposes, from whichever surface it keeps them in. */-export function getAgentAdvancedFields(providerId: AgentProviderId): RepoAgentField[] {+export function getAgentAdvancedSettings(providerId: AgentProviderId): AgentAdvancedSettings {const behavior = getPlugin(providerId).behavior;- const definitionFields = behavior.repoAgents?.attributeFields();- if (definitionFields) return definitionFields;- return behavior.mcp?.launchProfileFields?.() ?? [];-}--/** Where a provider keeps its per-agent settings. */-export type AgentAdvancedSurface = 'definition' | 'launch-profile' | 'none';--/**- * Which of the two surfaces a provider uses, for a caller that has to treat them- * differently — the renderer offers a restart only for a launch profile, which is- * read once at spawn and so cannot reach a session already running.- *- * Reported rather than inferred from the provider id: that check was `=== 'codex'`- * for as long as Codex was the only provider with a profile, and silently- * excluded the next one.- */-export function getAgentAdvancedSurface(providerId: AgentProviderId): AgentAdvancedSurface {- const behavior = getPlugin(providerId).behavior;- if (behavior.repoAgents?.attributeFields()) return 'definition';- if (behavior.mcp?.launchProfileFields) return 'launch-profile';- return 'none';+ const surface = behavior.repoAgents+ ? 'definition'+ : behavior.mcp?.launchProfileSettings+ ? 'launch-profile'+ : 'none';+ return { surface, keys: Object.keys(advancedSettings(providerId)) };}/**@@ -70,7 +56,7 @@ export async function updateAgentAdvancedConfig(params: {if (!agent) throw new Error(`No agent with id ${params.agentId}`);const behavior = getPlugin(agent.providerId).behavior;- if (!behavior.repoAgents && !behavior.mcp?.launchProfileFields) {+ if (!behavior.repoAgents && !behavior.mcp?.launchProfileSettings) {throw new Error(`Agent ${params.agentId} has no editable advanced configuration.`);}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 74828e579..e5d4d28e0 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@@ -60,7 +60,7 @@ vi.mock('@main/core/providers/plugin-registry', () => ({behavior:id === 'claude'? { repoAgents: { launchDefinition: () => ({}) } }- : { mcp: { launchProfileFields: () => [] } },+ : { mcp: { launchProfileSettings: () => ({}) } },}),}));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 4c8cbfe1d..4972be3ed 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@@ -96,7 +96,7 @@ async function propagateToLaunch(agentId: string, config: AgentConfigFile): Promif (!agent) throw new Error(`No agent with id ${agentId}`);const behavior = getPlugin(agent.providerId).behavior;- if (!behavior.repoAgents && behavior.mcp?.launchProfileFields) {+ if (!behavior.repoAgents && behavior.mcp?.launchProfileSettings) {// Re-applies the controller itself when it has to.await setAgentProviderConfig({agentId,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.tsindex f6a7cdd8b..c2e2b0254 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts@@ -5,6 +5,11 @@ const mocks = vi.hoisted(() => ({deploy: vi.fn(),exec: vi.fn(),dispose: vi.fn(),+ plugin: {+ metadata: { name: 'Claude Code' } as { name: string; sessionStartMaySignIn?: boolean },+ capabilities: { hostDependency: { binaryNames: ['claude'] } },+ behavior: {},+ },}));vi.mock('@main/core/sdk-host/shared-host-deployment', () => ({@@ -18,10 +23,7 @@ vi.mock('@switch-console/core/deps/runtime', () => ({resolveCommandPath: async () => '/usr/bin/claude',}));vi.mock('@main/core/providers/plugin-registry', () => ({- getPlugin: () => ({- metadata: { name: 'Claude Code' },- capabilities: { hostDependency: { binaryNames: ['claude'] } },- }),+ getPlugin: () => mocks.plugin,}));vi.mock('@main/core/dependencies/host-dependency-store', () => ({ hostDependencyStore: {} }));vi.mock('@main/core/dependencies/dependency-managers', () => ({@@ -35,12 +37,13 @@ vi.mock('@main/core/execution-context/ssh-execution-context', () => ({}));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn() } }));-const { getProviderReadiness } = await import('./agent-model-catalogue');+const { getAgentModelCatalogue, getProviderReadiness } = await import('./agent-model-catalogue');const remote = { providerId: 'claude' as const, sshHost: 'builder', dir: '/work' };beforeEach(() => {vi.clearAllMocks();+ mocks.plugin.metadata = { name: 'Claude Code' };mocks.exec.mockResolvedValue({stdout: JSON.stringify({ status: 'authenticated', message: 'Signed in', models: [] }),});@@ -72,3 +75,42 @@ it('says Switch is not set up on a host with no bundle, rather than deploying onexpect(mocks.deploy).not.toHaveBeenCalled();expect(mocks.exec).not.toHaveBeenCalled();});++const deployedHost = () =>+ mocks.locate.mockResolvedValue({+ ctx: { exec: mocks.exec, dispose: mocks.dispose },+ entrypoint: '/home/me/.local/state/switch/sdk-host/shared-host-a.mjs',+ });+const hostModes = () => mocks.exec.mock.calls.map((call) => call[1]?.[1]);++it("lists a provider's models from its own session", async () => {+ deployedHost();+ mocks.exec.mockResolvedValue({+ stdout: JSON.stringify({+ status: 'unknown',+ message: 'Models loaded.',+ models: [{ id: 'fast', name: 'Fast' }],+ }),+ });++ const catalogue = await getAgentModelCatalogue(remote);++ expect(catalogue).toEqual({+ kind: 'available',+ models: [{ id: 'fast', name: 'Fast', variants: [] }],+ });+ expect(hostModes()).toEqual(['--models']);+});++it('asks the sign-in check first for a provider whose session start may sign in', async () => {+ mocks.plugin.metadata = { name: 'Antigravity', sessionStartMaySignIn: true };+ deployedHost();+ mocks.exec.mockResolvedValue({+ stdout: JSON.stringify({ status: 'unauthenticated', message: 'Sign in first.', models: [] }),+ });++ const catalogue = await getAgentModelCatalogue({ ...remote, providerId: 'antigravity' });++ expect(catalogue).toEqual({ kind: 'unavailable', reason: 'Sign in first.' });+ expect(hostModes()).toEqual(['--probe']);+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.tsindex b27628b02..86a36d4ef 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts@@ -47,12 +47,14 @@ export async function getAgentModelCatalogue(params: {sshHost: string | null;dir: string;}): Promise<AgentModelCatalogue> {- if (['claude', 'codex', 'cursor', 'antigravity'].includes(params.providerId)) {- // Listing Antigravity's models means starting a real ACP session, and- // starting one signs in — which opens a browser when there is no cached- // token. Opening the agent form is not a request to sign in, so ask the- // read-only probe first and stop here when the answer is no.- if (params.providerId === 'antigravity') {+ const plugin = getPlugin(params.providerId);+ const launchProfileModels = plugin.behavior.mcp?.launchProfileModels;+ if (!launchProfileModels) {+ // The provider's own session lists its models. Starting one may sign the+ // CLI in — opening a browser when there is no cached token — and opening+ // the agent form is not a request to sign in, so such a provider is asked+ // the read-only sign-in check first and stops here when the answer is no.+ if (plugin.metadata.sessionStartMaySignIn) {const probe = await getProviderReadiness(params, false);if (probe.status !== 'authenticated') return { kind: 'unavailable', reason: probe.message };}@@ -61,14 +63,6 @@ export async function getAgentModelCatalogue(params: {? { kind: 'available', models: readiness.models.map((model) => ({ ...model, variants: [] })) }: { kind: 'unavailable', reason: readiness.message };}- const plugin = getPlugin(params.providerId);- const launchProfileModels = plugin.behavior.mcp?.launchProfileModels;- if (!launchProfileModels) {- return {- kind: 'unavailable',- reason: `${plugin.metadata.name} does not publish a model list.`,- };- }let ctx: IExecutionContext | null = null;try {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.tsindex e4b593467..6d37843ca 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts@@ -5,8 +5,7 @@ import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-serveimport { createRPCController } from '@shared/lib/ipc/rpc';import { addAgent, type AddAgentParams } from './add-agent';import {- getAgentAdvancedFields,- getAgentAdvancedSurface,+ getAgentAdvancedSettings,readAgentAdvancedConfig,updateAgentAdvancedConfig,} from './agent-advanced-config';@@ -21,7 +20,6 @@ import {attachConfiguredAgents,type AttachConfiguredAgentsParams,} from './attach-configured-agents';-import { getAgentDefinitionFields } from './definition-fields';import { deleteAgent, type DeleteAgentOptions } from './deleteAgent';import {discoverLoadableAgentsInDir,@@ -38,17 +36,14 @@ import { setAgentAutoApprove, type AgentAutoApproveParams } from './setAgentAutoexport const agentsController = createRPCController({addAgent: (params: AddAgentParams) => addAgent(params),- definitionFields: (params: { providerId: AgentProviderId }) =>- Promise.resolve(getAgentDefinitionFields(params.providerId)),/**- * The per-agent advanced configuration, wherever the provider keeps it —- * a repo-agent definition (Claude) or a launch profile (Codex). One form,- * one editor; see `agent-advanced-config.ts`.+ * Where the provider keeps the per-agent advanced configuration — a+ * repo-agent definition (Claude) or a launch profile (Codex) — and which of+ * the server's fields it applies. One form, one editor; see+ * `agent-advanced-config.ts`.*/- advancedFields: (params: { providerId: AgentProviderId }) =>- Promise.resolve(getAgentAdvancedFields(params.providerId)),- advancedSurface: (params: { providerId: AgentProviderId }) =>- Promise.resolve(getAgentAdvancedSurface(params.providerId)),+ advancedSettings: (params: { providerId: AgentProviderId }) =>+ Promise.resolve(getAgentAdvancedSettings(params.providerId)),/*** The models the agent's own host offers, for the advanced-configuration* fields that declare a catalogue binding. Reports why it could not be readdiff --git a/console/apps/switch-console-desktop/src/main/core/agents/definition-fields.ts b/console/apps/switch-console-desktop/src/main/core/agents/definition-fields.tsdeleted file mode 100644index 1e46efb6c..000000000--- a/console/apps/switch-console-desktop/src/main/core/agents/definition-fields.ts+++ /dev/null@@ -1,13 +0,0 @@-import type { RepoAgentField } from '@switch-console/core/agents/plugins';-import { getPlugin } from '@main/core/providers/plugin-registry';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';--/**- * The editable attribute fields for a provider's agent definitions (e.g. a Claude- * Code subagent's model / effort / tools / system prompt), in display order, or- * an empty list when the provider has no definition concept. Drives the "Advanced- * configuration" section of the add-agent modal (CHOO-1440).- */-export function getAgentDefinitionFields(providerId: AgentProviderId): RepoAgentField[] {- return getPlugin(providerId).behavior.repoAgents?.attributeFields() ?? [];-}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.tsindex 79dcac350..e88b2dc41 100644--- 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.ts@@ -174,7 +174,7 @@ describe('importAgentConfig', () => {expect(config).toMatchObject({ instructions: 'Mine.' });});- it('drops a hand-typed value this app would not offer', async () => {+ it('drops a hand-typed count this app would not offer, and carries a choice as written', async () => {await write(DEF_PATH,`---\nname: ${NAME}\ndescription: Reviews diffs\neffort: High\nmaxTurns: 2.5\nmodel: opus\n---\n\nBe thorough.\n`@@ -183,8 +183,7 @@ describe('importAgentConfig', () => {await importClaude();const config = await readAgentConfigFile(createPluginFs(dir), NAME);- expect(config?.settings).toMatchObject({ model: 'opus' });- expect(config?.settings).not.toHaveProperty('effort');+ expect(config?.settings).toMatchObject({ model: 'opus', effort: 'High' });expect(config?.settings).not.toHaveProperty('maxTurns');});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.tsindex 078b4e37a..245f0ebe5 100644--- 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.ts@@ -1,8 +1,8 @@import type {+ AdvancedSettings,IRepoAgentsBehavior,PluginFs,RepoAgentAttributes,- RepoAgentField,} from '@switch-console/core/agents/plugins';import { log } from '@main/lib/logger';import {@@ -33,8 +33,10 @@ import { agentConfigRelativePath } from './switch-settings-paths';* - 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.+ * - a count that is not a positive whole number (a hand-typed `maxTurns:+ * 2.5`) is left out rather than carried into every launch. Which values a+ * choice takes is the Switch server's to say, so a hand-typed choice is+ * carried as written and the form says when it is not one of them.** The definition file is left where it is, and recorded as accounted for (see* {@link acknowledgeDefinition}).@@ -137,30 +139,26 @@ async function importDefinition(params: {return acknowledge({...withDescription,instructions: typeof instructions === 'string' ? instructions : '',- settings: offeredSettings(name, settings, repoAgents.attributeFields()),+ settings: offeredSettings(name, settings, repoAgents.advancedSettings()),});}/**- * 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.+ * The settings this app would let someone set: 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[]+ advanced: AdvancedSettings): 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;+ advanced[key] === 'number'+ ? value === null || (typeof value === 'number' && Number.isInteger(value) && value > 0)+ : true;if (offered) {kept[key] = value;} else {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.tsindex c6f6e321b..ae547bdb2 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.test.ts@@ -1,39 +1,23 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { log } from '@main/lib/logger';+import { describe, expect, it } from 'vitest';+import '@main/core/providers/plugin-registry';import { knownAgentTypeForProvider } from './known-agent-type';-vi.mock('@main/lib/logger', () => ({- log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },-}));-describe('knownAgentTypeForProvider', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('maps codex to its own gateway known-agent type', () => {- expect(knownAgentTypeForProvider('codex')).toBe('codex');- expect(log.warn).not.toHaveBeenCalled();- });-it('maps claude to claude-code', () => {expect(knownAgentTypeForProvider('claude')).toBe('claude-code');- expect(log.warn).not.toHaveBeenCalled();});- it('maps opencode to its own gateway known-agent type', () => {- // Without this it fell through to the fallback and registered as- // claude-code, so an operator onboarding it by hand was told to run- // `claude` in an OpenCode agent's directory.- expect(knownAgentTypeForProvider('opencode')).toBe('opencode');- expect(log.warn).not.toHaveBeenCalled();- });-});+ it.each(['codex', 'opencode', 'antigravity', 'cursor'])(+ 'registers %s under its own gateway known-agent type',+ (providerId) => {+ // Without this OpenCode fell through to a fallback and registered as+ // claude-code, so an operator onboarding it by hand was told to run+ // `claude` in an OpenCode agent's directory.+ expect(knownAgentTypeForProvider(providerId)).toBe(providerId);+ }+ );-it('registers Antigravity under its own gateway type', () => {- expect(knownAgentTypeForProvider('antigravity')).toBe('antigravity');-});--it('maps Cursor to its own backend profile', () => {- expect(knownAgentTypeForProvider('cursor')).toBe('cursor');+ it('refuses a provider this build does not have', () => {+ expect(() => knownAgentTypeForProvider('nope')).toThrow("unknown agent provider 'nope'");+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.tsindex 825d0fb80..1be1404f6 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/known-agent-type.ts@@ -1,20 +1,12 @@-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import { requireProvider } from '@shared/core/providers/agent-provider-registry';/**- * A gateway known-agent type. The union is closed to the keys of `KNOWN_AGENTS`- * in `switch_core/gateway/known_agents.py` — a value outside it is rejected at- * registration, so it is worth catching at the call site instead.+ * A gateway known-agent type: one `known_agent()` resolves in+ * `switch_core/gateway/known_agents.py`. The gateway rejects any other value at+ * registration. Each provider's comes from its plugin metadata.*/-export type KnownAgentType = 'claude-code' | 'codex' | 'opencode' | 'antigravity' | 'cursor';+export type KnownAgentType = string;-const KNOWN_AGENT_TYPE_BY_PROVIDER: Record<AgentProviderId, KnownAgentType> = {- claude: 'claude-code',- codex: 'codex',- opencode: 'opencode',- antigravity: 'antigravity',- cursor: 'cursor',-};--export function knownAgentTypeForProvider(providerId: AgentProviderId): KnownAgentType {- return KNOWN_AGENT_TYPE_BY_PROVIDER[providerId];+export function knownAgentTypeForProvider(providerId: string): KnownAgentType {+ return requireProvider(providerId).knownAgentType;}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.tsindex f743d8e22..77306d326 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -11,7 +11,7 @@ import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { AGENT_PROVIDER_IDS } from '@shared/core/providers/agent-provider-registry';+import { isValidProviderId } from '@shared/core/providers/agent-provider-registry';import { makeHookSessionId } from '@shared/core/providers/hook-session-id';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import { sessionStatusUpdatedChannel } from '@shared/core/sessions/sessionEvents';@@ -98,7 +98,7 @@ class RemoteSessionReconciler {if (value && typeof value === 'object' && 'discoveryError' in value)throw new Error(String(value.discoveryError));const session = sessionSchema.parse(value);- if (!AGENT_PROVIDER_IDS.some((provider) => provider === session.provider))+ if (!isValidProviderId(session.provider))throw new Error(`Session ${session.sessionId} uses unsupported provider "${session.provider}". Update Console to open it.`);diff --git a/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.tsnew file mode 100644index 000000000..75f4abd9e--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts@@ -0,0 +1,113 @@+import { acpProviderRuntime, cursorAcp, PROVIDER_RUNTIMES } from '@switch-console/agent-providers';+import { pluginRegistry } from '@switch-console/plugins/agents';+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { machineProviderOptions } from '@renderer/features/locations/components/add-agent-modal/machine-provider-picker';+import { buildAgentGroups } from '@renderer/lib/components/agent-selector/agent-selector-options';+import {+ agentProviderIds,+ isValidProviderId,+ requireProvider,+ setAgentProviderCatalogue,+} from '@shared/core/providers/agent-provider-registry';+import { listRemoteAgentTypeAvailability } from '../agent-types/availability';+import { knownAgentTypeForProvider } from '../agents/known-agent-type';+import { buildAgentProviderCatalogue } from './agent-provider-catalogue';++const mocks = vi.hoisted(() => ({ probe: vi.fn() }));+vi.mock('@main/core/dependencies/remote-dependency-manager', () => ({+ getRemoteDependencyManager: async () => ({ probe: mocks.probe }),+}));+vi.mock('@main/lib/logger', () => ({ log: { debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+vi.mock('@renderer/lib/components/agent-icon', () => ({ AgentIcon: () => null }));+vi.mock('@renderer/lib/ipc', () => ({ events: { on: vi.fn() }, rpc: {} }));++/**+ * Registering a provider is a plugin plus a runtime. This registers a made-up+ * ACP CLI both ways — the plugin into the real registry, the runtime made from+ * its hooks — and checks that the desktop lists it, labels it and knows how to+ * sign it in, with no desktop code naming it.+ */+beforeAll(() => {+ const cursor = pluginRegistry.get('cursor')!;+ pluginRegistry.register({+ ...cursor,+ metadata: {+ id: 'dummy',+ name: 'Dummy',+ description: 'A made-up agent CLI.',+ websiteUrl: 'https://dummy.example.com',+ cliLabel: 'Dummy CLI',+ },+ capabilities: {+ ...cursor.capabilities,+ hostDependency: { ...cursor.capabilities.hostDependency, binaryNames: ['dummy-agent'] },+ },+ });+ const dummyRuntime = acpProviderRuntime({+ ...cursorAcp,+ provider: 'dummy',+ label: 'Dummy',+ defaultBinary: 'dummy-agent',+ loginCommand: 'dummy-agent login',+ });+ setAgentProviderCatalogue(+ buildAgentProviderCatalogue(pluginRegistry.getAll(), [...PROVIDER_RUNTIMES, dummyRuntime])+ );+});++describe('a provider added as a plugin and a runtime', () => {+ it('is in the catalogue, with its runtime login command and defaults from its plugin', () => {+ expect(agentProviderIds().at(-1)).toBe('dummy');+ expect(isValidProviderId('dummy')).toBe(true);+ expect(requireProvider('dummy')).toEqual({+ id: 'dummy',+ name: 'Dummy',+ description: 'A made-up agent CLI.',+ docUrl: 'https://dummy.example.com',+ cliLabel: 'Dummy CLI',+ loginCommand: 'dummy-agent login',+ knownAgentType: 'dummy',+ });+ expect(knownAgentTypeForProvider('dummy')).toBe('dummy');+ });++ it('is an agent type the create-agent form offers, and says what to install by its CLI label', async () => {+ mocks.probe.mockResolvedValue({ status: 'missing' });++ const types = await listRemoteAgentTypeAvailability('example-host');++ expect(types).toContainEqual({+ agentId: 'dummy',+ available: false,+ blockedReason: 'Install Dummy CLI on example-host.',+ blockedKind: 'not-installed',+ });+ });++ it('is listed by the agent selector', () => {+ const items = buildAgentGroups(['dummy']).flatMap((group) => group.items);++ expect(items).toContainEqual({+ value: 'dummy',+ label: 'Dummy',+ agentId: 'dummy',+ disabled: false,+ });+ });++ it('is listed among the providers a managed machine reports', () => {+ const options = machineProviderOptions({+ id: 'machine-1',+ name: 'Build box',+ kind: 'linux',+ state: 'online',+ providers: [{ provider: 'dummy', ready: true, problem: null }],+ acceptsLogins: false,+ cloud: false,+ workspacesDir: null,+ local: null,+ });++ expect(options).toContainEqual({ id: 'dummy', name: 'Dummy', ready: true, problem: null });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.test.tsindex 1ea1046c0..c10d784be 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.test.ts@@ -20,17 +20,13 @@ vi.mock('@main/core/dependencies/registry', () => ({DEPENDENCIES: [],}));-vi.mock('@shared/core/providers/agent-provider-registry', () => ({- AGENT_PROVIDERS: [{ id: 'claude' }, { id: 'codex' }],-}));-vi.mock('../settings/provider-settings-service', () => ({providerOverrideSettings: {getItemWithMeta: vi.fn(),},}));-const { getPlugin } = await import('@main/core/providers/plugin-registry');+const { getPlugin, listPlugins } = await import('@main/core/providers/plugin-registry');const { providerOverrideSettings } = await import('../settings/provider-settings-service');void (await import('@main/core/dependencies/registry'));@@ -176,7 +172,11 @@ describe('buildAgentPayload', () => {});describe('buildAgentPayloads', () => {- it('returns one entry per AGENT_PROVIDERS entry', async () => {+ it('returns one entry per registered plugin, in registration order', async () => {+ vi.mocked(listPlugins).mockReturnValue([+ makeProvider('claude', 'claude'),+ makeProvider('codex', 'codex'),+ ]);vi.mocked(getPlugin).mockImplementation((id) => makeProvider(id, id));vi.mocked(providerOverrideSettings.getItemWithMeta).mockResolvedValue(defaultSettings());diff --git a/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.ts b/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.tsindex e3e57bf29..3432783c4 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/agent-payload-builder.ts@@ -19,13 +19,9 @@ import type {AgentPayload,InstallOption,} from '@shared/core/providers/agent-payload';-import {- AGENT_PROVIDERS,- type AgentProviderId,-} from '@shared/core/providers/agent-provider-registry';import { getDependencyDescriptor } from '../dependencies/registry';import { providerOverrideSettings } from '../settings/provider-settings-service';-import { getPlugin } from './plugin-registry';+import { getPlugin, listPlugins } from './plugin-registry';/*** Optional callback injected by the controller so the builder can enrich the@@ -58,7 +54,7 @@ function buildMetadata(provider: CLIAgentPluginProvider): AgentMetadata {}async function buildOne(- id: AgentProviderId,+ id: string,platform: Platform,dependencyManager?: HostDependencyManager,enrichHostDep?: EnrichHostDep@@ -108,7 +104,7 @@ export async function buildAgentPayload(dependencyManager?: HostDependencyManager,enrichHostDep?: EnrichHostDep): Promise<AgentPayload | null> {- return buildOne(id as AgentProviderId, platform, dependencyManager, enrichHostDep);+ return buildOne(id, platform, dependencyManager, enrichHostDep);}export async function buildAgentPayloads(@@ -117,7 +113,9 @@ export async function buildAgentPayloads(enrichHostDep?: EnrichHostDep): Promise<AgentPayload[]> {const results = await Promise.all(- AGENT_PROVIDERS.map((p) => buildOne(p.id, platform, dependencyManager, enrichHostDep))+ listPlugins().map((plugin) =>+ buildOne(plugin.metadata.id, platform, dependencyManager, enrichHostDep)+ ));return results.filter((r): r is AgentPayload => r !== null);}diff --git a/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.test.tsnew file mode 100644index 000000000..a9181c8b1--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';+import { buildAgentProviderCatalogue } from './agent-provider-catalogue';++const plugin = (metadata: { id: string; cliLabel?: string; knownAgentType?: string }) => ({+ metadata: {+ name: `${metadata.id} name`,+ description: `${metadata.id} description`,+ websiteUrl: `https://${metadata.id}.example.com`,+ ...metadata,+ },+});++const runtime = (id: string) => ({ id, loginCommand: `${id} login` });++describe('buildAgentProviderCatalogue', () => {+ it('makes one entry per plugin, in registration order, with its runtime login command', () => {+ const catalogue = buildAgentProviderCatalogue(+ [plugin({ id: 'beta' }), plugin({ id: 'alpha' })],+ [runtime('alpha'), runtime('beta')]+ );++ expect(catalogue).toEqual([+ {+ id: 'beta',+ name: 'beta name',+ description: 'beta description',+ docUrl: 'https://beta.example.com',+ cliLabel: 'beta name',+ loginCommand: 'beta login',+ knownAgentType: 'beta',+ },+ expect.objectContaining({ id: 'alpha', loginCommand: 'alpha login' }),+ ]);+ });++ it('takes the CLI label and gateway type from the plugin when it names them', () => {+ const [entry] = buildAgentProviderCatalogue(+ [plugin({ id: 'acme', cliLabel: 'Acme CLI', knownAgentType: 'acme-code' })],+ [runtime('acme')]+ );++ expect(entry).toMatchObject({ cliLabel: 'Acme CLI', knownAgentType: 'acme-code' });+ });++ it('refuses a plugin with no runtime, naming it', () => {+ expect(() =>+ buildAgentProviderCatalogue(+ [plugin({ id: 'acme' }), plugin({ id: 'beta' })],+ [runtime('beta')]+ )+ ).toThrow('No runtime in agent-providers for: acme.');+ });++ it('refuses a runtime with no plugin, naming it', () => {+ expect(() =>+ buildAgentProviderCatalogue([plugin({ id: 'beta' })], [runtime('beta'), runtime('acme')])+ ).toThrow('No plugin for: acme.');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.ts b/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.tsnew file mode 100644index 000000000..8bc5fb6a1--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/providers/agent-provider-catalogue.ts@@ -0,0 +1,40 @@+import type { ProviderRuntime } from '@switch-console/agent-providers';+import type { CLIAgentPluginMetadata } from '@switch-console/core/agents/plugins';+import type { AgentProviderDefinition } from '@shared/core/providers/agent-provider-registry';++/**+ * The provider catalogue: one entry per provider, in plugin registration order,+ * made from its plugin metadata and its runtime's login command.+ *+ * A provider registers in two places — a plugin in `packages/plugins` and a+ * runtime in `packages/agent-providers`. One with only one half is a build that+ * would list it and then fail to run it, so this throws naming the missing half.+ */+export function buildAgentProviderCatalogue(+ plugins: readonly { metadata: CLIAgentPluginMetadata }[],+ runtimes: readonly Pick<ProviderRuntime, 'id' | 'loginCommand'>[]+): AgentProviderDefinition[] {+ const pluginIds = plugins.map((plugin) => plugin.metadata.id);+ const runtimeById = new Map(runtimes.map((runtime) => [runtime.id, runtime]));+ const missingRuntime = pluginIds.filter((id) => !runtimeById.has(id));+ const missingPlugin = [...runtimeById.keys()].filter((id) => !pluginIds.includes(id));+ if (missingRuntime.length || missingPlugin.length)+ throw new Error(+ [+ 'Agent provider registration is incomplete.',+ ...(missingRuntime.length+ ? [`No runtime in agent-providers for: ${missingRuntime.join(', ')}.`]+ : []),+ ...(missingPlugin.length ? [`No plugin for: ${missingPlugin.join(', ')}.`] : []),+ ].join(' ')+ );+ return plugins.map(({ metadata }) => ({+ id: metadata.id,+ name: metadata.name,+ description: metadata.description,+ docUrl: metadata.websiteUrl,+ cliLabel: metadata.cliLabel ?? metadata.name,+ loginCommand: runtimeById.get(metadata.id)!.loginCommand,+ knownAgentType: metadata.knownAgentType ?? metadata.id,+ }));+}diff --git a/console/apps/switch-console-desktop/src/main/core/providers/controller.ts b/console/apps/switch-console-desktop/src/main/core/providers/controller.tsindex f10acd941..6e3abf20c 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/controller.ts@@ -7,7 +7,11 @@ import type {} from '@switch-console/core/deps/runtime';import { reportedCliAction } from '@main/core/telemetry/cli-action';import type { ProviderCustomConfig } from '@shared/core/app-settings';-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import {+ type AgentProviderDefinition,+ type AgentProviderId,+ agentProviders,+} from '@shared/core/providers/agent-provider-registry';import { createRPCController } from '@shared/lib/ipc/rpc';import { clearResolvedPathCache } from '../agent-runtime/impl/resolve-agent-executable';import { agentUpdateService } from '../dependencies/agent-update-service';@@ -38,6 +42,9 @@ const TARGET = 'local';export const providersController = createRPCController({// ── Metadata ────────────────────────────────────────────────────────────────+ /** The provider catalogue the renderer installs before its first render. */+ catalogue: (): readonly AgentProviderDefinition[] => agentProviders(),+list: async (connectionId?: string) => {const mgr = await getDependencyManager(connectionId);return buildAgentPayloads(mgr.platform, mgr, enrichHostDep);diff --git a/console/apps/switch-console-desktop/src/main/core/providers/plugin-registry.ts b/console/apps/switch-console-desktop/src/main/core/providers/plugin-registry.tsindex 078877ace..9f47fc819 100644--- a/console/apps/switch-console-desktop/src/main/core/providers/plugin-registry.ts+++ b/console/apps/switch-console-desktop/src/main/core/providers/plugin-registry.ts@@ -1,17 +1,22 @@+import { PROVIDER_RUNTIMES } from '@switch-console/agent-providers';import type {CLIAgentPluginMetadata,CLIAgentPluginProvider,} from '@switch-console/core/agents/plugins';import { pluginRegistry } from '@switch-console/plugins/agents';-import { AGENT_PROVIDER_IDS } from '@shared/core/providers/agent-provider-registry';+import {+ type AgentProviderDefinition,+ setAgentProviderCatalogue,+} from '@shared/core/providers/agent-provider-registry';+import { buildAgentProviderCatalogue } from './agent-provider-catalogue';-// Assert plugin ids match the canonical AGENT_PROVIDER_IDS list at startup.-const pluginIds = new Set(pluginRegistry.ids());-for (const id of AGENT_PROVIDER_IDS) {- if (!pluginIds.has(id)) {- throw new Error(`Plugin registry parity violation: missing plugin for provider '${id}'`);- }-}+/**+ * Built when this module loads, which `src/main/index.ts` makes the first thing+ * the main process does, so shared code can read the catalogue from then on.+ */+export const AGENT_PROVIDER_CATALOGUE: readonly AgentProviderDefinition[] =+ buildAgentProviderCatalogue(pluginRegistry.getAll(), PROVIDER_RUNTIMES);+setAgentProviderCatalogue(AGENT_PROVIDER_CATALOGUE);export function getPlugin(id: string): CLIAgentPluginProvider {const plugin = pluginRegistry.get(id);diff --git a/console/apps/switch-console-desktop/src/main/core/providers/provider-argv-parity.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/provider-argv-parity.test.tsdeleted file mode 100644index eac2a5e0d..000000000--- a/console/apps/switch-console-desktop/src/main/core/providers/provider-argv-parity.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { pluginRegistry } from '@switch-console/plugins/agents';-import { describe, expect, it } from 'vitest';-import { getProvider } from '@shared/core/providers/agent-provider-registry';--/** `splitFlag` in standard-command.ts is not exported; this mirrors it. */-function splitFlag(flag: string): string[] {- return flag.split(/\s+/).filter(Boolean);-}--/** Whether `needle` appears in `haystack` as a contiguous run. */-function containsSequence(haystack: string[], needle: string[]): boolean {- if (needle.length === 0) return true;- return haystack.some((_, i) => needle.every((token, offset) => haystack[i + offset] === token));-}--function buildCodexArgs(autoApprove: boolean): string[] {- return pluginRegistry.get('codex')!.behavior.prompt!.buildCommand({- cli: 'codex',- autoApprove,- model: '',- isResuming: false,- }).args;-}--/**- * The registry's argv fields describe the plugin rather than driving it, so- * nothing at runtime notices when the two disagree. Codex is the entry worth- * pinning: its flags suppress approval prompts, so a stale mirror- * misrepresents how much access a session is launched with.- */-describe('codex registry metadata matches the argv the plugin builds', () => {- it('emits the mirrored autoApproveFlag', () => {- const def = getProvider('codex')!;- const args = buildCodexArgs(true);-- expect(def.autoApproveFlag).toBeDefined();- expect(containsSequence(args, splitFlag(def.autoApproveFlag!))).toBe(true);- });-- it('leaves the sandbox to the user config on both sides of the mirror', () => {- // Auto-approve means unattended approvals, not unattended filesystem and- // network access.- const def = getProvider('codex')!;-- expect(def.autoApproveFlag).not.toContain('sandbox_mode');- expect(buildCodexArgs(true).join(' ')).not.toContain('sandbox_mode');- });-- it('adds no approval override on a session that does not auto-approve', () => {- expect(buildCodexArgs(false)).not.toContain('-c');- });-});diff --git a/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts b/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.tsindex e7889f8d5..939dbd74d 100644--- a/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts@@ -20,7 +20,6 @@ import type { TelemetryHostSetupAction, TelemetryOutcome } from '@main/core/teleimport { trackEvent } from '@main/core/telemetry/telemetry-service';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { AGENT_PROVIDER_IDS } from '@shared/core/providers/agent-provider-registry';import {agentIdForStep,hostSetupActivityEventChannel,@@ -54,11 +53,7 @@ const runners = new Map<string, HostSetupRunner>();*/function plannableAgentTypes() {return listPlugins()- .filter(- (plugin) =>- AGENT_PROVIDER_IDS.some((id) => id === plugin.metadata.id) &&- plugin.capabilities.hostDependency.binaryNames.length > 0- )+ .filter((plugin) => plugin.capabilities.hostDependency.binaryNames.length > 0).map((plugin) => ({agentId: plugin.metadata.id,name: remoteDependencyDescriptor(plugin.metadata.id)?.name ?? plugin.metadata.id,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 4ff1c00ea..984cc7ba4 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@@ -47,6 +47,7 @@ import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notificimport { switchRoomService } from '@main/core/switch-rooms/switch-room-service';import { workspaceServer } from '@main/core/workspaces/workspace-session';import { log } from '@main/lib/logger';+import { providerNamesSentence } from '@shared/core/providers/agent-provider-registry';import { makeHookSessionId } from '@shared/core/providers/hook-session-id';import type { Session } from '@shared/core/sessions/sessions';import { JournalUnavailableError } from './host-journal';@@ -403,7 +404,7 @@ export async function buildSharedHostConfig(const launch = await agentLaunchConfig(session.agentId);if (!providerAdapterRegistry.supports(session.providerId))throw new Error(- 'SDK sessions support Claude Code, Codex, OpenCode, Antigravity and Cursor. Choose one of these providers.'+ `SDK sessions support ${providerNamesSentence()}. Choose one of these providers.`);if (transport.kind !== 'ssh' && process.platform === 'win32')throw new Error(diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.tsindex 276646386..237ff3806 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/createSession.ts@@ -6,6 +6,7 @@ import { getAgentById } from '@main/core/agents/getAgentById';import { locationManager } from '@main/core/locations/location-manager';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';+import { providerNamesSentence } from '@shared/core/providers/agent-provider-registry';import type { SessionConfig } from '@shared/core/sessions/session-config';import type {CreateSessionError,@@ -41,7 +42,7 @@ export async function createSession(if (!providerAdapterRegistry.supports(agent.providerId))return err({type: 'spawn-failed',- message: 'SDK sessions support Claude Code, Codex, OpenCode, Antigravity CLI and Cursor.',+ message: `SDK sessions support ${providerNamesSentence()}.`,});if (!adopted && process.platform === 'win32' && location?.transport.kind !== 'ssh')return err({diff --git a/console/apps/switch-console-desktop/src/main/core/settings/schema.ts b/console/apps/switch-console-desktop/src/main/core/settings/schema.tsindex d31acba6f..d3cf2b54b 100644--- a/console/apps/switch-console-desktop/src/main/core/settings/schema.ts+++ b/console/apps/switch-console-desktop/src/main/core/settings/schema.ts@@ -1,6 +1,6 @@import z from 'zod';import { BROWSER_ISOLATED_PROFILE_ID } from '@shared/browser';-import { AGENT_PROVIDER_IDS } from '@shared/core/providers/agent-provider-registry';+import { isValidProviderId } from '@shared/core/providers/agent-provider-registry';import type { AppSettingsKeyName } from '@shared/core/settings/setting-keys';import { openInAppIdSchema } from '@shared/openInApps';import { DEFAULT_AGENT_ID } from './settings-registry';@@ -31,7 +31,11 @@ export const themeSchema = z.optional().default(null);-export const defaultAgentSchema = z.optional(z.enum(AGENT_PROVIDER_IDS)).default(DEFAULT_AGENT_ID);+export const defaultAgentSchema = z+ .optional(+ z.string().refine((id) => isValidProviderId(id), { message: 'Unknown agent provider.' })+ )+ .default(DEFAULT_AGENT_ID);/*** Per-provider execution settings stored as host-agnostic overrides.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.tsindex 7043716ef..18002b6ff 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -2542,4 +2542,13 @@ describe('agent management calls', () => {);await expect(fetchAdvancedConfigSchema(SERVER)).rejects.toThrow();});++ it('says a server that does not serve the fields is older than them', async () => {+ fetchMock.mockImplementation(async () => respond(404, { detail: 'Not Found' }));+ const refusal = await fetchAdvancedConfigSchema(SERVER).catch((error: unknown) => error);+ expect(refusal).not.toBeInstanceOf(AgentManagementUnavailableError);+ expect((refusal as Error).message).toMatch(+ /does not serve the advanced configuration fields.*Update the server/+ );+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex de141a012..7c27d713e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -3213,12 +3213,24 @@ const advancedConfigSchemaResponse = z.object({/*** Each provider's advanced configuration fields, keyed by provider* (`GET /gateway/management/advanced-config`): what a managed agent's- * `advanced_config` is checked against.+ * `advanced_config` is checked against, and what every agent's advanced+ * configuration form is built from. A server serves them whether or not it+ * runs agent management, so one that answers 404 is older than the fields.*/export async function fetchAdvancedConfigSchema(server: SwitchServer): Promise<Record<string, AdvancedConfigField[]>> {- const res = await managementFetch(server, '/advanced-config', { authenticated: true });+ let res: Response;+ try {+ res = await managementFetch(server, '/advanced-config', { authenticated: true });+ } catch (error) {+ if (error instanceof AgentManagementUnavailableError)+ throw new Error(+ `${server.name} does not serve the advanced configuration fields Console builds its form from. Update the server to set an agent's advanced configuration.`,+ { cause: error }+ );+ throw error;+ }const { providers } = advancedConfigSchemaResponse.parse(await res.json());return Object.fromEntries(Object.entries(providers).map(([provider, { fields }]) => [diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex 44a8a7bba..ae9ce688e 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -1,4 +1,6 @@import './app/configure-app-identity';+// Installs the agent provider catalogue before any module that reads it loads.+import './core/providers/plugin-registry';import { join } from 'node:path';import { setTimeout as delay } from 'node:timers/promises';import { config as dotenvConfig } from 'dotenv';diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsxindex 805d20999..a86723cd4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-advanced-config.tsx@@ -1,13 +1,12 @@import type { RepoAgentAttributes, RepoAgentField } from '@switch-console/core/agents/plugins';import { useQuery } from '@tanstack/react-query';-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useState } from 'react';import { rpc } from '@renderer/lib/ipc';import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';import { getProvider } from '@shared/core/providers/agent-provider-registry';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import {- advancedFields,attributesFromForm,DefinitionFieldInput,formFromAttributes,@@ -15,21 +14,26 @@ import {type FormValue,} from '../agent-definition-fields';import { fieldCatalogueState, type ModelCatalogueResult } from '../agent-model-catalogue';+import { useLocalAdvancedFields } from '../use-local-advanced-fields';/**- * Collapsed "Advanced configuration" section for the add-agent modal. Renders the- * provider's definition attribute fields (model, effort, tools, system prompt, …)- * beyond name/description, and reports the assembled attributes so the modal can- * pass them to `addAgent`, which writes them into the agent's on-disk definition.- * Collapsed by default so ordinary users are not overwhelmed (CHOO-1440).+ * Collapsed "Advanced configuration" section for the add-agent modal, for a+ * provider that keeps its per-agent settings in the agent definition it runs+ * as (Claude Code). Renders the model and the server's advanced fields for the+ * provider, and reports the assembled attributes so the modal can pass them to+ * `addAgent`, which writes them into the agent's config file. Collapsed by+ * default so ordinary users are not overwhelmed (CHOO-1440).*/export function AgentAdvancedConfig({+ serverId,providerId,sshHost,dir,initial,onChange,}: {+ /** The Switch server the agent belongs to, whose fields the form shows; null when none is chosen. */+ serverId: string | null;providerId: AgentProviderId | null;sshHost: string | null;dir: string;@@ -49,13 +53,8 @@ export function AgentAdvancedConfig({kind: 'unavailable' as const,reason: 'No execution directory is configured yet. You can enter a model alias or ID.',};- const { data: allFields } = useQuery({- queryKey: ['agentDefinitionFields', providerId],- queryFn: () => (providerId ? rpc.agents.definitionFields({ providerId }) : Promise.resolve([])),- enabled: !!providerId,- });-- const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);+ const local = useLocalAdvancedFields(serverId, providerId);+ const fields = local.surface === 'definition' ? local.fields : NO_FIELDS;const providerLabel = providerId ? (getProvider(providerId)?.name ?? providerId) : null;const [state, setState] = useState<FormState>({});@@ -68,7 +67,7 @@ export function AgentAdvancedConfig({onChange(attributesFromForm(fields, form));}, [fields, initial, onChange]);- if (!providerId || fields.length === 0) return null;+ if (!providerId || local.surface !== 'definition') return null;const setField = (key: string, value: FormValue) => {setState((prev) => {@@ -79,20 +78,36 @@ export function AgentAdvancedConfig({};return (- <AdvancedConfigSection- providerLabel={providerLabel}- fields={fields}- form={state}- catalogue={executionCatalogue}- onFieldChange={setField}- />+ <div className="flex flex-col gap-2">+ {fields.length > 0 && (+ <AdvancedConfigSection+ providerLabel={providerLabel}+ fields={fields}+ form={state}+ catalogue={executionCatalogue}+ onFieldChange={setField}+ />+ )}+ <AdvancedConfigProblem problem={local.problem} />+ </div>+ );+}++const NO_FIELDS: RepoAgentField[] = [];++/** Why the advanced configuration is not all the server defines, when it is not. */+export function AdvancedConfigProblem({ problem }: { problem: string | null }) {+ if (!problem) return null;+ return (+ <p role="alert" className="text-xs text-foreground-destructive">+ {problem}+ </p>);}/**- * The collapsed section itself, whatever supplies its fields: the provider's own- * definition fields for an agent this Console runs, the server's schema for a- * managed one.+ * The collapsed section itself, for an agent this Console runs or a managed+ * one: the model and the server's fields for the provider either way.*/export function AdvancedConfigSection({providerLabel,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsxindex 9da9efe71..cebd93bf9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx@@ -1,5 +1,6 @@+import type { RepoAgentField } from '@switch-console/core/agents/plugins';import { useQuery } from '@tanstack/react-query';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useState } from 'react';import { rpc } from '@renderer/lib/ipc';import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';@@ -20,6 +21,8 @@ import {fieldWithCatalogue,type ModelCatalogueResult,} from '../agent-model-catalogue';+import { useLocalAdvancedFields } from '../use-local-advanced-fields';+import { AdvancedConfigProblem } from './agent-advanced-config';/*** Collapsed "Advanced configuration" section for a provider that keeps its@@ -27,17 +30,22 @@ import {* per-agent provider config (or null when nothing is set) so the modal can pass* it to `addAgent`, which persists it on the agent and folds it into the profile.*- * The fields are the same ones the agent's Settings tab edits after creation —- * fetched over RPC from the provider's own plugin, so the two forms cannot drift,- * and the section renders nothing for a provider that declares none. That empty- * field list is the gate: no caller needs to know which providers have one.+ * The fields are the same ones the agent's Settings tab edits after creation:+ * the model and the agent's Switch server's fields for the provider, so the two+ * forms cannot drift. Only one of the two surfaces — this or the agent+ * definition `AgentAdvancedConfig` renders — exists per provider, and this one+ * renders nothing for the other; for a provider with neither it renders only+ * a problem with the server's fields, if there is one.*/export function LaunchProfileConfig({+ serverId,providerId,sshHost,dir,onChange,}: {+ /** The Switch server the agent belongs to, whose fields the form shows; null when none is chosen. */+ serverId: string | null;providerId: AgentProviderId | null;/** The host the agent will run on: its SSH alias, or null for this machine. */sshHost: string | null;@@ -46,27 +54,8 @@ export function LaunchProfileConfig({}) {const [open, setOpen] = useState(false);- // Which surface this provider actually keeps its settings in. `advancedFields`- // below answers "the fields, from wherever they live" and falls back to the- // definition fields for a provider that has those — which is the same list- // `AgentAdvancedConfig` renders beside this, so Claude Code showed two- // identical "Advanced configuration" sections. Only one of the two surfaces- // exists per provider; this is how the agent's Settings tab picks, and the- // creation form has to pick the same way or the two disagree about what an- // agent even has.- const { data: surface } = useQuery({- queryKey: ['agentAdvancedSurface', providerId],- queryFn: () =>- providerId ? rpc.agents.advancedSurface({ providerId }) : Promise.resolve('none' as const),- enabled: !!providerId,- });-- const { data } = useQuery({- queryKey: ['agentAdvancedFields', providerId],- queryFn: () => (providerId ? rpc.agents.advancedFields({ providerId }) : Promise.resolve([])),- enabled: !!providerId,- });- const fields = useMemo(() => (surface === 'launch-profile' ? (data ?? []) : []), [data, surface]);+ const local = useLocalAdvancedFields(serverId, providerId);+ const fields = local.surface === 'launch-profile' ? local.fields : NO_FIELDS;// The models that host offers, for the fields bound to it. Asked of the host// the agent will run on, since that is what decides the answer — and only once@@ -98,12 +87,14 @@ export function LaunchProfileConfig({setState((prev) => ({ ...prev, [key]: value }));}, []);- if (!providerId) return null;+ // Also rendered for a provider that keeps no per-agent settings, so a+ // problem with the server's fields for it is still shown.+ if (!providerId || local.surface === undefined || local.surface === 'definition') return null;const providerLabel = getProvider(providerId)?.name ?? providerId;return (- <div>+ <div className="flex flex-col gap-2">{fields.length > 0 && (<DisclosureRowopen={open}@@ -148,6 +139,9 @@ export function LaunchProfileConfig({})}</div>)}+ <AdvancedConfigProblem problem={local.problem} /></div>);}++const NO_FIELDS: RepoAgentField[] = [];diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/machine-provider-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/machine-provider-picker.tsxindex ed896691d..1bcdf5612 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/machine-provider-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/machine-provider-picker.tsx@@ -5,7 +5,7 @@ import { Field, FieldLabel } from '@renderer/lib/ui/field';import { cn } from '@renderer/utils/utils';import type { OwnedMachine } from '@shared/core/managed-agents/managed-agents';import {- AGENT_PROVIDERS,+ agentProviders,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';import { autoSelectedAgentType } from './agent-type-auto-selection';@@ -15,7 +15,7 @@ import { GiveMachineLogin } from './give-machine-login';export function machineProviderOptions(machine: OwnedMachine): { id: AgentProviderId; name: string; ready: boolean; problem: string | null }[] {- return AGENT_PROVIDERS.map((provider) => {+ return agentProviders().map((provider) => {const reported = machine.providers.find((entry) => entry.provider === provider.id);return {id: provider.id,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsxindex 9fb8f58ce..b0bbe5cf1 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/new-agent-form.tsx@@ -964,6 +964,7 @@ export const NewAgentForm = observer(function NewAgentForm({{canConfigureAgent && !!pickState.providerId && !managedRun && !isCloudRun && (<><AgentAdvancedConfig+ serverId={pickState.serverId}providerId={pickState.providerId}sshHost={isRemoteRun ? runHost : null}dir={dir}@@ -971,6 +972,7 @@ export const NewAgentForm = observer(function NewAgentForm({onChange={onAdvancedChange}/><LaunchProfileConfig+ serverId={pickState.serverId}providerId={pickState.providerId}sshHost={isRemoteRun ? runHost : null}dir={dir}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsxindex d05fdee02..8eb2644c6 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx@@ -23,14 +23,6 @@ const UNSET = '__unset__';export type FormValue = string | boolean;export type FormState = Record<string, FormValue>;-/** name/description are collected as top-level fields, not advanced ones. */-export const TOP_LEVEL_KEYS = new Set(['name', 'description']);--/** The advanced (non top-level) attribute fields, in provider display order. */-export function advancedFields(allFields: RepoAgentField[]): RepoAgentField[] {- return allFields.filter((f) => !TOP_LEVEL_KEYS.has(f.key));-}-export function emptyForm(fields: RepoAgentField[]): FormState {const state: FormState = {};for (const field of fields) state[field.key] = field.type === 'boolean' ? false : '';@@ -82,7 +74,7 @@ export function attributesFromForm(return attributes;}-/** One provider-declared definition attribute, rendered by its field type. */+/** One advanced configuration field, rendered by its type. */export function DefinitionFieldInput({field,value,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.test.tsnew file mode 100644index 000000000..44df82db3--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import { choicesNotOffered, localAdvancedFields } from './local-advanced-fields';++const CODEX = { id: 'codex', label: 'Codex' };+const EFFORT = {+ key: 'effort',+ label: 'Reasoning effort',+ type: 'select' as const,+ options: [+ { value: '', label: 'Default' },+ { value: 'high', label: 'high' },+ ],+};++describe('localAdvancedFields', () => {+ it('offers the model, then the server’s fields the plugin applies', () => {+ expect(+ localAdvancedFields(+ CODEX,+ { surface: 'launch-profile', keys: ['effort'] },+ { kind: 'schema', schema: { codex: [EFFORT] } }+ )+ ).toEqual({ fields: [{ key: 'model', label: 'Model', type: 'text' }, EFFORT], problem: null });+ });++ it('offers nothing, and says nothing, for a new provider with no fields and no settings', () => {+ expect(+ localAdvancedFields(+ { id: 'newcli', label: 'New CLI' },+ { surface: 'none', keys: [] },+ { kind: 'schema', schema: { newcli: [] } }+ )+ ).toEqual({ fields: [], problem: null });+ });++ it('offers nothing while the server’s fields load', () => {+ expect(+ localAdvancedFields(CODEX, { surface: 'launch-profile', keys: [] }, { kind: 'loading' })+ ).toEqual({ fields: [], problem: null });+ });++ it('says there is no server to read the fields from, and offers only the model', () => {+ const result = localAdvancedFields(+ CODEX,+ { surface: 'launch-profile', keys: ['effort'] },+ { kind: 'no-server' }+ );+ expect(result.fields.map((field) => field.key)).toEqual(['model']);+ expect(result.problem).toBe(+ 'There is no Switch server to read the advanced configuration fields from, so only the model can be set.'+ );+ expect(+ localAdvancedFields(CODEX, { surface: 'none', keys: [] }, { kind: 'no-server' }).problem+ ).toBe('There is no Switch server to read the advanced configuration fields from.');+ });+});++describe('choicesNotOffered', () => {+ it('names a saved choice the server’s field does not offer', () => {+ expect(choicesNotOffered([EFFORT], { effort: 'High' })).toMatch(+ /Reasoning effort is “High”, which the Switch server does not offer/+ );+ });++ it('is null for offered and unset choices', () => {+ expect(choicesNotOffered([EFFORT], { effort: 'high' })).toBeNull();+ expect(choicesNotOffered([EFFORT], { effort: '' })).toBeNull();+ expect(choicesNotOffered([EFFORT], {})).toBeNull();+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.tsnew file mode 100644index 000000000..cb6b7865a--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/local-advanced-fields.ts@@ -0,0 +1,97 @@+import type { RepoAgentAttributes, RepoAgentField } from '@switch-console/core/agents/plugins';+import { MODEL_FIELD } from '@renderer/features/managed-agents/managed-agent-changes';+import type {+ AgentAdvancedSettings,+ AgentAdvancedSurface,+} from '@shared/core/agents/agent-advanced-settings';+import type { AdvancedConfigField } from '@shared/core/managed-agents/managed-agents';++/**+ * The "Advanced configuration" of an agent this Console runs: the model, when+ * its provider keeps per-agent settings, then the fields the agent's Switch+ * server defines for its provider that the provider's plugin applies.+ *+ * The server is the only place the fields are defined. When they cannot be+ * read the form says why and offers only the model, rather than a copy of+ * them; a provider the server lists with no fields offers no more than the+ * model, and one that keeps no per-agent settings offers nothing.+ */+export type LocalAdvancedFields = {+ /** Where the provider keeps the settings; undefined until known. */+ surface: AgentAdvancedSurface | undefined;+ /** The fields to render, in order; empty until the server's are known. */+ fields: RepoAgentField[];+ /** Why the form is not the whole of what the server defines, said for a person. */+ problem: string | null;+};++/** What is known of the server's fields for the provider. */+export type ServerFields =+ | { kind: 'no-server' }+ | { kind: 'loading' }+ | { kind: 'error'; message: string }+ | { kind: 'schema'; schema: Record<string, AdvancedConfigField[]> };++/** The fields and problem for what is known of the plugin's settings and the server's fields. Pure. */+export function localAdvancedFields(+ provider: { id: string; label: string },+ settings: AgentAdvancedSettings,+ server: ServerFields+): Omit<LocalAdvancedFields, 'surface'> {+ const providerLabel = provider.label;+ const model = settings.surface === 'none' ? [] : [MODEL_FIELD];+ switch (server.kind) {+ case 'loading':+ return { fields: [], problem: null };+ case 'no-server':+ return {+ fields: model,+ problem: `There is no Switch server to read the advanced configuration fields from${onlyModel(settings)}.`,+ };+ case 'error':+ return { fields: model, problem: server.message };+ case 'schema': {+ const offered = server.schema[provider.id];+ if (!offered)+ return {+ fields: model,+ problem: `The Switch server does not list ${providerLabel}, so it defines no advanced configuration for it.`,+ };+ const applied = offered.filter((field) => settings.keys.includes(field.key));+ const unapplied = offered.filter((field) => !settings.keys.includes(field.key));+ return {+ fields: [...model, ...applied],+ problem:+ unapplied.length === 0+ ? null+ : `The Switch server defines settings this version of Console cannot apply for ${providerLabel}: ${unapplied.map((field) => field.label).join(', ')}. Update Console to set them.`,+ };+ }+ }+}++/** How a problem ends: what the form still offers, when it offers the model. */+export function onlyModel(settings: AgentAdvancedSettings): string {+ return settings.surface === 'none' ? '' : ', so only the model can be set';+}++/**+ * The saved choices the server's fields do not offer, said for a person, or+ * null when there are none: a value typed into a definition by hand is kept+ * as written, and a choice list would otherwise show it as nothing chosen.+ */+export function choicesNotOffered(+ fields: RepoAgentField[],+ attributes: RepoAgentAttributes+): string | null {+ const off = fields.flatMap((field) => {+ const value = attributes[field.key];+ if (field.type !== 'select' || typeof value !== 'string' || value === '') return [];+ return (field.options ?? []).some((option) => option.value === value)+ ? []+ : [`${field.label} is “${value}”`];+ });+ return off.length === 0+ ? null+ : `${off.join('; ')}, which the Switch server does not offer. Choose another value or leave it unset.`;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsxindex d8d47909d..1b0c29649 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx@@ -2,8 +2,8 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { Loader2, RefreshCw } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useCallback, useEffect, useMemo, useState } from 'react';+import { AdvancedConfigProblem } from '@renderer/features/locations/components/add-agent-modal/agent-advanced-config';import {- advancedFields,attributesFromForm,emptyForm,formFromAttributes,@@ -11,7 +11,9 @@ import {type FormValue,} from '@renderer/features/locations/components/agent-definition-fields';import { type ModelCatalogueResult } from '@renderer/features/locations/components/agent-model-catalogue';+import { choicesNotOffered } from '@renderer/features/locations/components/local-advanced-fields';import { useAgentEdit } from '@renderer/features/locations/components/main-panel/agent-edits';+import { useLocalAdvancedFields } from '@renderer/features/locations/components/use-local-advanced-fields';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { isProvisioned } from '@renderer/features/sessions/stores/session-store';import { describeFailure } from '@renderer/lib/errors/describe-failure';@@ -50,22 +52,9 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetticonst providerId = agent?.providerId ?? null;const editable = !!agent;- const { data: allFields } = useQuery({- queryKey: ['agentAdvancedFields', providerId],- queryFn: () => (providerId ? rpc.agents.advancedFields({ providerId }) : Promise.resolve([])),- enabled: !!providerId,- });- const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);-- // Where the provider keeps these settings, which decides whether a running- // session can be brought onto them. Asked of the provider rather than inferred- // from its id.- const { data: surface } = useQuery({- queryKey: ['agentAdvancedSurface', providerId],- queryFn: () =>- providerId ? rpc.agents.advancedSurface({ providerId }) : Promise.resolve('none' as const),- enabled: !!providerId,- });+ // The fields are the agent's Switch server's; where the provider keeps the+ // values decides whether a running session can be brought onto them.+ const { fields, surface, problem } = useLocalAdvancedFields(agent?.serverId ?? null, providerId);const { data: locations } = useQuery({queryKey: ['locations'],@@ -106,11 +95,13 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetticonst staleSessionIds = sessionsStartedBeforeChanges(locationId, agentId);+ // A stored setting the form does not show — the server's fields could not be+ // read, or this Console cannot apply one — is kept rather than dropped unseen.const save = useMutation({mutationFn: () =>rpc.agents.updateAdvancedConfig({agentId: agentId as string,- attributes: attributesFromForm(fields, form),+ attributes: { ...current, ...attributesFromForm(fields, form) },}),onSuccess: () => {toast({ title: 'Advanced configuration saved' });@@ -204,7 +195,10 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSettirevert: onRevert,});- if (!editable || fields.length === 0) return null;+ if (!editable) return null;++ const shownProblem = problem ?? (current ? choicesNotOffered(fields, current) : null);+ if (fields.length === 0) return <AdvancedConfigProblem problem={shownProblem} />;// A launch profile is read once, when the session starts, so a change cannot// reach a running session without one — and a resume carries the new profile,@@ -215,41 +209,44 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetticonst showStaleNotice = restartable && staleSessionIds.length > 0 && (dirty || save.isSuccess);return (- <AdvancedConfigDisclosure- fields={fields}- form={form}- summary={summariseValues(fields, savedForm)}- catalogue={catalogue}- intro="The agent's model, reasoning effort and tools. Its instructions are above, and its name is fixed."- onFieldChange={setField}- >- {showStaleNotice && (- <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3">- <p className="text-xs text-foreground-muted">- {staleSessionIds.length === 1- ? 'A session is running'- : `${staleSessionIds.length} sessions are running`}{' '}- on the previous configuration — it is read only when a session starts.{' '}- {dirty- ? 'Save, then Restart to apply it now.'- : 'It applies to the next session — or use Restart to apply it now (the conversation is resumed).'}- </p>- <Button- size="sm"- variant="outline"- disabled={dirty || restart.isPending}- onClick={() => restart.mutate()}- >- {restart.isPending ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <RefreshCw className="size-3.5" />- )}- {restartFailed.length > 0 ? 'Retry restart' : 'Restart'}- </Button>- </div>- )}- </AdvancedConfigDisclosure>+ <div className="flex flex-col gap-2">+ <AdvancedConfigDisclosure+ fields={fields}+ form={form}+ summary={summariseValues(fields, savedForm)}+ catalogue={catalogue}+ intro="The agent's model, reasoning effort and tools. Its instructions are above, and its name is fixed."+ onFieldChange={setField}+ >+ {showStaleNotice && (+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3">+ <p className="text-xs text-foreground-muted">+ {staleSessionIds.length === 1+ ? 'A session is running'+ : `${staleSessionIds.length} sessions are running`}{' '}+ on the previous configuration — it is read only when a session starts.{' '}+ {dirty+ ? 'Save, then Restart to apply it now.'+ : 'It applies to the next session — or use Restart to apply it now (the conversation is resumed).'}+ </p>+ <Button+ size="sm"+ variant="outline"+ disabled={dirty || restart.isPending}+ onClick={() => restart.mutate()}+ >+ {restart.isPending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <RefreshCw className="size-3.5" />+ )}+ {restartFailed.length > 0 ? 'Retry restart' : 'Restart'}+ </Button>+ </div>+ )}+ </AdvancedConfigDisclosure>+ <AdvancedConfigProblem problem={shownProblem} />+ </div>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/use-local-advanced-fields.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/use-local-advanced-fields.tsnew file mode 100644index 000000000..9699cffad--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/use-local-advanced-fields.ts@@ -0,0 +1,55 @@+import { useQuery } from '@tanstack/react-query';+import { useMemo } from 'react';+import { useAdvancedConfigSchema } from '@renderer/features/managed-agents/use-managed-agents';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { rpc } from '@renderer/lib/ipc';+import { type AgentProviderId, getProvider } from '@shared/core/providers/agent-provider-registry';+import {+ type LocalAdvancedFields,+ localAdvancedFields,+ onlyModel,+ type ServerFields,+} from './local-advanced-fields';++/** The advanced configuration fields of an agent of `providerId` on the server `serverId`. */+export function useLocalAdvancedFields(+ serverId: string | null,+ providerId: AgentProviderId | null+): LocalAdvancedFields {+ const settingsQuery = useQuery({+ queryKey: ['agentAdvancedSettings', providerId],+ queryFn: () => rpc.agents.advancedSettings({ providerId: providerId! }),+ enabled: providerId !== null,+ });+ const schemaQuery = useAdvancedConfigSchema(providerId === null ? null : serverId);+ const settings = settingsQuery.data;+ const schema = schemaQuery.data;+ const schemaError = schemaQuery.error;+ // Memoised on what it is built from, so a form that resets when its fields+ // change is not reset on every render.+ return useMemo((): LocalAdvancedFields => {+ if (!providerId || !settings) return { surface: undefined, fields: [], problem: null };+ const server: ServerFields =+ serverId === null+ ? { kind: 'no-server' }+ : schemaError+ ? {+ kind: 'error',+ message: failureText(+ schemaError,+ `The Switch server’s advanced configuration fields could not be read${onlyModel(settings)}.`+ ),+ }+ : schema+ ? { kind: 'schema', schema }+ : { kind: 'loading' };+ return {+ surface: settings.surface,+ ...localAdvancedFields(+ { id: providerId, label: getProvider(providerId)?.name ?? providerId },+ settings,+ server+ ),+ };+ }, [providerId, serverId, settings, schema, schemaError]);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsxindex b947f3e3e..4b15de3ca 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/load-existing-agents-section.tsx@@ -41,7 +41,7 @@ import {import { Spinner } from '@renderer/lib/ui/spinner';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { AGENT_PROVIDERS, getProvider } from '@shared/core/providers/agent-provider-registry';+import { agentProviders, getProvider } from '@shared/core/providers/agent-provider-registry';type LoadableAgentRow = {name: string;@@ -318,7 +318,7 @@ export function LoadExistingAgentsSection({return () => clearInterval(id);}, [deepScan.isPending]);- const providerOptions = AGENT_PROVIDERS.filter((p) => p.detectable !== false);+ const providerOptions = agentProviders();return (<section className="pt-2">diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsxindex 271f4b5d3..288234fbf 100644--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx@@ -31,8 +31,8 @@ import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import { StatusBadge } from '@renderer/lib/ui/status-badge';import {- AGENT_PROVIDER_IDS,asAgentProviderId,+ isValidProviderId,} from '@shared/core/providers/agent-provider-registry';import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';import { isHostBlocked } from '@shared/core/remote-hosts/reachability';@@ -300,8 +300,7 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {signIn={// Installed is not usable: a session also needs// the CLI signed in on this host.- !blocked &&- (AGENT_PROVIDER_IDS as readonly string[]).includes(row.agentId) ? (+ !blocked && isValidProviderId(row.agentId) ? (<ProviderConnectionStatusproviderId={asAgentProviderId(row.agentId)}sshHost={sshHost}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.tsindex 62bcda3df..5dc9a5d5d 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-store.ts@@ -12,7 +12,7 @@ import { workspacesStore } from '@renderer/features/workspaces/workspaces-store'import type { Snapshottable } from '@renderer/lib/stores/snapshottable';import type { AgentConnectionKind } from '@shared/core/agents/agent-connection';import {- AGENT_PROVIDER_IDS,+ agentProviderIds,isValidProviderId,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';@@ -371,7 +371,7 @@ export class SidebarStore implements Snapshottable<SidebarSnapshot> {const providerId = this.locationProviderId(location.id);if (providerId) present.add(providerId);}- return AGENT_PROVIDER_IDS.filter((id) => present.has(id));+ return agentProviderIds().filter((id) => present.has(id));}get sidebarRows(): SidebarRow[] {diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsxindex 0c51dd6b5..ed3e4f144 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx@@ -45,8 +45,8 @@ import { Switch } from '@renderer/lib/ui/switch';import { cn } from '@renderer/utils/utils';import { AGENT_NAME_PATTERN, slugifyAgentNamePart } from '@shared/core/agents/agent-slug';import {- AGENT_PROVIDER_IDS,type AgentProviderId,+ isValidProviderId,providerDisplayName,} from '@shared/core/providers/agent-provider-registry';import { describeRemoteDirRefusal } from '@shared/core/remote-hosts/remote-dir';@@ -482,8 +482,8 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {: providerParam? String(values[providerParam.name] ?? ''): (pickedProvider ?? '');- const provider = (AGENT_PROVIDER_IDS as readonly string[]).includes(providerText)- ? (providerText as AgentProviderId)+ const provider: AgentProviderId | null = isValidProviderId(providerText)+ ? providerText: null;const locationText = entry.location? interpolate(entry.location, values)@@ -580,9 +580,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {const list =at && at.location !== LOCAL_RUN_LOCATION ? availability.data : localAvailability.data;candidates = list- ?.filter(- (a) => a.available && (AGENT_PROVIDER_IDS as readonly string[]).includes(a.agentId)- )+ ?.filter((a) => a.available && isValidProviderId(a.agentId)).map((a) => a.agentId);}if (candidates === undefined) continue; // the list is still loadingdiff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-selector/agent-selector-options.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-selector/agent-selector-options.tsindex a300bf893..9485f2bdf 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-selector/agent-selector-options.ts+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-selector/agent-selector-options.ts@@ -1,5 +1,5 @@import {- AGENT_PROVIDERS,+ agentProviderIds,getProvider,type AgentProviderId,} from '@shared/core/providers/agent-provider-registry';@@ -24,11 +24,9 @@ export function buildAgentGroups(installingAgents: ReadonlySet<AgentProviderId> = new Set(),getName?: (id: AgentProviderId) => string): AgentGroup[] {- const allAgentIds = AGENT_PROVIDERS.map((p) => p.id);+ const allAgentIds = agentProviderIds();const installedSet = new Set(- [...installedAgents, ...assumedInstalledAgents].filter((id) =>- allAgentIds.includes(id as AgentProviderId)- )+ [...installedAgents, ...assumedInstalledAgents].filter((id) => allAgentIds.includes(id)));const resolveName = getName ?? ((id: AgentProviderId) => getProvider(id)?.name ?? id);diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsxindex 03d2ef148..8b5b8b268 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx@@ -4,14 +4,6 @@ import { rpc } from '@renderer/lib/ipc';import { Button } from '@renderer/lib/ui/button';import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';-const loginCommands: Record<AgentProviderId, string> = {- claude: 'claude auth login',- codex: 'codex login',- cursor: 'agent login',- antigravity: 'antigravity-acp --login',- opencode: 'opencode auth login',-};-/*** Whether a provider's CLI is installed and signed in on a machine. One check* per provider, machine and directory, shared by every component that asks:@@ -48,8 +40,6 @@ export function providerProblem(return null;}-export { loginCommands };-export function ProviderConnectionStatus({providerId,sshHost,@@ -61,9 +51,10 @@ export function ProviderConnectionStatus({dir: string;compact?: boolean;}) {+ const provider = getProvider(providerId);const query = useProviderReadiness(providerId, sshHost, dir, true);const copy = useMutation({- mutationFn: () => navigator.clipboard.writeText(loginCommands[providerId]),+ mutationFn: (command: string) => navigator.clipboard.writeText(command),});const data = query.data;const checking = query.isFetching;@@ -98,7 +89,7 @@ export function ProviderConnectionStatus({<div className="flex items-center gap-2"><Icon className={`size-4 shrink-0 ${tone} ${checking ? 'animate-spin' : ''}`} /><span className="font-medium">- {getProvider(providerId)?.name} · {headline}+ {provider?.name ?? providerId} · {headline}</span><ButtonclassName="ml-auto shrink-0"@@ -125,17 +116,17 @@ export function ProviderConnectionStatus({: data?.message}</p>)}- {!checking && data?.installed && !ready && (+ {!checking && data?.installed && !ready && provider && (<div className="mt-2 space-y-1"><p>Run in a terminal {sshHost ? `on ${sshHost}` : 'on this computer'}, then Recheck:</p><div className="flex items-center gap-2 rounded bg-background px-2 py-1"><code className="min-w-0 flex-1 text-xs break-all select-all">- {loginCommands[providerId]}+ {provider.loginCommand}</code><Buttonsize="sm"variant="ghost"- onClick={() => copy.mutate()}+ onClick={() => copy.mutate(provider.loginCommand)}aria-label="Copy sign-in command">{copy.isSuccess ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsxindex f455a21a8..30ee8acff 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx@@ -1,7 +1,7 @@import { CircleAlert } from 'lucide-react';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { loginCommands, providerProblem, useProviderReadiness } from './provider-connection-status';+import { providerProblem, useProviderReadiness } from './provider-connection-status';/*** A warning beside an agent whose provider cannot run on the agent's machine:@@ -23,13 +23,14 @@ export function ProviderIssueIndicator({const { data } = useProviderReadiness(providerId, sshHost, '', hostReachable);const problem = providerProblem(data);if (!problem) return null;- const name = getProvider(providerId)?.name ?? providerId;+ const provider = getProvider(providerId);+ const name = provider?.name ?? providerId;const where = sshHost ? `on ${sshHost}` : 'on this computer';const fix =data?.installed === false? `Install the ${name} CLI ${where}.`- : data?.status === 'unauthenticated'- ? `Run \`${loginCommands[providerId]}\` ${where}.`+ : data?.status === 'unauthenticated' && provider+ ? `Run \`${provider.loginCommand}\` ${where}.`: data?.message;return (<Tooltip>diff --git a/console/apps/switch-console-desktop/src/renderer/main.tsx b/console/apps/switch-console-desktop/src/renderer/main.tsxindex a1801ce0e..2dabea9d1 100644--- a/console/apps/switch-console-desktop/src/renderer/main.tsx+++ b/console/apps/switch-console-desktop/src/renderer/main.tsx@@ -15,12 +15,15 @@ import { wireMouseNavigation } from '@renderer/lib/layout/mouse-navigation';import { viewStateCache } from '@renderer/lib/stores/view-state-cache';import { log } from '@renderer/utils/logger';import { initSoundPlayer } from '@renderer/utils/soundPlayer';+import { setAgentProviderCatalogue } from '@shared/core/providers/agent-provider-registry';import type { NavigationSnapshot, SidebarSnapshot } from '@shared/view-state';import { App } from './App';import { ErrorBoundary } from './lib/components/error-boundary';import { appState } from './lib/stores/app-state';async function bootstrap() {+ // Before anything else: stores and views read provider metadata synchronously.+ setAgentProviderCatalogue(await rpc.providers.catalogue());wireExternalLinkRequests();appState.update.start();diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsxindex babe0b186..974f7468b 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/advanced-config-sections.test.tsx@@ -4,21 +4,17 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/**- * One "Advanced configuration" per agent, in the add-agent modal.+ * One "Advanced configuration" per agent, in the add-agent modal, built from+ * the agent's Switch server's fields for its provider.** A provider keeps its per-agent settings in exactly one place — a repo-agent* definition (Claude Code) or a launch profile (Codex, OpenCode) — and the- * agent's Settings tab picks between them by asking which. The creation form- * did not ask: it rendered the definition section and the launch-profile- * section side by side, and the launch-profile one reads a "give me the fields,- * from wherever they live" call that falls back to the definition fields. So a- * Claude Code agent got the same section twice, offering to configure the same- * thing in two boxes that wrote to different places.+ * definition section and the launch-profile section render side by side, each+ * only for its own surface, so no provider gets the same section twice.*/-const definitionFields = vi.hoisted(() => vi.fn());-const advancedFields = vi.hoisted(() => vi.fn());-const advancedSurface = vi.hoisted(() => vi.fn());+const advancedSettings = vi.hoisted(() => vi.fn());+const advancedConfigSchema = vi.hoisted(() => vi.fn());vi.mock('@renderer/lib/ipc', () => ({rpc: {@@ -26,34 +22,35 @@ vi.mock('@renderer/lib/ipc', () => ({providerReadiness: vi.fn(() =>Promise.resolve({ status: 'unknown', message: 'Not checked in this test.', models: [] })),- definitionFields,- advancedFields,- advancedSurface,+ advancedSettings,modelCatalogue: vi.fn(() =>Promise.resolve({ kind: 'unavailable', reason: 'not asked in this test' })),},+ managedAgents: { advancedConfigSchema },},+ events: { on: vi.fn(() => () => {}) },}));import { AgentAdvancedConfig } from '@renderer/features/locations/components/add-agent-modal/agent-advanced-config';import { LaunchProfileConfig } from '@renderer/features/locations/components/add-agent-modal/launch-profile-config';-const FIELD = {- key: 'model',- label: 'Model',- type: 'string' as const,- required: false,- advanced: true,+const EFFORT = {+ key: 'effort',+ label: 'Reasoning effort',+ type: 'select' as const,+ options: [+ { value: '', label: 'Default' },+ { value: 'high', label: 'high' },+ ],};let container: HTMLDivElement | null = null;let root: Root | null = null;beforeEach(() => {- definitionFields.mockReset();- advancedFields.mockReset();- advancedSurface.mockReset();+ advancedSettings.mockReset();+ advancedConfigSchema.mockReset();});afterEach(async () => {@@ -63,9 +60,8 @@ afterEach(async () => {root = null;});-/** Renders the pair exactly as the modal does, and returns how many- * "Advanced configuration" sections ended up on screen. */-async function sectionCount(): Promise<number> {+/** Renders the pair exactly as the modal does, for an agent of `providerId` on `server-1`. */+async function render(providerId: string): Promise<HTMLDivElement> {container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);@@ -76,14 +72,16 @@ async function sectionCount(): Promise<number> {root!.render(<QueryClientProvider client={client}><AgentAdvancedConfig+ serverId="server-1"sshHost={null}dir=""- providerId={'claude' as never}+ providerId={providerId as never}initial={{}}onChange={() => {}}/><LaunchProfileConfig- providerId={'claude' as never}+ serverId="server-1"+ providerId={providerId as never}sshHost={null}dir="/tmp/repo"onChange={() => {}}@@ -91,43 +89,105 @@ async function sectionCount(): Promise<number> {</QueryClientProvider>));- // Both sections load their fields over RPC, so the first paint has neither.+ // The plugin's settings and the server's fields load over RPC, so the first+ // paint has neither.await act(async () => {await new Promise((resolve) => setTimeout(resolve, 0));});+ return container;+}++/** The "Advanced configuration" sections on screen. */+function sections(on: HTMLElement): HTMLButtonElement[] {// Matched on the opening words rather than the whole string: the disclosure// also summarises what it holds ("Claude Code · 1 field"), and how it is// summarised is not what this test is about.- return [...container.querySelectorAll('button')].filter((b) =>+ return [...on.querySelectorAll('button')].filter((b) =>b.textContent?.trim().startsWith('Advanced configuration')- ).length;+ );+}++/** The field labels of the one section, opened. */+async function openedLabels(on: HTMLElement): Promise<string[]> {+ const [section] = sections(on);+ await act(async () => section!.click());+ return [...on.querySelectorAll('label')].map((label) => label.textContent?.trim() ?? '');+}++function alertText(on: HTMLElement): string | null {+ return on.querySelector('[role="alert"]')?.textContent ?? null;}describe('the add-agent modal’s advanced sections', () => {it('shows one for a provider that keeps its settings in a definition', async () => {- // Claude Code. Note both calls answer with fields — that overlap is the- // whole bug, and it is what the surface has to arbitrate.- advancedSurface.mockResolvedValue('definition');- definitionFields.mockResolvedValue([FIELD]);- advancedFields.mockResolvedValue([FIELD]);+ advancedSettings.mockResolvedValue({ surface: 'definition', keys: ['effort'] });+ advancedConfigSchema.mockResolvedValue({ claude: [EFFORT] });- expect(await sectionCount()).toBe(1);+ const on = await render('claude');+ expect(sections(on)).toHaveLength(1);+ expect(await openedLabels(on)).toEqual(['Model (optional)', 'Reasoning effort (optional)']);+ expect(alertText(on)).toBeNull();});it('shows one for a provider that keeps them in a launch profile', async () => {- // Codex: no definition fields, so only the profile section has anything.- advancedSurface.mockResolvedValue('launch-profile');- definitionFields.mockResolvedValue([]);- advancedFields.mockResolvedValue([FIELD]);+ advancedSettings.mockResolvedValue({ surface: 'launch-profile', keys: ['effort'] });+ advancedConfigSchema.mockResolvedValue({ codex: [EFFORT] });++ const on = await render('codex');+ expect(sections(on)).toHaveLength(1);+ expect(await openedLabels(on)).toEqual(['Model (optional)', 'Reasoning effort (optional)']);+ });++ it('shows none for a provider the server lists with no fields and that keeps no settings', async () => {+ advancedSettings.mockResolvedValue({ surface: 'none', keys: [] });+ advancedConfigSchema.mockResolvedValue({ newcli: [] });++ const on = await render('newcli');+ expect(sections(on)).toHaveLength(0);+ expect(alertText(on)).toBeNull();+ });++ it('names a server field for a provider that keeps no settings, without a section', async () => {+ advancedSettings.mockResolvedValue({ surface: 'none', keys: [] });+ advancedConfigSchema.mockResolvedValue({ newcli: [EFFORT] });++ const on = await render('newcli');+ expect(sections(on)).toHaveLength(0);+ expect(alertText(on)).toMatch(/cannot apply for newcli: Reasoning effort/);+ });++ it('offers only the model for a launch-profile provider the server lists with no fields', async () => {+ advancedSettings.mockResolvedValue({ surface: 'launch-profile', keys: [] });+ advancedConfigSchema.mockResolvedValue({ cursor: [] });++ const on = await render('cursor');+ expect(await openedLabels(on)).toEqual(['Model (optional)']);+ expect(alertText(on)).toBeNull();+ });++ it('says so when the server’s fields cannot be read, and offers only the model', async () => {+ advancedSettings.mockResolvedValue({ surface: 'launch-profile', keys: ['effort'] });+ advancedConfigSchema.mockRejectedValue(new Error('Switch is unreachable.'));++ const on = await render('codex');+ expect(alertText(on)).toContain('Switch is unreachable.');+ expect(await openedLabels(on)).toEqual(['Model (optional)']);+ });++ it('says so when the server does not list the provider', async () => {+ advancedSettings.mockResolvedValue({ surface: 'launch-profile', keys: ['effort'] });+ advancedConfigSchema.mockResolvedValue({ claude: [] });- expect(await sectionCount()).toBe(1);+ const on = await render('codex');+ expect(alertText(on)).toMatch(/does not list Codex/);});- it('shows none for a provider with no per-agent settings at all', async () => {- advancedSurface.mockResolvedValue('none');- definitionFields.mockResolvedValue([]);- advancedFields.mockResolvedValue([]);+ it('names a server field this Console cannot apply, rather than offering it', async () => {+ advancedSettings.mockResolvedValue({ surface: 'launch-profile', keys: [] });+ advancedConfigSchema.mockResolvedValue({ codex: [EFFORT] });- expect(await sectionCount()).toBe(0);+ const on = await render('codex');+ expect(alertText(on)).toMatch(/cannot apply for Codex: Reasoning effort/);+ expect(await openedLabels(on)).toEqual(['Model (optional)']);});});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-advanced-settings.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-advanced-settings.tsnew file mode 100644index 000000000..bb693c7f6--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-advanced-settings.ts@@ -0,0 +1,18 @@+/** Where a provider keeps an agent's per-agent settings. */+export type AgentAdvancedSurface = 'definition' | 'launch-profile' | 'none';++/** What a provider's plugin does with an agent's advanced configuration. */+export type AgentAdvancedSettings = {+ /**+ * Where it keeps them. A caller has to treat the two surfaces differently —+ * the renderer offers a restart only for a launch profile, which is read once+ * at spawn and so cannot reach a session already running.+ *+ * Reported rather than inferred from the provider id: that check was+ * `=== 'codex'` for as long as Codex was the only provider with a profile,+ * and silently excluded the next one.+ */+ surface: AgentAdvancedSurface;+ /** The keys of the server's advanced configuration fields it applies. */+ keys: string[];+};diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.tsindex 66fdf21a8..74e3516d8 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts@@ -10,8 +10,9 @@ import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-sc* Per-agent, provider-specific launch configuration: the values folded into the* agent's launch profile at spawn.*- * The keys are whatever the provider declares in `mcp.launchProfileFields()`, so- * this schema does not name them. Two providers do not agree on what a per-agent+ * The keys are the model, the instructions and the advanced settings the+ * provider declares in `mcp.launchProfileSettings()`, so this schema does not+ * name them. Two providers do not agree on what a per-agent* setting even is — Codex has a reasoning-effort enum, a verbosity and a* reasoning summary; OpenCode has none of those, and instead has a model-specific* variant, a temperature, a top-p and a step cap. A fixed field list would be one@@ -36,7 +37,7 @@ const agentProviderConfigV2 = z.object({* key it does not know is ignored either way.*/providerId: z.string(),- /** Field key → value, as declared by that provider's `launchProfileFields()`. */+ /** Setting key → value: the model, the instructions and that provider's `launchProfileSettings()`. */values: z.record(z.string(), z.string()),});diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.test.ts b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.test.tsnew file mode 100644index 000000000..3e146e0b2--- /dev/null+++ b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from 'vitest';++/** A fresh copy of the module, with no catalogue installed yet. */+async function freshRegistry() {+ vi.resetModules();+ return import('./agent-provider-registry');+}++const provider = (id: string, name: string) => ({+ id,+ name,+ description: `${name} description`,+ docUrl: `https://${id}.example.com`,+ cliLabel: name,+ loginCommand: `${id} login`,+ knownAgentType: id,+});++describe('agent provider catalogue', () => {+ it('refuses to answer before it is loaded', async () => {+ const registry = await freshRegistry();++ expect(() => registry.agentProviders()).toThrow('read before it was loaded');+ expect(() => registry.isValidProviderId('claude')).toThrow('read before it was loaded');+ expect(() => registry.providerDisplayName('claude')).toThrow('read before it was loaded');+ });++ it('answers from the providers it was given, in their order', async () => {+ const registry = await freshRegistry();+ registry.setAgentProviderCatalogue([provider('b', 'Bee'), provider('a', 'Ay')]);++ expect(registry.agentProviderIds()).toEqual(['b', 'a']);+ expect(registry.providerNamesSentence()).toBe('Bee and Ay');+ expect(registry.asAgentProviderId('a')).toBe('a');+ expect(() => registry.asAgentProviderId('c')).toThrow("unknown agent provider 'c'");+ expect(registry.providerDisplayName('c')).toBe('c');+ });++ it('refuses a catalogue that names a provider twice', async () => {+ const registry = await freshRegistry();++ expect(() =>+ registry.setAgentProviderCatalogue([provider('a', 'Ay'), provider('a', 'Ay again')])+ ).toThrow('names a provider twice');+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.tsindex d2c5d85c5..22bdde9d5 100644--- a/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts+++ b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts@@ -1,184 +1,99 @@-export const AGENT_PROVIDER_IDS = ['codex', 'claude', 'antigravity', 'cursor', 'opencode'] as const;--export type AgentProviderId = (typeof AGENT_PROVIDER_IDS)[number];-/**- * Narrow a provider id that arrived as an opaque string — from a database row- * or a launch spec read off disk — to a registered one.- *- * Throws rather than passing it through: every consumer dispatches on this- * value, so an unregistered id silently selects no behaviour at all.+ * A provider id: the id of a plugin in `packages/plugins/src/agents/impl/<id>/`.+ * Open rather than a union so that adding a provider changes no desktop code;+ * a value from storage is checked against the catalogue with+ * {@link isValidProviderId} or {@link asAgentProviderId}.*/-export function asAgentProviderId(value: string): AgentProviderId {- if ((AGENT_PROVIDER_IDS as readonly string[]).includes(value)) return value as AgentProviderId;- throw new Error(`unknown agent provider '${value}'`);-}+export type AgentProviderId = string;+/**+ * What the desktop app shows and needs for one provider, built in the main+ * process from the provider's plugin metadata and its runtime entry in+ * `@switch-console/agent-providers`.+ */export type AgentProviderDefinition = {id: AgentProviderId;name: string;/** Short one-liner shown in the agent info card. */- description?: string;- docUrl?: string;- installCommand?: string;- commands?: string[];- versionArgs?: string[];- /** Skip running the CLI for dependency version detection. */- skipVersionProbe?: boolean;- detectable?: boolean;- cli?: string;- autoApproveFlag?: string;- /** Auto-approval is provided by provider-specific environment variables instead of CLI args. */- autoApproveViaEnv?: boolean;- initialPromptFlag?: string;- resumeFlag?: string;- /**- * CLI flag to assign a unique session ID per chat instance.- * Used to isolate session state when multiple chats of the same provider- * run in the same worktree. The flag receives a deterministic UUID- * derived from the Switch Console session ID.- * e.g. '--session-id' for Claude Code.- */- sessionIdFlag?: string;- newSessionFlag?: string;- sessionIdOnResumeOnly?: boolean;- /** Resume flag used when sessionIdOnResumeOnly is set but no provider session id is stored yet. */- resumeWithoutSessionFlag?: string;- defaultArgs?: string[];- planActivateCommand?: string;- autoStartCommand?: string;- icon?: string;- iconDark?: string;- /** Accessible alt text for the provider logo. */- alt?: string;- /** When true, the logo should be colour-inverted in dark mode. */- invertInDark?: boolean;+ description: string;+ docUrl: string;+ /** What to tell someone to install, where the product name alone would be ambiguous. */+ cliLabel: string;+ /** The command a person runs on the execution machine to sign the CLI in. */+ loginCommand: string;+ /** The Switch gateway's known-agent type, sent when an agent registers. */+ knownAgentType: string;};+type Catalogue = {+ providers: readonly AgentProviderDefinition[];+ byId: ReadonlyMap<string, AgentProviderDefinition>;+};++let catalogue: Catalogue | null = null;+/**- * Provider ids and display metadata, plus a mirror of each provider's argv shape.- *- * The argv fields here are descriptive, not authoritative: nothing reads them at- * spawn time. `packages/plugins/src/agents/impl/<id>/index.ts` builds the real- * command, so change the plugin first and update the mirror to match.+ * Install the provider catalogue. The main process builds it from the plugin+ * and runtime registries before anything else loads; the renderer fetches it+ * over RPC before its first render.*/-export const AGENT_PROVIDERS: AgentProviderDefinition[] = [- {- id: 'codex',- name: 'Codex',- description:- 'CLI that connects to OpenAI models for project-aware code assistance and terminal workflows.',- docUrl: 'https://github.com/openai/codex',- installCommand: 'npm install -g @openai/codex',- commands: ['codex'],- versionArgs: ['--version'],- cli: 'codex',- // Kept in sync with the plugin by the parity test in- // src/main/core/providers/provider-argv-parity.test.ts.- autoApproveFlag: '-c approval_policy="never"',- initialPromptFlag: '',- resumeFlag: 'resume',- sessionIdFlag: ' ',- sessionIdOnResumeOnly: true,- resumeWithoutSessionFlag: 'resume --last',- icon: 'openai.svg',- alt: 'Codex',- },- {- id: 'claude',- name: 'Claude Code',- description:- 'CLI that uses Anthropic Claude for code edits, explanations, and structured refactors in the terminal.',- docUrl: 'https://code.claude.com/docs/en/quickstart',- installCommand: 'curl -fsSL https://claude.ai/install.sh | bash',- commands: ['claude'],- versionArgs: ['--version'],- cli: 'claude',- autoApproveFlag: '--dangerously-skip-permissions',- initialPromptFlag: '',- resumeFlag: '--resume',- sessionIdFlag: '--session-id',- planActivateCommand: '/plan',- icon: 'claude.svg',- alt: 'Claude Code',- },- {- id: 'cursor',- name: 'Cursor',- description:- "Cursor's agent CLI; provides editor-style, location-aware assistance from the shell.",- docUrl: 'https://cursor.com/docs/cli/overview',- installCommand: 'curl https://cursor.com/install -fsS | bash',- commands: ['cursor-agent'],- versionArgs: ['--version'],- cli: 'cursor-agent',- autoApproveFlag: '-f --approve-mcps',- initialPromptFlag: '',- resumeFlag: '--resume',- icon: 'cursor.svg',- alt: 'Cursor CLI',- invertInDark: true,- },- {- id: 'antigravity',- name: 'Antigravity',- description:- 'Google Antigravity ACP with native authentication, approvals and persistent conversations.',- docUrl: 'https://github.com/agentclientprotocol/registry/tree/main/antigravity-acp',- commands: ['antigravity-acp'],- versionArgs: ['--version'],- cli: 'antigravity-acp',- initialPromptFlag: '',- planActivateCommand: '/plan',- icon: 'antigravity.svg',- alt: 'Antigravity ACP',- },- {- id: 'opencode',- name: 'OpenCode',- description:- 'OpenCode CLI that interfaces with models for code generation and edits from the shell.',- docUrl: 'https://opencode.ai/docs/cli/',- installCommand: 'npm install -g opencode-ai',- commands: ['opencode'],- versionArgs: ['--version'],- cli: 'opencode',- autoApproveViaEnv: true,- initialPromptFlag: '--prompt',- resumeFlag: '--session',- sessionIdFlag: '--session',- sessionIdOnResumeOnly: true,- resumeWithoutSessionFlag: '--continue',- icon: 'opencode.svg',- iconDark: 'opencode-dark.svg',- alt: 'OpenCode CLI',- },-];+export function setAgentProviderCatalogue(providers: readonly AgentProviderDefinition[]): void {+ const byId = new Map(providers.map((provider) => [provider.id, provider]));+ if (byId.size !== providers.length)+ throw new Error(+ `The agent provider catalogue names a provider twice: ${providers.map((p) => p.id).join(', ')}`+ );+ catalogue = { providers, byId };+}-const PROVIDER_MAP = new Map<string, AgentProviderDefinition>(- AGENT_PROVIDERS.map((provider) => [provider.id, provider])-);+function loaded(): Catalogue {+ if (!catalogue)+ throw new Error(+ 'The agent provider catalogue was read before it was loaded. The main process sets it when its plugin registry loads, and the renderer before its first render.'+ );+ return catalogue;+}-export function getProvider(id: AgentProviderId): AgentProviderDefinition | undefined {- return PROVIDER_MAP.get(id);+/** Every provider, in the order the interface lists them. */+export function agentProviders(): readonly AgentProviderDefinition[] {+ return loaded().providers;}-export function getInstallCommandForProvider(id: AgentProviderId): string | null {- return PROVIDER_MAP.get(id)?.installCommand ?? null;+export function agentProviderIds(): AgentProviderId[] {+ return loaded().providers.map((provider) => provider.id);+}++/** Every provider's name as a sentence fragment: "Codex, Claude Code and OpenCode". */+export function providerNamesSentence(): string {+ const names = loaded().providers.map((provider) => provider.name);+ return names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names.join('');+}++export function getProvider(id: string): AgentProviderDefinition | undefined {+ return loaded().byId.get(id);+}++/** A registered provider's definition; throws for an id the catalogue does not have. */+export function requireProvider(id: string): AgentProviderDefinition {+ const provider = getProvider(id);+ if (!provider) throw new Error(`unknown agent provider '${id}'`);+ return provider;}-/**- * Validates if a string is a valid provider ID.- * @param value - The value to validate- * @returns true if the value is a valid provider ID, false otherwise- */export function isValidProviderId(value: unknown): value is AgentProviderId {- return typeof value === 'string' && AGENT_PROVIDER_IDS.includes(value as AgentProviderId);+ return typeof value === 'string' && loaded().byId.has(value);}-export function isValidProviderSessionId(providerId: string, providerSessionId: string): boolean {- if (providerId === 'opencode') return providerSessionId.startsWith('ses');- return true;+/**+ * Narrow a provider id that arrived as an opaque string — from a database row+ * or a launch spec read off disk — to a registered one.+ *+ * Throws rather than passing it through: every consumer dispatches on this+ * value, so an unregistered id silently selects no behaviour at all.+ */+export function asAgentProviderId(value: string): AgentProviderId {+ if (isValidProviderId(value)) return value;+ throw new Error(`unknown agent provider '${value}'`);}/**@@ -188,20 +103,13 @@ export function isValidProviderSessionId(providerId: string, providerSessionId:*/export function providerDisplayName(id: string | null | undefined): string | null {if (!id) return null;- if (!isValidProviderId(id)) return id;- return PROVIDER_MAP.get(id)?.name ?? id;+ return getProvider(id)?.name ?? id;}export function getDescriptionForProvider(id: AgentProviderId): string | null {- return PROVIDER_MAP.get(id)?.description ?? null;+ return getProvider(id)?.description ?? null;}export function getDocUrlForProvider(id: AgentProviderId): string | null {- return PROVIDER_MAP.get(id)?.docUrl ?? null;-}--export function listDetectableProviders(): AgentProviderDefinition[] {- return AGENT_PROVIDERS.filter(- (provider) => provider.detectable !== false && provider.commands?.length- );+ return getProvider(id)?.docUrl ?? null;}diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/hook-session-id.ts b/console/apps/switch-console-desktop/src/shared/core/providers/hook-session-id.tsindex fd21977cc..54c2d05f2 100644--- a/console/apps/switch-console-desktop/src/shared/core/providers/hook-session-id.ts+++ b/console/apps/switch-console-desktop/src/shared/core/providers/hook-session-id.ts@@ -1,15 +1,5 @@-import { AGENT_PROVIDER_IDS, type AgentProviderId } from './agent-provider-registry';+import type { AgentProviderId } from './agent-provider-registry';export function makeHookSessionId(provider: AgentProviderId, sessionId: string): string {return `${provider}-session-${sessionId}`;}--export function parseHookSessionId(- id: string-): { providerId: AgentProviderId; sessionId: string } | null {- for (const providerId of AGENT_PROVIDER_IDS) {- const prefix = `${providerId}-session-`;- if (id.startsWith(prefix)) return { providerId, sessionId: id.slice(prefix.length) };- }- return null;-}diff --git a/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/global-setup.ts b/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/global-setup.tsnew file mode 100644index 000000000..757321a31--- /dev/null+++ b/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/global-setup.ts@@ -0,0 +1,23 @@+import { PROVIDER_RUNTIMES } from '@switch-console/agent-providers';+import { pluginRegistry } from '@switch-console/plugins/agents';+import type { TestProject } from 'vitest/node';+import { buildAgentProviderCatalogue } from '@main/core/providers/agent-provider-catalogue';+import type { AgentProviderDefinition } from '@shared/core/providers/agent-provider-registry';++declare module 'vitest' {+ export interface ProvidedContext {+ agentProviderCatalogue: AgentProviderDefinition[];+ }+}++/**+ * Builds the real provider catalogue once, in Node, and hands it to every test+ * file — browser ones included, which cannot load the plugin or runtime+ * registries themselves.+ */+export default function setup(project: TestProject): void {+ project.provide(+ 'agentProviderCatalogue',+ buildAgentProviderCatalogue(pluginRegistry.getAll(), PROVIDER_RUNTIMES)+ );+}diff --git a/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/install.ts b/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/install.tsnew file mode 100644index 000000000..c50a8155b--- /dev/null+++ b/console/apps/switch-console-desktop/tooling/agent-provider-catalogue/install.ts@@ -0,0 +1,8 @@+import { inject } from 'vitest';+import { setAgentProviderCatalogue } from '@shared/core/providers/agent-provider-registry';++/**+ * Installs the provider catalogue before a test file loads, as the main process+ * and the renderer each do before anything reads it.+ */+setAgentProviderCatalogue(inject('agentProviderCatalogue'));diff --git a/console/apps/switch-console-desktop/vitest.config.ts b/console/apps/switch-console-desktop/vitest.config.tsindex 984a6e10b..fbf388e0a 100644--- a/console/apps/switch-console-desktop/vitest.config.ts+++ b/console/apps/switch-console-desktop/vitest.config.ts@@ -16,6 +16,13 @@ const alias = {// isolated copy installed under tooling/node-deps/ (compiled for system Node).// The root node_modules/better-sqlite3 stays Electron-compiled at all times,// so no rebuild dance is needed when switching between app dev and DB tests.+// Every project that runs app code gets the real agent provider catalogue,+// built in Node by the global setup and installed before each test file.+const agentProviderCatalogue = {+ globalSetup: ['./tooling/agent-provider-catalogue/global-setup.ts'],+ setupFiles: ['./tooling/agent-provider-catalogue/install.ts'],+};+const toolingAlias = {...alias,'better-sqlite3': resolve(__dirname, 'tooling/node-deps/node_modules/better-sqlite3'),@@ -33,6 +40,7 @@ export default defineConfig({test: {name: 'node',environment: 'node',+ ...agentProviderCatalogue,include: ['src/**/*.test.ts', 'scripts/**/*.test.ts'],exclude: ['**/_*/**',@@ -52,6 +60,7 @@ export default defineConfig({test: {name: 'main-db',environment: 'node',+ ...agentProviderCatalogue,include: ['src/main/core/**/*.db.test.ts','src/main/db/legacy-port/**/*.test.ts',@@ -114,7 +123,11 @@ export default defineConfig({// Supplies the preload bridge before a test module is evaluated, so// renderer imports can be static. See the file's docblock for why a// dynamic import of app code breaks React here.- setupFiles: ['./src/renderer/tests/browser/setup-electron-bridge.ts'],+ globalSetup: agentProviderCatalogue.globalSetup,+ setupFiles: [+ './src/renderer/tests/browser/setup-electron-bridge.ts',+ ...agentProviderCatalogue.setupFiles,+ ],},},],diff --git a/console/docs/add-an-agent-provider.md b/console/docs/add-an-agent-provider.mdnew file mode 100644index 000000000..0b55de8bd--- /dev/null+++ b/console/docs/add-an-agent-provider.md@@ -0,0 +1,246 @@+# Add an agent provider++This is how to add a new agent CLI to Switch. If the CLI speaks the+[Agent Client Protocol](https://agentclientprotocol.com) (ACP), you write a hooks+file and a plugin entry, register each of them with one line, and add one line to+core's provider table. You don't write an adapter. A CLI that doesn't speak ACP+needs its own adapter; see [Not ACP](#not-acp) at the end.++New to this? Read [Adding support for a new agent CLI](new-agent-cli.md) first:+it's the short version, step by step.++Paths below are relative to the repository root. `<id>` is the provider id+Switch stores, in lowercase (`cursor`, `antigravity`). Choose it once: agent+records and sessions keep it, so it can't be renamed later.++## What you touch++| # | File | What it is |+|---|---|---|+| 1 | `console/packages/agent-providers/src/<id>/<id>-acp.ts` | The ACP hooks: how to run the CLI and what makes it different from other ACP agents |+| 2 | `console/packages/agent-providers/src/providers/registry.ts` | One line: `acpProviderRuntime(<id>Acp)` in `PROVIDER_RUNTIMES` |+| 3 | `console/packages/plugins/src/agents/impl/<id>/index.ts` and `icon.ts` | The plugin: name, description, how to find and install the CLI, and its icon |+| 4 | `console/packages/plugins/src/agents/plugin-registry.ts` | One line: the plugin in the registration list |+| 5 | `core/switch_core/providers/registry.py` | One entry in the server's provider table: the id and a label |+| 6 | `console/packages/agent-providers/src/<id>/<id>.integration.test.ts` | The conformance suite, run against the real CLI |++That's all you touch. Console's create-agent flow, the provider settings, the+agent controller's status report, the gateway's provider list and the server's+validation all read these registrations. If a change outside these files seems+to be needed, the registration is missing something. Say so in your PR rather+than adding another hardcoded provider list.++Registrations 2 and 4 must name the same providers. Console and the agent+controller refuse to start when they don't, and the error names the half that's+missing.++## 1. The ACP hooks++Copy `console/packages/agent-providers/src/cursor/cursor-adapter.ts` or+`src/antigravity/antigravity-adapter.ts` and trim it. The interface is+`AcpProviderHooks` in `src/acp/hooks.ts`, and every field is documented there.+A minimal provider looks like this:++```ts+import { createAcpAdapter, type AcpAdapter } from '../acp/acp-adapter';+import type { AcpAdapterOptions, AcpProviderHooks } from '../acp/hooks';++export const exampleAcp: AcpProviderHooks = {+ provider: 'example',+ label: 'Example CLI',+ defaultBinary: 'example',+ capabilities: {+ modelSwitchInSession: true,+ steering: false,+ resume: true,+ approvals: true,+ userInput: false,+ },+ launch: ({ binaryPath, env }) => ({ command: binaryPath, args: ['acp'], env }),+ loginCommand: 'example login',+};++export function createExampleAdapter(options: AcpAdapterOptions = {}): AcpAdapter {+ return createAcpAdapter(exampleAcp, options);+}+```++The generic adapter already handles the following, picking behaviour from what+the agent advertises. **Don't re-implement any of it in hooks:**++- the `initialize` handshake, and refusing to start when HTTP MCP servers are+ configured but the agent doesn't declare `mcpCapabilities.http`;+- session start, and resume through `session/load` or `session/resume`. When the+ agent advertises neither, the host starts a fresh conversation and keeps the+ transcript;+- the session's MCP servers, both stdio and HTTP;+- prompts, attachments (images, audio and embedded resources where advertised,+ resource links otherwise) and the system context;+- streaming text and tool calls into the transcript, including diffs and raw+ output;+- permission requests:+ - allow once without asking for tools on the session's own MCP servers,+ everything in full access, and edits in auto-accept-edits;+ - otherwise offer allow once, allow for this session, and reject, and never+ offer permanent policies;+- model selection through a `model` config option or through the session's+ `models` list;+- cancel, queued turns, process exit and errors.++Add hooks only for what really differs:++| Hook | When you need it |+|---|---|+| `launch` (required) | The binary, its arguments and its environment. It may prepare the host first, as Antigravity does with its profile directory. The environment is complete and not merged with anything, so add to `env`, never to `process.env`. |+| `loginCommand` (required) | The command a person runs on the execution machine to sign in. It is shown whenever the CLI is signed out. |+| `checkSignIn` | Answers "is this CLI signed in?" **without signing it in**. Use the `handshake()` it's given, or the CLI's own status command. Without it, the check runs the handshake and reports the sign-in as unknown. |+| `inheritEnv` | Environment variables the CLI reads, such as its API key, that the session host should pass through from the machine. The common vendor keys (`OPENAI_API_KEY`, `GEMINI_API_KEY`, proxies…) are already passed through. |+| `authMethodId` | The `authenticate` method to send when a session starts, given its environment; return undefined when that environment already signs the CLI in (Cursor with `CURSOR_API_KEY`). Omit it for an agent that needs none. |+| `sessionMode` | The ACP mode for each Switch runtime mode, when the agent's modes are permission levels. |+| `promptCapabilities` | Content the agent accepts without advertising it. Prefer fixing the advertisement upstream. |+| `mcpServerOf` | How a tool call names its MCP server, if the agent says so (in `_meta`, `rawInput`…). Without it, tools on registered servers still ask for permission. |+| `itemType` | Vendor typing for tool calls, such as subagents. |+| `permission` | A permission request the vendor uses for something else, such as Antigravity's questions. |+| `extensions` | Vendor-specific requests and notifications, such as Cursor's `cursor/ask_question`, `cursor/create_plan` and `update_todos`. Use `askQuestions`, `requestDecision` and `completeItem` on the context they're given; these already cancel when no turn is running. |+| `nativeSessionIdPrefix` | Only when an earlier, non-ACP runtime of the same provider stored session ids that must not be resumed. |++Then add the runtime to `PROVIDER_RUNTIMES` in `src/providers/registry.ts`:++```ts+acpProviderRuntime(exampleAcp),+```++### Sign-in checks++A sign-in check must never be what changes its answer. Don't call+`authenticate` from it: for most agents that's the sign-in itself, and it can+open a browser on the machine. The check runs whenever Console or the agent+controller asks about the provider, including on remote and headless machines.++## 2. The plugin++The plugin is what Console shows and how it finds the CLI. Copy+`console/packages/plugins/src/agents/impl/cursor/` and edit it:++- `metadata` sets the display name, a one-line description and the docs URL.+ Optional fields, all documented in+ `console/packages/core/src/agents/plugins/index.ts`:+ - `cliLabel`: for when the name alone is ambiguous ("Cursor CLI").+ - `knownAgentType`: defaults to the id.+ - `sessionStartMaySignIn`: set it when starting a session can open a sign-in+ browser, so model listing checks sign-in first.+- `hostDependency` gives the executable names to look for on `PATH`, plus+ install commands per platform.+- `mcp`, `prompt`, `sessions` and the rest: for an ACP CLI that runs only+ through the session host, copy Antigravity's (`mcp: { kind: 'none' }`,+ `prompt: { kind: 'none' }`, and a `buildCommand` that throws).+- `icon.ts` holds an SVG. Give it an `alt`, and set `invertInDark` if it is a+ dark single-colour mark.++The plugin declares no advanced-configuration fields. Those are defined only in+core's provider table (step 3), and Console builds every agent's form from what+the agent's Switch server serves. A plugin only applies values: if the provider+takes settings, its plugin lists the keys it applies and the shape of each+(`mcp.launchProfileSettings()`, or `repoAgents.advancedSettings()` for a+provider that runs named definitions) and turns them into launch inputs. Leave+both out for a provider with no settings. A field the server defines that the+plugin doesn't apply is shown as one this Console can't apply, and the agent+controller refuses a definition that sets it.++Add it to the list in `plugin-registry.ts`. The list order is the order the UI+shows.++## 3. Core's provider table++Add one entry to the provider table in `core/switch_core/providers/registry.py`+with the id and a display label. Leave everything else at its default unless the+server really needs it:++- **Advanced settings:** none by default. Empty is valid, and Console then+ offers no advanced form. When the provider does take settings, this is the+ only place their fields (label, type, help, choices) are defined: add them to+ `core/switch_core/providers/advanced_fields.py`, and have the plugin apply+ each by its key (step 2).+- **Known-agent profile:** the generic managed-agent profile, keyed by the id.++The server validates agent definitions, the gateway's provider list and+`get_advanced_config` from this table, and no migration is needed.++## 4. Conformance and the real CLI++Add `src/<id>/<id>.integration.test.ts`:++```ts+import { spawnSync } from 'node:child_process';+import { describeConformance, echoMcpServerSpec } from '../testing/index';+import { createExampleAdapter } from './example-acp';++describeConformance('example', {+ createAdapter: async () => createExampleAdapter(),+ unavailableReason: async () => {+ const probe = spawnSync('example', ['--version'], { encoding: 'utf8' });+ return probe.error || probe.status !== 0 ? 'the example binary is not on PATH' : null;+ },+ mcpServers: { echo: echoMcpServerSpec() },+});+```++The suite runs ten scenarios against the real CLI:++- a simple turn+- a file write in full access+- an approval accepted+- an approval declined+- an interrupt+- a message mid-turn+- resume+- a question+- a subagent+- a registered MCP server++It spends real tokens and skips itself, saying why, when the binary or sign-in+is missing. It doesn't run in CI, so run it locally with the CLI installed and+signed in:++```bash+cd console/packages/agent-providers+pnpm exec vitest run src/<id>/<id>.integration.test.ts+```++The suite gives the CLI a minimal environment (PATH, HOME and a few basics),+not your shell's. A CLI that signs in with an API key needs the key passed+through in `env`, or it falls back to its interactive sign-in and times out.+Cursor's test does this:++```ts+...(process.env.CURSOR_API_KEY ? { env: { CURSOR_API_KEY: process.env.CURSOR_API_KEY } } : {}),+```++Skip a scenario only when the CLI really can't do it, and give the reason in+`skip`, with the CLI version and date. Record the result in the known-limits table in+`console/packages/agent-providers/README.md`.++## 5. Checks before you open the PR++```bash+cd console+pnpm -r --filter './packages/**' run build+pnpm -r run typecheck+pnpm -r run lint+pnpm -r run format:check+pnpm -r run test+```++If you changed core, also run `just check`, `just typecheck` and `just test`+from the repository root. Then open the pull request and fill in the template's+agent CLI section: the real-CLI test summary and a short video of the CLI+working in Console. [Adding support for a new agent CLI](new-agent-cli.md) says+what the video has to show.++## Not ACP++A CLI with its own protocol needs an adapter that implements `ProviderAdapter`+(`console/packages/agent-providers/src/adapter.ts`). Codex (JSON-RPC+app-server), OpenCode (HTTP and SSE) and Claude (the Agent SDK) are the+examples. Register it in `PROVIDER_RUNTIMES` with its own `createAdapter`,+`checkSignIn` and `loginCommand`. Everything after step 1 is the same.diff --git a/console/docs/new-agent-cli.md b/console/docs/new-agent-cli.mdnew file mode 100644index 000000000..1edee6139--- /dev/null+++ b/console/docs/new-agent-cli.md@@ -0,0 +1,77 @@+# Adding support for a new agent CLI++This page is the short version: what to do, in order, and what your pull+request has to show. The technical details are in+[Add an agent provider](add-an-agent-provider.md).++## Before you start++- **Check the CLI speaks ACP** (the [Agent Client Protocol](https://agentclientprotocol.com)).+ Most do: look for an `acp` command or an ACP mode in its docs. If it does,+ you write a small file describing the CLI and reuse everything else. If it+ doesn't, the work is much bigger; ask first.+- **Have the CLI installed and logged in on your computer**, with an account+ that can make model calls. You'll need it to test.++## 1. Write the code++Follow [Add an agent provider](add-an-agent-provider.md). For an ACP CLI you+add:++- a file that says how to start the CLI and what's special about it;+- a plugin with its name, icon and how to install it;+- one line in each of two lists, and one line on the server.++You shouldn't need to change anything else. If you do, say why in your pull+request.++## 2. Run the automatic tests++From `console/`:++```bash+pnpm -r --filter './packages/**' run build+pnpm -r run typecheck && pnpm -r run lint && pnpm -r run test+```++These use a fake CLI, so they're quick and free. They also run on your pull+request.++## 3. Test with the real CLI++The automatic tests can't run your CLI for real: that needs your account and+spends real model calls. So you run this check yourself, once:++```bash+cd console/packages/agent-providers+pnpm exec vitest run src/<your-cli>/<your-cli>.integration.test.ts+```++It runs 10 checks against the real CLI: a simple reply, writing a file,+asking for permission, stopping a turn, remembering a conversation, and so+on. Copy the summary it prints at the end. You'll paste it into your pull+request.++If a check can't pass because the CLI really can't do that thing, mark it as+skipped in the test file with the reason. Don't leave it failing.++## 4. Try it in Switch Console++Run Switch Console from your branch and record your screen while you do this:++1. Open the agent setup and show your CLI marked as **signed in**.+2. Create an agent with it and pick a model.+3. Talk to the agent in a room and get a reply.+4. Ask it to run a shell command, and show that it asks your permission first.++Keep the video short; a couple of minutes is plenty.++## 5. Open the pull request++The pull request template asks for two things:++- **the real-CLI test summary** from step 3;+- **the video** from step 4.++Fill in both. We review a new CLI from those two things, so a pull request+without them waits.diff --git a/console/packages/agent-controller/src/providers.test.ts b/console/packages/agent-controller/src/providers.test.tsnew file mode 100644index 000000000..e2f15ace5--- /dev/null+++ b/console/packages/agent-controller/src/providers.test.ts@@ -0,0 +1,18 @@+import { providerRuntimeIds } from '@switch-console/agent-providers';+import { pluginRegistry } from '@switch-console/plugins/agents';+import { expect, it } from 'vitest';+import { PROVIDERS, registeredProviders } from './providers';++it('runs every provider that has both a plugin and a runtime', () => {+ expect([...PROVIDERS].sort()).toEqual([...pluginRegistry.ids()].sort());+ expect([...PROVIDERS].sort()).toEqual([...providerRuntimeIds()].sort());+});++it('refuses a provider registered on only one side, naming the missing half', () => {+ expect(() => registeredProviders(['claude', 'newcli'], ['claude'])).toThrow(+ 'No runtime in agent-providers for: newcli.'+ );+ expect(() => registeredProviders(['claude'], ['claude', 'newcli'])).toThrow(+ 'No plugin for: newcli.'+ );+});diff --git a/console/packages/agent-controller/src/providers.ts b/console/packages/agent-controller/src/providers.tsnew file mode 100644index 000000000..445506d22--- /dev/null+++ b/console/packages/agent-controller/src/providers.ts@@ -0,0 +1,31 @@+import { providerRuntimeIds } from '@switch-console/agent-providers';+import { pluginRegistry } from '@switch-console/plugins/agents';++/**+ * The providers both halves of a registration name: a plugin, and a runtime+ * the execution host can run. A provider with only one half is a build that+ * would report it and then fail to run it, so that refuses to start instead.+ */+export function registeredProviders(+ plugins: readonly string[],+ runtimes: readonly string[]+): readonly string[] {+ const missingRuntime = plugins.filter((id) => !runtimes.includes(id));+ const missingPlugin = runtimes.filter((id) => !plugins.includes(id));+ if (missingRuntime.length || missingPlugin.length)+ throw new Error(+ [+ 'Agent provider registration is incomplete.',+ ...(missingRuntime.length+ ? [`No runtime in agent-providers for: ${missingRuntime.join(', ')}.`]+ : []),+ ...(missingPlugin.length ? [`No plugin for: ${missingPlugin.join(', ')}.`] : []),+ ].join(' ')+ );+ return plugins;+}++export const PROVIDERS: readonly string[] = registeredProviders(+ pluginRegistry.ids(),+ providerRuntimeIds()+);diff --git a/console/packages/agent-controller/src/schemas.ts b/console/packages/agent-controller/src/schemas.tsindex 148a65ef2..fb5dca6cb 100644--- a/console/packages/agent-controller/src/schemas.ts+++ b/console/packages/agent-controller/src/schemas.ts@@ -1,5 +1,6 @@import { sealedLoginSchema } from '@switch-console/agent-providers';import { z } from 'zod';+import { PROVIDERS } from './providers';/*** The wire messages between this controller and Management, as v1 uses them.@@ -14,11 +15,12 @@ import { z } from 'zod';export const PROTOCOL_VERSION = 2;-export const PROVIDERS = ['claude', 'codex', 'opencode', 'antigravity', 'cursor'] as const;-export type Provider = (typeof PROVIDERS)[number];+export { PROVIDERS };+/** A provider id this controller has both a plugin and a runtime for. */+export type Provider = string;export function isProvider(value: string): value is Provider {- return (PROVIDERS as readonly string[]).includes(value);+ return PROVIDERS.includes(value);}/** The contract's reason codes, plus the ones v1 adds. */@@ -196,7 +198,7 @@ export type ProcessState = (typeof PROCESS_STATES)[number];const reasonCode = z.enum(REASON_CODES);export const providerStatusSchema = z.object({- provider: z.enum(PROVIDERS),+ provider: z.string().refine(isProvider, { message: 'Not a provider this controller runs.' }),installed: z.boolean(),version: z.string().nullable(),auth: z.enum(['ok', 'expired', 'missing', 'unknown']),diff --git a/console/packages/agent-controller/src/template.test.ts b/console/packages/agent-controller/src/template.test.tsindex 668fb15e9..9fc31d10c 100644--- a/console/packages/agent-controller/src/template.test.ts+++ b/console/packages/agent-controller/src/template.test.ts@@ -200,7 +200,7 @@ describe('buildWatcherTemplate', () => {});describe('advancedConfigDefinitionProblem', () => {- it('accepts the advanced configuration a provider offers', () => {+ it('accepts the advanced configuration a provider applies', () => {expect(advancedConfigDefinitionProblem('opencode', {...definition,@@ -224,6 +224,24 @@ describe('advancedConfigDefinitionProblem', () => {).toMatch(/'effort'/);});+ it('accepts an empty configuration for a provider that applies no settings', () => {+ expect(+ advancedConfigDefinitionProblem('antigravity', { ...definition, advanced_config: {} })+ ).toBeNull();+ expect(+ advancedConfigDefinitionProblem('cursor', { ...definition, advanced_config: {} })+ ).toBeNull();+ });++ it('names a value of a shape this controller cannot apply', () => {+ expect(+ advancedConfigDefinitionProblem('opencode', {+ ...definition,+ advanced_config: { temperature: 'warm' },+ })+ ).toMatch(/'temperature'.*number/);+ });+it('names a Claude Code setting its session cannot start with', () => {expect(advancedConfigDefinitionProblem('claude', {diff --git a/console/packages/agent-controller/src/template.ts b/console/packages/agent-controller/src/template.tsindex d54b14129..fc9eb1d88 100644--- a/console/packages/agent-controller/src/template.ts+++ b/console/packages/agent-controller/src/template.ts@@ -2,12 +2,8 @@ import { randomUUID } from 'node:crypto';import {agentLaunchDefinitionSchema,controllerConnectionId,- createAntigravityAdapter,- createClaudeAdapter,- createCodexAdapter,- createCursorAdapter,- createOpencodeAdapter,EXECUTION_INHERIT_ENV,+ providerRuntime,type ProviderCapabilities,type SharedHostConfig,sharedConfigSchema,@@ -22,16 +18,11 @@ const capabilityCache = new Map<Provider, ProviderCapabilities>();function adapterCapabilities(provider: Provider): ProviderCapabilities {const cached = capabilityCache.get(provider);if (cached) return cached;- const adapter =- provider === 'claude'- ? createClaudeAdapter()- : provider === 'codex'- ? createCodexAdapter()- : provider === 'opencode'- ? createOpencodeAdapter()- : provider === 'antigravity'- ? createAntigravityAdapter()- : createCursorAdapter();+ const adapter = providerRuntime(provider).createAdapter({+ binaryPath: undefined,+ logger: undefined,+ skill: '',+ });capabilityCache.set(provider, adapter.capabilities);return adapter.capabilities;}@@ -43,8 +34,10 @@ export function watcherSessionId(agentId: string): string {/*** What keeps an agent's advanced configuration from being applied as defined,- * naming the field, or null when nothing does. A field this build does not- * know is refused rather than ignored: a newer server may send one an older+ * naming the field, or null when nothing does. The server checked the values+ * against its fields when the definition was written; what is left to refuse+ * here is a field this build's plugin does not apply, or a value of a shape it+ * cannot apply, rather than ignore it: a newer server may send one an older* controller cannot apply.*/export function advancedConfigDefinitionProblem(diff --git a/console/packages/agent-providers/README.md b/console/packages/agent-providers/README.mdindex 159e51a63..a55df5c4b 100644--- a/console/packages/agent-providers/README.md+++ b/console/packages/agent-providers/README.md@@ -12,7 +12,13 @@ protocols. These five adapters are the only Console session runtime.ride along in `raw` for debugging.- `src/testing/` — the conformance suite (`describeConformance`) that everyadapter runs against the real provider, plus `EventRecorder`.-- `src/<provider>/` — one directory per provider.+- `src/acp/` — the generic Agent Client Protocol adapter every ACP-speaking+ CLI runs on, and the `AcpProviderHooks` a CLI supplies.+- `src/providers/registry.ts` — `PROVIDER_RUNTIMES`, the one list of providers+ the execution host can run: each entry's adapter, sign-in check and login+ command.+- `src/<provider>/` — one directory per provider. For an ACP CLI this is only+ its hooks.## Transports (decided, do not relitigate per adapter)@@ -21,8 +27,9 @@ protocols. These five adapters are the only Console session runtime.| `opencode` | `opencode serve` spawned per session, driven with `@opencode-ai/sdk` over HTTP + SSE | Sessions are server-side; permissions and questions are answerable over the API. One server per session because OpenCode stores MCP registrations per directory and Switch registers an MCP server per session. || `claude` | `@anthropic-ai/claude-agent-sdk` `query()` in streaming-input mode, one long-lived query per session | Mid-turn messages queue into the live loop; `canUseTool` carries both approvals and `AskUserQuestion`; sessions share the CLI's transcript files so `--resume` interoperates. || `codex` | `codex app-server` JSON-RPC over stdio | The Codex SDK wraps `codex exec`, which cannot answer approvals. app-server can, and supports `turn/steer`, `thread/resume` and `turn/interrupt`. |-| `antigravity` | `agy --input-format stream-json --output-format stream-json` over stdio | The only non-interactive surface the CLI has. The process stays alive between turns, so one NDJSON line per turn keeps the conversation, and `--conversation <id>` resumes it after the process goes away. |-| `cursor` | `agent acp` JSON-RPC over stdio | Native sessions, model catalogue, MCP registration and approvals. |+| `antigravity` | `antigravity-acp`, ACP over stdio, on the generic ACP adapter | Native sessions, resume, model selection through a `model` config option, MCP registration, approvals and questions. |+| `cursor` | `agent acp`, ACP over stdio, on the generic ACP adapter | Native sessions, model catalogue, MCP registration and approvals, plus Cursor's question, plan, todo and task extensions. |+| any new ACP CLI | ACP over stdio, on the generic ACP adapter | Write hooks, not an adapter: see [Add an agent provider](../../docs/add-an-agent-provider.md). |## Rules for an adapter@@ -58,54 +65,46 @@ does not filter; use `pnpm exec vitest run <file>` for one provider.| opencode | 1.18.27 | 10/10 | Auto-answers doom-loop and subagent asks in `full-access` with `once`, never `always` (OpenCode remembers `always` per directory). Config isolation only via `XDG_CONFIG_HOME`. || claude | 2.1.260 | 10/10 | `AskUserQuestion` is offered to a session **only while a `canUseTool` callback is registered** — in `default` and `bypassPermissions` alike — so the adapter registers one in every mode and filters the SDK's `CLAUDE_SDK_CAN_USE_TOOL_SHADOWED` warning rather than obeying it. A mid-turn message is queued after the running turn, not folded into it; the adapter keeps the turn open until every queued send is answered. || codex | 0.153.2 | 9/10 | `request_user_input` only works in Plan mode, so `user-input` is skipped. Subagents need `--enable multi_agent_v2`. `turn/steer` joins the running turn. |-| antigravity | 1.2.4 | 7/10 | Headless `agy` has no prompt channel at all: a tool that needs permission is auto-denied, so `approval-required` and `approval-declined` are skipped and the mode emits a `runtime.warning` at session start. `ask_question` is skipped by the CLI, so `user-input` is skipped. No steering — a mid-turn message queues as its own turn. No in-process cancel: an interrupt kills the process and the next turn respawns on `--conversation`. File tools run in the CLI's own scratch workspace unless `--add-dir <cwd>` is passed. Attachments are passed as file paths in the prompt text: the stream-json input accepts `text` blocks only and rejects `image`. Outside `full-access` a staged attachment is unreadable until its directory is passed as another `--add-dir`, which only takes effect at launch, so such a turn respawns first. A file the `download_attachment` Switch tool fetches lands under `~/.switch/sessions/<runtime pid>/media`, a directory named after a process the adapter never sees and created mid-turn, so outside `full-access` the session is given `~/.switch/sessions` at spawn and those downloads are readable without a respawn. |--## Cursor CLI--The local Cursor adapter uses `agent acp` with the installed CLI's existing login.-It registers session-scoped MCP servers, queues follow-up turns, supports native-resume and model selection, and translates tool, question and plan decisions to-Console events. Only caller-registered MCP tools bypass interactive decisions;-ordinary approvals select allow-once and never persist allow-always policies.-Cursor's question/plan extension methods are handled (including the ACP `_` wire-prefix). The installed CLI/default model used for verification did not expose its-AskQuestion tool, so real conversation questions use prose; protocol answer and-plan approval payloads are tested separately. Subagent lifecycle is verified.--Cursor is Console-managed and local-only; there is no separate connector install.-Create-agent and provider settings expose it when `agent` is installed.--## Antigravity CLI--The local Antigravity adapter drives `agy` in stream-json print mode with the-installed CLI's existing login. `HOME` cannot be redirected — the credential-lives in the macOS keychain keyed outside the CLI's own directories — so the-session runs against the user's real Antigravity configuration and the adapter-has to reach into it rather than build an isolated copy.--**MCP servers** go into `<cwd>/.agents/mcp_config.json`, the workspace-customization root the CLI walks up from the working directory. That is the only-location scoped to a single session's directory that keeps the caller's server-names: a `plugins/<name>/mcp_config.json` also works but the CLI renames every-server it finds there to `<plugin>_<server>`, and `~/.gemini/config/mcp_config.json`-is machine-wide. The adapter merges into whatever the file already had and puts-the original bytes back on stop. Two sessions sharing one working directory-therefore share the file; the last writer wins for a name they both use.--**Permissions** are the reason the adapter also touches-`~/.gemini/antigravity-cli/settings.json`, the one file whose `permissions.allow`-the CLI honours (a workspace `.agents/settings.json` is not read for this). In-the modes that do not pass `--dangerously-skip-permissions`, the caller's own MCP-servers are allow-listed there as `mcp(<name>/*)` so the session can reach the-room protocol it was started for, and nothing else is. The rules are refcounted-across the adapter's live sessions and removed when the last one stops.--**Attachments** are named by path in the turn text; the CLI reads them with its-own file tools rather than receiving bytes. The host stages them outside the-session's working directory, and outside `full-access` the CLI denies reading a-path it was not given, so the adapter passes their directory as another-`--add-dir`. That grant is read at launch only — writing it to a live process-changes nothing — so the first turn to bring a new directory respawns on-`--conversation` before it is sent, and later turns from the same directory reuse-the process. A `read_file` entry in the CLI's `denied_actions` still raises a-`runtime.warning` naming the attachments that may not have been opened.+| antigravity (ACP) | antigravity-acp 1.1.1 | 9/10 (2026-10-11) | `subagent` is skipped: `invoke_subagent` runs past the 300 s deadline, on main's adapter as on the generic one. `mcp-registered` passes on the generic adapter and timed out on main's. |+| cursor (ACP) | 2026.10.01 | not recorded | The account used hit Cursor's usage limit, so no model turn ran. Set `CURSOR_API_KEY` in the shell to run the suite with a key; the test passes it through. |+| antigravity (retired `agy` adapter, kept for history) | 1.2.4 | 7/10 | Headless `agy` has no prompt channel at all: a tool that needs permission is auto-denied, so `approval-required` and `approval-declined` are skipped and the mode emits a `runtime.warning` at session start. `ask_question` is skipped by the CLI, so `user-input` is skipped. No steering — a mid-turn message queues as its own turn. No in-process cancel: an interrupt kills the process and the next turn respawns on `--conversation`. File tools run in the CLI's own scratch workspace unless `--add-dir <cwd>` is passed. Attachments are passed as file paths in the prompt text: the stream-json input accepts `text` blocks only and rejects `image`. Outside `full-access` a staged attachment is unreadable until its directory is passed as another `--add-dir`, which only takes effect at launch, so such a turn respawns first. A file the `download_attachment` Switch tool fetches lands under `~/.switch/sessions/<runtime pid>/media`, a directory named after a process the adapter never sees and created mid-turn, so outside `full-access` the session is given `~/.switch/sessions` at spawn and those downloads are readable without a respawn. |++## ACP providers++Cursor and Antigravity run on one adapter, `src/acp/acp-adapter.ts`, which+covers the protocol and chooses behaviour from what the agent advertises in+`initialize` and `session/new`:++- resume uses `session/load` when the agent advertises `loadSession`, else+ `session/resume` when it advertises `sessionCapabilities.resume`, else asks+ the host for a fresh conversation;+- a `model` select in the session's config options is set with+ `session/set_config_option`; otherwise `session/set_model` is used against+ the session's `models` list;+- attachments go as `image`, `audio` or embedded `resource` blocks only where+ the agent (or its hooks) says it takes them, else as `resource_link`.++Everything else that differs between CLIs is in its hooks file+(`src/cursor/cursor-adapter.ts`, `src/antigravity/antigravity-adapter.ts`):+binary and arguments, the `authenticate` method, the mode for each runtime+mode, how a tool call names its MCP server, sign-in checks, and vendor+extensions.++Permission requests follow one policy for every ACP agent. A tool on an MCP+server the session registered is allowed once without asking, as is+everything in `full-access` and edits in `auto-accept-edits`. Otherwise the+person is offered allow once, allow for this session and reject; options+naming a permanent or future policy are never offered.++**Cursor** extensions: `cursor/ask_question` (several questions, multi-select),+`cursor/create_plan` (an approval with the plan as its detail),+`update_todos`, `task` and `generate_image`, each with and without the ACP `_`+prefix. The CLI and default model used for verification did not expose its+AskQuestion tool, so `user-input` is skipped in its conformance run.++**Antigravity** runs in its own profile directory (`GEMINI_HOME`), set up for+OAuth on first use. Its questions arrive as permission requests whose tool+call id starts with `interaction_`. Native session ids are stored with an+`acp:` prefix; a conversation saved by the retired `agy` runtime starts fresh.+Its sign-in check reads `authMethods` from the handshake and never calls+`authenticate`, which would open a browser.diff --git a/console/packages/agent-providers/src/acp-mcp.ts b/console/packages/agent-providers/src/acp-mcp.tsdeleted file mode 100644index 0b20788e4..000000000--- a/console/packages/agent-providers/src/acp-mcp.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { McpServerSpec } from './adapter';--/**- * Refuse to start an ACP session whose HTTP MCP servers the agent cannot- * reach.- *- * An ACP agent says in `initialize` whether it accepts MCP servers over HTTP- * (`agentCapabilities.mcpCapabilities.http`). The Switch tools are served that- * way, so an agent that does not declare it would start a session with no- * Switch tools and nothing to say why. `http` is what the agent declared.- */-export function requireHttpMcp(- agent: string,- servers: Record<string, McpServerSpec>,- http: boolean | undefined-): void {- const over = Object.entries(servers)- .filter(([, spec]) => spec.transport === 'http')- .map(([name]) => name);- if (over.length === 0 || http === true) return;- throw new Error(- `${agent} does not declare MCP over HTTP (agentCapabilities.mcpCapabilities.http), and the MCP server${over.length > 1 ? 's' : ''} ${over.join(', ')} ${over.length > 1 ? 'are' : 'is'} only reachable that way. Update ${agent}; the session is not started without its tools.`- );-}diff --git a/console/packages/agent-providers/src/acp/acp-adapter.test.ts b/console/packages/agent-providers/src/acp/acp-adapter.test.tsnew file mode 100644index 000000000..5416a0df6--- /dev/null+++ b/console/packages/agent-providers/src/acp/acp-adapter.test.ts@@ -0,0 +1,342 @@+import type * as fs from 'node:fs/promises';+import { beforeEach, expect, it, vi } from 'vitest';+import { ProviderConversationUnavailableError } from '../adapter';+import { FakeAppServer } from '../codex/fake-app-server';+import type { ProviderRuntimeEvent } from '../events';+import type { AcpProviderHooks } from './hooks';++vi.mock('node:fs/promises', async (original) => ({+ ...(await original<typeof fs>()),+ realpath: async (path: string) => path,+ readFile: async (_path: string, encoding?: string) =>+ encoding ? 'file text' : Buffer.from('bytes'),+}));+const servers: FakeAppServer[] = [];+/** What the fake agent answers; each test shapes it before starting a session. */+const agent: {+ capabilities: Record<string, unknown>;+ session: Record<string, unknown>;+} = { capabilities: {}, session: {} };+const spawned: Array<{ command: string; args: string[] }> = [];+vi.mock('node:child_process', () => ({+ spawn: (command: string, args: string[]) => {+ spawned.push({ command, args });+ const server = new FakeAppServer();+ server.replyAlways('initialize', () => ({ agentCapabilities: agent.capabilities }));+ for (const method of ['session/new', 'session/load', 'session/resume'])+ server.replyAlways(method, () => ({ sessionId: 'native', ...agent.session }));+ for (const method of ['session/set_mode', 'session/set_model', 'session/set_config_option'])+ server.replyAlways(method, () => ({}));+ servers.push(server);+ return server;+ },+}));+const { createAcpAdapter } = await import('./acp-adapter');++/** The least a new ACP provider has to say about itself. */+const dummy: AcpProviderHooks = {+ provider: 'dummy',+ label: 'Dummy ACP',+ defaultBinary: 'dummy-acp',+ capabilities: {+ modelSwitchInSession: true,+ steering: false,+ resume: true,+ approvals: true,+ userInput: false,+ },+ launch: ({ binaryPath, env }) => ({ command: binaryPath, args: ['--acp'], env }),+ loginCommand: 'dummy-acp login',+};++beforeEach(() => {+ servers.length = 0;+ spawned.length = 0;+ agent.capabilities = {};+ agent.session = {};+});++async function start(+ hooks: AcpProviderHooks = dummy,+ input: Partial<Parameters<ReturnType<typeof createAcpAdapter>['startSession']>[0]> = {}+) {+ const adapter = createAcpAdapter(hooks, {});+ const events: ProviderRuntimeEvent[] = [];+ adapter.subscribe((event) => events.push(event));+ const session = await adapter.startSession({+ sessionId: 's',+ cwd: '/work',+ runtimeMode: 'approval-required',+ env: {},+ mcpServers: {},+ ...input,+ });+ return { adapter, events, session, server: servers.at(-1)! };+}+const flush = () => new Promise((resolve) => setImmediate(resolve));++it('runs a provider from nothing but its launch hook, with no sign-in or mode calls', async () => {+ const { server, session } = await start();+ expect(spawned).toEqual([{ command: 'dummy-acp', args: ['--acp'] }]);+ expect(session).toEqual({ provider: 'dummy', sessionId: 's', nativeSessionId: 'native' });+ expect(server.received.map((m) => m.method)).toEqual(['initialize', 'session/new']);+});++it('resumes with session/load when the agent advertises it, and session/resume otherwise', async () => {+ agent.capabilities = { loadSession: true, sessionCapabilities: { resume: {} } };+ const loaded = await start(dummy, { resume: { nativeSessionId: 'saved' } });+ expect(loaded.server.received.find((m) => m.method === 'session/load')?.params).toMatchObject({+ sessionId: 'saved',+ });+ agent.capabilities = { sessionCapabilities: { resume: {} } };+ const resumed = await start(dummy, { resume: { nativeSessionId: 'saved' } });+ expect(resumed.server.received.some((m) => m.method === 'session/load')).toBe(false);+ expect(resumed.server.received.find((m) => m.method === 'session/resume')?.params).toMatchObject({+ sessionId: 'saved',+ });+});++it('asks for a fresh conversation when the agent cannot resume', async () => {+ await expect(start(dummy, { resume: { nativeSessionId: 'saved' } })).rejects.toBeInstanceOf(+ ProviderConversationUnavailableError+ );+});++it('selects models through the models list when the agent offers no model config option', async () => {+ agent.session = { models: { availableModels: [{ modelId: 'fast', name: 'Fast' }] } };+ const { adapter, server } = await start();+ expect(await adapter.listModels('s')).toEqual([{ id: 'fast', label: 'Fast', options: {} }]);+ await adapter.setModel('s', { id: 'fast' });+ expect(server.received.find((m) => m.method === 'session/set_model')?.params).toEqual({+ sessionId: 'native',+ modelId: 'fast',+ });+});++it('selects models through the model config option, refusing one it does not offer', async () => {+ agent.session = {+ models: { availableModels: [{ modelId: 'ignored', name: 'Ignored' }] },+ configOptions: [{ id: 'model', type: 'select', options: [{ value: 'deep', name: 'Deep' }] }],+ };+ const { adapter, server } = await start();+ expect(await adapter.listModels('s')).toMatchObject([{ id: 'deep' }]);+ await expect(adapter.setModel('s', { id: 'ignored' })).rejects.toThrow('Unavailable model');+ await adapter.setModel('s', { id: 'deep' });+ expect(server.received.find((m) => m.method === 'session/set_config_option')?.params).toEqual({+ sessionId: 'native',+ configId: 'model',+ value: 'deep',+ });+ expect(server.received.some((m) => m.method === 'session/set_model')).toBe(false);+});++it('sends attachments as the agent advertises it can take them, else as resource links', async () => {+ agent.capabilities = { promptCapabilities: { image: true } };+ const { adapter, server } = await start();+ await adapter.sendTurn({+ sessionId: 's',+ turnId: 't',+ text: 'look',+ attachments: [+ { path: '/work/shot.png', mimeType: 'image/png' },+ { path: '/work/notes.txt', mimeType: 'text/plain' },+ { path: '/work/voice.wav', mimeType: 'audio/wav' },+ ],+ });+ const prompt = (await server.waitFor('session/prompt')).params?.prompt as Array<+ Record<string, unknown>+ >;+ expect(prompt.map((block) => block.type)).toEqual([+ 'text',+ 'image',+ 'resource_link',+ 'resource_link',+ ]);+ expect(prompt[2]).toEqual({+ type: 'resource_link',+ uri: 'file:///work/notes.txt',+ name: 'notes.txt',+ mimeType: 'text/plain',+ });+});++it('embeds file contents when the agent takes embedded context', async () => {+ agent.capabilities = { promptCapabilities: { embeddedContext: true } };+ const { adapter, server } = await start();+ await adapter.sendTurn({+ sessionId: 's',+ turnId: 't',+ text: 'read',+ attachments: [{ path: '/work/notes.txt', mimeType: 'text/plain' }],+ });+ const prompt = (await server.waitFor('session/prompt')).params?.prompt as Array<+ Record<string, unknown>+ >;+ expect(prompt[1]).toEqual({+ type: 'resource',+ resource: { uri: 'file:///work/notes.txt', mimeType: 'text/plain', text: 'file text' },+ });+});++it('auto-approves a tool the hooks place on any session-registered MCP server', async () => {+ const hooks: AcpProviderHooks = {+ ...dummy,+ mcpServerOf: (toolCall) => toolCall._meta?.server as string | undefined,+ };+ const { adapter, events, server } = await start(hooks, {+ mcpServers: { echo: { transport: 'stdio', command: 'node', args: ['echo.js'] } },+ });+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });+ const options = [{ optionId: 'once', name: 'Allow once', kind: 'allow_once' }];+ for (const [id, server_] of [+ [70, 'echo'],+ [71, 'elsewhere'],+ ] as const)+ server.send({+ id,+ method: 'session/request_permission',+ params: {+ sessionId: 'native',+ toolCall: { toolCallId: `call-${id}`, _meta: { server: server_ } },+ options,+ },+ });+ await flush();+ expect(server.received.find((m) => m.id === 70)?.result).toEqual({+ outcome: { outcome: 'selected', optionId: 'once' },+ });+ expect(events.filter((e) => e.type === 'request.opened')).toHaveLength(1);+});++it('offers allow-for-session, maps it to the agent option, and answers decline with cancelled when no reject is offered', async () => {+ const { adapter, events, server } = await start();+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });+ const ask = (id: number, options: Array<Record<string, string>>) =>+ server.send({+ id,+ method: 'session/request_permission',+ params: { sessionId: 'native', toolCall: { toolCallId: `t${id}`, kind: 'execute' }, options },+ });+ ask(60, [+ { optionId: 'once', name: 'Allow', kind: 'allow_once' },+ { optionId: 'always', name: 'Allow for this session', kind: 'allow_always' },+ ]);+ await flush();+ const opened = events.filter((e) => e.type === 'request.opened');+ const first = opened[0];+ if (first?.type !== 'request.opened') throw new Error('No approval');+ expect(first.requestType).toBe('command_execution_approval');+ expect(first.title).toBe('Dummy ACP needs permission');+ expect(first.options.map((o) => o.decision)).toEqual(['accept', 'acceptForSession', 'cancel']);+ await adapter.respondToRequest('s', first.requestId, 'acceptForSession');+ ask(61, [{ optionId: 'once', name: 'Allow', kind: 'allow_once' }]);+ await flush();+ const second = events.filter((e) => e.type === 'request.opened')[1];+ if (second?.type !== 'request.opened') throw new Error('No approval');+ await adapter.respondToRequest('s', second.requestId, 'decline');+ await flush();+ expect(server.received.find((m) => m.id === 60)?.result).toEqual({+ outcome: { outcome: 'selected', optionId: 'always' },+ });+ expect(server.received.find((m) => m.id === 61)?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+});++it('approves without asking in full access, and approves only edits in auto-accept-edits', async () => {+ for (const [runtimeMode, kind, prompted] of [+ ['full-access', 'execute', 0],+ ['auto-accept-edits', 'edit', 0],+ ['auto-accept-edits', 'execute', 1],+ ] as const) {+ const { adapter, events, server } = await start(dummy, { runtimeMode });+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });+ server.send({+ id: 50,+ method: 'session/request_permission',+ params: {+ sessionId: 'native',+ toolCall: { toolCallId: 'x', kind },+ options: [{ optionId: 'once', name: 'Allow', kind: 'allow_once' }],+ },+ });+ await flush();+ expect(events.filter((e) => e.type === 'request.opened')).toHaveLength(prompted);+ }+});++it('lets vendor extensions ask questions and add items, and cancels them outside a turn', async () => {+ const hooks: AcpProviderHooks = {+ ...dummy,+ extensions: (context, on) => {+ on.request('_dummy/ask', () =>+ context.askQuestions(+ [+ {+ id: 'pick',+ question: 'Pick',+ options: [+ { label: 'A', value: 'a' },+ { label: 'B', value: 'b' },+ ],+ multiSelect: true,+ allowCustomAnswer: false,+ },+ ],+ (selected) => ({ picked: selected[0]!.values })+ )+ );+ on.notification('_dummy/note', () =>+ context.completeItem({ id: 'note', type: 'tool_call', status: 'completed', title: 'Note' })+ );+ },+ };+ const { adapter, events, server } = await start(hooks);+ server.send({ id: 40, method: '_dummy/ask', params: {} });+ await flush();+ expect(server.received.find((m) => m.id === 40)?.result).toEqual({+ outcome: { outcome: 'cancelled' },+ });+ await adapter.sendTurn({ sessionId: 's', turnId: 't', text: 'go' });+ server.notify('_dummy/note', {});+ server.send({ id: 41, method: '_dummy/ask', params: {} });+ await flush();+ const asked = events.find((e) => e.type === 'user-input.requested');+ if (asked?.type !== 'user-input.requested') throw new Error('No question');+ await expect(adapter.respondToUserInput('s', asked.requestId, { pick: ['z'] })).rejects.toThrow(+ 'offered'+ );+ await adapter.respondToUserInput('s', asked.requestId, { pick: ['a', 'b'] });+ await flush();+ expect(server.received.find((m) => m.id === 41)?.result).toEqual({ picked: ['a', 'b'] });+ expect(events.find((e) => e.type === 'item.completed')).toMatchObject({+ turnId: 't',+ item: { id: 'note', title: 'Note' },+ });+});++it('fills a stdio MCP server environment from the session for its envVars', async () => {+ const { server } = await start(dummy, {+ env: { TOKEN: 'secret', OTHER: 'unused' },+ mcpServers: {+ tools: {+ transport: 'stdio',+ command: 'node',+ args: [],+ env: { MODE: 'x' },+ envVars: ['TOKEN', 'MISSING'],+ },+ },+ });+ expect(server.received.find((m) => m.method === 'session/new')?.params?.mcpServers).toEqual([+ {+ name: 'tools',+ command: 'node',+ args: [],+ env: [+ { name: 'TOKEN', value: 'secret' },+ { name: 'MODE', value: 'x' },+ ],+ },+ ]);+});diff --git a/console/packages/agent-providers/src/acp/acp-adapter.ts b/console/packages/agent-providers/src/acp/acp-adapter.tsnew file mode 100644index 000000000..430a62c40--- /dev/null+++ b/console/packages/agent-providers/src/acp/acp-adapter.ts@@ -0,0 +1,767 @@+import { randomUUID } from 'node:crypto';+import { readFile, realpath } from 'node:fs/promises';+import { basename } from 'node:path';+import { pathToFileURL } from 'node:url';+import type { ModelChoice } from '@switch-console/shared/session-v1';+import type {+ ModelSelection,+ ProviderAdapter,+ ProviderCapabilities,+ ProviderSendTurnInput,+ ProviderSessionStartInput,+} from '../adapter';+import { ProviderConversationUnavailableError, ProviderSessionError } from '../adapter';+import type {+ ApprovalDecision,+ ProviderItem,+ ProviderRuntimeEvent,+ UserInputAnswers,+ UserInputQuestion,+} from '../events';+import { readiness, type ProviderReadiness, type SignInCheckInput } from '../readiness';+import {+ JsonRpcError,+ noopLogger,+ StdioJsonRpcClient,+ type ProviderLogger,+} from '../transport/stdio-json-rpc';+import type {+ AcpAdapterOptions,+ AcpProviderHooks,+ AcpSelectedAnswer,+ AcpSessionContext,+} from './hooks';+import { acpMcpServers, requireHttpMcp } from './mcp';+import {+ ACP_CANCELLED,+ modelConfigOption,+ modelsFromConfig,+ modelsFromList,+ type AcpConfigOption,+ type AcpInitializeResult,+ type AcpPermissionRequest,+ type AcpPromptCapabilities,+ type AcpSessionResult,+ type AcpSessionUpdate,+ type AcpToolCall,+} from './protocol';++export const ACP_CLIENT_INFO = { name: 'switch-console', version: '0.1.0' } as const;++/** The `initialize` request every ACP session and sign-in check opens with. */+export async function acpInitialize(client: StdioJsonRpcClient): Promise<AcpInitializeResult> {+ return await client.request<AcpInitializeResult>('initialize', {+ protocolVersion: 1,+ clientInfo: ACP_CLIENT_INFO,+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ });+}++/** A provider's sign-in check, run the way its hooks say, always tidying up the process. */+export async function checkAcpSignIn(+ hooks: AcpProviderHooks,+ input: SignInCheckInput+): Promise<ProviderReadiness> {+ let client: StdioJsonRpcClient | undefined;+ const handshake = async () => {+ client = new StdioJsonRpcClient({+ ...(await hooks.launch(input)),+ cwd: input.cwd,+ logger: noopLogger,+ onExit: () => {},+ });+ return await acpInitialize(client);+ };+ try {+ if (hooks.checkSignIn) return await hooks.checkSignIn({ ...input, handshake });+ await handshake();+ return readiness(+ 'unknown',+ `${hooks.label} started but has no sign-in check. If its sessions fail, sign in on the execution machine with ${hooks.loginCommand}.`+ );+ } finally {+ await client?.dispose();+ }+}++interface PendingDecision {+ responses: Map<ApprovalDecision, unknown>;+ settle: (value: unknown) => void;+}+interface PendingQuestion {+ questions: UserInputQuestion[];+ answer: (selected: AcpSelectedAnswer[]) => unknown;+ settle: (value: unknown) => void;+}+interface State {+ id: string;+ nativeId: string;+ client: StdioJsonRpcClient;+ turn: string | null;+ queue: ProviderSendTurnInput[];+ items: Map<string, ProviderItem>;+ decisions: Map<string, PendingDecision>;+ questions: Map<string, PendingQuestion>;+ messageId: string;+ messageText: string;+ stopping: boolean;+ interrupted: boolean;+ context: string;+ runtimeMode: ProviderSessionStartInput['runtimeMode'];+ mcpNames: Set<string>;+ toolServers: Map<string, string>;+ prompt: AcpPromptCapabilities;+ configOptions: AcpConfigOption[];+ models: ModelChoice[];+}++type Emittable<T = ProviderRuntimeEvent> = T extends ProviderRuntimeEvent+ ? Omit<T, 'eventId' | 'provider' | 'sessionId' | 'createdAt'>+ : never;++/**+ * One adapter for every agent that speaks the Agent Client Protocol. The+ * protocol is handled here, choosing behaviour from what the agent advertises+ * (`session/load` or `session/resume`, a models list or a `model` config+ * option); what differs between CLIs comes from {@link AcpProviderHooks}.+ */+export class AcpAdapter implements ProviderAdapter {+ readonly provider: string;+ readonly capabilities: ProviderCapabilities;+ private readonly sessions = new Map<string, State>();+ private readonly listeners = new Set<(event: ProviderRuntimeEvent) => void>();+ private readonly logger: ProviderLogger;++ constructor(+ private readonly hooks: AcpProviderHooks,+ private readonly options: AcpAdapterOptions+ ) {+ this.provider = hooks.provider;+ this.capabilities = hooks.capabilities;+ this.logger = options.logger ?? noopLogger;+ }++ subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }+ hasSession(id: string): boolean {+ return this.sessions.has(id);+ }++ async startSession(input: ProviderSessionStartInput) {+ const { hooks } = this;+ if (this.hasSession(input.sessionId))+ throw new ProviderSessionError(hooks.provider, input.sessionId, 'session already started');+ const cwd = await realpath(input.cwd);+ const prefix = hooks.nativeSessionIdPrefix;+ if (input.resume && prefix && !input.resume.nativeSessionId.startsWith(prefix.prefix))+ throw new ProviderConversationUnavailableError(+ hooks.provider,+ input.sessionId,+ prefix.legacyMessage+ );+ const launch = await hooks.launch({+ binaryPath: this.options.binaryPath ?? hooks.defaultBinary,+ cwd,+ env: input.env,+ });+ const client = new StdioJsonRpcClient({+ ...launch,+ cwd,+ logger: this.logger,+ onExit: (reason) => this.exited(input.sessionId, reason),+ });+ const state: State = {+ id: input.sessionId,+ nativeId: '',+ client,+ turn: null,+ queue: [],+ items: new Map(),+ decisions: new Map(),+ questions: new Map(),+ messageId: '',+ messageText: '',+ stopping: false,+ interrupted: false,+ context: input.systemContext ?? '',+ runtimeMode: input.runtimeMode,+ mcpNames: new Set(Object.keys(input.mcpServers)),+ toolServers: new Map(),+ prompt: {},+ configOptions: [],+ models: [],+ };+ this.sessions.set(state.id, state);+ const context = this.context(state);+ client.onNotification('session/update', (params) => {+ const payload = params as { sessionId: string; update: AcpSessionUpdate };+ if (payload.sessionId === state.nativeId) this.update(state, payload.update);+ });+ client.onServerRequest('session/request_permission', (params) =>+ this.permission(state, context, params as AcpPermissionRequest)+ );+ hooks.extensions?.(context, {+ request: (method, handler) => client.onServerRequest(method, async (p) => handler(p)),+ notification: (method, handler) => client.onNotification(method, handler),+ });+ this.emit(state, { type: 'session.state.changed', status: 'starting' });+ try {+ const initialized = await acpInitialize(client);+ const agent = initialized.agentCapabilities ?? {};+ requireHttpMcp(hooks.label, input.mcpServers, agent.mcpCapabilities?.http);+ state.prompt = {+ image: Boolean(agent.promptCapabilities?.image || hooks.promptCapabilities?.image),+ audio: Boolean(agent.promptCapabilities?.audio || hooks.promptCapabilities?.audio),+ embeddedContext: Boolean(+ agent.promptCapabilities?.embeddedContext || hooks.promptCapabilities?.embeddedContext+ ),+ };+ // Signing in belongs here: starting a session is work the user asked+ // for, so a browser opening is an answer to something they did. Sign-in+ // checks stop at the handshake above.+ const authMethodId = hooks.authMethodId?.(input.env);+ if (authMethodId) await client.request('authenticate', { methodId: authMethodId });+ const mcpServers = acpMcpServers(input.mcpServers, input.env);+ let method = 'session/new';+ if (input.resume) {+ method = agent.loadSession+ ? 'session/load'+ : agent.sessionCapabilities?.resume+ ? 'session/resume'+ : '';+ if (!method)+ throw new ProviderConversationUnavailableError(+ hooks.provider,+ input.sessionId,+ `This ${hooks.label} cannot resume saved conversations.`+ );+ state.nativeId = input.resume.nativeSessionId.slice(prefix?.prefix.length ?? 0);+ }+ const result = await client.request<AcpSessionResult>(method, {+ cwd,+ mcpServers,+ ...(input.resume ? { sessionId: state.nativeId } : {}),+ });+ state.nativeId = result.sessionId ?? state.nativeId;+ if (!state.nativeId) throw new Error(`${hooks.label} returned no session ID.`);+ state.configOptions = result.configOptions ?? [];+ state.models = modelConfigOption(state.configOptions)+ ? modelsFromConfig(state.configOptions)+ : modelsFromList(result.models);+ const mode = hooks.sessionMode?.(input.runtimeMode);+ if (mode)+ await client.request('session/set_mode', { sessionId: state.nativeId, modeId: mode });+ if (input.model) await this.setModel(state.id, input.model);+ const nativeSessionId = `${prefix?.prefix ?? ''}${state.nativeId}`;+ this.emit(state, { type: 'session.started', nativeSessionId });+ this.emit(state, { type: 'session.state.changed', status: 'ready' });+ return { provider: hooks.provider, sessionId: state.id, nativeSessionId };+ } catch (cause) {+ await client.dispose();+ this.sessions.delete(state.id);+ if (cause instanceof ProviderConversationUnavailableError) throw cause;+ const details =+ cause instanceof JsonRpcError &&+ typeof cause.data === 'object' &&+ cause.data !== null &&+ 'details' in cause.data+ ? String(cause.data.details)+ : '';+ throw new ProviderSessionError(+ hooks.provider,+ state.id,+ `Could not start ${hooks.label}: ${String(cause)}${details ? `: ${details}` : ''}${client.stderr ? `\n${client.stderr}` : ''}`,+ { cause }+ );+ }+ }++ async sendTurn(input: ProviderSendTurnInput) {+ const state = this.require(input.sessionId);+ state.queue.push(input);+ if (!state.turn) this.drain(state);+ return { turnId: input.turnId };+ }++ private drain(state: State): void {+ if (state.turn || state.stopping || !this.hasSession(state.id)) return;+ const input = state.queue.shift();+ if (!input) return;+ state.turn = input.turnId;+ state.interrupted = false;+ state.messageId = randomUUID();+ state.items.clear();+ state.toolServers.clear();+ this.emit(state, { type: 'turn.started', turnId: input.turnId });+ this.emit(state, { type: 'session.state.changed', status: 'running' });+ void this.run(state, input).then(+ (reason) => {+ if (state.turn !== input.turnId) return;+ const interrupted = state.interrupted || reason === 'cancelled';+ this.complete(+ state,+ interrupted ? 'interrupted' : reason === 'end_turn' ? 'completed' : 'error',+ interrupted+ ? 'Interrupted.'+ : reason === 'end_turn'+ ? undefined+ : `${this.hooks.label} stopped: ${reason}`+ );+ },+ (error: unknown) => {+ if (state.turn !== input.turnId) return;+ this.complete(+ state,+ state.interrupted ? 'interrupted' : 'error',+ state.interrupted ? 'Interrupted.' : String(error)+ );+ }+ );+ }++ private async run(state: State, input: ProviderSendTurnInput): Promise<string> {+ if (input.model) await this.setModel(state.id, input.model);+ const prompt: Array<Record<string, unknown>> = [+ { type: 'text', text: state.context ? `${state.context}\n\n${input.text}` : input.text },+ ];+ state.context = '';+ for (const attachment of input.attachments ?? []) {+ const { mimeType, path } = attachment;+ const media = mimeType.startsWith('image/')+ ? state.prompt.image && 'image'+ : mimeType.startsWith('audio/')+ ? state.prompt.audio && 'audio'+ : undefined;+ if (media) {+ prompt.push({ type: media, data: (await readFile(path)).toString('base64'), mimeType });+ } else if (state.prompt.embeddedContext) {+ prompt.push({+ type: 'resource',+ resource: {+ uri: pathToFileURL(path).href,+ mimeType,+ ...(mimeType.startsWith('text/') || /json|xml/.test(mimeType)+ ? { text: await readFile(path, 'utf8') }+ : { blob: (await readFile(path)).toString('base64') }),+ },+ });+ } else {+ prompt.push({+ type: 'resource_link',+ uri: pathToFileURL(path).href,+ name: basename(path),+ mimeType,+ });+ }+ }+ return (+ await state.client.request<{ stopReason: string }>('session/prompt', {+ sessionId: state.nativeId,+ prompt,+ })+ ).stopReason;+ }++ async interruptTurn(id: string): Promise<void> {+ const state = this.require(id);+ if (!state.turn) return;+ state.interrupted = true;+ state.client.notify('session/cancel', { sessionId: state.nativeId });+ this.cancelPending(state);+ }++ async listModels(id: string): Promise<ModelChoice[]> {+ return this.require(id).models;+ }++ async setModel(id: string, model: ModelSelection): Promise<void> {+ const state = this.require(id);+ if (!modelConfigOption(state.configOptions)) {+ await state.client.request('session/set_model', {+ sessionId: state.nativeId,+ modelId: model.id,+ });+ return;+ }+ if (!state.models.some((choice) => choice.id === model.id))+ throw new ProviderSessionError(this.provider, id, `Unavailable model: ${model.id}`);+ const result = await state.client.request<{ configOptions?: AcpConfigOption[] }>(+ 'session/set_config_option',+ { sessionId: state.nativeId, configId: 'model', value: model.id }+ );+ if (result.configOptions) this.applyConfigOptions(state, result.configOptions);+ }++ async respondToRequest(id: string, requestId: string, decision: ApprovalDecision): Promise<void> {+ const state = this.require(id);+ const pending = state.decisions.get(requestId);+ if (!pending)+ throw new ProviderSessionError(this.provider, id, `No pending approval ${requestId}`);+ const response = pending.responses.get(decision);+ if (response === undefined && decision !== 'cancel' && decision !== 'decline')+ throw new ProviderSessionError(this.provider, id, `Decision ${decision} is not offered`);+ state.decisions.delete(requestId);+ pending.settle(response ?? ACP_CANCELLED);+ this.emit(state, { type: 'request.resolved', requestId, decision });+ }++ async respondToUserInput(+ id: string,+ requestId: string,+ answers: UserInputAnswers+ ): Promise<void> {+ const state = this.require(id);+ const pending = state.questions.get(requestId);+ if (!pending)+ throw new ProviderSessionError(this.provider, id, `No pending question ${requestId}`);+ const selected = pending.questions.map((question) => {+ const answer = answers[question.id];+ const values = Array.isArray(answer) ? answer : typeof answer === 'string' ? [answer] : [];+ if (+ !values.length ||+ (!question.multiSelect && values.length !== 1) ||+ values.some((value) => !question.options.some((option) => option.value === value))+ )+ throw new ProviderSessionError(+ this.provider,+ id,+ `Invalid answer for ${question.id}: choose one of the offered answers.`+ );+ return { questionId: question.id, values };+ });+ state.questions.delete(requestId);+ pending.settle(pending.answer(selected));+ this.emit(state, { type: 'user-input.resolved', requestId });+ }++ private context(state: State): AcpSessionContext {+ const active = () => (state.turn && !state.interrupted ? state.turn : null);+ return {+ get turnId() {+ return active();+ },+ mcpServerNames: state.mcpNames,+ askQuestions: async (questions, answer) => {+ const turnId = active();+ if (!turnId) return ACP_CANCELLED;+ const requestId = randomUUID();+ return await new Promise((settle) => {+ state.questions.set(requestId, { questions, answer, settle });+ this.emit(state, { type: 'user-input.requested', turnId, requestId, questions });+ });+ },+ requestDecision: async ({ requestType, title, detail, options }) => {+ const turnId = active();+ if (!turnId) return ACP_CANCELLED;+ const requestId = randomUUID();+ const responses = new Map<ApprovalDecision, unknown>();+ for (const option of options)+ if (option.decision !== 'cancel') responses.set(option.decision, option.response);+ return await new Promise((settle) => {+ state.decisions.set(requestId, { responses, settle });+ this.emit(state, {+ type: 'request.opened',+ turnId,+ requestId,+ requestType,+ title,+ ...(detail === undefined ? {} : { detail }),+ options: options.map(({ decision, label }) => ({ decision, label })),+ });+ });+ },+ completeItem: (item) => {+ if (!state.turn) return;+ this.emit(state, { type: 'item.completed', turnId: state.turn, item });+ },+ };+ }++ private async permission(+ state: State,+ context: AcpSessionContext,+ request: AcpPermissionRequest+ ): Promise<unknown> {+ if (request.sessionId !== state.nativeId || !state.turn || state.interrupted)+ return ACP_CANCELLED;+ const vendor = this.hooks.permission?.(context, request);+ if (vendor) return await vendor;+ const { toolCall } = request;+ const once = request.options.find((option) => option.kind === 'allow_once');+ const server = this.hooks.mcpServerOf?.(toolCall) ?? state.toolServers.get(toolCall.toolCallId);+ if (+ once &&+ ((server !== undefined && state.mcpNames.has(server)) ||+ state.runtimeMode === 'full-access' ||+ (state.runtimeMode === 'auto-accept-edits' && toolCall.kind === 'edit'))+ )+ return { outcome: { outcome: 'selected', optionId: once.optionId } };+ const options: Array<{ decision: ApprovalDecision; label: string; response: unknown }> = [];+ for (const option of request.options) {+ const decision =+ option.kind === 'allow_once'+ ? 'accept'+ : option.kind === 'allow_always'+ ? 'acceptForSession'+ : option.kind === 'reject_once'+ ? 'decline'+ : undefined;+ // Permanent policies are intentionally not offered by this session UI.+ if (+ !decision ||+ options.some((offered) => offered.decision === decision) ||+ /future|permanent/i.test(option.name)+ )+ continue;+ options.push({+ decision,+ label: option.name,+ response: { outcome: { outcome: 'selected', optionId: option.optionId } },+ });+ }+ options.push({ decision: 'cancel', label: 'Cancel', response: ACP_CANCELLED });+ return await context.requestDecision({+ requestType:+ toolCall.kind === 'execute'+ ? 'command_execution_approval'+ : toolCall.kind === 'edit'+ ? 'file_change_approval'+ : 'tool_approval',+ title: toolCall.title ?? `${this.hooks.label} needs permission`,+ options,+ });+ }++ private applyConfigOptions(state: State, options: AcpConfigOption[]): void {+ state.configOptions = options;+ if (modelConfigOption(options)) state.models = modelsFromConfig(options);+ }++ private update(state: State, update: AcpSessionUpdate): void {+ if (update.sessionUpdate === 'config_option_update' && update.configOptions) {+ this.applyConfigOptions(state, update.configOptions);+ return;+ }+ if (!state.turn) return;+ if (+ update.sessionUpdate === 'agent_message_chunk' &&+ update.content &&+ !Array.isArray(update.content) &&+ update.content.type === 'text'+ ) {+ if (!state.messageText)+ this.emit(state, {+ type: 'item.started',+ turnId: state.turn,+ item: {+ id: state.messageId,+ type: 'assistant_message',+ status: 'in_progress',+ title: '',+ text: '',+ },+ });+ state.messageText += update.content.text ?? '';+ this.emit(state, {+ type: 'content.delta',+ turnId: state.turn,+ itemId: state.messageId,+ delta: update.content.text ?? '',+ });+ return;+ }+ if (+ (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update') &&+ update.toolCallId+ )+ this.toolUpdate(state, state.turn, {+ ...update,+ toolCallId: update.toolCallId,+ content: Array.isArray(update.content) ? update.content : [],+ });+ }++ private toolUpdate(state: State, turnId: string, update: AcpToolCall): void {+ const old = state.items.get(update.toolCallId);+ const server = this.hooks.mcpServerOf?.(update);+ if (server !== undefined) state.toolServers.set(update.toolCallId, server);+ const text = (update.content ?? [])+ .map((part) =>+ part.type === 'diff' ? `${part.path}\n${part.newText ?? ''}` : (part.content?.text ?? '')+ )+ .join('\n');+ const output = update.rawOutput;+ const outputFailed =+ output &&+ (Boolean(output.error) ||+ output.rejected === true ||+ output.permissionDenied === true ||+ (typeof output.exitCode === 'number' && output.exitCode !== 0));+ const resultText = output ? JSON.stringify(output, null, 2) : '';+ const toolText = [text, resultText].filter(Boolean).join('\n');+ const item: ProviderItem = {+ id: update.toolCallId,+ type:+ (old?.type !== 'tool_call' ? old?.type : undefined) ??+ this.hooks.itemType?.(update) ??+ (server !== undefined || update.toolCallId.startsWith('mcp_')+ ? 'mcp_tool_call'+ : update.kind === 'execute'+ ? 'command_execution'+ : update.kind === 'edit'+ ? 'file_change'+ : 'tool_call'),+ title: update.title ?? old?.title ?? 'Tool',+ status: outputFailed+ ? 'failed'+ : update.status === 'completed'+ ? 'completed'+ : update.status === 'failed'+ ? 'failed'+ : (old?.status ?? 'in_progress'),+ ...(toolText || old?.text ? { text: toolText || old?.text } : {}),+ };+ state.items.set(item.id, item);+ this.emit(state, {+ type:+ item.status === 'completed' || item.status === 'failed'+ ? 'item.completed'+ : old+ ? 'item.updated'+ : 'item.started',+ turnId,+ item,+ });+ this.finishMessage(state, 'completed');+ state.messageId = randomUUID();+ }++ private finishMessage(state: State, status: 'completed' | 'failed'): void {+ if (!state.turn || !state.messageText) return;+ this.emit(state, {+ type: 'item.completed',+ turnId: state.turn,+ item: {+ id: state.messageId,+ type: 'assistant_message',+ title: 'Assistant',+ status,+ text: state.messageText,+ },+ });+ state.messageText = '';+ }++ private complete(+ state: State,+ outcome: 'completed' | 'interrupted' | 'error',+ message?: string+ ): void {+ if (!state.turn) return;+ const turnId = state.turn;+ this.finishMessage(state, outcome === 'completed' ? 'completed' : 'failed');+ for (const item of state.items.values())+ if (item.status === 'in_progress') {+ if (outcome === 'completed') {+ outcome = 'error';+ message = `${this.hooks.label} ended the turn without confirming a pending tool result.`;+ }+ this.emit(state, {+ type: 'item.completed',+ turnId,+ item: {+ ...item,+ status: 'failed',+ ...(message ? { text: [item.text, message].filter(Boolean).join('\n') } : {}),+ },+ });+ }+ this.cancelPending(state);+ state.turn = null;+ this.emit(state, {+ type: 'turn.completed',+ turnId,+ outcome,+ ...(message ? { message } : {}),+ usage: [],+ });+ if (!state.turn)+ this.emit(state, {+ type: 'session.state.changed',+ status: state.stopping ? 'stopped' : outcome === 'error' ? 'error' : 'ready',+ });+ this.drain(state);+ }++ private cancelPending(state: State): void {+ for (const [requestId, pending] of state.questions) {+ pending.settle(ACP_CANCELLED);+ this.emit(state, { type: 'user-input.resolved', requestId });+ }+ state.questions.clear();+ for (const [requestId, pending] of state.decisions) {+ pending.settle(ACP_CANCELLED);+ this.emit(state, { type: 'request.resolved', requestId, decision: 'cancel' });+ }+ state.decisions.clear();+ }++ async stopSession(id: string): Promise<void> {+ const state = this.sessions.get(id);+ if (!state) return;+ state.stopping = true;+ if (state.turn) await this.interruptTurn(id);+ await state.client.dispose();+ this.exited(id, 'Session stopped');+ }+ async stopAll(): Promise<void> {+ await Promise.all([...this.sessions.keys()].map((id) => this.stopSession(id)));+ }+ private exited(id: string, reason: string): void {+ const state = this.sessions.get(id);+ if (!state) return;+ const stopping = state.stopping;+ state.stopping = true;+ this.complete(state, stopping ? 'interrupted' : 'error', reason);+ this.cancelPending(state);+ for (const input of state.queue.splice(0))+ this.emit(state, {+ type: 'turn.completed',+ turnId: input.turnId,+ outcome: 'error',+ message: reason,+ usage: [],+ });+ this.sessions.delete(id);+ this.emit(state, { type: 'session.state.changed', status: 'stopped' });+ this.emit(state, { type: 'session.exited', reason });+ }+ private require(id: string): State {+ const state = this.sessions.get(id);+ if (!state || !state.client.isAlive)+ throw new ProviderSessionError(this.provider, id, 'Session is not running');+ return state;+ }+ private emit(state: State, event: Emittable): void {+ const full = {+ ...event,+ eventId: randomUUID(),+ provider: this.provider,+ sessionId: state.id,+ createdAt: new Date().toISOString(),+ } as ProviderRuntimeEvent;+ for (const listener of this.listeners) {+ try {+ listener(full);+ } catch (cause) {+ this.logger.error(`${this.hooks.label} event listener failed`, { error: String(cause) });+ }+ }+ }+}++export function createAcpAdapter(hooks: AcpProviderHooks, options: AcpAdapterOptions): AcpAdapter {+ return new AcpAdapter(hooks, options);+}diff --git a/console/packages/agent-providers/src/acp/hooks.ts b/console/packages/agent-providers/src/acp/hooks.tsnew file mode 100644index 000000000..0465a11ae--- /dev/null+++ b/console/packages/agent-providers/src/acp/hooks.ts@@ -0,0 +1,155 @@+import type { ProviderCapabilities, RuntimeMode } from '../adapter';+import type {+ ApprovalDecision,+ ItemType,+ ProviderItem,+ RequestType,+ UserInputQuestion,+} from '../events';+import type { ProviderReadiness, SignInCheckInput } from '../readiness';+import type { ProviderLogger } from '../transport/stdio-json-rpc';+import type {+ AcpInitializeResult,+ AcpPermissionRequest,+ AcpPromptCapabilities,+ AcpToolCall,+} from './protocol';++/** The process an ACP provider runs as. */+export interface AcpLaunch {+ command: string;+ args: string[];+ /** Complete environment for the process; not merged with anything. */+ env: Record<string, string>;+ /**+ * Looks at each line the process prints and returns a message to kill it+ * with, for output that means it can never answer (an interactive sign-in+ * prompt, say).+ */+ rejectOutputLine?: (line: string) => string | undefined;+}++export interface AcpLaunchInput {+ binaryPath: string;+ cwd: string;+ env: Record<string, string>;+}++/** One answered question: the option values chosen, already checked against what was offered. */+export interface AcpSelectedAnswer {+ questionId: string;+ values: string[];+}++/**+ * What a provider's vendor extensions can do inside a running session. Every+ * call is a no-op answer (`cancelled`) when no turn is running or the turn was+ * interrupted, so an extension never has to check that itself.+ */+export interface AcpSessionContext {+ /** The running turn, or null when there is none or it was interrupted. */+ readonly turnId: string | null;+ /** Names of the MCP servers this session registered. */+ readonly mcpServerNames: ReadonlySet<string>;+ /**+ * Ask the user questions. Resolves with what `answer` returns for the+ * user's choices, or ACP's `cancelled` outcome when the turn ends first.+ */+ askQuestions(+ questions: UserInputQuestion[],+ answer: (selected: AcpSelectedAnswer[]) => unknown+ ): Promise<unknown>;+ /**+ * Ask the user for a decision. Resolves with the `response` of the option+ * chosen. `cancel` (and `decline`, when not offered) resolve with ACP's+ * `cancelled` outcome.+ */+ requestDecision(input: {+ requestType: RequestType;+ title: string;+ detail?: string;+ options: Array<{ decision: ApprovalDecision; label: string; response: unknown }>;+ }): Promise<unknown>;+ /** Add a finished item to the running turn's transcript. */+ completeItem(item: ProviderItem): void;+}++export interface AcpExtensionRegistrar {+ request(method: string, handler: (params: unknown) => Promise<unknown> | unknown): void;+ notification(method: string, handler: (params: unknown) => void): void;+}++/**+ * Everything that makes one ACP-speaking CLI different from another. The+ * generic adapter covers the protocol and picks behaviour from the agent's+ * advertised capabilities; these hooks cover the rest.+ */+export interface AcpProviderHooks {+ /** Provider id, as Switch stores it. */+ provider: string;+ /** How messages name the CLI: "Cursor CLI", "Antigravity". */+ label: string;+ /** Executable used when the caller names none. */+ defaultBinary: string;+ capabilities: ProviderCapabilities;+ /** The command, arguments and environment to run the agent with. May prepare the host first. */+ launch(input: AcpLaunchInput): Promise<AcpLaunch> | AcpLaunch;+ /** The command a person runs on the execution machine to sign the CLI in. */+ loginCommand: string;+ /**+ * Environment variables the CLI reads (an API key, an endpoint) that a+ * session host should pass through from the machine's environment. The+ * common vendor keys are already passed through for every provider.+ */+ inheritEnv?: readonly string[];+ /**+ * Whether the CLI is signed in, answered without signing it in: a check+ * must never be what changes its answer. `handshake` runs the agent and+ * returns its `initialize` answer. Without this hook the check runs the+ * handshake and reports the sign-in as unknown.+ */+ checkSignIn?(input: AcpSignInInput): Promise<ProviderReadiness>;+ /**+ * `authenticate` method sent after `initialize` when a session starts with+ * this environment, which may open a browser; undefined sends none (the+ * session environment already signs it in, say). Omit for an agent that+ * never needs a sign-in call.+ */+ authMethodId?(env: Record<string, string>): string | undefined;+ /**+ * Prompt content the agent accepts whether or not it advertises it. What it+ * advertises in `initialize` is always honoured as well.+ */+ promptCapabilities?: AcpPromptCapabilities;+ /** The ACP mode to put a new session in for Switch's runtime mode. Omit to leave the agent's default. */+ sessionMode?(runtimeMode: RuntimeMode): string;+ /**+ * Native session ids are stored with this prefix, telling them apart from+ * ids an earlier, non-ACP runtime of the same provider stored. A resume id+ * without it starts a fresh conversation with `legacyMessage`.+ */+ nativeSessionIdPrefix?: { prefix: string; legacyMessage: string };+ /** The MCP server a tool call belongs to, when the agent says so. */+ mcpServerOf?(toolCall: AcpToolCall): string | undefined;+ /** Vendor item typing, consulted before the protocol's own `kind`. */+ itemType?(toolCall: AcpToolCall): ItemType | undefined;+ /**+ * A permission request the vendor uses for something else (a question, say).+ * Return undefined to let the adapter treat it as a permission request.+ */+ permission?(+ context: AcpSessionContext,+ request: AcpPermissionRequest+ ): Promise<unknown> | undefined;+ /** Register vendor-specific requests and notifications for a session. */+ extensions?(context: AcpSessionContext, on: AcpExtensionRegistrar): void;+}++export interface AcpSignInInput extends SignInCheckInput {+ handshake(): Promise<AcpInitializeResult>;+}++export interface AcpAdapterOptions {+ binaryPath?: string;+ logger?: ProviderLogger;+}diff --git a/console/packages/agent-providers/src/acp/mcp.ts b/console/packages/agent-providers/src/acp/mcp.tsnew file mode 100644index 000000000..99cbe3b16--- /dev/null+++ b/console/packages/agent-providers/src/acp/mcp.ts@@ -0,0 +1,56 @@+import type { McpServerSpec } from '../adapter';++/**+ * Refuse to start an ACP session whose HTTP MCP servers the agent cannot+ * reach.+ *+ * An ACP agent says in `initialize` whether it accepts MCP servers over HTTP+ * (`agentCapabilities.mcpCapabilities.http`). The Switch tools are served that+ * way, so an agent that does not declare it would start a session with no+ * Switch tools and nothing to say why. `http` is what the agent declared.+ */+export function requireHttpMcp(+ agent: string,+ servers: Record<string, McpServerSpec>,+ http: boolean | undefined+): void {+ const over = Object.entries(servers)+ .filter(([, spec]) => spec.transport === 'http')+ .map(([name]) => name);+ if (over.length === 0 || http === true) return;+ throw new Error(+ `${agent} does not declare MCP over HTTP (agentCapabilities.mcpCapabilities.http), and the MCP server${over.length > 1 ? 's' : ''} ${over.join(', ')} ${over.length > 1 ? 'are' : 'is'} only reachable that way. Update ${agent}; the session is not started without its tools.`+ );+}++/**+ * The session's MCP servers in ACP's `session/new` shape. A stdio server's+ * `envVars` are filled from the session environment, under its explicit `env`.+ */+export function acpMcpServers(+ servers: Record<string, McpServerSpec>,+ env: Record<string, string>+): Array<Record<string, unknown>> {+ return Object.entries(servers).map(([name, server]) =>+ server.transport === 'stdio'+ ? {+ name,+ command: server.command,+ args: server.args,+ env: Object.entries({+ ...Object.fromEntries(+ (server.envVars ?? [])+ .filter((key) => env[key] !== undefined)+ .map((key) => [key, env[key]])+ ),+ ...server.env,+ }).map(([name, value]) => ({ name, value })),+ }+ : {+ name,+ type: 'http',+ url: server.url,+ headers: Object.entries(server.headers ?? {}).map(([name, value]) => ({ name, value })),+ }+ );+}diff --git a/console/packages/agent-providers/src/acp/protocol.ts b/console/packages/agent-providers/src/acp/protocol.tsnew file mode 100644index 000000000..e2cf90c12--- /dev/null+++ b/console/packages/agent-providers/src/acp/protocol.ts@@ -0,0 +1,118 @@+import type { ModelChoice } from '@switch-console/shared/session-v1';++/**+ * The slice of the Agent Client Protocol (https://agentclientprotocol.com) the+ * generic adapter reads. Agents send more; anything not named here is ignored+ * unless a provider's hooks pick it up.+ */++export interface AcpPromptCapabilities {+ image?: boolean;+ audio?: boolean;+ embeddedContext?: boolean;+}++export interface AcpAgentCapabilities {+ loadSession?: boolean;+ promptCapabilities?: AcpPromptCapabilities;+ mcpCapabilities?: { http?: boolean; sse?: boolean };+ sessionCapabilities?: { resume?: unknown };+}++export interface AcpInitializeResult {+ protocolVersion?: number;+ agentInfo?: { name?: string; version?: string };+ agentCapabilities?: AcpAgentCapabilities;+ authMethods?: Array<{ id?: string; name?: string }>;+}++export interface AcpConfigChoice {+ value: string;+ name: string;+}++export interface AcpConfigOption {+ id: string;+ type: string;+ currentValue?: string;+ options?: Array<AcpConfigChoice | { options: AcpConfigChoice[] }>;+}++export interface AcpSessionModels {+ availableModels: Array<{ modelId: string; name: string }>;+ currentModelId?: string;+}++export interface AcpSessionModes {+ availableModes: Array<{ id: string; name?: string }>;+ currentModeId?: string;+}++/** What `session/new`, `session/load` and `session/resume` answer. */+export interface AcpSessionResult {+ sessionId?: string;+ models?: AcpSessionModels;+ modes?: AcpSessionModes;+ configOptions?: AcpConfigOption[];+}++export interface AcpPermissionOption {+ optionId: string;+ name: string;+ kind: string;+}++export interface AcpToolCallContent {+ type: string;+ content?: { type: string; text?: string };+ path?: string;+ oldText?: string;+ newText?: string;+}++export interface AcpToolCall {+ toolCallId: string;+ title?: string;+ kind?: string;+ status?: string;+ content?: AcpToolCallContent[];+ rawInput?: Record<string, unknown>;+ rawOutput?: Record<string, unknown>;+ _meta?: Record<string, unknown>;+}++export interface AcpSessionUpdate extends Omit<AcpToolCall, 'content' | 'toolCallId'> {+ sessionUpdate: string;+ toolCallId?: string;+ content?: AcpToolCallContent[] | { type: string; text?: string };+ configOptions?: AcpConfigOption[];+}++export interface AcpPermissionRequest {+ sessionId: string;+ toolCall: AcpToolCall;+ options: AcpPermissionOption[];+}++export const ACP_CANCELLED = { outcome: { outcome: 'cancelled' } } as const;++/** Models offered through a `model` select in the session's config options. */+export function modelsFromConfig(options: AcpConfigOption[]): ModelChoice[] {+ const model = modelConfigOption(options);+ return (model?.options ?? [])+ .flatMap((option) => ('value' in option ? [option] : option.options))+ .map((option) => ({ id: option.value, label: option.name, options: {}, imageInput: true }));+}++export function modelConfigOption(options: AcpConfigOption[]): AcpConfigOption | undefined {+ return options.find((option) => option.id === 'model' && option.type === 'select');+}++/** Models offered through the session's `models` list. */+export function modelsFromList(models: AcpSessionModels | undefined): ModelChoice[] {+ return (models?.availableModels ?? []).map((model) => ({+ id: model.modelId,+ label: model.name,+ options: {},+ }));+}diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.tsindex 9e25a8684..a21279d1e 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.test.ts@@ -395,3 +395,35 @@ it('refuses to start a session whose HTTP MCP servers the agent cannot reach', a).rejects.toThrow('Antigravity does not declare MCP over HTTP');expect(servers.at(-1)!.received.some((m) => m.method === 'session/new')).toBe(false);});++it('auto-approves calls to any MCP server the session registered, not only Switch', async () => {+ const adapter = createAntigravityAdapter();+ const events: ProviderRuntimeEvent[] = [];+ adapter.subscribe((e) => events.push(e));+ await adapter.startSession({+ sessionId: 'echo',+ cwd: '/work',+ runtimeMode: 'approval-required',+ env: {},+ mcpServers: { echo: { transport: 'stdio', command: 'node', args: ['echo.js'] } },+ });+ const server = servers.at(-1)!;+ await adapter.sendTurn({ sessionId: 'echo', turnId: 't', text: 'echo' });+ server.send({+ id: 94,+ method: 'session/request_permission',+ params: {+ sessionId: 'native',+ toolCall: {+ toolCallId: 'call',+ _meta: { is_mcp_tool_call: true, mcp: { server: 'echo', tool: 'echo' } },+ },+ options: [{ optionId: 'once', name: 'Allow once', kind: 'allow_once' }],+ },+ });+ await flush();+ expect(server.received.find((m) => m.id === 94)?.result).toEqual({+ outcome: { outcome: 'selected', optionId: 'once' },+ });+ expect(events.filter((e) => e.type === 'request.opened')).toHaveLength(0);+});diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.tsindex bca4aef54..5a2c40378 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts@@ -1,669 +1,85 @@-import { randomUUID } from 'node:crypto';-import { readFile, realpath } from 'node:fs/promises';-import { pathToFileURL } from 'node:url';-import type { ModelChoice } from '@switch-console/shared/session-v1';-import { requireHttpMcp } from '../acp-mcp';-import type {- ModelSelection,- ProviderAdapter,- ProviderSendTurnInput,- ProviderSessionStartInput,-} from '../adapter';-import { ProviderSessionError, ProviderConversationUnavailableError } from '../adapter';-import type {- ApprovalDecision,- ProviderItem,- ProviderRuntimeEvent,- UserInputAnswers,-} from '../events';+import { createAcpAdapter, type AcpAdapter } from '../acp/acp-adapter';+import type { AcpAdapterOptions, AcpProviderHooks } from '../acp/hooks';+import { readiness } from '../readiness';import {- type StdioJsonRpcClient,- JsonRpcError,- noopLogger,- type ProviderLogger,-} from '../transport/stdio-json-rpc';-import { modelsFromConfig, type ConfigOption } from './protocol';-import { authenticateAntigravity, createAntigravityClient, initializeAntigravity } from './runtime';--interface PermissionOption {- optionId: string;- name: string;- kind: string;-}-interface ToolUpdate {- sessionUpdate: string;- _meta?: { is_mcp_tool_call?: boolean; mcp?: { server?: string; tool?: string } };- toolCallId: string;- title?: string;- kind?: string;- status?: string;- content?: Array<{- type: string;- content?: { type: string; text?: string };- path?: string;- oldText?: string;- newText?: string;- }>;-}-interface Update extends Omit<ToolUpdate, 'content'> {- configOptions?: ConfigOption[];- content?: ToolUpdate['content'] | { type: string; text?: string };-}-interface State {- id: string;- nativeId: string;- models?: ModelChoice[];- configOptions: ConfigOption[];- questions: Map<- string,- { questionId: string; choices: string[]; settle: (value: unknown) => void }- >;- client: StdioJsonRpcClient;- turn: string | null;- queue: ProviderSendTurnInput[];- items: Map<string, ProviderItem>;- approvals: Map<- string,- { options: Map<ApprovalDecision, string>; settle: (value: unknown) => void }- >;- messageId: string;- messageText: string;- stopping: boolean;- interrupted: boolean;- context: string;- autoApproveSwitchTools: boolean;-}--type Emittable<T = ProviderRuntimeEvent> = T extends ProviderRuntimeEvent- ? Omit<T, 'eventId' | 'provider' | 'sessionId' | 'createdAt'>- : never;--export interface AntigravityAdapterOptions {- binaryPath?: string;- logger?: ProviderLogger;-}--export class AntigravityAdapter implements ProviderAdapter {- readonly provider = 'antigravity';- readonly capabilities = {+ ANTIGRAVITY_SIGN_IN,+ antigravityLaunch,+ antigravityProfile,+ antigravitySignedIn,+} from './runtime';++/** Antigravity's `antigravity-acp`, whose questions arrive as permission requests. */+export const antigravityAcp: AcpProviderHooks = {+ provider: 'antigravity',+ label: 'Antigravity',+ defaultBinary: 'antigravity-acp',+ capabilities: {modelSwitchInSession: true,steering: false,resume: true,approvals: true,userInput: true,- };- private readonly sessions = new Map<string, State>();- private readonly listeners = new Set<(event: ProviderRuntimeEvent) => void>();- private readonly logger: ProviderLogger;- constructor(private readonly options: AntigravityAdapterOptions = {}) {- this.logger = options.logger ?? noopLogger;- }-- subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void {- this.listeners.add(listener);- return () => this.listeners.delete(listener);- }- hasSession(id: string): boolean {- return this.sessions.has(id);- }-- async startSession(input: ProviderSessionStartInput) {- if (this.hasSession(input.sessionId))- throw new ProviderSessionError('antigravity', input.sessionId, 'session already started');- const cwd = await realpath(input.cwd);- if (input.resume && !input.resume.nativeSessionId.startsWith('acp:'))- throw new ProviderConversationUnavailableError(- 'antigravity',- input.sessionId,- 'This conversation belongs to the previous Antigravity CLI runtime. Start a fresh ACP conversation; the existing transcript is preserved.'- );- const client = await createAntigravityClient({- binaryPath: this.options.binaryPath ?? 'antigravity-acp',- cwd,- env: input.env,- logger: this.logger,- onExit: (reason) => this.exited(input.sessionId, reason),- });- const state: State = {- id: input.sessionId,- nativeId: '',- configOptions: [],- questions: new Map(),- client,- turn: null,- queue: [],- items: new Map(),- approvals: new Map(),- messageId: '',- messageText: '',- stopping: false,- interrupted: false,- context: input.systemContext ?? '',- autoApproveSwitchTools: Object.hasOwn(input.mcpServers, 'switch'),- };- this.sessions.set(state.id, state);- client.onNotification('session/update', (params) => {- const payload = params as { sessionId: string; update: Update };- if (payload.sessionId === state.nativeId) this.update(state, payload.update);- });- client.onServerRequest('session/request_permission', (params) =>- this.permission(- state,- params as { sessionId: string; toolCall: ToolUpdate; options: PermissionOption[] }- )- );- this.emit(state, { type: 'session.state.changed', status: 'starting' });+ },+ launch: antigravityLaunch,+ loginCommand: 'antigravity-acp --login',+ // `authMethods` is the agent's own answer: the sign-ins it still wants.+ // Calling `authenticate` here would not test the sign-in but perform it,+ // opening a browser.+ // 1.3 lists every method whether or not one is in use, so an outstanding+ // method is only signed out when the profile holds no token either.+ checkSignIn: async ({ handshake, env }) => {try {- const initialized = await initializeAntigravity(client);- requireHttpMcp(- 'Antigravity',- input.mcpServers,- initialized.agentCapabilities?.mcpCapabilities?.http- );- // Signing in belongs here — starting a session is work the user asked- // for, so a browser opening is an answer to something they did. The- // readiness probe deliberately stops at the handshake above.- await authenticateAntigravity(client);- const mcpServers = Object.entries(input.mcpServers).map(([name, server]) =>- server.transport === 'stdio'- ? {- name,- command: server.command,- args: server.args,- env: Object.entries({- ...Object.fromEntries(- (server.envVars ?? [])- .filter((key) => input.env[key] !== undefined)- .map((key) => [key, input.env[key]])- ),- ...server.env,- }).map(([name, value]) => ({ name, value })),- }- : {- name,- type: 'http',- url: server.url,- headers: Object.entries(server.headers ?? {}).map(([name, value]) => ({- name,- value,- })),- }- );- if (input.resume && !initialized.agentCapabilities?.sessionCapabilities?.resume)- throw new ProviderConversationUnavailableError(- 'antigravity',- input.sessionId,- 'This Antigravity ACP runtime cannot resume saved conversations.'- );- state.nativeId = input.resume?.nativeSessionId.slice(4) ?? '';- const result = await client.request<{- sessionId?: string;- configOptions?: ConfigOption[];- }>(input.resume ? 'session/resume' : 'session/new', {- cwd,- mcpServers,- ...(input.resume ? { sessionId: state.nativeId } : {}),- });- state.nativeId = result.sessionId ?? state.nativeId;- state.configOptions = result.configOptions ?? [];- state.models = modelsFromConfig(state.configOptions);- if (!state.nativeId) throw new Error('Antigravity returned no session ID.');- await client.request('session/set_mode', {- sessionId: state.nativeId,- modeId:- input.runtimeMode === 'full-access'- ? 'yolo'- : input.runtimeMode === 'auto-accept-edits'- ? 'auto_edit'- : 'default',- });- if (input.model) await this.setModel(state.id, input.model);- this.emit(state, { type: 'session.started', nativeSessionId: `acp:${state.nativeId}` });- this.emit(state, { type: 'session.state.changed', status: 'ready' });- return {- provider: 'antigravity',- sessionId: state.id,- nativeSessionId: `acp:${state.nativeId}`,- };- } catch (cause) {- await client.dispose();- this.sessions.delete(state.id);- if (cause instanceof ProviderConversationUnavailableError) throw cause;- const details =- cause instanceof JsonRpcError &&- typeof cause.data === 'object' &&- cause.data !== null &&- 'details' in cause.data- ? String(cause.data.details)- : '';- throw new ProviderSessionError(- 'antigravity',- state.id,- `Could not start Antigravity ACP: ${String(cause)}${details ? `: ${details}` : ''}${client.stderr ? `\n${client.stderr}` : ''}`,- { cause }- );+ return !(await handshake()).authMethods?.length ||+ (await antigravitySignedIn(antigravityProfile(env)))+ ? readiness('authenticated', 'Signed in to Antigravity ACP.')+ : readiness('unauthenticated', ANTIGRAVITY_SIGN_IN);+ } catch (error) {+ if (/sign in|auth required|unauthenticated/i.test(String(error)))+ return readiness('unauthenticated', ANTIGRAVITY_SIGN_IN);+ throw error;}- }-- async sendTurn(input: ProviderSendTurnInput) {- const state = this.require(input.sessionId);- state.queue.push(input);- if (!state.turn) this.drain(state);- return { turnId: input.turnId };- }-- private drain(state: State): void {- if (state.turn || state.stopping || !this.hasSession(state.id)) return;- const input = state.queue.shift();- if (!input) return;- state.turn = input.turnId;- state.interrupted = false;- state.messageId = randomUUID();- state.items.clear();- this.emit(state, { type: 'turn.started', turnId: input.turnId });- this.emit(state, { type: 'session.state.changed', status: 'running' });- void this.run(state, input).then(- (reason) => {- if (state.turn !== input.turnId) return;- const interrupted = state.interrupted || reason === 'cancelled';- this.complete(- state,- interrupted ? 'interrupted' : reason === 'end_turn' ? 'completed' : 'error',- interrupted- ? 'Interrupted.'- : reason === 'end_turn'- ? undefined- : `Antigravity stopped: ${reason}`- );- },- (error: unknown) => {- if (state.turn !== input.turnId) return;- this.complete(- state,- state.interrupted ? 'interrupted' : 'error',- state.interrupted ? 'Interrupted.' : String(error)- );- }- );- }-- private async run(state: State, input: ProviderSendTurnInput): Promise<string> {- if (input.model) await this.setModel(state.id, input.model);- const prompt: Array<Record<string, unknown>> = [- { type: 'text', text: state.context ? `${state.context}\n\n${input.text}` : input.text },- ];- state.context = '';- for (const attachment of input.attachments ?? []) {- if (attachment.mimeType.startsWith('image/') || attachment.mimeType.startsWith('audio/')) {- prompt.push({- type: attachment.mimeType.startsWith('image/') ? 'image' : 'audio',- data: (await readFile(attachment.path)).toString('base64'),- mimeType: attachment.mimeType,- });- } else {- prompt.push({- type: 'resource',- resource: {- uri: pathToFileURL(attachment.path).href,- mimeType: attachment.mimeType,- ...(attachment.mimeType.startsWith('text/') || /json|xml/.test(attachment.mimeType)- ? { text: await readFile(attachment.path, 'utf8') }- : { blob: (await readFile(attachment.path)).toString('base64') }),- },- });- }- }- return (- await state.client.request<{ stopReason: string }>('session/prompt', {- sessionId: state.nativeId,- prompt,- })- ).stopReason;- }-- async interruptTurn(id: string): Promise<void> {- const state = this.require(id);- if (!state.turn) return;- state.interrupted = true;- state.client.notify('session/cancel', { sessionId: state.nativeId });- this.cancelApprovals(state);- }-- async listModels(id: string): Promise<ModelChoice[]> {- return this.require(id).models ?? [];- }-- async setModel(id: string, model: ModelSelection): Promise<void> {- const state = this.require(id);- if (!state.models?.some((choice) => choice.id === model.id))- throw new ProviderSessionError('antigravity', id, `Unavailable model: ${model.id}`);- const result = await state.client.request<{ configOptions?: ConfigOption[] }>(- 'session/set_config_option',- {- sessionId: state.nativeId,- configId: 'model',- value: model.id,- }+ },+ // Opens a browser when the profile holds no usable token, which is why+ // only a session start sends it and the sign-in check never does.+ authMethodId: () => 'oauth-personal',+ promptCapabilities: { image: true, audio: true, embeddedContext: true },+ sessionMode: (runtimeMode) =>+ runtimeMode === 'full-access'+ ? 'yolo'+ : runtimeMode === 'auto-accept-edits'+ ? 'auto_edit'+ : 'default',+ nativeSessionIdPrefix: {+ prefix: 'acp:',+ legacyMessage:+ 'This conversation belongs to the previous Antigravity CLI runtime. Start a fresh ACP conversation; the existing transcript is preserved.',+ },+ mcpServerOf: (toolCall) => {+ const meta = toolCall._meta as+ | { is_mcp_tool_call?: boolean; mcp?: { server?: unknown } }+ | undefined;+ return meta?.is_mcp_tool_call === true && typeof meta.mcp?.server === 'string'+ ? meta.mcp.server+ : undefined;+ },+ permission: (context, { toolCall, options }) => {+ if (!toolCall.toolCallId.startsWith('interaction_')) return undefined;+ if (!options.length) return Promise.resolve({ outcome: { outcome: 'cancelled' } });+ return context.askQuestions(+ [+ {+ id: toolCall.toolCallId,+ question: toolCall.title ?? 'Choose an option.',+ options: options.map((option) => ({ value: option.optionId, label: option.name })),+ multiSelect: false,+ allowCustomAnswer: false,+ },+ ],+ ([selected]) => ({ outcome: { outcome: 'selected', optionId: selected!.values[0] } }));- if (result.configOptions) {- state.configOptions = result.configOptions;- state.models = modelsFromConfig(state.configOptions);- }- }-- async respondToRequest(id: string, requestId: string, decision: ApprovalDecision): Promise<void> {- const state = this.require(id);- const pending = state.approvals.get(requestId);- if (!pending)- throw new ProviderSessionError('antigravity', id, `No pending approval ${requestId}`);- const optionId = pending.options.get(decision);- if (!optionId && decision !== 'cancel' && decision !== 'decline')- throw new ProviderSessionError('antigravity', id, `Decision ${decision} is not offered`);- state.approvals.delete(requestId);- pending.settle({- outcome: optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' },- });- this.emit(state, { type: 'request.resolved', requestId, decision });- }-- async respondToUserInput(- id: string,- requestId: string,- answers: UserInputAnswers- ): Promise<void> {- const state = this.require(id);- const question = state.questions.get(requestId);- if (!question)- throw new ProviderSessionError('antigravity', id, 'Question is no longer pending.');- const answer = answers[question.questionId];- const choice =- typeof answer === 'string' ? answer : answer?.length === 1 ? answer[0] : undefined;- if (!choice || !question.choices.includes(choice))- throw new ProviderSessionError('antigravity', id, 'Choose one of the offered answers.');- state.questions.delete(requestId);- question.settle({ outcome: { outcome: 'selected', optionId: choice } });- this.emit(state, { type: 'user-input.resolved', requestId });- }-- private async permission(- state: State,- params: { sessionId: string; toolCall: ToolUpdate; options: PermissionOption[] }- ): Promise<unknown> {- if (params.sessionId !== state.nativeId || !state.turn || state.interrupted)- return { outcome: { outcome: 'cancelled' } };- const turnId = state.turn;- const requestId = randomUUID();- if (params.toolCall.toolCallId.startsWith('interaction_')) {- if (!params.options.length) return { outcome: { outcome: 'cancelled' } };- return new Promise((settle) => {- state.questions.set(requestId, {- questionId: params.toolCall.toolCallId,- choices: params.options.map((option) => option.optionId),- settle,- });- this.emit(state, {- type: 'user-input.requested',- turnId,- requestId,- questions: [- {- id: params.toolCall.toolCallId,- question: params.toolCall.title ?? 'Choose an option.',- options: params.options.map((option) => ({- value: option.optionId,- label: option.name,- })),- multiSelect: false,- allowCustomAnswer: false,- },- ],- });- });- }- const once = params.options.find((option) => option.kind === 'allow_once');- if (- once &&- state.autoApproveSwitchTools &&- params.toolCall._meta?.is_mcp_tool_call === true &&- params.toolCall._meta.mcp?.server === 'switch'- )- return { outcome: { outcome: 'selected', optionId: once.optionId } };- const options = new Map<ApprovalDecision, string>();- const offered: Array<{ decision: ApprovalDecision; label: string }> = [];- for (const option of params.options) {- if (!['allow_once', 'allow_always', 'reject_once'].includes(option.kind)) continue;- const decision =- option.kind === 'allow_once'- ? 'accept'- : option.kind === 'allow_always'- ? 'acceptForSession'- : 'decline';- // Permanent policies are intentionally not offered by this session UI.- if (options.has(decision) || /future|permanent/i.test(option.name)) continue;- options.set(decision, option.optionId);- offered.push({ decision, label: option.name });- }- offered.push({ decision: 'cancel', label: 'Cancel' });- return new Promise((settle) => {- state.approvals.set(requestId, { options, settle });- this.emit(state, {- type: 'request.opened',- turnId,- requestId,- requestType:- params.toolCall.kind === 'execute'- ? 'command_execution_approval'- : params.toolCall.kind === 'edit'- ? 'file_change_approval'- : 'tool_approval',- title: params.toolCall.title ?? 'Antigravity needs permission',- options: offered,- });- });- }-- private update(state: State, update: Update): void {- if (update.sessionUpdate === 'config_option_update' && update.configOptions) {- state.configOptions = update.configOptions;- state.models = modelsFromConfig(state.configOptions);- return;- }- if (!state.turn) return;- if (- update.sessionUpdate === 'agent_message_chunk' &&- update.content &&- !Array.isArray(update.content) &&- update.content.type === 'text'- ) {- if (!state.messageText)- this.emit(state, {- type: 'item.started',- turnId: state.turn,- item: {- id: state.messageId,- type: 'assistant_message',- status: 'in_progress',- title: '',- text: '',- },- });- state.messageText += update.content.text ?? '';- this.emit(state, {- type: 'content.delta',- turnId: state.turn,- itemId: state.messageId,- delta: update.content.text ?? '',- });- return;- }- if (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update') {- const old = state.items.get(update.toolCallId);- const content = Array.isArray(update.content) ? update.content : [];- const text = content- .map((part) =>- part.type === 'diff' ? `${part.path}\n${part.newText ?? ''}` : (part.content?.text ?? '')- )- .join('\n');- const item: ProviderItem = {- id: update.toolCallId,- type:- old?.type ??- (update.toolCallId.startsWith('mcp_')- ? 'mcp_tool_call'- : update.kind === 'execute'- ? 'command_execution'- : update.kind === 'edit'- ? 'file_change'- : 'tool_call'),- title: update.title ?? old?.title ?? 'Tool',- status:- update.status === 'completed'- ? 'completed'- : update.status === 'failed'- ? 'failed'- : (old?.status ?? 'in_progress'),- ...(text || old?.text ? { text: text || old?.text } : {}),- };- state.items.set(item.id, item);- this.emit(state, {- type:- item.status === 'completed' || item.status === 'failed'- ? 'item.completed'- : old- ? 'item.updated'- : 'item.started',- turnId: state.turn,- item,- });- this.finishMessage(state, 'completed');- state.messageId = randomUUID();- }- }-- private finishMessage(state: State, status: 'completed' | 'failed'): void {- if (!state.turn || !state.messageText) return;- this.emit(state, {- type: 'item.completed',- turnId: state.turn,- item: {- id: state.messageId,- type: 'assistant_message',- title: 'Assistant',- status,- text: state.messageText,- },- });- state.messageText = '';- }-- private complete(- state: State,- outcome: 'completed' | 'interrupted' | 'error',- message?: string- ): void {- if (!state.turn) return;- const turnId = state.turn;- this.finishMessage(state, outcome === 'completed' ? 'completed' : 'failed');- for (const item of state.items.values())- if (item.status === 'in_progress') {- if (outcome === 'completed') {- outcome = 'error';- message = 'Antigravity ended the turn without confirming a pending tool result.';- }- this.emit(state, {- type: 'item.completed',- turnId,- item: {- ...item,- status: 'failed',- ...(message ? { text: [item.text, message].filter(Boolean).join('\n') } : {}),- },- });- }- this.cancelApprovals(state);- state.turn = null;- this.emit(state, {- type: 'turn.completed',- turnId,- outcome,- ...(message ? { message } : {}),- usage: [],- });- if (!state.turn)- this.emit(state, {- type: 'session.state.changed',- status: state.stopping ? 'stopped' : outcome === 'error' ? 'error' : 'ready',- });- this.drain(state);- }+ },+};- private cancelApprovals(state: State): void {- for (const [requestId, question] of state.questions) {- question.settle({ outcome: { outcome: 'cancelled' } });- this.emit(state, { type: 'user-input.resolved', requestId });- }- state.questions.clear();- for (const [requestId, pending] of state.approvals) {- pending.settle({ outcome: { outcome: 'cancelled' } });- this.emit(state, { type: 'request.resolved', requestId, decision: 'cancel' });- }- state.approvals.clear();- }- async stopSession(id: string): Promise<void> {- const state = this.sessions.get(id);- if (!state) return;- state.stopping = true;- if (state.turn) await this.interruptTurn(id);- await state.client.dispose();- this.exited(id, 'Session stopped');- }- async stopAll(): Promise<void> {- await Promise.all([...this.sessions.keys()].map((id) => this.stopSession(id)));- }- private exited(id: string, reason: string): void {- const state = this.sessions.get(id);- if (!state) return;- const stopping = state.stopping;- state.stopping = true;- this.complete(state, stopping ? 'interrupted' : 'error', reason);- this.cancelApprovals(state);- for (const input of state.queue.splice(0))- this.emit(state, {- type: 'turn.completed',- turnId: input.turnId,- outcome: 'error',- message: reason,- usage: [],- });- this.sessions.delete(id);- this.emit(state, { type: 'session.state.changed', status: 'stopped' });- this.emit(state, { type: 'session.exited', reason });- }- private require(id: string): State {- const state = this.sessions.get(id);- if (!state || !state.client.isAlive)- throw new ProviderSessionError('antigravity', id, 'Session is not running');- return state;- }- private emit(state: State, event: Emittable): void {- const full = {- ...event,- eventId: randomUUID(),- provider: 'antigravity',- sessionId: state.id,- createdAt: new Date().toISOString(),- } as ProviderRuntimeEvent;- for (const listener of this.listeners) {- try {- listener(full);- } catch (cause) {- this.logger.error('Antigravity event listener failed', { error: String(cause) });- }- }- }-}-export function createAntigravityAdapter(- options: AntigravityAdapterOptions = {}-): AntigravityAdapter {- return new AntigravityAdapter(options);+export function createAntigravityAdapter(options: AcpAdapterOptions = {}): AcpAdapter {+ return createAcpAdapter(antigravityAcp, options);}diff --git a/console/packages/agent-providers/src/antigravity/antigravity.integration.test.ts b/console/packages/agent-providers/src/antigravity/antigravity.integration.test.tsindex 519580ef2..ae382a476 100644--- a/console/packages/agent-providers/src/antigravity/antigravity.integration.test.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity.integration.test.ts@@ -11,5 +11,9 @@ describeConformance('antigravity', {// `invoke_subagent` runs a whole nested conversation, which can outlast the// default deadline on a slow day.timeoutMs: 300_000,+ skip: {+ subagent:+ 'antigravity-acp 1.1.1 runs invoke_subagent past the 300 s deadline, on main and on the generic ACP adapter alike (2026-10-11).',+ },mcpServers: { echo: echoMcpServerSpec() },});diff --git a/console/packages/agent-providers/src/antigravity/protocol.ts b/console/packages/agent-providers/src/antigravity/protocol.tsdeleted file mode 100644index ce71b50b5..000000000--- a/console/packages/agent-providers/src/antigravity/protocol.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { ModelChoice } from '@switch-console/shared/session-v1';--export interface ConfigChoice {- value: string;- name: string;-}-export interface ConfigOption {- id: string;- type: string;- currentValue?: string;- options?: Array<ConfigChoice | { options: ConfigChoice[] }>;-}-export function modelsFromConfig(options: ConfigOption[]): ModelChoice[] {- const model = options.find((option) => option.id === 'model' && option.type === 'select');- return (model?.options ?? [])- .flatMap((option) => ('value' in option ? [option] : option.options))- .map((option) => ({ id: option.value, label: option.name, options: {}, imageInput: true }));-}diff --git a/console/packages/agent-providers/src/antigravity/runtime.test.ts b/console/packages/agent-providers/src/antigravity/runtime.test.tsindex 1d5f2ee70..16ba5f714 100644--- a/console/packages/agent-providers/src/antigravity/runtime.test.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.test.ts@@ -2,8 +2,7 @@ import { mkdtemp, readFile, rm, writeFile, mkdir } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, expect, it } from 'vitest';-import { noopLogger } from '../transport/stdio-json-rpc';-import { antigravityProfile, antigravitySignedIn, createAntigravityClient } from './runtime';+import { antigravityLaunch, antigravityProfile, antigravitySignedIn } from './runtime';const roots: string[] = [];afterEach(async () => {@@ -15,14 +14,11 @@ it('records the auth type where every Antigravity ACP version reads it, keepingroots.push(profile);await mkdir(join(profile, 'antigravity-acp'), { recursive: true });await writeFile(join(profile, 'antigravity-acp', 'settings.json'), '{"auth":{"type":"kept"}}');- const client = await createAntigravityClient({+ await antigravityLaunch({binaryPath: '/bin/true',cwd: profile,env: { GEMINI_HOME: profile, PATH: '/usr/bin:/bin' },- logger: noopLogger,- onExit: () => {},});- await client.dispose();expect(JSON.parse(await readFile(join(profile, 'settings.json'), 'utf8'))).toEqual({auth: { type: 'oauth-personal' },});diff --git a/console/packages/agent-providers/src/antigravity/runtime.ts b/console/packages/agent-providers/src/antigravity/runtime.tsindex a9537d6c8..9660b664c 100644--- a/console/packages/agent-providers/src/antigravity/runtime.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.ts@@ -1,7 +1,7 @@import { mkdir, readFile, writeFile } from 'node:fs/promises';import { homedir } from 'node:os';import { basename, dirname, join, isAbsolute } from 'node:path';-import { StdioJsonRpcClient, type ProviderLogger } from '../transport/stdio-json-rpc';+import type { AcpLaunch, AcpLaunchInput } from '../acp/hooks';export const ANTIGRAVITY_SIGN_IN ='Sign in to Antigravity ACP on the execution host with antigravity-acp --login. The ACP runtime has a separate login from agy.';@@ -35,13 +35,11 @@ export async function antigravitySignedIn(profile: string): Promise<boolean> {}}-export async function createAntigravityClient(input: {- binaryPath: string;- cwd: string;- env: Record<string, string>;- logger: ProviderLogger;- onExit: (reason: string) => void;-}): Promise<StdioJsonRpcClient> {+/**+ * How `antigravity-acp` runs: in its own profile directory, set up for OAuth+ * on first use, and killed when it prints a sign-in link instead of answering.+ */+export async function antigravityLaunch(input: AcpLaunchInput): Promise<AcpLaunch> {if (['agy', 'antigravity'].includes(basename(input.binaryPath)))throw new Error('The selected executable is the old Antigravity CLI. Install and select antigravity-acp in provider setup.'@@ -61,10 +59,9 @@ export async function createAntigravityClient(input: {});}const raw = basename(input.binaryPath).startsWith('agy_acp_server');- return new StdioJsonRpcClient({+ return {command: input.binaryPath,args: raw && process.platform === 'linux' ? ['--uid='] : [],- cwd: input.cwd,env: {...input.env,GEMINI_HOME: profile,@@ -75,47 +72,9 @@ export async function createAntigravityClient(input: {? { ANTIGRAVITY_HARNESS_PATH: join(dirname(input.binaryPath), 'localharness_external') }: {}),},- logger: input.logger,- onExit: input.onExit,rejectOutputLine: (line) =>line.includes('Open the following link to authenticate the ACP server:')? ANTIGRAVITY_SIGN_IN: undefined,- });-}--/**- * The ACP handshake, and nothing else.- *- * Deliberately does NOT sign in. The response's `authMethods` is the agent- * saying which sign-ins are still outstanding, so this is the whole of what a- * caller needs to ANSWER "is this signed in?" — and answering that question- * must not change it. Signing in is {@link authenticateAntigravity}, called- * only where the user has asked for work that needs it.- */-export async function initializeAntigravity(client: StdioJsonRpcClient) {- return await client.request<{- agentCapabilities?: {- sessionCapabilities?: { resume?: unknown };- mcpCapabilities?: { http?: boolean };- };- authMethods?: { id?: string }[];- }>('initialize', {- protocolVersion: 1,- clientInfo: { name: 'switch-console', version: '0.1.0' },- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },- });-}--/**- * Sign in to the ACP server.- *- * **This opens a browser** when the profile holds no usable token — the OAuth- * consent page, launched by the agent itself. `BROWSER=false` in the spawn env- * asks it not to, and it is not obliged to listen, which is why the call site- * matters more than the mitigation: only call this for work the user asked- * for, never to find out whether it would be needed.- */-export async function authenticateAntigravity(client: StdioJsonRpcClient) {- await client.request('authenticate', { methodId: 'oauth-personal' });+ };}diff --git a/console/packages/agent-providers/src/claude/sign-in.ts b/console/packages/agent-providers/src/claude/sign-in.tsnew file mode 100644index 000000000..9536c9c2f--- /dev/null+++ b/console/packages/agent-providers/src/claude/sign-in.ts@@ -0,0 +1,41 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { z } from 'zod';+import {+ commandOutput,+ readiness,+ signInWith,+ type ProviderReadiness,+ type SignInCheckInput,+} from '../readiness';++export const CLAUDE_LOGIN = 'claude auth login';++export function parseClaudeAuthStatus(output: string): ProviderReadiness {+ const value = z.object({ loggedIn: z.boolean() }).safeParse(JSON.parse(output));+ if (!value.success)+ return readiness(+ 'unknown',+ 'Could not verify authentication. Check provider setup and try again.'+ );+ return value.data.loggedIn+ ? readiness('authenticated', 'Signed in.')+ : readiness('unauthenticated', signInWith(CLAUDE_LOGIN));+}++export async function checkClaudeSignIn(input: SignInCheckInput): Promise<ProviderReadiness> {+ let output: string;+ try {+ output = (+ await promisify(execFile)(input.binaryPath, ['auth', 'status'], {+ cwd: input.cwd,+ env: input.env,+ timeout: 15000,+ maxBuffer: 1024 * 1024,+ })+ ).stdout;+ } catch (error) {+ output = commandOutput(error);+ }+ return parseClaudeAuthStatus(output);+}diff --git a/console/packages/agent-providers/src/codex/sign-in.ts b/console/packages/agent-providers/src/codex/sign-in.tsnew file mode 100644index 000000000..557ca8a9f--- /dev/null+++ b/console/packages/agent-providers/src/codex/sign-in.ts@@ -0,0 +1,36 @@+import { z } from 'zod';+import { readiness, signInWith, type ProviderReadiness, type SignInCheckInput } from '../readiness';+import { noopLogger, StdioJsonRpcClient } from '../transport/stdio-json-rpc';++export const CODEX_LOGIN = 'codex login';++export async function checkCodexSignIn(input: SignInCheckInput): Promise<ProviderReadiness> {+ const client = new StdioJsonRpcClient({+ command: input.binaryPath,+ args: ['app-server'],+ cwd: input.cwd,+ env: input.env,+ logger: noopLogger,+ onExit: () => {},+ });+ const timer = setTimeout(() => {+ void client.dispose().catch(() => console.warn('Provider readiness process cleanup failed.'));+ }, 20000);+ try {+ await client.request('initialize', {+ clientInfo: { name: 'switch-console', version: '0.1.0' },+ });+ client.notify('initialized', null);+ const account = z+ .object({ account: z.unknown().nullable(), requiresOpenaiAuth: z.boolean() })+ .parse(await client.request('account/read', { refreshToken: false }));+ if (!account.account && account.requiresOpenaiAuth)+ return readiness('unauthenticated', signInWith(CODEX_LOGIN));+ return account.account+ ? readiness('authenticated', 'Signed in.')+ : readiness('unknown', 'This Codex backend does not require OpenAI sign-in.');+ } finally {+ clearTimeout(timer);+ await client.dispose();+ }+}diff --git a/console/packages/agent-providers/src/cursor/cursor-adapter.ts b/console/packages/agent-providers/src/cursor/cursor-adapter.tsindex 09177c11f..edf319fc5 100644--- a/console/packages/agent-providers/src/cursor/cursor-adapter.ts+++ b/console/packages/agent-providers/src/cursor/cursor-adapter.ts@@ -1,28 +1,32 @@+import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';-import { readFile, realpath } from 'node:fs/promises';-import { pathToFileURL } from 'node:url';-import type { ModelChoice } from '@switch-console/shared/session-v1';-import { requireHttpMcp } from '../acp-mcp';-import type {- ModelSelection,- ProviderAdapter,- ProviderSendTurnInput,- ProviderSessionStartInput,-} from '../adapter';-import { ProviderSessionError } from '../adapter';-import type {- ApprovalDecision,- ProviderItem,- ProviderRuntimeEvent,- UserInputAnswers,- UserInputQuestion,-} from '../events';-import {- StdioJsonRpcClient,- JsonRpcError,- noopLogger,- type ProviderLogger,-} from '../transport/stdio-json-rpc';+import { promisify } from 'node:util';+import { createAcpAdapter, type AcpAdapter } from '../acp/acp-adapter';+import type { AcpAdapterOptions, AcpProviderHooks, AcpSessionContext } from '../acp/hooks';+import type { ItemType } from '../events';+import { commandOutput, readiness, signInWith, type ProviderReadiness } from '../readiness';++const CURSOR_LOGIN = 'agent login';+const SIGNED_OUT = /not logged in|login required|authentication required/i;++/** Reads `agent about`, which names the signed-in account. */+export function parseCursorAbout(output: string): ProviderReadiness {+ if (+ /not logged in|not authenticated|login required|authentication required|not signed in/i.test(+ output+ )+ )+ return readiness('unauthenticated', signInWith(CURSOR_LOGIN));+ const email = output.match(/User Email(?:[ \t]*:[ \t]*|[ \t]+)(.+)/i)?.[1]?.trim();+ if (!email)+ return readiness(+ 'unknown',+ 'Could not verify authentication. Check provider setup and try again.'+ );+ return SIGNED_OUT.test(email)+ ? readiness('unauthenticated', signInWith(CURSOR_LOGIN))+ : readiness('authenticated', 'Signed in.');+}interface CursorQuestion {title?: string;@@ -37,696 +41,130 @@ interface CursorPlan {name?: string;plan: string;}-interface PermissionOption {- optionId: string;- name: string;- kind: string;-}-interface ToolUpdate {- sessionUpdate: string;- toolCallId: string;- title?: string;- kind?: string;- rawInput?: { _toolName?: string; providerIdentifier?: string; toolName?: string };- rawOutput?: Record<string, unknown>;- status?: string;- content?: Array<{- type: string;- content?: { type: string; text?: string };- path?: string;- oldText?: string;- newText?: string;- }>;-}-interface Update extends Omit<ToolUpdate, 'content'> {- content?: ToolUpdate['content'] | { type: string; text?: string };-}-interface State {- id: string;- nativeId: string;- models?: ModelChoice[];- client: StdioJsonRpcClient;- turn: string | null;- queue: ProviderSendTurnInput[];- items: Map<string, ProviderItem>;- approvals: Map<- string,- { options: Map<ApprovalDecision, string>; settle: (value: unknown) => void }- >;- messageId: string;- messageText: string;- stopping: boolean;- interrupted: boolean;- context: string;- runtimeMode: ProviderSessionStartInput['runtimeMode'];- questions: Map<string, { questions: UserInputQuestion[]; settle: (value: unknown) => void }>;- plans: Map<string, (value: unknown) => void>;- mcpNames: Set<string>;- toolServers: Map<string, string>;++function question(context: AcpSessionContext, params: CursorQuestion): Promise<unknown> {+ return context.askQuestions(+ params.questions.map((q) => ({+ id: q.id,+ header: params.title,+ question: q.prompt,+ options: q.options.map((o) => ({ label: o.label, value: o.id })),+ multiSelect: q.allowMultiple ?? false,+ allowCustomAnswer: false,+ })),+ (selected) => ({+ outcome: {+ outcome: 'answered',+ answers: selected.map(({ questionId, values }) => ({+ questionId,+ selectedOptionIds: values,+ })),+ },+ })+ );}-type Emittable<T = ProviderRuntimeEvent> = T extends ProviderRuntimeEvent- ? Omit<T, 'eventId' | 'provider' | 'sessionId' | 'createdAt'>- : never;+function plan(context: AcpSessionContext, params: CursorPlan): Promise<unknown> {+ return context.requestDecision({+ requestType: 'tool_approval',+ title: params.name ?? 'Approve plan',+ detail: params.plan,+ options: [+ { decision: 'accept', label: 'Approve plan', response: { outcome: { outcome: 'accepted' } } },+ { decision: 'decline', label: 'Reject plan', response: { outcome: { outcome: 'rejected' } } },+ { decision: 'cancel', label: 'Cancel', response: { outcome: { outcome: 'cancelled' } } },+ ],+ });+}-export interface CursorAdapterOptions {- binaryPath?: string;- logger?: ProviderLogger;+function extensionItem(+ context: AcpSessionContext,+ title: string,+ params: unknown,+ type: ItemType+): void {+ const data = params as { toolCallId?: string; agentId?: string; description?: string };+ context.completeItem({+ id: data.toolCallId ?? randomUUID(),+ type,+ status: 'completed',+ title: data.description ?? title,+ text: JSON.stringify(params, null, 2),+ ...(data.agentId ? { nativeChildId: data.agentId } : {}),+ });}-export class CursorAdapter implements ProviderAdapter {- readonly provider = 'cursor';- readonly capabilities = {+/** Cursor's `agent acp`, with its questions, plans, todos and subagent tasks. */+export const cursorAcp: AcpProviderHooks = {+ provider: 'cursor',+ label: 'Cursor CLI',+ defaultBinary: 'agent',+ capabilities: {modelSwitchInSession: true,steering: false,resume: true,approvals: true,userInput: false,- };- private readonly sessions = new Map<string, State>();- private readonly listeners = new Set<(event: ProviderRuntimeEvent) => void>();- private readonly logger: ProviderLogger;- constructor(private readonly options: CursorAdapterOptions = {}) {- this.logger = options.logger ?? noopLogger;- }-- subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void {- this.listeners.add(listener);- return () => this.listeners.delete(listener);- }- hasSession(id: string): boolean {- return this.sessions.has(id);- }-- async startSession(input: ProviderSessionStartInput) {- if (this.hasSession(input.sessionId))- throw new ProviderSessionError('cursor', input.sessionId, 'session already started');- const cwd = await realpath(input.cwd);- const client = new StdioJsonRpcClient({- command: this.options.binaryPath ?? 'agent',- args: ['acp'],- cwd,- env: input.env,- logger: this.logger,- onExit: (reason) => this.exited(input.sessionId, reason),- });- const state: State = {- id: input.sessionId,- nativeId: '',- client,- turn: null,- queue: [],- items: new Map(),- approvals: new Map(),- messageId: '',- messageText: '',- stopping: false,- interrupted: false,- context: input.systemContext ?? '',- runtimeMode: input.runtimeMode,- questions: new Map(),- plans: new Map(),- mcpNames: new Set(Object.keys(input.mcpServers)),- toolServers: new Map(),- };- this.sessions.set(state.id, state);- client.onNotification('session/update', (params) => {- const payload = params as { sessionId: string; update: Update };- if (payload.sessionId === state.nativeId) this.update(state, payload.update);- });- client.onServerRequest('session/request_permission', (params) =>- this.permission(- state,- params as { sessionId: string; toolCall: ToolUpdate; options: PermissionOption[] }- )- );+ },+ launch: ({ binaryPath, env }) => ({ command: binaryPath, args: ['acp'], env }),+ loginCommand: CURSOR_LOGIN,+ checkSignIn: async ({ binaryPath, cwd, env }) => {+ // `about` and `status` answer "Not logged in" whatever API key they run+ // with, so a key cannot be checked without spending a request: it is taken+ // as given, and a bad one fails the first turn.+ if (env.CURSOR_API_KEY?.trim())+ return readiness('authenticated', 'Signs in with the Cursor API key it was given.');+ let output: string;+ try {+ output = (+ await promisify(execFile)(binaryPath, ['about'], {+ cwd,+ env,+ timeout: 15000,+ maxBuffer: 1024 * 1024,+ })+ ).stdout;+ } catch (error) {+ output = commandOutput(error);+ }+ return parseCursorAbout(output);+ },+ // With an API key the CLI is signed in already; `cursor_login` would ignore+ // the key and start a browser sign-in, which a host cannot finish.+ authMethodId: (env) => (env.CURSOR_API_KEY?.trim() ? undefined : 'cursor_login'),+ promptCapabilities: { image: true },+ // Cursor's own modes are workflows (agent, plan, ask), not permission+ // levels, so the runtime mode is enforced on its permission requests.+ sessionMode: () => 'agent',+ mcpServerOf: (toolCall) => {+ const server = toolCall.rawInput?.providerIdentifier;+ return typeof server === 'string' && server ? server : undefined;+ },+ itemType: (toolCall) =>+ toolCall.rawInput?._toolName === 'task' || toolCall.title?.startsWith('Task:')+ ? 'subagent'+ : undefined,+ extensions: (context, on) => {for (const prefix of ['cursor/', '_cursor/']) {- client.onServerRequest(`${prefix}ask_question`, async (params) =>- this.question(state, params as CursorQuestion)- );- client.onServerRequest(`${prefix}create_plan`, async (params) =>- this.plan(state, params as CursorPlan)- );+ on.request(`${prefix}ask_question`, (params) => question(context, params as CursorQuestion));+ on.request(`${prefix}create_plan`, (params) => plan(context, params as CursorPlan));for (const [method, title, type] of [['update_todos', 'Tasks', 'tool_call'],['task', 'Subagent task', 'subagent'],['generate_image', 'Generated image', 'tool_call'],] as const) {- const handle = (params: unknown) => this.extensionItem(state, title, params, type);- client.onNotification(`${prefix}${method}`, handle);- client.onServerRequest(`${prefix}${method}`, async (params) => {- handle(params);- return {};- });- }- }- this.emit(state, { type: 'session.state.changed', status: 'starting' });- try {- const initialized = await client.request<{- agentInfo?: { version: string };- agentCapabilities?: { loadSession?: boolean; mcpCapabilities?: { http?: boolean } };- }>('initialize', {- protocolVersion: 1,- clientInfo: { name: 'switch-console', version: '0.1.0' },- clientCapabilities: {},- });- requireHttpMcp(- 'Cursor CLI',- input.mcpServers,- initialized.agentCapabilities?.mcpCapabilities?.http- );- // With an API key the CLI is signed in already; `cursor_login` would- // ignore the key and start a browser sign-in, which a host cannot finish.- if (!input.env.CURSOR_API_KEY?.trim())- await client.request('authenticate', { methodId: 'cursor_login' });- const mcpServers = Object.entries(input.mcpServers).map(([name, server]) =>- server.transport === 'stdio'- ? {- name,- command: server.command,- args: server.args,- env: Object.entries(server.env ?? {}).map(([name, value]) => ({ name, value })),- }- : {- name,- type: 'http',- url: server.url,- headers: Object.entries(server.headers ?? {}).map(([name, value]) => ({- name,- value,- })),- }- );- if (input.resume && !initialized.agentCapabilities?.loadSession)- throw new Error('This Cursor CLI does not support session resume.');- state.nativeId = input.resume?.nativeSessionId ?? '';- const result = await client.request<{- sessionId?: string;- models?: { availableModels: { modelId: string; name: string }[] };- }>(input.resume ? 'session/load' : 'session/new', {- cwd,- mcpServers,- ...(input.resume ? { sessionId: input.resume.nativeSessionId } : {}),- });- state.nativeId = result.sessionId ?? state.nativeId;- state.models = (result.models?.availableModels ?? []).map((model) => ({- id: model.modelId,- label: model.name,- options: {},- }));- if (!state.nativeId) throw new Error('Cursor returned no session ID.');- await client.request('session/set_mode', {- sessionId: state.nativeId,- modeId: 'agent',- });- if (input.model) await this.setModel(state.id, input.model);- this.emit(state, { type: 'session.started', nativeSessionId: state.nativeId });- this.emit(state, { type: 'session.state.changed', status: 'ready' });- return { provider: 'cursor', sessionId: state.id, nativeSessionId: state.nativeId };- } catch (cause) {- await client.dispose();- this.sessions.delete(state.id);- const details =- cause instanceof JsonRpcError &&- typeof cause.data === 'object' &&- cause.data !== null &&- 'details' in cause.data- ? String(cause.data.details)- : '';- throw new ProviderSessionError(- 'cursor',- state.id,- `Could not start Cursor ACP: ${String(cause)}${details ? `: ${details}` : ''}${client.stderr ? `\n${client.stderr}` : ''}`,- { cause }- );- }- }-- async sendTurn(input: ProviderSendTurnInput) {- const state = this.require(input.sessionId);- state.queue.push(input);- if (!state.turn) this.drain(state);- return { turnId: input.turnId };- }-- private drain(state: State): void {- if (state.turn || state.stopping || !this.hasSession(state.id)) return;- const input = state.queue.shift();- if (!input) return;- state.turn = input.turnId;- state.interrupted = false;- state.messageId = randomUUID();- state.items.clear();- state.toolServers.clear();- this.emit(state, { type: 'turn.started', turnId: input.turnId });- this.emit(state, { type: 'session.state.changed', status: 'running' });- void this.run(state, input).then(- (reason) => {- if (state.turn !== input.turnId) return;- const interrupted = state.interrupted || reason === 'cancelled';- this.complete(- state,- interrupted ? 'interrupted' : reason === 'end_turn' ? 'completed' : 'error',- interrupted- ? 'Interrupted.'- : reason === 'end_turn'- ? undefined- : `Cursor stopped: ${reason}`- );- },- (error: unknown) => {- if (state.turn !== input.turnId) return;- this.complete(- state,- state.interrupted ? 'interrupted' : 'error',- state.interrupted ? 'Interrupted.' : String(error)+ on.notification(`${prefix}${method}`, (params) =>+ extensionItem(context, title, params, type));- }- );- }-- private async run(state: State, input: ProviderSendTurnInput): Promise<string> {- if (input.model) await this.setModel(state.id, input.model);- const prompt: Array<Record<string, unknown>> = [- { type: 'text', text: state.context ? `${state.context}\n\n${input.text}` : input.text },- ];- state.context = '';- for (const attachment of input.attachments ?? []) {- if (attachment.mimeType.startsWith('image/')) {- prompt.push({- type: 'image',- data: (await readFile(attachment.path)).toString('base64'),- mimeType: attachment.mimeType,- });- } else {- prompt.push({- type: 'text',- text: `Attached file: ${pathToFileURL(attachment.path).href}`,+ on.request(`${prefix}${method}`, (params) => {+ extensionItem(context, title, params, type);+ return {};});}}- return (- await state.client.request<{ stopReason: string }>('session/prompt', {- sessionId: state.nativeId,- prompt,- })- ).stopReason;- }-- async interruptTurn(id: string): Promise<void> {- const state = this.require(id);- if (!state.turn) return;- state.interrupted = true;- state.client.notify('session/cancel', { sessionId: state.nativeId });- this.cancelApprovals(state);- }-- async listModels(id: string): Promise<ModelChoice[]> {- return this.require(id).models ?? [];- }-- async setModel(id: string, model: ModelSelection): Promise<void> {- const state = this.require(id);- await state.client.request('session/set_model', {- sessionId: state.nativeId,- modelId: model.id,- });- }-- async respondToRequest(id: string, requestId: string, decision: ApprovalDecision): Promise<void> {- const state = this.require(id);- const plan = state.plans.get(requestId);- if (plan) {- state.plans.delete(requestId);- plan({- outcome: {- outcome:- decision === 'accept' ? 'accepted' : decision === 'decline' ? 'rejected' : 'cancelled',- },- });- this.emit(state, { type: 'request.resolved', requestId, decision });- return;- }- const pending = state.approvals.get(requestId);- if (!pending) throw new ProviderSessionError('cursor', id, `No pending approval ${requestId}`);- const optionId = pending.options.get(decision);- if (!optionId && decision !== 'cancel' && decision !== 'decline')- throw new ProviderSessionError('cursor', id, `Decision ${decision} is not offered`);- state.approvals.delete(requestId);- pending.settle({- outcome: optionId ? { outcome: 'selected', optionId } : { outcome: 'cancelled' },- });- this.emit(state, { type: 'request.resolved', requestId, decision });- }-- async respondToUserInput(- id: string,- requestId: string,- answers: UserInputAnswers- ): Promise<void> {- const state = this.require(id);- const pending = state.questions.get(requestId);- if (!pending) throw new ProviderSessionError('cursor', id, `No pending question ${requestId}`);- const selected = pending.questions.map((question) => {- const answer = answers[question.id];- const values = Array.isArray(answer) ? answer : typeof answer === 'string' ? [answer] : [];- if (- !values.length ||- (!question.multiSelect && values.length !== 1) ||- values.some((value) => !question.options.some((option) => option.value === value))- )- throw new ProviderSessionError('cursor', id, `Invalid answer for ${question.id}`);- return { questionId: question.id, selectedOptionIds: values };- });- state.questions.delete(requestId);- pending.settle({ outcome: { outcome: 'answered', answers: selected } });- this.emit(state, { type: 'user-input.resolved', requestId });- }-- private question(state: State, params: CursorQuestion): Promise<unknown> | unknown {- if (!state.turn || state.interrupted) return { outcome: { outcome: 'cancelled' } };- const requestId = randomUUID();- const questions = params.questions.map((q) => ({- id: q.id,- header: params.title,- question: q.prompt,- options: q.options.map((o) => ({ label: o.label, value: o.id })),- multiSelect: q.allowMultiple ?? false,- allowCustomAnswer: false,- }));- return new Promise((settle) => {- state.questions.set(requestId, { questions, settle });- this.emit(state, { type: 'user-input.requested', turnId: state.turn!, requestId, questions });- });- }+ },+};- private plan(state: State, params: CursorPlan): Promise<unknown> | unknown {- if (!state.turn || state.interrupted) return { outcome: { outcome: 'cancelled' } };- const requestId = randomUUID();- return new Promise((settle) => {- state.plans.set(requestId, settle);- this.emit(state, {- type: 'request.opened',- turnId: state.turn!,- requestId,- requestType: 'tool_approval',- title: params.name ?? 'Approve plan',- detail: params.plan,- options: [- { decision: 'accept', label: 'Approve plan' },- { decision: 'decline', label: 'Reject plan' },- { decision: 'cancel', label: 'Cancel' },- ],- });- });- }-- private extensionItem(- state: State,- title: string,- params: unknown,- type: ProviderItem['type'] = 'tool_call'- ): void {- if (!state.turn) return;- const data = params as { toolCallId?: string; agentId?: string; description?: string };- this.emit(state, {- type: 'item.completed',- turnId: state.turn,- item: {- id: data.toolCallId ?? randomUUID(),- type,- status: 'completed',- title: data.description ?? title,- text: JSON.stringify(params, null, 2),- ...(data.agentId ? { nativeChildId: data.agentId } : {}),- },- });- }-- private async permission(- state: State,- params: { sessionId: string; toolCall: ToolUpdate; options: PermissionOption[] }- ): Promise<unknown> {- if (params.sessionId !== state.nativeId || !state.turn || state.interrupted)- return { outcome: { outcome: 'cancelled' } };- const once = params.options.find((option) => option.kind === 'allow_once');- if (- once &&- (state.mcpNames.has(state.toolServers.get(params.toolCall.toolCallId) ?? '') ||- state.runtimeMode === 'full-access' ||- (state.runtimeMode === 'auto-accept-edits' && params.toolCall.kind === 'edit'))- )- return { outcome: { outcome: 'selected', optionId: once.optionId } };- const turnId = state.turn;- const requestId = randomUUID();- const options = new Map<ApprovalDecision, string>();- const offered: Array<{ decision: ApprovalDecision; label: string }> = [];- for (const option of params.options) {- if (!['allow_once', 'reject_once'].includes(option.kind)) continue;- const decision =- option.kind === 'allow_once'- ? 'accept'- : option.kind === 'allow_always'- ? 'acceptForSession'- : 'decline';- // Permanent policies are intentionally not offered by this session UI.- if (options.has(decision) || /future|permanent/i.test(option.name)) continue;- options.set(decision, option.optionId);- offered.push({ decision, label: option.name });- }- offered.push({ decision: 'cancel', label: 'Cancel' });- return new Promise((settle) => {- state.approvals.set(requestId, { options, settle });- this.emit(state, {- type: 'request.opened',- turnId,- requestId,- requestType:- params.toolCall.kind === 'execute'- ? 'command_execution_approval'- : params.toolCall.kind === 'edit'- ? 'file_change_approval'- : 'tool_approval',- title: params.toolCall.title ?? 'Cursor needs permission',- options: offered,- });- });- }-- private update(state: State, update: Update): void {- if (!state.turn) return;- if (- update.sessionUpdate === 'agent_message_chunk' &&- update.content &&- !Array.isArray(update.content) &&- update.content.type === 'text'- ) {- if (!state.messageText)- this.emit(state, {- type: 'item.started',- turnId: state.turn,- item: {- id: state.messageId,- type: 'assistant_message',- status: 'in_progress',- title: '',- text: '',- },- });- state.messageText += update.content.text ?? '';- this.emit(state, {- type: 'content.delta',- turnId: state.turn,- itemId: state.messageId,- delta: update.content.text ?? '',- });- return;- }- if (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update') {- const old = state.items.get(update.toolCallId);- if (update.rawInput?.providerIdentifier)- state.toolServers.set(update.toolCallId, update.rawInput.providerIdentifier);- const content = Array.isArray(update.content) ? update.content : [];- const text = content- .map((part) =>- part.type === 'diff' ? `${part.path}\n${part.newText ?? ''}` : (part.content?.text ?? '')- )- .join('\n');- const output = update.rawOutput;- const outputFailed =- output &&- (Boolean(output.error) ||- output.rejected === true ||- output.permissionDenied === true ||- (typeof output.exitCode === 'number' && output.exitCode !== 0));- const resultText = output ? JSON.stringify(output, null, 2) : '';- const toolText = [text, resultText].filter(Boolean).join('\n');- const item: ProviderItem = {- id: update.toolCallId,- type:- (old?.type !== 'tool_call' ? old?.type : undefined) ??- (update.rawInput?._toolName === 'task' || update.title?.startsWith('Task:')- ? 'subagent'- : update.rawInput?.providerIdentifier || update.toolCallId.startsWith('mcp_')- ? 'mcp_tool_call'- : update.kind === 'execute'- ? 'command_execution'- : update.kind === 'edit'- ? 'file_change'- : 'tool_call'),- title: update.title ?? old?.title ?? 'Tool',- status: outputFailed- ? 'failed'- : update.status === 'completed'- ? 'completed'- : update.status === 'failed'- ? 'failed'- : (old?.status ?? 'in_progress'),- ...(toolText || old?.text ? { text: toolText || old?.text } : {}),- };- state.items.set(item.id, item);- this.emit(state, {- type:- item.status === 'completed' || item.status === 'failed'- ? 'item.completed'- : old- ? 'item.updated'- : 'item.started',- turnId: state.turn,- item,- });- this.finishMessage(state, 'completed');- state.messageId = randomUUID();- }- }-- private finishMessage(state: State, status: 'completed' | 'failed'): void {- if (!state.turn || !state.messageText) return;- this.emit(state, {- type: 'item.completed',- turnId: state.turn,- item: {- id: state.messageId,- type: 'assistant_message',- title: 'Assistant',- status,- text: state.messageText,- },- });- state.messageText = '';- }-- private complete(- state: State,- outcome: 'completed' | 'interrupted' | 'error',- message?: string- ): void {- if (!state.turn) return;- const turnId = state.turn;- this.finishMessage(state, outcome === 'completed' ? 'completed' : 'failed');- for (const item of state.items.values())- if (item.status === 'in_progress') {- if (outcome === 'completed') {- outcome = 'error';- message = 'Cursor ended the turn without confirming a pending tool result.';- }- this.emit(state, {- type: 'item.completed',- turnId,- item: {- ...item,- status: 'failed',- ...(message ? { text: [item.text, message].filter(Boolean).join('\n') } : {}),- },- });- }- this.cancelApprovals(state);- state.turn = null;- this.emit(state, {- type: 'turn.completed',- turnId,- outcome,- ...(message ? { message } : {}),- usage: [],- });- if (!state.turn)- this.emit(state, {- type: 'session.state.changed',- status: state.stopping ? 'stopped' : outcome === 'error' ? 'error' : 'ready',- });- this.drain(state);- }-- private cancelApprovals(state: State): void {- for (const [requestId, pending] of state.approvals) {- pending.settle({ outcome: { outcome: 'cancelled' } });- this.emit(state, { type: 'request.resolved', requestId, decision: 'cancel' });- }- state.approvals.clear();- for (const [requestId, pending] of state.questions) {- pending.settle({ outcome: { outcome: 'cancelled' } });- this.emit(state, { type: 'user-input.resolved', requestId });- }- state.questions.clear();- for (const [requestId, settle] of state.plans) {- settle({ outcome: { outcome: 'cancelled' } });- this.emit(state, { type: 'request.resolved', requestId, decision: 'cancel' });- }- state.plans.clear();- }- async stopSession(id: string): Promise<void> {- const state = this.sessions.get(id);- if (!state) return;- state.stopping = true;- if (state.turn) await this.interruptTurn(id);- await state.client.dispose();- this.exited(id, 'Session stopped');- }- async stopAll(): Promise<void> {- await Promise.all([...this.sessions.keys()].map((id) => this.stopSession(id)));- }- private exited(id: string, reason: string): void {- const state = this.sessions.get(id);- if (!state) return;- const stopping = state.stopping;- state.stopping = true;- this.complete(state, stopping ? 'interrupted' : 'error', reason);- this.cancelApprovals(state);- for (const input of state.queue.splice(0))- this.emit(state, {- type: 'turn.completed',- turnId: input.turnId,- outcome: 'error',- message: reason,- usage: [],- });- this.sessions.delete(id);- this.emit(state, { type: 'session.state.changed', status: 'stopped' });- this.emit(state, { type: 'session.exited', reason });- }- private require(id: string): State {- const state = this.sessions.get(id);- if (!state || !state.client.isAlive)- throw new ProviderSessionError('cursor', id, 'Session is not running');- return state;- }- private emit(state: State, event: Emittable): void {- const full = {- ...event,- eventId: randomUUID(),- provider: 'cursor',- sessionId: state.id,- createdAt: new Date().toISOString(),- } as ProviderRuntimeEvent;- for (const listener of this.listeners) {- try {- listener(full);- } catch (cause) {- this.logger.error('Cursor event listener failed', { error: String(cause) });- }- }- }-}-export function createCursorAdapter(options: CursorAdapterOptions = {}): CursorAdapter {- return new CursorAdapter(options);+export function createCursorAdapter(options: AcpAdapterOptions = {}): AcpAdapter {+ return createAcpAdapter(cursorAcp, options);}diff --git a/console/packages/agent-providers/src/cursor/cursor.integration.test.ts b/console/packages/agent-providers/src/cursor/cursor.integration.test.tsindex a8bf0f432..9e18c17bc 100644--- a/console/packages/agent-providers/src/cursor/cursor.integration.test.ts+++ b/console/packages/agent-providers/src/cursor/cursor.integration.test.ts@@ -15,4 +15,7 @@ describeConformance('cursor', {'Installed Cursor default model does not expose AskQuestion in agent or plan mode; protocol handlers are covered with wire-level tests and prose questions with Mattermost.',},mcpServers: { echo: echoMcpServerSpec() },+ // The harness hands the CLI a minimal environment, so a key in the shell+ // would not reach it and Cursor would fall back to a browser sign-in.+ ...(process.env.CURSOR_API_KEY ? { env: { CURSOR_API_KEY: process.env.CURSOR_API_KEY } } : {}),});diff --git a/console/packages/agent-providers/src/host/agent-env.ts b/console/packages/agent-providers/src/host/agent-env.tsindex bd8b190b9..9bdccf411 100644--- a/console/packages/agent-providers/src/host/agent-env.ts+++ b/console/packages/agent-providers/src/host/agent-env.ts@@ -1,3 +1,5 @@+import { PROVIDER_RUNTIMES } from '../providers/registry';+export const AGENT_ENV_VARS = ['ALL_PROXY','ANTHROPIC_API_KEY',@@ -64,11 +66,12 @@ export const AGENT_ENV_VARS = [/*** What a session host's `execution.inheritEnv` names: the provider variables- * above plus the basics a CLI needs to find itself, its home and its terminal.+ * above, those each registered provider's runtime asks for, and the basics a+ * CLI needs to find itself, its home and its terminal.* Console and the headless agents controller both launch hosts with it.*/export const EXECUTION_INHERIT_ENV: readonly string[] = [- ...AGENT_ENV_VARS,+ ...new Set([...AGENT_ENV_VARS, ...PROVIDER_RUNTIMES.flatMap((runtime) => runtime.inheritEnv)]),'PATH','HOME','USER',diff --git a/console/packages/agent-providers/src/host/provider-readiness.test.ts b/console/packages/agent-providers/src/host/provider-readiness.test.tsindex 10f7f61d5..4e13988cb 100644--- a/console/packages/agent-providers/src/host/provider-readiness.test.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from 'vitest';-import { checkProviderReadiness, parseAuthentication } from './provider-readiness';+import { parseClaudeAuthStatus } from '../claude/sign-in';+import { parseCursorAbout } from '../cursor/cursor-adapter';+import { checkProviderReadiness } from './provider-readiness';describe('a Cursor API key', () => {it('is taken as given: Cursor cannot check one without spending a request', async () => {@@ -20,32 +22,28 @@ describe('a Cursor API key', () => {describe('provider authentication', () => {it('recognizes signed-out Claude without assuming an installed CLI is ready', () => {- expect(parseAuthentication('claude', '{"loggedIn":false}').status).toBe('unauthenticated');+ expect(parseClaudeAuthStatus('{"loggedIn":false}').status).toBe('unauthenticated');});it('accepts native API-key authentication', () => {- expect(parseAuthentication('claude', '{"loggedIn":true,"authMethod":"api-key"}').status).toBe(+ expect(parseClaudeAuthStatus('{"loggedIn":true,"authMethod":"api-key"}').status).toBe('authenticated');});it('does not return account details to the renderer', () => {- expect(parseAuthentication('cursor', 'User Email: [email protected]')).toEqual({+ expect(parseCursorAbout('User Email: [email protected]')).toEqual({status: 'authenticated',message: 'Signed in.',models: [],});});it('accepts Cursor table output without a colon', () => {- expect(parseAuthentication('cursor', 'User Email [email protected]').status).toBe(- 'authenticated'- );+ expect(parseCursorAbout('User Email [email protected]').status).toBe('authenticated');});it('recognizes signed-out Cursor', () => {- expect(parseAuthentication('cursor', 'User Email: Not logged in').status).toBe(- 'unauthenticated'- );+ expect(parseCursorAbout('User Email: Not logged in').status).toBe('unauthenticated');});it('keeps an unsupported status command inconclusive', () => {- expect(parseAuthentication('cursor', 'Unknown command about').status).toBe('unknown');+ expect(parseCursorAbout('Unknown command about').status).toBe('unknown');});it('does not turn a missing executable into a signed-out result', async () => {expect(@@ -64,6 +62,6 @@ describe('provider authentication', () => {it.each(['Not logged in. Run agent login.', 'Authentication required', 'Not signed in'])('recognizes signed-out Cursor without an account row: %s',(output) => {- expect(parseAuthentication('cursor', output).status).toBe('unauthenticated');+ expect(parseCursorAbout(output).status).toBe('unauthenticated');});diff --git a/console/packages/agent-providers/src/host/provider-readiness.ts b/console/packages/agent-providers/src/host/provider-readiness.tsindex aef3c1fc8..a518816ed 100644--- a/console/packages/agent-providers/src/host/provider-readiness.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.ts@@ -1,186 +1,33 @@-import { execFile } from 'node:child_process';-import { promisify } from 'node:util';-import { z } from 'zod';-import {- ANTIGRAVITY_SIGN_IN,- antigravityProfile,- antigravitySignedIn,- createAntigravityClient,- initializeAntigravity,-} from '../antigravity/runtime';-import { startOpencodeServer, stopOpencodeServer } from '../opencode/server';-import { JsonRpcError, noopLogger, StdioJsonRpcClient } from '../transport/stdio-json-rpc';+import { providerRuntime } from '../providers/registry';+import { readiness, signInWith, type ProviderReadiness } from '../readiness';+import { JsonRpcError } from '../transport/stdio-json-rpc';-export const providerReadinessSchema = z.object({- status: z.enum(['authenticated', 'unauthenticated', 'unconfigured', 'unknown']),- message: z.string(),- models: z.array(z.object({ id: z.string(), name: z.string() })),-});-export type ProviderReadiness = z.infer<typeof providerReadinessSchema>;-const execute = promisify(execFile);-const login: Record<string, string> = {- claude: 'claude auth login',- codex: 'codex login',- cursor: 'agent login',- antigravity: 'antigravity-acp --login',- opencode: 'opencode auth login',-};-function result(status: ProviderReadiness['status'], message: string): ProviderReadiness {- return { status, message, models: [] };-}-export function parseAuthentication(provider: string, output: string): ProviderReadiness {- if (provider === 'claude') {- const value = z.object({ loggedIn: z.boolean() }).safeParse(JSON.parse(output));- if (value.success)- return result(- value.data.loggedIn ? 'authenticated' : 'unauthenticated',- value.data.loggedIn- ? 'Signed in.'- : `Sign in on the execution machine with ${login[provider]}.`- );- }- if (provider === 'cursor') {- if (- /not logged in|not authenticated|login required|authentication required|not signed in/i.test(- output- )- )- return result('unauthenticated', 'Sign in on the execution machine with agent login.');- const email = output.match(/User Email(?:[ \t]*:[ \t]*|[ \t]+)(.+)/i)?.[1]?.trim();- if (email)- return result(- /not logged in|login required|authentication required/i.test(email)- ? 'unauthenticated'- : 'authenticated',- /not logged in|login required|authentication required/i.test(email)- ? 'Sign in on the execution machine with agent login.'- : 'Signed in.'- );- }- return result('unknown', 'Could not verify authentication. Check provider setup and try again.');-}+export { providerReadinessSchema, type ProviderReadiness } from '../readiness';++/**+ * Whether a provider's CLI is signed in on this machine, asked of the CLI+ * itself through the provider's own check. A failure the check did not+ * recognise is reported as unknown, never as signed out.+ */export async function checkProviderReadiness(input: {provider: string;binaryPath: string;cwd: string;env: Record<string, string>;}): Promise<ProviderReadiness> {- let client: StdioJsonRpcClient | undefined;- let timer: ReturnType<typeof setTimeout> | undefined;+ const runtime = providerRuntime(input.provider);try {- if (input.provider === 'opencode') {- const server = await startOpencodeServer({- ...input,- startupTimeoutMs: 15000,- skills: [],- config: { $schema: 'https://opencode.ai/config.json', permission: {}, mcp: {} },- });- try {- const response = await fetch(`${server.url}/provider`, {- headers: { Authorization: server.authorization },- signal: AbortSignal.timeout(15000),- });- if (!response.ok) return result('unknown', 'Could not check OpenCode backend connections.');- const inventory = z.object({ connected: z.array(z.string()) }).parse(await response.json());- return result(- inventory.connected.length ? 'authenticated' : 'unconfigured',- inventory.connected.length- ? 'OpenCode has connected backends. Model access depends on the selected backend.'- : 'No connected OpenCode backends were reported. Configure a backend; local models may need no sign-in.'- );- } finally {- await stopOpencodeServer(server);- }- }- if (input.provider === 'cursor' && input.env.CURSOR_API_KEY?.trim())- // `cursor-agent about` and `status` answer "Not logged in" whatever API- // key they run with, so a key cannot be checked without spending a- // request: it is taken as given, and a bad one fails the first turn.- return result('authenticated', 'Signs in with the Cursor API key it was given.');- if (input.provider === 'claude' || input.provider === 'cursor') {- let output: string;- try {- output = (- await execute(- input.binaryPath,- input.provider === 'claude' ? ['auth', 'status'] : ['about'],- { cwd: input.cwd, env: input.env, timeout: 15000, maxBuffer: 1024 * 1024 }- )- ).stdout;- } catch (error) {- // A signed-out CLI may return a nonzero exit with a structured status.- output =- typeof (error as { stdout?: unknown }).stdout === 'string'- ? (error as { stdout: string }).stdout- : '';- }- return parseAuthentication(input.provider, output);- }- if (input.provider === 'antigravity') {- client = await createAntigravityClient({ ...input, logger: noopLogger, onExit: () => {} });- // Handshake only. This used to call `authenticate`, which does not test- // the sign-in — it performs it, opening a browser, and then reported- // "signed in" whether or not anything had happened. `authMethods` is the- // agent's own answer to the question being asked: the sign-ins it still- // wants. Empty means none outstanding.- const initialized = await initializeAntigravity(client);- return !initialized.authMethods?.length ||- (await antigravitySignedIn(antigravityProfile(input.env)))- ? result('authenticated', 'Signed in to Antigravity ACP.')- : result('unauthenticated', ANTIGRAVITY_SIGN_IN);- }- if (input.provider !== 'codex')- return result('unknown', 'This provider has no authentication check.');- client = new StdioJsonRpcClient({- command: input.binaryPath,- args: ['app-server'],- cwd: input.cwd,- env: input.env,- logger: noopLogger,- onExit: () => {},- });- timer = setTimeout(() => {- void client- ?.dispose()- .catch(() => console.warn('Provider readiness process cleanup failed.'));- }, 20000);- await client.request('initialize', {- clientInfo: { name: 'switch-console', version: '0.1.0' },- });- client.notify('initialized', null);- const account = z- .object({ account: z.unknown().nullable(), requiresOpenaiAuth: z.boolean() })- .parse(await client.request('account/read', { refreshToken: false }));- if (!account.account && account.requiresOpenaiAuth)- return result('unauthenticated', 'Sign in on the execution machine with codex login.');- return result(- account.account ? 'authenticated' : 'unknown',- account.account ? 'Signed in.' : 'This Codex backend does not require OpenAI sign-in.'- );+ return await runtime.checkSignIn(input);} catch (error) {- if (- input.provider === 'antigravity' &&- /sign in|auth required|unauthenticated/i.test(String(error))- )- return result(- 'unauthenticated',- 'Sign in on the execution host with antigravity-acp --login.'- );if (error instanceof JsonRpcError &&error.code === -32000 &&/auth|log.?in|sign.?in|API key is missing|no API key/i.test(error.message))- return result(- 'unauthenticated',- `Sign in on the execution machine with ${login[input.provider]}.`- );- return result(+ return readiness('unauthenticated', signInWith(runtime.loginCommand));+ return readiness('unknown','Could not verify authentication. Check the connection and provider setup, then retry.');- } finally {- if (timer) clearTimeout(timer);- await client?.dispose();}}diff --git a/console/packages/agent-providers/src/host/server.ts b/console/packages/agent-providers/src/host/server.tsindex 71573003a..a2f835296 100644--- a/console/packages/agent-providers/src/host/server.ts+++ b/console/packages/agent-providers/src/host/server.ts@@ -6,11 +6,7 @@ import { commandSchema } from '@switch-console/shared/session-v1';import type { Command, Session } from '@switch-console/shared/session-v1';import { z } from 'zod';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';-import { createCursorAdapter } from '../cursor/cursor-adapter';-import { createOpencodeAdapter } from '../opencode/opencode-adapter';+import { isProviderRuntime, providerRuntime, providerRuntimeIds } from '../providers/registry';import { HostedSession } from './session-host';const id = z.string().min(1).max(200);@@ -42,7 +38,9 @@ export const agentLaunchDefinitionSchema = z.strictObject({}) satisfies z.ZodType<AgentLaunchDefinition>;export const startSchema = z.strictObject({- provider: z.enum(['claude', 'codex', 'opencode', 'antigravity', 'cursor']),+ provider: z.string().refine(isProviderRuntime, {+ message: `Unsupported execution provider. This host runs ${providerRuntimeIds().join(', ')}.`,+ }),input: z.strictObject({sessionId: id,cwd: z.string().min(1),@@ -75,23 +73,7 @@ export function adapterFor(binaryPath: string | undefined,skill: string): ProviderAdapter {- switch (provider) {- case 'claude':- return createClaudeAdapter({ claudeExecutablePath: binaryPath });- case 'codex':- return createCodexAdapter({ binaryPath });- case 'opencode':- return createOpencodeAdapter({- binaryPath,- skills: skill ? [{ name: 'switch', content: skill }] : [],- });- case 'antigravity':- return createAntigravityAdapter({ binaryPath });- case 'cursor':- return createCursorAdapter({ binaryPath });- default:- throw new Error(`Unsupported execution provider: ${provider}`);- }+ return providerRuntime(provider).createAdapter({ binaryPath, logger: undefined, skill });}async function body(request: IncomingMessage): Promise<unknown> {diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex eb9a620c5..19e9bafd3 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -37,11 +37,19 @@ export { createOpencodeAdapter, OpencodeAdapter } from './opencode/opencode-adapexport type { OpencodeSkill } from './opencode/server';export type { CodexAdapterOptions } from './codex/codex-adapter';export { CodexAdapter, createCodexAdapter } from './codex/codex-adapter';-export { AntigravityAdapter, createAntigravityAdapter } from './antigravity/antigravity-adapter';-export type { AntigravityAdapterOptions } from './antigravity/antigravity-adapter';--export { CursorAdapter, createCursorAdapter } from './cursor/cursor-adapter';-export type { CursorAdapterOptions } from './cursor/cursor-adapter';+export { AcpAdapter, createAcpAdapter } from './acp/acp-adapter';+export type {+ AcpAdapterOptions,+ AcpExtensionRegistrar,+ AcpLaunch,+ AcpLaunchInput,+ AcpProviderHooks,+ AcpSelectedAnswer,+ AcpSessionContext,+ AcpSignInInput,+} from './acp/hooks';+export { antigravityAcp, createAntigravityAdapter } from './antigravity/antigravity-adapter';+export { cursorAcp, createCursorAdapter } from './cursor/cursor-adapter';export { ChatProjector } from './session-v1/chat-projector';export { EventOutbox } from './session-v1/event-outbox';export { HostConnection } from './host/client';@@ -137,8 +145,16 @@ export { prepareCodexSessionHome, withManagedCodexSandbox } from './codex/home';export { readSharedCredentials, sharedConfigSchema } from './host/shared-config';export type { SharedHostConfig } from './host/shared-config';-export { providerReadinessSchema } from './host/provider-readiness';-export type { ProviderReadiness } from './host/provider-readiness';+export { providerReadinessSchema } from './readiness';+export type { ProviderReadiness, SignInCheckInput } from './readiness';+export {+ acpProviderRuntime,+ isProviderRuntime,+ PROVIDER_RUNTIMES,+ providerRuntime,+ providerRuntimeIds,+} from './providers/registry';+export type { ProviderRuntime, ProviderRuntimeOptions } from './providers/registry';export { CONTROL_FILE, ControlClient, SidecarConnectionClosedError } from './host/control';export { hostSessions, hostSessionsByAgent, LIST_SCRIPT } from './host/session-list';export { JournalUnavailableError, replayJournal } from './host/journal-snapshot';diff --git a/console/packages/agent-providers/src/opencode/sign-in.ts b/console/packages/agent-providers/src/opencode/sign-in.tsnew file mode 100644index 000000000..4d21c0aec--- /dev/null+++ b/console/packages/agent-providers/src/opencode/sign-in.ts@@ -0,0 +1,34 @@+import { z } from 'zod';+import { readiness, type ProviderReadiness, type SignInCheckInput } from '../readiness';+import { startOpencodeServer, stopOpencodeServer } from './server';++export const OPENCODE_LOGIN = 'opencode auth login';++/** OpenCode signs in per backend, so "signed in" means at least one backend is connected. */+export async function checkOpencodeSignIn(input: SignInCheckInput): Promise<ProviderReadiness> {+ const server = await startOpencodeServer({+ ...input,+ startupTimeoutMs: 15000,+ skills: [],+ config: { $schema: 'https://opencode.ai/config.json', permission: {}, mcp: {} },+ });+ try {+ const response = await fetch(`${server.url}/provider`, {+ headers: { Authorization: server.authorization },+ signal: AbortSignal.timeout(15000),+ });+ if (!response.ok) return readiness('unknown', 'Could not check OpenCode backend connections.');+ const inventory = z.object({ connected: z.array(z.string()) }).parse(await response.json());+ return inventory.connected.length+ ? readiness(+ 'authenticated',+ 'OpenCode has connected backends. Model access depends on the selected backend.'+ )+ : readiness(+ 'unconfigured',+ 'No connected OpenCode backends were reported. Configure a backend; local models may need no sign-in.'+ );+ } finally {+ await stopOpencodeServer(server);+ }+}diff --git a/console/packages/agent-providers/src/providers/registry.ts b/console/packages/agent-providers/src/providers/registry.tsnew file mode 100644index 000000000..f4061b82f--- /dev/null+++ b/console/packages/agent-providers/src/providers/registry.ts@@ -0,0 +1,106 @@+import { checkAcpSignIn, createAcpAdapter } from '../acp/acp-adapter';+import type { AcpProviderHooks } from '../acp/hooks';+import type { ProviderAdapter } from '../adapter';+import { antigravityAcp } from '../antigravity/antigravity-adapter';+import { createClaudeAdapter } from '../claude/claude-adapter';+import { checkClaudeSignIn, CLAUDE_LOGIN } from '../claude/sign-in';+import { createCodexAdapter } from '../codex/codex-adapter';+import { checkCodexSignIn, CODEX_LOGIN } from '../codex/sign-in';+import { cursorAcp } from '../cursor/cursor-adapter';+import { createOpencodeAdapter } from '../opencode/opencode-adapter';+import { checkOpencodeSignIn, OPENCODE_LOGIN } from '../opencode/sign-in';+import type { ProviderReadiness, SignInCheckInput } from '../readiness';+import type { ProviderLogger } from '../transport/stdio-json-rpc';++export interface ProviderRuntimeOptions {+ /** The provider's executable; the provider's default when undefined. */+ binaryPath: string | undefined;+ logger: ProviderLogger | undefined;+ /**+ * The Switch skill file, for a provider that loads skills from a directory+ * it is given (OpenCode), or '' for none. Codex takes it through its session+ * home instead, and ACP agents through the session's system context.+ */+ skill: string;+}++/** What the execution host needs to run one provider. */+export interface ProviderRuntime {+ id: string;+ /** The command a person runs on the execution machine to sign the CLI in. */+ loginCommand: string;+ /**+ * Environment variables the CLI reads (credentials, endpoints) that a+ * session host passes through from the machine's environment.+ */+ inheritEnv: readonly string[];+ createAdapter(options: ProviderRuntimeOptions): ProviderAdapter;+ /** Whether the CLI is signed in, answered without signing it in. */+ checkSignIn(input: SignInCheckInput): Promise<ProviderReadiness>;+}++/** An ACP-speaking CLI's runtime, made entirely from its hooks. */+export function acpProviderRuntime(hooks: AcpProviderHooks): ProviderRuntime {+ return {+ id: hooks.provider,+ loginCommand: hooks.loginCommand,+ inheritEnv: hooks.inheritEnv ?? [],+ createAdapter: ({ binaryPath, logger }) => createAcpAdapter(hooks, { binaryPath, logger }),+ checkSignIn: (input) => checkAcpSignIn(hooks, input),+ };+}++/**+ * Every provider the execution host can run. This is the runtime half of+ * registering a provider; the other half is its plugin in+ * `packages/plugins/src/agents/plugin-registry.ts`, and the two must name the+ * same providers.+ */+export const PROVIDER_RUNTIMES: readonly ProviderRuntime[] = [+ {+ id: 'claude',+ loginCommand: CLAUDE_LOGIN,+ inheritEnv: [],+ createAdapter: ({ binaryPath, logger }) =>+ createClaudeAdapter({ claudeExecutablePath: binaryPath, ...(logger ? { logger } : {}) }),+ checkSignIn: checkClaudeSignIn,+ },+ {+ id: 'codex',+ loginCommand: CODEX_LOGIN,+ inheritEnv: [],+ createAdapter: ({ binaryPath, logger }) =>+ createCodexAdapter({ binaryPath, ...(logger ? { logger } : {}) }),+ checkSignIn: checkCodexSignIn,+ },+ {+ id: 'opencode',+ loginCommand: OPENCODE_LOGIN,+ inheritEnv: [],+ createAdapter: ({ binaryPath, logger, skill }) =>+ createOpencodeAdapter({+ binaryPath,+ ...(logger ? { logger } : {}),+ skills: skill ? [{ name: 'switch', content: skill }] : [],+ }),+ checkSignIn: checkOpencodeSignIn,+ },+ acpProviderRuntime(antigravityAcp),+ acpProviderRuntime(cursorAcp),+];++const RUNTIMES = new Map(PROVIDER_RUNTIMES.map((runtime) => [runtime.id, runtime]));++export function providerRuntimeIds(): string[] {+ return [...RUNTIMES.keys()];+}++export function isProviderRuntime(id: string): boolean {+ return RUNTIMES.has(id);+}++export function providerRuntime(id: string): ProviderRuntime {+ const runtime = RUNTIMES.get(id);+ if (!runtime) throw new Error(`Unsupported execution provider: ${id}`);+ return runtime;+}diff --git a/console/packages/agent-providers/src/readiness.ts b/console/packages/agent-providers/src/readiness.tsnew file mode 100644index 000000000..f65e0139f--- /dev/null+++ b/console/packages/agent-providers/src/readiness.ts@@ -0,0 +1,33 @@+import { z } from 'zod';++export const providerReadinessSchema = z.object({+ status: z.enum(['authenticated', 'unauthenticated', 'unconfigured', 'unknown']),+ message: z.string(),+ models: z.array(z.object({ id: z.string(), name: z.string() })),+});+export type ProviderReadiness = z.infer<typeof providerReadinessSchema>;++/** Where a sign-in check runs: the provider's executable, in a directory, with an environment. */+export interface SignInCheckInput {+ binaryPath: string;+ cwd: string;+ env: Record<string, string>;+}++export function readiness(status: ProviderReadiness['status'], message: string): ProviderReadiness {+ return { status, message, models: [] };+}++export function signInWith(loginCommand: string): string {+ return `Sign in on the execution machine with ${loginCommand}.`;+}++/**+ * The output of a status command a signed-out CLI may answer with a nonzero+ * exit: its stdout either way, or '' when it printed none.+ */+export function commandOutput(error: unknown): string {+ return typeof (error as { stdout?: unknown }).stdout === 'string'+ ? (error as { stdout: string }).stdout+ : '';+}diff --git a/console/packages/core/src/agents/plugins/capabilities/mcp.ts b/console/packages/core/src/agents/plugins/capabilities/mcp.tsindex 499064128..9e89472d6 100644--- a/console/packages/core/src/agents/plugins/capabilities/mcp.ts+++ b/console/packages/core/src/agents/plugins/capabilities/mcp.ts@@ -1,7 +1,7 @@import z from 'zod';import { definePluginCapability } from '../../../lib/plugins/capability';import type { PluginFs } from '../../runtime/fs';-import type { RepoAgentField } from './repo-agents';+import type { AdvancedSettings } from './repo-agents';export type McpTransport = 'stdio' | 'http';@@ -77,9 +77,10 @@ export function resolveLaunchProfileEnv(}/**- * Optional per-agent specialization folded into the launch profile: the values- * collected for the fields the provider declares in- * {@link IMcpBehavior.launchProfileFields}, keyed by those fields' keys.+ * Optional per-agent specialization folded into the launch profile: the+ * agent's model and instructions, and the values of the advanced settings the+ * provider declares in {@link IMcpBehavior.launchProfileSettings}, keyed by+ * those settings' keys.** Deliberately open rather than a fixed set of names. Providers do not agree on* what a per-agent setting is — Codex's reasoning-effort enum, verbosity and@@ -162,22 +163,24 @@ export type IMcpBehavior = {*/launchProfilePaths?(params: { slug: string; workingDir: string }): string[];/**- * The per-agent fields that feed {@link launchProfile}, declared so the UI can- * collect them without knowing the provider.+ * The advanced settings this provider applies at session start, beside the+ * model and instructions — the keys of the server's advanced configuration+ * fields that feed {@link launchProfile}, by the shape of value each takes.*- * This is the launch-profile counterpart of `repoAgents.attributeFields()`:+ * This is the launch-profile counterpart of `repoAgents.advancedSettings()`:* a provider keeps its per-agent settings either in a repo-agent definition or- * in a launch profile, and whichever it is, the same "advanced configuration"- * form renders these and the same editor saves them. Declaring them beside the- * profile builder that consumes them is what stops the field list and the TOML- * it produces drifting apart.+ * in one it reads at session start, and whichever it is, the same "advanced+ * configuration" form renders the server's fields and the same editor saves+ * them. Declared beside the profile builder that consumes them so the keys it+ * writes and the keys it claims cannot drift apart.*- * Undefined for a provider that writes no profile.+ * Undefined for a provider that keeps no per-agent settings this way; empty+ * for one that takes only the model and instructions.*/- launchProfileFields?(): RepoAgentField[];+ launchProfileSettings?(): AdvancedSettings;/**- * The models this host offers for {@link launchProfileFields}'s model field,- * with the reasoning variants each accepts.+ * The models this host offers for the agent's model field, with the+ * reasoning variants each accepts.** Optional, and the form works without it: a provider that does not implement* this gets a plain text model field, which is where both providers started.diff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 2a00b79f8..6ce6285d3 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -61,6 +61,26 @@ export const RECOGNISED_SWITCH_TOOL_RULES: readonly string[] = [*/export const SWITCH_AGENT_SETTINGS_DIR = '.switch/agents';+/**+ * The shape of value a provider applies for one advanced setting at launch:+ * a string (a server field of type `text`, `textarea` or `select`), a finite+ * number, a boolean, or a list of strings.+ */+export type AdvancedSettingKind = 'text' | 'number' | 'boolean' | 'list';++/**+ * The advanced settings a provider applies when a session launches, keyed by+ * the key of the server's advanced configuration field each comes from.+ *+ * The fields themselves — label, type, help, choices — are defined only by the+ * Switch server (`core/switch_core/providers/advanced_fields.py`) and served+ * to every client; a plugin declares only what it turns into launch inputs, so+ * a value it does not apply is refused rather than dropped. Empty for a+ * provider that applies none. The agent's main attributes — name, description,+ * model, instructions — are not advanced settings.+ */+export type AdvancedSettings = Readonly<Record<string, AdvancedSettingKind>>;+/** A renderable input type for an agent attribute field. */export type RepoAgentFieldType = 'text' | 'textarea' | 'select' | 'list' | 'number' | 'boolean';@@ -87,10 +107,10 @@ export type RepoAgentFieldCatalogue =| { kind: 'model-variant'; modelField: string };/**- * One editable attribute of an agent, declared by the agent provider. The- * renderer builds the create/edit form from these descriptors, so the set of- * attributes — and how they are presented — is provider-specific. `key` is the- * attribute name in the {@link RepoAgentAttributes} map the provider serializes.+ * One editable attribute of an agent, as a form renders it: the server's+ * advanced configuration fields for the agent's provider, and the model. `key`+ * is the attribute name in the {@link RepoAgentAttributes} map the provider+ * serializes.*/export type RepoAgentField = {key: string;@@ -114,8 +134,8 @@ export type RepoAgentField = {/** A single attribute value; shape depends on the field's `type`. */export type RepoAgentAttributeValue = string | string[] | number | boolean | null;-/** An agent's attributes, keyed by {@link RepoAgentField.key}. Always carries- * `name` and `description`; the rest are provider-defined. */+/** An agent's attributes, keyed by {@link RepoAgentField.key}: its main+ * attributes and the advanced settings its provider applies. */export type RepoAgentAttributes = Record<string, RepoAgentAttributeValue>;/**@@ -147,9 +167,8 @@ export type IRepoAgentsBehavior = {launchArgs(workingDir: string, agentName: string): string[];/** The named agent's Switch credentials as env vars, for the launched session. */readLaunchEnv(workdirFs: PluginFs, agentName: string): Promise<Record<string, string>>;- /** The attribute fields this provider supports, in display order. Drives the- * create/edit form; the first two are always `name` and `description`. */- attributeFields(): RepoAgentField[];+ /** The advanced settings a definition carries, in the order it is written. */+ advancedSettings(): AdvancedSettings;/*** The definition file's exact text for these attributes, without writing it.*@@ -169,8 +188,9 @@ export type IRepoAgentsBehavior = {/** Create or overwrite a named agent's on-disk definition from its attributes* (workdir scope). `attributes.name` selects the agent. */writeDefinition(workdirFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;- /** The current attribute values for an existing agent definition, keyed to- * {@link attributeFields}, or null if no definition exists. */+ /** The current attribute values for an existing agent definition — its+ * main attributes and {@link advancedSettings} — or null if no definition+ * exists. */readDefinition(workdirFs: PluginFs, name: string): Promise<RepoAgentAttributes | null>;/** Remove a named agent's provider-specific files — its definition and any* legacy per-agent settings (workdir scope). The provider-neutral Switchdiff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.tsindex 167f49d43..d55f489b6 100644--- a/console/packages/core/src/agents/plugins/index.ts+++ b/console/packages/core/src/agents/plugins/index.ts@@ -37,6 +37,24 @@ const metadataSchema = z.object({description: z.string(),websiteUrl: z.string(),compatibleVersions: z.string().optional(),+ /**+ * What to tell someone to install, where the product name alone would be+ * ambiguous ("Cursor CLI" rather than the editor). Defaults to `name`.+ */+ cliLabel: z.string().optional(),+ /**+ * The Switch gateway's known-agent type for this provider, sent when an agent+ * registers. Must be a key the gateway's known-agent list accepts. Defaults to+ * `id`.+ */+ knownAgentType: z.string().optional(),+ /**+ * Whether starting a session may sign the CLI in — opening a browser when it+ * holds no usable token. Listing a provider's models starts a session, so+ * when this is set the app asks the read-only sign-in check first and lists+ * models only once that says signed in. Defaults to false.+ */+ sessionStartMaySignIn: z.boolean().optional(),});export type CLIAgentPluginMetadata = z.infer<typeof metadataSchema>;@@ -79,6 +97,8 @@ export {SWITCH_TOOL_RULES,} from './capabilities/repo-agents';export type {+ AdvancedSettingKind,+ AdvancedSettings,IRepoAgentsBehavior,LocalRepoAgent,RepoAgentAttributes,diff --git a/console/packages/plugins/src/agents/impl/antigravity/index.ts b/console/packages/plugins/src/agents/impl/antigravity/index.tsindex 6beee5466..db80ebb5e 100644--- a/console/packages/plugins/src/agents/impl/antigravity/index.ts+++ b/console/packages/plugins/src/agents/impl/antigravity/index.ts@@ -9,6 +9,8 @@ export const plugin = definePlugin(description:'Google Antigravity ACP with native authentication, approvals and persistent conversations.',websiteUrl: 'https://github.com/agentclientprotocol/registry/tree/main/antigravity-acp',+ cliLabel: 'Antigravity ACP',+ sessionStartMaySignIn: true,},{autoApprove: {diff --git a/console/packages/plugins/src/agents/impl/claude/index.ts b/console/packages/plugins/src/agents/impl/claude/index.tsindex a415321dc..9804a8b1c 100644--- a/console/packages/plugins/src/agents/impl/claude/index.ts+++ b/console/packages/plugins/src/agents/impl/claude/index.ts@@ -14,6 +14,7 @@ export const plugin = definePlugin(description:'CLI that uses Anthropic Claude for code edits, explanations, and structured refactors in the terminal.',websiteUrl: 'https://code.claude.com/docs/en/quickstart',+ knownAgentType: 'claude-code',},{autoApprove: {diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 773d86e88..aac2ac45b 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -274,12 +274,22 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {});});-describe('claudeRepoAgentsBehavior.attributeFields', () => {- it('declares name and description first, both required', () => {- const fields = claudeRepoAgentsBehavior.attributeFields();- expect(fields[0]).toMatchObject({ key: 'name', required: true, immutableOnEdit: true });- expect(fields[1]).toMatchObject({ key: 'description', required: true });- expect(fields.map((f) => f.key)).toContain('tools');+describe('claudeRepoAgentsBehavior.advancedSettings', () => {+ it('names the frontmatter it writes, without the main attributes', () => {+ const settings = claudeRepoAgentsBehavior.advancedSettings();+ expect(Object.keys(settings)).toEqual([+ 'tools',+ 'disallowedTools',+ 'permissionMode',+ 'color',+ 'maxTurns',+ 'background',+ 'isolation',+ 'effort',+ 'memory',+ ]);+ for (const main of ['name', 'description', 'model', 'instructions'])+ expect(settings).not.toHaveProperty(main);});});diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.ts b/console/packages/plugins/src/agents/impl/claude/subagents.tsindex 0c427a2f7..18e22e940 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.ts@@ -1,11 +1,12 @@import path from 'node:path';import {+ type AdvancedSettingKind,+ type AdvancedSettings,type IRepoAgentsBehavior,type LocalRepoAgent,type PluginFs,type RepoAgentAttributes,type RepoAgentDefinition,- type RepoAgentField,type RepoAgentLaunchDefinition,RECOGNISED_SWITCH_TOOL_RULES,SWITCH_AGENT_SETTINGS_DIR,@@ -54,130 +55,38 @@ const MD_SUFFIX = '.md';* instructions — so the key here is the canonical one, not `prompt`.*/const BODY_KEY = 'instructions';-const LIST_KEYS = new Set(['tools', 'disallowedTools']);-const NUMBER_KEYS = new Set(['maxTurns']);-const BOOLEAN_KEYS = new Set(['background']);--/** Attribute fields Claude Code subagents support, in form display order. The- * field keys match the `.claude/agents/<name>.md` frontmatter keys verbatim.- * The system prompt is not among them: it is the agent's `instructions`, a- * main attribute alongside name and description rather than an advanced- * setting. hooks / mcpServers / skills are intentionally omitted — they are- * nested/block-list YAML, edit the `.md` directly for those. */-const CLAUDE_SUBAGENT_FIELDS: RepoAgentField[] = [- {- key: 'name',- label: 'Name',- type: 'text',- required: true,- immutableOnEdit: true,- placeholder: 'code-reviewer',- help: "The subagent's identity (lowercase letters, digits, . _ -). Can't be changed later.",- },- {- key: 'description',- label: 'Description',- type: 'text',- required: true,- placeholder: 'Reviews diffs for correctness and style.',- help: 'When the parent should delegate to this subagent.',- },- {- key: 'model',- label: 'Model',- type: 'text',- placeholder: 'inherit',- help: 'inherit, an alias (sonnet, opus, haiku, fable), or a full model id. Empty = inherit.',- },- {- key: 'tools',- label: 'Tools',- type: 'list',- placeholder: 'Read, Grep, Bash',- help: 'Comma-separated allowlist. Empty inherits all tools. The Switch tools are always kept.',- },- {- key: 'disallowedTools',- label: 'Disallowed tools',- type: 'list',- placeholder: 'Write, Edit',- help: 'Comma-separated tools to deny from the inherited/allowed set.',- },- {- key: 'permissionMode',- label: 'Permission mode',- type: 'select',- options: [- { value: '', label: 'Default (inherit)' },- { value: 'default', label: 'default' },- { value: 'acceptEdits', label: 'acceptEdits' },- { value: 'auto', label: 'auto' },- { value: 'dontAsk', label: 'dontAsk' },- { value: 'bypassPermissions', label: 'bypassPermissions' },- { value: 'plan', label: 'plan' },- ],- },- {- key: 'color',- label: 'Color',- type: 'select',- options: [- { value: '', label: 'None' },- { value: 'red', label: 'red' },- { value: 'blue', label: 'blue' },- { value: 'green', label: 'green' },- { value: 'yellow', label: 'yellow' },- { value: 'purple', label: 'purple' },- { value: 'orange', label: 'orange' },- { value: 'pink', label: 'pink' },- { value: 'cyan', label: 'cyan' },- ],- },- { key: 'maxTurns', label: 'Max turns', type: 'number', placeholder: 'unlimited' },- {- key: 'background',- label: 'Always run in background',- type: 'boolean',- help: 'Run this subagent as a background task.',- },- {- key: 'isolation',- label: 'Isolation',- type: 'select',- options: [- { value: '', label: 'None' },- { value: 'worktree', label: 'worktree (isolated git copy)' },- ],- },- {- key: 'effort',- label: 'Effort',- type: 'select',- options: [- { value: '', label: 'Inherit' },- { value: 'low', label: 'low' },- { value: 'medium', label: 'medium' },- { value: 'high', label: 'high' },- { value: 'xhigh', label: 'xhigh' },- { value: 'max', label: 'max' },- ],- },- {- key: 'memory',- label: 'Persistent memory',- type: 'select',- options: [- { value: '', label: 'Off' },- { value: 'user', label: 'user' },- { value: 'project', label: 'project' },- { value: 'local', label: 'local' },- ],- },-];-const FRONTMATTER_FIELD_KEYS = CLAUDE_SUBAGENT_FIELDS.map((f) => f.key).filter(- (key) => key !== 'name' && key !== 'description' && key !== BODY_KEY-);+/**+ * The advanced settings a subagent definition carries, keyed by their+ * `.claude/agents/<name>.md` frontmatter keys verbatim, in the order they are+ * written. The server defines the fields a person fills them in with; these+ * are what this file writes. hooks / mcpServers / skills are intentionally+ * absent — they are nested/block-list YAML, edit the `.md` directly for those.+ */+const CLAUDE_ADVANCED_SETTINGS: AdvancedSettings = {+ tools: 'list',+ disallowedTools: 'list',+ permissionMode: 'text',+ color: 'text',+ maxTurns: 'number',+ background: 'boolean',+ isolation: 'text',+ effort: 'text',+ memory: 'text',+};++const keysOfKind = (kind: AdvancedSettingKind): Set<string> =>+ new Set(+ Object.entries(CLAUDE_ADVANCED_SETTINGS)+ .filter(([, settingKind]) => settingKind === kind)+ .map(([key]) => key)+ );+const LIST_KEYS = keysOfKind('list');+const NUMBER_KEYS = keysOfKind('number');+const BOOLEAN_KEYS = keysOfKind('boolean');++/** Frontmatter written after the name and description: the model, then the advanced settings. */+const FRONTMATTER_FIELD_KEYS = ['model', ...Object.keys(CLAUDE_ADVANCED_SETTINGS)];type SubagentFrontmatter = {name: string | null;@@ -531,8 +440,8 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return result;},- attributeFields(): RepoAgentField[] {- return CLAUDE_SUBAGENT_FIELDS;+ advancedSettings(): AdvancedSettings {+ return CLAUDE_ADVANCED_SETTINGS;},renderDefinition(attributes: RepoAgentAttributes): string {diff --git a/console/packages/plugins/src/agents/impl/codex/index.ts b/console/packages/plugins/src/agents/impl/codex/index.tsindex d0a3a3d8c..44692bd26 100644--- a/console/packages/plugins/src/agents/impl/codex/index.ts+++ b/console/packages/plugins/src/agents/impl/codex/index.ts@@ -7,7 +7,7 @@ import {} from '@switch-console/core/agents/plugins/helpers';import type { HostDependencyDescriptor, InstallOption } from '@switch-console/core/deps';import { icon } from './icon';-import { codexLaunchProfile, codexLaunchProfileFields, codexProfilePaths } from './profile';+import { codexLaunchProfile, codexLaunchProfileSettings, codexProfilePaths } from './profile';const CODEX_WINDOWS_INSTALL_SCRIPT ='powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"';@@ -133,6 +133,6 @@ export const provider = registerPluginBehavior(plugin, {// Switch Console's.launchProfile: codexLaunchProfile,launchProfilePaths: codexProfilePaths,- launchProfileFields: codexLaunchProfileFields,+ launchProfileSettings: codexLaunchProfileSettings,},});diff --git a/console/packages/plugins/src/agents/impl/codex/profile.test.ts b/console/packages/plugins/src/agents/impl/codex/profile.test.tsindex ac81f4e3a..82a07e08f 100644--- a/console/packages/plugins/src/agents/impl/codex/profile.test.ts+++ b/console/packages/plugins/src/agents/impl/codex/profile.test.ts@@ -3,11 +3,8 @@ import { describe, expect, it } from 'vitest';import {buildCodexProfileToml,CODEX_PROFILE_SETTING_KEYS,- CODEX_REASONING_EFFORTS,- CODEX_REASONING_SUMMARIES,- CODEX_VERBOSITY_LEVELS,codexLaunchProfile,- codexLaunchProfileFields,+ codexLaunchProfileSettings,codexProfileName,codexProfileRelativePath,} from './profile';@@ -155,10 +152,6 @@ describe('codexLaunchProfile', () => {// put `--profile <name>` on the command line, pointing at nothing.expect(codexLaunchProfile({ slug: 'a', workingDir: WD, values: {} })).toBeNull();});-- it('exposes the stable reasoning-effort levels', () => {- expect(CODEX_REASONING_EFFORTS).toEqual(['none', 'low', 'medium', 'high', 'xhigh', 'max']);- });});describe('codexProfileName', () => {@@ -197,34 +190,25 @@ describe('codexProfileName', () => {});});-describe('codexLaunchProfileFields', () => {+describe('codexLaunchProfileSettings', () => {it('declares exactly the advanced keys the profile builder consumes', () => {- expect(codexLaunchProfileFields().map((field) => field.key)).toEqual([- 'model',- 'effort',- 'verbosity',- 'reasoningSummary',- 'webSearch',- ]);+ expect(codexLaunchProfileSettings()).toEqual({+ effort: 'text',+ verbosity: 'text',+ reasoningSummary: 'text',+ webSearch: 'text',+ });});- it('does not offer instructions as an advanced setting', () => {- // Instructions are a main attribute of the agent, collected once for every- // provider. Offering them here too would be two boxes for one value.- expect(codexLaunchProfileFields().map((field) => field.key)).not.toContain('instructions');+ it('does not claim the model or instructions as advanced settings', () => {+ // Main attributes of the agent, collected once for every provider.+ expect(codexLaunchProfileSettings()).not.toHaveProperty('model');+ expect(codexLaunchProfileSettings()).not.toHaveProperty('instructions');// Still written into the profile, since Codex reads only its own file.+ expect(CODEX_PROFILE_SETTING_KEYS).toContain('model');expect(CODEX_PROFILE_SETTING_KEYS).toContain('instructions');});- it('offers every reasoning effort the profile accepts, plus an unset default', () => {- const effort = codexLaunchProfileFields().find((field) => field.key === 'effort');-- expect(effort?.options?.map((option) => option.value)).toEqual([- '',- ...CODEX_REASONING_EFFORTS,- ]);- });-it('writes every declared setting, so one cannot be collected and then dropped', () => {const filled = Object.fromEntries(CODEX_PROFILE_SETTING_KEYS.map((key) => [key, key === 'webSearch' ? 'true' : 'x'])@@ -243,16 +227,6 @@ describe('codexLaunchProfileFields', () => {expect((toml.tools as Record<string, unknown>).web_search).toBe(true);});- it('offers only the verbosity and summary values Codex accepts', () => {- const optionsFor = (key: string) =>- codexLaunchProfileFields()- .find((field) => field.key === key)- ?.options?.map((option) => option.value);-- expect(optionsFor('verbosity')).toEqual(['', ...CODEX_VERBOSITY_LEVELS]);- expect(optionsFor('reasoningSummary')).toEqual(['', ...CODEX_REASONING_SUMMARIES]);- });-it('turns web search off explicitly, which is not the same as leaving it unset', () => {const off = parseTOML(buildCodexProfileToml({ webSearch: 'false' }));expect((off.tools as Record<string, unknown>).web_search).toBe(false);diff --git a/console/packages/plugins/src/agents/impl/codex/profile.ts b/console/packages/plugins/src/agents/impl/codex/profile.tsindex ee2bfc96f..a6fb8f842 100644Binary files a/console/packages/plugins/src/agents/impl/codex/profile.ts and b/console/packages/plugins/src/agents/impl/codex/profile.ts differdiff --git a/console/packages/plugins/src/agents/impl/cursor/index.ts b/console/packages/plugins/src/agents/impl/cursor/index.tsindex 356c11a5f..dacac20ea 100644--- a/console/packages/plugins/src/agents/impl/cursor/index.ts+++ b/console/packages/plugins/src/agents/impl/cursor/index.ts@@ -10,8 +10,9 @@ export const plugin = definePlugin(id: 'cursor',name: 'Cursor',description:- "Cursor's agent CLI; provides editor-style, project-aware assistance from the shell.",+ "Cursor's agent CLI; provides editor-style, location-aware assistance from the shell.",websiteUrl: 'https://cursor.com/docs/cli/overview',+ cliLabel: 'Cursor CLI',},{autoApprove: {@@ -81,19 +82,7 @@ export const provider = registerPluginBehavior(plugin, {},mcp: {...cursorMcpAdapter(),- launchProfileFields: () => [- {- key: 'model',- label: 'Model',- type: 'text',- help: 'Blank uses the Cursor default on the execution machine.',- },- {- key: 'instructions',- label: 'Instructions',- type: 'textarea',- help: 'Additional instructions for SDK sessions.',- },- ],+ // Read at session start, and only the model and the instructions.+ launchProfileSettings: () => ({}),},});diff --git a/console/packages/plugins/src/agents/impl/opencode/index.ts b/console/packages/plugins/src/agents/impl/opencode/index.tsindex 724a4120a..0f3abf332 100644--- a/console/packages/plugins/src/agents/impl/opencode/index.ts+++ b/console/packages/plugins/src/agents/impl/opencode/index.ts@@ -8,7 +8,7 @@ import { icon } from './icon';import { opencodeLaunchProfileModels } from './models';import {opencodeLaunchProfile,- opencodeLaunchProfileFields,+ opencodeLaunchProfileSettings,opencodeProfilePaths,} from './profile';@@ -106,7 +106,7 @@ export const provider = registerPluginBehavior(plugin, {// session it starts.launchProfile: opencodeLaunchProfile,launchProfilePaths: opencodeProfilePaths,- launchProfileFields: opencodeLaunchProfileFields,+ launchProfileSettings: opencodeLaunchProfileSettings,// A variant is whatever the chosen model declares, so the only correct list// is the one the installed OpenCode reports. Asking also lets a typed model// be checked, which matters because OpenCode accepts an unknown one indiff --git a/console/packages/plugins/src/agents/impl/opencode/profile.test.ts b/console/packages/plugins/src/agents/impl/opencode/profile.test.tsindex d510b03c3..041d2b10d 100644--- a/console/packages/plugins/src/agents/impl/opencode/profile.test.ts+++ b/console/packages/plugins/src/agents/impl/opencode/profile.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';import {buildOpencodeConfig,opencodeLaunchProfile,- opencodeLaunchProfileFields,+ opencodeLaunchProfileSettings,opencodeProfileName,opencodeProfilePaths,} from './profile';@@ -20,63 +20,49 @@ function configOf(profile: NonNullable<ReturnType<typeof opencodeLaunchProfile>>return parse(file.content);}-describe('opencodeLaunchProfileFields', () => {+describe('opencodeLaunchProfileSettings', () => {it('declares exactly the advanced keys the config builder consumes', () => {- expect(opencodeLaunchProfileFields().map((field) => field.key)).toEqual([- 'model',- 'variant',- 'temperature',- 'topP',- 'maxSteps',- 'webSearch',- 'smallModel',- ]);+ expect(opencodeLaunchProfileSettings()).toEqual({+ variant: 'text',+ temperature: 'number',+ topP: 'number',+ maxSteps: 'number',+ webSearch: 'text',+ smallModel: 'text',+ });});- it('does not offer instructions as an advanced setting', () => {- // Instructions are a main attribute of the agent, collected once for every- // provider. Offering them here too would be two boxes for one value.- expect(opencodeLaunchProfileFields().map((field) => field.key)).not.toContain('instructions');+ it('does not claim the model or instructions as advanced settings', () => {+ // Main attributes of the agent, collected once for every provider.+ expect(opencodeLaunchProfileSettings()).not.toHaveProperty('model');+ expect(opencodeLaunchProfileSettings()).not.toHaveProperty('instructions');});- it('offers no Codex-only setting, which OpenCode has no key for', () => {+ it('claims no Codex-only setting, which OpenCode has no key for', () => {// Verbosity and reasoning summary exist for Codex and simply do not exist in- // OpenCode's config; offering them would collect a value that goes nowhere.- const keys = opencodeLaunchProfileFields().map((field) => field.key);+ // OpenCode's config; claiming them would accept a value that goes nowhere.+ const keys = Object.keys(opencodeLaunchProfileSettings());expect(keys).not.toContain('verbosity');expect(keys).not.toContain('reasoningSummary');expect(keys).not.toContain('effort');});- it('declares no fixed list of reasoning variants, because there is not one', () => {- // The accepted values come from the chosen model's own capabilities, so any- // list hardcoded here would be wrong for most models — and flatly empty for- // every local one.- const variant = opencodeLaunchProfileFields().find((field) => field.key === 'variant')!;- expect(variant.options).toBeUndefined();- });-- it('binds the variant to the model above, so the choices follow it', () => {- const variant = opencodeLaunchProfileFields().find((field) => field.key === 'variant')!;- expect(variant.catalogue).toEqual({ kind: 'model-variant', modelField: 'model' });- });-- it('binds both model fields to the host catalogue, so a typo can be caught', () => {- // OpenCode accepts a model it does not have without complaint and only fails- // when the agent tries to answer, so the check has to happen here.- for (const key of ['model', 'smallModel']) {- const field = opencodeLaunchProfileFields().find((f) => f.key === key)!;- expect(field.catalogue).toEqual({ kind: 'model' });- }- });-- it('names a field the variant can follow', () => {- // The renderer resolves the binding by key, so a rename that missed one side- // would silently leave the variant with no choices.- const fields = opencodeLaunchProfileFields();- const variant = fields.find((field) => field.key === 'variant')!;- const bound = variant.catalogue as { kind: string; modelField: string };- expect(fields.some((field) => field.key === bound.modelField)).toBe(true);+ it('writes every declared setting, so one cannot be accepted and then dropped', () => {+ const filled = Object.fromEntries(+ Object.entries(opencodeLaunchProfileSettings()).map(([key, kind]) => [+ key,+ kind === 'number' ? '1' : key === 'webSearch' ? 'true' : 'x',+ ])+ );+ const config = parse(buildOpencodeConfig(filled, null)!);+ expect(Object.keys(config.agent.build).sort()).toEqual([+ 'maxSteps',+ 'permission',+ 'temperature',+ 'top_p',+ 'variant',+ ]);+ expect(config.small_model).toBe('x');});});diff --git a/console/packages/plugins/src/agents/impl/opencode/profile.ts b/console/packages/plugins/src/agents/impl/opencode/profile.tsindex d819e5d99..87b3f5499 100644--- a/console/packages/plugins/src/agents/impl/opencode/profile.ts+++ b/console/packages/plugins/src/agents/impl/opencode/profile.ts@@ -1,5 +1,6 @@import type {- RepoAgentField,+ AdvancedSettingKind,+ AdvancedSettings,SwitchLaunchProfile,SwitchLaunchSpecialization,} from '@switch-console/core/agents/plugins';@@ -78,28 +79,26 @@ const ALLOW = 'allow';const DENY = 'deny';/**- * How each per-agent setting is collected and where it goes in the config.- *- * One declaration serves the form and the writer, so a new setting is one entry- * here rather than a field list and a writer that can disagree.+ * Where each per-agent setting goes in the config, by the key it is stored and+ * collected under. The fields a person fills them in with are the server's.** `path` is a dotted path, absent for a setting handled specially* (`instructions`, which is a file rather than a value). `scope` says what it is* relative to: the agent's own object (`agent.build.…`) for most, or the config- * root for the few OpenCode keys that have no per-agent form. Everything is- * collected as a string or a number, and blank means the key is omitted so the+ * root for the few OpenCode keys that have no per-agent form. Every value+ * reaches the writer as a string, and blank means the key is omitted so the* user's own `opencode.json` decides — which is not the same as writing a* default-looking value over it.*/type OpencodeSetting = {- field: RepoAgentField;+ key: string;/**- * True for a setting that is a main attribute of the agent rather than an- * advanced one. It is still rendered into the profile — OpenCode only reads- * its own files — but it is collected once, provider-agnostically, so it is- * not offered again in this provider's advanced form.+ * The shape of value the setting takes as an advanced setting, or null for a+ * main attribute of the agent (its model, its instructions). Those are still+ * rendered into the profile — OpenCode only reads its own files — but they+ * are collected once, provider-agnostically, rather than as advanced settings.*/- topLevel?: boolean;+ advanced: AdvancedSettingKind | null;path?: string;scope?: 'agent' | 'config';toValue?: (raw: string) => unknown;@@ -119,73 +118,14 @@ const numeric = (raw: string): unknown => {};const OPENCODE_SETTINGS: OpencodeSetting[] = [+ { key: 'model', advanced: null, path: 'model' },+ { key: 'variant', advanced: 'text', path: 'variant' },+ { key: 'temperature', advanced: 'number', path: 'temperature', toValue: numeric },+ { key: 'topP', advanced: 'number', path: 'top_p', toValue: numeric },+ { key: 'maxSteps', advanced: 'number', path: 'maxSteps', toValue: numeric },{- field: {- key: 'model',- label: 'Model',- type: 'text',- placeholder: 'e.g. anthropic/claude-sonnet-4-5 — blank uses the OpenCode default',- help: 'Overrides the model for this agent only, as provider/model. Includes a local model: define the provider once in your OpenCode config and an agent can run against it.',- catalogue: { kind: 'model' },- },- path: 'model',- },- {- field: {- key: 'variant',- label: 'Reasoning variant',- type: 'text',- placeholder: 'e.g. high — blank uses the model default',- help: "OpenCode's reasoning-effort control. Which values a model takes is the model's own business, so the choices follow the model above; most local models have none.",- catalogue: { kind: 'model-variant', modelField: 'model' },- },- path: 'variant',- },- {- field: {- key: 'temperature',- label: 'Temperature',- type: 'number',- placeholder: 'e.g. 0.2',- help: 'How much randomness the model is allowed. Blank leaves it to the model.',- },- path: 'temperature',- toValue: numeric,- },- {- field: {- key: 'topP',- label: 'Top-p',- type: 'number',- placeholder: 'e.g. 0.9',- help: 'Nucleus-sampling cutoff. Blank leaves it to the model.',- },- path: 'top_p',- toValue: numeric,- },- {- field: {- key: 'maxSteps',- label: 'Step limit',- type: 'number',- placeholder: 'e.g. 40',- help: 'How many tool-calling steps the agent may take before it has to answer.',- },- path: 'maxSteps',- toValue: numeric,- },- {- field: {- key: 'webSearch',- label: 'Web search',- type: 'select',- options: [- { value: '', label: 'Default' },- { value: 'true', label: 'On' },- { value: 'false', label: 'Off' },- ],- help: 'Whether this agent may search the web.',- },+ key: 'webSearch',+ advanced: 'text',// Web search is not a setting in OpenCode, it is a tool the agent is allowed// or denied. Written as a permission rather than under `tools`, which// OpenCode normalises into exactly this.@@ -193,35 +133,24 @@ const OPENCODE_SETTINGS: OpencodeSetting[] = [toValue: (raw) => (raw === 'true' ? ALLOW : DENY),},{- field: {- key: 'smallModel',- label: 'Utility model',- type: 'text',- placeholder: 'e.g. ollama/gemma4:latest — blank uses your OpenCode default',- help: 'The cheaper model OpenCode uses for background work like naming the conversation. Worth setting to match the model above when the point is to keep everything on one machine — otherwise that background work goes wherever your own config sends it.',- catalogue: { kind: 'model' },- },+ key: 'smallModel',+ advanced: 'text',path: 'small_model',// Top-level: OpenCode has no per-agent utility model, so this is the one// setting here that applies to the session rather than to the agent. The// config file is per-agent, so writing it at the root is still per-agent.scope: 'config',},- {- field: {- key: 'instructions',- label: 'Instructions',- type: 'textarea',- placeholder: "Extra guidance for this agent, e.g. 'You are a careful reviewer…'",- help: "Added to OpenCode's own instructions, the way an AGENTS.md is. Blank keeps OpenCode defaults.",- },- topLevel: true,- },+ { key: 'instructions', advanced: null },];-/** The fields the "advanced configuration" form renders for an OpenCode agent. */-export function opencodeLaunchProfileFields(): RepoAgentField[] {- return OPENCODE_SETTINGS.filter((setting) => !setting.topLevel).map((setting) => setting.field);+/** The advanced settings an OpenCode profile carries, beside the model and instructions. */+export function opencodeLaunchProfileSettings(): AdvancedSettings {+ return Object.fromEntries(+ OPENCODE_SETTINGS.flatMap((setting) =>+ setting.advanced ? [[setting.key, setting.advanced]] : []+ )+ );}/** Set a dotted path within an object, creating the intermediate objects. */@@ -267,7 +196,7 @@ export function buildOpencodeConfig(// containing a key it does not recognise, silently and whole.for (const setting of OPENCODE_SETTINGS) {if (!setting.path) continue;- const raw = values[setting.field.key];+ const raw = values[setting.key];if (typeof raw !== 'string' || raw.trim() === '') continue;const value = setting.toValue ? setting.toValue(raw.trim()) : raw.trim();diff --git a/console/packages/plugins/src/agents/plugin-registry.ts b/console/packages/plugins/src/agents/plugin-registry.tsindex 5ae5dd214..824d6cc4c 100644--- a/console/packages/plugins/src/agents/plugin-registry.ts+++ b/console/packages/plugins/src/agents/plugin-registry.ts@@ -11,6 +11,7 @@ import { provider as opencode } from './impl/opencode';export const pluginRegistry = createPluginRegistry<CLIAgentPluginProvider>();-for (const p of [antigravity, claude, codex, cursor, opencode]) {+// Registration order is the order the desktop app lists providers in.+for (const p of [codex, claude, antigravity, cursor, opencode]) {pluginRegistry.register(p);}diff --git a/console/packages/plugins/src/agents/session-launch.test.ts b/console/packages/plugins/src/agents/session-launch.test.tsindex 2b326f9c6..ec1be16a6 100644--- a/console/packages/plugins/src/agents/session-launch.test.ts+++ b/console/packages/plugins/src/agents/session-launch.test.ts@@ -1,8 +1,8 @@import { describe, expect, it } from 'vitest';import { SWITCH_SKILL_CONTEXT, SWITCH_SKILL_FILE } from '../switch-skill';import {- advancedConfigFields,advancedConfigProblem,+ advancedSettings,agentLaunchSources,sessionLaunchConfig,} from './session-launch';@@ -158,40 +158,40 @@ describe('agentLaunchSources', () => {});});-describe('advancedConfigFields', () => {- it('offers each provider’s own fields without the agent’s main attributes', () => {- expect(advancedConfigFields('claude').map((field) => field.key)).toEqual([- 'tools',- 'disallowedTools',- 'permissionMode',- 'color',- 'maxTurns',- 'background',- 'isolation',- 'effort',- 'memory',- ]);- expect(advancedConfigFields('codex').map((field) => field.key)).toEqual([- 'effort',- 'verbosity',- 'reasoningSummary',- 'webSearch',- ]);- expect(advancedConfigFields('opencode').map((field) => field.key)).toEqual([- 'variant',- 'temperature',- 'topP',- 'maxSteps',- 'webSearch',- 'smallModel',- ]);- expect(advancedConfigFields('cursor')).toEqual([]);- expect(advancedConfigFields('antigravity')).toEqual([]);+describe('advancedSettings', () => {+ it('lists the settings each provider applies, without the agent’s main attributes', () => {+ expect(advancedSettings('claude')).toEqual({+ tools: 'list',+ disallowedTools: 'list',+ permissionMode: 'text',+ color: 'text',+ maxTurns: 'number',+ background: 'boolean',+ isolation: 'text',+ effort: 'text',+ memory: 'text',+ });+ expect(advancedSettings('codex')).toEqual({+ effort: 'text',+ verbosity: 'text',+ reasoningSummary: 'text',+ webSearch: 'text',+ });+ expect(advancedSettings('opencode')).toEqual({+ variant: 'text',+ temperature: 'number',+ topP: 'number',+ maxSteps: 'number',+ webSearch: 'text',+ smallModel: 'text',+ });+ expect(advancedSettings('cursor')).toEqual({});+ expect(advancedSettings('antigravity')).toEqual({});});});describe('advancedConfigProblem', () => {- it('accepts values of each field’s type', () => {+ it('accepts values of the shape each setting is applied as', () => {expect(advancedConfigProblem('claude', {tools: ['Read'],@@ -202,17 +202,27 @@ describe('advancedConfigProblem', () => {).toBeNull();});- it('names a field the provider does not offer', () => {+ it('accepts an empty configuration for a provider that applies no settings', () => {+ expect(advancedConfigProblem('antigravity', {})).toBeNull();+ expect(advancedConfigProblem('cursor', {})).toBeNull();+ });++ it('names a field the provider does not apply', () => {expect(advancedConfigProblem('codex', { sandbox: 'workspace-write' })).toBe(- "The advanced configuration field 'sandbox' is not one codex offers."+ "The advanced configuration field 'sandbox' is not one this build applies for codex.");expect(advancedConfigProblem('cursor', { effort: 'high' })).toMatch(/'effort'/);+ expect(advancedConfigProblem('antigravity', { effort: 'high' })).toMatch(/'effort'/);});- it('names a field whose value is not of its type', () => {+ it('names a field whose value is not of the shape it is applied as', () => {expect(advancedConfigProblem('claude', { tools: 'Read' })).toMatch(/'tools'.*list/);+ expect(advancedConfigProblem('claude', { background: 'true' })).toMatch(/'background'/);expect(advancedConfigProblem('opencode', { temperature: '0.2' })).toMatch(/'temperature'/);- expect(advancedConfigProblem('codex', { effort: 'extreme' })).toMatch(/'effort'.*select/);- expect(advancedConfigProblem('codex', { effort: '' })).toMatch(/'effort'/);+ expect(advancedConfigProblem('codex', { effort: 3 })).toMatch(/'effort'.*text/);+ });++ it('leaves which values a field accepts to the server', () => {+ expect(advancedConfigProblem('codex', { effort: 'extreme' })).toBeNull();});});diff --git a/console/packages/plugins/src/agents/session-launch.ts b/console/packages/plugins/src/agents/session-launch.tsindex 62a350672..eb05a698b 100644--- a/console/packages/plugins/src/agents/session-launch.ts+++ b/console/packages/plugins/src/agents/session-launch.ts@@ -1,7 +1,8 @@import type {+ AdvancedSettingKind,+ AdvancedSettings,CLIAgentPluginProvider,RepoAgentAttributes,- RepoAgentField,RepoAgentLaunchDefinition,SwitchLaunchSpecialization,} from '@switch-console/core/agents/plugins';@@ -22,9 +23,6 @@ export type AdvancedConfigValue = string | number | boolean | string[];/** An agent's advanced configuration, keyed by its provider's field keys; unset fields are absent. */export type AdvancedConfig = Record<string, AdvancedConfigValue>;-/** Fields that are the agent's main attributes, collected outside its advanced configuration. */-const MAIN_ATTRIBUTE_KEYS = new Set(['name', 'description', 'model', 'instructions']);-function pluginFor(provider: string): CLIAgentPluginProvider {const plugin = pluginRegistry.get(provider);if (!plugin) throw new Error(`No plugin found for provider: ${provider}`);@@ -32,51 +30,44 @@ function pluginFor(provider: string): CLIAgentPluginProvider {}/**- * The advanced configuration fields a provider offers: the ones Console's- * advanced configuration form renders for it, from whichever surface the- * provider keeps them in, without the agent's main attributes. Empty for a- * provider with none.+ * The advanced settings a provider applies at launch, from whichever surface+ * the provider keeps them in. Empty for a provider that applies none. The+ * fields they are filled in with are the Switch server's.*/-export function advancedConfigFields(provider: string): RepoAgentField[] {+export function advancedSettings(provider: string): AdvancedSettings {const behavior = pluginFor(provider).behavior;- const fields =- behavior.repoAgents?.attributeFields() ?? behavior.mcp?.launchProfileFields?.() ?? [];- return fields.filter((field) => !MAIN_ATTRIBUTE_KEYS.has(field.key));+ return behavior.repoAgents?.advancedSettings() ?? behavior.mcp?.launchProfileSettings?.() ?? {};}-function valueFits(field: RepoAgentField, value: AdvancedConfigValue): boolean {- switch (field.type) {+function valueFits(kind: AdvancedSettingKind, value: AdvancedConfigValue): boolean {+ switch (kind) {case 'list':return Array.isArray(value) && value.every((item) => typeof item === 'string');case 'number':return typeof value === 'number' && Number.isFinite(value);case 'boolean':return typeof value === 'boolean';- case 'select':- return (- typeof value === 'string' &&- value !== '' &&- (field.options ?? []).some((option) => option.value === value)- );case 'text':- case 'textarea':return typeof value === 'string';}}/**- * What is wrong with an advanced configuration for a provider, naming the- * field, or null when every field is one the provider offers and holds a value- * of its type. A select's unset choice ("") is not a value: an unset field is- * left out.+ * What keeps an advanced configuration from being applied at launch, naming+ * the field, or null when the provider applies every field it holds, each+ * with a value of the shape it takes. A field the provider does not apply is+ * refused rather than dropped: a newer server may define one this build+ * cannot apply. Which values a field accepts is the server's to check, when+ * the configuration is written.*/export function advancedConfigProblem(provider: string, config: AdvancedConfig): string | null {- const fields = new Map(advancedConfigFields(provider).map((field) => [field.key, field]));+ const settings = advancedSettings(provider);for (const [key, value] of Object.entries(config)) {- const field = fields.get(key);- if (!field) return `The advanced configuration field '${key}' is not one ${provider} offers.`;- if (!valueFits(field, value))- return `The advanced configuration field '${key}' does not hold a valid ${field.type} value.`;+ const kind = settings[key];+ if (!kind)+ return `The advanced configuration field '${key}' is not one this build applies for ${provider}.`;+ if (!valueFits(kind, value))+ return `The advanced configuration field '${key}' does not hold a ${kind} value, the shape this build applies.`;}return null;}diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex a99236e6c..12836179f 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -121,7 +121,7 @@ from switch_core.budgets import BudgetExceededfrom switch_core.config import SwitchConfigfrom switch_core.db.models import Agent, Taskfrom switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.gateway.known_agents import known_agentfrom switch_core.observability.catalogue import AGENT_CONNECTIONS_REFUSEDfrom switch_core.observability.metrics import metricsfrom switch_core.trust.client import GuardrailBlockedError@@ -262,7 +262,7 @@ async def _register_known(Returns ``(agent_id, api_key)``. Shared by the single and bulkregister-known endpoints."""- spec = KNOWN_AGENTS.get(agent_type)+ spec = known_agent(agent_type)if spec is None:raise HTTPException(status_code=400,diff --git a/core/switch_core/bridges/agent/operations/agent_management.py b/core/switch_core/bridges/agent/operations/agent_management.pyindex cc66b0243..70ae6945e 100644--- a/core/switch_core/bridges/agent/operations/agent_management.py+++ b/core/switch_core/bridges/agent/operations/agent_management.py@@ -145,7 +145,9 @@ async def get_advanced_config(provider: str) -> list[dict[str, Any]]:the provider, the same "Advanced configuration" Switch Console offers.Args:- provider: "claude", "codex", "opencode", "antigravity" or "cursor".+ provider: A provider's id, as `list_machines` reports it, such as+ "claude" for Claude Code. An unknown id is refused with the ids+ Switch runs.Returns:A list of fields, each {key, label, type, help, placeholder, options,@@ -199,8 +201,9 @@ async def create_agent(machine: The machine's `id`, or its exact `name`, from`list_machines`. A name shared by several machines is refused withthe candidates listed; pass the id instead.- provider: The agent CLI to run: "claude" (Claude Code), "codex",- "opencode", "antigravity" or "cursor".+ provider: The agent CLI to run, by its id as `list_machines` reports+ it, such as "claude" for Claude Code. An unknown id is refused+ with the ids Switch runs.model: The model to run, or null for the provider's default.advanced_config: The provider's advanced settings, such as{"effort": "high"} for Claude Code or Codex, keyed by the fieldsdiff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 708ee3ebe..39a3b4d22 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -2167,7 +2167,8 @@ async def update_agent_detail(A managed agent (one `list_managed_agents` shows) only, and only with the"can manage agents" capability:- provider: "claude", "codex", "opencode", "antigravity" or "cursor".+ provider: A provider's id, as `list_machines` reports it, such as+ "claude" for Claude Code.model: The model to run; "" for the provider's default.advanced_config: The provider's advanced settings, replacing thecurrent ones whole, keyed by the fields `get_advanced_config`diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.pyindex 3f6e327f3..86ff8cfa1 100644--- a/core/switch_core/bridges/agent/protocol/agent_detail.py+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py@@ -32,7 +32,7 @@ from switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.gateway.known_agents import known_agentfrom switch_core.gateway.schemas import (AgentDetail,AgentModelSummary,@@ -341,7 +341,7 @@ async def apply_agent_options(md = dict(agent.metadata_) if isinstance(agent.metadata_, dict) else {}raw_agent_type = md.get("known_agent_type")agent_type = raw_agent_type if isinstance(raw_agent_type, str) else None- spec = KNOWN_AGENTS.get(agent_type) if agent_type else None+ spec = known_agent(agent_type) if agent_type else Noneif spec is None:raise AgentOptionsNotEditable("This agent has no known-agent type; options are not editable."diff --git a/core/switch_core/connections/loader.py b/core/switch_core/connections/loader.pyindex 9d6bcdd17..6b9807c12 100644--- a/core/switch_core/connections/loader.py+++ b/core/switch_core/connections/loader.py@@ -23,11 +23,6 @@ SKILL_PATH_RE = re.compile()FRONTMATTER_RE = re.compile(r"\A---\n(.*?)\n---\n", re.DOTALL)-# Hosts whose agent loads skills from a directory the hosted bootstrap can-# install into. Cursor and Antigravity have none, so a cloud agent on those-# providers gets connection credentials but no connection skills.-SKILL_PROVIDERS = frozenset({"claude", "codex", "opencode"})-class CatalogError(RuntimeError):passdiff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex 8e0b9474e..3e2c9e1fc 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -38,7 +38,7 @@ from switch_core.gateway.dependencies import (get_session,get_user_store,)-from switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.gateway.known_agents import known_agent, known_agentsfrom switch_core.gateway.schemas import (AgentDetail,AgentSummary,@@ -148,7 +148,7 @@ async def list_known_agent_types() -> list[KnownAgentType]:tool_count=len(spec.tools),options_schema=spec.options_schema.model_json_schema(),)- for key, spec in KNOWN_AGENTS.items()+ for key, spec in known_agents().items()]@@ -169,7 +169,7 @@ async def register_known_agent(user: Annotated[User, Depends(get_current_user)],protocol: Annotated[AgentCore, Depends(get_protocol)],) -> RegisterAgentResponse:- spec = KNOWN_AGENTS.get(req.agent_type)+ spec = known_agent(req.agent_type)if spec is None:raise HTTPException(status_code=400,@@ -233,7 +233,7 @@ async def register_known_subagents(inherit the parent's `channels_enabled` / `repo_dir` unless overridden in`options`."""- spec = KNOWN_AGENTS.get(req.agent_type)+ spec = known_agent(req.agent_type)if spec is None:raise HTTPException(status_code=400, detail=f"Unknown agent type: {req.agent_type}"diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex b81eb550b..1fa9447c1 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -53,6 +53,7 @@ from switch_core.gateway.messaging_installs import (from switch_core.gateway.oidc_routes import register_oidc_clientfrom switch_core.gateway.oidc_routes import router as oidc_routerfrom switch_core.gateway.packages import router as packages_router+from switch_core.gateway.providers import router as providers_routerfrom switch_core.gateway.references import router as references_routerfrom switch_core.gateway.room_groups import router as room_groups_routerfrom switch_core.gateway.room_links import router as room_links_router@@ -147,6 +148,7 @@ def create_gateway_app(tags=["provider-connections"],)app.include_router(connection_catalog_router, tags=["provider-connections"])+ app.include_router(providers_router, tags=["agent providers"])# authlib's OIDC client stores transient state/nonce/PKCE in the request# session across the IdP redirect round-trip; SameSite=Lax lets the cookiediff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.pyindex fcd284dcb..c6f4e464d 100644--- a/core/switch_core/gateway/known_agents.py+++ b/core/switch_core/gateway/known_agents.py@@ -12,6 +12,13 @@ from switch_core.bridges.agent.protocol.types import (TaskProtocolConfig,ToolSpec,)+from switch_core.providers.registry import (+ AgentProvider,+ ConsoleStart,+ TerminalStart,+ agent_provider,+ agent_providers,+)if TYPE_CHECKING:from switch_core.db.models import Agent@@ -49,29 +56,39 @@ class KnownAgentOptions(BaseModel):class KnownAgent(ABC):- """Pre-built agent definition for one-click registration.+ """Pre-built agent definition for one-click registration, for one provider.- Each subclass binds together: the connector type, the typed options schema- accepted at registration, and a `build_profile` classmethod that derives- the integration profile from validated options.+ Each subclass binds together the typed options schema accepted at+ registration and a `build_profile` method that derives the integration+ profile from validated options. The connector type and tools come from the+ provider's entry in `switch_core.providers.registry`."""- connector_type: ClassVar[str]options_schema: ClassVar[type[KnownAgentOptions]]- tools: ClassVar[list[ToolSpec]]- models: ClassVar[list[ModelSpec]]- @classmethod+ def __init__(self, provider: AgentProvider) -> None:+ self.provider = provider++ @property+ def connector_type(self) -> str:+ return self.provider.connector_type++ @property+ def tools(self) -> list[ToolSpec]:+ return list(self.provider.tools)++ @property+ def models(self) -> list[ModelSpec]:+ return []+@abstractmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile: ...+ def build_profile(self, options: KnownAgentOptions) -> IntegrationProfile: ...- @classmethod- def parse_options(cls, raw: dict[str, Any] | None) -> KnownAgentOptions:- return cls.options_schema.model_validate(raw or {})+ def parse_options(self, raw: dict[str, Any] | None) -> KnownAgentOptions:+ return self.options_schema.model_validate(raw or {})- @classmethoddef connect_command(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,@@ -90,9 +107,8 @@ class KnownAgent(ABC):"""return None- @classmethoddef start_session_instructions(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,@@ -188,26 +204,9 @@ class ClaudeCodeOptions(KnownAgentOptions):class ClaudeCodeKnownAgent(KnownAgent):- connector_type = "Claude Code"options_schema = ClaudeCodeOptions- tools = [- ToolSpec(name="Bash", description="Executes shell commands"),- ToolSpec(name="Edit", description="Makes targeted edits to files"),- ToolSpec(name="Write", description="Creates or overwrites files"),- ToolSpec(name="Read", description="Reads file contents"),- ToolSpec(name="Glob", description="Finds files by name pattern"),- ToolSpec(name="Grep", description="Searches file contents for patterns"),- ToolSpec(name="NotebookEdit", description="Modifies Jupyter notebook cells"),- ToolSpec(name="Agent", description="Spawns a subagent to handle a task"),- ToolSpec(name="WebFetch", description="Fetches and processes web content"),- ToolSpec(name="WebSearch", description="Performs web searches"),- ToolSpec(name="Monitor", description="Runs background watch commands"),- ToolSpec(name="Skill", description="Executes a skill"),- ]- models: ClassVar[list[ModelSpec]] = []- @classmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:+ def build_profile(self, options: KnownAgentOptions) -> IntegrationProfile:assert isinstance(options, ClaudeCodeOptions)if options.auto_session:connection_model = "auto_session"@@ -233,9 +232,8 @@ class ClaudeCodeKnownAgent(KnownAgent):),)- @classmethoddef connect_command(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,@@ -277,9 +275,8 @@ class ClaudeCodeKnownAgent(KnownAgent):)return f'cd {dir_token} && claude "{prompt}"{subagent_flags}{flag}'- @classmethoddef start_session_instructions(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,@@ -303,7 +300,7 @@ class ClaudeCodeKnownAgent(KnownAgent):sessions in genuinely different rooms instead."""assert isinstance(options, ClaudeCodeOptions)- cmd = cls.connect_command(options, agent, room_name, assume_role)+ cmd = self.connect_command(options, agent, room_name, assume_role)if not options.channels_enabled:# session_passive: reads asynchronously, so the operator must@@ -349,26 +346,25 @@ class ClaudeCodeKnownAgent(KnownAgent):)-class CodexOptions(KnownAgentOptions):+class GenericAgentOptions(KnownAgentOptions):auto_session: bool = False- """When True, the operator's connector (Switch Console) watches every room this- agent belongs to and auto-spawns a Codex session — connected to the room and+ """When True, the operator's connector (Switch Console) watches every room+ this agent belongs to and auto-spawns a session — connected to the room andwired to the agent's identity — the moment the agent is addressed in a room- where it has no live session. The registered profile becomes `auto_session`.- Codex has no plugin-channel of its own; Switch Console delivers inbound room- messages by injecting them into the session's terminal (CHOO-1436)."""+ where it has no live session. The registered profile becomes+ `auto_session`. These providers have no connector channel of their own;+ Switch Console delivers inbound room messages into the session itself."""repo_dir: str | None = None- """Absolute path to the directory the operator runs Codex from. Used to- generate a ready-to-paste `cd <repo_dir> && codex "connect to switch room …"`- command shown when the agent is addressed with no live session. None → a- `<codex-dir>` placeholder is shown instead."""+ """Absolute path to the directory the operator runs the agent from, used in+ the start command shown when the agent is addressed with no live session.+ None shows a `<provider-dir>` placeholder instead."""- # No `channels_enabled`: Switch Console sends it for every provider, but Codex- # has no connector channel of its own, so nothing here could act on it.+ # No `channels_enabled`: Switch Console sends it for every provider, but+ # only Claude Code has a connector channel that could act on it.# `KnownAgentOptions` ignores unknown keys, so the shared registration path- # still works — and the schema-driven gateway form does not render a control- # that silently does nothing.+ # still works — and the schema-driven gateway form does not render a+ # control that silently does nothing.@field_validator("repo_dir", mode="before")@classmethod@@ -378,169 +374,32 @@ class CodexOptions(KnownAgentOptions):return value-class CodexKnownAgent(KnownAgent):- connector_type = "Codex CLI"- options_schema = CodexOptions- tools = [- ToolSpec(name="Shell", description="Executes shell commands"),- ToolSpec(name="ApplyPatch", description="Applies patches to files"),- ToolSpec(name="Read", description="Reads file contents"),- ]- models: ClassVar[list[ModelSpec]] = []-- @classmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:- assert isinstance(options, CodexOptions)- # Switch Console watches + auto-spawns when auto_session; otherwise it keeps a- # session live and delivers messages by terminal injection, which is the- # session_addressable model. Codex does not report per-tool events or- # mediate tool calls (it runs auto-approved), so those lists stay empty —- # unlike Claude Code, whose PostToolUse hooks report tool activity.- connection_model = (- "auto_session" if options.auto_session else "session_addressable"- )- return IntegrationProfile(- connection_model=connection_model,- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=[],- task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),- # Same story as Claude Code: Codex is a TUI, so reset / compact /- # interrupt only work when Switch Console is driving the session and can- # inject keystrokes. A standalone `codex` can't be controlled, so all- # three resolve per live session via AgentRuntimeState.- command_capabilities=CommandCapabilities(- reset="session_dependent",- compact="session_dependent",- interrupt="session_dependent",- ),- )-- @classmethod- def connect_command(- cls,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- assume_role: str | None,- ) -> str | None:- assert isinstance(options, CodexOptions)- dir_token = options.repo_dir if options.repo_dir else "<codex-dir>"- prompt = connect_prompt(room_name, agent.name, assume_role, also_pull=False)- return f'cd "{dir_token}" && codex "{prompt}"'+class GenericKnownAgent(KnownAgent):+ """The known agent of every provider without one of its own: a CLI that+ Switch Console runs, delivering room messages into its session."""- @classmethod- def start_session_instructions(- cls,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- assume_role: str | None = None,- other_room_names: list[str] | None = None,- connected_not_live: bool = False,- ) -> str | None:- """Build the room-facing onboarding message for a Codex agent.-- Mirrors the Claude Code shape but emits a `codex "…"` command (never a- `claude` one) and omits Claude-specific flags. Codex sessions are normally- auto-managed by Switch Console, so this fallback is shown mainly when no- connector is watching.- """- assert isinstance(options, CodexOptions)- cmd = cls.connect_command(options, agent, room_name, assume_role)-- prefix = f"@{owner_handle}\n\n" if owner_handle else ""- if connected_not_live:- opening = (- "I have a session connected to this room, but it isn't reporting "- "as live, so I'm not receiving messages. Relaunch it, or start a "- "fresh session, with:"- )- elif other_room_names:- where = ", ".join(f"**{name}**" for name in other_room_names)- opening = (- f"I don't have a session connected to this room right now, but I "- f"do have other session(s) connected to {where}. Either ask me in "- "one of those rooms to come here, or start a new session connected "- "to this room — my operator should run:"- )- else:- opening = (- "I don't have a session connected to this room. To set up a new "- "session connected to this room, my operator should run:"- )- return (- f"{prefix}{opening}\n\n```\n{cmd}\n```\n\n(or start Codex manually and "- "ask me to connect to the room.)"- )---class OpenCodeOptions(KnownAgentOptions):- auto_session: bool = False- """When True, the operator's connector (Switch Console) watches every room this- agent belongs to and auto-spawns an OpenCode session — connected to the room- and wired to the agent's identity — the moment the agent is addressed in a- room where it has no live session. The registered profile becomes- `auto_session`. Like Codex, OpenCode has no connector channel of its own;- Switch Console delivers inbound room messages by injecting them into the- session's terminal."""-- repo_dir: str | None = None- """Absolute path to the directory the operator runs OpenCode from. Used to- generate a ready-to-paste `cd <repo_dir> && opencode --prompt "connect to- switch room …"` command shown when the agent is addressed with no live- session. None → an `<opencode-dir>` placeholder is shown instead."""+ options_schema = GenericAgentOptions- # No `channels_enabled`, for the same reason as Codex: Switch Console sends it- # for every provider, but OpenCode has no connector channel for it to act on.-- @field_validator("repo_dir", mode="before")- @classmethod- def _blank_string_to_none(cls, value: object) -> object:- if isinstance(value, str) and value.strip() == "":- return None- return value---class OpenCodeKnownAgent(KnownAgent):- connector_type = "OpenCode CLI"- options_schema = OpenCodeOptions- tools = [- ToolSpec(name="Bash", description="Executes shell commands"),- ToolSpec(name="Edit", description="Edits existing files"),- ToolSpec(name="Write", description="Writes new files"),- ToolSpec(name="Read", description="Reads file contents"),- ToolSpec(name="Grep", description="Searches file contents"),- ToolSpec(name="Glob", description="Finds files by pattern"),- ToolSpec(name="List", description="Lists directory contents"),- ToolSpec(name="WebFetch", description="Fetches web pages"),- ToolSpec(name="Task", description="Spawns a sub-agent"),- ]- models: ClassVar[list[ModelSpec]] = []-- @classmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:- assert isinstance(options, OpenCodeOptions)+ def build_profile(self, options: KnownAgentOptions) -> IntegrationProfile:+ assert isinstance(options, GenericAgentOptions)return IntegrationProfile(+ # Switch Console watches and auto-spawns when auto_session; otherwise+ # it keeps a session live and delivers messages into it, which is+ # the session_addressable model.connection_model=("auto_session" if options.auto_session else "session_addressable"),message_exchange=True,- # OpenCode's connector reports session and tool activity to Switch- # Console over its local hook port, which drives the session's status- # in the app. None of it reaches Switch as reported events, and- # nothing mediates a tool call before it runs, so both stay empty —- # the same position as Codex, and unlike Claude Code.+ # Tool activity, where a provider reports it, goes to Switch Console+ # to drive the session's status; none of it reaches Switch as+ # reported events, and nothing mediates a tool call before it runs.pre_invocation_mediation=[],post_invocation_mediation=[],event_reporting=[],task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),- # A TUI, so reset / compact / interrupt only work while Switch Console- # is driving the session and can write to it. A standalone `opencode`- # cannot be controlled, so all three resolve per live session via- # AgentRuntimeState.+ # Reset / compact / interrupt only work while Switch Console drives+ # the session; a standalone CLI cannot be controlled, so all three+ # resolve per live session via AgentRuntimeState.command_capabilities=CommandCapabilities(reset="session_dependent",compact="session_dependent",@@ -548,27 +407,25 @@ class OpenCodeKnownAgent(KnownAgent):),)- @classmethoddef connect_command(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,assume_role: str | None,) -> str | None:- """The prompt goes through `--prompt`, never as a positional argument:- OpenCode reads its first positional as the project directory, so a bare- `opencode "connect to switch room …"` is a request to open a directory- of that name rather than a prompt.- """- assert isinstance(options, OpenCodeOptions)- dir_token = options.repo_dir if options.repo_dir else "<opencode-dir>"+ assert isinstance(options, GenericAgentOptions)+ start = self.provider.session_start+ if not isinstance(start, TerminalStart):+ return None+ dir_token = (+ options.repo_dir if options.repo_dir else f"<{self.provider.id}-dir>"+ )prompt = connect_prompt(room_name, agent.name, assume_role, also_pull=False)- return f'cd "{dir_token}" && opencode --prompt "{prompt}"'+ return f'cd "{dir_token}" && ' + start.command.replace("{prompt}", prompt)- @classmethoddef start_session_instructions(- cls,+ self,options: KnownAgentOptions,agent: Agent,room_name: str,@@ -577,10 +434,15 @@ class OpenCodeKnownAgent(KnownAgent):other_room_names: list[str] | None = None,connected_not_live: bool = False,) -> str | None:- """Build the room-facing onboarding message for an OpenCode agent."""- assert isinstance(options, OpenCodeOptions)- cmd = cls.connect_command(options, agent, room_name, assume_role)-+ """Build the room-facing onboarding message: the start command for a+ provider started from a terminal, else how to start it from Switch+ Console. These sessions are normally auto-managed by Switch Console, so+ this is shown mainly when no connector is watching."""+ assert isinstance(options, GenericAgentOptions)+ start = self.provider.session_start+ if isinstance(start, ConsoleStart):+ return _console_start_instructions(start, agent, room_name, owner_handle)+ cmd = self.connect_command(options, agent, room_name, assume_role)prefix = f"@{owner_handle}\n\n" if owner_handle else ""if connected_not_live:opening = (@@ -602,154 +464,62 @@ class OpenCodeKnownAgent(KnownAgent):"session connected to this room, my operator should run:")return (- f"{prefix}{opening}\n\n```\n{cmd}\n```\n\n(or start OpenCode manually "- "and ask me to connect to the room.)"+ f"{prefix}{opening}\n\n```\n{cmd}\n```\n\n(or start "+ f"{self.provider.label} manually and ask me to connect to the room.)")-class AntigravityOptions(KnownAgentOptions):- auto_session: bool = False- repo_dir: str | None = None+def _console_start_instructions(+ start: ConsoleStart, agent: Agent, room_name: str, owner_handle: str | None+) -> str:+ prefix = f"{owner_handle} — " if owner_handle else ""+ runtime = (+ f", enable the {start.runtime} runtime in its advanced settings,"+ if start.runtime+ else ""+ )+ sign_in = (+ f" Sign in with `{start.sign_in_command}` first if you have not already."+ if start.sign_in_command+ else ""+ )+ return (+ f"{prefix}open **{agent.name}** in Switch Console{runtime} and start a "+ f"local session in **{room_name}**.{sign_in}"+ )- @field_validator("repo_dir", mode="before")- @classmethod- def _blank_string_to_none(cls, value: object) -> object:- return None if isinstance(value, str) and not value.strip() else value---class AntigravityKnownAgent(KnownAgent):- connector_type = "Antigravity CLI"- options_schema = AntigravityOptions- tools = [- ToolSpec(name="run_command", description="Executes shell commands"),- ToolSpec(name="write_to_file", description="Writes files"),- ToolSpec(name="replace_file_content", description="Edits existing files"),- ToolSpec(- name="multi_replace_file_content",- description="Applies several edits to one file",- ),- ToolSpec(name="view_file", description="Reads file contents"),- ToolSpec(name="grep_search", description="Searches file contents"),- ToolSpec(name="find_by_name", description="Finds files by pattern"),- ToolSpec(name="list_dir", description="Lists directory contents"),- ToolSpec(name="read_url_content", description="Fetches web pages"),- ToolSpec(name="search_web", description="Searches the web"),- ToolSpec(name="call_mcp_tool", description="Calls a tool on an MCP server"),- ToolSpec(name="invoke_subagent", description="Delegates to a subagent"),- ]- models: ClassVar[list[ModelSpec]] = []- @classmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:- assert isinstance(options, AntigravityOptions)- return IntegrationProfile(- connection_model="auto_session"- if options.auto_session- else "session_addressable",- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=[],- task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),- command_capabilities=CommandCapabilities(- reset="session_dependent",- compact="session_dependent",- interrupt="session_dependent",- ),- )+# Providers whose known agent is not the generic one, by `known_agent_type`.+_SPECIALISED: dict[str, type[KnownAgent]] = {"claude-code": ClaudeCodeKnownAgent}- @classmethod- def start_session_instructions(- cls,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- assume_role: str | None = None,- other_room_names: list[str] | None = None,- connected_not_live: bool = False,- ) -> str | None:- prefix = f"{owner_handle} — " if owner_handle else ""- return (- f"{prefix}open **{agent.name}** in Switch Console, enable the Antigravity CLI "- f"runtime in its advanced settings, and start a local session in **{room_name}**. "- "Sign in with `agy` first if you have not already."- )+def _known_agent_of(provider: AgentProvider) -> KnownAgent:+ return _SPECIALISED.get(provider.known_agent_type, GenericKnownAgent)(provider)-class CursorOptions(KnownAgentOptions):- auto_session: bool = False- repo_dir: str | None = None- @field_validator("repo_dir", mode="before")- @classmethod- def _blank_string_to_none(cls, value: object) -> object:- return None if isinstance(value, str) and not value.strip() else value---class CursorKnownAgent(KnownAgent):- connector_type = "Cursor CLI"- options_schema = CursorOptions- tools = [- ToolSpec(name="shell", description="Executes shell commands"),- ToolSpec(name="read_file", description="Reads file contents"),- ToolSpec(name="write", description="Writes files"),- ToolSpec(name="str_replace", description="Edits existing files"),- ToolSpec(name="grep", description="Searches file contents"),- ToolSpec(name="glob", description="Finds files by pattern"),- ]- models: ClassVar[list[ModelSpec]] = []+def known_agents() -> dict[str, KnownAgent]:+ """Every known-agent spec, one per provider, keyed by the+ `known_agent_type` an agent registered through it stores."""+ return {+ provider.known_agent_type: _known_agent_of(provider)+ for provider in agent_providers()+ }- @classmethod- def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:- assert isinstance(options, CursorOptions)- return IntegrationProfile(- connection_model="auto_session"- if options.auto_session- else "session_addressable",- message_exchange=True,- pre_invocation_mediation=[],- post_invocation_mediation=[],- event_reporting=[],- task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),- command_capabilities=CommandCapabilities(- reset="session_dependent",- compact="session_dependent",- interrupt="session_dependent",- ),- )- @classmethod- def start_session_instructions(- cls,- options: KnownAgentOptions,- agent: Agent,- room_name: str,- owner_handle: str | None,- assume_role: str | None = None,- other_room_names: list[str] | None = None,- connected_not_live: bool = False,- ) -> str | None:- prefix = f"{owner_handle} — " if owner_handle else ""- return (- f"{prefix}open **{agent.name}** in Switch Console, enable the Cursor CLI ACP "- f"runtime in its advanced settings, and start a local session in **{room_name}**. "- "Sign in with `agent` first if you have not already."- )+def known_agent(agent_type: str) -> KnownAgent | None:+ """The spec registered as `agent_type`, or None when there is none."""+ return known_agents().get(agent_type)-KNOWN_AGENTS: dict[str, type[KnownAgent]] = {- "claude-code": ClaudeCodeKnownAgent,- "codex": CodexKnownAgent,- "opencode": OpenCodeKnownAgent,- "antigravity": AntigravityKnownAgent,- "cursor": CursorKnownAgent,-}+def provider_known_agent(provider_id: str) -> KnownAgent:+ """The spec agents of `provider_id` register through. Raises+ UnknownProvider for a provider Switch does not run."""+ return _known_agent_of(agent_provider(provider_id))def known_agent_for(agent: Agent,-) -> tuple[type[KnownAgent], KnownAgentOptions] | None:+) -> tuple[KnownAgent, KnownAgentOptions] | None:"""Resolve the KnownAgent spec and parsed options for a registered Agent.Returns None when the agent was not registered via `/agents/register`@@ -757,7 +527,7 @@ def known_agent_for("""md = agent.metadata_ if isinstance(agent.metadata_, dict) else {}agent_type = md.get("known_agent_type")- spec = KNOWN_AGENTS.get(agent_type) if isinstance(agent_type, str) else None+ spec = known_agent(agent_type) if isinstance(agent_type, str) else Noneif spec is None:return Noneoptions = spec.parse_options(md.get("known_agent_options"))diff --git a/core/switch_core/gateway/providers.py b/core/switch_core/gateway/providers.pynew file mode 100644index 000000000..70c1620f2--- /dev/null+++ b/core/switch_core/gateway/providers.py@@ -0,0 +1,33 @@+"""The provider list and each provider's advanced-configuration fields,+mounted at `/management` beside the agent-management routes but served+whether or not agent management is on: Switch Console builds the+advanced-configuration form of every agent from them, the ones it runs+itself as well as managed ones."""++from __future__ import annotations++from typing import Annotated, Any++from fastapi import APIRouter, Depends++from switch_core.db.models import User+from switch_core.gateway.auth import get_current_user+from switch_core.providers.schema import advanced_config_schema, providers_schema++router = APIRouter(prefix="/management")++CurrentUser = Annotated[User, Depends(get_current_user)]++[email protected]("/providers")+async def list_providers(user: CurrentUser) -> dict[str, Any]:+ """Every provider a definition can name, each with its label and its+ advanced-configuration fields, in the order a client offers them."""+ return providers_schema()++[email protected]("/advanced-config")+async def get_advanced_config(user: CurrentUser) -> dict[str, Any]:+ """Each provider's advanced-configuration fields, which a definition's+ `advanced_config` is checked against."""+ return advanced_config_schema()diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 550289666..0708384db 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -252,7 +252,7 @@ class AgentSummary(BaseModel):# under the user's main agent). The UI nests children under their parent.parent_agent_id: str | None = None# `known_agent_type` is set when this agent was registered via- # `/agents/register` with one of the KNOWN_AGENTS specs (e.g. "claude-code").+ # `/agents/register` with one of the `known_agents()` specs (e.g. "claude-code").# `known_agent_options` is the last validated options payload. Together# they let the UI render an "edit options" form against the spec's schema.known_agent_type: str | None = Nonediff --git a/core/switch_core/management/advanced_config.py b/core/switch_core/management/advanced_config.pyindex 647d4f973..2eb051b70 100644--- a/core/switch_core/management/advanced_config.py+++ b/core/switch_core/management/advanced_config.py@@ -1,27 +1,24 @@-"""Each provider's "Advanced configuration": the settings a managed agent may carry.+"""How a definition's "Advanced configuration" is checked.-The one schema per provider, owned here: every definition is checked against-it whatever machine runs the agent, and `GET /gateway/management/advanced-config`-and the `get_advanced_config` agent operation serve it so a client can build its-form from it. The fields, labels and help mirror the advanced forms Switch-Console offers for its own agents (Claude Code's subagent fields, the Codex-profile and OpenCode settings in `console/packages/plugins`).--`model` and the instructions are not here: they are top-level definition fields.+The fields each provider takes are declared with the provider, in+`switch_core.providers.registry` (`switch_core.providers.advanced_fields` holds+the field model): every definition is checked against them whatever machine+runs the agent. `switch_core.providers.schema` serves them, at+`GET /gateway/management/providers` and `GET /gateway/management/advanced-config`,+and the `get_advanced_config` agent operation, so a client can build its form+from them.An advanced config is a JSON object keyed by field. A field that is not set is-left out, never sent as null, "" or []. A `select` field's served options start-with `{"value": "", "label": <unset label>}`, the choice a form shows for-"leave it unset"; "" is not a value it accepts.+left out, never sent as null, "" or []."""from __future__ import annotationsimport math-from dataclasses import dataclass-from typing import Any, Literal+from typing import Any-FieldType = Literal["text", "textarea", "number", "boolean", "list", "select"]+from switch_core.providers.advanced_fields import AdvancedField+from switch_core.providers.registry import agent_providerMAX_KEYS = 32MAX_STRING_CHARS = 4096@@ -29,258 +26,10 @@ MAX_LIST_ITEMS = 64MAX_LIST_ITEM_CHARS = 256-@dataclass(frozen=True)-class Option:- value: str- label: str---@dataclass(frozen=True)-class Catalogue:- """Where a form can offer choices for a free-text field: `model` for the- provider's models, `model-variant` for the variants of the model named in- `model_field`."""-- kind: Literal["model", "model-variant"]- model_field: str | None---@dataclass(frozen=True)-class AdvancedField:- key: str- label: str- type: FieldType- help: str | None- placeholder: str | None- # A select's choices, the unset choice ("") first.- options: tuple[Option, ...] | None- catalogue: Catalogue | None-- def accepted_values(self) -> list[str]:- return [option.value for option in self.options or () if option.value != ""]-- def wire(self) -> dict[str, Any]:- catalogue: dict[str, Any] | None = None- if self.catalogue is not None:- catalogue = {"kind": self.catalogue.kind}- if self.catalogue.model_field is not None:- catalogue["model_field"] = self.catalogue.model_field- return {- "key": self.key,- "label": self.label,- "type": self.type,- "help": self.help,- "placeholder": self.placeholder,- "options": None- if self.options is None- else [- {"value": option.value, "label": option.label}- for option in self.options- ],- "catalogue": catalogue,- }---def _field(- key: str,- label: str,- type: FieldType,- *,- help: str | None = None,- placeholder: str | None = None,- catalogue: Catalogue | None = None,-) -> AdvancedField:- return AdvancedField(- key=key,- label=label,- type=type,- help=help,- placeholder=placeholder,- options=None,- catalogue=catalogue,- )---def _select(- key: str,- label: str,- unset: str,- values: list[str] | list[tuple[str, str]],- *,- help: str | None = None,-) -> AdvancedField:- """A select whose values are labelled by themselves unless given as- (value, label) pairs."""- options = [Option(value="", label=unset)]- for value in values:- if isinstance(value, tuple):- options.append(Option(value=value[0], label=value[1]))- else:- options.append(Option(value=value, label=value))- return AdvancedField(- key=key,- label=label,- type="select",- help=help,- placeholder=None,- options=tuple(options),- catalogue=None,- )---_ON_OFF = [("true", "On"), ("false", "Off")]--CLAUDE_FIELDS: tuple[AdvancedField, ...] = (- _field(- "tools",- "Tools",- "list",- placeholder="Read, Grep, Bash",- help="Comma-separated allowlist. Empty inherits all tools. The Switch tools are always kept.",- ),- _field(- "disallowedTools",- "Disallowed tools",- "list",- placeholder="Write, Edit",- help="Comma-separated tools to deny from the inherited/allowed set.",- ),- _select(- "permissionMode",- "Permission mode",- "Default (inherit)",- ["default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan"],- ),- _select(- "color",- "Color",- "None",- ["red", "blue", "green", "yellow", "purple", "orange", "pink", "cyan"],- ),- _field("maxTurns", "Max turns", "number", placeholder="unlimited"),- _field(- "background",- "Always run in background",- "boolean",- help="Run this subagent as a background task.",- ),- _select(- "isolation",- "Isolation",- "None",- [("worktree", "worktree (isolated git copy)")],- ),- _select("effort", "Effort", "Inherit", ["low", "medium", "high", "xhigh", "max"]),- _select("memory", "Persistent memory", "Off", ["user", "project", "local"]),-)--CODEX_FIELDS: tuple[AdvancedField, ...] = (- _select(- "effort",- "Reasoning effort",- "Default",- ["none", "low", "medium", "high", "xhigh", "max"],- help="How hard the model thinks before answering. `none` disables reasoning.",- ),- _select(- "verbosity",- "Verbosity",- "Default",- ["low", "medium", "high"],- help="How much prose the model writes in its answers.",- ),- _select(- "reasoningSummary",- "Reasoning summary",- "Default",- ["auto", "concise", "detailed", "none"],- help="How much of the model's thinking is summarised back as it works.",- ),- _select(- "webSearch",- "Web search",- "Default",- _ON_OFF,- help="Whether this agent may search the web.",- ),-)--OPENCODE_FIELDS: tuple[AdvancedField, ...] = (- _field(- "variant",- "Reasoning variant",- "text",- placeholder="e.g. high — blank uses the model default",- help="OpenCode's reasoning-effort control. Which values a model takes is the model's own business, so the choices follow the model above; most local models have none.",- catalogue=Catalogue(kind="model-variant", model_field="model"),- ),- _field(- "temperature",- "Temperature",- "number",- placeholder="e.g. 0.2",- help="How much randomness the model is allowed. Blank leaves it to the model.",- ),- _field(- "topP",- "Top-p",- "number",- placeholder="e.g. 0.9",- help="Nucleus-sampling cutoff. Blank leaves it to the model.",- ),- _field(- "maxSteps",- "Step limit",- "number",- placeholder="e.g. 40",- help="How many tool-calling steps the agent may take before it has to answer.",- ),- _select(- "webSearch",- "Web search",- "Default",- _ON_OFF,- help="Whether this agent may search the web.",- ),- _field(- "smallModel",- "Utility model",- "text",- placeholder="e.g. ollama/gemma4:latest — blank uses your OpenCode default",- help="The cheaper model OpenCode uses for background work like naming the conversation. Worth setting to match the model above when the point is to keep everything on one machine — otherwise that background work goes wherever your own config sends it.",- catalogue=Catalogue(kind="model", model_field=None),- ),-)--# Keyed by every provider a definition can name (`schemas.Provider`).-ADVANCED_FIELDS: dict[str, tuple[AdvancedField, ...]] = {- "claude": CLAUDE_FIELDS,- "codex": CODEX_FIELDS,- "opencode": OPENCODE_FIELDS,- "cursor": (),- "antigravity": (),-}--def provider_fields(provider: str) -> list[dict[str, Any]]:"""The provider's fields as served. Raises ValueError for a providerSwitch does not run."""- if provider not in ADVANCED_FIELDS:- raise ValueError(- f"unknown provider {provider!r}; one of {', '.join(ADVANCED_FIELDS)}"- )- return [field.wire() for field in ADVANCED_FIELDS[provider]]---def advanced_config_schema() -> dict[str, Any]:- """Every provider's fields, as `GET /gateway/management/advanced-config`- serves them."""- return {- "providers": {- provider: {"fields": provider_fields(provider)}- for provider in ADVANCED_FIELDS- }- }+ return [field.wire() for field in agent_provider(provider).advanced_fields]def _value_problem(field: AdvancedField, value: Any) -> str | None:@@ -323,11 +72,9 @@ def _value_problem(field: AdvancedField, value: Any) -> str | None:def validate_advanced_config(provider: str, config: dict[str, Any]) -> None:"""Raise ValueError naming every field of `config` that `provider` doesnot take, or takes in another form."""- if provider not in ADVANCED_FIELDS:- raise ValueError(f"unknown provider {provider!r}")+ fields = {field.key: field for field in agent_provider(provider).advanced_fields}if len(config) > MAX_KEYS:raise ValueError(f"advanced_config takes at most {MAX_KEYS} fields")- fields = {field.key: field for field in ADVANCED_FIELDS[provider]}problems = []for key, value in config.items():field = fields.get(key)diff --git a/core/switch_core/management/gateway_routes.py b/core/switch_core/management/gateway_routes.pyindex 2989afd44..4c8513405 100644--- a/core/switch_core/management/gateway_routes.py+++ b/core/switch_core/management/gateway_routes.py@@ -19,7 +19,6 @@ from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.db.models import User, require_tenant_idfrom switch_core.gateway.auth import get_current_userfrom switch_core.gateway.dependencies import get_protocol, get_session-from switch_core.management.advanced_config import advanced_config_schemafrom switch_core.management.dependencies import get_managementfrom switch_core.management.errors import ManagementRoutefrom switch_core.management.schemas import (@@ -158,13 +157,6 @@ async def withdraw_sealed_login(return {"ok": True}[email protected]("/advanced-config")-async def get_advanced_config(user: CurrentUser) -> dict[str, Any]:- """Each provider's advanced-configuration fields, which a definition's- `advanced_config` is checked against."""- return advanced_config_schema()--@router.get("/agents")async def list_managed_agents(session: Session, user: CurrentUser, management: Managementdiff --git a/core/switch_core/management/schemas.py b/core/switch_core/management/schemas.pyindex ffc955776..f05a80ae5 100644--- a/core/switch_core/management/schemas.py+++ b/core/switch_core/management/schemas.py@@ -29,21 +29,13 @@ from switch_core.db.models import AgentDefinition as AgentDefinitionRowfrom switch_core.management.advanced_config import validate_advanced_configfrom switch_core.management.process_lease import ProcessLeasesfrom switch_core.management.sealed_logins import PublicKey, key_id+from switch_core.providers.registry import AgentProviderId-Provider = Literal["claude", "codex", "opencode", "antigravity", "cursor"]+Provider = AgentProviderIdControllerKind = Literal["console", "daemon", "ec2"]DesiredState = Literal["running", "stopped"]Isolation = Literal["shared", "isolated"]-# The known-agent spec each provider registers through.-PROVIDER_KNOWN_AGENT_TYPES: dict[str, str] = {- "claude": "claude-code",- "codex": "codex",- "opencode": "opencode",- "antigravity": "antigravity",- "cursor": "cursor",-}-MAX_INSTRUCTIONS_BYTES = 32 * 1024MAX_CONTROLLER_NAME_CHARS = 200MAX_CONTROLLER_DESCRIPTION_CHARS = 500diff --git a/core/switch_core/management/service.py b/core/switch_core/management/service.pyindex e6239b0fa..000ba9df8 100644--- a/core/switch_core/management/service.py+++ b/core/switch_core/management/service.py@@ -66,7 +66,7 @@ from switch_core.gateway.cloud_controllers import (record_controller_status,wake_controller_machine,)-from switch_core.gateway.known_agents import KNOWN_AGENTS, KnownAgent+from switch_core.gateway.known_agents import KnownAgent, provider_known_agentfrom switch_core.management import reason_codes, tokensfrom switch_core.management.errors import ManagementError, not_foundfrom switch_core.management.notifier import ControllerNotifier@@ -78,7 +78,6 @@ from switch_core.management.placement import ()from switch_core.management.process_lease import ProcessLeases, read_leasesfrom switch_core.management.schemas import (- PROVIDER_KNOWN_AGENT_TYPES,ControllerDescription,CreateManagedAgentRequest,DefinitionV1,@@ -92,6 +91,7 @@ from switch_core.management.schemas import (workspaces_dir_of,)from switch_core.management.sealed_logins import PublicKey, SealedLogin, key_id+from switch_core.providers.registry import provider_idslogger = logging.getLogger(__name__)@@ -907,12 +907,12 @@ class ManagementService:controller_id: str,provider: str,) -> AgentController:- if provider not in PROVIDER_KNOWN_AGENT_TYPES:+ if provider not in provider_ids():raise ManagementError(422,reason_codes.VALIDATION_ERROR,f"Unknown provider {provider!r}; one of "- f"{', '.join(sorted(PROVIDER_KNOWN_AGENT_TYPES))}.",+ f"{', '.join(sorted(provider_ids()))}.",)controller = await self.owned_controller(session, tenant_id, owner_id, controller_id@@ -1389,14 +1389,14 @@ class ManagementService:provider = params.get("provider")if (agent_id is not None- or provider not in PROVIDER_KNOWN_AGENT_TYPES+ or provider not in provider_ids()or set(params) != {"provider"}):raise ManagementError(422,reason_codes.VALIDATION_ERROR,"provider.recheck takes no agent_id and params.provider naming "- f"one of {', '.join(sorted(PROVIDER_KNOWN_AGENT_TYPES))}.",+ f"one of {', '.join(sorted(provider_ids()))}.",)operation = await self.operations.create(session,@@ -1490,14 +1490,15 @@ def with_directory(def _known_agent_registration(definition: DefinitionV1, existing_metadata: dict[str, Any] | None-) -> tuple[type[KnownAgent], Any, dict[str, Any]]:+) -> tuple[KnownAgent, Any, dict[str, Any]]:"""The known-agent spec, options and metadata a definition registers with.Options the definition does not speak to (Claude Code's `channels_enabled`,say) keep whatever the agent already had. An agent already registered asa different known type is refused rather than silently converted."""- known_type = PROVIDER_KNOWN_AGENT_TYPES[definition.provider]+ spec = provider_known_agent(definition.provider)+ known_type = spec.provider.known_agent_typemetadata = dict(existing_metadata) if isinstance(existing_metadata, dict) else {}current_type = metadata.get("known_agent_type")if current_type is not None and current_type != known_type:@@ -1507,7 +1508,6 @@ def _known_agent_registration(f"This agent is registered as {current_type!r}, which does not run "f"provider {definition.provider!r}.",)- spec = KNOWN_AGENTS[known_type]current_options = metadata.get("known_agent_options")raw_options = dict(current_options) if isinstance(current_options, dict) else {}raw_options["auto_session"] = Truediff --git a/core/switch_core/providers/advanced_fields.py b/core/switch_core/providers/advanced_fields.pynew file mode 100644index 000000000..f3bda71a4--- /dev/null+++ b/core/switch_core/providers/advanced_fields.py@@ -0,0 +1,245 @@+"""The settings a managed agent of each provider may carry, its "Advanced configuration".++Each field is a key, a label and a type a client can build a form from. These+are the only definitions of them: Switch Console builds the advanced form of+every agent, its own and managed ones, from what the server serves, and its+provider plugins only apply the values, by key, when a session launches. Each+provider in `switch_core.providers.registry` names its fields; a provider with+none has an empty tuple.++`model` and the instructions are not here: they are top-level definition fields.+A `select` field's served options start with `{"value": "", "label": <unset+label>}`, the choice a form shows for "leave it unset"; "" is not a value it+accepts.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++FieldType = Literal["text", "textarea", "number", "boolean", "list", "select"]+++@dataclass(frozen=True)+class Option:+ value: str+ label: str+++@dataclass(frozen=True)+class Catalogue:+ """Where a form can offer choices for a free-text field: `model` for the+ provider's models, `model-variant` for the variants of the model named in+ `model_field`."""++ kind: Literal["model", "model-variant"]+ model_field: str | None+++@dataclass(frozen=True)+class AdvancedField:+ key: str+ label: str+ type: FieldType+ help: str | None+ placeholder: str | None+ # A select's choices, the unset choice ("") first.+ options: tuple[Option, ...] | None+ catalogue: Catalogue | None++ def accepted_values(self) -> list[str]:+ return [option.value for option in self.options or () if option.value != ""]++ def wire(self) -> dict[str, Any]:+ catalogue: dict[str, Any] | None = None+ if self.catalogue is not None:+ catalogue = {"kind": self.catalogue.kind}+ if self.catalogue.model_field is not None:+ catalogue["model_field"] = self.catalogue.model_field+ return {+ "key": self.key,+ "label": self.label,+ "type": self.type,+ "help": self.help,+ "placeholder": self.placeholder,+ "options": None+ if self.options is None+ else [+ {"value": option.value, "label": option.label}+ for option in self.options+ ],+ "catalogue": catalogue,+ }+++def _field(+ key: str,+ label: str,+ type: FieldType,+ *,+ help: str | None = None,+ placeholder: str | None = None,+ catalogue: Catalogue | None = None,+) -> AdvancedField:+ return AdvancedField(+ key=key,+ label=label,+ type=type,+ help=help,+ placeholder=placeholder,+ options=None,+ catalogue=catalogue,+ )+++def _select(+ key: str,+ label: str,+ unset: str,+ values: list[str] | list[tuple[str, str]],+ *,+ help: str | None = None,+) -> AdvancedField:+ """A select whose values are labelled by themselves unless given as+ (value, label) pairs."""+ options = [Option(value="", label=unset)]+ for value in values:+ if isinstance(value, tuple):+ options.append(Option(value=value[0], label=value[1]))+ else:+ options.append(Option(value=value, label=value))+ return AdvancedField(+ key=key,+ label=label,+ type="select",+ help=help,+ placeholder=None,+ options=tuple(options),+ catalogue=None,+ )+++_ON_OFF = [("true", "On"), ("false", "Off")]++CLAUDE_FIELDS: tuple[AdvancedField, ...] = (+ _field(+ "tools",+ "Tools",+ "list",+ placeholder="Read, Grep, Bash",+ help="Comma-separated allowlist. Empty inherits all tools. The Switch tools are always kept.",+ ),+ _field(+ "disallowedTools",+ "Disallowed tools",+ "list",+ placeholder="Write, Edit",+ help="Comma-separated tools to deny from the inherited/allowed set.",+ ),+ _select(+ "permissionMode",+ "Permission mode",+ "Default (inherit)",+ ["default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan"],+ ),+ _select(+ "color",+ "Color",+ "None",+ ["red", "blue", "green", "yellow", "purple", "orange", "pink", "cyan"],+ ),+ _field("maxTurns", "Max turns", "number", placeholder="unlimited"),+ _field(+ "background",+ "Always run in background",+ "boolean",+ help="Run this subagent as a background task.",+ ),+ _select(+ "isolation",+ "Isolation",+ "None",+ [("worktree", "worktree (isolated git copy)")],+ ),+ _select("effort", "Effort", "Inherit", ["low", "medium", "high", "xhigh", "max"]),+ _select("memory", "Persistent memory", "Off", ["user", "project", "local"]),+)++CODEX_FIELDS: tuple[AdvancedField, ...] = (+ _select(+ "effort",+ "Reasoning effort",+ "Default",+ ["none", "low", "medium", "high", "xhigh", "max"],+ help="How hard the model thinks before answering. `none` disables reasoning.",+ ),+ _select(+ "verbosity",+ "Verbosity",+ "Default",+ ["low", "medium", "high"],+ help="How much prose the model writes in its answers.",+ ),+ _select(+ "reasoningSummary",+ "Reasoning summary",+ "Default",+ ["auto", "concise", "detailed", "none"],+ help="How much of the model's thinking is summarised back as it works.",+ ),+ _select(+ "webSearch",+ "Web search",+ "Default",+ _ON_OFF,+ help="Whether this agent may search the web.",+ ),+)++OPENCODE_FIELDS: tuple[AdvancedField, ...] = (+ _field(+ "variant",+ "Reasoning variant",+ "text",+ placeholder="e.g. high — blank uses the model default",+ help="OpenCode's reasoning-effort control. Which values a model takes is the model's own business, so the choices follow the model above; most local models have none.",+ catalogue=Catalogue(kind="model-variant", model_field="model"),+ ),+ _field(+ "temperature",+ "Temperature",+ "number",+ placeholder="e.g. 0.2",+ help="How much randomness the model is allowed. Blank leaves it to the model.",+ ),+ _field(+ "topP",+ "Top-p",+ "number",+ placeholder="e.g. 0.9",+ help="Nucleus-sampling cutoff. Blank leaves it to the model.",+ ),+ _field(+ "maxSteps",+ "Step limit",+ "number",+ placeholder="e.g. 40",+ help="How many tool-calling steps the agent may take before it has to answer.",+ ),+ _select(+ "webSearch",+ "Web search",+ "Default",+ _ON_OFF,+ help="Whether this agent may search the web.",+ ),+ _field(+ "smallModel",+ "Utility model",+ "text",+ placeholder="e.g. ollama/gemma4:latest — blank uses your OpenCode default",+ help="The cheaper model OpenCode uses for background work like naming the conversation. Worth setting to match the model above when the point is to keep everything on one machine — otherwise that background work goes wherever your own config sends it.",+ catalogue=Catalogue(kind="model", model_field=None),+ ),+)diff --git a/core/switch_core/providers/registry.py b/core/switch_core/providers/registry.pynew file mode 100644index 000000000..672b4cc93--- /dev/null+++ b/core/switch_core/providers/registry.py@@ -0,0 +1,209 @@+"""The agent CLIs Switch runs: one entry per provider, and the only list of them.++Everything else that depends on which providers exist — definition+validation, the known-agent specs agents register through, advanced+configuration, the gateway's provider list — reads this table through the+functions below. Adding a provider is adding an entry; one with no advanced+settings or tools needs only an `id` and a `label`.++Read the table through `agent_providers()` / `agent_provider()` rather than+importing `AGENT_PROVIDERS`, so every reader sees the same table.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Annotated++from pydantic import AfterValidator++from switch_core.bridges.agent.protocol.types import ToolSpec+from switch_core.providers.advanced_fields import (+ CLAUDE_FIELDS,+ CODEX_FIELDS,+ OPENCODE_FIELDS,+ AdvancedField,+)+++class UnknownProvider(ValueError):+ pass+++@dataclass(frozen=True)+class TerminalStart:+ """The operator starts a session by running `command` in the agent's+ directory; `{prompt}` in it stands for the connect prompt."""++ command: str+++@dataclass(frozen=True)+class ConsoleStart:+ """The operator starts a session from Switch Console. `runtime` names the+ runtime to enable in the agent's advanced settings there and+ `sign_in_command` the command that signs the CLI in; None when there is+ nothing to say."""++ runtime: str | None+ sign_in_command: str | None+++@dataclass(frozen=True)+class AgentProvider:+ id: str+ """What a definition, a launch and a provider connection name it by."""++ label: str+ """How people see it named."""++ known_agent_type: str = ""+ """The known-agent spec its agents register through, stored on each agent+ as `known_agent_type`. Defaults to `id`."""++ connector_type: str = ""+ """The connector type its agents register with, stored on each agent row.+ Defaults to `label`."""++ advanced_fields: tuple[AdvancedField, ...] = ()+ """The settings a managed agent of this provider may carry."""++ tools: tuple[ToolSpec, ...] = ()+ """The built-in tools its agents register."""++ session_start: TerminalStart | ConsoleStart = ConsoleStart(+ runtime=None, sign_in_command=None+ )+ """How the operator starts a session when the agent is addressed with none+ running."""++ def __post_init__(self) -> None:+ if not self.known_agent_type:+ object.__setattr__(self, "known_agent_type", self.id)+ if not self.connector_type:+ object.__setattr__(self, "connector_type", self.label)+++AGENT_PROVIDERS: tuple[AgentProvider, ...] = (+ # Claude Code's known agent (`ClaudeCodeKnownAgent`) builds its own launch+ # command, so `session_start` is not read for it.+ AgentProvider(+ id="claude",+ label="Claude Code",+ known_agent_type="claude-code",+ advanced_fields=CLAUDE_FIELDS,+ tools=(+ ToolSpec(name="Bash", description="Executes shell commands"),+ ToolSpec(name="Edit", description="Makes targeted edits to files"),+ ToolSpec(name="Write", description="Creates or overwrites files"),+ ToolSpec(name="Read", description="Reads file contents"),+ ToolSpec(name="Glob", description="Finds files by name pattern"),+ ToolSpec(name="Grep", description="Searches file contents for patterns"),+ ToolSpec(+ name="NotebookEdit", description="Modifies Jupyter notebook cells"+ ),+ ToolSpec(name="Agent", description="Spawns a subagent to handle a task"),+ ToolSpec(name="WebFetch", description="Fetches and processes web content"),+ ToolSpec(name="WebSearch", description="Performs web searches"),+ ToolSpec(name="Monitor", description="Runs background watch commands"),+ ToolSpec(name="Skill", description="Executes a skill"),+ ),+ ),+ AgentProvider(+ id="codex",+ label="Codex",+ connector_type="Codex CLI",+ advanced_fields=CODEX_FIELDS,+ tools=(+ ToolSpec(name="Shell", description="Executes shell commands"),+ ToolSpec(name="ApplyPatch", description="Applies patches to files"),+ ToolSpec(name="Read", description="Reads file contents"),+ ),+ session_start=TerminalStart(command='codex "{prompt}"'),+ ),+ AgentProvider(+ id="opencode",+ label="OpenCode",+ connector_type="OpenCode CLI",+ advanced_fields=OPENCODE_FIELDS,+ tools=(+ ToolSpec(name="Bash", description="Executes shell commands"),+ ToolSpec(name="Edit", description="Edits existing files"),+ ToolSpec(name="Write", description="Writes new files"),+ ToolSpec(name="Read", description="Reads file contents"),+ ToolSpec(name="Grep", description="Searches file contents"),+ ToolSpec(name="Glob", description="Finds files by pattern"),+ ToolSpec(name="List", description="Lists directory contents"),+ ToolSpec(name="WebFetch", description="Fetches web pages"),+ ToolSpec(name="Task", description="Spawns a sub-agent"),+ ),+ # OpenCode reads its first positional argument as the project+ # directory, so the prompt has to go through `--prompt`.+ session_start=TerminalStart(command='opencode --prompt "{prompt}"'),+ ),+ AgentProvider(+ id="antigravity",+ label="Antigravity",+ connector_type="Antigravity CLI",+ tools=(+ ToolSpec(name="run_command", description="Executes shell commands"),+ ToolSpec(name="write_to_file", description="Writes files"),+ ToolSpec(name="replace_file_content", description="Edits existing files"),+ ToolSpec(+ name="multi_replace_file_content",+ description="Applies several edits to one file",+ ),+ ToolSpec(name="view_file", description="Reads file contents"),+ ToolSpec(name="grep_search", description="Searches file contents"),+ ToolSpec(name="find_by_name", description="Finds files by pattern"),+ ToolSpec(name="list_dir", description="Lists directory contents"),+ ToolSpec(name="read_url_content", description="Fetches web pages"),+ ToolSpec(name="search_web", description="Searches the web"),+ ToolSpec(name="call_mcp_tool", description="Calls a tool on an MCP server"),+ ToolSpec(name="invoke_subagent", description="Delegates to a subagent"),+ ),+ session_start=ConsoleStart(runtime="Antigravity CLI", sign_in_command="agy"),+ ),+ AgentProvider(+ id="cursor",+ label="Cursor CLI",+ tools=(+ ToolSpec(name="shell", description="Executes shell commands"),+ ToolSpec(name="read_file", description="Reads file contents"),+ ToolSpec(name="write", description="Writes files"),+ ToolSpec(name="str_replace", description="Edits existing files"),+ ToolSpec(name="grep", description="Searches file contents"),+ ToolSpec(name="glob", description="Finds files by pattern"),+ ),+ session_start=ConsoleStart(runtime="Cursor CLI ACP", sign_in_command="agent"),+ ),+)+++def agent_providers() -> tuple[AgentProvider, ...]:+ """Every provider, in the order a client offers them."""+ return AGENT_PROVIDERS+++def provider_ids() -> list[str]:+ return [provider.id for provider in agent_providers()]+++def agent_provider(provider_id: str) -> AgentProvider:+ """The provider named `provider_id`. Raises UnknownProvider, naming the+ providers there are, for one Switch does not run."""+ for provider in agent_providers():+ if provider.id == provider_id:+ return provider+ raise UnknownProvider(+ f"unknown provider {provider_id!r}; one of {', '.join(provider_ids())}"+ )+++def _require_agent_provider(value: str) -> str:+ agent_provider(value)+ return value+++AgentProviderId = Annotated[str, AfterValidator(_require_agent_provider)]+"""A provider id in a request body, refused unless the table has it."""diff --git a/core/switch_core/providers/schema.py b/core/switch_core/providers/schema.pynew file mode 100644index 000000000..3c474a7b6--- /dev/null+++ b/core/switch_core/providers/schema.py@@ -0,0 +1,37 @@+"""The providers and their advanced-configuration fields, as the gateway+serves them to every client — Switch Console builds the advanced form of each+agent, its own and managed ones, from these."""++from __future__ import annotations++from typing import Any++from switch_core.providers.registry import agent_providers+++def advanced_config_schema() -> dict[str, Any]:+ """Every provider's fields, as `GET /gateway/management/advanced-config`+ serves them."""+ return {+ "providers": {+ provider.id: {+ "fields": [field.wire() for field in provider.advanced_fields]+ }+ for provider in agent_providers()+ }+ }+++def providers_schema() -> dict[str, Any]:+ """Every provider a definition can name, in the order a client offers+ them, as `GET /gateway/management/providers` serves them."""+ return {+ "providers": [+ {+ "id": provider.id,+ "label": provider.label,+ "advanced_fields": [field.wire() for field in provider.advanced_fields],+ }+ for provider in agent_providers()+ ]+ }diff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.pyindex 37cef0628..e90429ff3 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py@@ -14,7 +14,7 @@ from switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.gateway.known_agents import KNOWN_AGENTS+from switch_core.gateway.known_agents import known_agentsdef _service(session_factory: async_sessionmaker[AsyncSession]) -> AgentCore:@@ -62,7 +62,7 @@ async def _make_agent(await session.flush()if known:- spec = KNOWN_AGENTS["claude-code"]+ spec = known_agents()["claude-code"]opts = spec.parse_options({})integration_profile = spec.build_profile(opts).model_dump()metadata_ = {diff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.pyindex 67b22f621..93627f8ac 100644--- a/core/tests/switch_core/gateway/test_known_agents.py+++ b/core/tests/switch_core/gateway/test_known_agents.py@@ -2,21 +2,28 @@ from __future__ import annotationsfrom types import SimpleNamespace+import pytest++from switch_core.bridges.agent.protocol.types import (+ CommandCapabilities,+ IntegrationProfile,+ TaskProtocolConfig,+)from switch_core.gateway.known_agents import (- KNOWN_AGENTS,- AntigravityKnownAgent,- AntigravityOptions,ClaudeCodeKnownAgent,ClaudeCodeOptions,- CodexKnownAgent,- CodexOptions,- CursorKnownAgent,- CursorOptions,- OpenCodeKnownAgent,- OpenCodeOptions,+ GenericAgentOptions,+ GenericKnownAgent,known_agent_for,+ known_agents,)+CLAUDE = known_agents()["claude-code"]+CODEX = known_agents()["codex"]+OPENCODE = known_agents()["opencode"]+ANTIGRAVITY = known_agents()["antigravity"]+CURSOR = known_agents()["cursor"]+def _agent(metadata: dict | None) -> SimpleNamespace:return SimpleNamespace(name="claude-code.test", metadata_=metadata)@@ -37,13 +44,11 @@ def _identity(agent_name: str) -> str:class TestBuildProfileConnectionModel:def test_channels_enabled_defaults_to_session_addressable(self) -> None:- profile = ClaudeCodeKnownAgent.build_profile(- ClaudeCodeOptions(channels_enabled=True)- )+ profile = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=True))assert profile.connection_model == "session_addressable"def test_auto_session_option_sets_auto_session_model(self) -> None:- profile = ClaudeCodeKnownAgent.build_profile(+ profile = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=True, auto_session=True))assert profile.connection_model == "auto_session"@@ -52,15 +57,13 @@ class TestBuildProfileConnectionModel:# Auto-spawn is driven by the connector's HTTP notification watch and a# pull-on-connect, not a live channel push, so auto_session applies even# when channels are disabled.- profile = ClaudeCodeKnownAgent.build_profile(+ profile = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=False, auto_session=True))assert profile.connection_model == "auto_session"def test_channels_disabled_without_auto_session_is_session_passive(self) -> None:- profile = ClaudeCodeKnownAgent.build_profile(- ClaudeCodeOptions(channels_enabled=False)- )+ profile = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=False))assert profile.connection_model == "session_passive"def test_auto_session_defaults_off(self) -> None:@@ -71,7 +74,7 @@ class TestBuildProfileCommandCapabilities:def test_claude_code_commands_are_session_dependent(self) -> None:# Claude Code can be reset/compacted/interrupted only when a session is# driving it from Switch Console — so all three depend on the live session.- caps = ClaudeCodeKnownAgent.build_profile(+ caps = CLAUDE.build_profile(ClaudeCodeOptions(channels_enabled=True)).command_capabilitiesassert caps.reset == "session_dependent"@@ -82,9 +85,7 @@ class TestBuildProfileCommandCapabilities:class TestStartSessionInstructions:def test_channels_enabled_appends_dev_flag_after_prompt(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/Users/x/aq-switch")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not None# The flag must come AFTER the prompt argument so claude treats the# quoted text as the initial prompt, not as a value for the flag.@@ -97,9 +98,7 @@ class TestStartSessionInstructions:def test_channels_disabled_passive_message_shape(self) -> None:opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/srv/agent")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "ops", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)assert msg is not Noneassert "--dangerously-load-development-channels" not in msg# The connect prompt itself instructs a pull (passive sessions get no@@ -114,9 +113,7 @@ class TestStartSessionInstructions:def test_channels_enabled_is_not_passive_shaped(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "ops", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)assert msg is not Noneassert "pull the latest messages" not in msgassert "Anthropic API key or subscription" not in msg@@ -128,9 +125,7 @@ class TestStartSessionInstructions:opts = ClaudeCodeOptions(channels_enabled=False, auto_session=True, repo_dir="/srv/agent")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "ops", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)assert msg is not Noneassert "--dangerously-load-development-channels" not in msgassert (@@ -140,7 +135,7 @@ class TestStartSessionInstructions:def test_connected_not_live_opening(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/srv/agent")- msg = ClaudeCodeKnownAgent.start_session_instructions(+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None, connected_not_live=True)assert msg is not None@@ -153,9 +148,7 @@ class TestStartSessionInstructions:def test_no_repo_dir_uses_placeholder(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, repo_dir=None)- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "triage", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "triage", None)assert msg is not Noneassert "cd <claude-dir>" in msg# Still the channels flag because channels_enabled is True.@@ -167,9 +160,7 @@ class TestStartSessionInstructions:# The gateway edit form submits "" when the field is cleared.opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="")assert opts.repo_dir is None- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "triage", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "triage", None)assert msg is not Noneassert "cd <claude-dir>" in msg@@ -179,18 +170,14 @@ class TestStartSessionInstructions:# single string configured on the agent, which could only ever be# right on one platform.opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", "louisa"- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", "louisa")assert msg is not Noneassert msg.startswith("@louisa\n\n")def test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:# Nobody to mention is not a reason to withhold the instructions.opts = ClaudeCodeOptions(channels_enabled=True)- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert not msg.startswith("@")@@ -198,17 +185,13 @@ class TestStartSessionInstructions:# Passive message names the operator inline ("my operator @louisa")# rather than as a leading prefix, so they still get pinged to pull.opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", "louisa"- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", "louisa")assert msg is not Noneassert "my operator @louisa" in msgdef test_passive_without_a_linked_owner_says_my_operator(self) -> None:opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/x")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert "my operator has to trigger me" in msgassert "@" not in msg@@ -219,9 +202,7 @@ class TestStartSessionInstructions:repo_dir="/Users/x/repo",subagent_name="seo-writer",)- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not None# --agent / --settings come after the quoted prompt and before the# dev-channels flag; the settings path matches what the configure skill@@ -238,9 +219,7 @@ class TestStartSessionInstructions:opts = ClaudeCodeOptions(channels_enabled=False, repo_dir="/r", subagent_name="reviewer")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "ops", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "ops", None)assert msg is not Noneassert "--agent reviewer" in msgassert "--settings .claude/switch-subagents/reviewer.settings.json" in msg@@ -248,9 +227,7 @@ class TestStartSessionInstructions:def test_no_subagent_name_omits_agent_flag(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/r")- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert "--agent" not in msgassert "switch-subagents" not in msg@@ -258,9 +235,7 @@ class TestStartSessionInstructions:def test_empty_string_subagent_name_normalised_to_none(self) -> None:opts = ClaudeCodeOptions(channels_enabled=True, subagent_name="")assert opts.subagent_name is None- msg = ClaudeCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert "--agent" not in msg@@ -268,7 +243,7 @@ class TestStartSessionInstructions:# We refer to "this room" in the lead-in rather than naming it, so the# message reads the same regardless of where it's posted.opts = ClaudeCodeOptions(channels_enabled=True, repo_dir="/x")- msg = ClaudeCodeKnownAgent.start_session_instructions(+ msg = CLAUDE.start_session_instructions(opts, _agent({}), "Some Long Room Name", None)assert msg is not None@@ -280,26 +255,26 @@ class TestStartSessionInstructions:class TestCodexKnownAgent:def test_registered_under_codex_key(self) -> None:- assert KNOWN_AGENTS.get("codex") is CodexKnownAgent- assert CodexKnownAgent.connector_type == "Codex CLI"+ assert isinstance(CODEX, GenericKnownAgent)+ assert CODEX.connector_type == "Codex CLI"def test_default_profile_is_session_addressable(self) -> None:- profile = CodexKnownAgent.build_profile(CodexOptions())+ profile = CODEX.build_profile(GenericAgentOptions())assert profile.connection_model == "session_addressable"def test_auto_session_sets_auto_session_model(self) -> None:- profile = CodexKnownAgent.build_profile(CodexOptions(auto_session=True))+ profile = CODEX.build_profile(GenericAgentOptions(auto_session=True))assert profile.connection_model == "auto_session"def test_no_tool_call_mediation_or_reporting(self) -> None:# Codex runs auto-approved and reports lifecycle hooks only (not per-tool# events), unlike Claude Code.- profile = CodexKnownAgent.build_profile(CodexOptions())+ profile = CODEX.build_profile(GenericAgentOptions())assert profile.pre_invocation_mediation == []assert profile.event_reporting == []def test_can_delegate_and_accept_tasks(self) -> None:- profile = CodexKnownAgent.build_profile(CodexOptions())+ profile = CODEX.build_profile(GenericAgentOptions())assert profile.task_protocol.can_delegate is Trueassert profile.task_protocol.can_accept is True@@ -309,14 +284,14 @@ class TestCodexKnownAgent:# Must stay in step with `BY_PROVIDER.codex` in Switch Console's# `main/core/switch-rooms/session-control.ts`; declaring a command here# that Switch Console cannot execute yields a worse message than "unsupported".- caps = CodexKnownAgent.build_profile(CodexOptions()).command_capabilities+ caps = CODEX.build_profile(GenericAgentOptions()).command_capabilitiesassert caps.reset == "session_dependent"assert caps.compact == "session_dependent"assert caps.interrupt == "session_dependent"def test_start_session_instructions_emit_codex_not_claude(self) -> None:- opts = CodexOptions(repo_dir="/Users/x/repo")- msg = CodexKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/Users/x/repo")+ msg = CODEX.start_session_instructions(opts, _agent_named("codex.test"), "hub", None)assert msg is not None@@ -335,14 +310,14 @@ class TestCodexKnownAgent:assert "start Codex manually" in msgdef test_repo_dir_with_spaces_stays_quoted(self) -> None:- opts = CodexOptions(repo_dir="/Users/alice/my project")- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)+ opts = GenericAgentOptions(repo_dir="/Users/alice/my project")+ msg = CODEX.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert 'cd "/Users/alice/my project" && codex' in msgdef test_connected_not_live_opening(self) -> None:- opts = CodexOptions(repo_dir="/r")- msg = CodexKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/r")+ msg = CODEX.start_session_instructions(opts, _agent_named("codex.test"), "ops", None, connected_not_live=True)assert msg is not None@@ -351,8 +326,8 @@ class TestCodexKnownAgent:assert "claude" not in msgdef test_other_room_names_branch(self) -> None:- opts = CodexOptions(repo_dir="/r")- msg = CodexKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/r")+ msg = CODEX.start_session_instructions(opts,_agent_named("codex.test"),"ops",@@ -365,8 +340,8 @@ class TestCodexKnownAgent:assert "claude" not in msgdef test_assume_role_folded_into_prompt(self) -> None:- opts = CodexOptions(repo_dir="/r")- msg = CodexKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/r")+ msg = CODEX.start_session_instructions(opts, _agent_named("codex.test"), "ops", None, assume_role="reviewer")assert msg is not None@@ -376,32 +351,28 @@ class TestCodexKnownAgent:) in msgdef test_empty_string_repo_dir_normalised_to_placeholder(self) -> None:- opts = CodexOptions(repo_dir="")+ opts = GenericAgentOptions(repo_dir="")assert opts.repo_dir is None- msg = CodexKnownAgent.start_session_instructions(- opts, _agent({}), "triage", None- )+ msg = CODEX.start_session_instructions(opts, _agent({}), "triage", None)assert msg is not Noneassert 'cd "<codex-dir>"' in msgdef test_an_unlinked_owner_leaves_the_message_unmentioned(self) -> None:- opts = CodexOptions()- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)+ opts = GenericAgentOptions()+ msg = CODEX.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert not msg.startswith("@")def test_no_repo_dir_uses_codex_placeholder(self) -> None:- msg = CodexKnownAgent.start_session_instructions(- CodexOptions(repo_dir=None), _agent({}), "triage", None+ msg = CODEX.start_session_instructions(+ GenericAgentOptions(repo_dir=None), _agent({}), "triage", None)assert msg is not Noneassert 'cd "<codex-dir>"' in msgdef test_the_owner_is_prepended_as_an_at_mention(self) -> None:- opts = CodexOptions(repo_dir="/x")- msg = CodexKnownAgent.start_session_instructions(- opts, _agent({}), "hub", "cmcd"- )+ opts = GenericAgentOptions(repo_dir="/x")+ msg = CODEX.start_session_instructions(opts, _agent({}), "hub", "cmcd")assert msg is not Noneassert msg.startswith("@cmcd\n\n")@@ -410,15 +381,15 @@ class TestCodexKnownAgent:# must still accept it — but Codex has no channel, so it is not a field.# The gateway renders the options form from this schema; a declared field# would be an interactive control that changes nothing.- assert "channels_enabled" not in CodexOptions.model_json_schema()["properties"]-- opts = CodexOptions.model_validate({"channels_enabled": False})- assert "channels_enabled" not in opts.model_dump()assert (- CodexKnownAgent.build_profile(opts).connection_model- == "session_addressable"+ "channels_enabled"+ not in GenericAgentOptions.model_json_schema()["properties"])+ opts = GenericAgentOptions.model_validate({"channels_enabled": False})+ assert "channels_enabled" not in opts.model_dump()+ assert CODEX.build_profile(opts).connection_model == "session_addressable"+def test_known_agent_for_round_trips_codex(self) -> None:agent = _agent({@@ -429,36 +400,36 @@ class TestCodexKnownAgent:result = known_agent_for(agent)assert result is not Nonespec, options = result- assert spec is CodexKnownAgent- assert isinstance(options, CodexOptions)+ assert spec.provider.id == "codex"+ assert isinstance(options, GenericAgentOptions)assert options.auto_session is Trueassert options.repo_dir == "/tmp/r"class TestOpenCodeKnownAgent:def test_registered_under_opencode_key(self) -> None:- assert KNOWN_AGENTS.get("opencode") is OpenCodeKnownAgent- assert OpenCodeKnownAgent.connector_type == "OpenCode CLI"+ assert isinstance(OPENCODE, GenericKnownAgent)+ assert OPENCODE.connector_type == "OpenCode CLI"def test_default_profile_is_session_addressable(self) -> None:- profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())+ profile = OPENCODE.build_profile(GenericAgentOptions())assert profile.connection_model == "session_addressable"def test_auto_session_sets_auto_session_model(self) -> None:- profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions(auto_session=True))+ profile = OPENCODE.build_profile(GenericAgentOptions(auto_session=True))assert profile.connection_model == "auto_session"def test_no_tool_call_mediation_or_reporting(self) -> None:# OpenCode's connector reports activity to Switch Console over the local# hook port to drive session status; none of it reaches Switch as# reported events, and nothing gates a tool call before it runs.- profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())+ profile = OPENCODE.build_profile(GenericAgentOptions())assert profile.pre_invocation_mediation == []assert profile.post_invocation_mediation == []assert profile.event_reporting == []def test_can_delegate_and_accept_tasks(self) -> None:- profile = OpenCodeKnownAgent.build_profile(OpenCodeOptions())+ profile = OPENCODE.build_profile(GenericAgentOptions())assert profile.task_protocol.can_delegate is Trueassert profile.task_protocol.can_accept is True@@ -467,7 +438,7 @@ class TestOpenCodeKnownAgent:# `main/core/switch-rooms/session-control.ts`; declaring a command here# that Switch Console cannot execute yields a worse message than# "unsupported".- caps = OpenCodeKnownAgent.build_profile(OpenCodeOptions()).command_capabilities+ caps = OPENCODE.build_profile(GenericAgentOptions()).command_capabilitiesassert caps.reset == "session_dependent"assert caps.compact == "session_dependent"assert caps.interrupt == "session_dependent"@@ -476,8 +447,8 @@ class TestOpenCodeKnownAgent:# OpenCode reads its first positional as the project directory, so a bare# `opencode "connect to switch room hub"` asks it to open a directory of# that name. The prompt must go through --prompt.- opts = OpenCodeOptions(repo_dir="/Users/x/repo")- msg = OpenCodeKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/Users/x/repo")+ msg = OPENCODE.start_session_instructions(opts, _agent_named("opencode.test"), "hub", None)assert msg is not None@@ -488,8 +459,8 @@ class TestOpenCodeKnownAgent:assert 'opencode "connect' not in msgdef test_start_session_instructions_emit_opencode_only(self) -> None:- opts = OpenCodeOptions(repo_dir="/Users/x/repo")- msg = OpenCodeKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/Users/x/repo")+ msg = OPENCODE.start_session_instructions(opts, _agent_named("opencode.test"), "hub", None)assert msg is not None@@ -500,16 +471,14 @@ class TestOpenCodeKnownAgent:assert "start OpenCode manually" in msgdef test_repo_dir_with_spaces_stays_quoted(self) -> None:- opts = OpenCodeOptions(repo_dir="/Users/alice/my project")- msg = OpenCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ opts = GenericAgentOptions(repo_dir="/Users/alice/my project")+ msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert 'cd "/Users/alice/my project" && opencode' in msgdef test_assume_role_is_folded_into_the_prompt(self) -> None:- opts = OpenCodeOptions(repo_dir="/r")- msg = OpenCodeKnownAgent.start_session_instructions(+ opts = GenericAgentOptions(repo_dir="/r")+ msg = OPENCODE.start_session_instructions(opts, _agent_named("opencode.test"), "ops", None, assume_role="reviewer")assert msg is not None@@ -519,32 +488,28 @@ class TestOpenCodeKnownAgent:) in msgdef test_blank_repo_dir_uses_placeholder(self) -> None:- msg = OpenCodeKnownAgent.start_session_instructions(- OpenCodeOptions(repo_dir=""), _agent({}), "triage", None+ msg = OPENCODE.start_session_instructions(+ GenericAgentOptions(repo_dir=""), _agent({}), "triage", None)assert msg is not Noneassert 'cd "<opencode-dir>"' in msgdef test_no_repo_dir_uses_placeholder(self) -> None:- msg = OpenCodeKnownAgent.start_session_instructions(- OpenCodeOptions(repo_dir=None), _agent({}), "triage", None+ msg = OPENCODE.start_session_instructions(+ GenericAgentOptions(repo_dir=None), _agent({}), "triage", None)assert msg is not Noneassert 'cd "<opencode-dir>"' in msgdef test_an_unlinked_owner_produces_no_mention(self) -> None:- opts = OpenCodeOptions()- msg = OpenCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", None- )+ opts = GenericAgentOptions()+ msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", None)assert msg is not Noneassert not msg.startswith("@")def test_the_owner_is_mentioned(self) -> None:- opts = OpenCodeOptions(repo_dir="/x")- msg = OpenCodeKnownAgent.start_session_instructions(- opts, _agent({}), "hub", "cmcd"- )+ opts = GenericAgentOptions(repo_dir="/x")+ msg = OPENCODE.start_session_instructions(opts, _agent({}), "hub", "cmcd")assert msg is not Noneassert msg.startswith("@cmcd")@@ -554,15 +519,13 @@ class TestOpenCodeKnownAgent:# field. The gateway renders the options form from this schema; a# declared field would be an interactive control that changes nothing.assert (- "channels_enabled" not in OpenCodeOptions.model_json_schema()["properties"]+ "channels_enabled"+ not in GenericAgentOptions.model_json_schema()["properties"])- opts = OpenCodeOptions.model_validate({"channels_enabled": False})+ opts = GenericAgentOptions.model_validate({"channels_enabled": False})assert "channels_enabled" not in opts.model_dump()- assert (- OpenCodeKnownAgent.build_profile(opts).connection_model- == "session_addressable"- )+ assert OPENCODE.build_profile(opts).connection_model == "session_addressable"def test_known_agent_for_round_trips_opencode(self) -> None:agent = _agent(@@ -574,8 +537,8 @@ class TestOpenCodeKnownAgent:result = known_agent_for(agent)assert result is not Nonespec, options = result- assert spec is OpenCodeKnownAgent- assert isinstance(options, OpenCodeOptions)+ assert spec.provider.id == "opencode"+ assert isinstance(options, GenericAgentOptions)assert options.auto_session is Trueassert options.repo_dir == "/tmp/r"@@ -594,7 +557,7 @@ class TestKnownAgentFor:result = known_agent_for(agent)assert result is not Nonespec, options = result- assert spec is ClaudeCodeKnownAgent+ assert isinstance(spec, ClaudeCodeKnownAgent)assert isinstance(options, ClaudeCodeOptions)assert options.channels_enabled is Falseassert options.repo_dir == "/tmp/r"@@ -646,13 +609,13 @@ class TestKnownAgentFor:class TestAntigravityKnownAgent:def test_registry_and_profile(self) -> None:- assert KNOWN_AGENTS["antigravity"] is AntigravityKnownAgent+ assert isinstance(ANTIGRAVITY, GenericKnownAgent)for auto_session, expected in [(False, "session_addressable"),(True, "auto_session"),]:- profile = AntigravityKnownAgent.build_profile(- AntigravityOptions(auto_session=auto_session)+ profile = ANTIGRAVITY.build_profile(+ GenericAgentOptions(auto_session=auto_session))assert profile.connection_model == expectedassert profile.message_exchange@@ -660,15 +623,11 @@ class TestAntigravityKnownAgent:assert profile.pre_invocation_mediation == []def test_onboarding_requires_console_runtime(self) -> None:- options = AntigravityKnownAgent.parse_options({"repo_dir": " "})+ options = ANTIGRAVITY.parse_options({"repo_dir": " "})assert options.repo_dir is Noneagent = _agent_named("antigravity.test")- assert (- AntigravityKnownAgent.connect_command(options, agent, "hub", None) is None- )- text = AntigravityKnownAgent.start_session_instructions(- options, agent, "hub", None- )+ assert ANTIGRAVITY.connect_command(options, agent, "hub", None) is None+ text = ANTIGRAVITY.start_session_instructions(options, agent, "hub", None)assert "Antigravity CLI" in textassert "`agy`" in textassert "local session" in text@@ -677,13 +636,13 @@ class TestAntigravityKnownAgent:class TestCursorKnownAgent:def test_registry_and_profile(self) -> None:- assert KNOWN_AGENTS["cursor"] is CursorKnownAgent+ assert isinstance(CURSOR, GenericKnownAgent)for auto_session, expected in [(False, "session_addressable"),(True, "auto_session"),]:- profile = CursorKnownAgent.build_profile(- CursorOptions(auto_session=auto_session)+ profile = CURSOR.build_profile(+ GenericAgentOptions(auto_session=auto_session))assert profile.connection_model == expectedassert profile.message_exchange@@ -691,11 +650,115 @@ class TestCursorKnownAgent:assert profile.pre_invocation_mediation == []def test_onboarding_requires_console_acp(self) -> None:- options = CursorKnownAgent.parse_options({"repo_dir": " "})+ options = CURSOR.parse_options({"repo_dir": " "})assert options.repo_dir is Noneagent = _agent_named("cursor.test")- assert CursorKnownAgent.connect_command(options, agent, "hub", None) is None- text = CursorKnownAgent.start_session_instructions(options, agent, "hub", None)+ assert CURSOR.connect_command(options, agent, "hub", None) is None+ text = CURSOR.start_session_instructions(options, agent, "hub", None)assert "Cursor CLI ACP" in textassert "local session" in textassert "cursor.test" in text+++_SESSION_DEPENDENT = CommandCapabilities(+ reset="session_dependent",+ compact="session_dependent",+ interrupt="session_dependent",+)+++ ("known_agent_type", "connector_type", "tools", "reported"),+ [+ (+ "claude-code",+ "Claude Code",+ [+ "Bash",+ "Edit",+ "Write",+ "Read",+ "Glob",+ "Grep",+ "NotebookEdit",+ "Agent",+ "WebFetch",+ "WebSearch",+ "Monitor",+ "Skill",+ ],+ ["tool_calls"],+ ),+ ("codex", "Codex CLI", ["Shell", "ApplyPatch", "Read"], []),+ (+ "opencode",+ "OpenCode CLI",+ [+ "Bash",+ "Edit",+ "Write",+ "Read",+ "Grep",+ "Glob",+ "List",+ "WebFetch",+ "Task",+ ],+ [],+ ),+ (+ "antigravity",+ "Antigravity CLI",+ [+ "run_command",+ "write_to_file",+ "replace_file_content",+ "multi_replace_file_content",+ "view_file",+ "grep_search",+ "find_by_name",+ "list_dir",+ "read_url_content",+ "search_web",+ "call_mcp_tool",+ "invoke_subagent",+ ],+ [],+ ),+ (+ "cursor",+ "Cursor CLI",+ ["shell", "read_file", "write", "str_replace", "grep", "glob"],+ [],+ ),+ ],+)+def test_every_stored_known_agent_type_resolves_as_before(+ known_agent_type: str, connector_type: str, tools: list[str], reported: list[str]+) -> None:+ """Agents carry their `known_agent_type` and options in metadata; each one+ already stored must keep resolving to the same connector type, tools and+ profile."""+ for auto_session in (False, True):+ agent = _agent(+ {+ "known_agent_type": known_agent_type,+ "known_agent_options": {"auto_session": auto_session, "repo_dir": "/r"},+ }+ )+ resolved = known_agent_for(agent)+ assert resolved is not None+ spec, options = resolved+ assert spec.connector_type == connector_type+ assert [tool.name for tool in spec.tools] == tools+ assert spec.models == []+ assert options.model_dump()["repo_dir"] == "/r"+ assert spec.build_profile(options) == IntegrationProfile(+ connection_model="auto_session" if auto_session else "session_addressable",+ message_exchange=True,+ pre_invocation_mediation=reported,+ post_invocation_mediation=[],+ event_reporting=reported,+ task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),+ command_capabilities=_SESSION_DEPENDENT,+ )diff --git a/core/tests/switch_core/gateway/test_providers.py b/core/tests/switch_core/gateway/test_providers.pynew file mode 100644index 000000000..e1dc7e29c--- /dev/null+++ b/core/tests/switch_core/gateway/test_providers.py@@ -0,0 +1,31 @@+"""The provider list and advanced-configuration fields are served on a+gateway that runs no agent management, since Switch Console builds the form+of the agents it runs itself from them too."""++from __future__ import annotations++from types import SimpleNamespace++import httpx+from fastapi import FastAPI++from switch_core.gateway.auth import get_current_user+from switch_core.gateway.providers import router as providers_router+from switch_core.providers.schema import advanced_config_schema, providers_schema+++async def test_they_are_served_without_agent_management() -> None:+ gateway_app = FastAPI()+ gateway_app.include_router(providers_router)+ gateway_app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id="u")+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=gateway_app), base_url="http://test"+ ) as client:+ providers = await client.get("/management/providers")+ advanced = await client.get("/management/advanced-config")+ agents = await client.get("/management/agents")+ assert providers.status_code == 200, providers.text+ assert providers.json() == providers_schema()+ assert advanced.status_code == 200, advanced.text+ assert advanced.json() == advanced_config_schema()+ assert agents.status_code == 404diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.pyindex 38cb9f0e2..87c6ba086 100644--- a/core/tests/switch_core/management/harness.py+++ b/core/tests/switch_core/management/harness.py@@ -61,6 +61,7 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway import dependencies as gw_depsfrom switch_core.gateway.auth import create_jwt+from switch_core.gateway.providers import router as providers_routerfrom switch_core.keys import Keyringfrom switch_core.management import controller_routesfrom switch_core.management.errors import ManagementError@@ -208,6 +209,7 @@ def build_harness(agent_app = FastAPI()gateway_app = FastAPI()+ gateway_app.include_router(providers_router)management.install(agent_bridge_app=agent_app, gateway_app=gateway_app, protocol=protocol)diff --git a/core/tests/switch_core/management/test_advanced_config.py b/core/tests/switch_core/management/test_advanced_config.pyindex 54bcdcd24..e9474448f 100644--- a/core/tests/switch_core/management/test_advanced_config.py+++ b/core/tests/switch_core/management/test_advanced_config.py@@ -7,16 +7,35 @@ from typing import Anyimport pytestfrom pydantic import ValidationError-from switch_core.management.advanced_config import (- ADVANCED_FIELDS,- advanced_config_schema,- validate_advanced_config,-)-from switch_core.management.schemas import DefinitionV1, Provider+from switch_core.management.advanced_config import validate_advanced_config+from switch_core.management.schemas import DefinitionV1+from switch_core.providers.schema import advanced_config_schema, providers_schema-def test_every_provider_a_definition_names_has_a_schema() -> None:- assert set(ADVANCED_FIELDS) == set(Provider.__args__) # type: ignore[attr-defined]+def test_a_definition_refuses_a_provider_switch_does_not_run() -> None:+ with pytest.raises(ValidationError) as raised:+ DefinitionV1(provider="gemini")+ assert (+ "unknown provider 'gemini'; one of claude, codex, opencode, antigravity, cursor"+ in str(raised.value)+ )+++def test_the_served_provider_list() -> None:+ providers = providers_schema()["providers"]++ assert [(provider["id"], provider["label"]) for provider in providers] == [+ ("claude", "Claude Code"),+ ("codex", "Codex"),+ ("opencode", "OpenCode"),+ ("antigravity", "Antigravity"),+ ("cursor", "Cursor CLI"),+ ]+ by_id = {provider["id"]: provider for provider in providers}+ served = advanced_config_schema()["providers"]+ for provider_id, provider in by_id.items():+ assert provider["advanced_fields"] == served[provider_id]["fields"]+ assert by_id["cursor"]["advanced_fields"] == []def test_the_served_schema() -> None:diff --git a/core/tests/switch_core/management/test_gateway_routes.py b/core/tests/switch_core/management/test_gateway_routes.pyindex 1b8990715..81e1817ae 100644--- a/core/tests/switch_core/management/test_gateway_routes.py+++ b/core/tests/switch_core/management/test_gateway_routes.py@@ -133,7 +133,7 @@ class TestOwnerIsolation:return foundroutes = [r for r in gateway_router.routes if hasattr(r, "dependant")]- assert len(routes) == 17+ assert len(routes) == 16for route in routes:assert get_current_user in calls(route.dependant), route.path # type: ignore[attr-defined]@@ -450,6 +450,34 @@ class TestManagedAgents:assert effort["options"][0] == {"value": "", "label": "Inherit"}assert anonymous.status_code == 401+ async def test_the_provider_list_is_served(self, harness: Harness) -> None:+ owner = await add_member(harness.session_factory, "ada")+ async with harness.client() as client:+ served = await client.get(+ "/gateway/management/providers", cookies=cookies_for(owner)+ )+ advanced = await client.get(+ "/gateway/management/advanced-config", cookies=cookies_for(owner)+ )+ anonymous = await client.get("/gateway/management/providers")+ assert served.status_code == 200, served.text+ providers = served.json()["providers"]+ assert [provider["id"] for provider in providers] == [+ "claude",+ "codex",+ "opencode",+ "antigravity",+ "cursor",+ ]+ assert providers[0]["label"] == "Claude Code"+ for entry in providers:+ assert set(entry) == {"id", "label", "advanced_fields"}+ assert (+ entry["advanced_fields"]+ == advanced.json()["providers"][entry["id"]]["fields"]+ )+ assert anonymous.status_code == 401+async def test_adopting_an_existing_agent(self, harness: Harness) -> None:owner = await add_member(harness.session_factory, "ada")async with harness.session_factory() as session:diff --git a/core/tests/switch_core/providers/test_provider_registry.py b/core/tests/switch_core/providers/test_provider_registry.pynew file mode 100644index 000000000..5ce8db701--- /dev/null+++ b/core/tests/switch_core/providers/test_provider_registry.py@@ -0,0 +1,181 @@+"""The provider table, and that a provider added to it reaches everything that+depends on which providers exist."""++from __future__ import annotations++from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI+from pydantic import ValidationError++from switch_core.gateway.auth import get_current_user+from switch_core.gateway.known_agents import (+ ClaudeCodeKnownAgent,+ GenericKnownAgent,+ known_agent_for,+ known_agents,+ provider_known_agent,+)+from switch_core.gateway.providers import router as providers_router+from switch_core.management.advanced_config import (+ provider_fields,+ validate_advanced_config,+)+from switch_core.management.schemas import DefinitionV1+from switch_core.management.service import _known_agent_registration+from switch_core.providers import registry+from switch_core.providers.registry import (+ AgentProvider,+ ConsoleStart,+ UnknownProvider,+ agent_provider,+ agent_providers,+ provider_ids,+)+from switch_core.providers.schema import advanced_config_schema+++def test_ids_known_agent_types_and_connector_types_are_unique() -> None:+ providers = agent_providers()+ for attribute in ("id", "known_agent_type", "connector_type", "label"):+ values = [getattr(provider, attribute) for provider in providers]+ assert len(values) == len(set(values)), attribute+ assert all(values), attribute+++def test_each_providers_advanced_fields_are_well_formed() -> None:+ for provider in agent_providers():+ keys = [field.key for field in provider.advanced_fields]+ assert len(keys) == len(set(keys)), provider.id+ for field in provider.advanced_fields:+ if field.type == "select":+ assert field.options, (provider.id, field.key)+ assert field.options[0].value == "", (provider.id, field.key)+ assert field.accepted_values(), (provider.id, field.key)+ else:+ assert field.options is None, (provider.id, field.key)+++def test_the_stored_identifiers_of_existing_providers_are_unchanged() -> None:+ # `known_agent_type` and `connector_type` are stored on agent rows, so an+ # existing provider's must never change.+ assert {+ provider.id: (provider.known_agent_type, provider.connector_type)+ for provider in agent_providers()+ } == {+ "claude": ("claude-code", "Claude Code"),+ "codex": ("codex", "Codex CLI"),+ "opencode": ("opencode", "OpenCode CLI"),+ "antigravity": ("antigravity", "Antigravity CLI"),+ "cursor": ("cursor", "Cursor CLI"),+ }+++def test_an_unknown_provider_is_refused_with_the_ones_there_are() -> None:+ with pytest.raises(UnknownProvider) as raised:+ agent_provider("gemini")+ assert str(raised.value) == (+ "unknown provider 'gemini'; one of claude, codex, opencode, antigravity, cursor"+ )+++def test_only_claude_has_a_known_agent_of_its_own() -> None:+ specs = known_agents()+ assert list(specs) == [p.known_agent_type for p in agent_providers()]+ assert isinstance(specs["claude-code"], ClaudeCodeKnownAgent)+ assert all(+ isinstance(spec, GenericKnownAgent)+ for key, spec in specs.items()+ if key != "claude-code"+ )+++NEW = AgentProvider(id="newcli", label="New CLI")+++def new_provider(monkeypatch: pytest.MonkeyPatch) -> AgentProvider:+ monkeypatch.setattr(registry, "AGENT_PROVIDERS", (*registry.AGENT_PROVIDERS, NEW))+ return NEW+++class TestANewProvider:+ """A provider added with nothing but an id and a label."""++ def test_its_defaults(self, new_provider: AgentProvider) -> None:+ assert new_provider.known_agent_type == "newcli"+ assert new_provider.connector_type == "New CLI"+ assert new_provider.advanced_fields == ()+ assert new_provider.tools == ()+ assert new_provider.session_start == ConsoleStart(+ runtime=None, sign_in_command=None+ )+ assert provider_ids()[-1] == "newcli"++ async def test_it_is_served_in_the_provider_list(+ self, new_provider: AgentProvider+ ) -> None:+ app = FastAPI()+ app.include_router(providers_router, prefix="/gateway")+ app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id="u")+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as client:+ providers = await client.get("/gateway/management/providers")+ advanced = await client.get("/gateway/management/advanced-config")+ assert providers.status_code == 200, providers.text+ assert providers.json()["providers"][-1] == {+ "id": "newcli",+ "label": "New CLI",+ "advanced_fields": [],+ }+ assert advanced.json()["providers"]["newcli"] == {"fields": []}++ def test_it_has_an_empty_advanced_configuration(+ self, new_provider: AgentProvider+ ) -> None:+ assert advanced_config_schema()["providers"]["newcli"] == {"fields": []}+ assert provider_fields("newcli") == []+ validate_advanced_config("newcli", {})+ with pytest.raises(ValueError, match="it has no advanced configuration"):+ validate_advanced_config("newcli", {"effort": "high"})++ def test_a_definition_may_name_it(self, new_provider: AgentProvider) -> None:+ assert DefinitionV1(provider="newcli").provider == "newcli"+ with pytest.raises(ValidationError, match="newcli has no setting 'effort'"):+ DefinitionV1(provider="newcli", advanced_config={"effort": "high"})++ def test_it_gets_a_known_agent(self, new_provider: AgentProvider) -> None:+ spec = known_agents()["newcli"]+ assert isinstance(spec, GenericKnownAgent)+ assert provider_known_agent("newcli").connector_type == "New CLI"+ assert spec.connector_type == "New CLI"+ assert spec.tools == []+ options = spec.parse_options({"repo_dir": "/r", "channels_enabled": True})+ assert options.model_dump() == {"auto_session": False, "repo_dir": "/r"}+ assert spec.build_profile(options).connection_model == "session_addressable"+ agent = SimpleNamespace(+ name="new.agent",+ metadata_={"known_agent_type": "newcli", "known_agent_options": {}},+ )+ assert spec.connect_command(options, agent, "hub", None) is None # type: ignore[arg-type]+ assert spec.start_session_instructions(options, agent, "hub", None) == ( # type: ignore[arg-type]+ "open **new.agent** in Switch Console and start a local session in **hub**."+ )+ resolved = known_agent_for(agent) # type: ignore[arg-type]+ assert resolved is not None+ assert resolved[0].provider is new_provider++ def test_a_managed_agent_registers_through_it(+ self, new_provider: AgentProvider+ ) -> None:+ spec, options, metadata = _known_agent_registration(+ DefinitionV1(provider="newcli", directory="/w"), None+ )+ assert spec.provider is new_provider+ assert metadata == {+ "known_agent_type": "newcli",+ "known_agent_options": {"auto_session": True, "repo_dir": "/w"},+ }diff --git a/docs/design/agent-controllers-v1.md b/docs/design/agent-controllers-v1.mdindex 73e12f5f2..d3257e829 100644--- a/docs/design/agent-controllers-v1.md+++ b/docs/design/agent-controllers-v1.md@@ -171,7 +171,10 @@ Controller access token (`{id}` must match the token's `cid`, otherwise `403 for- `POST /gateway/management/operations` and `GET /gateway/management/operations?controller_id=`.- `GET /gateway/management/advanced-config` returns each provider's advanced-configurationschema, `{"providers": {"claude": {"fields": [...]}, "codex": ..., "opencode": ...,- "cursor": {"fields": []}, "antigravity": {"fields": []}}}` (see Advanced configuration below).+ "cursor": {"fields": []}, "antigravity": {"fields": []}}}` (see Advanced configuration below),+ and `GET /gateway/management/providers` the providers in order, each with its label and the+ same fields. These two are served whether or not agent management is on: Switch Console+ builds the advanced-configuration form of the agents it runs itself from them too.**Placement checks** run on create, adopt and move, and on a change to `running`. Each failure returns `409` with a reason:- `controller_revoked`@@ -205,8 +208,11 @@ Any change that affects a controller bumps its `assignment_revision` and nudgesSwitch Console offers for its own agents. The server owns one fixed schema per provider(`management/advanced_config.py`), checks every create and update against it whatevermachine runs the agent, and serves it at `GET /gateway/management/advanced-config` and-through the `get_advanced_config(provider)` agent operation. Controllers report nothing-about settings; they apply what they are given.+through the `get_advanced_config(provider)` agent operation. Switch Console and the+controller hold no copy of the fields; their provider plugins only apply values, by key.+Controllers report nothing about settings; they apply what they are given, and report+`definition_invalid` for a key their build does not apply or a value of a shape it cannot+apply, rather than starting the agent without it.- Each served field is `{key, label, type, help, placeholder, options, catalogue}`. `type`is `text` or `textarea` (a string), `number` (finite), `boolean`, `list` (strings) ordiff --git a/gateway/src/data/management.test.ts b/gateway/src/data/management.test.tsindex 7964dc128..59327edff 100644--- a/gateway/src/data/management.test.ts+++ b/gateway/src/data/management.test.ts@@ -4,7 +4,9 @@ import {createManagedAgent,enrollCommand,fetchManagementAvailable,+ fetchProviders,managementError,+ providerLabel,shellQuote,} from "./management";@@ -133,3 +135,22 @@ describe("shellQuote", () => {expect(shellQuote("")).toBe("''");});});++describe("fetchProviders", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("reads the provider list the server serves", async () => {+ const providers = [{ id: "codex", label: "Codex", advanced_fields: [] }];+ const fetch = respond(200, { providers });+ await expect(fetchProviders()).resolves.toEqual(providers);+ expect(fetch).toHaveBeenCalledWith("/gateway/management/providers", expect.anything());+ });+});++describe("providerLabel", () => {+ it("is the listed label, else the id", () => {+ const providers = [{ id: "codex", label: "Codex", advanced_fields: [] }];+ expect(providerLabel(providers, "codex")).toBe("Codex");+ expect(providerLabel(providers, "newcli")).toBe("newcli");+ });+});diff --git a/gateway/src/data/management.ts b/gateway/src/data/management.tsindex 68a1015df..7d893c5b5 100644--- a/gateway/src/data/management.ts+++ b/gateway/src/data/management.ts@@ -1,18 +1,32 @@// Agent management: the machines (agent controllers) that run managed agents,// the agents placed on them, and the operations sent to them. Served under-// /gateway/management only when the server turns on its agent_management flag;-// every failure comes back as {"error": {"code", "message", "retryable"}}.+// /gateway/management only when the server turns on its agent_management flag,+// except the provider list and advanced-configuration fields, which are always+// served; every failure comes back as {"error": {"code", "message", "retryable"}}.const BASE = "/gateway/management";-export type Provider = "claude" | "codex" | "opencode" | "antigravity" | "cursor";-export const PROVIDERS: { value: Provider; label: string }[] = [- { value: "claude", label: "Claude Code" },- { value: "codex", label: "Codex" },- { value: "opencode", label: "OpenCode" },- { value: "antigravity", label: "Antigravity" },- { value: "cursor", label: "Cursor CLI" },-];+/** A provider's id, one of those `fetchProviders` lists. */+export type Provider = string;++/** One field of a provider's advanced configuration, as the server describes it. */+export interface AdvancedField {+ key: string;+ label: string;+ type: "text" | "textarea" | "number" | "boolean" | "list" | "select";+ help: string | null;+ placeholder: string | null;+ /** A select's choices, the first (value "") meaning unset; null for other types. */+ options: { value: string; label: string }[] | null;+ catalogue: { kind: "model" | "model-variant"; model_field?: string } | null;+}++/** A provider a definition can name. */+export interface ProviderInfo {+ id: Provider;+ label: string;+ advanced_fields: AdvancedField[];+}export type DesiredState = "running" | "stopped";export type Isolation = "shared" | "isolated";@@ -236,6 +250,16 @@ export async function revokeController(controllerId: string): Promise<void> {});}+/** Every provider the server runs, in the order to offer them. */+export async function fetchProviders(): Promise<ProviderInfo[]> {+ return (await request<{ providers: ProviderInfo[] }>("/providers")).providers;+}++/** The provider's label, or its id when the server does not list it. */+export function providerLabel(providers: ProviderInfo[], provider: Provider): string {+ return providers.find((p) => p.id === provider)?.label ?? provider;+}+export function fetchManagedAgents(): Promise<ManagedAgent[]> {return request<ManagedAgent[]>("/agents");}diff --git a/gateway/src/pages/machines/MachinesPage.test.tsx b/gateway/src/pages/machines/MachinesPage.test.tsxindex 4bd07da74..21302f23f 100644--- a/gateway/src/pages/machines/MachinesPage.test.tsx+++ b/gateway/src/pages/machines/MachinesPage.test.tsx@@ -1,6 +1,6 @@import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";-import type { Controller, ManagedAgent } from "../../data/management";+import type { Controller, ManagedAgent, ProviderInfo } from "../../data/management";import MachinesPage from "./MachinesPage";const laptop: Controller = {@@ -94,9 +94,16 @@ const pmAgent: ManagedAgent = {updated_at: "2026-10-01T00:00:00Z",};+const servedProviders: ProviderInfo[] = [+ { id: "claude", label: "Claude Code", advanced_fields: [] },+ { id: "codex", label: "Codex", advanced_fields: [] },+];+type Call = { path: string; method: string; body: unknown };+/** The management routes, answering GET /providers with `servedProviders` unless `routes` says otherwise. */function mockManagement(routes: Record<string, [number, unknown]>) {+ routes = { "GET /providers": [200, { providers: servedProviders }], ...routes };const calls: Call[] = [];vi.stubGlobal("fetch",@@ -295,4 +302,50 @@ describe("MachinesPage", () => {await screen.findByText("The machine laptop has not reported recently."),).toBeTruthy();});++ it("labels and offers the providers the server lists", async () => {+ mockManagement({+ "GET /providers": [+ 200,+ {+ providers: [+ ...servedProviders,+ { id: "newcli", label: "New CLI", advanced_fields: [] },+ ],+ },+ ],+ "GET /controllers": [+ 200,+ [+ {+ ...laptop,+ status: {+ ...laptop.status!,+ providers: [{ ...laptop.status!.providers[0]!, provider: "newcli" }],+ },+ },+ ],+ ],+ "GET /agents": [200, []],+ "GET /operations": [200, []],+ });+ render(<MachinesPage />);+ expect(await screen.findByText("New CLI")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "New managed agent" }));+ fireEvent.mouseDown(await screen.findByRole("combobox", { name: "Provider" }));+ const options = (await screen.findAllByRole("option")).map((o) => o.textContent);+ expect(options).toEqual(["Claude Code", "Codex", "New CLI"]);+ });++ it("says when the provider list cannot load, and shows providers by id", async () => {+ mockManagement({+ "GET /providers": [500, { detail: "boom" }],+ "GET /controllers": [200, [laptop]],+ "GET /agents": [200, [pmAgent]],+ "GET /operations": [200, []],+ });+ render(<MachinesPage />);+ expect(await screen.findByText(/Could not load the providers this server runs/)).toBeTruthy();+ expect(await screen.findByText("codex: login expired")).toBeTruthy();+ });});diff --git a/gateway/src/pages/machines/MachinesPage.tsx b/gateway/src/pages/machines/MachinesPage.tsxindex 8d201060a..b8569d27d 100644--- a/gateway/src/pages/machines/MachinesPage.tsx+++ b/gateway/src/pages/machines/MachinesPage.tsx@@ -35,8 +35,10 @@ import {type ManagedAgent,ManagementApiError,type Operation,- PROVIDERS,+ fetchProviders,+ type ProviderInfo,type ProviderStatus,+ providerLabel,revokeController,unmanageAgent,updateManagedAgent,@@ -102,11 +104,7 @@ const PROCESS_COLOR: Record<string, "success" | "warning" | "error" | "default">failed: "error",};-function providerLabel(provider: string): string {- return PROVIDERS.find((p) => p.value === provider)?.label ?? provider;-}--function providerChip(status: ProviderStatus) {+function providerChip(status: ProviderStatus, label: (provider: string) => string) {const ok = status.installed && status.auth === "ok";const problem = !status.installed? "not installed"@@ -126,7 +124,7 @@ function providerChip(status: ProviderStatus) {size="small"variant="outlined"color={ok ? "success" : status.installed ? "warning" : "default"}- label={problem ? `${providerLabel(status.provider)}: ${problem}` : providerLabel(status.provider)}+ label={problem ? `${label(status.provider)}: ${problem}` : label(status.provider)}/></Tooltip>);@@ -149,6 +147,8 @@ export default function MachinesPage() {const [controllers, setControllers] = useState<Controller[] | null>(null);const [agents, setAgents] = useState<ManagedAgent[] | null>(null);const [operations, setOperations] = useState<Operation[] | null>(null);+ const [providers, setProviders] = useState<ProviderInfo[] | null>(null);+ const [providersError, setProvidersError] = useState<string | null>(null);const [loadError, setLoadError] = useState<string | null>(null);const [notice, setNotice] = useState<{ severity: "success" | "error"; text: string } | null>(null,@@ -186,6 +186,19 @@ export default function MachinesPage() {return () => clearInterval(timer);}, [load]);+ useEffect(() => {+ fetchProviders().then(setProviders, (err) =>+ setProvidersError(+ `Could not load the providers this server runs, so providers show by id: ${errorMessage(err)}`,+ ),+ );+ }, []);++ const label = useCallback(+ (provider: string) => providerLabel(providers ?? [], provider),+ [providers],+ );+const act = useCallback(async (what: string, action: () => Promise<unknown>) => {setBusy(true);@@ -265,9 +278,9 @@ export default function MachinesPage() {const missing = row.status.providers.filter((p) => !p.installed);return (<Stack direction="row" spacing={0.5} alignItems="center" sx={{ height: "100%", overflow: "hidden" }}>- {installed.map(providerChip)}+ {installed.map((status) => providerChip(status, label))}{missing.length > 0 && (- <Tooltip title={`Not installed: ${missing.map((p) => providerLabel(p.provider)).join(", ")}`}>+ <Tooltip title={`Not installed: ${missing.map((p) => label(p.provider)).join(", ")}`}><Typography variant="body2" color="text.secondary" sx={{ whiteSpace: "nowrap" }}>+{missing.length} not installed</Typography>@@ -367,7 +380,7 @@ export default function MachinesPage() {},},],- [act, busy],+ [act, busy, label],);const agentColumns = useMemo<GridColDef<ManagedAgent>[]>(@@ -377,7 +390,7 @@ export default function MachinesPage() {field: "provider",headerName: "Provider",width: 130,- valueGetter: (_value, row) => providerLabel(row.definition.provider),+ valueGetter: (_value, row) => label(row.definition.provider),},{field: "controller_id",@@ -531,7 +544,7 @@ export default function MachinesPage() {},},],- [act, busy, controllerName],+ [act, busy, controllerName, label],);const agentName = useCallback(@@ -550,7 +563,7 @@ export default function MachinesPage() {minWidth: 160,valueGetter: (_value, row) =>agentName(row.agent_id) ??- `${controllerName(row.controller_id)}${row.params.provider ? ` · ${providerLabel(String(row.params.provider))}` : ""}`,+ `${controllerName(row.controller_id)}${row.params.provider ? ` · ${label(String(row.params.provider))}` : ""}`,},{field: "outcome",@@ -570,7 +583,7 @@ export default function MachinesPage() {),},],- [agentName, controllerName],+ [agentName, controllerName, label],);const recentOperations = useMemo(@@ -590,6 +603,7 @@ export default function MachinesPage() {{loadError}</Alert>)}+ {providersError && !loadError && <Alert severity="warning">{providersError}</Alert>}<Box><Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>@@ -658,6 +672,7 @@ export default function MachinesPage() {open={editing !== null}agent={editing === "new" ? null : editing}controllers={controllers ?? []}+ providers={providers ?? []}onClose={() => setEditing(null)}onSaved={() => void load()}/>diff --git a/gateway/src/pages/machines/ManagedAgentDialog.tsx b/gateway/src/pages/machines/ManagedAgentDialog.tsxindex cb1913fb1..f90744a8c 100644--- a/gateway/src/pages/machines/ManagedAgentDialog.tsx+++ b/gateway/src/pages/machines/ManagedAgentDialog.tsx@@ -20,8 +20,8 @@ import {type Isolation,type DesiredState,type ManagedAgent,- PROVIDERS,type Provider,+ type ProviderInfo,updateManagedAgent,} from "../../data/management";@@ -42,7 +42,11 @@ interface Form {running: boolean;}-function initialForm(agent: ManagedAgent | null, controllers: Controller[]): Form {+function initialForm(+ agent: ManagedAgent | null,+ controllers: Controller[],+ providers: ProviderInfo[],+): Form {if (agent)return {name: agent.name,@@ -62,7 +66,7 @@ function initialForm(agent: ManagedAgent | null, controllers: Controller[]): Forname: "",description: "",controllerId: online?.id ?? "",- provider: "claude",+ provider: providers[0]?.id ?? "",model: "",instructions: "",directory: "",@@ -95,6 +99,7 @@ export default function ManagedAgentDialog({open,agent,controllers,+ providers,onClose,onSaved,}: {@@ -102,16 +107,18 @@ export default function ManagedAgentDialog({/** The agent to edit, or null to create one. */agent: ManagedAgent | null;controllers: Controller[];+ /** The providers the server runs; empty until they have loaded. */+ providers: ProviderInfo[];onClose: () => void;onSaved: () => void;}) {- const [form, setForm] = useState<Form>(() => initialForm(agent, controllers));+ const [form, setForm] = useState<Form>(() => initialForm(agent, controllers, providers));const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);useEffect(() => {if (!open) return;- setForm(initialForm(agent, controllers));+ setForm(initialForm(agent, controllers, providers));setError(null);// Reset only when the dialog opens or switches agent, not on every status refresh.}, [open, agent?.agent_id]);@@ -124,7 +131,15 @@ export default function ManagedAgentDialog({);const nameValid = agent !== null || NAME_PATTERN.test(form.name);const canSave =- nameValid && (agent !== null || form.description.trim() !== "") && !saving;+ nameValid &&+ (agent !== null || form.description.trim() !== "") &&+ form.provider !== "" &&+ !saving;+ // An agent keeps its provider even if the server no longer lists it.+ const providerChoices =+ form.provider === "" || providers.some((p) => p.id === form.provider)+ ? providers+ : [...providers, { id: form.provider, label: form.provider, advanced_fields: [] }];const save = async () => {setSaving(true);@@ -206,9 +221,10 @@ export default function ManagedAgentDialog({label="Provider"value={form.provider}onChange={(e) => set("provider", e.target.value as Provider)}+ helperText={providers.length === 0 ? "Loading the providers this server runs…" : undefined}>- {PROVIDERS.map((p) => (- <MenuItem key={p.value} value={p.value}>+ {providerChoices.map((p) => (+ <MenuItem key={p.id} value={p.id}>{p.label}</MenuItem>))}