Files
DeepTutor/deeptutor_cli/provider_cmd.py
TyrionH-is-coding c3d1dd0b15 feat(llm): add first-party OpenAI Codex OAuth provider (#690)
Replaces the oauth_cli_kit indirection with DeepTutor's own PKCE loopback
sign-in, an account-scoped live model catalog, and a Settings card that exposes
only the OAuth surface. Credentials live in `<user-root>/private/openai-codex/`
with owner-only permissions, atomic writes, and a generation guard that stops a
late refresh from resurrecting a signed-out session; `~/.codex` is never read or
modified. A CLI path shares the same service.

A Codex token authorizes one person's ChatGPT plan, so credentials anchor to the
signing-in account's own root and the managed profile is marked `owner_bound`:
`redacted_model_access` drops it for every caller, and it is not offered as an
assignable model. Signing in publishes the profile but only activates it when no
LLM is configured yet, so it never repoints a deployment that already has one.

Also from review: reschedule the status poll so one dropped response cannot
strand the card on "waiting"; defer the catalog reload when the operator has
unsaved edits instead of discarding them; log the real cause behind the generic
provider error; stop promising a retry when the token refresh actually failed;
bind both loopback stacks since `localhost` may resolve to either; and drop the
provider metadata fields nothing consumed.
2026-07-26 22:27:54 +08:00

101 lines
3.6 KiB
Python

"""CLI commands for provider auth and access validation."""
from __future__ import annotations
import asyncio
import webbrowser
import typer
from deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service
from .common import maybe_run
def register(app: typer.Typer) -> None:
@app.command("login")
def provider_login(
provider: str = typer.Argument(
...,
help="Provider: openai-codex (OAuth login) | github-copilot (validate existing Copilot auth)",
),
) -> None:
"""Authenticate or validate provider access."""
key = provider.strip().lower().replace("-", "_")
if key == "openai_codex":
maybe_run(_login_openai_codex())
return
if key == "github_copilot":
maybe_run(_login_github_copilot())
return
raise typer.BadParameter(
f"Unknown provider `{provider}`. Supported: openai-codex, github-copilot"
)
async def _login_openai_codex() -> None:
service = get_codex_oauth_service()
try:
started = await service.start_login()
authorize_url = str(started["authorize_url"])
typer.echo(
"Opening the OpenAI Codex sign-in in your browser; "
"credentials are written only to DeepTutor's private directory."
)
if not webbrowser.open(authorize_url):
typer.echo(f"The browser did not open automatically. Visit: {authorize_url}")
while True:
status = service.public_status()
operation_state = status.get("operation_state")
if operation_state == "completed":
typer.echo(
f"OpenAI Codex sign-in succeeded. Models available: "
f"{status.get('model_count', 0)}."
)
active_model = status.get("active_model")
if active_model:
typer.echo(f"Codex is the active model: {active_model}")
else:
typer.echo("Select a Codex model in Settings to start using it.")
return
if operation_state in {"failed", "expired", "cancelled"}:
error_code = status.get("error_code") or operation_state
typer.echo(f"OpenAI Codex sign-in did not complete: {error_code}")
raise typer.Exit(code=1)
await asyncio.sleep(0.5)
except asyncio.CancelledError:
await service.cancel_login()
typer.echo("Cancelled the OpenAI Codex sign-in.")
raise typer.Exit(code=130) from None
except CodexAuthError as exc:
typer.echo(f"OpenAI Codex sign-in failed: {exc.public_message}")
raise typer.Exit(code=1)
async def _login_github_copilot() -> None:
"""Validate an existing GitHub Copilot auth session via a lightweight request."""
try:
from openai import AsyncOpenAI
except ImportError:
typer.echo(
"openai is not installed. Install CLI deps from a local checkout: "
"python -m pip install -e ./packaging/deeptutor-cli"
)
raise typer.Exit(code=1)
try:
client = AsyncOpenAI(
api_key="copilot",
base_url="https://api.githubcopilot.com",
max_retries=0,
)
await client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "ping"}],
max_tokens=1,
)
except Exception as exc:
typer.echo(f"GitHub Copilot auth validation failed: {exc}")
raise typer.Exit(code=1) from exc
typer.echo("GitHub Copilot auth validation succeeded.")