Repository navigation
Add tool adapter registry and per-tool LLM gateway implementations - #5065
Conversation
There was a problem hiding this comment.
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 transformationAlternative:
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.
There was a problem hiding this comment.
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/toolsadapter interface + default registry with auto-registration viainit(). - 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/teardownorchestration, 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.
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
|
✅ Large PR justification has been provided. The size review has been dismissed and this PR can now proceed with normal review. |
Large PR justification has been provided. Thank you!
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
JAORMX
left a comment
There was a problem hiding this comment.
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:
parentJSONPointer("/a/b/c")→/a/bjsonPointerExists→ falseadd /a/b → {}patch fails because RFC 6902 requires/ato 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
ensurePathExistsinpkg/client/config_editor.go. It already segment-walks AND parses with hujson. That deletesjsonPointerExists+ensureLLMParent+ the standardize dance, and the multi-level guarantee comes for free. Closes the loop on round-1's "reusepkg/clientprimitives" 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.Lstatreject 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 withjsonPointerExistsand skip the patch when absent. pkg/config/config.go's newMarshal()exists solely for one test helper. Inlineyaml.Marshal(cfg)intempProviderand don't grow the public surface.runLLMSetup/runLLMTeardownis real business logic with 390 LOC of unit tests incmd/thv/app/. Per.claude/rules/cli-commands.md, that's a smell — orchestration belongs inpkg/. Future-cleanup direction, not for this PR.- Tests —
TestConfigureLLMGateway_JSONCPreservesExistingParentonly substring-assertsEXISTING_KEY; the headline JSONC promise (comments + trailing commas survive) deserves a literal assertion. The rollback test inrunLLMSetupconfigures 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.
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
There was a problem hiding this comment.
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.
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:
Fixes #5030
Type of change
Test plan
API Compatibility
Special notes for reviewers
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.