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
Managed Codex agents can write in their workspace; provider versions read with a home (#757)
Louis Amaudruz91857eefdb3c
diff --git a/console/packages/agent-controller/src/doctor.test.ts b/console/packages/agent-controller/src/doctor.test.tsindex 9bbced521..7706caad7 100644--- a/console/packages/agent-controller/src/doctor.test.ts+++ b/console/packages/agent-controller/src/doctor.test.ts@@ -20,7 +20,9 @@ function inputs(overrides: Partial<DoctorInputs> = {}): DoctorInputs {bundle: () => '/opt/shared-host.mjs',exchange: async () => ({}),locate: async (provider) =>- provider === 'claude' ? { path: '/usr/bin/claude', version: '2.1.0' } : null,+ provider === 'claude'+ ? { path: '/usr/bin/claude', version: '2.1.0', versionProblem: null }+ : null,probe: async () => ({ status: 'authenticated', message: 'Signed in.', models: [] }),service: async () => 'running',latest: async () => ({ version: '0.2.0', packageUrl: 'https://example.invalid/p.tgz' }),diff --git a/console/packages/agent-controller/src/main.ts b/console/packages/agent-controller/src/main.tsindex 70419e032..ab57458d9 100644--- a/console/packages/agent-controller/src/main.ts+++ b/console/packages/agent-controller/src/main.ts@@ -1,7 +1,7 @@import { spawn } from 'node:child_process';import { realpathSync } from 'node:fs';import { hostname } from 'node:os';-import { resolve } from 'node:path';+import { join, resolve } from 'node:path';import { parseArgs } from 'node:util';import { generateSealingKeyPair } from '@switch-console/agent-providers';import packageJson from '../package.json' with { type: 'json' };@@ -442,7 +442,7 @@ async function runCommand(args: string[]): Promise<number> {}),new DetachedRuntime({ layout, bundlePath: sharedHostBundle })),- locator: new PathProviderLocator(process.env.PATH),+ locator: new PathProviderLocator(process.env.PATH, join(dataDir, 'version-probe')),fetch,openWebSocket: nodeWebSocket,log,@@ -707,7 +707,7 @@ async function doctorCommand(args: string[]): Promise<number> {strict: true,});const { dataDir, store, secrets } = await openState(values['data-dir']);- const locator = new PathProviderLocator(process.env.PATH);+ const locator = new PathProviderLocator(process.env.PATH, join(dataDir, 'version-probe'));try {const separateUsers = await findSeparateUsersConfig(currentUid(), dataDir);const separateRuntime = separateUsersdiff --git a/console/packages/agent-controller/src/schemas.ts b/console/packages/agent-controller/src/schemas.tsindex 1a4065029..148a65ef2 100644--- a/console/packages/agent-controller/src/schemas.ts+++ b/console/packages/agent-controller/src/schemas.ts@@ -203,6 +203,10 @@ export const providerStatusSchema = z.object({auth_source: z.enum(['local', 'sealed']).nullable(),checked_at: time,reason: reasonCode.optional(),+ /** Why no version was read from an installed CLI. */+ version_problem: z.string().max(300).optional(),+ /** Why a login given to the machine is not used, in the controller's words. */+ auth_problem: z.string().max(300).optional(),});export type ProviderStatus = z.infer<typeof providerStatusSchema>;diff --git a/console/packages/agent-controller/src/status.test.ts b/console/packages/agent-controller/src/status.test.tsindex 1d3a268a3..22a12eb51 100644--- a/console/packages/agent-controller/src/status.test.ts+++ b/console/packages/agent-controller/src/status.test.ts@@ -185,7 +185,7 @@ describe('mapAgentProcess', () => {describe('providerStatusFrom', () => {const at = '2026-01-01T00:00:00Z';- const located = { path: '/usr/bin/claude', version: '2.0.0' };+ const located = { path: '/usr/bin/claude', version: '2.0.0', versionProblem: null };const readiness = (status: 'authenticated' | 'unauthenticated' | 'unconfigured' | 'unknown') => ({status,message: '',@@ -340,11 +340,13 @@ describe('ProviderStatuses with logins given to the machine', () => {answer = sealedAnswer('sk-ant-oat-expired');runtime.loginReadiness = { status: 'unauthenticated', message: 'Token expired.', models: [] };- expect(await statuses.check('claude')).toMatchObject({+ const expired = await statuses.check('claude');+ expect(expired).toMatchObject({auth: 'expired',auth_source: 'sealed',reason: 'provider_login_expired',});+ expect(expired.auth_problem).toContain('Token expired.');expect(statuses.loginProblem('claude')?.message).toContain('Token expired.');expect(await statuses.givenLogin('claude')).toBeNull();@@ -382,11 +384,57 @@ describe('PathProviderLocator', () => {writeFileSync(script, '#!/bin/sh\necho "2026.01.15-abc"\n');chmodSync(script, 0o755);writeFileSync(join(dir, 'claude'), 'not executable');- const locator = new PathProviderLocator(`/nonexistent:${dir}`);- expect(await locator.locate('cursor')).toEqual({ path: script, version: '2026.01.15-abc' });+ const locator = new PathProviderLocator(`/nonexistent:${dir}`, join(dir, 'probe-home'));+ expect(await locator.locate('cursor')).toEqual({+ path: script,+ version: '2026.01.15-abc',+ versionProblem: null,+ });expect(await locator.locate('claude')).toBeNull();expect(await locator.locate('codex')).toBeNull();});++ it('reads the version of a CLI that writes in its home first, with a home of its own', async () => {+ const script = join(dir, 'opencode');+ writeFileSync(+ script,+ '#!/bin/sh\nmkdir -p "$XDG_DATA_HOME/opencode" "$HOME/.cache" || exit 1\necho 1.18.35\n'+ );+ chmodSync(script, 0o755);+ const previous = process.env.HOME;+ process.env.HOME = '/nonexistent';+ try {+ const located = await new PathProviderLocator(dir, join(dir, 'probe-home')).locate(+ 'opencode'+ );+ expect(located).toEqual({ path: script, version: '1.18.35', versionProblem: null });+ } finally {+ process.env.HOME = previous;+ }+ });+});++describe('a CLI whose version cannot be read', () => {+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'controller-version-'));+ });+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it('says why, so the report can carry it', async () => {+ const script = join(dir, 'opencode');+ writeFileSync(script, '#!/bin/sh\necho "EROFS: read-only file system" >&2\nexit 1\n');+ chmodSync(script, 0o755);+ const located = await new PathProviderLocator(dir, join(dir, 'probe-home')).locate('opencode');+ expect(located).toEqual({+ path: script,+ version: null,+ versionProblem: 'exited 1: EROFS: read-only file system',+ });+ expect(+ providerStatusFrom('opencode', located, null, '2026-01-01T00:00:00Z').version_problem+ ).toBe('exited 1: EROFS: read-only file system');+ });});describe('StatusCollector', () => {diff --git a/console/packages/agent-controller/src/status.ts b/console/packages/agent-controller/src/status.tsindex b2f7ac7bf..d7beba8b8 100644--- a/console/packages/agent-controller/src/status.ts+++ b/console/packages/agent-controller/src/status.ts@@ -1,6 +1,6 @@import { execFile } from 'node:child_process';import { constants } from 'node:fs';-import { access, statfs } from 'node:fs/promises';+import { access, mkdir, statfs } from 'node:fs/promises';import { arch, freemem, platform, release, totalmem } from 'node:os';import { delimiter, join } from 'node:path';import { promisify } from 'node:util';@@ -25,7 +25,8 @@ import type { GivenLogin, LoginProblem, SealedLogins } from './sealed-logins';import type { AgentRow, ControllerStore } from './store';export const PROVIDER_TTL_MS = 10 * 60 * 1000;-const VERSION_TIMEOUT_MS = 10_000;+// A first run may unpack the CLI's own runtime (OpenCode's Bun) before printing.+const VERSION_TIMEOUT_MS = 30_000;const DETAIL_LIMIT = 1000;/** A launch this recent with nothing alive yet is still starting, not crashed. */export const LAUNCH_GRACE_MS = 15_000;@@ -39,7 +40,12 @@ export function contractPlatform(): Platform {};}-export type LocatedProvider = { path: string; version: string | null };+/** A provider's CLI, its version, and why none was read when it was not. */+export type LocatedProvider = {+ path: string;+ version: string | null;+ versionProblem: string | null;+};/** Finds a provider's CLI on this machine. */export interface ProviderLocator {@@ -51,7 +57,16 @@ export interface ProviderLocator {* as Console's dependency detection does, and asks it for its version.*/export class PathProviderLocator implements ProviderLocator {- constructor(private readonly path: string | undefined) {}+ /**+ * `probeHome` is the home CLIs run with to print their version: some+ * (OpenCode) write there before printing, and the controller's user may have+ * none it can write in. Kept between probes, so a runtime a CLI unpacks on+ * its first run is unpacked once.+ */+ constructor(+ private readonly path: string | undefined,+ private readonly probeHome: string+ ) {}async locate(provider: Provider): Promise<LocatedProvider | null> {const plugin = pluginRegistry.get(provider);@@ -66,28 +81,71 @@ export class PathProviderLocator implements ProviderLocator {} catch {continue;}+ if (dependency.skipVersionProbe)+ return { path: candidate, version: null, versionProblem: null };return {path: candidate,- version: dependency.skipVersionProbe- ? null- : await readVersion(candidate, dependency.versionArgs ?? ['--version']),+ ...(await readVersion(+ candidate,+ dependency.versionArgs ?? ['--version'],+ this.probeHome+ )),};}return null;}}-async function readVersion(binary: string, args: string[]): Promise<string | null> {+/** The version a CLI prints, or why none could be read. */+async function readVersion(+ binary: string,+ args: string[],+ home: string+): Promise<{ version: string | null; versionProblem: string | null }> {try {+ await mkdir(home, { recursive: true, mode: 0o700 });const { stdout, stderr } = await promisify(execFile)(binary, args, {timeout: VERSION_TIMEOUT_MS,+ env: {+ ...process.env,+ HOME: home,+ XDG_CONFIG_HOME: join(home, '.config'),+ XDG_DATA_HOME: join(home, '.local', 'share'),+ XDG_STATE_HOME: join(home, '.local', 'state'),+ XDG_CACHE_HOME: join(home, '.cache'),+ },});- return `${stdout}\n${stderr}`.match(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/)?.[0] ?? null;- } catch {- return null;+ const output = `${stdout}\n${stderr}`;+ const version = output.match(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/)?.[0] ?? null;+ return version+ ? { version, versionProblem: null }+ : { version: null, versionProblem: `printed no version: ${lastLine(output)}` };+ } catch (error) {+ const failed = error as NodeJS.ErrnoException & {+ killed?: boolean;+ code?: number | string;+ stderr?: string;+ stdout?: string;+ };+ const versionProblem = failed.killed+ ? `timed out after ${VERSION_TIMEOUT_MS / 1000} s`+ : typeof failed.code === 'number'+ ? `exited ${failed.code}: ${lastLine(`${failed.stdout ?? ''}\n${failed.stderr ?? ''}`)}`+ : errorMessage(error);+ return { version: null, versionProblem: versionProblem.slice(0, 300) };}}+function lastLine(output: string): string {+ return (+ output+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)+ .at(-1) ?? '(nothing)'+ );+}+export function providerStatusFrom(provider: Provider,located: LocatedProvider | null,@@ -104,7 +162,13 @@ export function providerStatusFrom(checked_at: checkedAt,reason: 'provider_not_installed',};- const base = { provider, installed: true, version: located.version, checked_at: checkedAt };+ const base = {+ provider,+ installed: true,+ version: located.version,+ ...(located.versionProblem ? { version_problem: located.versionProblem } : {}),+ checked_at: checkedAt,+ };if (!readiness) return { ...base, auth: 'unknown', auth_source: null, reason: 'internal' };switch (readiness.status) {case 'authenticated':@@ -191,10 +255,13 @@ export class ProviderStatuses {auth: 'expired',auth_source: 'sealed',reason: 'provider_login_expired',+ auth_problem: problem.message.slice(0, 300),};}- } else if (given) problem = given.problem;- else {+ } else if (given) {+ problem = given.problem;+ if (problem) status = { ...status, auth_problem: problem.message.slice(0, 300) };+ } else {const held = this.entries.get(provider);login = held?.login ?? null;problem = held?.problem ?? null;@@ -204,6 +271,7 @@ export class ProviderStatuses {auth: held.status.auth,auth_source: 'sealed',reason: held.status.reason,+ ...(held.status.auth_problem ? { auth_problem: held.status.auth_problem } : {}),};}}diff --git a/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts b/console/packages/agent-controller/src/systemd-runtime.e2e.test.tsindex f4df3498e..493139758 100644--- a/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts+++ b/console/packages/agent-controller/src/systemd-runtime.e2e.test.ts@@ -129,7 +129,9 @@ describe.skipIf(!dataDir)('agents as users of their own, under systemd', () => {}),locator: {locate: async (provider) =>- provider === 'claude' ? { path: fakeClaude, version: '2.0.0' } : null,+ provider === 'claude'+ ? { path: fakeClaude, version: '2.0.0', versionProblem: null }+ : null,},fetch,openWebSocket: core.openWebSocket,diff --git a/console/packages/agent-controller/src/systemd-runtime.ts b/console/packages/agent-controller/src/systemd-runtime.tsindex 029d02601..f624f3594 100644--- a/console/packages/agent-controller/src/systemd-runtime.ts+++ b/console/packages/agent-controller/src/systemd-runtime.ts@@ -213,7 +213,13 @@ export class SystemdRuntime implements AgentRuntime {message: `${binaryPath} is under ${home}, which agents running as users of their own cannot reach. Install the ${provider} CLI system-wide.`,models: [],};- const probeHome = join(this.deps.config.dataDir, 'probe-home');+ // A login given to the machine is checked in a home of its own: a CLI may+ // keep what it signed in with there (Cursor does), and a check of the+ // machine's own login in the same home would then pass although no agent,+ // each a user of its own, can use it.+ const probeHome = login+ ? join(this.deps.config.dataDir, 'login-check', provider, 'home')+ : join(this.deps.config.dataDir, 'probe-home-local');await mkdir(probeHome, { recursive: true, mode: 0o700 });const given = login? await loginProbeEnvironment(diff --git a/console/packages/agent-controller/src/template.test.ts b/console/packages/agent-controller/src/template.test.tsindex 28fbd0f94..668fb15e9 100644--- a/console/packages/agent-controller/src/template.test.ts+++ b/console/packages/agent-controller/src/template.test.ts@@ -47,7 +47,10 @@ describe('buildWatcherTemplate', () => {expect(template.execution).toMatchObject({credentialsPath: '/data/agents/agent-1/credentials.json',binaryPath: `/usr/bin/${provider}`,- codexConfig: provider === 'codex' ? 'developer_instructions = "Review pull requests."\n' : '',+ codexConfig:+ provider === 'codex'+ ? 'sandbox_mode = "workspace-write"\ndeveloper_instructions = "Review pull requests."\n'+ : '',});expect(template.execution!.inheritEnv).toEqual(expect.arrayContaining(['PATH', 'HOME', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY'])@@ -110,7 +113,9 @@ describe('buildWatcherTemplate', () => {...advanced,});expect(template.start.input.model).toEqual({ id: 'gpt-5.5', options: { effort: 'high' } });- expect(template.execution!.codexConfig).toBe(console.codexConfig);+ expect(template.execution!.codexConfig).toBe(+ `sandbox_mode = "workspace-write"\n${console.codexConfig}`+ );expect(template.execution!.codexConfig).toContain('model_verbosity = "low"');expect(template.execution!.codexConfig).toContain('web_search = true');expect(template.start.input).not.toHaveProperty('agentDefinition');diff --git a/console/packages/agent-controller/src/template.ts b/console/packages/agent-controller/src/template.tsindex 7109b8c42..d54b14129 100644--- a/console/packages/agent-controller/src/template.ts+++ b/console/packages/agent-controller/src/template.ts@@ -11,6 +11,7 @@ import {type ProviderCapabilities,type SharedHostConfig,sharedConfigSchema,+ withManagedCodexSandbox,} from '@switch-console/agent-providers';import { advancedConfigProblem, sessionLaunchConfig } from '@switch-console/plugins/agents';import type { AgentDefinition, Provider } from './schemas';@@ -148,7 +149,10 @@ export function buildWatcherTemplate(input: {credentialsPath: input.credentialsPath,inheritEnv: [...EXECUTION_INHERIT_ENV],...(input.binaryPath ? { binaryPath: input.binaryPath } : {}),- codexConfig: launch.codexConfig,+ codexConfig:+ provider === 'codex'+ ? withManagedCodexSandbox(launch.codexConfig, input.definition.auto_approve)+ : launch.codexConfig,skill: launch.skill,context: launch.context,instructions: launch.instructions,diff --git a/console/packages/agent-controller/src/testing/fake-runtime.ts b/console/packages/agent-controller/src/testing/fake-runtime.tsindex f03c665fe..25826b7c3 100644--- a/console/packages/agent-controller/src/testing/fake-runtime.ts+++ b/console/packages/agent-controller/src/testing/fake-runtime.ts@@ -168,6 +168,6 @@ export class FakeLocator implements ProviderLocator {async locate(provider: Provider): Promise<LocatedProvider | null> {if (this.missing.has(provider)) return null;- return { path: `/usr/bin/${provider}`, version: '1.2.3' };+ return { path: `/usr/bin/${provider}`, version: '1.2.3', versionProblem: null };}}diff --git a/console/packages/agent-providers/src/antigravity/runtime.test.ts b/console/packages/agent-providers/src/antigravity/runtime.test.tsnew file mode 100644index 000000000..1d5f2ee70--- /dev/null+++ b/console/packages/agent-providers/src/antigravity/runtime.test.ts@@ -0,0 +1,47 @@+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';++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});++it('records the auth type where every Antigravity ACP version reads it, keeping one already there', async () => {+ const profile = await mkdtemp(join(tmpdir(), 'antigravity-profile-'));+ roots.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({+ 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' },+ });+ expect(await readFile(join(profile, 'antigravity-acp', 'settings.json'), 'utf8')).toBe(+ '{"auth":{"type":"kept"}}'+ );+});++it('counts a profile as signed in by the token --login writes, with a refresh token', async () => {+ const profile = await mkdtemp(join(tmpdir(), 'antigravity-token-'));+ roots.push(profile);+ expect(await antigravitySignedIn(profile)).toBe(false);+ await mkdir(join(profile, 'antigravity-acp'), { recursive: true });+ await writeFile(join(profile, 'antigravity-acp', 'acp_token.json'), '{"access_token":"a"}');+ expect(await antigravitySignedIn(profile)).toBe(false);+ await writeFile(+ join(profile, 'antigravity-acp', 'acp_token.json'),+ '{"access_token":"a","refresh_token":"r"}'+ );+ expect(await antigravitySignedIn(profile)).toBe(true);+ expect(antigravityProfile({ GEMINI_HOME: profile, HOME: '/home/x' })).toBe(profile);+});diff --git a/console/packages/agent-providers/src/antigravity/runtime.ts b/console/packages/agent-providers/src/antigravity/runtime.tsindex 0ec66e7fb..a9537d6c8 100644--- a/console/packages/agent-providers/src/antigravity/runtime.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.ts@@ -1,4 +1,4 @@-import { mkdir, writeFile } from 'node:fs/promises';+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';@@ -6,6 +6,35 @@ import { StdioJsonRpcClient, type ProviderLogger } from '../transport/stdio-jsonexport 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.';+/** The Gemini home an Antigravity ACP server runs with: its sign-in and settings live under it. */+export function antigravityProfile(env: Record<string, string>): string {+ return (+ env.GEMINI_HOME || join(env.HOME || homedir(), '.local', 'state', 'switch', 'antigravity-acp')+ );+}++/**+ * Whether the profile holds a consumer sign-in: the token file `--login`+ * writes, with a refresh token in it. Antigravity ACP 1.3 lists every sign-in+ * method in `initialize` whether or not one is in use, so the handshake no+ * longer says; the token itself is checked when a session signs in with it.+ */+export async function antigravitySignedIn(profile: string): Promise<boolean> {+ let text: string;+ try {+ text = await readFile(join(profile, 'antigravity-acp', 'acp_token.json'), 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw error;+ }+ try {+ const token = JSON.parse(text) as Record<string, unknown> | null;+ return typeof token?.refresh_token === 'string' && token.refresh_token.length > 0;+ } catch {+ return false;+ }+}+export async function createAntigravityClient(input: {binaryPath: string;cwd: string;@@ -17,17 +46,20 @@ export async function createAntigravityClient(input: {throw new Error('The selected executable is the old Antigravity CLI. Install and select antigravity-acp in provider setup.');- const profile =- input.env.GEMINI_HOME ||- join(input.env.HOME || homedir(), '.local', 'state', 'switch', 'antigravity-acp');- await mkdir(profile, { recursive: true, mode: 0o700 });- await writeFile(- join(profile, 'settings.json'),- JSON.stringify({ auth: { type: 'oauth-personal' } }),- { mode: 0o600, flag: 'wx' }- ).catch((error: NodeJS.ErrnoException) => {- if (error.code !== 'EEXIST') throw error;- });+ const profile = antigravityProfile(input.env);+ // Antigravity ACP up to 1.1 reads its settings at the profile's root; 1.3+ // reads them beside its token, in `antigravity-acp/`. Without the auth type+ // recorded, a signed-in profile answers `initialize` as signed out.+ for (const directory of [profile, join(profile, 'antigravity-acp')]) {+ await mkdir(directory, { recursive: true, mode: 0o700 });+ await writeFile(+ join(directory, 'settings.json'),+ JSON.stringify({ auth: { type: 'oauth-personal' } }),+ { mode: 0o600, flag: 'wx' }+ ).catch((error: NodeJS.ErrnoException) => {+ if (error.code !== 'EEXIST') throw error;+ });+ }const raw = basename(input.binaryPath).startsWith('agy_acp_server');return new StdioJsonRpcClient({command: input.binaryPath,diff --git a/console/packages/agent-providers/src/codex/codex-adapter.test.ts b/console/packages/agent-providers/src/codex/codex-adapter.test.tsindex 4e93ea6da..7fcff39db 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.test.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.test.ts@@ -1,3 +1,6 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { beforeEach, describe, expect, it, vi } from 'vitest';import { ProviderConversationUnavailableError } from '../adapter';import type { ProviderRuntimeEvent, ProviderRuntimeEventType } from '../events';@@ -87,6 +90,34 @@ describe('CodexAdapter', () => {});});+ it('passes the sandbox its configuration names, on a resumed thread as on a new one', async () => {+ const home = await mkdtemp(join(tmpdir(), 'codex-home-'));+ try {+ await writeFile(join(home, 'config.toml'), 'sandbox_mode = "workspace-write"\n');+ const adapter = createCodexAdapter();+ const pending = adapter.startSession({+ sessionId: 'resumed',+ cwd: '/work',+ runtimeMode: 'full-access',+ env: { PATH: '/usr/bin', CODEX_HOME: home },+ mcpServers: {},+ resume: { nativeSessionId: THREAD },+ });+ const server = servers.at(-1)!;+ server.replyAlways('thread/resume', () => ({ thread: { id: THREAD } }));+ await pending;+ const resumed = server.received.find((message) => message.method === 'thread/resume');+ expect(resumed?.params).toMatchObject({+ threadId: THREAD,+ sandbox: 'workspace-write',+ approvalPolicy: 'never',+ });+ await adapter.stopAll();+ } finally {+ await rm(home, { recursive: true, force: true });+ }+ });+it('fails resume without silently opening a fresh thread', async () => {const adapter = createCodexAdapter();const pending = adapter.startSession({diff --git a/console/packages/agent-providers/src/codex/codex-adapter.ts b/console/packages/agent-providers/src/codex/codex-adapter.tsindex 7de53ce57..b053c447b 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.ts@@ -1,5 +1,7 @@import { randomUUID } from 'node:crypto';-import { basename } from 'node:path';+import { readFile } from 'node:fs/promises';+import { basename, join } from 'node:path';+import { parse } from 'smol-toml';import { z } from 'zod';import {type ModelSelection,@@ -39,6 +41,7 @@ import {CODEX_SERVER_NOTIFICATIONS,CODEX_SERVER_REQUESTS,type CodexAskForApproval,+ type CodexSandboxMode,type CodexThreadTokenUsageUpdatedNotification,type CodexTokenUsageBreakdown,type CodexCommandExecutionApprovalParams,@@ -134,6 +137,33 @@ function threadModeConfig(mode: RuntimeMode): ThreadModeConfig {}}+const SANDBOX_MODES = new Set<CodexSandboxMode>([+ 'read-only',+ 'workspace-write',+ 'danger-full-access',+]);++/**+ * The `sandbox_mode` the session's Codex configuration names, passed with the+ * thread as well: a resumed thread otherwise keeps the sandbox it started+ * with, whatever the configuration says now. Null when it names none, so Codex+ * applies its own default.+ */+async function configuredSandbox(codexHome: string | undefined): Promise<CodexSandboxMode | null> {+ if (!codexHome) return null;+ let text: string;+ try {+ text = await readFile(join(codexHome, 'config.toml'), 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+ const mode = parse(text).sandbox_mode;+ return typeof mode === 'string' && SANDBOX_MODES.has(mode as CodexSandboxMode)+ ? (mode as CodexSandboxMode)+ : null;+}+function sessionStatusOf(status: CodexThreadStatusChangedNotification['status']): SessionStatus {switch (status.type) {case 'idle':@@ -294,9 +324,11 @@ export class CodexAdapter implements ProviderAdapter {throw new Error('Sign in on the execution machine with codex login.');const mode = threadModeConfig(input.runtimeMode);+ const sandbox = await configuredSandbox(input.env.CODEX_HOME);const config = {cwd: input.cwd,approvalPolicy: mode.approvalPolicy,+ ...(sandbox ? { sandbox } : {}),approvalsReviewer: 'user' as const,...(input.model?.id ? { model: input.model.id } : {}),...(input.systemContext ? { developerInstructions: input.systemContext } : {}),diff --git a/console/packages/agent-providers/src/codex/home.test.ts b/console/packages/agent-providers/src/codex/home.test.tsindex 4323722e0..5eaca7e3d 100644--- a/console/packages/agent-providers/src/codex/home.test.ts+++ b/console/packages/agent-providers/src/codex/home.test.ts@@ -2,8 +2,8 @@ import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/import { tmpdir } from 'node:os';import { join } from 'node:path';import { parse } from 'smol-toml';-import { afterEach, expect, it } from 'vitest';-import { prepareCodexSessionHome } from './home';+import { afterEach, describe, expect, it } from 'vitest';+import { prepareCodexSessionHome, withManagedCodexSandbox } from './home';const roots: string[] = [];afterEach(async () => {@@ -88,3 +88,25 @@ it('links the user’s own Codex skills into a session home that has no skills f});expect(await readFile(join(home, 'skills', '.system', 'SKILL.md'), 'utf8')).toBe('system skill');});++describe('withManagedCodexSandbox', () => {+ it('lets a managed agent write in its workspace, or anywhere when it bypasses permissions', () => {+ expect(parse(withManagedCodexSandbox('web_search = true\n', false))).toEqual({+ sandbox_mode: 'workspace-write',+ web_search: true,+ });+ expect(parse(withManagedCodexSandbox('', true))).toEqual({+ sandbox_mode: 'danger-full-access',+ });+ });++ it('keeps a sandbox the configuration already names', () => {+ const config = 'sandbox_mode = "read-only"\n[mcp_servers.x]\ncommand = "x"\n';+ expect(withManagedCodexSandbox(config, true)).toBe(config);+ });++ it('puts the sandbox before any table, where TOML reads it as top level', () => {+ const merged = withManagedCodexSandbox('[mcp_servers.x]\ncommand = "x"\n', false);+ expect(parse(merged)).toMatchObject({ sandbox_mode: 'workspace-write' });+ });+});diff --git a/console/packages/agent-providers/src/codex/home.ts b/console/packages/agent-providers/src/codex/home.tsindex 68f76ecf8..0d2da09c4 100644--- a/console/packages/agent-providers/src/codex/home.ts+++ b/console/packages/agent-providers/src/codex/home.ts@@ -4,6 +4,20 @@ import { join } from 'node:path';import { parse, stringify } from 'smol-toml';import { linkHomeAsset, linkSkills, optionalText } from '../host/provider-home';+/**+ * A managed agent's Codex configuration with the sandbox its sessions run+ * in: Codex's default is read-only, which on a machine with no Codex+ * configuration of its own leaves an agent unable to write in its own+ * directory. An agent that bypasses permissions gets full access, any other+ * may write in its workspace; a `sandbox_mode` the configuration already+ * names is kept.+ */+export function withManagedCodexSandbox(config: string, autoApprove: boolean): string {+ if ('sandbox_mode' in parse(config)) return config;+ const mode = autoApprove ? 'danger-full-access' : 'workspace-write';+ return `sandbox_mode = "${mode}"\n${config}`;+}+/** Native rollouts remain in the persistent session directory on the execution host. */export async function prepareCodexSessionHome(input: {root: string;diff --git a/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts b/console/packages/agent-providers/src/cursor/cursor-adapter.test.tsindex 729e7eab6..15a1ee936 100644--- a/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts+++ b/console/packages/agent-providers/src/cursor/cursor-adapter.test.ts@@ -33,7 +33,7 @@ beforeEach(() => {servers.length = 0;acp.http = true;});-async function setup(resume = false) {+async function setup(resume = false, env: Record<string, string> = {}) {const adapter = createCursorAdapter();const events: ProviderRuntimeEvent[] = [];adapter.subscribe((e) => events.push(e));@@ -41,7 +41,7 @@ async function setup(resume = false) {sessionId: 's',cwd: '/work',runtimeMode: 'approval-required',- env: {},+ env,mcpServers: {switch: { transport: 'stdio', command: 'node', args: ['server.js'], env: { MODE: 'test' } },},@@ -52,6 +52,14 @@ async function setup(resume = false) {}const flush = () => new Promise((resolve) => setImmediate(resolve));+it('signs in with cursor_login only when it was given no API key', async () => {+ const signedIn = await setup();+ expect(signedIn.server.received.some((m) => m.method === 'authenticate')).toBe(true);+ const withKey = await setup(false, { CURSOR_API_KEY: 'crsr_synthetic' });+ expect(withKey.server.received.some((m) => m.method === 'authenticate')).toBe(false);+ expect(withKey.session.nativeSessionId).toBe('native');+});+it('registers session MCP servers and resumes the exact native session', async () => {const { server, session } = await setup(true);expect(session.nativeSessionId).toBe('native');diff --git a/console/packages/agent-providers/src/cursor/cursor-adapter.ts b/console/packages/agent-providers/src/cursor/cursor-adapter.tsindex c07df702f..09177c11f 100644--- a/console/packages/agent-providers/src/cursor/cursor-adapter.ts+++ b/console/packages/agent-providers/src/cursor/cursor-adapter.ts@@ -195,7 +195,10 @@ export class CursorAdapter implements ProviderAdapter {input.mcpServers,initialized.agentCapabilities?.mcpCapabilities?.http);- await client.request('authenticate', { methodId: 'cursor_login' });+ // 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'? {diff --git a/console/packages/agent-providers/src/host/agent-host.test.ts b/console/packages/agent-providers/src/host/agent-host.test.tsindex 8290a6397..12a293b59 100644--- a/console/packages/agent-providers/src/host/agent-host.test.ts+++ b/console/packages/agent-providers/src/host/agent-host.test.ts@@ -1380,7 +1380,7 @@ it('starts the session serving a room again when its host has gone, instead of aexpect((await AgentHostAssignments.open(root)).sessions()).toHaveLength(1);});-it('takes the model, approval mode, instructions and advanced configuration from the template, and nothing else', () => {+it('takes the model, approval mode, instructions and advanced configuration from the template', () => {const root = '/state';const edited = watchable(root);edited.start.input.model = { id: 'claude-sonnet-4-6', options: { effort: 'high' } };@@ -1429,6 +1429,31 @@ it('takes the model, approval mode, instructions and advanced configuration fromexpect(cleared.start.input).not.toHaveProperty('agentDefinition');});+it('gives a session the provider login its agent signs in with now, keeping its own id', () => {+ const root = '/state';+ const controller = watchable(root);+ controller.start.input.env = { CURSOR_API_KEY: 'crsr_given', SWITCHDASH_SESSION_ID: 'watcher' };+ const saved = watchable(root);+ saved.session = {+ ...saved.session,+ agentId: controller.session.agentId,+ sessionId: 'room-session',+ };+ saved.start.input.env = { SWITCHDASH_SESSION_ID: 'room-session', CURSOR_API_KEY: 'crsr_old' };++ const refreshed = withDefinitionOf(saved, controller);++ expect(definitionChanged(saved, controller)).toBe(true);+ expect(refreshed.start.input.env).toEqual({+ CURSOR_API_KEY: 'crsr_given',+ SWITCHDASH_SESSION_ID: 'room-session',+ });+ delete controller.start.input.env.CURSOR_API_KEY;+ expect(withDefinitionOf(refreshed, controller).start.input.env).toEqual({+ SWITCHDASH_SESSION_ID: 'room-session',+ });+});+it('gives a session the credentials and binary of whoever runs its watcher now', () => {const root = '/state';const controller = watchable(root);diff --git a/console/packages/agent-providers/src/host/agent-host.ts b/console/packages/agent-providers/src/host/agent-host.tsindex ba12d96f5..6cfd9edd8 100644--- a/console/packages/agent-providers/src/host/agent-host.ts+++ b/console/packages/agent-providers/src/host/agent-host.ts@@ -278,9 +278,9 @@ export async function stopSupersededSessions(* `config` with what its agent's definition decides — the model, the approval* mode, the instructions and skill the provider is given, and what the* agent's advanced configuration becomes: the agent definition Claude Code- * runs as and the Codex profile — and the credentials and provider binary of- * whoever runs the watcher, taken from the watcher's `template` as it stands- * now. Everything else stays the session's own: its identity,+ * runs as and the Codex profile — and the credentials, provider binary and+ * environment (where a provider login given since lives) of whoever runs the+ * watcher, taken from the watcher's `template` as it stands now. Everything else stays the session's own: its identity,* directory and native conversation, so a session started after its agent was* edited resumes its conversation under the edit instead of under what the* agent was when the session was first created.@@ -298,6 +298,13 @@ export function withDefinitionOf(if (model) next.start.input.model = structuredClone(model);else delete next.start.input.model;next.start.input.runtimeMode = template.start.input.runtimeMode;+ // The environment carries the provider login the agent signs in with: a+ // session created before a login was given, changed or withdrawn takes the+ // current one. Only the session's own id stays its own.+ const sessionId = next.start.input.env.SWITCHDASH_SESSION_ID;+ next.start.input.env = structuredClone(template.start.input.env);+ if (next.start.input.env.SWITCHDASH_SESSION_ID !== undefined && sessionId !== undefined)+ next.start.input.env.SWITCHDASH_SESSION_ID = sessionId;if (!next.execution?.agentDefinition) {const { agentName, agentDefinition } = template.start.input;if (agentName) next.start.input.agentName = agentName;diff --git a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.tsindex b187dd57f..560fdbb1b 100644--- a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts@@ -2,7 +2,12 @@ import { beforeEach, expect, it, vi } from 'vitest';import type * as Protocol from '../transport/stdio-json-rpc';import { JsonRpcError } from '../transport/stdio-json-rpc';import { checkProviderReadiness } from './provider-readiness';-const mock = vi.hoisted(() => ({ request: vi.fn(), dispose: vi.fn(), notify: vi.fn() }));+const mock = vi.hoisted(() => ({+ request: vi.fn(),+ dispose: vi.fn(),+ notify: vi.fn(),+ token: null as string | null,+}));vi.mock('../transport/stdio-json-rpc', async (original) => ({...(await original<typeof Protocol>()),StdioJsonRpcClient: class {@@ -14,10 +19,15 @@ vi.mock('../transport/stdio-json-rpc', async (original) => ({beforeEach(() => {vi.resetAllMocks();mock.dispose.mockResolvedValue(undefined);+ mock.token = null;});vi.mock('node:fs/promises', () => ({mkdir: vi.fn(async () => {}),writeFile: vi.fn(async () => {}),+ readFile: vi.fn(async () => {+ if (mock.token === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ return mock.token;+ }),}));const input = { binaryPath: 'provider', cwd: '/tmp', env: {} };it('blocks missing Codex credentials only when the backend requires authentication', async () => {@@ -73,6 +83,19 @@ it('reports an outstanding Antigravity sign-in as unauthenticated', async () =>expect(result.message).toContain('antigravity-acp --login');expect(mock.dispose).toHaveBeenCalledOnce();});+// Antigravity ACP 1.3 lists every sign-in method in its handshake, signed in or+// not: the token --login wrote is what says.+it('counts the token --login wrote as signed in when the handshake lists methods', async () => {+ mock.request.mockResolvedValueOnce({ authMethods: [{ id: 'oauth-personal' }] });+ mock.token = '{"access_token":"a","refresh_token":"r"}';+ const result = await checkProviderReadiness({+ ...input,+ provider: 'antigravity',+ env: { GEMINI_HOME: '/profile' },+ });+ expect(result.status).toBe('authenticated');+ expect(mock.request.mock.calls.map((call) => call[0])).toEqual(['initialize']);+});// An agent that says nothing about auth is not an agent asking to be signed in.it('treats a handshake with no authMethods as nothing outstanding', async () => {mock.request.mockResolvedValueOnce({});diff --git a/console/packages/agent-providers/src/host/provider-readiness.test.ts b/console/packages/agent-providers/src/host/provider-readiness.test.tsindex 3e716dfb4..10f7f61d5 100644--- a/console/packages/agent-providers/src/host/provider-readiness.test.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.test.ts@@ -1,6 +1,23 @@import { describe, expect, it } from 'vitest';import { checkProviderReadiness, parseAuthentication } from './provider-readiness';+describe('a Cursor API key', () => {+ it('is taken as given: Cursor cannot check one without spending a request', async () => {+ expect(+ await checkProviderReadiness({+ provider: 'cursor',+ binaryPath: '/nonexistent/cursor-agent',+ cwd: '/',+ env: { CURSOR_API_KEY: 'crsr_synthetic' },+ })+ ).toEqual({+ status: 'authenticated',+ message: 'Signs in with the Cursor API key it was given.',+ models: [],+ });+ });+});+describe('provider authentication', () => {it('recognizes signed-out Claude without assuming an installed CLI is ready', () => {expect(parseAuthentication('claude', '{"loggedIn":false}').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 48f35c63a..aef3c1fc8 100644--- a/console/packages/agent-providers/src/host/provider-readiness.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.ts@@ -3,6 +3,8 @@ import { promisify } from 'node:util';import { z } from 'zod';import {ANTIGRAVITY_SIGN_IN,+ antigravityProfile,+ antigravitySignedIn,createAntigravityClient,initializeAntigravity,} from '../antigravity/runtime';@@ -90,6 +92,11 @@ export async function checkProviderReadiness(input: {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 {@@ -117,9 +124,10 @@ export async function checkProviderReadiness(input: {// 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- ? result('unauthenticated', ANTIGRAVITY_SIGN_IN)- : result('authenticated', 'Signed in to Antigravity ACP.');+ 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.');diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.tsindex ffe41747e..5f1aab5b1 100644--- a/console/packages/agent-providers/src/host/session-host.test.ts+++ b/console/packages/agent-providers/src/host/session-host.test.ts@@ -1193,3 +1193,20 @@ it('knows which command started a turn', async () => {expect(host.originOf('turn')).toEqual(message('turn').origin);expect(host.originOf('unknown')).toBeNull();});++it('starts a conversation on recovery when the first start never opened one', async () => {+ const root = await mkdtemp(join(tmpdir(), 'sdk-host-test-'));+ roots.push(root);+ const failing = setup('cursor');+ vi.mocked(failing.adapter.startSession).mockRejectedValueOnce(new Error('Invalid params'));+ await expect(HostedSession.start(root, failing.config, failing.adapter)).rejects.toThrow(+ 'Invalid params'+ );+ const recovered = setup('cursor');+ const host = await HostedSession.start(root, recovered.config, recovered.adapter);+ hosts.push(host);+ expect(recovered.adapter.startSession).toHaveBeenCalledWith(+ expect.not.objectContaining({ resume: expect.anything() })+ );+ await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));+});diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex 13b04381e..15c358ae3 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -256,7 +256,9 @@ export class HostedSession {);return host;}- if (!host.nativeId)+ // A session whose provider never opened a conversation (its first+ // start failed) has nothing to resume: it starts one below.+ if (!host.nativeId && host.providerAnswered())throw new Error('Cannot recover a session without its native provider ID.');if (config.epochAuthority !== 'server') config.session.epoch = randomUUID();const next = host.replica.snapshot();diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.tsindex 683b5c03b..4f94d01d8 100644--- a/console/packages/agent-providers/src/index.ts+++ b/console/packages/agent-providers/src/index.ts@@ -123,7 +123,7 @@ export {watcherHealthSchema,} from './host/watcher-tools';-export { prepareCodexSessionHome } from './codex/home';+export { prepareCodexSessionHome, withManagedCodexSandbox } from './codex/home';export { readSharedCredentials, sharedConfigSchema } from './host/shared-config';export type { SharedHostConfig } from './host/shared-config';