Skip to content

Feature/cli agent handler - #2671

Closed
manasseh-fikadu wants to merge 4 commits into
The-PR-Agent:mainfrom
manasseh-fikadu:feature/cli-agent-handler
Closed

manasseh-fikadu wants to merge 4 commits into
The-PR-Agent:mainfrom
manasseh-fikadu:feature/cli-agent-handler

Conversation

@manasseh-fikadu

Copy link
Copy Markdown

No description provided.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add CLI-backed AI handler (Claude Code/Codex) with per-request handler resolution

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add a new AI handler that routes completions through local Claude Code or Codex CLIs.
• Resolve the AI handler per request after repo settings are merged, avoiding stale config.
• Document and test CLI model selection, invocation behavior, and output parsing.
Diagram

graph TD
  pr[PRAgent] --> settings["Settings (.toml)"] --> factory["handler_factory"] --> cli["CliAgentAIHandler"]
  cli --> claude{{"Claude Code CLI"}}
  cli --> codex{{"Codex CLI"}}
  tests["Unit tests"] --> cli
  docs["Usage docs"] --> settings
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. LiteLLM provider adapter for the CLIs
  • ➕ Keeps a single handler path (LiteLLM) for all models
  • ➕ May reuse existing retry/logging/usage plumbing
  • ➖ Not feasible unless CLIs expose an HTTP/OpenAI-compatible endpoint (they currently don’t)
  • ➖ Would still require subprocess wrapping somewhere, just hidden behind a provider shim
2. Pluggable handler registry (entry points)
  • ➕ Allows third-party handler implementations without editing core factory
  • ➕ Makes adding future backends (more CLIs/local runners) cleaner
  • ➖ More moving parts and packaging complexity than needed for two backends
  • ➖ Harder to debug in monorepo installs; overkill for current scope

Recommendation: Current approach is appropriate: the CLIs are subprocess-only, so a dedicated handler is the cleanest integration point, and resolving the handler per request correctly accounts for repo-level config/model overrides. If more handlers/backends are expected to proliferate, consider evolving handler_factory into a registry to reduce conditional imports and centralize validation.

Files changed (6) +734 / -5

Enhancement (2) +435 / -0
cli_agent_ai_handler.pyAdd cli_agent AI handler that shells out to Claude/Codex CLIs +374/-0

Add cli_agent AI handler that shells out to Claude/Codex CLIs

• Introduces a new BaseAiHandler implementation that delegates chat completions to local 'claude' or 'codex exec' subprocesses using stdin (avoiding argv size limits). Adds backend/model parsing, safe/isolated invocation defaults, timeouts + retries, Claude JSON output parsing with usage capture, and optional structured-output unwrapping.

pr_agent/algo/ai_handlers/cli_agent_ai_handler.py

handler_factory.pyAdd handler factory with model-based auto-detection +61/-0

Add handler factory with model-based auto-detection

• Adds a lazy-import resolver that selects handlers by 'config.ai_handler', or infers 'cli_agent' from a 'cli/' model prefix, otherwise defaulting to LiteLLM. Encapsulates handler selection so entry points can call it after repo config is known.

pr_agent/algo/ai_handlers/handler_factory.py

Refactor (1) +14 / -5
pr_agent.pyResolve AI handler after settings merge (per request) +14/-5

Resolve AI handler after settings merge (per request)

• Defers AI handler selection until after CLI args and repo '.pr_agent.toml' are applied, preventing stale model/handler inference. Switches from a hardcoded LiteLLM default to using a handler factory when no explicit handler is injected.

pr_agent/agent/pr_agent.py

Tests (1) +234 / -0
test_cli_agent_ai_handler.pyAdd unit tests for cli_agent and handler selection +234/-0

Add unit tests for cli_agent and handler selection

• Covers 'cli/<backend>' model parsing, argv construction, Claude output parsing, stderr diagnostics, fenced-structured unwrapping, factory selection logic, and basic chat_completion flows for both Claude and Codex using mocks.

tests/unittest/test_cli_agent_ai_handler.py

Documentation (1) +37 / -0
changing_a_model.mdDocument running models via local Claude Code/Codex CLIs +37/-0

Document running models via local Claude Code/Codex CLIs

• Adds a new section describing the 'cli/<backend>[/<model>]' model syntax and how it auto-selects the 'cli_agent' handler. Documents cli_agent configuration knobs, limitations (no images, no temperature), and expected best-fit commands.

docs/docs/usage-guide/changing_a_model.md

Other (1) +14 / -0
configuration.tomlExpose ai_handler and cli_agent settings in default config +14/-0

Expose ai_handler and cli_agent settings in default config

• Documents 'config.ai_handler' including auto-detect behavior and adds a new '[cli_agent]' section covering binaries, timeouts, codex config isolation, extra args, and structured-output unwrapping.

pr_agent/settings/configuration.toml

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (5) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Single quotes in data.get() 📘 Rule violation ⚙ Maintainability
Description
cli_agent_ai_handler.py uses single-quoted string literals ('result', 'subtype') inside
data.get(...), violating the double-quotes convention. This can cause style/lint noncompliance and
inconsistent codebase formatting.
Code

pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[R234-236]

+    if data.get("is_error"):
+        raise CliAgentError(f"claude reported an error: {data.get('result') or data.get('subtype')}")
+
Relevance

●●● Strong

Repo often enforces double-quote style in touched Python, including nested .get() patterns.

PR-#2584

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires double quotes for Python string literals. The added line uses
'result' and 'subtype' as single-quoted literals.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[234-236]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new CLI agent handler uses single-quoted string literals, but the project requires double quotes for Python string literals.

## Issue Context
This is in newly added code and should be aligned with the repo's enforced quoting style.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[234-236]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Non-imperative module docstring 📘 Rule violation ⚙ Maintainability
Description
The newly added module docstring begins with descriptive phrasing (AI handler that delegates...)
instead of imperative mood. This violates the docstring/comment phrasing requirement.
Code

pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[R1-2]

+"""AI handler that delegates completions to a locally installed coding-agent CLI
+(Claude Code's `claude`, or Codex's `codex exec`) instead of an HTTP endpoint.
Relevance

●●● Strong

Imperative phrasing for comments/docstrings has been enforced and accepted recently.

PR-#2661

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694688 requires newly added docstrings/comments to use imperative phrasing. The
module docstring starts with a descriptive clause rather than an imperative verb.

Rule 2694688: Docstrings and comments must use imperative phrasing
pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[1-5]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Newly added docstrings/comments should use imperative phrasing (e.g., "Delegate...", "Return...") rather than descriptive phrasing.

## Issue Context
This rule applies to new/modified docstrings in the PR.

## Fix Focus Areas
- pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[1-5]
- pr_agent/algo/ai_handlers/cli_agent_ai_handler.py[70-75]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Overlong line in docs 📘 Rule violation ⚙ Maintainability
Description
A newly added Markdown line exceeds the 120-character maximum. This reduces readability and violates
the repository line-length rule.
Code

docs/docs/usage-guide/changing_a_model.md[92]

+If you already have [Claude Code](https://claude.com/claude-code) or [Codex](https://developers.openai.com/codex/cli) installed and logged in, PR-Agent can run its completions through those CLIs instead of calling a model API. Requests then bill against that CLI's existing login (e.g. a Claude or ChatGPT subscription) and no API key is configured in PR-Agent at all.
Relevance

●●● Strong

Team has accepted docs rewraps to satisfy line-length conventions in Markdown.

PR-#2470

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694690 requires that modified source files do not contain lines longer than 120
characters. The added documentation line at 92 is a single long sentence exceeding that limit.

Rule 2694690: Enforce maximum line length of 120 characters
docs/docs/usage-guide/changing_a_model.md[92-92]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
At least one newly added line exceeds the 120-character limit.

## Issue Context
The compliance checklist requires a maximum line length of 120 characters for modified files.

## Fix Focus Areas
- docs/docs/usage-guide/changing_a_model.md[92-92]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (3)
4. Overlong TOML config line 📘 Rule violation ⚙ Maintainability
Description
A newly added configuration.toml line (with an inline comment) exceeds the 120-character maximum.
This violates the line-length requirement for modified files.
Code

pr_agent/settings/configuration.toml[11]

+ai_handler="" # "" (auto-detect from model), "litellm", "openai", "cli_agent", "langchain". A "cli/..." model auto-selects "cli_agent".
Relevance

●●● Strong

Line-length fixes are commonly accepted in this repo (Ruff/CI compliance).

PR-#2584

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694690 requires that modified source files do not contain lines longer than 120
characters. The ai_handler line includes a long inline comment that pushes the line over the
limit.

Rule 2694690: Enforce maximum line length of 120 characters
pr_agent/settings/configuration.toml[11-11]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A modified TOML line exceeds the 120-character maximum due to a long inline comment.

## Issue Context
The compliance checklist enforces a 120-character max line length across modified files.

## Fix Focus Areas
- pr_agent/settings/configuration.toml[11-12]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. .pr_agent.toml missing new keys 📘 Rule violation ≡ Correctness
Description
New configuration keys/sections were added under pr_agent/settings/configuration.toml but the root
.pr_agent.toml was not updated to reflect them. This violates the requirement to keep these
configuration locations in sync when behavior/config keys change.
Code

pr_agent/settings/configuration.toml[R367-370]

+[cli_agent]
+# Settings for the "cli_agent" AI handler, which runs completions through a locally
+# installed coding-agent CLI instead of an HTTP API. Selected by a "cli/<backend>[/<model>]"
+# model, e.g. config.model = "cli/claude/opus" or "cli/codex/gpt-5.1-codex-max".
Relevance

●● Moderate

Config consistency is valued, but no close precedent that .pr_agent.toml must mirror every new
configuration.toml key.

PR-#2504

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694685 requires config key/behavior changes to be reflected consistently in both
.pr_agent.toml and pr_agent/settings/*.toml. This PR adds a new [cli_agent] section in
pr_agent/settings/configuration.toml, while .pr_agent.toml contains no corresponding
cli_agent/ai_handler configuration.

Rule 2694685: Keep .pr_agent.toml and pr_agent/settings/*.toml configuration in sync on behavior changes
pr_agent/settings/configuration.toml[367-378]
.pr_agent.toml[1-27]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Configuration keys/sections were added/changed in `pr_agent/settings/configuration.toml` without corresponding updates in the root `.pr_agent.toml`.

## Issue Context
The checklist requires keeping `.pr_agent.toml` and `pr_agent/settings/*.toml` in sync for configuration-key/behavior changes.

## Fix Focus Areas
- pr_agent/settings/configuration.toml[367-378]
- .pr_agent.toml[1-30]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Auto actions bypass handler 🐞 Bug ≡ Correctness
Description
GitHub Action runner auto paths call PRReviewer/PRDescription/PRCodeSuggestions without passing an
AI handler, so they always use the tools’ default LiteLLM handler and ignore both
config.ai_handler and cli/... model inference. This makes the new CLI-agent configuration
ineffective (and potentially breaks runs) for GitHub Action auto_review/auto_describe/auto_improve
flows.
Code

pr_agent/settings/configuration.toml[11]

+ai_handler="" # "" (auto-detect from model), "litellm", "openai", "cli_agent", "langchain". A "cli/..." model auto-selects "cli_agent".
Relevance

●● Moderate

Seems plausible but needs context; similar runner-config behavior changes were accepted, but not
this exact ai_handler wiring.

PR-#2490

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The config now documents auto-selection of cli_agent, but GitHub Action auto-actions still
construct tools with default handler values. The tools’ constructors default ai_handler to
LiteLLMAIHandler, so these call sites ignore the new handler selection logic entirely.

pr_agent/settings/configuration.toml[5-12]
pr_agent/servers/github_action_runner.py[229-240]
pr_agent/tools/pr_reviewer.py[38-66]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
GitHub Action runner auto-actions instantiate PR tools without providing an `ai_handler`, so the tools fall back to `LiteLLMAIHandler` regardless of `config.ai_handler` or a `cli/...` model.

### Issue Context
This PR introduces handler inference (`cli/...` -> `cli_agent`) and an explicit `config.ai_handler` knob, but that inference is only used where `get_ai_handler_class()` is called (currently via `PRAgent`). The GitHub Action runner has auto paths that bypass `PRAgent` and call tool constructors directly.

### Fix Focus Areas
- pr_agent/servers/github_action_runner.py[229-240]
- pr_agent/servers/github_action_runner.py[337-342]

Suggested change: after repo settings are applied (and after any env/config overrides are loaded), resolve `handler_cls = get_ai_handler_class()` and pass `ai_handler=handler_cls` into `PRDescription`, `PRReviewer`, and `PRCodeSuggestions` in both auto-action blocks (pull_request and workflow_run). Alternatively, route these auto-actions through `PRAgent().handle_request(...)` so they share the same resolution path.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context
✅ Compliance rules (platform): 34 rules
Review mode: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 10/18, lines 739/200; both must reach the floor). Router rationale: This adds a substantial new subprocess-based handler, handler selection/configuration, CLI security and timeout behavior, parsing/retry paths, and integration changes across multiple independent code paths where subtle defects are plausible.

Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.
Tip of the day
💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant