Autonomous research system for measurable, computer-executable research.
Python
fix: preserve Codex keyring auth identity (#10)
electrixoulaa198d089fde
diff --git a/docs/guides/credentials.md b/docs/guides/credentials.mdindex 435971d..5595d02 100644--- a/docs/guides/credentials.md+++ b/docs/guides/credentials.md@@ -61,12 +61,12 @@ redacted identity; for file-based login it includes a hash of the stable accountidentifier, never a token. At runtime Praxist stages `auth.json`, when present,inside a private disposable OS-temporary Codex home so the app-server canrefresh its own copy without writing the operator's `CODEX_HOME`. Keyring-backed-login uses the same private empty home and the operating-system credential-store. The private home is removed when its app-server closes and is never put-in task files, run artifacts, logs, or replay. The runtime verifies the-app-server account is actually `chatgpt` before starting a peer turn, blanks-API-key endpoint overrides, and never falls back to an API or relay when-Codex-native mode was selected.+login retains the operator home as the stable operating-system keyring namespace;+database and log state remain run-local. A private file-backed home is removed+when its app-server closes and is never put in task files, run artifacts, logs,+or replay. The runtime verifies the app-server account is actually `chatgpt`+before starting a peer turn, blanks API-key endpoint overrides, and never falls+back to an API or relay when Codex-native mode was selected.On resume, `--codex-native` may select saved-login authentication only when theexisting run already has the canonical `codex_sdk` agent runtime and native OpenAIdiff --git a/praxist/plugins/agent_runtimes/codex_sdk/_auth.py b/praxist/plugins/agent_runtimes/codex_sdk/_auth.pyindex f0f2c05..e672cae 100644--- a/praxist/plugins/agent_runtimes/codex_sdk/_auth.py+++ b/praxist/plugins/agent_runtimes/codex_sdk/_auth.py@@ -54,16 +54,18 @@ _PROBE_ENV_KEYS = frozenset(@dataclassclass StagedChatgptHome:- """Private, disposable Codex home containing only runtime authentication."""+ """Codex home preserving auth identity without sharing file-backed state."""path: Pathcredential_store: strcredential_key_id: str+ remove_on_close: bool = Truedef close(self) -> None:- """Remove the staged credential and all app-server-owned scratch state."""+ """Remove disposable authentication state owned by this instance."""- shutil.rmtree(self.path, ignore_errors=True)+ if self.remove_on_close:+ shutil.rmtree(self.path, ignore_errors=True)def discover_chatgpt_credential(@@ -140,18 +142,28 @@ def chatgpt_credential_key_id(codex_home: Path) -> str:def stage_chatgpt_home(codex_home: Path) -> StagedChatgptHome:- """Stage saved auth in a private home so Codex cannot mutate operator state."""+ """Resolve a safe runtime home without changing the saved-auth identity."""source_home = codex_home.resolve()snapshot = _read_chatgpt_file_auth(source_home)source = "file" if snapshot is not None else "keyring"account_id = snapshot[1] if snapshot is not None else None+ credential_key_id = _credential_key_id(source_home, source, account_id)+ if snapshot is None:+ # Codex derives its keyring lookup key from canonical CODEX_HOME.+ return StagedChatgptHome(+ path=source_home,+ credential_store=source,+ credential_key_id=credential_key_id,+ remove_on_close=False,+ )+path = Path(tempfile.mkdtemp(prefix="praxist-codex-auth-"))path.chmod(0o700)staged = StagedChatgptHome(path=path,credential_store=source,- credential_key_id=_credential_key_id(source_home, source, account_id),+ credential_key_id=credential_key_id,)try:if snapshot is not None:diff --git a/praxist/plugins/agent_runtimes/codex_sdk/adapter.py b/praxist/plugins/agent_runtimes/codex_sdk/adapter.pyindex 4da92b5..4c40d77 100644--- a/praxist/plugins/agent_runtimes/codex_sdk/adapter.py+++ b/praxist/plugins/agent_runtimes/codex_sdk/adapter.py@@ -9,6 +9,7 @@ import hashlibimport jsonimport loggingimport os+import tempfileimport threadingfrom collections.abc import Awaitable, Callable, Iterator, Mappingfrom concurrent.futures import Future as ConcurrentFuture@@ -809,22 +810,37 @@ def available_chatgpt_models() -> tuple[str, ...]:client: Any | None = Nonetry:sdk = _load_sdk()- config = sdk["CodexConfig"](- codex_bin=resolve_codex_binary(),- config_overrides=_SUBSCRIPTION_RUNTIME_OVERRIDES,- env=_client_process_env("openai", os.environ, staged.path, subscription=True),- )- client = sdk["Codex"](config)- response = client.models(include_hidden=False)- return tuple(- sorted(- {- str(item.model).strip()- for item in getattr(response, "data", ())- if str(getattr(item, "model", "")).strip()- }- )- )+ with tempfile.TemporaryDirectory(prefix="praxist-codex-probe-") as state_dir:+ try:+ config = sdk["CodexConfig"](+ codex_bin=resolve_codex_binary(),+ config_overrides=(+ "cli_auth_credentials_store=" + json.dumps(staged.credential_store),+ f"sqlite_home={json.dumps(state_dir)}",+ f"log_dir={json.dumps(state_dir)}",+ *_SUBSCRIPTION_RUNTIME_OVERRIDES,+ ),+ env=_client_process_env("openai", os.environ, staged.path, subscription=True),+ )+ client = sdk["Codex"](config)+ account = client.account(refresh_token=False)+ if _codex_account_type(account) != "chatgpt":+ raise RuntimeError("Codex app-server did not select ChatGPT authentication")+ response = client.models(include_hidden=False)+ return tuple(+ sorted(+ {+ str(item.model).strip()+ for item in getattr(response, "data", ())+ if str(getattr(item, "model", "")).strip()+ }+ )+ )+ finally:+ if client is not None:+ with contextlib.suppress(Exception):+ client.close()+ client = Noneexcept Exception: # noqa: BLE001 - never expose account or app-server details.raise RuntimeError("Unable to read the available ChatGPT Codex model catalog") from Nonefinally:diff --git a/tests/unit/test_codex_sdk_adapter.py b/tests/unit/test_codex_sdk_adapter.pyindex fdf24bb..ca2576c 100644--- a/tests/unit/test_codex_sdk_adapter.py+++ b/tests/unit/test_codex_sdk_adapter.py@@ -904,6 +904,56 @@ class RuntimeExecutionTest(unittest.IsolatedAsyncioTestCase):await runtime.aclose()self.assertFalse(staged_home.exists())+ async def test_chatgpt_subscription_preserves_keyring_home_identity(self) -> None:+ from praxist.plugins.agent_runtimes.codex_sdk._auth import chatgpt_credential_key_id++ runtime = CodexSdkRuntime()+ self.addAsyncCleanup(runtime.aclose)+ harness = _SdkHarness()+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ run_dir = root / "run"+ run_dir.mkdir()+ codex_home = root / "operator-codex"+ codex_home.mkdir()+ marker = codex_home / "config.toml"+ marker.write_text('model = "operator-default"\n', encoding="utf-8")+ credential = CredentialRef(+ scope="model_provider",+ provider="openai_compatible",+ target_ref="model_provider:openai_compatible",+ key_id=chatgpt_credential_key_id(codex_home),+ source="runtime_session",+ )+ with (+ patch.object(adapter, "_load_sdk", side_effect=lambda: harness.sdk()),+ patch.object(adapter, "start_relay") as relay,+ patch.object(adapter, "resolve_codex_binary", return_value="/sdk/codex"),+ patch.object(adapter, "verify_chatgpt_login"),+ patch.dict("os.environ", {"CODEX_HOME": str(codex_home)}, clear=False),+ ):+ result = await runtime.execute(+ _request(+ str(run_dir),+ provider_ref="model_provider:openai_compatible",+ credential_ref=credential,+ ),+ AgentRuntimeExecutionContext(env={}),+ )++ self.assertTrue(result.success, result.error)+ relay.assert_not_called()+ client = harness.clients[0]+ self.assertEqual(client.account_calls, [False])+ config = harness.configs[0].kwargs+ self.assertEqual(Path(config["env"]["CODEX_HOME"]), codex_home)+ self.assertIn(+ 'cli_auth_credentials_store="keyring"',+ config["config_overrides"],+ )+ await runtime.aclose()+ self.assertEqual(marker.read_text(encoding="utf-8"), 'model = "operator-default"\n')+async def test_chatgpt_subscription_rejects_non_chatgpt_app_server_account(self) -> None:from praxist.plugins.agent_runtimes.codex_sdk._auth import chatgpt_credential_key_iddiff --git a/tests/unit/test_codex_sdk_auth.py b/tests/unit/test_codex_sdk_auth.pyindex d397e68..1ae4097 100644--- a/tests/unit/test_codex_sdk_auth.py+++ b/tests/unit/test_codex_sdk_auth.py@@ -390,18 +390,19 @@ class ChatGptCredentialDiscoveryTest(unittest.TestCase):staged.close()self.assertFalse(staged_path.exists())- def test_keyring_auth_uses_empty_private_home(self) -> None:+ def test_keyring_auth_preserves_operator_home_as_lookup_identity(self) -> None:from praxist.plugins.agent_runtimes.codex_sdk._auth import stage_chatgpt_homewith tempfile.TemporaryDirectory() as tmp:- staged = stage_chatgpt_home(Path(tmp))- staged_path = staged.path- try:- self.assertEqual(staged.credential_store, "keyring")- self.assertEqual(list(staged_path.iterdir()), [])- finally:- staged.close()- self.assertFalse(staged_path.exists())+ operator_home = Path(tmp)+ marker = operator_home / "config.toml"+ marker.write_text('model = "operator-default"\n', encoding="utf-8")+ staged = stage_chatgpt_home(operator_home)++ self.assertEqual(staged.path, operator_home)+ self.assertEqual(staged.credential_store, "keyring")+ staged.close()+ self.assertEqual(marker.read_text(encoding="utf-8"), 'model = "operator-default"\n')class CodexSdkRuntimeCredentialHookTest(unittest.TestCase):@@ -459,7 +460,9 @@ class ChatGptModelCatalogTest(unittest.TestCase):def test_catalog_uses_private_staged_auth_and_closes_resources(self) -> None:from praxist.plugins.agent_runtimes.codex_sdk import adapter- staged = types.SimpleNamespace(path=Path("/private/codex"), close=Mock())+ staged = types.SimpleNamespace(+ path=Path("/private/codex"), credential_store="file", close=Mock()+ )response = types.SimpleNamespace(data=[types.SimpleNamespace(model="gpt-5.6-luna"),@@ -468,6 +471,9 @@ class ChatGptModelCatalogTest(unittest.TestCase):])client = Mock()+ client.account.return_value = types.SimpleNamespace(+ account=types.SimpleNamespace(root=types.SimpleNamespace(type="chatgpt"))+ )client.models.return_value = responseconfig = object()sdk = {@@ -488,7 +494,41 @@ class ChatGptModelCatalogTest(unittest.TestCase):self.assertEqual(models, ("gpt-5.4", "gpt-5.6-luna"))verify_login.assert_called_once_with()+ client.account.assert_called_once_with(refresh_token=False)client.models.assert_called_once_with(include_hidden=False)+ self.assertIn(+ 'cli_auth_credentials_store="file"',+ sdk["CodexConfig"].call_args.kwargs["config_overrides"],+ )+ client.close.assert_called_once_with()+ staged.close.assert_called_once_with()++ def test_catalog_rejects_non_chatgpt_app_server_account(self) -> None:+ from praxist.plugins.agent_runtimes.codex_sdk import adapter++ staged = types.SimpleNamespace(+ path=Path("/operator/codex"), credential_store="keyring", close=Mock()+ )+ client = Mock()+ client.account.return_value = types.SimpleNamespace(+ account=types.SimpleNamespace(root=types.SimpleNamespace(type="apiKey"))+ )+ sdk = {+ "Codex": Mock(return_value=client),+ "CodexConfig": Mock(return_value=object()),+ }+ with (+ patch.object(adapter, "verify_chatgpt_login"),+ patch.object(adapter, "operator_codex_home", return_value=staged.path),+ patch.object(adapter, "stage_chatgpt_home", return_value=staged),+ patch.object(adapter, "resolve_codex_binary", return_value="/sdk/codex"),+ patch.object(adapter, "_client_process_env", return_value={}),+ patch.object(adapter, "_load_sdk", return_value=sdk),+ self.assertRaisesRegex(RuntimeError, "model catalog"),+ ):+ adapter.available_chatgpt_models()++ client.models.assert_not_called()client.close.assert_called_once_with()staged.close.assert_called_once_with()