ISSUE DESCRIPTION gemini-cli: support Login with Google (oauth-personal), mirroring…
- User
ISSUE DESCRIPTION
gemini-cli: support Login with Google (oauth-personal), mirroring codex auth.json The
codexagent injects a cached OAuth credential (~/.codex/auth.json) so runs can use a login instead of an API key (CODEX_AUTH_JSON_PATH/CODEX_FORCE_AUTH_JSON), andclaude-codeacceptsCLAUDE_CODE_OAUTH_TOKEN(#173).gemini-clihas no equivalent — it only wiresGEMINI_API_KEY/ Vertex env, so users with a "Login with Google" session (~/.gemini/oauth_creds.json) must keep a separate API key for runs.Proposal: add the same opt-in OAuth-credential injection to the
gemini-cliagent, mirroring the codex pattern —GEMINI_OAUTH_CREDS_PATH/GEMINI_FORCE_OAUTH, default behavior unchanged (fully backward-compatible).I have a working implementation that mirrors the codex auth flow (
_resolve_oauth_creds_path→ upload → chown →~/.gemini) with tests ported 1:1 fromtest_codex_auth.py, verified end-to-end (gemini-cli --ae GEMINI_FORCE_OAUTH=truecompleted hello-world, reward 1.0). Happy to open the PR or hand it off — whichever you prefer.Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /harbor, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand how it's organized and find relevant files related to the OAuth authentication flow.
The issue is about adding OAuth credential injection to the gemini-cli agent, similar to how codex handles it. Let me first explore the repository structure to understand what we're working with.
Assistant
Let me explore more to understand the structure. Let me look at the adapters folder and search for gemini-related code.
<tool_call> <function=bash_terminal> <parameter=command> find /harbor -type d -name "gemini" | head -20 </tool_call>
Assistant
Let me search for gemini-related code in the repository.
Assistant
Let me search more broadly for gemini CLI related files or folders.
<tool_call> <function=bash_terminal> <parameter=command> ls -la /harbor/adapters/ </tool_call>
Assistant
Let me use the proper tool syntax for the bash terminal command.
Assistant
This repository seems to be about benchmark adapters. Let me search for gemini-cli or auth-related code more broadly.
<tool_call> <function=bash_terminal> <parameter=command> grep -r "gemini-cli" /harbor --include=".py" --include=".md" --include="*.json" 2>/dev/null | head -20 </tool_call>
Assistant
Let me try using the grep command properly to search for gemini-cli related content.
Assistant
Now I found relevant files. Let me look at the gemini_cli.py agent implementation and also search for the codex auth implementation to understand the pattern.
<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use the proper tool syntax for the bash terminal command to view the gemini_cli.py file.
Assistant
Now let me search for the codex auth implementation to understand the pattern we need to mirror.
<tool_call> <function=bash_terminal> <parameter=command> grep -r "oauth" /harbor --include="*.py" 2>/dev/null | grep -v ".venv" | head -30 </tool_call>
Assistant
Let me search for oauth-related code in the repository to understand the pattern.
Assistant
The results show OAuth authentication related to the viewer server and auth handler, but not the specific OAuth credential injection for gemini-cli that we need. Let me search for "codex" and "auth.json" to find the pattern for codex auth.
<tool_call> <function=bash_terminal> <parameter=command> grep -r "auth.json" /harbor --include="*.py" 2>/dev/null | grep -v ".venv" | head -30 </tool_call>
Assistant
Let me try a different approach - let me search for codex-related files and look at how auth.json is used.
Assistant
Now I found relevant files. Let me look at the codex.py file to understand the auth.json injection pattern.
<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/src/harbor/agents/installed/codex.py </tool_call>
Assistant
Let me use the proper tool syntax for the bash terminal command to view the codex.py file.
Assistant
I made a typo - let me fix it.
<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/src/harbor/agents/installed/codex.py </tool_call>
Assistant
Let me use the proper tool syntax for the bash terminal command to view the codex.py file.
Assistant
Now I understand the codex auth.json injection pattern. Let me also look at the test file for codex auth to understand the expected behavior.
<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/tests/unit/agents/installed/test_codex_auth.py </tool_call>
Assistant
Let me use the proper tool syntax to read the test file.
Assistant
Now I understand the pattern from codex.py and the test file. I need to implement a similar OAuth credential injection for gemini-cli. The key features are:
_resolve_oauth_creds_path()method to resolve the OAuth credentials file path- Support for
GEMINI_OAUTH_CREDS_PATHenvironment variable (explicit path) - Support for
GEMINI_FORCE_OAUTHenvironment variable (use~/.gemini/oauth_creds.json) - Upload the file to the container, chown it, and create a symlink in
~/.gemini/
Let me also look at the base agent class to understand how
_get_envworks and what utilities are available.<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/src/harbor/agents/installed/base.py </tool_call>
Assistant
Let me use the proper tool syntax to read the base.py file.
Assistant
Now I understand the base agent class and the
_get_envmethod. Let me also check theparse_bool_env_valuefunction to understand how it works.<tool_call> <function=bash_terminal> <parameter=command> grep -A 20 "def parse_bool_env_value" /harbor/src/harbor/utils/env.py </tool_call>
Assistant
Let me use the proper tool syntax to find the parse_bool_env_value function.
Assistant
Let me see the full function and also check what
_TRUE_BOOL_VALUESand_FALSE_BOOL_VALUESare.Assistant
Now I have all the information I need. Let me implement the OAuth credential injection for gemini-cli. I'll need to modify the
gemini_cli.pyfile to add:- A
_resolve_oauth_creds_path()method that mirrors the codex pattern - Support for
GEMINI_OAUTH_CREDS_PATHandGEMINI_FORCE_OAUTHenvironment variables - Upload and symlink the OAuth credentials in the
run()method
Let me first look at the full gemini_cli.py file to understand where to make changes:
- A
Assistant
Now let me look at the run method in gemini_cli.py to see where I need to add the OAuth credential injection:
<tool_call> <function=bash_terminal> <parameter=command> grep -n "async def run" /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use the proper tool syntax to search for the run method in gemini_cli.py.
Assistant
Now let me view the run method and the surrounding code:
Assistant
Now I have a complete picture of the code. Let me implement the OAuth credential injection for gemini-cli by adding:
- A
_resolve_oauth_creds_path()method that mirrors the codex pattern - Upload and symlink the OAuth credentials in the
run()method
Let me create the implementation:
<tool_call> <function=bash_terminal> <parameter=command> cat /harbor/src/harbor/agents/installed/gemini_cli.py | head -30 </tool_call>
- A
Assistant
Let me first see the full imports section of the file to understand what I need to add.
Assistant
Now I understand the full picture. I need to:
- Add
parse_bool_env_valueimport fromharbor.utils.env - Add a
_resolve_oauth_creds_path()method that mirrors the codex pattern - Modify the
run()method to upload and use OAuth credentials when specified
Let me start by modifying the imports:
- Add
Assistant
I see the edit created duplicates. Let me reset the file and start fresh.
Assistant
Let me now use a different approach - let me first check the current file and then use the proper edit syntax:
Assistant
The file is now reset. Let me carefully add the import and the _resolve_oauth_creds_path method. Let me first add the import:
Assistant
Now let me verify the import was added correctly:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '16,30p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to check the imports section of the file.
Assistant
The import was added. Now I need to add the
_resolve_oauth_creds_path()method. Let me find a good place to add it - probably after the_validate_reasoning_effortmethod. Let me find where that method ends:<tool_call> <function=bash_terminal> <parameter=command> grep -n "_validate_reasoning_effort" /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to find where the _validate_reasoning_effort method ends.
Assistant
Let me view the _validate_reasoning_effort method to see where it ends:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '72,100p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to view the _validate_reasoning_effort method and find where it ends.
Assistant
The _validate_reasoning_effort method ends at line 99 (after the last closing parenthesis), and the install method starts at line 101. I'll add the _resolve_oauth_creds_path method between line 99 and line 101. Let me use the edit command to insert the new method.
<tool_call> <function=bash_terminal> <parameter=command> sed -n '99p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to check what line 99 contains.
Assistant
Let me check the install method to see where the install function begins:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '100,105p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me check what line 100 contains to understand where the _validate_reasoning_effort method ends.
Assistant
Now I can see that the install method starts at line 100. The _validate_reasoning_effort method ends at line 99 (with the closing
)). I need to insert the _resolve_oauth_creds_path method between lines 99 and 100.Let me use a different approach - I'll add the method using sed to insert lines after line 99.
<tool_call> <function=bash_terminal> <parameter=command> sed -i '99a
def _resolve_oauth_creds_path(self) -> Path | None:
"""Resolve which oauth_creds.json to inject, if any.
Defaults to None (GEMINI_API_KEY auth). Opt into oauth auth via:
- GEMINI_OAUTH_CREDS_PATH= → use that specific oauth_creds.json
- GEMINI_FORCE_OAUTH= → use ~/.gemini/oauth_creds.json
"""
explicit = self._get_env("GEMINI_OAUTH_CREDS_PATH")
if explicit:
p = Path(explicit)
if not p.is_file():
raise ValueError(
f"GEMINI_OAUTH_CREDS_PATH points to non-existent file: {explicit}"
)
return p
if parse_bool_env_value(
self._get_env("GEMINI_FORCE_OAUTH"),
name="GEMINI_FORCE_OAUTH",
default=False,
):
default = Path.home() / ".gemini" / "oauth_creds.json"
if not default.is_file():
raise ValueError(
f"GEMINI_FORCE_OAUTH is set but {default} does not exist"
)
return default
return None' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>Assistant
The sed command ran but I need to verify it worked correctly. Let me check the file around the area where I added the method.
Assistant
The sed command didn't insert the content correctly - it looks like the method wasn't added. Let me try a different approach using the edit command with heredoc syntax.
<tool_call> <function=bash_terminal> <parameter=command> cat -n /harbor/src/harbor/agents/installed/gemini_cli.py | sed -n '98,102p' </tool_call>
Assistant
Let me use the open command to view the file and then edit it properly:
Assistant
Let me use the open command to view the file at a specific line, then use edit properly:
Assistant
The method was added. Let me verify the insertion looks correct:
Assistant
The method was added. Now I need to modify the
run()method to use OAuth credentials when specified. Let me find the run method and see what changes need to be made:Assistant
Now let me view the run method to understand what needs to be modified.
<tool_call> <function=bash_terminal> <parameter=command> sed -n '679,760p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use the proper bash command syntax to view the run method.
Assistant
Now I need to modify the run() method to add OAuth credential injection similar to how codex does it. I need to:
- Resolve the OAuth credentials path using
_resolve_oauth_creds_path() - If OAuth credentials are specified, upload them to the container and create a symlink
- If no OAuth credentials, keep using the existing behavior (GEMINI_API_KEY, etc.)
Let me use Python to modify the run() method:
<tool_call> <function=bash_terminal> <parameter=command> python3 << 'PYEOF'
Let's read the file and modify the run() method to add OAuth support
with open('/harbor/src/harbor/agents/installed/gemini_cli.py', 'r') as f: content = f.read()
Find the section after "env = {"GEMINI_CLI_TRUST_WORKSPACE": "true"}" and before the auth_vars for loop
old_section = ''' # Gemini CLI refuses to honor
--yoloin an untrusted workspace and # overrides approval mode back to "default" env = {"GEMINI_CLI_TRUST_WORKSPACE": "true"}auth_vars = [ "GEMINI_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_API_KEY", ] for var in auth_vars: if var in os.environ: env[var] = os.environ[var] skills_command = self._build_register_skills_command()'''new_section = ''' # Gemini CLI refuses to honor
--yoloin an untrusted workspace and # overrides approval mode back to "default" env = {"GEMINI_CLI_TRUST_WORKSPACE": "true"}# Resolve OAuth credentials (if specified via env vars) oauth_creds_path = self._resolve_oauth_creds_path() # Build secrets directory path _REMOTE_GEMINI_SECRETS_DIR = "/tmp/gemini-secrets" remote_oauth_path = f"{_REMOTE_GEMINI_SECRETS_DIR}/oauth_creds.json" if oauth_creds_path: self.logger.debug("Gemini CLI auth: using oauth_creds.json from %s", oauth_creds_path) await environment.upload_file(oauth_creds_path, remote_oauth_path) # upload_file copies as root; fix ownership so the agent user can read it if environment.default_user is not None: await self.exec_as_root( environment, command=f"chown {environment.default_user} {remote_oauth_path}", ) # Create symlink to make OAuth creds available in ~/.gemini/ setup_command = ( f'mkdir -p ~/.gemini && ' f'ln -sf {shlex.quote(remote_oauth_path)} ~/.gemini/oauth_creds.json\\n' ) else: self.logger.debug("Gemini CLI auth: using GEMINI_API_KEY or Vertex credentials") setup_command = "" auth_vars = [ "GEMINI_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_API_KEY", ] for var in auth_vars: if var in os.environ: env[var] = os.environ[var] skills_command = self._build_register_skills_command()'''if old_section in content: content = content.replace(old_section, new_section) with open('/harbor/src/harbor/agents/installed/gemini_cli.py', 'w') as f: f.write(content) print("Successfully modified run() method to add OAuth support") else: print("Could not find the target section to modify") # Let's print a portion of the file to debug idx = content.find('# Gemini CLI refuses to honor') if idx >= 0: print(f"Found at index {idx}, section: {content[idx:idx+500]}") PYEOF </tool_call>
- Resolve the OAuth credentials path using
Assistant
Let me try running the Python script to modify the file again.
Assistant
Now I need to add the code that actually runs the setup_command (to execute the mkdir and ln commands). Let me check the modified section and add the code to execute the setup_command:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '695,750p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to view the modified section of the file.
Assistant
I see the issue - I need to add the code that actually executes the setup_command. Currently the code sets up the
setup_commandvariable but doesn't run it. Let me fix this by adding the code to execute the setup_command.Let me use Python to add the missing code to execute the setup_command:
Assistant
Good! Now let me verify the changes look correct by viewing the modified section:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '725,765p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use proper bash syntax to view the modified section.
Assistant
The modification looks correct. Now let me verify the entire flow by viewing the OAuth section of the code:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '695,745p' /harbor/src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me use the proper bash syntax to view the OAuth section of the code.
Assistant
The changes look correct. Now let me verify the complete file to ensure the code is syntactically correct by running a Python syntax check:
<tool_call> <function=bash_terminal> <parameter=command> python3 -m py_compile /harbor/src/harbor/agents/installed/gemini_cli.py && echo "Syntax OK" </tool_call>
Assistant
The syntax check should run - let me try again.
Assistant
The syntax is correct. Now let me also add a test file similar to the test_codex_auth.py for gemini-cli to ensure the OAuth resolution works correctly. Let me first check where the tests are located:
<tool_call> <function=bash_terminal> <parameter=command> ls -la /harbor/tests/unit/agents/installed/ </tool_call>
Assistant
Let me use the proper bash syntax to list the test files.
<tool_call> <function=bash_terminal> <parameter=command> ls -la /harbor/tests/unit/agents/installed/ </tool_call>
Assistant
Let me try running ls with proper bash syntax to list the test files.
Assistant
Now let me create a test file for the gemini-cli OAuth credentials resolution similar to test_codex_auth.py. I'll create test_gemini_cli_auth.py:
<tool_call> <function=bash_terminal> <parameter=command> cat > /harbor/tests/unit/agents/installed/test_gemini_cli_auth.py << 'TESTEOF' """Unit tests for Gemini CLI OAuth credentials resolution."""
import json from pathlib import Path from unittest.mock import AsyncMock
import pytest
from harbor.agents.installed.gemini_cli import GeminiCli
class TestResolveOAuthCredsPath: """Test _resolve_oauth_creds_path() priority logic."""
def test_default_returns_none(self, tmp_path, monkeypatch, temp_dir): """Default (no env vars) returns None even if ~/.gemini/oauth_creds.json exists.""" gemini_dir = tmp_path / ".gemini" gemini_dir.mkdir() (gemini_dir / "oauth_creds.json").write_text("{}") monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path)) monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") assert agent._resolve_oauth_creds_path() is None def test_explicit_path_via_env(self, tmp_path, monkeypatch, temp_dir): """GEMINI_OAUTH_CREDS_PATH env var selects a specific oauth_creds.json.""" auth_file = tmp_path / "custom-oauth.json" auth_file.write_text("{}") monkeypatch.setenv("GEMINI_OAUTH_CREDS_PATH", str(auth_file)) monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") assert agent._resolve_oauth_creds_path() == auth_file def test_explicit_path_via_extra_env(self, tmp_path, monkeypatch, temp_dir): """GEMINI_OAUTH_CREDS_PATH via extra_env (--ae) works.""" auth_file = tmp_path / "custom-oauth.json" auth_file.write_text("{}") monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) agent = GeminiCli( logs_dir=temp_dir, model_name="google/gemini-1.5-pro", extra_env={"GEMINI_OAUTH_CREDS_PATH": str(auth_file)}, ) assert agent._resolve_oauth_creds_path() == auth_file def test_explicit_path_missing_raises(self, monkeypatch, temp_dir): """GEMINI_OAUTH_CREDS_PATH pointing to nonexistent file raises.""" monkeypatch.setenv("GEMINI_OAUTH_CREDS_PATH", "/tmp/does-not-exist.json") monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") with pytest.raises(ValueError, match="non-existent file"): agent._resolve_oauth_creds_path() @pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes"]) def test_force_oauth_truthy_uses_home( self, value, tmp_path, monkeypatch, temp_dir ): """Truthy GEMINI_FORCE_OAUTH uses ~/.gemini/oauth_creds.json.""" gemini_dir = tmp_path / ".gemini" gemini_dir.mkdir() (gemini_dir / "oauth_creds.json").write_text("{}") monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path)) monkeypatch.setenv("GEMINI_FORCE_OAUTH", value) monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") assert agent._resolve_oauth_creds_path() == gemini_dir / "oauth_creds.json" @pytest.mark.parametrize("value", ["0", "false", "FALSE", "no"]) def test_force_oauth_falsy_returns_none( self, value, tmp_path, monkeypatch, temp_dir ): """Falsy GEMINI_FORCE_OAUTH does not use ~/.gemini/oauth_creds.json.""" gemini_dir = tmp_path / ".gemini" gemini_dir.mkdir() (gemini_dir / "oauth_creds.json").write_text("{}") monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path)) monkeypatch.setenv("GEMINI_FORCE_OAUTH", value) monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") assert agent._resolve_oauth_creds_path() is None def test_force_oauth_missing_raises(self, tmp_path, monkeypatch, temp_dir): """Truthy GEMINI_FORCE_OAUTH with missing ~/.gemini/oauth_creds.json raises.""" monkeypatch.setattr(Path, "home", staticmethod(lambda: tmp_path)) monkeypatch.setenv("GEMINI_FORCE_OAUTH", "true") monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") with pytest.raises(ValueError, match="does not exist"): agent._resolve_oauth_creds_path() def test_force_oauth_invalid_raises(self, monkeypatch, temp_dir): """Invalid GEMINI_FORCE_OAUTH values raise instead of being ignored.""" monkeypatch.setenv("GEMINI_FORCE_OAUTH", "sometimes") monkeypatch.delenv("GEMINI_OAUTH_CREDS_PATH", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") with pytest.raises(ValueError, match="cannot parse"): agent._resolve_oauth_creds_path()class TestGeminiCliRunAuth: """Test that run() wires OAuth credentials correctly."""
@pytest.mark.asyncio async def test_uploads_oauth_creds_when_present( self, tmp_path, monkeypatch, temp_dir ): """When oauth_creds.json exists, it's uploaded to the container.""" auth_file = tmp_path / "oauth_creds.json" auth_file.write_text( json.dumps({"tokens": {"access_token": "tok", "refresh_token": "ref"}}) ) monkeypatch.setenv("GEMINI_OAUTH_CREDS_PATH", str(auth_file)) monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) monkeypatch.delenv("GEMINI_API_KEY", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") mock_env = AsyncMock() mock_env.default_user = "agent" mock_env.exec.return_value = AsyncMock( return_code=0, stdout="", stderr="" ) await agent.run("do something", mock_env, AsyncMock()) mock_env.upload_file.assert_called_once() assert str(mock_env.upload_file.call_args[0][0]) == str(auth_file) assert mock_env.upload_file.call_args[0][1] == "/tmp/gemini-secrets/oauth_creds.json" # Should chown the uploaded file root_exec_calls = [ c for c in mock_env.exec.call_args_list if c.kwargs.get("user") == "root" and "chown" in c.kwargs.get("command", "") ] assert len(root_exec_calls) == 1 @pytest.mark.asyncio async def test_skips_chown_when_no_default_user( self, tmp_path, monkeypatch, temp_dir ): """When default_user is None, skip chown.""" auth_file = tmp_path / "oauth_creds.json" auth_file.write_text("{}") monkeypatch.setenv("GEMINI_OAUTH_CREDS_PATH", str(auth_file)) monkeypatch.delenv("GEMINI_FORCE_OAUTH", raising=False) monkeypatch.delenv("GEMINI_API_KEY", raising=False) agent = GeminiCli(logs_dir=temp_dir, model_name="google/gemini-1.5-pro") mock_env = AsyncMock() mock_env.default_user = None mock_env.exec.return_value = AsyncMock( return_code=0, stdout="", stderr="" ) await agent.run("do something", mock_env, AsyncMock()) mock_env.upload_file.assert_called_once() # No chown call root_exec_calls = [ c for c in mock_env.exec.call_args_list if c.kwargs.get("user") == "root" and "chown" in c.kwargs.get("command", "") ] assert len(root_exec_calls) == 0TESTEOF </tool_call>
Assistant
Let me run the command with the proper tool syntax.
Assistant
The command exited with code 0, but I should verify the test file was created properly. Let me check if the file exists and has the correct content:
<tool_call> <function=bash_terminal> <parameter=command> ls -la /harbor/tests/unit/agents/installed/test_gemini_cli_auth.py </tool_call>
Assistant
Let me use the proper tool syntax to check if the test file exists.
Assistant
The test file was created successfully. Now let me run the existing tests for gemini-cli to ensure my changes don't break any existing functionality.
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && python -m pytest tests/unit/agents/installed/test_gemini_cli.py -v --tb=short 2>&1 | head -100 </tool_call>
Assistant
Let me use the proper tool syntax to run the tests.
Assistant
Let me try running the tests using the correct Python path or the project's test setup:
Assistant
Let me try using the project's uv environment to run the tests:
Assistant
All 9 existing tests pass. Now let me run the new OAuth test file I created:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && uv run pytest tests/unit/agents/installed/test_gemini_cli_auth.py -v --tb=short 2>&1 </tool_call>
Assistant
Let me run the new OAuth test file.
Assistant
All 16 tests pass. Now let me also run the codex auth tests to make sure I'm following the same pattern correctly and haven't broken anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && uv run pytest tests/unit/agents/installed/test_codex_auth.py -v --tb=short 2>&1 </tool_call>
Assistant
Let me run the codex auth tests.
Assistant
All the codex auth tests pass as well. Now let me check the git diff to see what changes I made:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && git diff src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me check the git diff to see what changes I made.
Assistant
The diff shows the changes I made to the gemini_cli.py file. Let me also check if there are any other files changed.
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && git status </tool_call>
Assistant
Let me check the git status to see all the changes.
Assistant
Now let me verify the implementation once more by viewing the full updated run method to ensure everything looks correct. Let me also run a broader test to make sure I didn't break anything:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && uv run pytest tests/unit/agents/installed/ -v -k "gemini or codex" --tb=short 2>&1 | head -150 </tool_call>
Assistant
Let me run the broader test to verify everything is working correctly.
Assistant
All tests pass! Now let me review the checklist mentioned in the instructions:
-
✅ If an error was reported in the issue description, I have successfully reproduced it.
- The issue was about adding OAuth credential injection to gemini-cli. I've implemented this feature.
-
✅ If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- The implementation allows users to use
GEMINI_OAUTH_CREDS_PATHorGEMINI_FORCE_OAUTHenvironment variables to inject OAuth credentials, mirroring the codex pattern.
- The implementation allows users to use
-
✅ I have thought about edge cases and made sure my fix handles them as well.
- Handled explicit path via
GEMINI_OAUTH_CREDS_PATH - Handled default path via
GEMINI_FORCE_OAUTH - Error handling for non-existent files
- Proper handling of truthy/falsy values for
GEMINI_FORCE_OAUTH - Chown only when
default_useris not None
- Handled explicit path via
-
✅ I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
- All 78 tests related to gemini and codex pass
- All 16 tests for the new gemini_cli_auth module pass
- All 18 tests for the codex_auth module pass
Let me also check if there are any other tests I should run to make sure my changes don't break anything else:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && uv run pytest tests/unit/agents/installed/test_agent_skills.py -v --tb=short 2>&1 | tail -30 </tool_call>
-
Assistant
Let me run the agent_skills tests to make sure my changes don't break anything.
Assistant
All tests pass. Now let me also view the final implementation in the gemini_cli.py file to ensure everything looks clean:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && sed -n '690,770p' src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me view the final implementation of the run() method:
Assistant
The implementation looks clean and follows the same pattern as the codex auth implementation. Let me also view the _resolve_oauth_creds_path method:
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && sed -n '98,135p' src/harbor/agents/installed/gemini_cli.py </tool_call>
Assistant
Let me view the _resolve_oauth_creds_path method.
Assistant
The implementation looks complete and clean. Let me now summarize what I've done:
Summary of Changes
1. Modified
src/harbor/agents/installed/gemini_cli.py:- Added import:
from harbor.utils.env import parse_bool_env_value - Added
_resolve_oauth_creds_path()method: This method resolves the OAuth credentials path using two environment variables:GEMINI_OAUTH_CREDS_PATH: Explicit path to oauth_creds.json fileGEMINI_FORCE_OAUTH: Truthy value to use~/.gemini/oauth_creds.json
- Modified
run()method: Added OAuth credential injection that:- Resolves the OAuth credentials path
- Uploads the file to the container at
/tmp/gemini-secrets/oauth_creds.json - Changes ownership if
default_useris set - Creates a symlink at
~/.gemini/oauth_creds.json - Maintains backward compatibility (default behavior unchanged)
2. Created
tests/unit/agents/installed/test_gemini_cli_auth.py:- Added 16 tests mirroring the codex auth tests:
- Tests for
_resolve_oauth_creds_path()including:- Default returns None
- Explicit path via env var
- Explicit path via extra_env
- Missing file raises error
- Truthy/falsy GEMINI_FORCE_OAUTH values
- Invalid GEMINI_FORCE_OAUTH values raise error
- Tests for
run()method:- Uploads OAuth credentials when present
- Skips chown when no default_user
- Tests for
3. All existing tests pass:
- 78 tests related to gemini and codex pass
- 16 new tests for gemini_cli_auth pass
- All other related tests pass
4. Backward compatibility:
- Default behavior unchanged (still uses GEMINI_API_KEY or Vertex credentials)
- New feature is opt-in via environment variables
Now I'll submit the changes.
<tool_call> <function=bash_terminal> <parameter=command> cd /harbor && git diff --stat </tool_call>
- Added import:
Assistant
Let me check the git diff stats before submitting.
Assistant
Let me run a final verification to ensure everything is working correctly:
Assistant
All tests pass. Now let me submit the changes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →