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
feat(codex): hand sessions an API key kept in the OS keyring (CHOO-3838) (#1081)
Christian McDermott6d5ac1ffc506
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 778f73d05..f6b949120 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2028,6 +2028,21 @@ version of their own to them without also giving them a release of their own.- **Connectors says why Airtable or Google Workspace can't be connected on aserver without a public address**: the operator is told to set`GATEWAY_PUBLIC_URL`, and everyone else whom to ask.+- **Codex sessions can use an API key kept in the OS keyring.** With+ `cli_auth_credentials_store = "keyring"` or `"auto"`, the execution machine's+ Codex keeps its login in the keyring, where a session's own Codex home cannot+ find it, so every session failed with "Sign in on the execution machine with+ codex login" while `codex login status` said it was signed in (#1048). When+ the machine has no `auth.json` to copy, a session now asks its Codex for the+ API key as it starts and keeps it in the memory of the session's own Codex+ process: it is not written to a file, put in the environment or copied into+ another keyring entry, and a changed key is picked up at the next start. A+ ChatGPT login in the keyring cannot be handed over, and the session says so+ with the file-storage workaround; it also refuses to hand over the key when an+ administrator's Codex configuration would have it saved elsewhere. A session+ that still has a working login of its own, such as one it copied while the+ machine had an `auth.json`, starts as before; a copy that no longer works is+ removed.#### Changed- **Managed agents and machines update when the server says they changed.**@@ -2075,18 +2090,13 @@ version of their own to them without also giving them a release of their own.skill said a request card needed the owner's linked identity and roommembership. Its addressing policy decides, and agents now read theirs with`get_agent_detail` and name the people who can answer.-- **A Codex session explains why a keyring login is not available to it.**- Each session runs in its own Codex home, which receives the machine's- `auth.json` but not a login stored in the OS keyring, so a machine signed in- with keyring storage (`cli_auth_credentials_store = "keyring"` or `"auto"`)- failed with only "Sign in on the execution machine with codex login" while- `codex login status` said it was signed in. The error now says that sessions- cannot use a keyring login, and gives the workaround for a machine whose- organization does not enforce the keyring: switch Codex to file storage,- which keeps the login in plaintext, sign in again and start a new session.- Giving this computer's Codex login to a machine says the same instead of- "This computer is not signed in to codex". Keyring logins are still not- supported in Switch sessions (#1048).+- **Giving this computer's Codex login to a machine explains a keyring+ login.** When Codex keeps its login in the OS keyring+ (`cli_auth_credentials_store = "keyring"` or `"auto"`), it said "This+ computer is not signed in to codex". It now says the login is in the keyring,+ which cannot be given to another machine, and gives the workaround for a+ machine whose organization does not enforce the keyring: switch Codex to file+ storage, which keeps the login in plaintext, and sign in again (#1048).### [0.40.1] - 2026-10-21diff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex 1a09b1aa4..3a3c2ac0c 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -95,6 +95,27 @@ export interface ProviderSessionStartInput {/** The definition of {@link agentName}, handed to the vendor directly instead* of read from its own files. */agentDefinition?: AgentLaunchDefinition;+ /**+ * Codex only: the execution machine's Codex home has no auth.json, so a+ * session with no login of its own is handed the API key that Codex keeps+ * in the OS keyring as it starts.+ */+ codexKeyringLogin?: CodexKeyringLogin;+}++/**+ * Where a Codex session's keyring login comes from (`codex/keyring-login.ts`).+ * It lives only in the session host's memory: `redact` is a function, so it+ * never reaches a configuration file, and the key itself is read anew each+ * time the session's Codex starts.+ */+export interface CodexKeyringLogin {+ /** The execution machine's own Codex home, whose login is in the keyring. */+ home: string;+ /** The environment Codex reads that login with. */+ env: Record<string, string>;+ /** Called with the key as soon as it is read, so everything the host records scrubs it. */+ redact: (secret: string) => void;}export interface ProviderSession {diff --git a/console/packages/agent-providers/src/codex/codex-adapter.test.ts b/console/packages/agent-providers/src/codex/codex-adapter.test.tsindex aac4de5f9..98f9fe820 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.test.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.test.ts@@ -81,25 +81,23 @@ describe('CodexAdapter', () => {expect(servers[0].received.some((m) => m.method === 'thread/start')).toBe(false);});- it('explains that an isolated session cannot use a keyring login, and the file workaround', async () => {+ it('asks for a sign-in, and reads no keyring, when the session had an auth.json to copy', async () => {account = null;const exited = vi.fn();const failed = start();servers.at(-1)?.on('exit', exited);const error = await failed.catch((cause: unknown) => cause);expect(error).toBeInstanceOf(Error);- const message = (error as Error).message;- expect(message).toContain(CODEX_SIGN_IN_REQUIRED);- expect(message).toContain('OS keyring');- expect(message).toContain('cli_auth_credentials_store = "file"');- expect(message).toContain('start a new session');- expect(message).toContain('plaintext');+ expect((error as Error).message.endsWith(`Error: ${CODEX_SIGN_IN_REQUIRED}`)).toBe(true);expect(servers).toHaveLength(1);expect(servers[0].received.map((m) => m.method)).toEqual(['initialize','initialized','account/read',]);+ expect((servers[0] as unknown as { spawnArgs: string[] }).spawnArgs.join(' ')).not.toContain(+ 'cli_auth_credentials_store'+ );expect(exited).toHaveBeenCalled();});diff --git a/console/packages/agent-providers/src/codex/codex-adapter.ts b/console/packages/agent-providers/src/codex/codex-adapter.tsindex 8ac6cb0d6..a7ac1b24a 100644--- a/console/packages/agent-providers/src/codex/codex-adapter.ts+++ b/console/packages/agent-providers/src/codex/codex-adapter.ts@@ -1,9 +1,10 @@import { randomUUID } from 'node:crypto';-import { readFile } from 'node:fs/promises';+import { readFile, rm } from 'node:fs/promises';import { basename, join } from 'node:path';import { parse } from 'smol-toml';import { z } from 'zod';import {+ type CodexKeyringLogin,type ModelSelection,type ProviderAdapter,type ProviderCapabilities,@@ -35,6 +36,7 @@ import {import { CumulativeUsage, mergeUsage, type UsageCounts } from '../usage';import { featureArgs, mcpServerConfigArgs, tomlString } from './config-args';import { mapCodexItem } from './item-mapping';+import { CODEX_KEYRING_READ_TIMEOUT_MS, readCodexKeyringApiKey } from './keyring-login';import {CODEX_CLIENT_METHODS,CODEX_CLIENT_NOTIFICATIONS,@@ -68,19 +70,30 @@ const PROVIDER = 'codex';const CLIENT_NAME = 'switch-console';const CLIENT_VERSION = '0.1.0';+export const CODEX_SIGN_IN_REQUIRED = 'Sign in on the execution machine with codex login.';+/**- * Codex keys a keyring login by its CODEX_HOME path, and a session runs in its- * own CODEX_HOME that receives only the execution machine's auth.json, so a- * keyring login reads as signed out here even though `codex login status`- * reports it.+ * Signed out with no auth.json on the machine: Codex reads a keyring login as+ * signed out when the keyring refuses it, so that is the likely cause when+ * `codex login status` disagrees.*/-export const CODEX_SIGN_IN_REQUIRED =- 'Sign in on the execution machine with codex login. If Codex says you are already signed in, ' +- 'your login is likely in the OS keyring (cli_auth_credentials_store = "keyring" or "auto"), ' +- 'which Switch sessions cannot use: they get the login only from auth.json. Unless your ' +- 'organization enforces the keyring, set cli_auth_credentials_store = "file" in the Codex ' +- 'config.toml on the execution machine, which keeps the login in plaintext, then run codex ' +- 'login again and start a new session.';+export const CODEX_KEYRING_SIGN_IN_REQUIRED =+ `${CODEX_SIGN_IN_REQUIRED} If Codex there says it is already signed in, it could not read ` ++ 'the login it keeps in the OS keyring: the keychain may be locked, or access to its ' ++ '"Codex Auth" item may have been denied.';++/**+ * Where a session that is handed a keyring login keeps it: in the memory of+ * its own Codex process, never in a file or the keyring. Given on the command+ * line, it outranks the user's and the project's configuration, and survives+ * Codex falling back to its defaults over a configuration it cannot read.+ */+const EPHEMERAL_LOGIN_ARGS = ['-c', 'cli_auth_credentials_store="ephemeral"'];++const accountSchema = z.object({+ account: z.unknown().nullable(),+ requiresOpenaiAuth: z.boolean(),+});/*** `multi_agent_v2` ships stable but off, and it is what puts `spawn_agent` in@@ -367,11 +380,28 @@ export class CodexAdapter implements ProviderAdapter {const mode = threadModeConfig(input.runtimeMode, input.cwd);const mcp = mcpServerConfigArgs(input.mcpServers, input.connectorMcpServers, input.runtimeMode);const args = ['app-server', ...featureArgs(this.features), ...mode.configArgs, ...mcp.args];+ const env = { ...input.env, ...mcp.env };+ const keyringLogin = input.codexKeyringLogin;+ let handOver = false;+ if (keyringLogin) {+ try {+ handOver = await this.lacksOwnLogin(args, input.cwd, env);+ } catch (cause) {+ throw new ProviderSessionError(+ PROVIDER,+ input.sessionId,+ `could not check the codex login: ${String(cause)}`,+ { cause }+ );+ }+ if (this.sessions.has(input.sessionId))+ throw new ProviderSessionError(PROVIDER, input.sessionId, 'session already started');+ }const client = new StdioJsonRpcClient({command: this.binaryPath,- args,+ args: handOver ? [...args, ...EPHEMERAL_LOGIN_ARGS] : args,cwd: input.cwd,- env: { ...input.env, ...mcp.env },+ env,logger: this.logger,onExit: (reason) => this.handleProcessExit(input.sessionId, reason),});@@ -406,10 +436,13 @@ export class CodexAdapter implements ProviderAdapter {};await client.request(CODEX_CLIENT_METHODS.initialize, initializeParams);client.notify(CODEX_CLIENT_NOTIFICATIONS.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) throw new Error(CODEX_SIGN_IN_REQUIRED);+ const account = accountSchema.parse(+ await client.request('account/read', { refreshToken: false })+ );+ if (!account.account && account.requiresOpenaiAuth) {+ if (!keyringLogin || !handOver) throw new Error(CODEX_SIGN_IN_REQUIRED);+ await this.signInFromKeyring(client, input.cwd, keyringLogin);+ }const configured = await configuredSandbox(input.env.CODEX_HOME);const sandbox = sandboxFor(input.runtimeMode, configured);@@ -426,7 +459,9 @@ export class CodexAdapter implements ProviderAdapter {const opened = await this.openThread(client, config, input.resume?.nativeSessionId);state.threadId = opened.thread.id;} catch (cause) {- this.sessions.delete(input.sessionId);+ // A start stopped part-way (reset while it waited on the keyring, say)+ // may already have been replaced under the same id.+ if (this.sessions.get(input.sessionId) === state) this.sessions.delete(input.sessionId);await client.dispose();if (input.resume &&@@ -668,6 +703,85 @@ export class CodexAdapter implements ProviderAdapter {});}+ /**+ * Whether a session that could be handed a keyring login has no login of+ * its own, asked of its Codex as configured. A copy of the machine's old+ * auth.json, or a login Codex saved for the session itself, keeps working+ * and is left alone; a copy that no longer works is only a plaintext secret+ * then, and is removed. Only the account cached at startup is read, so this+ * refreshes nothing.+ */+ private async lacksOwnLogin(+ args: string[],+ cwd: string,+ env: Record<string, string>+ ): Promise<boolean> {+ const probe = new StdioJsonRpcClient({+ command: this.binaryPath,+ args,+ cwd,+ env,+ logger: noopLogger,+ onExit: () => {},+ });+ try {+ await probe.request(CODEX_CLIENT_METHODS.initialize, {+ clientInfo: { name: CLIENT_NAME, title: 'Switch Console', version: CLIENT_VERSION },+ });+ probe.notify(CODEX_CLIENT_NOTIFICATIONS.initialized, null);+ const account = accountSchema.parse(+ await probe.request('account/read', { refreshToken: false })+ );+ if (account.account || !account.requiresOpenaiAuth) return false;+ } catch (error) {+ throw new Error(`${String(error)}${probe.stderr ? `\n${probe.stderr}` : ''}`, {+ cause: error,+ });+ } finally {+ await probe.dispose().catch((error: unknown) =>+ this.logger.warn('The Codex that checked a session login did not stop.', {+ error: String(error),+ })+ );+ }+ if (env.CODEX_HOME) await rm(join(env.CODEX_HOME, 'auth.json'), { force: true });+ return true;+ }++ /**+ * Hands the session's Codex the API key the machine's Codex keeps in the OS+ * keyring. Codex saves a login where its configuration says, so the key is+ * sent only once this process confirms it keeps logins in memory: a managed+ * configuration or an administrator's requirements outrank the command line.+ */+ private async signInFromKeyring(+ client: StdioJsonRpcClient,+ cwd: string,+ login: CodexKeyringLogin+ ): Promise<void> {+ const { config } = z+ .object({ config: z.object({ cli_auth_credentials_store: z.unknown() }) })+ .parse(await client.request('config/read', { cwd }));+ const store = config.cli_auth_credentials_store;+ if (store !== 'ephemeral')+ throw new Error(+ `Codex's configuration on the execution machine sets cli_auth_credentials_store to ${JSON.stringify(store ?? null)} for this session where Switch asked for "ephemeral" (an administrator's managed configuration or requirements can do this), so Switch did not hand the session the API key from the OS keyring: Codex would have saved another copy of it.`+ );+ const apiKey = await readCodexKeyringApiKey(+ this.binaryPath,+ login,+ CODEX_KEYRING_READ_TIMEOUT_MS+ );+ if (apiKey === null) throw new Error(CODEX_KEYRING_SIGN_IN_REQUIRED);+ login.redact(apiKey);+ await client.request('account/login/start', { type: 'apiKey', apiKey });+ const { account } = accountSchema.parse(+ await client.request('account/read', { refreshToken: false })+ );+ if (!z.object({ type: z.literal('apiKey') }).safeParse(account).success)+ throw new Error('Codex did not take the API key handed over from the OS keyring.');+ }+private async trySteer(state: CodexSessionState,activeTurnId: string,diff --git a/console/packages/agent-providers/src/codex/home.test.ts b/console/packages/agent-providers/src/codex/home.test.tsindex 1a9867f1a..3e396401f 100644--- a/console/packages/agent-providers/src/codex/home.test.ts+++ b/console/packages/agent-providers/src/codex/home.test.ts@@ -23,7 +23,8 @@ it('isolates config, preserves rollouts and refreshed auth on resume, and protecsourceHome,config: 'model = "test-model"',};- const home = await prepareCodexSessionHome(input);+ const { home, keyringLogin } = await prepareCodexSessionHome(input);+ expect(keyringLogin).toBe(false);expect(parse(await readFile(join(home, 'config.toml'), 'utf8'))).toEqual({model: 'test-model',model_reasoning_effort: 'high',@@ -36,26 +37,40 @@ it('isolates config, preserves rollouts and refreshed auth on resume, and protecexpect((await stat(join(home, 'auth.json'))).mode & 0o777).toBe(0o600);await writeFile(join(home, 'auth.json'), 'refreshed-fixture');await mkdir(join(home, 'sessions'));- expect(await prepareCodexSessionHome(input)).toBe(home);+ expect(await prepareCodexSessionHome(input)).toEqual({ home, keyringLogin: false });expect(await readFile(join(home, 'auth.json'), 'utf8')).toBe('refreshed-fixture');expect(await readFile(join(sourceHome, 'config.toml'), 'utf8')).toBe('model_reasoning_effort = "high"');const other = await prepareCodexSessionHome({ ...input, sessionId: 'other' });- expect(other).not.toBe(home);+ expect(other.home).not.toBe(home);});-it('allows native environment or keychain authentication when no login file exists', async () => {+it('hands the session a keyring login when the source home has no auth.json', async () => {const root = await mkdtemp(join(tmpdir(), 'codex-home-test-'));roots.push(root);- await expect(- prepareCodexSessionHome({- root,- sessionId: 'session',- sourceHome: join(root, 'missing'),- config: '',- })- ).resolves.toEqual(expect.any(String));+ const { home, keyringLogin } = await prepareCodexSessionHome({+ root,+ sessionId: 'session',+ sourceHome: join(root, 'missing'),+ config: '',+ });+ expect(keyringLogin).toBe(true);+ expect(await readdir(home)).not.toContain('auth.json');+});++it('leaves a copied login alone when the machine moves its own to the keyring', async () => {+ const root = await mkdtemp(join(tmpdir(), 'codex-home-test-'));+ roots.push(root);+ const sourceHome = join(root, 'source');+ await mkdir(sourceHome);+ await writeFile(join(sourceHome, 'auth.json'), 'fixture-login');+ const input = { root: join(root, 'sessions'), sessionId: 'session', sourceHome, config: '' };+ const { home } = await prepareCodexSessionHome(input);+ await rm(join(sourceHome, 'auth.json'));+ // Codex may still read the copy; the adapter decides once it has asked.+ expect(await prepareCodexSessionHome(input)).toEqual({ home, keyringLogin: true });+ expect(await readFile(join(home, 'auth.json'), 'utf8')).toBe('fixture-login');});it('removes a Switch skill file an earlier build left in the session home', async () => {@@ -67,7 +82,7 @@ it('removes a Switch skill file an earlier build left in the session home', asynsourceHome: join(root, 'missing'),config: '',};- const home = await prepareCodexSessionHome(input);+ const { home } = await prepareCodexSessionHome(input);await mkdir(join(home, 'skills/switch'), { recursive: true });await writeFile(join(home, 'skills/switch/SKILL.md'), 'old copy');await prepareCodexSessionHome(input);@@ -80,7 +95,7 @@ it('links the user’s own Codex skills into a session home that has no skills fconst sourceHome = join(root, 'source');await mkdir(join(sourceHome, 'skills', '.system'), { recursive: true });await writeFile(join(sourceHome, 'skills', '.system', 'SKILL.md'), 'system skill');- const home = await prepareCodexSessionHome({+ const { home } = await prepareCodexSessionHome({root: join(root, 'sessions'),sessionId: 'session',sourceHome,diff --git a/console/packages/agent-providers/src/codex/home.ts b/console/packages/agent-providers/src/codex/home.tsindex 1b08e61e3..67f761f3b 100644--- a/console/packages/agent-providers/src/codex/home.ts+++ b/console/packages/agent-providers/src/codex/home.ts@@ -1,5 +1,5 @@import { createHash, randomUUID } from 'node:crypto';-import { chmod, copyFile, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { chmod, copyFile, lstat, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { parse, stringify } from 'smol-toml';import type { RuntimeMode } from '../adapter';@@ -20,18 +20,26 @@ export function withManagedCodexSandbox(config: string, runtimeMode: RuntimeModereturn `sandbox_mode = "${mode}"\n${config}`;}-/** Native rollouts remain in the persistent session directory on the execution host. */+/**+ * Native rollouts remain in the persistent session directory on the execution+ * host. `keyringLogin` is set when the source home has no auth.json to copy:+ * the machine's login, if Codex has one, is then in the OS keyring, and a+ * session with no login of its own is handed it as it starts+ * (`CodexKeyringLogin`). A copy the session already has is left alone, since+ * Codex may still read it.+ */export async function prepareCodexSessionHome(input: {root: string;sessionId: string;sourceHome: string;config: string;-}): Promise<string> {+}): Promise<{ home: string; keyringLogin: boolean }> {const key = createHash('sha256').update(input.sessionId).digest('hex');const home = join(input.root, key);await mkdir(home, { recursive: true, mode: 0o700 });await chmod(home, 0o700);- await copyCodexAuthenticationOnce(home, input.sourceHome);+ const keyringLogin = !(await isFile(join(input.sourceHome, 'auth.json')));+ if (!keyringLogin) await copyCodexAuthenticationOnce(home, input.sourceHome);const sourceConfig = await optionalText(join(input.sourceHome, 'config.toml'));const config = { ...(sourceConfig ? parse(sourceConfig) : {}), ...parse(input.config) };// The session host registers its own `switch` server; an entry of that name@@ -50,7 +58,16 @@ export async function prepareCodexSessionHome(input: {// instructions, and a leftover copy would only be read again by shell.await rm(join(home, 'skills', 'switch'), { recursive: true, force: true });await linkSkills(join(input.sourceHome, 'skills'), join(home, 'skills'));- return home;+ return { home, keyringLogin };+}++async function isFile(path: string): Promise<boolean> {+ try {+ return (await stat(path)).isFile();+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;+ throw new Error('Could not load the execution-host Codex login.', { cause: error });+ }}/** A resumed session keeps its refreshed login; new sessions copy only auth. */diff --git a/console/packages/agent-providers/src/codex/keyring-login.integration.test.ts b/console/packages/agent-providers/src/codex/keyring-login.integration.test.tsnew file mode 100644index 000000000..7e553a134--- /dev/null+++ b/console/packages/agent-providers/src/codex/keyring-login.integration.test.ts@@ -0,0 +1,143 @@+import { spawnSync } from 'node:child_process';+import { mkdtemp, mkdir, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import type { ProviderRuntimeEvent } from '../events';+import { createCodexAdapter } from './codex-adapter';+import { CODEX_KEYRING_READ_TIMEOUT_MS, readCodexKeyringApiKey } from './keyring-login';++/**+ * The handoff against the real `codex` binary, with a made-up key and nothing+ * in the OS keyring: the source home keeps the key in auth.json, which Codex+ * exports the same way as a keyring login. Reading a real keychain entry is+ * the one part left to a manual check, as it writes to the developer's+ * keychain. The turn reaches OpenAI, whose 401 for the key is what proves the+ * session used it.+ */+const FAKE_KEY = 'sk-fake-switch-keyring-handoff-0000';++const unavailable = (() => {+ const probe = spawnSync('codex', ['--version'], { encoding: 'utf8' });+ return probe.error || probe.status !== 0;+})();++async function filesUnder(dir: string): Promise<string[]> {+ const entries = await readdir(dir, { withFileTypes: true, recursive: true });+ return entries+ .filter((entry) => entry.isFile())+ .map((entry) => join(entry.parentPath, entry.name));+}++describe.skipIf(unavailable)('Codex keyring login handoff (real codex)', () => {+ let root: string;+ let sourceHome: string;+ let sessionHome: string;+ let work: string;+ const env = () => ({+ PATH: process.env.PATH ?? '',+ HOME: process.env.HOME ?? '',+ CODEX_HOME: sessionHome,+ });++ beforeAll(async () => {+ root = await realpath(await mkdtemp(join(tmpdir(), 'codex-keyring-handoff-')));+ sourceHome = join(root, 'source');+ sessionHome = join(root, 'session');+ work = join(root, 'work');+ await mkdir(sourceHome);+ await writeFile(join(sourceHome, 'auth.json'), JSON.stringify({ OPENAI_API_KEY: FAKE_KEY }));+ // The session's own configuration, and a trusted project's, both ask for+ // a file: the command line has to outrank them.+ await mkdir(sessionHome);+ await writeFile(+ join(sessionHome, 'config.toml'),+ `cli_auth_credentials_store = "file"\n[projects.${JSON.stringify(work)}]\ntrust_level = "trusted"\n`+ );+ await mkdir(join(work, '.codex'), { recursive: true });+ spawnSync('git', ['init', '-q'], { cwd: work });+ await writeFile(join(work, '.codex', 'config.toml'), 'cli_auth_credentials_store = "file"\n');+ });++ afterAll(async () => {+ await rm(root, { recursive: true, force: true });+ });++ it('exports an API-key login through getAuthStatus', async () => {+ const key = await readCodexKeyringApiKey(+ 'codex',+ { home: sourceHome, env: env(), redact: () => {} },+ CODEX_KEYRING_READ_TIMEOUT_MS+ );+ expect(key).toBe(FAKE_KEY);+ });++ it(+ 'signs the session in from memory, writes the key nowhere, and sends it with the turn',+ { timeout: 120_000 },+ async () => {+ const adapter = createCodexAdapter();+ const events: ProviderRuntimeEvent[] = [];+ adapter.subscribe((event) => events.push(event));+ const redact = vi.fn();+ try {+ await adapter.startSession({+ sessionId: 'keyring-handoff',+ cwd: work,+ runtimeMode: 'full-access',+ env: env(),+ mcpServers: {},+ connectorMcpServers: [],+ codexKeyringLogin: { home: sourceHome, env: env(), redact },+ });+ expect(redact).toHaveBeenCalledWith(FAKE_KEY);+ await adapter.sendTurn({ sessionId: 'keyring-handoff', turnId: 'turn-1', text: 'hi' });+ const done = await new Promise<Extract<ProviderRuntimeEvent, { type: 'turn.completed' }>>(+ (resolve) => {+ const check = () => {+ const found = events.find(+ (event): event is Extract<ProviderRuntimeEvent, { type: 'turn.completed' }> =>+ event.type === 'turn.completed'+ );+ if (found) resolve(found);+ else setTimeout(check, 250);+ };+ check();+ }+ );+ expect(done.outcome).toBe('error');+ expect(done.message).toMatch(/401|Incorrect API key/);+ } finally {+ await adapter.stopAll();+ }+ expect(await readdir(sessionHome)).not.toContain('auth.json');+ for (const file of await filesUnder(sessionHome))+ expect((await readFile(file)).includes(FAKE_KEY), file).toBe(false);+ }+ );++ it('leaves a session that still has a working copied login as it was', async () => {+ const copied = join(root, 'session-with-copy');+ await mkdir(copied);+ await writeFile(join(copied, 'config.toml'), 'cli_auth_credentials_store = "file"\n');+ const copy = JSON.stringify({ OPENAI_API_KEY: 'sk-fake-switch-copied-login-0000' });+ await writeFile(join(copied, 'auth.json'), copy);+ const adapter = createCodexAdapter();+ const redact = vi.fn();+ try {+ await adapter.startSession({+ sessionId: 'keyring-copy',+ cwd: work,+ runtimeMode: 'full-access',+ env: { ...env(), CODEX_HOME: copied },+ mcpServers: {},+ connectorMcpServers: [],+ codexKeyringLogin: { home: sourceHome, env: env(), redact },+ });+ expect(redact).not.toHaveBeenCalled();+ } finally {+ await adapter.stopAll();+ }+ expect(await readFile(join(copied, 'auth.json'), 'utf8')).toBe(copy);+ });+});diff --git a/console/packages/agent-providers/src/codex/keyring-login.test.ts b/console/packages/agent-providers/src/codex/keyring-login.test.tsnew file mode 100644index 000000000..4d7e299ac--- /dev/null+++ b/console/packages/agent-providers/src/codex/keyring-login.test.ts@@ -0,0 +1,356 @@+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { CodexKeyringLogin, ProviderSessionStartInput } from '../adapter';+import type { ProviderRuntimeEvent } from '../events';+import { FakeAppServer } from './fake-app-server';++/** Stands in for an API key; asserted never to reach an error, a log line or an event. */+const SENTINEL = 'sk-sentinel-keyring-login-0001';+const EPHEMERAL = 'cli_auth_credentials_store="ephemeral"';++interface Spawned {+ spawnArgs: string[];+ spawnOptions: { cwd: string; env: Record<string, string> };+}++let sourceHome = '';+let sessionHome = '';+/** The Codex run against the machine's own home to read its login. */+const sources: Array<FakeAppServer & Spawned> = [];+/** The session's Codex: the login check first, then the session itself. */+const sessions: Array<FakeAppServer & Spawned> = [];+let source: {+ account: Record<string, unknown> | null;+ authStatus: Record<string, unknown> | { error: { code: number; message: string } };+ /** A keychain prompt nobody answers: Codex never gets as far as replying. */+ silent: boolean;+ /** Holds back the key until released. */+ hold: Promise<void> | null;+ /** Exits at once, saying this on stderr. */+ crash: string | null;+};+let session: {+ /** The login the session's Codex has of its own, without the in-memory store. */+ ownLogin: Record<string, unknown> | null;+ store: unknown;+ afterLogin: Record<string, unknown> | null;+ /** The login check exits at once, saying this on stderr. */+ probeCrash: string | null;+};++function crash(server: FakeAppServer, output: string) {+ server.stderr.write(`${output}\n`);+ setTimeout(() => server.kill(), 10);+}++vi.mock('node:child_process', () => ({+ spawn: (_command: string, args: string[], options: Spawned['spawnOptions']) => {+ const server = Object.assign(new FakeAppServer(), { spawnArgs: args, spawnOptions: options });+ if (options.cwd === sourceHome) {+ sources.push(server);+ if (source.silent) return server;+ if (source.crash) {+ crash(server, source.crash);+ return server;+ }+ server.replyAlways('initialize', () => ({ userAgent: 'fake' }));+ server.replyAlways('account/read', () => ({+ account: source.account,+ requiresOpenaiAuth: true,+ }));+ server.on('message', async (message) => {+ if (message.method !== 'getAuthStatus' || message.id === undefined) return;+ await source.hold;+ const reply = source.authStatus;+ if ('error' in reply) server.send({ id: message.id, error: reply.error as never });+ else server.send({ id: message.id, result: reply });+ });+ return server;+ }+ sessions.push(server);+ const ephemeral = args.includes(EPHEMERAL);+ if (!ephemeral && session.probeCrash) {+ crash(server, session.probeCrash);+ return server;+ }+ let signedIn = false;+ server.replyAlways('initialize', () => ({ userAgent: 'fake' }));+ server.replyAlways('account/read', () => ({+ account: ephemeral ? (signedIn ? session.afterLogin : null) : session.ownLogin,+ requiresOpenaiAuth: true,+ }));+ server.replyAlways('config/read', () => ({+ config: { cli_auth_credentials_store: session.store },+ origins: {},+ }));+ server.replyAlways('account/login/start', () => {+ signedIn = true;+ return { type: 'apiKey' };+ });+ server.replyAlways('thread/start', () => ({ thread: { id: 'thread-1' } }));+ return server;+ },+}));++const { CODEX_KEYRING_SIGN_IN_REQUIRED, createCodexAdapter } = await import('./codex-adapter');+const { CODEX_FILE_STORE_WORKAROUND, readCodexKeyringApiKey } = await import('./keyring-login');++const methods = (server: FakeAppServer | undefined) =>+ (server?.received ?? []).map((message) => message.method);+const sessionServer = () => sessions.at(-1);++function keyringLogin(redact: (secret: string) => void = () => {}): CodexKeyringLogin {+ return { home: sourceHome, env: { PATH: '/usr/bin' }, redact };+}++function startInput(login: CodexKeyringLogin | null): ProviderSessionStartInput {+ return {+ sessionId: 'session-1',+ cwd: '/work',+ runtimeMode: 'full-access',+ env: { PATH: '/usr/bin', CODEX_HOME: sessionHome },+ mcpServers: {},+ connectorMcpServers: [],+ ...(login ? { codexKeyringLogin: login } : {}),+ };+}++/** Starts a session that may be handed a keyring login, recording everything that could leak the key. */+async function start(login: CodexKeyringLogin = keyringLogin()) {+ const logged: unknown[] = [];+ const record = (...args: unknown[]) => logged.push(args);+ const adapter = createCodexAdapter({ logger: { debug: record, warn: record, error: record } });+ const events: ProviderRuntimeEvent[] = [];+ adapter.subscribe((event) => events.push(event));+ const outcome = await adapter.startSession(startInput(login)).then(+ (value) => ({ session: value, error: null }),+ (error: unknown) => ({ session: null, error: error as Error })+ );+ return { adapter, events, logged, ...outcome };+}++function expectNoLeak(result: Awaited<ReturnType<typeof start>>) {+ expect(result.error?.message ?? '').not.toContain(SENTINEL);+ expect(String(result.error?.cause ?? '')).not.toContain(SENTINEL);+ expect(JSON.stringify(result.logged)).not.toContain(SENTINEL);+ expect(JSON.stringify(result.events)).not.toContain(SENTINEL);+}++beforeEach(async () => {+ sourceHome = await mkdtemp(join(tmpdir(), 'codex-keyring-source-'));+ sessionHome = await mkdtemp(join(tmpdir(), 'codex-keyring-session-'));+ sources.length = 0;+ sessions.length = 0;+ source = {+ account: { type: 'apiKey' },+ authStatus: { authMethod: 'apikey', authToken: SENTINEL, requiresOpenaiAuth: true },+ silent: false,+ hold: null,+ crash: null,+ };+ session = {+ ownLogin: null,+ store: 'ephemeral',+ afterLogin: { type: 'apiKey' },+ probeCrash: null,+ };+});++afterEach(async () => {+ await rm(sourceHome, { recursive: true, force: true });+ await rm(sessionHome, { recursive: true, force: true });+});++describe('a Codex session with no login of its own', () => {+ it('keeps the login in memory and takes the key from Codex run against its own home', async () => {+ const order: string[] = [];+ const result = await start(+ keyringLogin((secret) => {+ order.push(`redact ${secret === SENTINEL}`);+ order.push(+ ...methods(sessionServer()).filter((method) => method === 'account/login/start')+ );+ })+ );+ expect(result.error).toBeNull();+ expect(result.session?.nativeSessionId).toBe('thread-1');++ // The login check runs the session's Codex as configured, and only reads.+ const [check, started] = sessions;+ expect(sessions).toHaveLength(2);+ expect(check.spawnArgs).not.toContain(EPHEMERAL);+ expect(check.spawnOptions.cwd).toBe('/work');+ expect(methods(check)).toEqual(['initialize', 'initialized', 'account/read']);+ expect(check.stdin.writableEnded).toBe(true);++ expect(started.spawnArgs.slice(-2)).toEqual(['-c', EPHEMERAL]);+ expect(methods(started)).toEqual([+ 'initialize',+ 'initialized',+ 'account/read',+ 'config/read',+ 'account/login/start',+ 'account/read',+ 'thread/start',+ ]);+ expect(started.received.find((m) => m.method === 'config/read')?.params).toEqual({+ cwd: '/work',+ });+ expect(started.received.find((m) => m.method === 'account/login/start')?.params).toEqual({+ type: 'apiKey',+ apiKey: SENTINEL,+ });+ // Scrubbed before it is sent anywhere.+ expect(order).toEqual(['redact true']);++ const [reader] = sources;+ expect(reader.spawnArgs).toEqual(['app-server']);+ expect(reader.spawnOptions.cwd).toBe(sourceHome);+ expect(reader.spawnOptions.env).toEqual({ PATH: '/usr/bin', CODEX_HOME: sourceHome });+ expect(methods(reader)).toEqual(['initialize', 'initialized', 'account/read', 'getAuthStatus']);+ expect(reader.received.find((m) => m.method === 'getAuthStatus')?.params).toEqual({+ includeToken: true,+ refreshToken: false,+ });+ expect(reader.stdin.writableEnded).toBe(true);+ expectNoLeak(result);+ await result.adapter.stopAll();+ });++ it('reads the key again each time the session starts, so a changed key is picked up', async () => {+ const first = await start();+ await first.adapter.stopAll();+ const second = await start();+ expect(second.error).toBeNull();+ expect(sources).toHaveLength(2);+ await second.adapter.stopAll();+ });++ it('removes a copied login that no longer works before handing over the key', async () => {+ await writeFile(join(sessionHome, 'auth.json'), 'stale-login');+ const result = await start();+ expect(result.error).toBeNull();+ expect(await readdir(sessionHome)).not.toContain('auth.json');+ await result.adapter.stopAll();+ });++ it('does not read the key when Codex would save it outside memory', async () => {+ session.store = 'file';+ const result = await start();+ expect(result.error?.message).toContain('sets cli_auth_credentials_store to "file"');+ expect(sources).toHaveLength(0);+ expect(methods(sessionServer())).not.toContain('account/login/start');+ expect(methods(sessionServer())).not.toContain('thread/start');+ });++ it.each([+ ['chatgpt', 'ChatGPT'],+ ['amazonBedrock', 'a amazonBedrock login'],+ ])(+ 'explains why a %s keyring login cannot be handed over, without asking for its token',+ async (type, shown) => {+ source.account = { type };+ const result = await start();+ expect(result.error?.message).toContain(`signed in with ${shown}`);+ expect(result.error?.message).toContain('only when it is an API key');+ expect(result.error?.message).toContain(CODEX_FILE_STORE_WORKAROUND);+ expect(methods(sources[0])).not.toContain('getAuthStatus');+ expect(methods(sessionServer())).not.toContain('account/login/start');+ }+ );++ it('sends nothing when Codex reports an API-key account but exports something else', async () => {+ source.authStatus = { authMethod: 'chatgpt', authToken: SENTINEL };+ const result = await start();+ expect(result.error?.message).toContain('did not hand over the key');+ expect(methods(sessionServer())).not.toContain('account/login/start');+ expectNoLeak(result);+ });++ it('asks for a sign-in, naming the keyring, when the machine’s Codex is signed out', async () => {+ source.account = null;+ const result = await start();+ expect(result.error?.message).toContain(CODEX_KEYRING_SIGN_IN_REQUIRED);+ expect(methods(sources[0])).not.toContain('getAuthStatus');+ });++ it('asks for a sign-in without starting that Codex when the machine has no Codex home', async () => {+ await rm(sourceHome, { recursive: true });+ const result = await start();+ expect(result.error?.message).toContain(CODEX_KEYRING_SIGN_IN_REQUIRED);+ expect(sources).toHaveLength(0);+ });++ it('says so when this Codex no longer exports its login', async () => {+ source.authStatus = { error: { code: -32601, message: 'method not found' } };+ const result = await start();+ expect(result.error?.message).toContain('no longer answers getAuthStatus');+ expect(methods(sessionServer())).not.toContain('account/login/start');+ });++ it('passes on what Codex said when it fails to report its login', async () => {+ source.crash = 'fixture: keyring backend unavailable';+ const result = await start();+ expect(result.error?.message).toContain('could not report its login');+ expect(result.error?.message).toContain('fixture: keyring backend unavailable');+ });++ it('fails when Codex does not take the key, without repeating it', async () => {+ session.afterLogin = null;+ const result = await start();+ expect(result.error?.message).toContain('did not take the API key');+ expect(methods(sessionServer())).not.toContain('thread/start');+ expectNoLeak(result);+ });++ it('does not unregister the session that replaced a start stopped while it waited on the keyring', async () => {+ let release = () => {};+ source.hold = new Promise<void>((resolve) => {+ release = resolve;+ });+ const adapter = createCodexAdapter();+ const stale = adapter.startSession(startInput(keyringLogin()));+ await vi.waitFor(() => expect(methods(sources[0])).toContain('getAuthStatus'));+ await adapter.stopSession('session-1');+ session.ownLogin = { type: 'apiKey' };+ await adapter.startSession(startInput(null));+ release();+ await expect(stale).rejects.toThrow();+ expect(adapter.hasSession('session-1')).toBe(true);+ await adapter.stopAll();+ });+});++describe('a Codex session with a login of its own', () => {+ it('starts as before, with its copy and no keyring read, when the machine moved its own login to the keyring', async () => {+ session.ownLogin = { type: 'chatgpt', email: null, planType: null };+ await writeFile(join(sessionHome, 'auth.json'), 'copied-login');+ const result = await start();+ expect(result.error).toBeNull();+ expect(sessionServer()?.spawnArgs).not.toContain(EPHEMERAL);+ expect(methods(sessionServer())).not.toContain('account/login/start');+ expect(sources).toHaveLength(0);+ expect(await readFile(join(sessionHome, 'auth.json'), 'utf8')).toBe('copied-login');+ await result.adapter.stopAll();+ });++ it('passes on what Codex said when checking the session’s login fails', async () => {+ session.probeCrash = 'fixture: invalid configuration';+ const result = await start();+ expect(result.error?.message).toContain('could not check the codex login');+ expect(result.error?.message).toContain('fixture: invalid configuration');+ expect(sources).toHaveLength(0);+ });+});++describe('readCodexKeyringApiKey', () => {+ it('gives up with a reason when the keyring does not answer, and stops that Codex', async () => {+ source.silent = true;+ await expect(readCodexKeyringApiKey('codex', keyringLogin(), 50)).rejects.toThrow(+ /did not read its login from the OS keyring within 0\.05 seconds.*"Codex Auth"/+ );+ expect(sources[0]?.stdin.writableEnded).toBe(true);+ });+});diff --git a/console/packages/agent-providers/src/codex/keyring-login.ts b/console/packages/agent-providers/src/codex/keyring-login.tsnew file mode 100644index 000000000..3f9f34a0b--- /dev/null+++ b/console/packages/agent-providers/src/codex/keyring-login.ts@@ -0,0 +1,136 @@+import { stat } from 'node:fs/promises';+import { z } from 'zod';+import type { CodexKeyringLogin } from '../adapter';+import { JsonRpcError, noopLogger, StdioJsonRpcClient } from '../transport/stdio-json-rpc';++/**+ * Long enough for someone at the machine to answer a keychain prompt, short+ * enough that a prompt nobody sees fails the session with a reason.+ */+export const CODEX_KEYRING_READ_TIMEOUT_MS = 30_000;++const METHOD_NOT_FOUND = -32601;++export const CODEX_FILE_STORE_WORKAROUND =+ 'Unless your organization enforces the keyring, set cli_auth_credentials_store = "file" in the ' ++ 'Codex config.toml on the execution machine, which keeps the login in plaintext, then run codex ' ++ 'login again and start a new session.';++const accountSchema = z.object({+ account: z.object({ type: z.string() }).nullable(),+ requiresOpenaiAuth: z.boolean(),+});++const authStatusSchema = z.object({+ authMethod: z.string().nullable(),+ authToken: z.string().nullish(),+});++/** A refusal worded here, passed on as it is. */+class KeyringLoginError extends Error {}++function loginKind(type: string): string {+ return type === 'chatgpt' ? 'ChatGPT' : `a ${type} login`;+}++/**+ * The API key the execution machine's Codex keeps in the OS keyring, for a+ * session whose own Codex home has no login to copy. Codex keys a keyring+ * entry by its home's path, so the session's Codex cannot find it; Codex run+ * against its own home reads it instead, and the keychain answers the program+ * that stored the entry without asking anyone.+ *+ * Only an API key is handed over. A ChatGPT login cannot be: Codex exports its+ * access token alone, which expires and cannot be refreshed without the+ * refresh token it keeps. The account is read before the key is asked for+ * because asking refreshes a stale ChatGPT login and writes it back to the+ * user's keyring, racing their own Codex.+ *+ * Null when the machine's Codex is signed out.+ */+export async function readCodexKeyringApiKey(+ binaryPath: string,+ login: CodexKeyringLogin,+ timeoutMs: number+): Promise<string | null> {+ try {+ await stat(login.home);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw new Error('Could not load the execution-host Codex login.', { cause: error });+ }+ // Run in the home rather than the agent's directory, so no project+ // configuration changes where this Codex reads its login.+ const client = new StdioJsonRpcClient({+ command: binaryPath,+ args: ['app-server'],+ cwd: login.home,+ env: { ...login.env, CODEX_HOME: login.home },+ logger: noopLogger,+ onExit: () => {},+ });+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () =>+ reject(+ new KeyringLoginError(+ `Codex on the execution machine did not read its login from the OS keyring within ${timeoutMs / 1000} seconds. The keychain may be locked, or the system may be waiting for someone at that machine to let Codex use its "Codex Auth" keychain item; start the session again once it can.`+ )+ ),+ timeoutMs+ );+ });+ try {+ return await Promise.race([readApiKey(client), timeout]);+ } catch (error) {+ if (error instanceof KeyringLoginError) throw error;+ const output = client.stderr.trim();+ throw new Error(+ `Codex on the execution machine could not report its login: ${error instanceof Error ? error.message : String(error)}${output ? `\n${output}` : ''}`,+ { cause: error }+ );+ } finally {+ clearTimeout(timer);+ // Whatever was read, or went wrong, is the answer: a reader that will not+ // stop is reported, not put in its place.+ await client+ .dispose()+ .catch((error: unknown) =>+ console.warn(+ `The Codex that read a keyring login did not stop: ${error instanceof Error ? error.message : String(error)}`+ )+ );+ }+}++async function readApiKey(client: StdioJsonRpcClient): Promise<string | null> {+ await client.request('initialize', { clientInfo: { name: 'switch-console', version: '0.1.0' } });+ client.notify('initialized', null);+ const { account } = accountSchema.parse(+ await client.request('account/read', { refreshToken: false })+ );+ if (!account) return null;+ if (account.type !== 'apiKey')+ throw new KeyringLoginError(+ `Codex on the execution machine is signed in with ${loginKind(account.type)} and has no auth.json, so its login is likely in the OS keyring (cli_auth_credentials_store = "keyring" or "auto"). A Switch session can take a login from the keyring only when it is an API key. ${CODEX_FILE_STORE_WORKAROUND}`+ );+ let status: z.infer<typeof authStatusSchema>;+ try {+ status = authStatusSchema.parse(+ await client.request('getAuthStatus', { includeToken: true, refreshToken: false })+ );+ } catch (error) {+ if (error instanceof JsonRpcError && error.code === METHOD_NOT_FOUND)+ throw new KeyringLoginError(+ `This version of Codex cannot hand Switch the API key it keeps in the OS keyring: it no longer answers getAuthStatus. ${CODEX_FILE_STORE_WORKAROUND}`,+ { cause: error }+ );+ throw error;+ }+ if (status.authMethod !== 'apikey' || !status.authToken)+ throw new KeyringLoginError(+ `Codex on the execution machine reported an API-key login but did not hand over the key. ${CODEX_FILE_STORE_WORKAROUND}`+ );+ return status.authToken;+}diff --git a/console/packages/agent-providers/src/host/agent-env.test.ts b/console/packages/agent-providers/src/host/agent-env.test.tsnew file mode 100644index 000000000..22323866a--- /dev/null+++ b/console/packages/agent-providers/src/host/agent-env.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';+import { codexKeyringReaderEnvironment } from './agent-env';++describe('codexKeyringReaderEnvironment', () => {+ const session = {+ PATH: '/usr/bin',+ HOME: '/home/user',+ CODEX_HOME: '/sessions/home',+ OPENAI_API_KEY: 'session-only',+ SWITCH_SERVICE_BEARER: 'session-only',+ GH_TOKEN: 'session-only',+ };++ it('gives the reader the basics and the host’s session bus, and none of the session’s credentials', () => {+ expect(+ codexKeyringReaderEnvironment(+ session,+ { DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus', SECRET: 'host-only' },+ 'linux'+ )+ ).toEqual({+ PATH: '/usr/bin',+ HOME: '/home/user',+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',+ });+ });++ it('prefers a session bus the session already names', () => {+ expect(+ codexKeyringReaderEnvironment(+ { ...session, XDG_RUNTIME_DIR: '/run/user/1000' },+ { XDG_RUNTIME_DIR: '/run/user/other' },+ 'linux'+ ).XDG_RUNTIME_DIR+ ).toBe('/run/user/1000');+ });++ it('matches names without regard to case on Windows only', () => {+ const windows = { Path: 'C:\\bin', SystemRoot: 'C:\\Windows', Switch_Service_Bearer: 'x' };+ expect(codexKeyringReaderEnvironment(windows, {}, 'win32')).toEqual({+ Path: 'C:\\bin',+ SystemRoot: 'C:\\Windows',+ });+ expect(codexKeyringReaderEnvironment(windows, {}, 'linux')).toEqual({});+ });+});diff --git a/console/packages/agent-providers/src/host/agent-env.ts b/console/packages/agent-providers/src/host/agent-env.tsindex aa1044857..7e921cc3a 100644--- a/console/packages/agent-providers/src/host/agent-env.ts+++ b/console/packages/agent-providers/src/host/agent-env.ts@@ -112,3 +112,48 @@ export const EXECUTION_INHERIT_ENV: readonly string[] = ['SSH_AUTH_SOCK',...WINDOWS_ENV,];++/** The basics a CLI needs to find itself and its home. */+const CODEX_KEYRING_READER_ENV = [+ 'PATH',+ 'HOME',+ 'USER',+ 'SHELL',+ 'TMPDIR',+ 'LANG',+ ...WINDOWS_ENV,+];++/**+ * How Codex on Linux reaches the Secret Service that holds a keyring login,+ * taken from the session host's own environment. Only the Codex that reads+ * the login is given these; sessions are not, so no provider starts using a+ * keyring it could not reach before. Untested on Linux so far.+ */+const KEYRING_BUS_ENV = ['DBUS_SESSION_BUS_ADDRESS', 'XDG_RUNTIME_DIR'];++/**+ * The environment of the Codex that reads a keyring login for a session+ * (`codex/keyring-login.ts`): what it needs from the session's, and the+ * keyring bus from the host's when the session's names none. None of the+ * credentials the session is given reach it. Matched without regard to case+ * on Windows.+ */+export function codexKeyringReaderEnvironment(+ sessionEnv: Record<string, string>,+ hostEnv: NodeJS.ProcessEnv,+ platform: NodeJS.Platform+): Record<string, string> {+ const pick = (env: Record<string, string | undefined>, names: readonly string[]) => {+ const wanted = new Set(platform === 'win32' ? names.map((name) => name.toUpperCase()) : names);+ const picked: Record<string, string> = {};+ for (const [name, value] of Object.entries(env))+ if (value && wanted.has(platform === 'win32' ? name.toUpperCase() : name))+ picked[name] = value;+ return picked;+ };+ return {+ ...pick(hostEnv, KEYRING_BUS_ENV),+ ...pick(sessionEnv, [...CODEX_KEYRING_READER_ENV, ...KEYRING_BUS_ENV]),+ };+}diff --git a/console/packages/agent-providers/src/host/hosted-provider.test.ts b/console/packages/agent-providers/src/host/hosted-provider.test.tsindex 213689cbe..86ff48b92 100644--- a/console/packages/agent-providers/src/host/hosted-provider.test.ts+++ b/console/packages/agent-providers/src/host/hosted-provider.test.ts@@ -91,12 +91,13 @@ it('keeps the prepared Codex home and refreshes its auth before provider startupconst original = credential('{"fixture":"original"}');await materializeHostedProvider(root, env, original, 'fixture-cli');const sourceHome = env.CODEX_HOME!;- const home = await prepareCodexSessionHome({+ const { home, keyringLogin } = await prepareCodexSessionHome({root: sourceHome,sessionId: 'session',sourceHome,config: 'model = "fixture-model"',});+ expect(keyringLogin).toBe(false);env.CODEX_HOME = home;await writeFile(join(home, 'auth.json'), '{"fixture":"native-refresh"}');await materializeHostedProvider(root, env, original, 'fixture-cli');diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.tsindex 2f5490f6e..28a6b16ce 100644--- a/console/packages/agent-providers/src/host/shared-config.test.ts+++ b/console/packages/agent-providers/src/host/shared-config.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -11,6 +11,7 @@ import {} from './shared-config';const NO_SERVICES = { grants: [], unavailable: null };+const NO_REDACTIONS = () => {};afterEach(() => vi.unstubAllEnvs());@@ -112,7 +113,15 @@ it('gives the provider the host’s own MCP server and no Switch identity', asynurl: 'http://127.0.0.1:4321/mcp',headers: { Authorization: 'Bearer per-session' },};- const prepared = await prepareSharedConfig(root, config, runtime, NO_SERVICES, null, {});+ const prepared = await prepareSharedConfig(+ root,+ config,+ runtime,+ NO_SERVICES,+ null,+ {},+ NO_REDACTIONS+ );expect(prepared.input.mcpServers).toEqual({ switch: runtime });expect(prepared.input.env).toEqual({ CONFIGURED: 'yes' });// The host itself still reports to Switch as the agent.@@ -122,72 +131,133 @@ it('gives the provider the host’s own MCP server and no Switch identity', asyn}});+/** A Codex session's launch spec, taking its Codex home from `CODEX_HOME`. */+async function codexHostConfig(root: string) {+ const credentialsPath = join(root, 'credentials.json');+ await writeFile(+ credentialsPath,+ JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://switch.test',+ SWITCH_API_TOKEN: 'agent-token',+ SWITCH_AGENT_ID: 'agent',+ },+ })+ );+ return sharedConfigSchema.parse({+ session: {+ sessionId: 'session',+ agentId: 'agent',+ hostId: 'host',+ epoch: 'epoch',+ provider: 'codex',+ status: 'starting',+ connectivity: 'online',+ pendingRequestIds: [],+ capabilities: {+ input: 'queue',+ approvals: true,+ questions: true,+ interrupt: true,+ reset: false,+ compact: false,+ modelChange: false,+ attachmentMimeTypes: [],+ },+ },+ start: {+ provider: 'codex',+ input: {+ sessionId: 'session',+ cwd: root,+ runtimeMode: 'approval-required',+ env: { CONFIGURED: 'yes', CODEX_HOME: join(root, 'codex-source') },+ mcpServers: {},+ },+ },+ roomConnection: { connectionId: 'controller' },+ execution: {+ credentialsPath,+ inheritEnv: [],+ codexConfig: '',+ skill: '',+ context: 'Switch skill text',+ },+ });+}++const CODEX_RUNTIME = {+ transport: 'http' as const,+ url: 'http://127.0.0.1:4321/mcp',+ headers: { Authorization: 'Bearer per-session' },+};+it('gives Codex the Switch skill as instructions, like the other providers', async () => {const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));try {- const credentialsPath = join(root, 'credentials.json');- await writeFile(- credentialsPath,- JSON.stringify({- env: {- SWITCH_API_ENDPOINT: 'https://switch.test',- SWITCH_API_TOKEN: 'agent-token',- SWITCH_AGENT_ID: 'agent',- },- })+ const config = await codexHostConfig(root);+ const prepared = await prepareSharedConfig(+ root,+ config,+ CODEX_RUNTIME,+ NO_SERVICES,+ null,+ {},+ NO_REDACTIONS);- const config = sharedConfigSchema.parse({- session: {- sessionId: 'session',- agentId: 'agent',- hostId: 'host',- epoch: 'epoch',- provider: 'codex',- status: 'starting',- connectivity: 'online',- pendingRequestIds: [],- capabilities: {- input: 'queue',- approvals: true,- questions: true,- interrupt: true,- reset: false,- compact: false,- modelChange: false,- attachmentMimeTypes: [],- },- },- start: {- provider: 'codex',- input: {- sessionId: 'session',- cwd: root,- runtimeMode: 'approval-required',- env: { CONFIGURED: 'yes', CODEX_HOME: join(root, 'codex-source') },- mcpServers: {},- },- },- roomConnection: { connectionId: 'controller' },- execution: {- credentialsPath,- inheritEnv: [],- codexConfig: '',- skill: '',- context: 'Switch skill text',- },- });- const runtime = {- transport: 'http' as const,- url: 'http://127.0.0.1:4321/mcp',- headers: { Authorization: 'Bearer per-session' },- };- const prepared = await prepareSharedConfig(root, config, runtime, NO_SERVICES, null, {});expect(prepared.input.systemContext).toBe('Switch skill text');} finally {await rm(root, { recursive: true, force: true });}});+it('hands a Codex session the keyring login of a home with no auth.json, with only what reading it needs', async () => {+ vi.stubEnv('DBUS_SESSION_BUS_ADDRESS', 'unix:path=/run/user/1000/bus');+ vi.stubEnv('XDG_RUNTIME_DIR', '/run/user/1000');+ const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));+ try {+ const source = join(root, 'codex-source');+ const config = await codexHostConfig(root);+ Object.assign(config.start.input.env, { PATH: '/usr/bin', OPENAI_API_KEY: 'session-only' });+ const redact = vi.fn();+ const keyring = await prepareSharedConfig(+ root,+ config,+ CODEX_RUNTIME,+ NO_SERVICES,+ null,+ {},+ redact+ );+ const login = keyring.input.codexKeyringLogin;+ expect(login?.home).toBe(source);+ expect(login?.env).toEqual({+ PATH: '/usr/bin',+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/run/user/1000/bus',+ XDG_RUNTIME_DIR: '/run/user/1000',+ });+ login?.redact('fixture-secret');+ expect(redact).toHaveBeenCalledWith('fixture-secret');+ expect(keyring.input.env.CODEX_HOME).not.toBe(source);+ expect(keyring.input.env.DBUS_SESSION_BUS_ADDRESS).toBeUndefined();++ await mkdir(source, { recursive: true });+ await writeFile(join(source, 'auth.json'), '{"fixture":"login"}');+ const file = await prepareSharedConfig(+ root,+ await codexHostConfig(root),+ CODEX_RUNTIME,+ NO_SERVICES,+ null,+ {},+ NO_REDACTIONS+ );+ expect(file.input.codexKeyringLogin).toBeUndefined();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});+describe('agent definitions in the launch spec', () => {const base = (input: Record<string, unknown>, execution: Record<string, unknown> = {}) => ({session: {@@ -355,7 +425,8 @@ describe('the skills of the agent’s service grants', () => {runtime,{ grants: [GITHUB_GRANT], unavailable: null },null,- {}+ {},+ NO_REDACTIONS);expect(claude.input.systemContext).toBe('Switch skill text\n\n# GitHub\n\nUse gh.');const opencode = await prepareSharedConfig(@@ -364,7 +435,8 @@ describe('the skills of the agent’s service grants', () => {runtime,{ grants: [GITHUB_GRANT], unavailable: null },null,- {}+ {},+ NO_REDACTIONS);expect(opencode.input.systemContext).toBe('Switch skill text');// Without a service endpoint nothing is set up for GitHub.@@ -389,13 +461,22 @@ describe('the skills of the agent’s service grants', () => {runtime,NO_SERVICES,null,- { example: vendor }+ { example: vendor },+ NO_REDACTIONS);expect(prepared.input.mcpServers).toEqual({ example: vendor, switch: runtime });await expect(- prepareSharedConfig(root, await configFor(root, 'claude'), runtime, NO_SERVICES, null, {- switch: vendor,- })+ prepareSharedConfig(+ root,+ await configFor(root, 'claude'),+ runtime,+ NO_SERVICES,+ null,+ {+ switch: vendor,+ },+ NO_REDACTIONS+ )).rejects.toThrow('which is taken');} finally {await rm(root, { recursive: true, force: true });@@ -416,7 +497,8 @@ describe('the skills of the agent’s service grants', () => {NO_SERVICES,null,// A vendor MCP server and a vendor CLI, both served on loopback.- { atlassian: served(4400), 'google-workspace': served(4401) }+ { atlassian: served(4400), 'google-workspace': served(4401) },+ NO_REDACTIONS);expect(prepared.input.connectorMcpServers.sort()).toEqual(['atlassian', 'google-workspace']);expect(prepared.input.connectorMcpServers).not.toContain('switch');@@ -431,7 +513,8 @@ describe('the skills of the agent’s service grants', () => {runtime,NO_SERVICES,null,- {}+ {},+ NO_REDACTIONS);expect(none.input.connectorMcpServers).toEqual([]);} finally {@@ -449,7 +532,8 @@ describe('the skills of the agent’s service grants', () => {runtime,{ grants: [], unavailable: 'Switch refused (HTTP 503).' },null,- {}+ {},+ NO_REDACTIONS);expect(prepared.input.systemContext).toBe(`Switch skill text\n\n${servicesUnavailableNotice('Switch refused (HTTP 503).')}`@@ -476,7 +560,8 @@ describe('the skills of the agent’s service grants', () => {execPath: '/usr/bin/node',entrypoint: '/opt/switch/shared-host.mjs',},- {}+ {},+ NO_REDACTIONS);// Git and gh ask the endpoint, which refuses, rather than this machine's sign-in.expect(prepared.input.env.SWITCH_SERVICE_ENDPOINT).toBe('http://127.0.0.1:5555');@@ -509,7 +594,8 @@ describe('the skills of the agent’s service grants', () => {execPath: '/usr/bin/node',entrypoint: '/opt/switch/shared-host.mjs',},- {}+ {},+ NO_REDACTIONS);const env = prepared.input.env;expect(env.SWITCH_SERVICE_ENDPOINT).toBe('http://127.0.0.1:5555');diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.tsindex f5c9a1bef..527e974cb 100644--- a/console/packages/agent-providers/src/host/shared-config.ts+++ b/console/packages/agent-providers/src/host/shared-config.ts@@ -2,12 +2,13 @@ import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';import { readFile, stat } from 'node:fs/promises';import { homedir } from 'node:os';-import { join } from 'node:path';+import { join, resolve } from 'node:path';import { promisify } from 'node:util';import { sessionSchema } from '@switch-console/shared/session-v1';import { z } from 'zod';-import type { HttpMcpServerSpec, ProviderSessionStartInput } from '../adapter';+import type { CodexKeyringLogin, HttpMcpServerSpec, ProviderSessionStartInput } from '../adapter';import { prepareCodexSessionHome } from '../codex/home';+import { codexKeyringReaderEnvironment } from './agent-env';import { agentHasOwnUser } from './host-permissions';import { type HostedCredential, hostedCredentialSchema } from './provider-login';import { roomConnectionSchema } from './room-inbox';@@ -127,7 +128,8 @@ export async function prepareSharedConfig(runtime: HttpMcpServerSpec,services: SessionServices,helpers: ServiceHelpers | null,- vendors: Record<string, HttpMcpServerSpec>+ vendors: Record<string, HttpMcpServerSpec>,+ redact: (secret: string) => void) {if (config.session.provider !== config.start.provider)throw new Error('Shared SDK host provider mismatch.');@@ -136,6 +138,7 @@ export async function prepareSharedConfig(let agentApiUrl = process.env.SWITCH_API_ENDPOINT;let token = process.env.SWITCH_API_TOKEN;const input = structuredClone(config.start.input);+ let codexKeyringLogin: CodexKeyringLogin | undefined;if (config.execution) {const execution = config.execution;if (execution.agentDefinition) {@@ -157,13 +160,22 @@ export async function prepareSharedConfig(execution.inheritEnv);input.env = { ...inherited, ...input.env };- if (config.start.provider === 'codex')- input.env.CODEX_HOME = await prepareCodexSessionHome({+ if (config.start.provider === 'codex') {+ const sourceHome = resolve(input.env.CODEX_HOME || join(homedir(), '.codex'));+ const prepared = await prepareCodexSessionHome({root: join(root, 'provider-home'),sessionId: config.session.sessionId,- sourceHome: input.env.CODEX_HOME || join(homedir(), '.codex'),+ sourceHome,config: execution.codexConfig,});+ if (prepared.keyringLogin)+ codexKeyringLogin = {+ home: sourceHome,+ env: codexKeyringReaderEnvironment(input.env, process.env, process.platform),+ redact,+ };+ input.env.CODEX_HOME = prepared.home;+ }// The skills of the agent's grants join the context for every provider// but OpenCode, which loads them as files (`adapterFor`), as it does the// Switch skill. Added here rather than saved with the session, so a@@ -216,6 +228,7 @@ export async function prepareSharedConfig(const started: ProviderSessionStartInput = {...input,connectorMcpServers: Object.keys(vendors),+ ...(codexKeyringLogin ? { codexKeyringLogin } : {}),};return { agentApiUrl, token, input: started, notices };}diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex a8dbe8f76..c1b9d1bb5 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -1108,7 +1108,8 @@ export async function hostSessionProcess(input: {mcp.spec,input.services,endpoint && { endpoint, execPath: process.execPath, entrypoint: input.entrypoint },- { ...vendors.specs, ...clis.specs }+ { ...vendors.specs, ...clis.specs },+ (secret) => redactions.add(secret));for (const notice of prepared.notices) serviceNotices.raise(notice);// The people watching see it as a notice; the agent reads it with the