Skip to content

Add tool adapter registry and per-tool LLM gateway implementations - #5065

Merged
yrobla merged 4 commits into
mainfrom
issue-5030
Apr 28, 2026
Merged

yrobla merged 4 commits into
mainfrom
issue-5030

Conversation

@yrobla

@yrobla yrobla commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements `thv llm setup` / `thv llm teardown` by extending the existing `pkg/client` framework rather than introducing a parallel adapter registry.

Why this approach:
The reviewer (JAORMX) correctly identified that the original `pkg/llm/tools` design duplicated path-resolution, file-locking, JSONC handling, and atomic writes that `pkg/client` already provides for 28 MCP client integrations. This PR adopts the suggested alternative: extend `clientAppConfig` with LLM gateway fields and add `ConfigureLLMGateway` / `RevertLLMGateway` methods to `ClientManager`.

What changed:

  • Extended `clientAppConfig` with `LLMGatewayMode`, `LLMGatewayOnly`, `LLMSettingsFile`, `LLMSettingsRelPath`, `LLMSettingsPlatformPrefix`, and `LLMGatewayKeys` fields.
  • Populated LLM gateway settings for Claude Code (direct/token-helper), Gemini CLI (direct), VS Code (proxy), Cursor (proxy), and Xcode (proxy, macOS-only, LLM-gateway-only — not an MCP client).
  • Added `ConfigureLLMGateway` / `RevertLLMGateway` / `DetectedLLMGatewayClients` to `ClientManager`, picking up file locking (`fileutils.WithFileLock`), JSONC preservation (`hujson`), and atomic writes (`fileutils.AtomicWriteFile`) for free.
  • Replaced the "not implemented" stubs in `thv llm setup` / `thv llm teardown` with real orchestration: setup detects installed tools, patches each settings file, and rolls back on config-persist failure; teardown reverts patches and optionally purges cached OIDC tokens.
  • `GetAllClients()`, `IsValidClient()`, and `GetClientListFormatted()` now exclude `LLMGatewayOnly` entries so Xcode does not appear in MCP client listings.
  • `runLLMSetup` / `runLLMTeardown` accept an injected `config.Provider` for full unit testability. Tests cover: no detected tools, partial apply failure, rollback on config-persist failure, teardown of all/one tool, unknown-tool error.

Fixes #5030

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (`task test`)
  • E2E tests (`task test-e2e`)
  • Linting (`task lint-fix`)
  • Manual testing (describe below)

API Compatibility

  • This PR does not break the `v1beta1` API, OR the `api-break-allowed` label is applied and the migration guidance is described above.

Special notes for reviewers

  • JSON Patch operations are now constructed via `json.Marshal([]llmPatchOp{...})` rather than `fmt.Sprintf` to prevent CodeQL "unsafe quoting" findings.
  • `RevertLLMGateway` guards with `os.Stat` before acquiring the lock so a missing/deleted settings directory is a clean no-op rather than a lock-file-creation error.
  • `parentJSONPointer` uses `strings.LastIndex` to return the true direct parent for arbitrarily nested pointers; `ensurePathExists` (already segment-walking) handles multi-level creation.
  • Follow-up issue for binary-presence detection (`exec.LookPath`): llm: strengthen tool detection with binary presence check #5070.

Large PR Justification

Integrated refactor: the original `pkg/llm/tools` package and its tests are deleted; equivalent functionality is added inside `pkg/client` as an extension of the existing client framework. The change cannot be split because the deletion and the extension are a single coherent replacement.

@yrobla
yrobla requested a review from Copilot April 27, 2026 08:03
@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Apr 27, 2026
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 27, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR introduces a tool-adapter framework for thv llm setup/teardown, enabling auto-discovery of supported AI tools and per-tool configuration patching to route through the LLM gateway (direct/token-helper or local proxy mode).

Changes:

  • Added pkg/llm/tools adapter interface + default registry with auto-registration via init().
  • Implemented adapters for Claude Code, Gemini CLI, Cursor, VS Code, and Xcode, including atomic JSON patch/revert helpers.
  • Replaced CLI “not implemented” stubs with real setup/teardown orchestration, including optional token purge.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
pkg/llm/tools/adapter.go Defines the Adapter interface, modes, placeholder API key, and ApplyConfig.
pkg/llm/tools/registry.go Adds default/global registry plus Registry methods (Register/All/Detected/Get).
pkg/llm/tools/doc.go Documents the tools package and extension mechanism (init + Register).
pkg/llm/tools/platform.go Adds XDG config helper used by adapters.
pkg/llm/tools/jsonpatch.go Introduces atomic JSON patch/revert utilities incl. nested-key helpers.
pkg/llm/tools/jsonpatch_test.go Unit tests for JSON patch/revert and nested-key behavior.
pkg/llm/tools/claudecode.go Claude Code adapter (token-helper + gateway URL).
pkg/llm/tools/geminicli.go Gemini CLI adapter (token-helper + gateway URL).
pkg/llm/tools/cursor.go Cursor adapter (proxy mode via dotted settings keys).
pkg/llm/tools/vscode.go VS Code adapter (proxy mode via dotted settings keys).
pkg/llm/tools/xcode.go Xcode adapter (macOS-only proxy-mode settings).
pkg/llm/tools/registry_test.go Registry behavior tests and default adapter presence assertions.
pkg/llm/tools/adapters_test.go Integration-style tests for adapter Detect/Apply/Revert behavior.
cmd/thv/app/llm.go Implements thv llm setup and thv llm teardown orchestration using adapters.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/tools/jsonpatch.go Resolved
Comment thread pkg/llm/tools/registry.go Resolved
Comment thread pkg/llm/tools/vscode.go Resolved
Comment thread pkg/llm/tools/cursor.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/tools/adapters_test.go Resolved
@codecov

codecov Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.36416% with 53 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.79%. Comparing base (cb03892) to head (d1b8c2f).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/client/llm_gateway.go 66.20% 27 Missing and 22 partials ⚠️
pkg/client/config.go 77.77% 1 Missing and 1 partial ⚠️
pkg/client/discovery.go 33.33% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5065      +/-   ##
==========================================
+ Coverage   69.78%   69.79%   +0.01%     
==========================================
  Files         566      568       +2     
  Lines       56625    56793     +168     
==========================================
+ Hits        39515    39638     +123     
- Misses      14086    14110      +24     
- Partials     3024     3045      +21     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 27, 2026
@yrobla
yrobla requested a review from Copilot April 27, 2026 08:32
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 27, 2026
@github-actions

Copy link
Copy Markdown
Contributor

✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review.

@github-actions
github-actions Bot dismissed their stale review April 27, 2026 08:33

Large PR justification has been provided. Thank you!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 6 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/tools/adapters_test.go Resolved
Comment thread pkg/llm/tools/adapters_test.go Resolved
Comment thread pkg/llm/tools/jsonpatch_test.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/llm/tools/jsonpatch.go Resolved
@yrobla
yrobla requested a review from Copilot April 27, 2026 10:01
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread pkg/llm/tools/jsonpatch.go Resolved
@yrobla
yrobla requested a review from Copilot April 27, 2026 14:35
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed labels Apr 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 12 out of 12 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/server/swagger.yaml Resolved
Comment thread cmd/thv/app/llm.go Resolved
Comment thread pkg/client/llm_gateway.go Resolved
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 27, 2026

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey Yolanda, this is a much tighter shape — pkg/llm/tools is gone, the file-handling guarantees are the same ones pkg/client already gives us, and the orchestration tests cover the rollback path I was worried about. Big improvement, thanks for the rework.

Round 2 is mostly nits. One real doc/code mismatch I'd want resolved before merge, plus a quoting hardening and a rebase.

What's resolved from round 1

For my own confidence I walked through every prior item against the current head:

Item Status Where
pkg/llm/tools parallel registry ✅ deleted; 4/5 clients extend existing clientAppConfig entries pkg/client/config.go
File locking ✅ fileutils.WithFileLock pkg/client/llm_gateway.go:55, 123
JSONC preservation ✅ hujson.Parse → Patch → Format :63, 90, 95
Atomic writes ✅ fileutils.AtomicWriteFile :99, 158
Empty-parent pruning bug ✅ gone (RFC 6902 remove only, no recursive cleanup) —
init() global registry ✅ gone —
Injected config.Provider + rollback path tested ✅ via errOnUpdateProvider stub cmd/thv/app/llm_test.go:202, 309
Cursor/VSCode settingsPath duplication ✅ all paths route through buildConfigFilePath + LLMSettingsPlatformPrefix —
BoolVar style ✅ cmd/thv/app/llm.go:347
CodeQL "unsafe quoting" ✅ all patches via json.Marshal([]llmPatchOp{…}) —
RevertLLMGateway lock-on-missing-dir ✅ os.Stat before WithFileLock :119-121
parentJSONPointer true direct parent ✅ strings.LastIndex :223-229
LLMGatewayOnly filtering ✅ all six entry points (GetAllClients, IsValidClient, GetClientListFormatted, IsClientInstalled, GetClientStatus, CreateClientConfig) —
Binary-presence detection ⏭ deferred to #5070, fine by me —

What I'd want before merge

1. The PR description and ConfigureLLMGateway disagree with the code on multi-level parent creation.

Description says "ensurePathExists (already segment-walking) handles multi-level creation". The actual ensureLLMParent at pkg/client/llm_gateway.go:236-252 only ensures the single direct parent. Trace /a/b/c where /a is missing:

  1. parentJSONPointer("/a/b/c") → /a/b
  2. jsonPointerExists → false
  3. add /a/b → {} patch fails because RFC 6902 requires /a to exist

Today no LLMGatewayKeySpec goes deeper than 2 (/env/ANTHROPIC_BASE_URL, /auth/tokenCommand), so this is dormant... but the next config that needs /a/b/c will silently fail at apply time. Two ways out:

  • Walk the segments and ensure each ancestor exists (~8 LOC).
  • My preference: route through the existing ensurePathExists in pkg/client/config_editor.go. It already segment-walks AND parses with hujson. That deletes jsonPointerExists + ensureLLMParent + the standardize dance, and the multi-level guarantee comes for free. Closes the loop on round-1's "reuse pkg/client primitives" theme.

Either fix the code or trim the description to say "single direct parent only" and document the constraint on LLMGatewayKeySpec.JSONPointer.

2. Token-helper command quoting. cmd/thv/app/llm.go:251 builds fmt.Sprintf("\"%s\" llm token", self) from os.Executable(). The string is JSON-marshalled correctly — that's fine — but it's then re-parsed as a shell command line by Claude Code's apiKeyHelper and Gemini's auth.tokenCommand. JSON escaping doesn't help against shell metacharacters. If the executable path contains a literal ", \, or ; (legal on macOS/Linux, occasional on Windows installers), the helper command becomes garbage and the user's tool can't authenticate.

Cheapest defense: reject os.Executable() paths containing "\\;\n\r with a clear error from runLLMSetup. Or POSIX-quote on Unix. Either way — this gets written into long-lived user config, so getting it wrong is very visible.

3. Rebase. PR is behind main. #5052 (68d29fbc, withPreemptiveRefresh fix) touches pkg/llm/tokensource.go and added pkg/auth/oauth/non_caching_refresher.go after this branch was cut. Not a revert risk — the merge would pull them in — but please rebase so CI runs against current main and any semantic conflicts in the LLM-token area surface now rather than after merge.

Smaller stuff (would-be-nice, not blocking)

  • Symlink TOCTOU in RevertLLMGateway — Stat→Lock→ReadFile follows symlinks; a same-UID process could swap the file between checks. os.Lstat reject of symlinks hardens this. Low likelihood given the threat model.
  • Brittle string match at RevertLLMGateway:147-148 — "path not found" is dead code (hujson only emits "value not found"). Cleaner: pre-check with jsonPointerExists and skip the patch when absent.
  • pkg/config/config.go's new Marshal() exists solely for one test helper. Inline yaml.Marshal(cfg) in tempProvider and don't grow the public surface.
  • runLLMSetup / runLLMTeardown is real business logic with 390 LOC of unit tests in cmd/thv/app/. Per .claude/rules/cli-commands.md, that's a smell — orchestration belongs in pkg/. Future-cleanup direction, not for this PR.
  • Tests — TestConfigureLLMGateway_JSONCPreservesExistingParent only substring-asserts EXISTING_KEY; the headline JSONC promise (comments + trailing commas survive) deserves a literal assertion. The rollback test in runLLMSetup configures one tool; the contract is "all patched tools roll back" — a 2-tool variant would lock that. Both cheap to add.

Re-iterating: the core is in great shape. Once 1 and 2 are addressed (and rebased), this is good to go.

Thanks again for taking the round-1 feedback seriously and doing the actual refactor — the result is markedly cleaner.

taskbot added 3 commits April 28, 2026 09:23
Introduces pkg/llm/tools with a Detect/Apply/Revert
adapter interface and auto-discovery registry. Adding a new tool requires
only implementing the interface and calling Register() from init() — no
changes to orchestration are needed.

Token-helper adapters (claude-code, gemini-cli) patch their config files
to invoke "thv llm token" on demand and point at the upstream gateway URL.
Proxy-mode adapters (cursor, vscode, xcode) patch their config files to
point at the localhost reverse proxy with a placeholder API key.

Replaces the "not implemented" stubs in thv llm setup/teardown with the
real orchestration logic: setup detects installed tools and applies all
adapters, teardown reverts them and (optionally) purges cached tokens.

All config file writes are atomic (temp-file + rename). VS Code and Cursor
settings use literal dotted key names rather than nested maps; a separate
revertFlatJSONFile helper handles that distinction.

Closes: #5030
@yrobla
yrobla requested a review from Copilot April 28, 2026 07:23
@github-actions github-actions Bot removed the size/XL Extra large PR: 1000+ lines changed label Apr 28, 2026
@yrobla
yrobla requested a review from JAORMX April 28, 2026 07:23
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 28, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/server/swagger.json Resolved
Comment thread docs/server/docs.go Resolved
Comment thread cmd/thv/app/llm.go Resolved
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 28, 2026
@yrobla
yrobla merged commit 60ccd8f into main Apr 28, 2026
32 of 33 checks passed
@yrobla
yrobla deleted the issue-5030 branch April 28, 2026 08:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

thv llm: tool adapter registry and per-tool implementations

5 participants