Compare commits

...
Author SHA1 Message Date
Finessse b654a19a09 feat(gemini): enable thinking by default for Gemini 3 Flash 2026-01-11 14:28:59 +07:00
Finessse 0420fd0046 build(scripts): embed version info in macOS build script
Use git describe/rev-parse for version/commit and pass via ldflags.
2026-01-11 08:43:00 +07:00
Finessse 46ad228707 sync(upstream): developer role + message_delta fix + auth cleanup
Cherry-picked:
- 7815ee33: adjust message_delta emission boundary in Claude-to-OpenAI
- 6762e081: add developer role support for Gemini translators
- 5e5d8142: fix auth error when antigravity refresh token missing
2026-01-11 06:45:24 +07:00
Finessse 741333697e sync(upstream): gemini thinking guards + thoughtSignature
Cherry-picked:
- 05444cf3: abort default injection on existing thinking keys
- 8edbda57: add thoughtSignature to node parts for Gemini/Antigravity

Skipped ef6bafbf (context cancellation) - structural conflict with our
multi-project fallback loops.
2026-01-11 06:45:24 +07:00
Finessse d3b5b0017f fix(config): preserve comments + deep copy nodes for YAML merge
Cherry-picked config fixes from upstream:
- 2e88c485: avoid adding new keys when merging
- ee552f87: deep copy nodes to prevent shared references
- c8e72ba0: preserve comment nodes during merge
- 09455f9e: additional merge edge case fixes

Kept our isZeroValueNode for smarter zero-value detection.
2026-01-11 06:33:53 +07:00
Finessse 9f5eb93f64 sync(upstream): add HttpRequest support across executors
Cherry-picked from e8e3bc86. Adds HttpRequest method to ProviderExecutor
interface for injecting credentials into arbitrary HTTP requests.

- Added HttpRequest to conductor.go interface
- Added HttpRequest stubs to kiro, minimax, zhipu executors
- Added http-request example
- Updated mock executors in tests

Also kept our Embed method and CountTokens implementations.
2026-01-11 06:32:53 +07:00
Finessse baf72225a5 sync(upstream): codex subscription dates + logger cleanup
Cherry-picked:
- 6494330c: add subscription date fields to ID token claims
- bc3195c8: remove unnecessary request details limit logic
2026-01-11 06:24:54 +07:00
Finessse 01e1d5aed2 sync(upstream): auth rotation atomic fix + memory leak fixes
- fix(auth): make provider rotation atomic (keep shouldKeepProviderOrder)
- fix(server): resolve memory leaks in failed attempts and codex cache
  - Add background cleanup goroutine for stale IP entries
  - Add cache expiry cleanup for codex prompt cache
- Update provider rotation tests for atomic rotation

Cherry-picked: 8be06255, 47dacce6
Merged with ProxyPilot's shouldKeepProviderOrder for gemini-3 fallback
2026-01-11 06:11:37 +07:00
Finessse 19bf935a2e sync(upstream): Gemini 3 Pro and Antigravity executor improvements
- feat(executor): enhance Antigravity payload with user role and dynamic system instructions
- feat(executor): add model-specific support for "gemini-3-pro" in execution
- feat(executor): update system instruction handling for Claude and Gemini-3-Pro models
- fix(executor): update gemini model identifier to gemini-3-pro-preview
- feat(executor): centralize systemInstruction handling

Cherry-picked: 67985d82, bda04eed, 1b2f9076, b6a0f7a0, 59a448b6
2026-01-11 06:03:27 +07:00
Finessse fd9d097b8e sync(upstream): management API and executor improvements
- feat(management): add generic API call handler
- Fix: disable thinking when tool_choice forces tool use
- feat(api): add ManagementTokenRequester interface (sans iflow)
- fix(management): refresh antigravity token for api-call $TOKEN$
- fix(auth): error when antigravity refresh token missing during refresh

Cherry-picked: ade71947, aca2ef63, ee171bc5, b01619b4, 5e5d8142
Adapted: removed iflow references (not in ProxyPilot)
2026-01-11 06:00:37 +07:00
Finessse 4bf4256e3f sync(upstream): logging/handlers improvements
- fix(logging): improve request/response capture
- fix(handlers): match raw error text before JSON body for duplicate detection
- feat(logging): disambiguate OAuth credential selection in debug logs
- Various logging refinements for auth selection

Cherry-picked from upstream: a091d12f, 3ca5fb10, 0e4148b2, 79fbcb3e, 48f6d7ab, 48f19aab, cb3bdffb, a95428f2
2026-01-11 05:57:48 +07:00
Finessse 95bbb4d7f3 sync(upstream): add index field to image response for LiteLLM
- Uses json.Marshal for cleaner image payload construction
- Cherry-picked from upstream 671558a8, a7fc2ee4
2026-01-11 05:50:58 +07:00
Finessse a9cef821f9 sync(upstream): preserve built-in tools across openai<->responses
Cherry-picked from upstream 0b834fcb
2026-01-11 05:48:45 +07:00
Finessse a1620c5cb0 fix(auth): support both Antigravity IDE and Gemini CLI token paths
- Check OS-specific Antigravity path first, fallback to ~/.gemini/
- Add expiry_date field support (Unix ms timestamp)
- Windows: %APPDATA%\Antigravity -> %USERPROFILE%\.gemini
- macOS: ~/Library/Application Support/Antigravity -> ~/.gemini
- Linux: ~/.antigravity -> ~/.gemini
2026-01-11 05:20:13 +07:00
Finessse 2465a8fff1 chore: remove upstream Community Projects section from README 2026-01-11 05:14:16 +07:00
Finessse f0568a5c20 docs(cli): update --antigravity-import flag description 2026-01-11 05:11:20 +07:00
Finessse 63da07d1f1 fix(cmd): update antigravity import to use new SDK method 2026-01-11 05:11:13 +07:00
Finessse 7157230427 refactor(auth): rename ImportFromGeminiCLI to ImportFromAntigravityIDE 2026-01-11 05:11:05 +07:00
Finessse bcdbba5f76 fix(auth): read tokens from Antigravity IDE instead of Gemini CLI
Update token paths to OS-specific Antigravity locations:
- Linux: ~/.antigravity/oauth_creds.json
- macOS: ~/Library/Application Support/Antigravity/oauth_creds.json
- Windows: %APPDATA%\Antigravity\oauth_creds.json
2026-01-11 05:10:59 +07:00
Finessse 9679f69b81 feat(auth): add Gemini CLI token import for Antigravity
- Add internal/auth/antigravity package with token loading from ~/.gemini/oauth_creds.json
- Add ImportFromGeminiCLI method to AntigravityAuthenticator
- Add DoAntigravityImport CLI command
- Add --antigravity-import flag to server binary

Usage: proxypilot --antigravity-import
2026-01-11 04:10:54 +07:00
Finessse 8ddaa140af chore: sync non-code changes from upstream v6.6.98
- .dockerignore: add .codex, .agents, .opencode entries
- .gitignore: add .codex, .agents, .opencode entries
- README.md: add Community Projects section (Quotio, CodMate, Claude Proxy VSCode)
2026-01-11 04:01:21 +07:00
Finessse 34f9bbd56e fix(auth): prevent race in kiro auth callback server shutdown 2026-01-10 06:03:03 +07:00
Finessse cddccdd5cb feat(executor): add project and model fallback on 429 for gemini-cli 2026-01-10 06:02:48 +07:00
Finessse 06c41e1a00 test(executor): add antigravity project switch integration test 2026-01-10 06:02:35 +07:00
Finessse 092cef6fa3 feat(executor): add project and model fallback on 429 for antigravity 2026-01-10 06:02:20 +07:00
Finessse 7806419df5 test(executor): add quota fallback unit tests 2026-01-10 06:02:06 +07:00
Finessse ff5a078229 feat(executor): add quota fallback helpers for project and model switching 2026-01-10 06:01:52 +07:00
Finessse e2894fa447 docs(readme): add security defaults and lightweight profile sections 2026-01-09 23:43:06 +07:00
Finessse d9500d4961 docs(config): document lightweight profile and new config options 2026-01-09 23:42:50 +07:00
Finessse ab2be5d03c fix(auth): simplify auto-refresh interval validation 2026-01-09 23:42:36 +07:00
Finessse 0761e2b695 fix(auth): prioritize paidTier over isDefault for antigravity tier detection 2026-01-09 23:42:13 +07:00
Finessse db647820c9 fix(util): add kiro prefix fallback and reduce debug log noise 2026-01-09 23:41:57 +07:00
Finessse 8c991a8ed3 feat(registry): add kiro thinking model definitions 2026-01-09 23:41:39 +07:00
Finessse 123fd00c0a feat(executor): add kiro thinking model variants mapping 2026-01-09 23:41:25 +07:00
Finessse b87fe4580d fix(executor): update antigravity user-agent and add required headers 2026-01-09 23:41:11 +07:00
Finessse aeff3e8c09 fix(memory): handle cliproxyexecutor.Response in auth adapter 2026-01-09 23:40:53 +07:00
Finessse 3a8fac2514 feat(server): wire up lightweight profile toggles and configurable CORS 2026-01-09 23:40:39 +07:00
Finessse 283e8cfb52 feat(config): add lightweight profile options and CORS settings 2026-01-09 23:40:25 +07:00
Finessse 854bd25940 feat(cache): add max-bytes size limit for prompt cache 2026-01-09 23:40:10 +07:00
Finessse f42cadf459 feat(cache): add max-bytes size limit for response cache 2026-01-09 23:39:57 +07:00
Finessse b4a54444d8 feat(usage): add sampling rate support for usage statistics 2026-01-09 23:39:42 +07:00
Finessse 6990e769ea fix(management): return 404 when request history is disabled 2026-01-09 23:39:28 +07:00
Finessse 69ba18a095 fix(middleware): respect request history sampling in logging middleware 2026-01-09 23:39:14 +07:00
Finessse 8b9f5ebe00 feat(middleware): add runtime toggle and sampling for request history 2026-01-09 23:39:00 +07:00
Finessse 65e243ec1b feat(middleware): add runtime toggle for Prometheus metrics 2026-01-09 23:38:47 +07:00
Finessse fce1e62aa4 perf(middleware): pool response body buffers to reduce GC pressure 2026-01-09 23:38:34 +07:00
Finessse bc3d89d958 perf(handlers): cache request details lookup per model 2026-01-09 23:38:21 +07:00
Finessse 5d9d4328f9 refactor(handlers): use pooled SSE writer helpers across all providers 2026-01-09 23:38:09 +07:00
Finessse b02b3c32ce perf(sdk): use pre-allocated byte slice for SSE keep-alive 2026-01-09 23:37:55 +07:00
Finessse 616cde1a0f test(sdk): add stream forwarder benchmarks 2026-01-09 23:37:41 +07:00
Finessse d2efc1dd8e feat(sdk): add pooled SSE writer helpers for reduced allocations 2026-01-09 23:37:29 +07:00
Finessse 86470c8274 feat(routing): add usage-aware credential selector
Routes requests to the account with lowest daily output tokens.
Spreads load across accounts to avoid hitting quota limits.
Config: routing.strategy = "usage-aware" or "least-used"
2026-01-08 04:45:19 +07:00
Finessse 5fdb0ff618 feat(webui): add per-account usage display
Auth table shows daily output tokens and request count.
Hover tooltip displays total usage stats.
API exposes usage field in auth-files response.
2026-01-08 04:34:50 +07:00
Finessse f9f4425147 chore: ignore local planning docs and debug configs 2026-01-06 06:39:59 +07:00
Finessse dc0685561e chore: rebuild webui assets 2026-01-06 06:24:55 +07:00
Finessse 0551a8bd18 chore: remove managementasset references from server 2026-01-06 06:24:20 +07:00
Finessse 33be41ba03 feat(cache): wire cache initialization and add docs
Initialize response/prompt caches in Service.Run from config.
Add cache lookup to executor payload helpers.
Document cache config and management API in README.
2026-01-06 06:24:01 +07:00
Finessse d317728d93 feat(webui): add priority controls and token expiry display
ProviderLogins table now shows:
- Priority column with up/down reorder buttons
- Expires column with color-coded status (green/yellow/red)
API exposes token_expires_at for WebUI consumption.
2026-01-06 06:22:40 +07:00
Finessse c8176cddab chore: remove legacy management UI
Remove /management.html, pp_open_legacy_ui tray binding,
disable-control-panel and panel-github-repository config options.
OpenManagementUI now opens /proxypilot.html directly.
2026-01-06 06:22:06 +07:00
Finessse 30978f1f17 feat(cache): add response cache and prompt cache tracking
Response cache stores completions keyed by request hash.
Prompt cache tracking aggregates cache_read/cache_creation tokens.
WebUI CacheStats component shows hit rates and token savings.
2026-01-06 06:21:54 +07:00
Finessse 1f3e82af04 fix(ci): move secrets check to step level 2026-01-05 13:02:06 +07:00
Finessse 093e77c8c0 feat: add priority/usage APIs, WebUI dashboard, config options
- PATCH /v0/management/auth/:id/priority endpoint
- GET /v0/management/auth/:id/usage endpoint
- AccountUsage.tsx dashboard component
- AutoRefreshBuffer, DailyResetHour config fields
- Conductor wiring for refresh config
2026-01-05 12:59:29 +07:00
Finessse 4dd917ff31 feat(auth): wire usage tracking and token expiry to CLI
- Add authUsagePlugin to bridge usage.Record -> Auth.Usage stats
- Register plugin in service.Run() after usage.StartDefault()
- Populate TokenExpiresAt from metadata in Load/Register/Update
- Enables per-auth usage tracking and proactive token refresh
2026-01-05 07:25:02 +07:00
Finessse 43f625caf1 chore: integrate sdk test files into main repo 2026-01-05 03:23:41 +07:00
Finessse c33d299137 feat(auth): add priority, usage tracking, and proactive token refresh
- Add Priority field to Auth for per-provider account ordering
- Add UsageStats struct tracking total/daily tokens and requests
- Track usage in MarkResult with daily reset logic
- Add TokenExpiresAt for proactive refresh (5min buffer)
- Sort available auths by priority in selector
2026-01-05 03:18:33 +07:00
Finessse 5930e6b8c4 fix(webui): load react-grab in dev mode only 2026-01-05 00:55:32 +07:00
Finessse 3531191944 feat(webui): add react-grab for component context copying
Ctrl+C on any element copies file name, component, and HTML source.
2026-01-05 00:52:24 +07:00
Finessse b9ccbfb107 refactor: remove Continue integration
Continue VS Code extension is no longer supported.
2026-01-05 00:19:59 +07:00
Finessse fecc80de5f refactor: remove TUI flags from CLI 2026-01-04 19:51:07 +07:00
Finessse 3abcc42139 refactor: remove proxypilotui command 2026-01-04 19:50:56 +07:00
Finessse b17f421233 refactor: remove TUI package
Windows CMD/PowerShell rendering issues. Will rebuild later.
2026-01-04 19:50:50 +07:00
Finessse d8eb507d6f chore(gitignore): ignore local harness artifacts 2026-01-01 00:54:39 +07:00
Finessse 7c87e241fb feat(tui): improve layout and ascii fallbacks 2026-01-01 00:52:14 +07:00
Finessse 3d9e0cb89b chore(registry): trim model catalog 2026-01-01 00:52:05 +07:00
Finessse 99c4d3ccc3 feat(memory): harden summarization pipeline 2026-01-01 00:51:56 +07:00
Finessse e5aec4a28e fix(harness): skip initializer in existing projects 2026-01-01 00:51:46 +07:00
Finessse 5f7ebd40fe fix(translator): drop defer_loading tool fields 2026-01-01 00:51:38 +07:00
Finessse 36621166c8 feat(antigravity): capture tier metadata and retry delays 2026-01-01 00:51:28 +07:00
Finessse e15a091615 fix(tui): use net.JoinHostPort for IPv6 compatibility
Replace fmt.Sprintf for address formatting with net.JoinHostPort
to properly handle IPv6 addresses.
2025-12-31 02:27:19 +07:00
Finessse ad5c8112cb feat(scripts): add Windows TUI web launcher
Batch script to start TUI with web dashboard enabled.
2025-12-31 02:11:05 +07:00
Finessse 50b540fcae feat(scripts): add Windows watchdog script
PowerShell script to monitor and restart ProxyPilot service.
2025-12-31 02:10:40 +07:00
Finessse 2ad425588f feat(docker): add Dockerfile for TUI container
Enable containerized deployment of the TUI application.
2025-12-31 02:09:53 +07:00
Finessse e099c1dc0b fix(util): update schema tests for placeholder property behavior
Adjust test expectations to include '_' placeholder property
added to object schemas without required fields (Claude VALIDATED mode).
2025-12-31 02:09:32 +07:00
Finessse 10013ad979 chore(deps): update dependencies
Sync go.mod and go.sum with latest dependency versions.
2025-12-31 02:08:55 +07:00
Finessse 556fac1667 feat(examples): add CountTokens to custom provider example
Demonstrate token counting implementation in custom provider.
2025-12-31 02:08:39 +07:00
Finessse 1b0394bf55 feat(translator): enhance Antigravity Claude request handling
Improve request translation with additional test coverage.
2025-12-31 02:08:06 +07:00
Finessse c720fad57b feat(executor): add embeddings support to Kiro executor
Handle embedding requests in Kiro runtime executor.
2025-12-31 02:07:48 +07:00
Finessse aafbdb9c46 feat(cmd): add Kilo Code and RooCode proxy configurations
Extend agent switching to support additional AI coding assistants
with their respective proxy settings.
2025-12-31 02:07:00 +07:00
Finessse 76c52e1a47 feat(tui): minor server view adjustments
Small styling updates for server status display.
2025-12-31 02:06:40 +07:00
Finessse 0ffee090d0 feat(tui): enhance switch view styling
Apply theme styles to provider switching interface.
2025-12-31 02:06:19 +07:00
Finessse fd71a01aa7 feat(tui): update mappings view with new styles
Apply consistent theme to model mappings display.
2025-12-31 02:05:41 +07:00
Finessse 2796512cb3 feat(tui): improve usage view layout
Better formatting and styling for usage statistics display.
2025-12-31 02:05:24 +07:00
Finessse 289871da14 feat(tui): enhance login view styling
Apply new theme styles to login form components.
2025-12-31 02:05:05 +07:00
Finessse 336359c9d7 feat(tui): connect logs view to ring buffer
Display real-time logs from GlobalBuffer with filtering
and auto-scroll support.
2025-12-31 02:04:10 +07:00
Finessse 06684b81ef feat(tui): improve main layout with responsive design
Enhance sidebar, content area, and navigation with better
proportions and overflow handling.
2025-12-31 02:03:12 +07:00
Finessse f0a7040b00 feat(tui): add comprehensive theme and styles system
Define color palette, component styles, and responsive layout
helpers for consistent TUI appearance.
2025-12-31 02:02:54 +07:00
Finessse 64358ecfd8 feat(updates): add GPG signature verification for releases
Implement release signature verification using embedded public key.
Ensures binary integrity before applying updates.
2025-12-31 02:02:16 +07:00
Finessse 0ce9661a88 feat(api): serve embedded dashboard assets
Replace placeholder HTML with actual embedded React assets.
Serve index.html, JS, CSS, and static files from embed.FS.
2025-12-31 02:01:31 +07:00
Finessse e01aeda3de feat(webui): update React dashboard bundle
Rebuild frontend assets with latest UI improvements.
2025-12-31 02:01:11 +07:00
Finessse de5098f8aa feat(api): integrate connection tracker and metrics
Wire ConnectionTrackerMiddleware and /metrics endpoint into
the Gin engine for production observability.
2025-12-31 02:00:22 +07:00
Finessse 2219bc04e4 feat(api): add Prometheus metrics endpoint
Expose /metrics endpoint for observability with request counts,
latencies, and connection stats.
2025-12-31 02:00:01 +07:00
Finessse 94ef02e19d feat(api): add connection tracker middleware
Track active HTTP connections with thread-safe counter.
Exposes ActiveConnections.Count() for monitoring.
2025-12-31 01:59:17 +07:00
Finessse f5b7aaf9ae feat(logging): wire ring buffer hook into global logger
Add GlobalBuffer hook to capture all log entries for real-time
display in TUI logs view.
2025-12-31 01:58:53 +07:00
Finessse 35018f2e43 feat(logging): add ring buffer for in-memory log capture
Implement thread-safe circular buffer that captures log entries
for display in TUI and web dashboard. Integrates as a logrus hook.
2025-12-31 01:58:09 +07:00
Finessse 6d4e3ceb29 chore: add platform-specific binary names to gitignore
Add proxypilot-linux, proxypilot-darwin, and proxypilot-windows
to prevent accidental commits of compiled binaries.
2025-12-31 01:57:36 +07:00
Finessse 6982a4cc31 feat(tui): add responsive layout and fix sidebar overflow
COMPLETED:
- Added ViewWithSize(width, height) pattern to all submodels
  - login.go: responsive provider rows with adaptive widths
  - switch.go: responsive agent rows without card borders
  - mappings.go: responsive table columns with calculateColumnWidths()
  - usage.go: responsive stat cards (2x2 grid layout)
  - logs.go: responsive log entries with message truncation

- Fixed main View() layout calculation in tui.go
  - Properly accounts for border (2) + padding (2) = 4 chars per panel
  - sidebarWidth now represents content width (20/14 for normal/narrow)
  - contentWidth = m.width - sidebarWidth - 9 (accounts for both panels)

- Added new screen files:
  - integrations.go: setup/integration screen
  - logs.go: real-time log viewer with filtering
  - mappings.go: model alias mappings table
  - usage.go: usage statistics with charts

PENDING TEST:
- Verify sidebar displays correctly alongside content (was overflowing)
- Test all screens at various terminal widths (60, 80, 100+ cols)

KNOWN ISSUE BEING FIXED:
- Sidebar was showing only "[8] Setup" at top due to width overflow
- Content panel was too wide, causing horizontal wrap
2025-12-30 08:45:56 +07:00
Finessse bd7575ca2b chore: apply upstream fixes from CLIProxyAPI v6.6.68
Cherry-picked fixes:
- fix(antigravity): inject required placeholder when properties exist without required
- fix(translators): correct key path for system_instruction.parts in Claude request logic
2025-12-30 02:26:57 +07:00
Finessse 27036f44a2 fix(ci): remove .syso files for non-Windows builds 2025-12-30 02:01:05 +07:00
Finessse 3f737dc3c7 fix: cross-platform SysProcAttr for non-Windows builds 2025-12-30 01:57:41 +07:00
Finessse 23a1fa749c chore: bump version to 0.2.0 2025-12-30 01:52:42 +07:00
Finessse e01976448c ci: rename workflows and use v* tag format 2025-12-30 01:43:16 +07:00
Finessse 6e53bdade9 feat: add --tui flag for interactive mode 2025-12-30 01:28:38 +07:00
Finessse 7d90fda663 feat(tui): add status dashboard screen 2025-12-30 01:28:34 +07:00
Finessse 93a0643466 feat(tui): add provider login screen 2025-12-30 01:28:29 +07:00
Finessse dd113e5077 feat(tui): add agent switch screen 2025-12-30 01:28:25 +07:00
Finessse e20343eeec feat(tui): add server control screen 2025-12-30 01:28:20 +07:00
Finessse 738cd4d365 feat(tui): add main TUI app and utilities 2025-12-30 01:28:05 +07:00
Finessse 244782281c feat(tui): add styles and key bindings 2025-12-30 01:28:01 +07:00
Finessse 1e803c918c deps: add bubbletea TUI dependencies 2025-12-30 01:27:57 +07:00
Finessse 3bf998591e docs: update CLI tools table for unified proxypilot 2025-12-30 01:27:53 +07:00
Finessse bff94bd739 chore: update gitignore for cli.md 2025-12-30 01:27:50 +07:00
Finessse 4f65198207 docs: add unified CLI documentation 2025-12-30 01:27:46 +07:00
Finessse 6737add91e ci: add proxypilot npm release workflows 2025-12-30 01:27:25 +07:00
Finessse 470a371295 feat: add unified proxypilot npm package 2025-12-30 01:27:21 +07:00
Finessse 8e18f36d96 chore: remove ppswitch workflows 2025-12-30 01:27:17 +07:00
Finessse baa38a6420 chore: remove ppswitch docs 2025-12-30 01:27:13 +07:00
Finessse b7cd41110e chore: remove standalone ppswitch CLI 2025-12-30 01:27:10 +07:00
Finessse 6fe6d743bd chore: remove ppswitch npm package 2025-12-30 01:27:06 +07:00
Finessse ea371ccfc6 refactor: remove desktop GUI, keep CLI + tray architecture
- Delete cmd/proxypilotui/main_windows.go (desktop GUI)
- Keep cmd/proxypilotui/assets/ (web dashboard)
- Update cliproxytray to remove embedded asset server
- Update proxypilot_dashboard.go for standalone dashboard
- Update README and docs for CLI + tray architecture
- Update proxypilotpack build scripts
2025-12-30 00:25:15 +07:00
Finessse 7b58cdc5a6 docs: add ppswitch documentation 2025-12-29 23:40:55 +07:00
Finessse d103729baf Revert "docs: add ppswitch config switcher documentation"
This reverts commit edacca735a.
2025-12-29 23:39:35 +07:00
Finessse edacca735a docs: add ppswitch config switcher documentation 2025-12-29 23:38:52 +07:00
Finessse 3d8fe7d4e9 fix(ci): fix bun publish auth by using local .npmrc 2025-12-29 22:55:57 +07:00
Finessse 83160e11a7 fix(ppswitch): correct GitHub URL in help text 2025-12-29 22:47:35 +07:00
Finessse 594c830a39 fix(ppswitch): correct GitHub repo URL in package files
- Update REPO to Finesssee/ProxyPilot
- Fix repository and homepage URLs
2025-12-29 22:14:40 +07:00
Finessse cea2b82ffc ci(ppswitch): add bun publish workflow
- Auto-publish to registry after release workflow completes
- Support manual workflow dispatch
- Use bun for publishing
2025-12-29 22:13:46 +07:00
Finessse 8f0165f743 ci(ppswitch): add release workflow for multi-platform builds
- Build binaries for darwin, linux, windows (amd64, arm64)
- Create GitHub release on ppswitch-v* tag push
- Use matrix strategy for parallel builds
2025-12-29 22:13:32 +07:00
Finessse 936cb0a873 feat(ppswitch): add bun package for easy installation
- Add package.json with bun postinstall script
- Add install.ts for binary download
- Add bin wrapper script
- Add README with usage instructions
- Version 0.1.0
2025-12-29 22:13:20 +07:00
Finessse 4206d57bd9 build(ppswitch): add Makefile for cross-platform builds
- Add build target for current platform
- Add build-all target for all platforms
- Add clean and install targets
2025-12-29 22:13:10 +07:00
Finessse b8ffbab975 chore(ppswitch): update version to 0.1.0 and help text
- Change version from 1.0.0 to 0.1.0
- Update install command to use bun
- Improve help text formatting
2025-12-29 22:12:59 +07:00
Finessse 9583beadb8 docs: update provider count to include Gemini CLI 2025-12-29 21:23:23 +07:00
Finessse 4827af9b48 chore(build): rebuild webui assets 2025-12-29 21:22:09 +07:00
Finessse 710a2dc3bc chore(api): update dashboard route configuration 2025-12-29 21:21:42 +07:00
Finessse 2125f99650 chore(webui): misc dashboard UI improvements
Minor updates to Integrations and ProviderLogins components.
2025-12-29 21:21:28 +07:00
Finessse 997ea17f88 feat(webui): add shell config modal to agent setup
Add 'Shell' button per agent that opens modal displaying environment
variables and shell profile configuration snippets. Includes copy-to-
clipboard functionality for easy shell integration.
2025-12-29 21:21:02 +07:00
Finessse ffb7ae1b41 feat(webui): add thinking budget settings UI component
Add ThinkingBudgetSettings component with preset selection (Low/Medium/
High/Custom), enable/disable toggle, and custom token input. Integrated
into dashboard routing.
2025-12-29 21:20:50 +07:00
Finessse 4f32ceac9b feat(webui): enhance request history viewer with filtering
Add live/history toggle, date range filtering, model/provider/status
filters, pagination, export/import/clear buttons, and statistics display.
Fetches from persistent /request-history endpoint.
2025-12-29 21:20:36 +07:00
Finessse 3e8d6e3c92 feat(api): register management routes for new features
Register routes for:
- /request-history/* endpoints (persistent history)
- /thinking-budget endpoint (extended thinking config)

Initialize RequestHistoryManager with auto-save.
2025-12-29 21:20:07 +07:00
Finessse 0da9aa6cd3 feat(cmd): add ppswitch lightweight config switcher binary
Add standalone ppswitch binary for fast agent configuration switching
without server logging overhead. Usage:
- ppswitch              Show all agent statuses
- ppswitch <agent>      Show specific agent status
- ppswitch <agent> <mode>  Switch agent to proxy/native mode
2025-12-29 21:19:52 +07:00
Finessse 7afc014c0e feat(cmd): integrate switch command into main binary
Add --switch and --mode flags plus subcommand-style 'proxypilot switch'
syntax for quick agent configuration switching. Supports both flag style
(--switch claude --mode proxy) and subcommand style (proxypilot switch
claude proxy).
2025-12-29 21:19:25 +07:00
Finessse 1a85ba0e17 feat(cmd): add agent configuration switch command
Add DoSwitch() and DoSwitchStatusAll() for switching agent configs
between proxy mode (routed through ProxyPilot) and native mode (direct
API access). Supports claude, gemini, codex, opencode, droid, cursor,
kilo, and roocode agents with backup/restore functionality.
2025-12-29 21:19:12 +07:00
Finessse 891a52c5de feat(api): add thinking budget management endpoint
Add GET/PUT /thinking-budget endpoint for configuring extended
thinking token budgets. Supports preset levels (Low 2048, Medium 8192,
High 32768) and custom values with enable/disable toggle.
2025-12-29 21:18:58 +07:00
Finessse f7ae19d960 feat(api): add request history API endpoints
Add management endpoints for request history:
- GET /request-history - list entries with pagination
- GET /request-history/stats - aggregate statistics
- DELETE /request-history - clear all entries
- POST /request-history/export - export to JSON
- POST /request-history/import - import from JSON
- POST /request-history/save - force save to disk

Integrate RequestHistoryManager with request logging middleware.
2025-12-29 21:18:45 +07:00
Finessse ad355f75a7 feat(api): add persistent request history storage
Add RequestHistoryManager with file-based persistence at
~/.cli-proxy-api/request-history.json. Features:
- Max 500 entries with automatic pruning
- Auto-save every 30 seconds
- Thread-safe with mutex protection
- In-memory ring buffer for performance
2025-12-29 21:18:31 +07:00
Finessse 48c4cbcdf7 feat(agents): add shell config interface for CLI setup
Add GetShellConfig() to AgentHandler interface returning ShellConfigInfo
with environment variables and shell profile snippets. Implement for all
agents: Claude Code, Codex, Gemini CLI, Cursor, OpenCode, Factory Droid,
and Amazon Q CLI.
2025-12-29 21:17:58 +07:00
Finessse e6ea4295ab feat(config): add thinking budget configuration types
Add ThinkingBudgetConfig struct with preset levels (Low 2048, Medium 8192,
High 32768, Custom) for controlling extended thinking token budgets.
Supports enabled toggle and custom token count.
2025-12-29 21:17:44 +07:00
Finessse ea41ba8980 docs: update README with new auth providers
- Update provider count (8 -> 9)
- Add Amazon Q CLI and Antigravity providers
- Add new login command examples
- Document token import features
2025-12-29 19:01:25 +07:00
Finessse 75cf72720c feat(ui): update ProxyPilot desktop UI
- Update embedded UI assets
- Improve Windows-specific UI handling
2025-12-29 19:01:20 +07:00
Finessse 58035e8499 fix(webui): fix agent setup component
Minor fix in agent setup component
2025-12-29 19:01:11 +07:00
Finessse 15bd80da7c feat(webui): add new provider logins UI
Add UI buttons for MiniMax, Zhipu, Amazon Q, and Kiro import logins
2025-12-29 19:01:05 +07:00
Finessse 9777997886 feat(integrations): enhance Gemini integration
- Add Gemini CLI agent configuration support
- Improve settings file detection
2025-12-29 19:00:48 +07:00
Finessse d02a63311c feat(integrations): enhance Claude integration
- Add support for Claude Code agent configuration
- Improve config file detection and parsing
2025-12-29 19:00:45 +07:00
Finessse 5ab8b5adf3 refactor(integrations): enhance agents integration
Major overhaul of agent integration system:
- Add support for additional agent types
- Improve configuration detection and management
- Better error handling and validation
2025-12-29 19:00:40 +07:00
Finessse 1e48d75aa8 feat(api): register new management routes
Wire up auth files and agents v2 management endpoints
2025-12-29 19:00:30 +07:00
Finessse 233eb30219 feat(api): add agents v2 management endpoints
Add comprehensive management API for agent configuration
2025-12-29 19:00:28 +07:00
Finessse e372d2220b feat(api): add auth files management endpoints
Add management endpoints for listing and managing auth token files
2025-12-29 19:00:27 +07:00
Finessse 551c664564 feat(cmd): add provider login CLI flags to server
- Add --minimax-login, --zhipu-login for API key providers
- Add --amazonq-import for Amazon Q CLI token import
- Add --kiro-import for Kiro IDE token import
- Add --kiro-aws-login for AWS Builder ID flow
2025-12-29 19:00:17 +07:00
Finessse 21101c7a03 feat(cmd): update run command with new login flags
- Add --minimax-login and --zhipu-login flags
- Add --amazonq-import and --kiro-import flags
- Integrate new auth providers into startup flow
2025-12-29 18:59:37 +07:00
Finessse 5099678f17 feat(cmd): enhance agent setup workflow
- Add comprehensive agent configuration wizard
- Support for multiple agent types (Claude Code, Codex, Cursor, etc.)
- Auto-detect existing configurations
- Improved user prompts and validation
2025-12-29 18:59:25 +07:00
Finessse b1653fc6d0 feat(cmd): enhance agent detection
- Improve agent detection logic for multiple CLI tools
- Add support for detecting Amazon Q CLI, OpenCode
- Better path resolution and state management
2025-12-29 18:59:16 +07:00
Finessse d3aa7ece4e refactor(cmd): update Kiro login flow
- Reorganize login methods (Google OAuth, AWS Builder ID)
- Add Kiro token import from IDE config
- Improve error handling and user feedback
2025-12-29 18:59:02 +07:00
Finessse f2c51915f0 feat(cmd): add Zhipu AI API key login
Add --zhipu-login CLI flag to prompt for and save Zhipu AI API key
2025-12-29 18:58:38 +07:00
Finessse ecbe4424cb feat(cmd): add MiniMax API key login
Add --minimax-login CLI flag to prompt for and save MiniMax API key
2025-12-29 18:58:28 +07:00
Finessse cae634a64f feat(agents): add agent detection framework
- Add manager.go for centralized agent management
- Add state.go for agent state persistence
- Add detection for Claude Code, Codex, Cursor, OpenCode
- Add detection for Gemini CLI, Amazon Q CLI
- Add factory_droid.go for FactoryDroid integration
2025-12-29 18:57:56 +07:00
Finessse 42063d9f2a feat(auth): add Amazon Q CLI token import
- Add internal/auth/amazonq/token.go for token file parsing
- Add sdk/auth/amazonq.go for SDK-level Amazon Q auth
- Support importing tokens from Amazon Q CLI (~/.aws/q/)
2025-12-29 18:57:45 +07:00
Finessse 33eefe2ec3 deps: add go-toml and sqlite dependencies
- Add pelletier/go-toml/v2 for TOML parsing (Amazon Q config)
- Add modernc.org/sqlite for local state persistence
- Update indirect dependencies
2025-12-29 18:57:35 +07:00
Finessse 3ca0cccc75 chore: expand .gitignore patterns
- Add Windows artifacts (Thumbs.db, desktop.ini)
- Add local settings patterns (*.local.json/yaml/toml)
- Add backup/temp file patterns (*.bak, *.tmp, *.swp)
- Add test script patterns (*.ahk)
- Expand .mcp and .cursor ignore patterns
2025-12-29 18:57:10 +07:00
Finessse e590a2e7c7 fix(ci): fix Build Release and docker-image workflows
- Add bundle creation step before building custom installer
  (copies ProxyPilot.exe, config, icons to cmd/installer/bundle/)
- Make docker-image workflow conditional on DockerHub secrets
- Skip docker build when credentials aren't configured
2025-12-28 21:08:09 +07:00
Finessse a1ca0ddcb8 chore: bump version to 0.1.6 2025-12-28 20:55:46 +07:00
Finessse c6661972b1 chore: add build/ to .gitignore 2025-12-28 20:54:16 +07:00
Finessse e0756a566c chore(scripts): add build helper scripts
Add PowerShell scripts for installer builds:
- build-installer.ps1
- find-inno.ps1
- windows/build-custom-installer.ps1
2025-12-28 20:53:59 +07:00
Finessse 89bafc418c feat(installer): add Inno Setup branding assets
Add wizard images and generation script for Inno Setup installer.
2025-12-28 20:53:48 +07:00
Finessse ff0dea6cd6 feat(installer): add installer UI React application
Add React-based UI for the custom installer:
- Clean modern installation wizard interface
- Progress tracking and status display
- TypeScript + Vite build
2025-12-28 20:53:40 +07:00
Finessse cb4a7e0bbf feat(installer): add custom Go-based installer
Add custom installer application with embedded UI for ProxyPilot installation.
2025-12-28 20:53:31 +07:00
Finessse 310fd1f202 ci(release): add custom installer build to release workflow
- Build installer UI
- Copy UI files to cmd/installer
- Build custom installer executable
- Generate installer branding images
- Include custom installer in release artifacts
2025-12-28 20:53:13 +07:00
Finessse 2a8565467b feat(installer): enhance Inno Setup installer configuration
Improve installer with additional configuration options and paths.
2025-12-28 20:53:03 +07:00
Finessse 7d1b514a2e chore(ui): update proxypilotui assets 2025-12-28 20:52:54 +07:00
Finessse 7fdbb17d47 fix(embedded): improve embedded server initialization
Minor improvements to embedded server startup.
2025-12-28 20:52:42 +07:00
Finessse 4511e2a589 docs: add provider migration documentation
Document the migration from iFlow to MiniMax and Zhipu AI providers.

Includes:
- Summary of changes
- Files deleted/created/modified
- New model definitions
- API details for new providers
- Auth file format examples
- Migration notes for existing users
2025-12-28 20:52:14 +07:00
Finessse 60582b647e docs: update README for MiniMax and Zhipu AI providers
- Update provider count from 7 to 8
- Add MiniMax to supported providers table
- Add Zhipu AI to supported providers table
2025-12-28 20:51:30 +07:00
Finessse e663c9d395 feat(auth): add Zhipu AI authenticator
Add API key authenticator for Zhipu AI provider.

- Simple API key input (no OAuth required)
- Supports label for account identification
2025-12-28 20:51:19 +07:00
Finessse a20c4cefdc feat(executor): add Zhipu AI executor
Add OpenAI-compatible executor for Zhipu AI (GLM models).

- Base URL: https://open.bigmodel.cn/api/paas/v4/
- Auth: Bearer token (API key)
- Supports streaming and non-streaming requests
- Token usage tracking
2025-12-28 20:51:10 +07:00
Finessse efda335476 feat(auth): add MiniMax authenticator
Add API key authenticator for MiniMax provider.

- Simple API key input (no OAuth required)
- Supports label for account identification
2025-12-28 20:51:00 +07:00
Finessse 833a560ae1 feat(executor): add MiniMax executor
Add OpenAI-compatible executor for MiniMax API.

- Base URL: https://api.minimax.io/v1
- Auth: Bearer token (API key)
- Supports streaming and non-streaming requests
- Token usage tracking
2025-12-28 20:50:45 +07:00
Finessse 1a3c4ec586 docs: remove iFlow from configuration and documentation
- Remove iFlow example from config.example.yaml
- Remove iFlow from one-click login list in proxypilot.md
2025-12-28 20:50:34 +07:00
Finessse 50b453adc0 refactor(webui): remove iFlow from React components
- Remove iFlow from StatusBar provider list
- Remove iFlow from ProviderLogins provider list
- Remove iFlow auth detection logic
2025-12-28 20:50:15 +07:00
Finessse 7d70539d80 refactor(tray): remove iFlow from system tray app
Remove iFlow OAuth endpoint case from tray application.
2025-12-28 20:50:05 +07:00
Finessse 1878476f76 refactor(ui): remove iFlow from ProxyPilot UI
- Remove iFlow button from login panel
- Remove iFlow OAuth endpoint case
- Remove iFlow click handler
2025-12-28 20:49:54 +07:00
Finessse 9c19023a39 feat(registry): replace iFlow models with MiniMax/Zhipu
- Remove GetIFlowModels() function
- Add GetMiniMaxModels() with M2, M2.1, M2.1-Lightning
- Add GetZhipuModels() with GLM-4.5, 4.6, 4.7, 4-Long, 4.6V
2025-12-28 20:49:44 +07:00
Finessse 70f292a8c8 refactor(api): fix generic import after iFlow removal
- Remove iFlow import and case handler
- Add importResult type definition (was in deleted iflow_import.go)
2025-12-28 20:49:33 +07:00
Finessse 75a9908a3b refactor(api): remove iFlow from oauth sessions
Remove iFlow case from provider normalization switch.
2025-12-28 20:49:24 +07:00
Finessse f780519ee6 refactor(api): remove iFlow handlers from auth_files
- Remove iFlow auth import
- Remove RequestIFlowToken handler
- Remove RequestIFlowCookieToken handler
2025-12-28 20:49:15 +07:00
Finessse 7457183dd1 refactor(cli): remove iFlow login flags
Remove --iflow-login and --iflow-cookie CLI flags.
2025-12-28 20:49:04 +07:00
Finessse 8822013a74 refactor(api): remove iFlow routes from server
Remove iFlow OAuth callback and management API routes.
2025-12-28 20:48:54 +07:00
Finessse bc30977567 refactor(cmd): update auth manager for new providers
- Remove iFlow authenticator
- Add MiniMax authenticator
- Add Zhipu authenticator
2025-12-28 20:48:44 +07:00
Finessse 0fb4f42ffb refactor(sdk): remove iFlow from service, add MiniMax/Zhipu
- Remove iFlow executor and model retrieval cases
- Add MiniMax executor registration
- Add Zhipu executor registration
- Add MiniMax/Zhipu model retrieval cases
2025-12-28 20:48:35 +07:00
Finessse d8165d05d9 refactor(sdk): remove iFlow from refresh registry
Remove iFlow provider registration from refresh lead registry.
2025-12-28 20:48:15 +07:00
Finessse 0b448f7aa7 refactor(api): remove iFlow import handlers
Remove iFlow bulk import handler and tests.

Deleted files:
- internal/api/handlers/management/iflow_import.go
- internal/api/handlers/management/iflow_import_test.go
2025-12-28 20:48:02 +07:00
Finessse 91b13504f8 refactor(sdk): remove iFlow authenticator
Remove iFlow SDK authenticator implementation.

Deleted: sdk/auth/iflow.go
2025-12-28 20:47:50 +07:00
Finessse ffc608b7fe refactor(executor): remove iFlow executor
Remove the iFlow request executor implementation.

Deleted: internal/runtime/executor/iflow_executor.go
2025-12-28 20:47:36 +07:00
Finessse 9e1cd7a61d refactor(cmd): remove iFlow CLI commands
Remove iFlow login and cookie authentication CLI commands.

Deleted files:
- internal/cmd/iflow_cookie.go
- internal/cmd/iflow_login.go
2025-12-28 20:47:24 +07:00
Finessse 277e66c542 refactor(auth): remove iFlow auth package
Remove the iFlow OAuth and cookie-based authentication implementation.
This provider is being replaced with simpler API key-based providers.

Deleted files:
- internal/auth/iflow/cookie_helpers.go
- internal/auth/iflow/iflow_auth.go
- internal/auth/iflow/iflow_token.go
- internal/auth/iflow/oauth_server.go
2025-12-28 20:47:12 +07:00
Finessse 9a2363d6bd chore: bump version to 0.1.5
Includes:
- Vision base64 parsing fix for OpenAI-to-Claude translation
- Memory API localhost authentication with API keys
- Global model mapping SDK hook for cross-provider aliases
- Comprehensive unit tests for auth, config, memory, and runtime
2025-12-28 10:49:06 +07:00
Finessse 352095c54c test(runtime): add unit tests for model registry, executors, and pricing
Covers model registration, quota tracking, concurrent access,
Claude/Gemini executor request prep, and pricing calculations.
2025-12-28 10:46:38 +07:00
Finessse 009fbb2a37 test(memory): add unit tests for file store, pruning, and semantic search
Covers event serialization, file operations, token-based pruning,
recency preservation, and semantic similarity scoring.
2025-12-28 10:46:21 +07:00
Finessse 7d11a35a16 test(config): add unit tests for config loading and validation
Covers YAML parsing, port validation, key sanitization, header
normalization, global model mapping lookup, and legacy migration.
2025-12-28 10:46:03 +07:00
Finessse 9cdce5e8d8 test(auth): add unit tests for Claude PKCE/token and Codex JWT parsing
Covers PKCE verifier/challenge generation, token expiry detection,
refresh timing, and JWT claim extraction for Claude and Codex auth.
2025-12-28 10:45:45 +07:00
Finessse 7d9a114bf8 feat(config): add global model mapping hook for SDK handlers
Adds GlobalModelMapperFunc type and hook to SDKConfig, allowing
SDK-level handlers to access Config-level global model mappings.
This enables cross-provider model aliasing (e.g., gpt-4o → claude-sonnet).
2025-12-28 10:45:26 +07:00
Finessse 82f02c6d59 feat(management): allow API key auth for localhost management endpoints
Enables configured API keys to authenticate management API requests
from localhost, making it easier to use tools like curl for local testing.
2025-12-28 10:45:00 +07:00
Finessse 096daa30a7 fix(translator): correct base64 image parsing for OpenAI-to-Claude translation
Split on ";base64," instead of "," to properly extract media type and data
from data URLs. Also adds support for URL-based images (https://).
2025-12-28 10:44:35 +07:00
Finessse 5b11c113fb fix(ci): remove README_CN.md from goreleaser config 2025-12-28 08:38:37 +07:00
Finessse b127b674e9 sync: squash merge upstream CLIProxyAPI v6.6.62
Synced with upstream v6.6.61-v6.6.62 changes:
- Added usage export/import endpoints
- Added normalizeCodexKey function
- Updated BootstrapRetries type
- Enhanced model definitions and antigravity config

Preserved ProxyPilot customizations:
- Kept CompressionConfig for long-context sessions
- Kept Kiro, GitHub Copilot, Amazon Q model definitions
- Kept shouldKeepProviderOrder for Gemini-3 provider stability
- Kept advanceProviderCursor pattern (separate cursor advancement)
- Removed AmpCode integration (not used)

Version: 0.1.4
2025-12-28 08:32:11 +07:00
Finessse 6163489aca fix(ci): resolve release workflow failures
1. Add permissions: contents: write to release.yml to fix 403 error
2. Add before hook to remove .syso files that break ARM64 cross-compile
3. Skip Windows ARM64 build (not commonly used)
2025-12-28 07:32:40 +07:00
Finessse 0b12eafe6c chore: bump version to 0.1.3 2025-12-28 07:17:57 +07:00
Finessse e89a0f5fcb chore(scripts): add UI state initialization script
PowerShell script to create initial ui-state.json with default
settings in %LOCALAPPDATA%\ProxyPilot.
2025-12-28 07:12:43 +07:00
Finessse c7d06a3ace chore(scripts): add auth directory migration script
PowerShell script to migrate auth files from legacy ~/.cli-proxy-api
to new %LOCALAPPDATA%\ProxyPilot\auth location.
2025-12-28 07:12:33 +07:00
Finessse 81848357c4 feat: auto-register translators on startup
Import translator package with side effects to register all
built-in format translators at initialization.
2025-12-28 07:11:28 +07:00
Finessse 74319cd89e feat(embedded): register SDK providers and configure logging
Register token store and config providers at startup, apply default
auth-dir resolution, and configure log output from config.
2025-12-28 07:10:56 +07:00
Finessse 018cba3491 feat(dashboard): add logo route and improve auth key handling
Add /logo.png route for branding and prefer server instance password
over env var for management key injection.
2025-12-28 07:10:36 +07:00
Finessse a6da22f391 refactor(desktopctl): use util.ResolveAuthDir for path handling
Simplify auth directory resolution by delegating to the centralized
util package.
2025-12-28 07:10:17 +07:00
Finessse 8ae32d440a feat(util): add cross-platform default auth directory helper
Add DefaultAuthDir() that returns OS-appropriate auth directory path
following XDG spec on Linux and LOCALAPPDATA on Windows.
2025-12-28 07:10:01 +07:00
Finessse 26a17c7456 security(webui): remove hardcoded management key from template 2025-12-28 07:09:44 +07:00
Finessse d0c29cb584 feat(api): wire translator endpoints to router
Add translation API routes for matrix, check, docs, score, and
compare endpoints.
2025-12-28 07:09:11 +07:00
Finessse 0f5836e14b refactor(translator): enhance registry with new capabilities
Update registry to support middleware, caching, pooling, and
resilience features integration.
2025-12-28 07:09:01 +07:00
Finessse e96d568671 feat(api): add translator HTTP endpoints
Add REST API handlers for translation matrix, format checking,
documentation, quality scoring, and structure comparison.
2025-12-28 07:08:51 +07:00
Finessse 21125722cd test(translator): add lazy loading tests
Add tests for lazy translator registration and loading behavior.
2025-12-28 07:08:41 +07:00
Finessse 3e47344da9 feat(translator): add testing utilities
Add mock translators and test helpers for translator unit testing.
2025-12-28 07:08:31 +07:00
Finessse 31e52f26e8 feat(translator): add translation quality scoring
Add quality assessment for translations with structural comparison
and scoring metrics.
2025-12-28 07:08:21 +07:00
Finessse 3cf08319d4 feat(translator): add documentation generation
Add markdown docs, mermaid diagram, and summary generation for
registered translators.
2025-12-28 07:08:12 +07:00
Finessse b1a4bede65 feat(translator): add API helper functions
Add compatibility matrix, format listing, and translation info
query APIs for registry introspection.
2025-12-28 07:07:57 +07:00
Finessse 6cfd29ff1d feat(translator): add middleware pipeline support
Add pre/post translation middleware for payload transformation,
logging, and conditional processing.
2025-12-28 07:07:47 +07:00
Finessse 2874e52a2a feat(translator): add resilience and recovery strategies
Add translation recovery with direct hit, fallback chain, and
auto-detect strategies for robust format conversion.
2025-12-28 07:07:35 +07:00
Finessse 40c46acc08 feat(translator): add fallback chain support
Add multi-hop translation fallback chains for indirect format
conversions when direct translators are unavailable.
2025-12-28 07:07:24 +07:00
Finessse d8eb83c8fd feat(translator): add automatic format detection
Add payload format auto-detection for OpenAI, Claude, Gemini, and
Antigravity formats based on JSON structure analysis.
2025-12-28 07:07:14 +07:00
Finessse 5de9cfa8ea feat(translator): add translation benchmarking utilities
Add benchmark suite for measuring translation performance including
P50/P95/P99 latency percentiles and comparison tools.
2025-12-28 07:07:04 +07:00
Finessse 185dcc46dd feat(translator): add batch translation processing
Add batch processor for translating multiple payloads concurrently
with configurable worker count and progress callbacks.
2025-12-28 07:06:52 +07:00
Finessse 705039b410 feat(translator): add translator instance pooling
Add object pooling for translator instances to reduce allocation
overhead and improve concurrent translation performance.
2025-12-28 07:06:40 +07:00
Finessse 782e3f26a5 feat(translator): add translation result caching
Add LRU cache for translation results with configurable TTL and size.
Improves performance by avoiding redundant translations for identical
payloads.
2025-12-28 07:06:30 +07:00
Finessse 25e73af418 feat(translator): add request/response validation utilities
Add validation helpers for translator payloads including JSON schema
validation, required field checks, and format-specific validators.
2025-12-28 07:06:07 +07:00
Finessse ceec470273 refactor: consolidate tray app into single binary with embedded engine
This release removes the need for a separate proxypilot-engine.exe binary.
The ProxyPilot.exe tray app now runs the proxy service in-process using
the cliproxy SDK builder pattern.

Changes:
- Add internal/embedded package for in-process server management
- Update desktopctl to support embedded mode alongside subprocess mode
- Clean up vestigial -exe flag and engine binary references
- Update package scripts to build only single binary
- Bump version to 0.1.2

The embedded engine in cmd/cliproxytray was already implemented; this
commit cleans up the remaining references to the old two-binary architecture.
2025-12-28 04:25:45 +07:00
Finessse bbcf06f163 chore: bump version to 0.1.1
Prepare release v0.1.1 with new features:
- Model-specific pricing for cost estimation
- Auto-update with download, verify, and install flow
- Cost savings display in Analytics
- Logo branding assets
2025-12-28 03:42:33 +07:00
Finessse 00c64b3bcb build(assets): update compiled webui assets
Rebuild embedded webui assets with latest changes including
cost savings display, auto-update flow, and component updates.
2025-12-28 03:21:23 +07:00
Finessse 24467aa957 refactor(webui): update frontend components and configuration
Update Header with logo display, improve AgentSetup and ProviderLogins
components. Update App.tsx and index.html for better structure.
Adjust Vite config for development.
2025-12-28 03:21:04 +07:00
Finessse 68cf672e6b refactor(integrations): improve agent detection and configuration
Update CLI agent detection and configuration handling. Improve
integration handlers for better error handling and status reporting.
2025-12-28 03:20:46 +07:00
Finessse d9f67d1a8a chore(assets): add ProxyPilot logo
Add logo.png to webui public folder and desktop app assets
for consistent branding across web and desktop interfaces.
2025-12-28 03:20:28 +07:00
Finessse 7e8863b45b feat(webui): add full auto-update flow to Settings
Add complete update workflow with stages: checking, available, downloading,
ready, installing. Show download progress bar, version info, and release
notes. Add Install & Restart button for applying updates.
2025-12-28 03:20:10 +07:00
Finessse 2ccbba05e5 feat(webui): add cost savings display to Analytics
Add Cost Savings hero card showing proxy cost vs direct API cost with
visual comparison bars. Add Cost column to Model Breakdown table.
Display savings percentage and total amount saved.
2025-12-28 03:19:51 +07:00
Finessse 5c60aea115 feat(api): add update management endpoints
Add handlers for update status, download, verify, and install operations.
Register new routes: GET /updates/status, POST /updates/download,
POST /updates/verify, POST /updates/install. Track download progress
with background goroutine and mutex-protected state.
2025-12-28 03:19:34 +07:00
Finessse 0a5b2f1fc0 feat(updates): add cross-platform update installation
Add install.go with archive extraction (zip, tar.gz) and binary replacement
logic. Windows uses batch script for safe replacement of running executable.
Unix directly replaces binary with backup. Includes cleanup for old versions.
2025-12-28 03:19:13 +07:00
Finessse 8dd850241a feat(updates): add download and signature verification
Add DownloadUpdate function to download platform-specific binaries from
GitHub releases with progress tracking. Add verify.go with SHA256 checksum
verification for downloaded files. Fix GitHub repo URL and add 404 handling
for repositories without releases.
2025-12-28 03:18:55 +07:00
Finessse 3ee272620e feat(usage): add model-specific pricing for cost estimation
Add comprehensive pricing table for Claude, GPT, Gemini, Qwen, and DeepSeek
models with per-million-token rates. Update cost calculation to use actual
model pricing instead of hardcoded estimates. Add new cost fields to
UsageStats for tracking actual cost, direct API cost, and savings.
2025-12-28 03:18:35 +07:00
Finessse 6a1038871f docs: update build documentation and CI workflow
- Update desktop app build process docs
- Clean up release workflow
- Update installer configuration
2025-12-28 00:07:12 +07:00
Finessse 2c09998780 build(assets): update compiled webui assets 2025-12-28 00:06:53 +07:00
Finessse 9c91f3c511 feat(desktop): add WebView2 bindings for new features
- Add agent detection and configuration bindings
- Add update check and download bindings
- Add usage and request monitoring bindings
- Update useProxyContext with new desktop API hooks
2025-12-28 00:06:27 +07:00
Finessse 281ac2e0ba refactor(backend): improve API and internal services
- Add request logging middleware
- Update integrations handler
- Improve desktopctl with browser opening
- Add client model interfaces
- Enhance usage logger plugin
- Update SDK handlers
2025-12-28 00:06:07 +07:00
Finessse 2e7b68922a feat(engine): add engine management and config editor
- Add engine.go for proxy engine lifecycle management
- Add ConfigEditor component for runtime configuration
2025-12-28 00:05:35 +07:00
Finessse bb562e3d36 feat(updates): add auto-update check system
- Add updates package with GitHub releases check
- Add updates management endpoint
2025-12-28 00:05:15 +07:00
Finessse 3f8366de1a feat(usage): add usage statistics dashboard
- Update usage management endpoint
- Add UsageStats component for token/cost tracking
2025-12-28 00:04:50 +07:00
Finessse f4a2ac6962 feat(monitor): add request monitoring dashboard
- Add requests management endpoint
- Add RequestMonitor component for real-time request tracking
2025-12-28 00:04:28 +07:00
Finessse d014612bd6 refactor(dashboard): update components for Flight Deck styling
- Refactor EngineControl with new status indicators
- Update Integrations with provider cards
- Enhance LogsViewer with better filtering and display
- Improve MemoryManager with modern UI patterns
- Update ModelMappings with collapsible sections
- Refactor ProviderLogins with OAuth flow improvements
- Update SemanticMemory styling
2025-12-28 00:03:57 +07:00
Finessse f7b02ce207 feat(ui): Flight Deck dashboard redesign
- Add icon rail navigation with collapsible panels
- Add Header component with engine status and controls
- Add StatusBar component with real-time metrics
- Add SettingsPanel for configuration management
- Add new UI components: icon-rail, provider-card, status-indicator
- Update badge, button, card components with Flight Deck styling
- Add CSS custom properties for consistent theming
- Remove react-grab.css (unused)
2025-12-28 00:03:34 +07:00
Finessse 9e2f45fcf5 feat(agents): add CLI agent detection with auto-configure/reset
- Add DetectCLIAgents for Claude Code, Codex CLI, Aider, Gemini CLI, Droid CLI
- Add ConfigureCLIAgent to auto-configure agents via shell profile or config files
- Add UnconfigureCLIAgent to reset/remove ProxyPilot configuration
- Add AgentSetup component with Configure/Reset buttons
- Shell profile agents show "restart shell" message, config file agents don't
2025-12-28 00:02:58 +07:00
Finessse 95eb896831 docs: add desktop app build process documentation 2025-12-27 07:16:21 +07:00
Finessse 660c0f7656 fix: use multi-resolution icon (16-256px) for proper Windows display 2025-12-27 07:13:13 +07:00
Finessse aca1f54478 fix: use CopyFile instead of deprecated FileCopy in installer 2025-12-27 07:05:51 +07:00
Finessse c10abab37c feat: embed ProxyPilot logo in all executables
- Add versioninfo.json for goversioninfo in tray and server
- Generate resource.syso files with embedded icon
- Update ico.go to embed actual icon.ico for tray
- All exes now show ProxyPilot logo in File Explorer
2025-12-27 07:05:13 +07:00
FinessseandClaude Opus 4.5 d71582d7d8 refactor(tray): simplify system tray to minimal menu
Before (nested submenus):
- Status
- Open Dashboard
- Engine → Start, Stop, Restart
- Connect → Copy ANTHROPIC_BASE_URL, Copy OPENAI_BASE_URL
- Settings → Launch on login, Auto-start proxy
- Tools → Open Logs, Copy Diagnostics, Advanced UI
- Updates → Check for Updates, Update ProxyPilot
- Quit

After (flat, minimal):
- Open Dashboard
- Start/Stop (toggle)
- Copy API URL
- Quit

Advanced settings moved to dashboard UI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:41:05 +07:00
Finessse f3bc99cc35 fix: add ProxyPilot logo to installer and shortcuts 2025-12-27 06:35:48 +07:00
FinessseandClaude Opus 4.5 923f3f68b7 ci: add release workflow with Inno Setup installer
- Add GitHub Actions workflow to build releases
- Update Inno Setup script for new binary structure
- Builds single-file installer (11MB) containing:
  - ProxyPilot.exe (tray + dashboard)
  - proxypilot-engine.exe (proxy server)
  - config.example.yaml

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:25:31 +07:00
FinessseandClaude Opus 4.5 0e03289627 feat(tray): embed WebView2 dashboard directly in tray app
- Embed React dashboard assets in tray binary
- Open dashboard in WebView2 window from tray
- Remove need for separate proxypilotui.exe
- Simplifies distribution to just ProxyPilot.exe + proxypilot-engine.exe

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:17:21 +07:00
FinessseandClaude Opus 4.5 7631297204 feat(webui): refactor dashboard with tabbed navigation and theme toggle
- Add 5-tab navigation: Engine, Auth, Routing, Memory, Logs
- Add dark/light/system theme toggle with persistence
- Extract 7 modular dashboard components:
  - EngineControl: proxy start/stop/restart controls
  - ProviderLogins: OAuth buttons for 6 AI providers
  - Integrations: CLI agent detection and configuration
  - ModelMappings: global model mapping CRUD
  - MemoryManager: session memory management
  - SemanticMemory: Ollama embeddings and namespaces
  - LogsViewer: diagnostics and log viewing
- Add centralized state management with ProxyProvider context
- Reduce App.tsx from 1,734 lines to 351 lines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:03:16 +07:00
FinessseandClaude Opus 4.5 3e3d0bf933 chore: restore logo to README
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 04:09:10 +07:00
FinessseandClaude Opus 4.5 c6d8e6abb1 chore: gitignore static and test folders
- Remove logo and test files from tracking
- Keep files locally but exclude from repo

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 04:00:38 +07:00
FinessseandClaude Opus 4.5 9fb39ff966 docs: fix Factory.ai and Anthropic research links
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:51:15 +07:00
FinessseandClaude Opus 4.5 e08235b4d1 docs: add CLIProxyAPI and VibeProxy to credits
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:50:09 +07:00
FinessseandClaude Opus 4.5 7a5fd20272 docs: add credits section for research inspirations
Credits Factory.ai and Anthropic for their research on context
compression and building effective agents.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:49:06 +07:00
FinessseandClaude Opus 4.5 b37551edd8 docs: update to GPT-5.2 models
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:46:18 +07:00
FinessseandClaude Opus 4.5 39c7c6760a docs: add 4.5 to Haiku model name
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:44:08 +07:00
FinessseandClaude Opus 4.5 7e13a0dfdd docs: update Gemini models to 3 Pro/Flash
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:42:34 +07:00
FinessseandClaude Opus 4.5 9394166777 docs: restyle README in VibeProxy format
- Cleaner centered branding with star badge
- Bold tagline with concise value prop
- GitHub tip callout for latest models
- Emoji bullet feature list
- Simplified sections
- Setup guide links

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:39:47 +07:00
FinessseandClaude Opus 4.5 a6ea590cce docs: add missing features to README
Added:
- Tool Calling Repair
- Extended Thinking support
- Quota Auto-Switch
- Usage Statistics
- 4 CLI Tools table
- Tool Integrations section (Droid, Cursor, Continue)
- Factory Droid configuration example

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:37:13 +07:00
FinessseandClaude Opus 4.5 7329675592 docs: update README with comprehensive feature list
- Added 7 auth providers, long-context features, desktop app details
- Added supported providers table with auth methods
- Simplified installation and quick start sections
- Added tool configuration examples (Claude Code, Codex CLI)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:29:38 +07:00
FinessseandClaude Opus 4.5 cab21a5089 refactor(auth): remove commented-out ErrTokenExpired
Removed dead code (commented-out ErrTokenExpired error constant) from
both claude/errors.go and codex/errors.go.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:01:27 +07:00
FinessseandClaude Opus 4.5 c4701abb00 refactor(misc): remove duplicate embed import
Removed redundant `_ "embed"` import as `embed` is already imported
and used for embed.FS.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:50:14 +07:00
FinessseandClaude Opus 4.5 7b3ef0ea43 refactor(errors): remove unused error constructors
Removed 5 unused helper functions: BadRequest(), Unauthorized(),
Forbidden(), NotFound(), InternalServerError(). Also removed the
now-unused net/http import.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:50:05 +07:00
FinessseandClaude Opus 4.5 5a9c652f48 docs: remove stale UI spec documentation
Remove desktop-ui-spec.md and windows-ui-spec.md which reference
deleted cliproxyctl CLI that no longer exists.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:35:13 +07:00
FinessseandClaude Opus 4.5 715c71830e refactor(auth): remove unused ProjectSelectionError type
Type was defined but never used anywhere in codebase.
Keep EmailRequiredError which is actively used.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:35:02 +07:00
FinessseandClaude Opus 4.5 aab8294d96 refactor(misc): remove commented dead code in codex_instructions.go
Remove unused lastReviewPrompt variable and associated dead code block.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:34:53 +07:00
FinessseandClaude Opus 4.5 59e947e8a8 chore: add long-context-features.md to gitignore exceptions
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:14:04 +07:00
FinessseandClaude Opus 4.5 2617902571 docs: add long-context features documentation
Document Factory.ai context compression and Anthropic agentic harness
implementations with architecture diagrams and configuration reference.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:55 +07:00
FinessseandClaude Opus 4.5 270a176925 test(api): add integration tests for long-context features
Test context compression adapter and harness middleware work together
without conflicts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:47 +07:00
FinessseandClaude Opus 4.5 f4e7d5b92e test(middleware): add session storage test for agentic harness
Add E2E test for session-based harness file detection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:39 +07:00
FinessseandClaude Opus 4.5 eb84cbe543 refactor(middleware): remove Puppeteer MCP detection from harness
Removed feature not present in original Factory.ai or Anthropic sources.
Keep implementation pure to research references.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:31 +07:00
FinessseandClaude Opus 4.5 e71648f4b6 feat(api): register AgenticHarnessMiddleware in server routes
Enable Anthropic-style INITIALIZER/CODING mode prompts for long-running
agentic clients.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:20 +07:00
FinessseandClaude Opus 4.5 1b5bd183b9 feat(cliproxy): wire up context compression in service startup
Add coreManagerWrapper to adapt auth manager types and initialize
LLM-based summarization after server creation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:09 +07:00
FinessseandClaude Opus 4.5 095718e31e feat(middleware): add InitSummarizerWithAuthManager for compression setup
Enables Factory.ai-style LLM summarization by wiring the summarizer
executor to the core auth manager.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:46 +07:00
FinessseandClaude Opus 4.5 abe7597d99 test(memory): add unit tests for ManagerAuthAdapter
12 tests covering adapter behavior, pipeline execution, and edge cases.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:37 +07:00
FinessseandClaude Opus 4.5 01cd7942b5 feat(memory): add CoreManagerExecutor interface and ManagerAuthAdapter
Bridge type differences between coreauth.Manager and memory.AuthExecutor
to enable LLM-based context compression through the auth pipeline.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:29 +07:00
FinessseandClaude Opus 4.5 b669cfa650 docs(readme): remove GitHub stars badge, keep X follow
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:23:31 +07:00
FinessseandClaude Opus 4.5 c53fabd3a8 fix(readme): correct X profile link
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:21:50 +07:00
FinessseandClaude Opus 4.5 4ceed0428b docs(readme): add X/Twitter follow badge
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:20:44 +07:00
FinessseandClaude Opus 4.5 462856639c fix: use transparent logo (remove white background)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:19:36 +07:00
FinessseandClaude Opus 4.5 b75ef23d5c fix(readme): use relative path for logo
Works for both public and private repos

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:17:52 +07:00
FinessseandClaude Opus 4.5 8e236dd69d feat: add ProxyPilot logo
- Add icon.png for README header
- Update .gitignore to track the logo

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:16:00 +07:00
FinessseandClaude Opus 4.5 20146a1f7d fix(license): update copyright holders
- Fix malformed date "2025.9-present"
- Add Finesssee as ProxyPilot fork maintainer

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:08:17 +07:00
FinessseandClaude Opus 4.5 b5b6d65e79 docs(readme): redesign with vibeproxy-style formatting
- Centered logo and badges
- Catchy tagline "Stop juggling API keys"
- Emoji-styled feature list
- Latest models callout section
- Cleaner installation/usage sections

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:02:52 +07:00
FinessseandClaude Opus 4.5 12aa47b91c refactor(proxypilotui): modernize asset embedding
- Replace inline HTML/CSS/JS with Vite-bundled React app
- Embed compiled assets from webui build
- Simplify index.html to load external JS/CSS

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:59 +07:00
FinessseandClaude Opus 4.5 5ce65eed85 refactor(webui): improve App.tsx code quality
- Add downloadBlob helper to reduce duplication
- Refactor export functions to use helper
- Fix model mapping edit to use controlled React state
  instead of DOM getElementById manipulation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:50 +07:00
FinessseandClaude Opus 4.5 e75e5716e9 refactor(webui): remove debug console.log
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:41 +07:00
FinessseandClaude Opus 4.5 d519feeba1 refactor(webui): cleanup unused component exports
- badge.tsx: remove unused badgeVariants export
- button.tsx: remove unused buttonVariants export
- card.tsx: remove unused CardAction, CardFooter components

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:33 +07:00
FinessseandClaude Opus 4.5 f1f8e2c1a6 refactor(webui): remove unused UI components
Delete input.tsx, progress.tsx, tabs.tsx - none were imported
or used anywhere in the codebase.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:23 +07:00
FinessseandClaude Opus 4.5 bd893efee9 docs: add SECURITY.md
Vulnerability reporting policy with:
- Supported versions
- Reporting methods (GitHub advisory, email)
- Response timeline expectations
- Responsible disclosure guidelines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:12 +07:00
FinessseandClaude Opus 4.5 18757ebe7c docs: add CONTRIBUTING.md
Guidelines for:
- Development environment setup
- Running tests
- Code style (go fmt, go vet)
- Pull request process
- Issue reporting
- Third-party provider integrations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:03 +07:00
FinessseandClaude Opus 4.5 09e96a45ca docs(readme): rebrand to ProxyPilot
Complete rewrite with:
- ProxyPilot branding and badges
- Feature list and architecture overview
- Quick start and configuration guide
- API endpoints documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:52:54 +07:00
FinessseandClaude Opus 4.5 8e729276b0 fix(license): correct copyright date typo
Changed "2025-2005.9" to "2024-2025"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:52:45 +07:00
FinessseandClaude Opus 4.5 1a1c85f043 chore: cleanup and remove Letta integration
- Remove internal/letta/ package (unused memory bridge)
- Remove Letta references from run.go and start-cliproxy.ps1
- Move docker-build scripts to scripts/
- Move TROUBLESHOOTING_ANTIGRAVITY.md and WARP.md to docs/

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 07:13:19 +07:00
FinessseandClaude Opus 4.5 9e187cd08f feat(droid): fix Droid CLI integration to use settings.json
- Update droid.go to use ~/.factory/settings.json (runtime config)
- Add /healthz endpoint for Droid health checks
- Add root-level API routes (/responses, /messages, etc.)
- Fix detection in proxypilotui to check settings.json
- Use thinking models with provider: "openai" for Responses API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 06:52:08 +07:00
FinessseandClaude Opus 4.5 a8c389ffa6 ci: add upstream sync check workflow
Add GitHub Actions workflow to check for upstream
repository updates.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:11:17 +07:00
FinessseandClaude Opus 4.5 999529c154 fix(webui): minor App.tsx updates
Minor updates to web UI App component.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:11:05 +07:00
FinessseandClaude Opus 4.5 355932e138 docs(memory): update memory system documentation
Update docs to reflect token-aware compression
and LLM summarization features.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:54 +07:00
FinessseandClaude Opus 4.5 d3466b31af fix(sdk): update stream forwarder for compression
Update stream forwarder to work with token-aware
compression middleware.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:43 +07:00
FinessseandClaude Opus 4.5 f19594e490 fix(sdk): update handlers for compression support
Update SDK handlers to integrate with token-aware
compression middleware.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:33 +07:00
FinessseandClaude Opus 4.5 946cc75e71 feat(ui): add agent detection and model mapping bindings
Add WebView2 JavaScript bindings:
- pp_detect_agents: List installed CLI agents
- pp_configure_agent: Configure agent for ProxyPilot
- pp_get_model_mappings: Get global mappings
- pp_save_model_mappings: Save global mappings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:21 +07:00
FinessseandClaude Opus 4.5 93c0b8703c chore(ui): remove React bundle, simplify embed
Remove bloated React bundle (~500KB) in favor of
simple embedded HTML (~15KB). Update embed.go to
only include index.html and vite.svg.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:10 +07:00
FinessseandClaude Opus 4.5 0dda5a01a2 refactor(ui): redesign desktop UI with ProxyPal style
Complete rewrite with ProxyPal-inspired design:
- KPI tiles (Saved, Requests, Tokens, Success)
- Provider grid with OAuth buttons
- CLI Agents section with status indicators
- Model Mappings editor
- Dark/light theme toggle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:59 +07:00
FinessseandClaude Opus 4.5 572792f2c6 feat(cmd): add --detect-agents and --setup-* flags
Add CLI flags for agent detection and configuration:
- --detect-agents: List installed CLI agents
- --setup-claude: Configure Claude Code
- --setup-codex: Configure Codex CLI
- --setup-droid: Configure Factory Droid

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:45 +07:00
FinessseandClaude Opus 4.5 12ac05a22f feat(cmd): add CLI agent auto-configuration
Generate config files to point CLI agents at ProxyPilot:
- Claude Code: ~/.claude/settings.json
- Codex CLI: ~/.codex/config.toml
- Factory Droid: ~/.factory/config.json

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:34 +07:00
FinessseandClaude Opus 4.5 af37fbf2e0 feat(cmd): add CLI agent detection
Detect installed CLI agents (Claude Code, Codex, Droid, Gemini)
by checking binaries and config files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:23 +07:00
FinessseandClaude Opus 4.5 f52bc59b2e docs(config): add model mappings example
Add global-model-mappings section to config.example.yaml
showing smart/rush/think aliases.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:11 +07:00
FinessseandClaude Opus 4.5 5cf7518f26 feat(api): add model mappings management handler
Add API handler for managing global model mappings
stored in ~/.proxypilot/model-mappings.json.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:00 +07:00
FinessseandClaude Opus 4.5 6767188a8e feat(config): add global model mappings support
Add GlobalModelMapping struct and LookupGlobalModelMapping()
for routing friendly model names to actual models.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:49 +07:00
FinessseandClaude Opus 4.5 7cbbf954d6 feat(api): register harness management routes
Add route registration for harness and model mappings
management endpoints.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:36 +07:00
FinessseandClaude Opus 4.5 6e8f055816 feat(api): add harness management API endpoints
Add CRUD operations for harness files:
- GET /v0/management/harness/files - list files
- GET /v0/management/harness/file - read file
- PUT /v0/management/harness/file - write file
- GET /v0/management/harness/export - export all
- POST /v0/management/harness/import - import files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:26 +07:00
FinessseandClaude Opus 4.5 87dbbedd4b feat(middleware): enhance agentic harness prompts
Improve INITIALIZER and CODING prompts based on Anthropic guidance:
- Structured feature_list.json format
- GET BEARINGS workflow for coding mode
- Puppeteer MCP detection for browser testing
- Session-aware state detection

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:15 +07:00
FinessseandClaude Opus 4.5 a84e59f31c feat(config): add CompressionConfig struct
Add configuration options for token-aware compression:
- Token threshold percentage
- Reserved output tokens
- LLM summary enable/disable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:01 +07:00
FinessseandClaude Opus 4.5 ca06786892 feat(executor): add token counting helper functions
Add utilities for estimating token counts using tiktoken
to support token-aware compression decisions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:52 +07:00
FinessseandClaude Opus 4.5 25dd8b2087 feat(middleware): add token-aware context compression
Implement proactive compression based on token count rather than bytes:
- Uses tiktoken for accurate token estimation
- Compresses at 75% threshold before hitting limits
- Reserves tokens for output generation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:42 +07:00
FinessseandClaude Opus 4.5 57d5b4b1b1 feat(memory): add anchored summary with LLM support
Update file_store.go with BuildAnchoredSummaryWithLLM() for
generating context-aware summaries during compression.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:32 +07:00
FinessseandClaude Opus 4.5 f80e1bb068 feat(memory): add LLM-based structured summarization
Add structured summary generation for context compression:
- structured_summary.go: Types and parsing for summaries
- summarizer.go: LLM summarization logic
- summarizer_executor.go: Routes to LLM pipeline

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:22 +07:00
RCD d68f32f00e Merge pull request #2 from Finesssee/sync-cliproxiapiplus
feat: sync with CLIProxyAPIPlus
2025-12-26 02:13:50 +07:00
382 changed files with 67119 additions and 14052 deletions
+5 -3
View File
@@ -13,8 +13,6 @@ Dockerfile
docs/*
README.md
README_CN.md
MANAGEMENT_API.md
MANAGEMENT_API_CN.md
LICENSE
# Runtime data folders (should be mounted as volumes)
@@ -25,10 +23,14 @@ config.yaml
# Development/editor
bin/*
.claude/*
.vscode/*
.claude/*
.codex/*
.gemini/*
.serena/*
.agent/*
.agents/*
.opencode/*
.bmad/*
_bmad/*
_bmad-output/*
+7
View File
@@ -7,6 +7,13 @@ assignees: ''
---
**Is it a request payload issue?**
[ ] Yes, this is a request payload issue. I am using a client/cURL to send a request payload, but I received an unexpected error.
[ ] No, it's another issue.
**If it's a request payload issue, you MUST know**
Our team doesn't have any GODs or ORACLEs or MIND READERs. Please make sure to attach the request log or curl payload.
**Describe the bug**
A clear and concise description of what the bug is.
+156
View File
@@ -0,0 +1,156 @@
name: check-upstream
on:
schedule:
# Run daily at 08:00 UTC (like vibeproxy)
- cron: '0 8 * * *'
workflow_dispatch: # Allow manual trigger
concurrency:
group: check-upstream
cancel-in-progress: true
permissions:
contents: write
pull-requests: write
jobs:
check-update:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get current version
id: current
run: |
# Extract current CLIProxyAPI version from go.mod or a version file
# For now, we'll check the latest commit from upstream
CURRENT_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git HEAD | cut -f1)
echo "sha=$CURRENT_SHA" >> $GITHUB_OUTPUT
- name: Get upstream release info
id: upstream
run: |
# Fetch latest release from CLIProxyAPI
RELEASE_INFO=$(curl -s https://api.github.com/repos/router-for-me/CLIProxyAPI/releases/latest)
# Extract tag name and version
TAG_NAME=$(echo "$RELEASE_INFO" | jq -r '.tag_name // empty')
if [ -z "$TAG_NAME" ]; then
echo "No release found, checking latest commit instead"
LATEST_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git HEAD | cut -f1)
echo "tag=" >> $GITHUB_OUTPUT
echo "sha=$LATEST_SHA" >> $GITHUB_OUTPUT
else
echo "Found release: $TAG_NAME"
echo "tag=$TAG_NAME" >> $GITHUB_OUTPUT
# Get the commit SHA for this tag
TAG_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git "refs/tags/$TAG_NAME" | cut -f1)
echo "sha=$TAG_SHA" >> $GITHUB_OUTPUT
fi
- name: Check for updates
id: check
run: |
echo "Current SHA: ${{ steps.current.outputs.sha }}"
echo "Upstream SHA: ${{ steps.upstream.outputs.sha }}"
echo "Upstream Tag: ${{ steps.upstream.outputs.tag }}"
if [ "${{ steps.current.outputs.sha }}" != "${{ steps.upstream.outputs.sha }}" ]; then
echo "Update available!"
echo "has_update=true" >> $GITHUB_OUTPUT
else
echo "Already up to date"
echo "has_update=false" >> $GITHUB_OUTPUT
fi
- name: Create sync branch and PR
if: steps.check.outputs.has_update == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
TAG="${{ steps.upstream.outputs.tag }}"
SHA="${{ steps.upstream.outputs.sha }}"
SHORT_SHA="${SHA:0:7}"
if [ -n "$TAG" ]; then
BRANCH_NAME="sync-upstream-$TAG"
PR_TITLE="feat: sync with CLIProxyAPI $TAG"
PR_BODY="## Summary
This PR syncs ProxyPilot with upstream CLIProxyAPI release \`$TAG\`.
**Upstream release:** https://github.com/router-for-me/CLIProxyAPI/releases/tag/$TAG
## Changes
- Updated to CLIProxyAPI $TAG ($SHORT_SHA)
## Checklist
- [ ] Review upstream changes
- [ ] Test locally before merging
- [ ] Update changelog if needed
---
🤖 Generated by [check-upstream workflow](https://github.com/${{ github.repository }}/actions/workflows/check-upstream.yml)"
else
BRANCH_NAME="sync-upstream-$SHORT_SHA"
PR_TITLE="feat: sync with CLIProxyAPI ($SHORT_SHA)"
PR_BODY="## Summary
This PR syncs ProxyPilot with latest upstream CLIProxyAPI commit.
**Upstream commit:** https://github.com/router-for-me/CLIProxyAPI/commit/$SHA
## Checklist
- [ ] Review upstream changes
- [ ] Test locally before merging
---
🤖 Generated by [check-upstream workflow](https://github.com/${{ github.repository }}/actions/workflows/check-upstream.yml)"
fi
# Check if branch already exists
if git ls-remote --exit-code --heads origin "$BRANCH_NAME" > /dev/null 2>&1; then
echo "Branch $BRANCH_NAME already exists, skipping"
exit 0
fi
# Check if PR already exists
EXISTING_PR=$(gh pr list --search "$PR_TITLE" --state open --json number --jq '.[0].number')
if [ -n "$EXISTING_PR" ]; then
echo "PR already exists: #$EXISTING_PR"
exit 0
fi
# Configure git
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
# Create branch
git checkout -b "$BRANCH_NAME"
# Add a marker file to track the sync (optional, can be removed)
echo "$SHA" > .upstream-sync-sha
echo "$TAG" > .upstream-sync-tag 2>/dev/null || true
# Commit
git add -A
git commit -m "$PR_TITLE" --allow-empty
# Push
git push origin "$BRANCH_NAME"
# Create PR
gh pr create \
--title "$PR_TITLE" \
--body "$PR_BODY" \
--base main \
--head "$BRANCH_NAME" \
--label "sync-upstream"
+20 -2
View File
@@ -6,30 +6,48 @@ on:
- v*
env:
APP_NAME: CLIProxyAPI
DOCKERHUB_REPO: eceasy/cli-proxy-api-plus
APP_NAME: ProxyPilot
DOCKERHUB_REPO: ${{ secrets.DOCKERHUB_REPO || 'proxypilot/proxypilot' }}
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Check DockerHub credentials
id: check-secrets
env:
HAS_USERNAME: ${{ secrets.DOCKERHUB_USERNAME != '' }}
HAS_TOKEN: ${{ secrets.DOCKERHUB_TOKEN != '' }}
run: |
if [[ "$HAS_USERNAME" != "true" || "$HAS_TOKEN" != "true" ]]; then
echo "skip=true" >> $GITHUB_OUTPUT
echo "::warning::DockerHub credentials not configured, skipping push"
else
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Checkout
if: steps.check-secrets.outputs.skip != 'true'
uses: actions/checkout@v4
- name: Set up QEMU
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Generate Build Metadata
if: steps.check-secrets.outputs.skip != 'true'
run: |
echo VERSION=`git describe --tags --always --dirty` >> $GITHUB_ENV
echo COMMIT=`git rev-parse --short HEAD` >> $GITHUB_ENV
echo BUILD_DATE=`date -u +%Y-%m-%dT%H:%M:%SZ` >> $GITHUB_ENV
- name: Build and push
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/build-push-action@v6
with:
context: .
+31
View File
@@ -0,0 +1,31 @@
name: Publish ProxyPilot via Bun
on:
workflow_run:
workflows: ["ProxyPilot Release"]
types:
- completed
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Setup registry auth
working-directory: bun/proxypilot
run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
- name: Publish package
working-directory: bun/proxypilot
run: bun publish --access public
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+84
View File
@@ -0,0 +1,84 @@
name: ProxyPilot Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
build:
name: Build ${{ matrix.os }}-${{ matrix.arch }}
runs-on: ubuntu-latest
strategy:
matrix:
include:
- os: darwin
arch: amd64
extension: ''
- os: darwin
arch: arm64
extension: ''
- os: linux
arch: amd64
extension: ''
- os: linux
arch: arm64
extension: ''
- os: windows
arch: amd64
extension: '.exe'
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Remove Windows resources for non-Windows builds
if: matrix.os != 'windows'
run: rm -f cmd/server/*.syso
- name: Build binary
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
CGO_ENABLED: 0
run: |
go build -ldflags="-s -w" -o proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }} ./cmd/server
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: proxypilot-${{ matrix.os }}-${{ matrix.arch }}
path: proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }}
release:
name: Create Release
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Prepare release assets
run: |
mkdir -p release
find artifacts -type f -exec cp {} release/ \;
ls -la release/
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: release/*
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+115
View File
@@ -0,0 +1,115 @@
name: Build Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
version:
description: 'Version (e.g., 0.1.0)'
required: true
default: '0.1.0'
permissions:
contents: write
jobs:
build-windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Build WebUI
run: |
cd webui
npm ci
npm run build
- name: Build Windows binaries
run: |
mkdir -p dist
# Build tray app (includes embedded dashboard)
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot.exe ./cmd/cliproxytray
- name: Build Installer UI
run: |
cd installer-ui
npm ci
npm run build
- name: Copy Installer UI to cmd/installer
run: |
# Ensure target directory exists
New-Item -ItemType Directory -Force -Path cmd/installer/ui | Out-Null
# Copy built UI files
Copy-Item -Path installer-ui/dist/* -Destination cmd/installer/ui/ -Recurse -Force
shell: pwsh
- name: Create bundle for installer
run: |
# Create bundle directory
New-Item -ItemType Directory -Force -Path cmd/installer/bundle | Out-Null
# Copy files for embedding
Copy-Item -Path dist/ProxyPilot.exe -Destination cmd/installer/bundle/
Copy-Item -Path config.example.yaml -Destination cmd/installer/bundle/
Copy-Item -Path static/icon.ico -Destination cmd/installer/bundle/
Copy-Item -Path static/icon.png -Destination cmd/installer/bundle/
shell: pwsh
- name: Build Custom Installer
run: |
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot-Installer.exe ./cmd/installer
- name: Install Inno Setup
run: |
choco install innosetup -y
- name: Generate installer branding images
run: |
cd installer/assets
powershell -ExecutionPolicy Bypass -File generate-wizard-images.ps1
- name: Get version
id: version
run: |
if ("${{ github.event.inputs.version }}" -ne "") {
echo "VERSION=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
} else {
$tag = "${{ github.ref_name }}"
$version = $tag -replace '^v', ''
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
}
- name: Build Inno Setup Installer
run: |
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" installer\proxypilot.iss
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: windows-release
path: |
dist/ProxyPilot.exe
dist/ProxyPilot-Installer.exe
dist/ProxyPilot-*-Setup.exe
- name: Upload to Release
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v1
with:
files: |
dist/ProxyPilot.exe
dist/ProxyPilot-Installer.exe
dist/ProxyPilot-${{ steps.version.outputs.VERSION }}-Setup.exe
config.example.yaml
+61 -9
View File
@@ -1,6 +1,9 @@
# Binaries
cli-proxy-api
cliproxy
proxypilot-linux
proxypilot-darwin
proxypilot-windows
*.exe
# Configuration
@@ -12,10 +15,18 @@ bin/*
logs/*
conv/*
temp/*
refs/*
# Storage backends
pgstore/*
gitstore/*
objectstore/*
# Static assets
static/*
!static/icon.png
!static/icon.ico
test/
refs/*
dist/*
.proxypilot/*
@@ -36,6 +47,9 @@ docs/*
!docs/memory.md
!docs/proxypilot.md
!docs/agentic-harness-demo.md
!docs/long-context-features.md
!docs/desktop-app-build-process.md
!docs/cli.md
AGENTS.md
CLAUDE.md
GEMINI.md
@@ -43,23 +57,61 @@ GEMINI.md
# Tooling metadata
.vscode/*
.claude/*
.codex/*
.gemini/*
.serena/*
.agent/*
.agents/*
.opencode/*
.bmad/*
_bmad/*
.mcp/cache/
_bmad-output/*
.mcp/*
.cursor/*
# Local artifacts
claude-progress.txt
feature_list.json
tui-snapshot*.txt
tui-ttyd.png
# Local settings (user-specific)
*.local.json
*.local.yaml
*.local.toml
# macOS
.DS_Store
._*
# Windows artifacts
nul
Thumbs.db
desktop.ini
# Backup/temp files
*~
*.bak
*.tmp
*.swp
*.orig
*.proxypilot-backup
# Test scripts
*.ahk
tray_click_log.txt
# Logs
*.log
*_out.txt
# Added by Gemini CLI fix
node_modules/
dist/
.turbo/
.env
*_out.txt
# Added by Gemini CLI fix
node_modules/
dist/
.turbo/
.env
build/
# Local files
PLAN-*.md
config-debug.yaml
+10 -1
View File
@@ -1,3 +1,9 @@
before:
hooks:
# Remove Windows resource files before building
# These .syso files cause ARM64 cross-compile failures on Linux/Darwin
- find . -name "*.syso" -type f -delete || true
builds:
- id: "cli-proxy-api-plus"
env:
@@ -9,6 +15,10 @@ builds:
goarch:
- amd64
- arm64
ignore:
# Skip Windows ARM64 (not commonly used)
- goos: windows
goarch: arm64
main: ./cmd/server/
binary: cli-proxy-api-plus
ldflags:
@@ -22,7 +32,6 @@ archives:
files:
- LICENSE
- README.md
- README_CN.md
- config.example.yaml
checksum:
+89
View File
@@ -0,0 +1,89 @@
# Contributing to ProxyPilot
Thank you for your interest in contributing to ProxyPilot! This guide will help you get started.
## Development Environment Setup
1. **Install Go 1.24+**
- Download from [golang.org](https://golang.org/dl/)
- Verify installation: `go version`
2. **Clone the repository**
```bash
git clone https://github.com/your-org/ProxyPilot.git
cd ProxyPilot
```
3. **Install dependencies**
```bash
go mod download
```
## Running Tests
Run all tests:
```bash
go test ./...
```
Run tests with coverage:
```bash
go test -cover ./...
```
Run tests for a specific package:
```bash
go test ./pkg/proxy/...
```
## Code Style Guidelines
We follow standard Go conventions:
- **Format code** before committing:
```bash
go fmt ./...
```
- **Run static analysis**:
```bash
go vet ./...
```
- Follow [Effective Go](https://golang.org/doc/effective_go) guidelines
- Keep functions focused and reasonably sized
- Add comments for exported functions and types
- Use meaningful variable and function names
## Pull Request Process
1. Fork the repository and create a feature branch from `main`
2. Make your changes with clear, atomic commits
3. Ensure all tests pass and add tests for new functionality
4. Run `go fmt` and `go vet` before submitting
5. Open a pull request with a clear description of the changes
6. Link any related issues in the PR description
7. Address review feedback promptly
## Issue Reporting Guidelines
When reporting issues, please include:
- **Bug reports**: Steps to reproduce, expected behavior, actual behavior, Go version, and OS
- **Feature requests**: Clear description of the proposed feature and its use case
- **Questions**: Check existing issues and documentation first
Use descriptive titles and provide as much context as possible.
## Third-Party Provider Integrations
We welcome contributions that add integrations with third-party providers! If you're adding a new provider integration:
- Follow the existing integration patterns in the codebase
- Include documentation for configuration options
- Add appropriate tests
- Update the README if necessary
## Questions?
Feel free to open an issue for any questions about contributing.
+15
View File
@@ -0,0 +1,15 @@
FROM alpine:latest
# Install ttyd
RUN apk add --no-cache ttyd
# Set working directory
WORKDIR /app
# Copy the binary (we'll mount it instead for dev)
# The binary will be mounted at runtime
EXPOSE 7681
# Run ttyd with the mounted binary
CMD ["ttyd", "-p", "7681", "-W", "./proxypilot", "tui"]
+3 -2
View File
@@ -1,7 +1,8 @@
MIT License
Copyright (c) 2025-2005.9 Luis Pater
Copyright (c) 2025.9-present Router-For.ME
Copyright (c) 2024-2025 Luis Pater
Copyright (c) 2024-2025 Router-For.ME
Copyright (c) 2025 Finesssee (ProxyPilot fork)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+304 -15
View File
@@ -1,31 +1,320 @@
# CLIProxyAPI Plus
<p align="center">
<img src="./static/icon.png" width="128" height="128" alt="ProxyPilot Logo">
</p>
English | [Chinese](README_CN.md)
<h1 align="center">ProxyPilot</h1>
This is the Plus version of [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI), adding support for third-party providers on top of the mainline project.
<p align="center">
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-28a745" alt="MIT License"></a>
<a href="https://golang.org/"><img src="https://img.shields.io/badge/Go-1.24+-00ADD8?logo=go" alt="Go Version"></a>
<a href="https://x.com/Finessse377721"><img src="https://img.shields.io/badge/Follow-%F0%9D%95%8F%2F%40Finessse377721-1c9bf0" alt="Follow on 𝕏"></a>
<a href="https://github.com/Finesssee/ProxyPilot"><img src="https://img.shields.io/github/stars/Finesssee/ProxyPilot.svg?style=social&label=Star%20this%20repo" alt="Star this repo"></a>
</p>
All third-party provider support is maintained by community contributors; CLIProxyAPI does not provide technical support. Please contact the corresponding community maintainer if you need assistance.
<p align="center">
<strong>Stop juggling API keys.</strong> ProxyPilot is a powerful local API proxy that lets you use your existing Claude Code, Codex, Gemini, Kiro, and Qwen subscriptions with any AI coding tool – no separate API keys required.
</p>
The Plus release stays in lockstep with the mainline features.
<p align="center">
Built in Go, it handles OAuth authentication, token management, and API translation automatically. One server to route them all.
</p>
## Differences from the Mainline
---
- Added Kiro (AWS CodeWhisperer) support (OAuth login), provided by [fuko2935](https://github.com/fuko2935/CLIProxyAPI/tree/feature/kiro-integration), [Ravens2121](https://github.com/Ravens2121/CLIProxyAPIPlus/)
> [!TIP]
> 📣 **Latest models supported:**
> Claude Opus 4.5 / Sonnet 4.5 with extended thinking, GPT-5.2 / GPT-5.2 Codex, Gemini 3 Pro/Flash, and Kiro (AWS CodeWhisperer)! 🚀
## Contributing
**Setup Guides:**
- [Claude Code Setup →](docs/claude-code-local-proxy.md)
- [Cursor IDE Setup →](docs/cursor-ide.md)
This project only accepts pull requests that relate to third-party provider support. Any pull requests unrelated to third-party provider support will be rejected.
---
If you need to submit any non-third-party provider changes, please open them against the mainline repository.
## Features
- 🎯 **10 Auth Providers** - Claude, Codex (OpenAI), Gemini, Gemini CLI, Kiro (AWS), Amazon Q CLI, Qwen, Antigravity, MiniMax, Zhipu AI
- 🔄 **Universal API Translation** - Auto-converts between OpenAI, Anthropic, and Gemini formats
- 🔧 **Tool Calling Repair** - Fixes tool/function call mismatches between providers automatically
- 🧠 **Extended Thinking** - Full support for Claude and Gemini thinking models
- 🔐 **OAuth Integration** - Browser-based login with automatic token refresh
- 👥 **Multi-Account Support** - Round-robin distribution with automatic failover
- ⚡ **Quota Auto-Switch** - Automatically switches to backup project/model when quota exceeded
- 📊 **Usage Statistics** - Track requests, tokens, and errors per provider/model
- 🧩 **Context Compression** - LLM-based summarization for long sessions (Factory.ai research)
- 🤖 **Agentic Harness** - Guided workflow for coding agents (Anthropic research)
- 💾 **Session Memory** - Persistent storage across conversation turns
- 🎨 **System Tray** - Native Windows tray app for quick access
- 📡 **60+ Management APIs** - Full control via REST endpoints
---
## Supported Providers
| Provider | Auth Method | Models |
|----------|-------------|--------|
| Claude (Anthropic) | OAuth2 / API Key | Claude Opus 4.5, Sonnet 4.5, Haiku 4.5 |
| Codex (OpenAI) | OAuth2 / API Key | GPT-5.2, GPT-5.2 Codex |
| Gemini | OAuth2 / API Key | Gemini 3 Pro, Gemini 3 Flash |
| Gemini CLI | OAuth2 | Cloud Code Assist (separate quota) |
| Kiro | OAuth2 + AWS SSO | AWS CodeWhisperer |
| Amazon Q CLI | Import from CLI | Amazon Q Developer |
| Qwen | OAuth2 | Qwen models |
| Antigravity | OAuth2 | Gemini via Antigravity (separate quota) |
| MiniMax | API Key | MiniMax M2, M2.1 models |
| Zhipu AI | API Key | GLM-4.5, GLM-4.6, GLM-4.7 |
| Custom | API Key | Any OpenAI-compatible endpoint |
---
## Installation
### Download Pre-built Release (Recommended)
1. Go to the [**Releases**](https://github.com/Finesssee/ProxyPilot/releases) page
2. Download the latest binary for your platform
3. Run `./proxypilot`
### Build from Source
```bash
git clone https://github.com/Finesssee/ProxyPilot.git
cd ProxyPilot
go build -o proxypilot ./cmd/server
./proxypilot
```
---
## Usage
### First Launch
1. Copy config: `cp config.example.yaml config.yaml`
2. Run: `./proxypilot`
3. Server starts on `http://localhost:8317`
4. Open dashboard: `http://localhost:8317/proxypilot.html`
### Authentication
Run OAuth login for your provider:
```bash
# OAuth providers (opens browser)
./proxypilot --claude-login # Claude
./proxypilot --codex-login # OpenAI/Codex
./proxypilot --login # Gemini
./proxypilot --kiro-login # Kiro (Google OAuth)
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID)
./proxypilot --qwen-login # Qwen
./proxypilot --antigravity-login # Antigravity
# Import providers (from existing CLI tools)
./proxypilot --amazonq-import # Amazon Q CLI (run 'q login' first)
./proxypilot --kiro-import # Kiro IDE token
# API key providers (prompts for key)
./proxypilot --minimax-login # MiniMax API key
./proxypilot --zhipu-login # Zhipu AI API key
```
OAuth tokens are stored locally and auto-refreshed before expiry.
### Security Defaults (Auth + CORS)
- Proxy requests require API keys by default. To allow unauthenticated access (not recommended), set `allow-unauthenticated: true` in `config.yaml`.
- CORS is enabled for non-management endpoints by default (wildcard `*`). Management endpoints **do not** emit CORS headers unless you explicitly allow origins under `cors.management-allow-origins`.
Example:
```yaml
allow-unauthenticated: false
cors:
allow-origins:
- "http://localhost:5173"
management-allow-origins:
- "http://localhost:5173"
```
### Configure Your Tools
**Claude Code** (`~/.claude/settings.json`):
```json
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8317",
"ANTHROPIC_AUTH_TOKEN": "your-api-key"
}
}
```
**Codex CLI** (`~/.codex/config.toml`):
```toml
[openai]
api_base_url = "http://127.0.0.1:8317"
```
**Factory Droid** (`~/.factory/settings.json`):
```json
{
"customModels": [{
"name": "ProxyPilot",
"baseUrl": "http://127.0.0.1:8317"
}]
}
```
---
## API Endpoints
```
POST /v1/chat/completions # OpenAI Chat Completions
POST /v1/responses # OpenAI Responses API
POST /v1/messages # Anthropic Messages API
GET /v1/models # List available models
GET /healthz # Health check
```
All endpoints auto-translate between formats based on the target provider.
---
## Caching
ProxyPilot includes two caching layers to reduce latency and token usage.
### Response Cache
Caches full API responses for identical requests. Useful for repeated queries during development.
**Config** (`config.yaml`):
```yaml
response-cache:
enabled: true # Default: false
max-size: 1000 # Max entries (default: 1000)
max-bytes: 0 # Optional total cache size cap in bytes
ttl-seconds: 300 # Cache TTL (default: 300 = 5 min)
exclude-models: # Models to skip (supports wildcards)
- "*-thinking"
- "o1-*"
```
### Prompt Cache
Synthetic prompt caching for providers without native support. Tracks repeated system prompts and estimates token savings.
**Config** (`config.yaml`):
```yaml
prompt-cache:
enabled: true # Default: false
max-size: 500 # Max entries (default: 500)
max-bytes: 0 # Optional total cache size cap in bytes
ttl-seconds: 1800 # Cache TTL (default: 1800 = 30 min)
```
### Cache Management API
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/v0/management/cache/stats` | GET | Response cache stats (hits, misses, size) |
| `/v0/management/cache/clear` | POST | Clear response cache |
| `/v0/management/cache/enabled` | PUT | Enable/disable at runtime `{"enabled": true}` |
| `/v0/management/prompt-cache/stats` | GET | Prompt cache stats + estimated tokens saved |
| `/v0/management/prompt-cache/clear` | POST | Clear prompt cache |
| `/v0/management/prompt-cache/enabled` | PUT | Enable/disable at runtime |
| `/v0/management/prompt-cache/top` | GET | Top 10 most-hit prompts |
---
## Lightweight Profile
For low‑memory or high‑throughput setups, you can disable heavier features:
```yaml
commercial-mode: true
usage-statistics-enabled: false
usage-sample-rate: 0.25
metrics-enabled: false
request-history-enabled: false
request-history-sample-rate: 0.25
agentic-harness-enabled: false
prompt-budget-enabled: false
request-log: false
response-cache:
enabled: false
prompt-cache:
enabled: false
```
---
## CLI Tools
| Binary | Description |
|--------|-------------|
| `proxypilot` | Main CLI with server and config switching |
| `cliproxytray` | System tray app |
---
## Tool Integrations
Works with these AI coding tools:
- **Claude Code** - Auto-configure via settings.json
- **Codex CLI** - Auto-configure via config.toml
- **Factory Droid** - Auto-configure via settings.json
- **Cursor IDE** - Manual endpoint configuration
- **Continue** - Manual endpoint configuration
---
## Requirements
- macOS, Linux, or Windows
- Go 1.24+ (for building from source)
---
## Author
ProxyPilot is developed and maintained by [@Finesssee](https://github.com/Finesssee). Some contributors shown in the git history are from upstream [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) merges. Direct contributors to ProxyPilot will be listed here as the project grows.
---
## Credits
ProxyPilot builds upon excellent work from the open-source community:
- **[CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)** - The original unified proxy server that inspired this project
- **[VibeProxy](https://github.com/automazeio/vibeproxy)** - Native macOS menu bar app showcasing clean proxy UX
Long-context features are inspired by research from the AI community:
- **[Factory.ai](https://factory.ai/news/evaluating-compression)** - Context compression techniques for long-running coding agents
- **[Anthropic](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)** - Effective harnesses for long-running agents
Special thanks to these teams for sharing their work and insights.
---
## License
This project is licensed under the MIT License - see `LICENSE`.
MIT License - see [LICENSE](LICENSE) for details.
---
## Support
- **Report Issues**: [GitHub Issues](https://github.com/Finesssee/ProxyPilot/issues)
---
## Disclaimer
This project is intended for educational and interoperability research purposes only. It interacts with various internal or undocumented APIs (such as Google's `v1internal`) to provide compatibility layers.
This project is for educational and interoperability research purposes. It interacts with various APIs to provide compatibility layers.
- **Use at your own risk.** The authors are not responsible for any consequences arising from the use of this software, including but not limited to account suspensions or service interruptions.
- This project is **not** affiliated with, endorsed by, or associated with Google, OpenAI, Anthropic, or any other service provider mentioned.
- Users are expected to comply with the Terms of Service of the respective platforms they connect to.
- **Use at your own risk.** Authors are not responsible for account suspensions or service interruptions.
- **Not affiliated** with Google, OpenAI, Anthropic, Amazon, or any other provider.
- Users must comply with the Terms of Service of connected platforms.
-23
View File
@@ -1,23 +0,0 @@
# CLIProxyAPI Plus
[English](README.md) | 中文
这是 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 的 Plus 版本,在原有基础上增加了第三方供应商的支持。
所有的第三方供应商支持都由第三方社区维护者提供,CLIProxyAPI 不提供技术支持。如需取得支持,请与对应的社区维护者联系。
该 Plus 版本的主线功能与主线功能强制同步。
## 与主线版本版本差异
- 新增 Kiro (AWS CodeWhisperer) 支持 (OAuth 登录), 由[fuko2935](https://github.com/fuko2935/CLIProxyAPI/tree/feature/kiro-integration)、[Ravens2121](https://github.com/Ravens2121/CLIProxyAPIPlus/)提供
## 贡献
该项目仅接受第三方供应商支持的 Pull Request。任何非第三方供应商支持的 Pull Request 都将被拒绝。
如果需要提交任何非第三方供应商支持的 Pull Request,请提交到主线版本。
## 许可证
此项目根据 MIT 许可证授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
+58
View File
@@ -0,0 +1,58 @@
# Security Policy
## Supported Versions
The following versions of ProxyPilot are currently supported with security updates:
| Version | Supported |
| ------- | ------------------ |
| latest | :white_check_mark: |
| < 1.0 | :x: |
## Reporting a Vulnerability
We take the security of ProxyPilot seriously. If you discover a security vulnerability, please report it responsibly.
### How to Report
You can report a vulnerability through one of the following methods:
1. **GitHub Security Advisory (Preferred)**: Open a private security advisory through [GitHub Security Advisories](https://github.com/smat-dev/ProxyPilot/security/advisories/new). This allows for private discussion and coordination.
2. **Email**: Send an email to the project maintainers with details of the vulnerability. Please include:
- A description of the vulnerability
- Steps to reproduce the issue
- Potential impact of the vulnerability
- Any suggested fixes (if available)
### What to Expect
After submitting a vulnerability report:
- **Initial Response**: You will receive an acknowledgment within **48 hours** confirming we have received your report.
- **Assessment**: We will investigate and assess the vulnerability within **7 days**.
- **Resolution Timeline**: We aim to release a fix for confirmed vulnerabilities within **30 days**, depending on complexity.
- **Disclosure**: Once a fix is released, we will coordinate with you on public disclosure timing.
We will keep you informed throughout the process and credit you for the discovery (unless you prefer to remain anonymous).
## Responsible Disclosure Guidelines
To protect our users, we ask that you:
- **DO NOT** disclose the vulnerability publicly until a fix has been released.
- **DO NOT** exploit the vulnerability beyond what is necessary to demonstrate the issue.
- **DO NOT** access, modify, or delete data belonging to other users.
- **DO** provide us with reasonable time to address the issue before any public disclosure.
- **DO** act in good faith to avoid privacy violations, data destruction, or service disruption.
We are committed to working with security researchers and will not take legal action against individuals who discover and report vulnerabilities responsibly.
## Security Best Practices for Users
- Always use the latest version of ProxyPilot.
- Review and understand the proxy configurations before deployment.
- Use secure connections (HTTPS) where applicable.
- Regularly review access logs for suspicious activity.
Thank you for helping keep ProxyPilot and its users safe.
-74
View File
@@ -1,74 +0,0 @@
# ProxyPilot & Droid CLI Troubleshooting Log
**Date:** 2025-12-19
**Subject:** Gemini/Antigravity API Key & Quota Issues
## 1. Issue Summary
The user encountered `[HTTP 400] API key not valid` and `[HTTP 429] Resource Exhausted` errors when using the `droid` CLI with the `gemini-3-pro-preview` model.
## 2. Root Causes Identified
### A. Wrong Model Routing (Primary Cause of Quota Error)
* **Symbol:** `gemini-3-pro-preview`
* **Issue:** In ProxyPilot's registry, `gemini-3-pro-preview` is defined as a **Google/Gemini CLI** model, not an Antigravity model. Requests were routing directly to Google using personal CLI keys/quota, which were exhausted (429).
* **Fix:** Switched Droid configuration to use **`gemini-3-pro-high`** (or `low`), which are the correct aliases for Antigravity-routed models. These are now confirmed working.
### B. Antigravity Account Rotation Failure
* **Issue:** Even when using Antigravity, only 1 of the 3 available accounts was being utilized.
* **Cause:** The Auth Selector (`selector.go`) uses a "Strict Fallback" heuristic. If exactly *one* auth file contains a `project_id` field, it is designated as the "Primary" account, and others are ignored until the primary is effectively invalid.
* **Discovery:** Only the account `truongnamphong8` had a `project_id`.
* **Fix:** Removed the `project_id` field from the auth file so all 3 accounts are treated as "peers" and rotated via Round Robin.
### C. "API Key Not Valid" Startup Error
* **Issue:** ProxyPilot server logs showed API key errors on startup.
* **Cause:** `config.yaml` contained a placeholder line: `api-key: "YOUR_LEGIT_API_KEY_HERE"`.
* **Fix:** Commented out the invalid line in `config.yaml`.
### D. Droid CLI Config Corruption
* **Issue:** Droid failed to load with "Failed to parse custom models config".
* **Cause:** The `config.json` file was saved with a UTF-8 **BOM** (Byte Order Mark) by PowerShell during debugging/editing.
* **Fix:** Rewrote `config.json` with UTF-8 (No BOM) encoding.
## 3. Preventative Measures & Best Practices
### Model Naming
**ALWAYS** use the Antigravity-specific model IDs to ensure requests route through the shared pool rather than personal quota:
* ✅ `gemini-3-pro-high`
* ✅ `gemini-3-pro-low`
* ✅ `gemini-3-flash` (if available via Antigravity)
* ✅ `antigravity-claude-sonnet-4-5-thinking`
* ❌ `gemini-3-pro-preview` (Routes to Google CLI)
### Auth File Management
When adding new Antigravity accounts (`.json` files in `~/.cli-proxy-api/`):
* Ensure **uniformity**. Either *all* files should have a `project_id`, or *none* should.
* If mixed, the one with `project_id` will monopolize traffic.
### Configuration
* Do not leave placeholder values (like "YOUR_KEY_HERE") in `config.yaml`; comment them out.
* When editing JSON configuration files on Windows, ensure your editor saves as **UTF-8 (No BOM)**.
## 4. Current Configuration (Verified)
* **Droid Config:** `~/.factory/config.json` updated with correct Antigravity model names.
* **ProxyPilot Config:** `d:\code\ProxyPilot\config.yaml` cleaned of invalid keys.
* **Auth Status:** 3 Antigravity accounts active and rotating.
## 5. Issue: Rate Limit Rotation "Stuck" on One Account
**Date:** 2025-12-20
**Subject:** HTTP 429 Handling in Antigravity Executor & Manager
### A. Issue Summary
The user experienced repeated 429 Too Many Requests errors from the *same* account (yuhh0704@gmail.com) despite having multiple healthy backup accounts (nnq2366) available. The rotation logic refused to switch to the backup, effectively blocking the user.
### B. Root Causes
1. **Missing Retry-After Parsing:** The AntigravityExecutor was receiving a Retry-After header (e.g., 1 hour) from the upstream API but was ignoring it. It only returned a generic error message.
* **Effect:** The AuthManager used a default backoff of only **1 second**.
2. **Model State Not Updated:** When the global Auth object was marked as "Rate Limited", the specific ModelState for the requested model (e.g., claude-opus-4-5-thinking) remained "Active".
* **Effect:** The RoundRobinSelector checked the *model* state, saw it was valid, and re-selected the same "Primary Fallback" account (due to strict fallback logic preferences) immediately after the 1-second backoff expired.
### C. The Fix
1. **Updated AntigravityExecutor:** Added logic to parse the Retry-After header (supporting both integer seconds and HTTP date formats) and pass it to the statusErr struct.
2. **Updated AuthManager (MarkResult):** Modified the result handling to explicitly update the ModelState with the error and cooldown info, not just the parent Auth object.
3. **Updated Selector (isAuthBlockedForModel):** Added a defensive check to respect NextRetryAfter timestamps even if the Unavailable boolean flag wasn't explicitly set, ensuring blocked models are strictly filtered out.
### D. Result
System now respects long cooldowns (e.g., 3 hours) and correctly skips the blocked "Primary" account to use the "Secondary" backups like nnq2366.
-156
View File
@@ -1,156 +0,0 @@
# WARP.md
This file provides guidance to WARP (warp.dev) when working with code in this repository.
## Common commands
### Go (engine + desktop binaries)
Build the main deliverables into `bin/`:
```pwsh
# Builds:
# - bin\proxypilot-engine.exe (engine)
# - bin\ProxyPilot.exe (tray app)
# - bin\ProxyPilotUI.exe (desktop dashboard)
go run .\cmd\proxypilotpack build
```
Run the engine directly:
```pwsh
# Uses config.yaml in the repo root by default
# (or pass -config <path>)
go run .\cmd\server -config .\config.yaml
```
Windows helpers (used for local development and Droid/Factory CLI integration):
```pwsh
# build engine (writes bin\proxypilot-engine.exe)
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\build-cliproxyapi.ps1
# start/stop/restart engine (writes logs\proxypilot-engine.{out,err}.log)
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-cliproxy.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\stop-cliproxy.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\restart-cliproxy.ps1
```
Package artifacts:
```pwsh
# Zip bundle -> dist\ProxyPilot.zip
# (includes tray, UI, engine, and config.example.yaml)
go run .\cmd\proxypilotpack package-zip
# Windows installer (Inno Setup) -> dist\ProxyPilot-Setup.exe
# Requires ISCC.exe (Inno Setup 6) available on PATH.
go run .\cmd\proxypilotpack package-inno
```
Docker (engine in a container):
```pwsh
docker compose up --build
```
### Web UI (Vite)
The web UI lives in `webui/`:
```pwsh
cd .\webui
npm install
npm run dev # local dev server
npm run build # typecheck + build
npm run lint
```
### Tests
Run all Go tests:
```pwsh
go test ./...
```
Run a single package:
```pwsh
go test .\internal\api -run TestName
```
Run a single test across all packages:
```pwsh
go test ./... -run TestName
```
Regression tests called out in docs:
- Droid SSE parsing: `sdk/api/handlers/openai/openai_responses_handlers_sse_done_test.go`
- Codex SSE done sentinel: `sdk/api/handlers/openai/openai_responses_handlers_sse_json_compat_test.go`
- Antigravity request shape: `internal/runtime/executor/antigravity_executor_shape_test.go`
## High-level architecture
### Binaries (`cmd/`)
This repo produces multiple Go binaries:
- `cmd/server` (engine): HTTP proxy server exposing OpenAI/Gemini/Claude-compatible endpoints; also hosts OAuth callback endpoints.
- `cmd/cliproxytray` (Windows tray app): starts/stops the engine, opens UI, toggles autostart, checks for updates.
- `cmd/proxypilotui` (Windows desktop UI): WebView2 desktop window for the Control Center; talks to the running engine and uses management endpoints.
- `cmd/proxypilotpack`: build/packaging orchestrator (build binaries into `bin/`, create `dist/` artifacts).
### Engine request path (big picture)
1. `cmd/server/main.go` loads config (`config.yaml` or a store-backed config), decides whether to run login flows or start the server.
2. `internal/cmd/StartService` builds the service via the exported SDK (`sdk/cliproxy.NewBuilder()`) and runs it.
3. The HTTP server is implemented in `internal/api/server.go` using Gin:
- `/v1/*` OpenAI-compatible endpoints (plus non-`/v1` aliases for clients that set base URL to `/v1`).
- `/v1/responses` has special streaming/SSE behavior for strict CLIs (see `docs/compat-matrix.md`).
- `/v1beta/*` Gemini-compatible endpoints.
- `/v1internal:method` Gemini CLI compatibility endpoint.
- OAuth callbacks like `/codex/callback`, `/google/callback`, etc. persist short-lived state for the login goroutines.
Core handler layer:
- `sdk/api/handlers/*` contains provider-specific API adapters (OpenAI/Gemini/Claude) and schema/streaming shims.
- `internal/api/handlers/management/*` contains management endpoints mounted under `/v0/management/*`.
### Management + desktop UX
- Management endpoints are only enabled when a secret is configured:
- `remote-management.secret-key` in `config.yaml`, or
- environment `MANAGEMENT_PASSWORD`.
- The tray app starts the engine via `internal/desktopctl.Start()` and injects a per-user `MANAGEMENT_PASSWORD` so the desktop UX can use `/v0/management/*` locally.
- The ProxyPilot dashboard page (`/proxypilot.html`) is served **localhost-only** and injects the management key into the HTML so users don’t paste keys manually.
Key components:
- `internal/desktopctl`: process management (start/stop/status), log file locations, and per-user UI state.
- `internal/api/proxypilot_dashboard.go`: local-only ProxyPilot dashboard HTML.
- `internal/managementasset`: downloads/serves the upstream management UI bundle and applies runtime text replacements for ProxyPilot branding.
### Config + persistence
- Default config is `config.yaml` (template: `config.example.yaml`).
- The engine can optionally use different config/auth persistence backends based on env vars (selected in `cmd/server/main.go`):
- Postgres-backed store (`PGSTORE_*`)
- Git-backed token store (`GITSTORE_*`)
- Object store (`OBJECTSTORE_*`)
### SDK embedding
The proxy can be embedded as a Go library:
- `sdk/cliproxy` exposes a builder (`NewBuilder`) that wires config watching, auth, translators, and the HTTP server.
- `docs/sdk-usage.md` shows the supported server options (middleware/router hooks, request logging overrides, management enablement).
## Docs worth reading first
- `docs/proxypilot.md` (Windows packaging + local management key behavior)
- `docs/compat-matrix.md` (client/upstream quirks; streaming/SSE gotchas; tests to protect)
- `docs/cursor-ide.md` (how Cursor expects base URL and API key behavior)
- `docs/sdk-usage.md` (how the engine is composed when embedded)
+2
View File
@@ -0,0 +1,2 @@
.npmrc
node_modules/
+74
View File
@@ -0,0 +1,74 @@
# proxypilot
ProxyPilot CLI - Includes the ProxyPilot server and configuration switcher for AI CLI agents.
## Features
- **Server**: Run the ProxyPilot proxy server locally
- **Switch**: Switch AI CLI agents between proxy and native modes
## Install
```bash
bun install -g proxypilot
```
Or run without installing:
```bash
bunx proxypilot
```
## Usage
```bash
# Start the ProxyPilot server
proxypilot server
# Show status of all agents
proxypilot switch
# Switch Claude to proxy mode
proxypilot switch claude proxy
# Switch Gemini to native mode
proxypilot switch gemini native
# Show help
proxypilot --help
```
## Supported Agents
| Agent | Command |
|-------|---------|
| Claude Code | `proxypilot switch claude proxy` |
| Gemini CLI | `proxypilot switch gemini proxy` |
| Codex CLI | `proxypilot switch codex proxy` |
| OpenCode | `proxypilot switch opencode proxy` |
| Factory Droid | `proxypilot switch droid proxy` |
| Cursor | `proxypilot switch cursor proxy` |
| Kilo Code* | `proxypilot switch kilo proxy` |
| RooCode* | `proxypilot switch roocode proxy` |
\* VS Code extensions require manual configuration
## Modes
- `proxy` - Route through ProxyPilot (http://127.0.0.1:8317)
- `native` - Use direct API access (restore original config)
## How It Works
The switcher manages config files for each agent:
```
~/.claude/
├── settings.json # Active config
├── settings.native.json # Original/backup config
└── settings.proxy.json # ProxyPilot config
```
## License
MIT
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bun
import { spawn } from "bun";
import { join } from "path";
const ext = process.platform === "win32" ? ".exe" : "";
const binary = join(import.meta.dir, `proxypilot${ext}`);
const proc = spawn([binary, ...process.argv.slice(2)], {
stdio: ["inherit", "inherit", "inherit"],
});
await proc.exited;
process.exit(proc.exitCode ?? 0);
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bun
import { $ } from "bun";
import { existsSync, chmodSync } from "fs";
import { join } from "path";
const VERSION = "0.2.0";
const REPO = "Finesssee/ProxyPilot";
const PLATFORM_MAP: Record<string, string> = {
darwin: "darwin",
linux: "linux",
win32: "windows",
};
const ARCH_MAP: Record<string, string> = {
x64: "amd64",
arm64: "arm64",
};
async function install() {
const platform = PLATFORM_MAP[process.platform];
const arch = ARCH_MAP[process.arch];
if (!platform || !arch) {
console.error(`Unsupported platform: ${process.platform}-${process.arch}`);
process.exit(1);
}
const ext = platform === "windows" ? ".exe" : "";
const binaryName = `proxypilot-${platform}-${arch}${ext}`;
const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${binaryName}`;
const binDir = join(import.meta.dir, "bin");
const binPath = join(binDir, platform === "windows" ? "proxypilot.exe" : "proxypilot");
console.log(`Downloading proxypilot v${VERSION} for ${platform}-${arch}...`);
try {
const response = await fetch(url, { redirect: "follow" });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
await Bun.write(binPath, response);
// Make executable on Unix
if (platform !== "windows") {
chmodSync(binPath, 0o755);
}
console.log("proxypilot installed successfully!");
console.log('Run "proxypilot --help" to get started.');
} catch (err: any) {
console.error("Failed to download proxypilot:", err.message);
console.error(`\nYou can manually download from:\nhttps://github.com/${REPO}/releases`);
process.exit(1);
}
}
install();
+38
View File
@@ -0,0 +1,38 @@
{
"name": "proxypilot",
"version": "0.2.0",
"description": "ProxyPilot - Local API proxy for AI coding tools with CLI control",
"bin": {
"proxypilot": "bin/proxypilot"
},
"scripts": {
"postinstall": "bun run install.ts"
},
"keywords": [
"proxypilot",
"claude",
"gemini",
"codex",
"ai",
"cli",
"proxy",
"config",
"switcher"
],
"author": "ProxyPilot",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Finesssee/ProxyPilot"
},
"homepage": "https://github.com/Finesssee/ProxyPilot",
"os": [
"darwin",
"linux",
"win32"
],
"cpu": [
"x64",
"arm64"
]
}
+197
View File
@@ -0,0 +1,197 @@
//go:build windows
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy"
log "github.com/sirupsen/logrus"
)
// EmbeddedEngine runs the proxy service in-process within the tray application.
// It provides thread-safe methods for starting, stopping, and querying the service status.
type EmbeddedEngine struct {
mu sync.Mutex
// running indicates whether the service is currently active.
running bool
// port is the port number the service is listening on.
port int
// configPath stores the path to the configuration file.
configPath string
// lastError holds the most recent error encountered during operation.
lastError error
// startedAt records when the service was started.
startedAt time.Time
// cancel is the function to cancel the service context.
cancel context.CancelFunc
// wg waits for the service goroutine to complete.
wg sync.WaitGroup
}
// NewEmbeddedEngine creates a new EmbeddedEngine instance.
func NewEmbeddedEngine() *EmbeddedEngine {
return &EmbeddedEngine{}
}
// Start builds and runs the proxy service in a background goroutine.
// It returns an error if the service is already running or if building the service fails.
func (e *EmbeddedEngine) Start(cfg *config.Config, configPath, password string) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.running {
return errors.New("engine is already running")
}
if cfg == nil {
return errors.New("configuration is required")
}
if configPath == "" {
return errors.New("configuration path is required")
}
// Build the service using the SDK builder pattern
builder := cliproxy.NewBuilder().
WithConfig(cfg).
WithConfigPath(configPath).
WithLocalManagementPassword(password)
service, err := builder.Build()
if err != nil {
e.lastError = fmt.Errorf("failed to build proxy service: %w", err)
return e.lastError
}
// Create a cancelable context for the service
ctx, cancel := context.WithCancel(context.Background())
e.cancel = cancel
// Track state
e.running = true
e.port = cfg.Port
e.configPath = configPath
e.lastError = nil
e.startedAt = time.Now()
log.Infof("starting embedded proxy engine on port %d", e.port)
// Run the service in a goroutine
e.wg.Add(1)
go func() {
defer e.wg.Done()
defer func() {
e.mu.Lock()
e.running = false
e.cancel = nil
e.mu.Unlock()
log.Info("embedded proxy engine stopped")
}()
err := service.Run(ctx)
if err != nil && !errors.Is(err, context.Canceled) {
e.mu.Lock()
e.lastError = fmt.Errorf("proxy service exited with error: %w", err)
e.mu.Unlock()
log.Errorf("embedded proxy engine error: %v", err)
}
}()
return nil
}
// Stop cancels the running service and waits for it to shut down.
// It returns an error if the service is not running.
func (e *EmbeddedEngine) Stop() error {
e.mu.Lock()
if !e.running {
e.mu.Unlock()
return errors.New("engine is not running")
}
if e.cancel != nil {
log.Info("stopping embedded proxy engine...")
e.cancel()
}
e.mu.Unlock()
// Wait for the goroutine to complete
e.wg.Wait()
return nil
}
// Restart stops the running service (if any) and starts it again with the new configuration.
func (e *EmbeddedEngine) Restart(cfg *config.Config, configPath, password string) error {
// Stop if running (ignore error if not running)
if e.IsRunning() {
if err := e.Stop(); err != nil {
log.Warnf("error stopping engine during restart: %v", err)
}
}
// Start with new configuration
return e.Start(cfg, configPath, password)
}
// Status returns the current status of the embedded engine.
// The returned status is compatible with desktopctl.Status for UI integration.
func (e *EmbeddedEngine) Status() desktopctl.Status {
e.mu.Lock()
defer e.mu.Unlock()
status := desktopctl.Status{
Running: e.running,
Managed: true, // Embedded engine is always managed by the tray
Port: e.port,
ConfigPath: e.configPath,
StartedAt: e.startedAt,
}
if e.running && e.port > 0 {
status.BaseURL = fmt.Sprintf("http://127.0.0.1:%d", e.port)
}
if e.lastError != nil {
status.LastError = e.lastError.Error()
}
return status
}
// IsRunning returns whether the engine is currently running.
func (e *EmbeddedEngine) IsRunning() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.running
}
// LastError returns the most recent error encountered, or nil if none.
func (e *EmbeddedEngine) LastError() error {
e.mu.Lock()
defer e.mu.Unlock()
return e.lastError
}
// Port returns the port number the engine is configured to listen on.
func (e *EmbeddedEngine) Port() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.port
}
+291 -288
View File
@@ -14,36 +14,73 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/getlantern/systray"
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
"github.com/jchv/go-webview2"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
"github.com/router-for-me/CLIProxyAPI/v6/internal/proxypilotupdate"
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
"github.com/router-for-me/CLIProxyAPI/v6/internal/trayicon"
"github.com/router-for-me/CLIProxyAPI/v6/internal/updates"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
)
const autostartAppName = "ProxyPilot"
const thinkingProxyPort = 8317
var assetServerURL string
var dashboardMu sync.Mutex
var dashboardOpen bool
func main() {
var repoRoot string
var configPath string
var exePath string
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate logs/)")
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
flag.StringVar(&exePath, "exe", "", "Path to ProxyPilot Engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
flag.Parse()
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
run(repoRoot, configPath, exePath)
repoRoot, configPath = applyDefaults(repoRoot, configPath)
run(repoRoot, configPath)
}
func run(repoRoot, configPath, exePath string) {
func run(repoRoot, configPath string) {
// Initialize logging
logging.SetupBaseLogger()
// Load config
cfg, err := config.LoadConfigOptional(configPath, false)
if err == nil && cfg != nil {
logging.ConfigureLogOutput(cfg.LoggingToFile, cfg.LogsMaxTotalSizeMB)
util.SetLogLevel(cfg)
}
if cfg == nil {
cfg = &config.Config{Port: 8318} // Default config if load fails
}
// Register token store
sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore())
// Register access providers
configaccess.Register()
// Create embedded engine (will be used instead of desktopctl)
engine := NewEmbeddedEngine()
// Get or create management password
password, _ := desktopctl.GetManagementPassword()
systray.Run(func() {
thinkingProxy := startThinkingProxy(configPath)
thinkingProxy := startThinkingProxy(engine)
defer thinkingProxy.Close()
if ico := trayicon.ProxyPilotICO(); len(ico) > 0 {
@@ -52,99 +89,76 @@ func run(repoRoot, configPath, exePath string) {
systray.SetTitle("ProxyPilot")
systray.SetTooltip("ProxyPilot")
statusItem := systray.AddMenuItem("Status: ...", "Current status")
// Header
systray.AddMenuItem("ProxyPilot", "ProxyPilot").Disable()
systray.AddSeparator()
// Status display item (disabled, updated dynamically)
statusItem := systray.AddMenuItem("○ Stopped", "Current proxy status")
statusItem.Disable()
systray.AddSeparator()
openProxyUI := systray.AddMenuItem("Open Dashboard", "Open ProxyPilot Control Center")
// Main actions
openDashboard := systray.AddMenuItem("Open Dashboard", "Open ProxyPilot Dashboard")
toggleItem := systray.AddMenuItem("Start Proxy", "Start/Stop proxy")
copyURLItem := systray.AddMenuItem("Copy API URL", "Copy http://127.0.0.1:8317/v1")
systray.AddSeparator()
// Engine submenu
engineMenu := systray.AddMenuItem("Engine", "Engine controls")
startItem := engineMenu.AddSubMenuItem("Start", "Start the ProxyPilot engine")
stopItem := engineMenu.AddSubMenuItem("Stop", "Stop the ProxyPilot engine")
restartItem := engineMenu.AddSubMenuItem("Restart", "Restart the ProxyPilot engine")
// Providers submenu
providersMenu := systray.AddMenuItem("Providers", "Provider status")
claudeItem := providersMenu.AddSubMenuItem("○ Claude - Inactive", "Claude provider status")
geminiItem := providersMenu.AddSubMenuItem("○ Gemini - Inactive", "Gemini provider status")
codexItem := providersMenu.AddSubMenuItem("○ Codex - Inactive", "Codex provider status")
qwenItem := providersMenu.AddSubMenuItem("○ Qwen - Inactive", "Qwen provider status")
anthropicItem := providersMenu.AddSubMenuItem("○ Anthropic - Inactive", "Anthropic provider status")
// Disable provider items (they're informational only for now)
claudeItem.Disable()
geminiItem.Disable()
codexItem.Disable()
qwenItem.Disable()
anthropicItem.Disable()
// Connect submenu (VibeProxy-style easy setup)
connectMenu := systray.AddMenuItem("Connect", "Environment variables")
copyAnthropicEnv := connectMenu.AddSubMenuItem("Copy ANTHROPIC_BASE_URL", "Copy export ANTHROPIC_BASE_URL=http://127.0.0.1:8317/v1")
copyOpenAIEnv := connectMenu.AddSubMenuItem("Copy OPENAI_BASE_URL", "Copy export OPENAI_BASE_URL=http://127.0.0.1:8317/v1")
// Settings submenu
settingsMenu := systray.AddMenuItem("Settings", "ProxyPilot settings")
autoOn, _, _ := desktopctl.IsWindowsRunAutostartEnabled(autostartAppName)
autoStartItem := settingsMenu.AddSubMenuItemCheckbox("Launch on login", "Start this tray app when you log in", autoOn)
// Diagnostics submenu
diagMenu := systray.AddMenuItem("Diagnostics", "Diagnostic tools")
copyDiagItem := diagMenu.AddSubMenuItem("Copy Diagnostics", "Copy diagnostics to clipboard")
openLogsItem := diagMenu.AddSubMenuItem("Open Logs Folder", "Open logs folder in explorer")
openAuthItem := diagMenu.AddSubMenuItem("Open Auth Folder", "Open auth folder in explorer")
systray.AddSeparator()
quitItem := systray.AddMenuItem("Quit", "Quit ProxyPilot")
// Auto-start proxy on launch if enabled
autoProxyOn, _ := desktopctl.GetAutoStartProxy()
autoStartProxyItem := settingsMenu.AddSubMenuItemCheckbox("Auto-start proxy", "Start the proxy server automatically", autoProxyOn)
// Tools submenu
toolsMenu := systray.AddMenuItem("Tools", "ProxyPilot tools")
openLogs := toolsMenu.AddSubMenuItem("Open Logs", "Open logs folder")
copyDiagnostics := toolsMenu.AddSubMenuItem("Copy Diagnostics", "Copy a support bundle to clipboard")
openLegacyUI := toolsMenu.AddSubMenuItem("Advanced UI", "Open management UI (advanced)")
// Updates submenu
updatesMenu := systray.AddMenuItem("Updates", "Check for updates")
checkUpdates := updatesMenu.AddSubMenuItem("Check for Updates", "Check GitHub Releases for a newer ProxyPilot")
updateNow := updatesMenu.AddSubMenuItem("Update ProxyPilot...", "Download and run the latest installer")
updateNow.Disable()
systray.AddSeparator()
quitItem := systray.AddMenuItem("Quit", "Quit")
lastErr := ""
var (
latestVersion string
assetName string
assetURL string
)
refresh := func() {
st, _ := desktopctl.StatusFor(configPath)
title := "Stopped"
if st.Running {
title = fmt.Sprintf("Running (:%d)", st.Port)
}
if st.LastError != "" && lastErr == "" {
lastErr = st.LastError
}
if lastErr != "" {
title = title + " - " + shorten(lastErr, 80)
}
statusItem.SetTitle("Status: " + title)
systray.SetTooltip("ProxyPilot - " + title)
if st.Running {
startItem.Disable()
stopItem.Enable()
restartItem.Enable()
} else {
startItem.Enable()
stopItem.Disable()
restartItem.Disable()
}
}
refresh()
// Optional: auto-start the proxy server on launch.
if autoProxyOn {
go func() {
st, _ := desktopctl.StatusFor(configPath)
if st.Running {
return
if !engine.IsRunning() {
engine.Start(cfg, configPath, password)
}
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
} else {
lastErr = ""
}
refresh()
}()
}
// Update UI based on status
refresh := func() {
st := engine.Status()
if st.Running {
port := st.Port
if port <= 0 {
port = 8318
}
statusItem.SetTitle(fmt.Sprintf("● Running on :%d", port))
systray.SetTooltip(fmt.Sprintf("ProxyPilot - Running (:%d)", port))
toggleItem.SetTitle("Stop Proxy")
toggleItem.SetTooltip("Stop the proxy")
} else {
statusItem.SetTitle("○ Stopped")
systray.SetTooltip("ProxyPilot - Stopped")
toggleItem.SetTitle("Start Proxy")
toggleItem.SetTooltip("Start the proxy")
}
}
refresh()
// Refresh status periodically
go func() {
t := time.NewTicker(2 * time.Second)
defer t.Stop()
@@ -153,155 +167,29 @@ func run(repoRoot, configPath, exePath string) {
}
}()
// Handle clicks
go func() {
for {
select {
case <-startItem.ClickedCh:
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-stopItem.ClickedCh:
if err := desktopctl.Stop(desktopctl.StopOptions{}); err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-restartItem.ClickedCh:
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-copyAnthropicEnv.ClickedCh:
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
case <-copyOpenAIEnv.ClickedCh:
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
case <-autoStartItem.ClickedCh:
if autoStartItem.Checked() {
_ = desktopctl.DisableWindowsRunAutostart(autostartAppName)
autoStartItem.Uncheck()
lastErr = ""
refresh()
continue
}
cmd, err := autostartCommand(repoRoot, configPath, exePath)
if err != nil {
lastErr = err.Error()
refresh()
continue
}
if err := desktopctl.EnableWindowsRunAutostart(autostartAppName, cmd); err != nil {
lastErr = err.Error()
refresh()
continue
}
autoStartItem.Check()
lastErr = ""
refresh()
case <-autoStartProxyItem.ClickedCh:
if autoStartProxyItem.Checked() {
_ = desktopctl.SetAutoStartProxy(false)
autoStartProxyItem.Uncheck()
lastErr = ""
refresh()
continue
}
_ = desktopctl.SetAutoStartProxy(true)
autoStartProxyItem.Check()
lastErr = ""
refresh()
case <-openProxyUI.ClickedCh:
if err := openProxyUIWithAutostart(repoRoot, configPath, exePath); err != nil {
lastErr = err.Error()
refresh()
case <-openDashboard.ClickedCh:
openProxyUIWithAutostart(engine, cfg, configPath, password)
case <-toggleItem.ClickedCh:
if engine.IsRunning() {
engine.Stop()
} else {
lastErr = ""
refresh()
}
case <-openLegacyUI.ClickedCh:
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
lastErr = "proxy is not running"
refresh()
continue
}
_ = desktopctl.OpenBrowser(st.BaseURL + "/management.html?legacy=1")
case <-openLogs.ClickedCh:
if err := desktopctl.OpenLogsFolder(repoRoot, configPath); err != nil {
lastErr = err.Error()
refresh()
}
case <-copyDiagnostics.ClickedCh:
if err := copyDiagnosticsToClipboard(configPath); err != nil {
lastErr = err.Error()
} else {
lastErr = "Diagnostics copied"
engine.Start(cfg, configPath, password)
}
refresh()
case <-checkUpdates.ClickedCh:
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
rel, err := proxypilotupdate.FetchLatestRelease(ctx)
if err != nil {
lastErr = err.Error()
refresh()
return
}
latestVersion = rel.Version()
assetName, assetURL = rel.FindPreferredAsset()
if strings.TrimSpace(assetURL) == "" {
lastErr = "no ProxyPilot asset found in latest release"
refresh()
return
}
// If this build is already tagged, avoid prompting unnecessarily.
if buildinfo.Version != "" && buildinfo.Version != "dev" && strings.EqualFold(buildinfo.Version, latestVersion) {
lastErr = "Up to date (" + latestVersion + ")"
updateNow.Disable()
refresh()
return
}
updateNow.SetTitle("Update ProxyPilot... (" + latestVersion + ")")
updateNow.Enable()
lastErr = "Update available (" + latestVersion + ")"
refresh()
}()
case <-updateNow.ClickedCh:
if strings.TrimSpace(assetURL) == "" {
lastErr = "no update asset URL (run Check for Updates)"
refresh()
continue
case <-copyURLItem.ClickedCh:
copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
case <-copyDiagItem.ClickedCh:
copyDiagnosticsToClipboard(engine)
case <-openLogsItem.ClickedCh:
desktopctl.OpenLogsFolder(repoRoot, configPath)
case <-openAuthItem.ClickedCh:
if dir, err := desktopctl.AuthDirFor(configPath); err == nil {
desktopctl.OpenFolder(dir)
}
go func() {
dest := filepath.Join(os.TempDir(), "ProxyPilot-"+sanitizeFileName(latestVersion)+"-"+sanitizeFileName(assetName))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
updateNow.SetTitle("Updating...")
lastErr = "Downloading update..."
refresh()
if err := proxypilotupdate.DownloadToFile(ctx, assetURL, dest); err != nil {
lastErr = err.Error()
updateNow.SetTitle("Update ProxyPilot...")
refresh()
return
}
// Run installer/zip handler and exit ProxyPilot so files can be replaced.
lastErr = "Launching installer..."
refresh()
_ = launchUpdate(dest)
systray.Quit()
}()
case <-quitItem.ClickedCh:
systray.Quit()
return
@@ -315,7 +203,7 @@ type closeFn func() error
func (c closeFn) Close() error { return c() }
func startThinkingProxy(configPath string) ioCloser {
func startThinkingProxy(engine *EmbeddedEngine) ioCloser {
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", thinkingProxyPort))
if err != nil {
// Best effort: don't crash the tray app if the port is already taken.
@@ -330,7 +218,7 @@ func startThinkingProxy(configPath string) ioCloser {
)
getProxy := func() (*httputil.ReverseProxy, *url.URL) {
st, _ := desktopctl.StatusFor(configPath)
st := engine.Status()
port := st.Port
if port <= 0 {
port = 8318
@@ -391,45 +279,174 @@ type ioCloser interface {
Close() error
}
func openProxyUIWithAutostart(repoRoot, configPath, exePath string) error {
// Prefer opening the desktop window if the UI binary exists next to this tray app.
if exe, err := os.Executable(); err == nil && strings.TrimSpace(exe) != "" {
dir := filepath.Dir(filepath.Clean(exe))
uiExe := filepath.Join(dir, "ProxyPilotUI.exe")
if _, err := os.Stat(uiExe); err == nil {
args := []string{}
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return exec.Command(uiExe, args...).Start()
func openProxyUIWithAutostart(engine *EmbeddedEngine, cfg *config.Config, configPath, password string) error {
// Start proxy if not running
if !engine.IsRunning() {
if err := engine.Start(cfg, configPath, password); err != nil {
// Continue anyway to show UI
}
}
// Fallback: open browser to the management UI (starts proxy if needed).
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
if _, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath}); err != nil {
// Open embedded WebView2 dashboard
go func() {
openEmbeddedDashboard(engine, cfg, configPath, password)
}()
return nil
}
func openEmbeddedDashboard(engine *EmbeddedEngine, cfg *config.Config, configPath, password string) {
// Lock this goroutine to an OS thread - required for Windows COM/GUI operations
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Prevent opening multiple dashboard windows
dashboardMu.Lock()
if dashboardOpen {
dashboardMu.Unlock()
return
}
dashboardOpen = true
dashboardMu.Unlock()
defer func() {
dashboardMu.Lock()
dashboardOpen = false
dashboardMu.Unlock()
}()
// Recover from any panics to prevent the tray app from crashing
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "WebView2 panic: %v\n", r)
// Try to open in browser as fallback
st := engine.Status()
if st.Running && strings.TrimSpace(st.BaseURL) != "" {
_ = desktopctl.OpenBrowser(st.BaseURL + "/proxypilot.html")
}
}
}()
target := assetServerURL + "/index.html"
if assetServerURL == "" {
// Fallback to browser if asset server failed
st := engine.Status()
if st.Running && strings.TrimSpace(st.BaseURL) != "" {
_ = desktopctl.OpenBrowser(st.BaseURL + "/proxypilot.html")
}
return
}
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: true,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ProxyPilot",
Width: 1200,
Height: 850,
Center: true,
IconId: 1, // Use embedded icon from resource.syso
},
})
if w == nil {
// Fallback to browser - WebView2 runtime may not be installed
fmt.Fprintf(os.Stderr, "WebView2 failed to initialize, falling back to browser\n")
_ = desktopctl.OpenBrowser(target)
return
}
defer w.Destroy()
// Bind desktop functions for the React UI
_ = w.Bind("pp_status", func() (map[string]any, error) {
cur := engine.Status()
return map[string]any{
"running": cur.Running,
"port": cur.Port,
"base_url": cur.BaseURL,
"last_error": cur.LastError,
}, nil
})
_ = w.Bind("pp_start", func() error {
return engine.Start(cfg, configPath, password)
})
_ = w.Bind("pp_stop", func() error { return engine.Stop() })
_ = w.Bind("pp_restart", func() error {
return engine.Restart(cfg, configPath, password)
})
_ = w.Bind("pp_open_logs", func() error { return desktopctl.OpenLogsFolder("", configPath) })
_ = w.Bind("pp_open_auth_folder", func() error {
dir, err := desktopctl.AuthDirFor(configPath)
if err != nil {
return err
}
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
st2, _ := desktopctl.StatusFor(configPath)
if st2.Running {
break
}
time.Sleep(150 * time.Millisecond)
return desktopctl.OpenFolder(dir)
})
_ = w.Bind("pp_get_oauth_private", func() (bool, error) { return desktopctl.GetOAuthPrivate() })
_ = w.Bind("pp_set_oauth_private", func(enabled bool) error { return desktopctl.SetOAuthPrivate(enabled) })
_ = w.Bind("pp_oauth", func(provider string) error { return startOAuthFlow(engine, getOAuthEndpoint(provider)) })
_ = w.Bind("pp_copy_diagnostics", func() error { return copyDiagnosticsToClipboard(engine) })
_ = w.Bind("pp_get_management_key", func() (string, error) { return desktopctl.GetManagementPassword() })
_ = w.Bind("pp_open_diagnostics", func() error {
cur := engine.Status()
if !cur.Running {
return fmt.Errorf("proxy not running")
}
return desktopctl.OpenBrowser(cur.BaseURL + "/proxypilot.html")
})
_ = w.Bind("pp_get_requests", func() (any, error) {
return middleware.GetRequestMonitor(), nil
})
_ = w.Bind("pp_get_usage", func() (any, error) {
stats := usage.GetRequestStatistics()
if stats == nil {
return nil, fmt.Errorf("usage statistics not available")
}
return usage.ComputeUsageStats(stats.Snapshot()), nil
})
_ = w.Bind("pp_detect_agents", func() ([]integrations.Agent, error) {
st := engine.Status()
proxyURL := st.BaseURL
if proxyURL == "" {
proxyURL = fmt.Sprintf("http://127.0.0.1:%d", st.Port)
}
return integrations.DetectCLIAgents(proxyURL), nil
})
_ = w.Bind("pp_configure_agent", func(agentID string) error {
st := engine.Status()
proxyURL := st.BaseURL
if proxyURL == "" {
proxyURL = fmt.Sprintf("http://127.0.0.1:%d", st.Port)
}
return integrations.ConfigureCLIAgent(agentID, proxyURL)
})
_ = w.Bind("pp_unconfigure_agent", func(agentID string) error {
return integrations.UnconfigureCLIAgent(agentID)
})
_ = w.Bind("pp_check_updates", func() (*updates.UpdateInfo, error) {
return updates.CheckForUpdates()
})
_ = w.Bind("pp_download_update", func(url string) error {
return desktopctl.OpenBrowser(url)
})
w.Navigate(target)
w.Run()
}
func getOAuthEndpoint(provider string) string {
switch strings.ToLower(strings.TrimSpace(provider)) {
case "antigravity":
return "/v0/management/antigravity-auth-url"
case "gemini-cli", "geminicli":
return "/v0/management/gemini-cli-auth-url"
case "codex":
return "/v0/management/codex-auth-url"
case "claude", "anthropic":
return "/v0/management/anthropic-auth-url"
case "qwen":
return "/v0/management/qwen-auth-url"
default:
return ""
}
st, _ = desktopctl.StatusFor(configPath)
if strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy base URL not available")
}
return desktopctl.OpenBrowser(st.BaseURL + "/proxypilot.html")
}
func shorten(s string, max int) string {
@@ -470,8 +487,8 @@ type authURLResponse struct {
Error string `json:"error"`
}
func startOAuthFlow(configPath string, endpointPath string) error {
st, _ := desktopctl.StatusFor(configPath)
func startOAuthFlow(engine *EmbeddedEngine, endpointPath string) error {
st := engine.Status()
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
@@ -511,8 +528,8 @@ func startOAuthFlow(configPath string, endpointPath string) error {
return openOAuthURL(out.URL, private)
}
func copyDiagnosticsToClipboard(configPath string) error {
st, _ := desktopctl.StatusFor(configPath)
func copyDiagnosticsToClipboard(engine *EmbeddedEngine) error {
st := engine.Status()
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
@@ -588,7 +605,7 @@ func findEdge() (string, error) {
return "", fmt.Errorf("msedge.exe not found")
}
func autostartCommand(repoRoot, configPath, exePath string) (string, error) {
func autostartCommand(repoRoot, configPath string) (string, error) {
exe, err := os.Executable()
if err == nil && strings.TrimSpace(exe) != "" {
exe = filepath.Clean(exe)
@@ -598,23 +615,19 @@ func autostartCommand(repoRoot, configPath, exePath string) (string, error) {
if exe == "" {
return "", fmt.Errorf("unable to resolve tray executable path")
}
args := make([]string, 0, 6)
args := make([]string, 0, 4)
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return quoteWindowsCommand(exe, args), nil
}
func applyDefaults(repoRoot, configPath, exePath string) (string, string, string) {
func applyDefaults(repoRoot, configPath string) (string, string) {
repoRoot = strings.TrimSpace(repoRoot)
configPath = strings.TrimSpace(configPath)
exePath = strings.TrimSpace(exePath)
exe, _ := os.Executable()
exeDir := ""
@@ -640,17 +653,7 @@ func applyDefaults(repoRoot, configPath, exePath string) (string, string, string
ensureConfig(configPath)
}
if exePath == "" && exeDir != "" {
for _, name := range []string{"proxypilot-engine.exe", "cliproxyapi-latest.exe"} {
cand := filepath.Join(exeDir, name)
if _, err := os.Stat(cand); err == nil {
exePath = cand
break
}
}
}
return repoRoot, configPath, exePath
return repoRoot, configPath
}
func ensureConfig(configPath string) {
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
{
"FixedFileInfo": {
"FileVersion": {
"Major": 0,
"Minor": 1,
"Patch": 6,
"Build": 0
},
"ProductVersion": {
"Major": 0,
"Minor": 1,
"Patch": 6,
"Build": 0
},
"FileFlagsMask": "3f",
"FileFlags ": "00",
"FileOS": "040004",
"FileType": "01",
"FileSubType": "00"
},
"StringFileInfo": {
"Comments": "Local AI Proxy with Embedded Engine",
"CompanyName": "ProxyPilot",
"FileDescription": "ProxyPilot - Single Binary Desktop App",
"FileVersion": "0.1.6",
"InternalName": "ProxyPilot",
"LegalCopyright": "MIT License",
"OriginalFilename": "ProxyPilot.exe",
"ProductName": "ProxyPilot",
"ProductVersion": "0.1.6"
},
"VarFileInfo": {
"Translation": {
"LangID": "0409",
"CharsetID": "04B0"
}
},
"IconPath": "../../static/icon.ico",
"ManifestPath": ""
}
+101
View File
@@ -0,0 +1,101 @@
# ProxyPilot Installer Build Script
# This script builds the installer with embedded UI and application files.
param(
[string]$OutputPath = ".\dist\ProxyPilotInstaller.exe",
[string]$ProxyPilotExe = ".\dist\ProxyPilot.exe",
[switch]$SkipUI
)
$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Split-Path -Parent (Split-Path -Parent $scriptDir)
Write-Host "Building ProxyPilot Installer..." -ForegroundColor Cyan
# Step 1: Build the installer UI (if not skipped)
if (-not $SkipUI) {
Write-Host "Building installer UI..." -ForegroundColor Yellow
Push-Location "$repoRoot\installer-ui"
try {
npm install
npm run build
}
finally {
Pop-Location
}
# Copy built UI to cmd/installer/ui
Write-Host "Copying UI assets..." -ForegroundColor Yellow
$uiSrcDir = "$repoRoot\installer-ui\dist"
$uiDstDir = "$scriptDir\ui"
if (Test-Path $uiDstDir) {
Remove-Item -Recurse -Force $uiDstDir
}
Copy-Item -Recurse $uiSrcDir $uiDstDir
}
# Step 2: Copy bundle files
Write-Host "Preparing bundle files..." -ForegroundColor Yellow
$bundleDir = "$scriptDir\bundle"
# Ensure bundle directory exists
if (-not (Test-Path $bundleDir)) {
New-Item -ItemType Directory -Path $bundleDir | Out-Null
}
# Copy ProxyPilot.exe
if (Test-Path $ProxyPilotExe) {
Copy-Item $ProxyPilotExe "$bundleDir\ProxyPilot.exe" -Force
Write-Host " Copied ProxyPilot.exe" -ForegroundColor Green
} else {
Write-Host " Warning: ProxyPilot.exe not found at $ProxyPilotExe" -ForegroundColor Yellow
}
# Copy config.example.yaml
$configExample = "$repoRoot\config.example.yaml"
if (Test-Path $configExample) {
Copy-Item $configExample "$bundleDir\config.example.yaml" -Force
Write-Host " Copied config.example.yaml" -ForegroundColor Green
}
# Copy icons
$iconIco = "$repoRoot\static\icon.ico"
$iconPng = "$repoRoot\static\icon.png"
if (Test-Path $iconIco) {
Copy-Item $iconIco "$bundleDir\icon.ico" -Force
Write-Host " Copied icon.ico" -ForegroundColor Green
}
if (Test-Path $iconPng) {
Copy-Item $iconPng "$bundleDir\icon.png" -Force
Write-Host " Copied icon.png" -ForegroundColor Green
}
# Step 3: Build the installer executable
Write-Host "Building installer executable..." -ForegroundColor Yellow
$outputDir = Split-Path -Parent $OutputPath
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir | Out-Null
}
Push-Location $repoRoot
try {
# Build with Windows GUI subsystem (no console window)
$env:GOOS = "windows"
$env:GOARCH = "amd64"
go build -ldflags="-s -w -H=windowsgui" -o $OutputPath ./cmd/installer
}
finally {
Pop-Location
}
if (Test-Path $OutputPath) {
$size = (Get-Item $OutputPath).Length / 1MB
Write-Host "Build complete: $OutputPath ($([math]::Round($size, 2)) MB)" -ForegroundColor Green
} else {
Write-Host "Build failed: Output file not created" -ForegroundColor Red
exit 1
}
+274
View File
@@ -0,0 +1,274 @@
# Server host/interface to bind to. Default is empty ("") to bind all interfaces (IPv4 + IPv6).
# Use "127.0.0.1" or "localhost" to restrict access to local machine only.
host: ""
# Server port
port: 8317
# TLS settings for HTTPS. When enabled, the server listens with the provided certificate and key.
tls:
enable: false
cert: ""
key: ""
# Management API settings
remote-management:
# Whether to allow remote (non-localhost) management access.
# When false, only localhost can access management endpoints (a key is still required).
allow-remote: false
# Management key. If a plaintext value is provided here, it will be hashed on startup.
# All management requests (even from localhost) require this key.
# Leave empty to disable the Management API entirely (404 for all /v0/management routes).
secret-key: "$2a$10$iphjVa6f4T/FARz4e/edtOHvdoxTbE4tv/9mS0ebvDg/C8fEbPtgq"
# Disable the bundled management control panel asset download and HTTP route when true.
disable-control-panel: false
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL.
panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
# Authentication directory (supports ~ for home directory)
auth-dir: "~/.cli-proxy-api"
# Long-running agent harness files root directory (feature_list.json, claude-progress.txt).
# The harness guides AI agents through structured, incremental development workflows.
# - INITIALIZER mode: Creates feature list, progress log, and init.sh for new sessions
# - CODING mode: Forces one-feature-at-a-time workflow with verification
# Leave empty to use session-based memory storage (recommended).
# Set to a specific directory to share harness files across sessions.
# harness-root-dir: ""
#
# Environment variables:
# CLIPROXY_HARNESS_ENABLED=true/false # Enable/disable harness injection (default: true)
# API keys for authentication
api-keys:
- "local-dev-key"
# Enable debug logging
debug: false
# When true, disable high-overhead HTTP middleware features to reduce per-request memory usage under high concurrency.
commercial-mode: false
# Open OAuth URLs in incognito/private browser mode.
# Useful when you want to login with a different account without logging out from your current session.
# Default: false (but Kiro auth defaults to true for multi-account support)
incognito-browser: true
# When true, write application logs to rotating files instead of stdout
logging-to-file: false
# Maximum total size (MB) of log files under the logs directory. When exceeded, the oldest log
# files are deleted until within the limit. Set to 0 to disable.
logs-max-total-size-mb: 0
# When false, disable in-memory usage statistics aggregation
usage-statistics-enabled: false
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
proxy-url: ""
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).
force-model-prefix: false
# Number of times to retry a request. Retries will occur if the HTTP response code is 403, 408, 500, 502, 503, or 504.
request-retry: 3
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.
max-retry-interval: 30
# Quota exceeded behavior
quota-exceeded:
switch-project: true # Whether to automatically switch to another project when a quota is exceeded
switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
# Routing strategy for selecting credentials when multiple match.
routing:
strategy: "round-robin" # round-robin (default), fill-first, usage-aware
# Global model mappings - route friendly names to actual models across all providers.
# These mappings are checked before per-credential model mappings.
# global-model-mappings:
# - from: "smart" # Client requests "smart"
# to: "claude-opus-4-5-20251101" # Routes to Claude Opus
# - from: "rush"
# to: "claude-haiku-4-5-20251001" # Routes to Claude Haiku (fast)
# - from: "think"
# to: "claude-opus-4-5-thinking" # Routes to thinking model
# - from: "gemini-pro"
# to: "gemini-2.5-pro-preview"
# provider: "gemini" # Only applies to Gemini provider
# - from: "cheap"
# to: "gpt-4o-mini"
# provider: "codex"
# enabled: false # Disabled mapping (kept for reference)
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
# Streaming behavior (SSE keep-alives, bootstrap retries, chunk sizing).
# streaming:
# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.
# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
# max-chunk-size: 65536 # Default: 65536 (64KB). Max bytes per response chunk. 0 disables limiting.
# Context compression behavior (Factory.ai-style structured summarization).
# Uses LLM to generate intelligent summaries with structured sections when context
# exceeds the threshold. Summaries include: session intent, file modifications,
# decisions made, next steps, and technical details.
# compression:
# enabled: true # Default: true. Enable LLM-based structured summarization.
# threshold-percent: 0.75 # Default: 0.75. Trigger compression at 75% of context window.
# max-summary-tokens: 2000 # Default: 2000. Maximum tokens for generated summaries.
# summarization-timeout-seconds: 30 # Default: 30. Timeout for LLM summarization calls.
# fallback-to-regex: true # Default: true. Use regex-based summary when LLM fails.
# Response caching - cache identical API responses to reduce upstream calls.
# response-cache:
# enabled: true
# max-size: 1000 # Max cached responses
# ttl-seconds: 300 # 5 minutes
# exclude-models: # Don't cache these models
# - "*-thinking"
# - "o1-*"
# Prompt caching - track system prompts for analytics.
# prompt-cache:
# enabled: true
# max-size: 500
# ttl-seconds: 1800 # 30 minutes
# Token-aware compression (proactive trimming based on model context window).
# Prevents "prompt too long" errors by trimming before hitting model limits.
# Environment variables:
# CLIPROXY_TOKEN_AWARE_ENABLED=true # Default: true. Enable token-based compression.
# CLIPROXY_COMPRESSION_THRESHOLD=0.75 # Default: 0.75. Trim at 75% of context window.
# CLIPROXY_RESERVE_TOKENS=8192 # Default: 8192. Tokens reserved for model output.
# Gemini API keys
# gemini-api-key:
# - api-key: "AIzaSy...01"
# prefix: "test" # optional: require calls like "test/gemini-3-pro-preview" to target this credential
# base-url: "https://generativelanguage.googleapis.com"
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080"
# excluded-models:
# - "gemini-2.5-pro" # exclude specific models from this provider (exact match)
# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)
# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview, gemini-3-flash-preview)
# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)
# - api-key: "AIzaSy...02"
# Codex API keys
# codex-api-key:
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/gpt-5-codex" to target this credential
# base-url: "https://www.example.com" # use the custom codex API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "gpt-5-codex" # upstream model name
# alias: "codex-latest" # client alias mapped to the upstream model
# excluded-models:
# - "gpt-5.2" # exclude specific models (exact match)
# - "gpt-5-*" # wildcard matching prefix (e.g. gpt-5-medium, gpt-5-codex)
# - "*-mini" # wildcard matching suffix (e.g. gpt-5-codex-mini)
# - "*codex*" # wildcard matching substring (e.g. gpt-5-codex-low)
# Claude API keys
# claude-api-key:
# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/claude-sonnet-latest" to target this credential
# base-url: "https://www.example.com" # use the custom claude API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "claude-sonnet-4-5-20250929" # upstream model name
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
# excluded-models:
# - "claude-opus-4-5-20251101" # exclude specific models (exact match)
# - "claude-4-*" # wildcard matching prefix (e.g. claude-sonnet-4-5-20250929)
# - "*-thinking" # wildcard matching suffix (e.g. claude-opus-4-5-thinking)
# - "*haiku*" # wildcard matching substring (e.g. claude-haiku-4-5-20251001)
# Kiro (AWS CodeWhisperer) configuration
# kiro-key:
# - token-file: "~/.aws/sso/cache/kiro-auth-token.json"
# region: "us-east-1"
# proxy-url: "socks5://proxy.example.com:1080"
# agent-task-type: "dev"
# excluded-models:
# - "kiro-claude-haiku"
# Kiro (AWS CodeWhisperer) configuration
# Note: Kiro API currently only operates in us-east-1 region
#kiro:
# - token-file: "~/.aws/sso/cache/kiro-auth-token.json" # path to Kiro token file
# agent-task-type: "" # optional: "vibe" or empty (API default)
# - access-token: "aoaAAAAA..." # or provide tokens directly
# refresh-token: "aorAAAAA..."
# profile-arn: "arn:aws:codewhisperer:us-east-1:..."
# proxy-url: "socks5://proxy.example.com:1080" # optional: proxy override
# OpenAI compatibility providers
# openai-compatibility:
# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.
# prefix: "test" # optional: require calls like "test/kimi-k2" to target this provider's credentials
# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.
# headers:
# X-Custom-Header: "custom-value"
# api-key-entries:
# - api-key: "sk-or-v1-...b780"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# - api-key: "sk-or-v1-...b781" # without proxy-url
# models: # The models supported by the provider.
# - name: "moonshotai/kimi-k2:free" # The actual model name.
# alias: "kimi-k2" # The alias used in the API.
# Vertex API keys (Vertex-compatible endpoints, use API key + base URL)
# vertex-api-key:
# - api-key: "vk-123..." # x-goog-api-key header
# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential
# base-url: "https://example.com/api" # e.g. https://zenmux.ai/api
# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override
# headers:
# X-Custom-Header: "custom-value"
# models: # optional: map aliases to upstream model names
# - name: "gemini-2.5-flash" # upstream model name
# alias: "vertex-flash" # client-visible alias
# - name: "gemini-1.5-pro"
# alias: "vertex-pro"
# OAuth provider excluded models
# oauth-excluded-models:
# gemini-cli:
# - "gemini-2.5-pro" # exclude specific models (exact match)
# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)
# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview, gemini-3-flash-preview)
# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)
# vertex:
# - "gemini-3-pro-preview"
# - "gemini-3-flash-preview"
# aistudio:
# - "gemini-3-pro-preview"
# antigravity:
# - "gemini-3-pro-preview"
# claude:
# - "claude-3-5-haiku-20241022"
# codex:
# - "gpt-5-codex-mini"
# qwen:
# - "vision-model"
# kiro:
# - "kiro-claude-haiku"
# Optional payload configuration
# payload:
# default: # Default rules only set parameters when they are missing in the payload.
# - models:
# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")
# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex
# params: # JSON path (gjson/sjson syntax) -> value
# "generationConfig.thinkingConfig.thinkingBudget": 32768
# override: # Override rules always set parameters, overwriting any existing values.
# - models:
# - name: "gpt-*" # Supports wildcards (e.g., "gpt-*")
# protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex
# params: # JSON path (gjson/sjson syntax) -> value
# "reasoning.effort": "high"
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+19
View File
@@ -0,0 +1,19 @@
//go:build windows
package main
import (
"embed"
)
// embeddedUI contains the built installer UI from installer-ui/dist.
// The ui directory should contain index.html and any other assets.
//
//go:embed all:ui
var embeddedUI embed.FS
// embeddedBundle contains the files to install.
// These are embedded during the build process.
//
//go:embed bundle/ProxyPilot.exe bundle/config.example.yaml bundle/icon.ico bundle/icon.png
var embeddedBundle embed.FS
+196
View File
@@ -0,0 +1,196 @@
//go:build windows
package main
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
// InstallConfig holds the configuration for the installation process.
type InstallConfig struct {
// InstallDir is the target installation directory.
// Defaults to %LOCALAPPDATA%\ProxyPilot.
InstallDir string
// CreateDesktopShortcut indicates whether to create a Desktop shortcut.
CreateDesktopShortcut bool
// EnableAutostart indicates whether to register the app for autostart.
EnableAutostart bool
}
// ProgressCallback is called during file copy operations to report progress.
type ProgressCallback func(progress int, status string)
// bundleFiles is the list of files to extract from the embedded bundle.
var bundleFiles = []struct {
src string // Path within embeddedBundle.
dst string // Destination filename.
size int64 // Approximate size for progress calculation.
}{
{"bundle/ProxyPilot.exe", "ProxyPilot.exe", 0},
{"bundle/config.example.yaml", "config.example.yaml", 0},
{"bundle/icon.ico", "icon.ico", 0},
{"bundle/icon.png", "icon.png", 0},
}
// CopyFiles extracts the embedded bundle files to the installation directory.
func CopyFiles(config *InstallConfig, progress ProgressCallback) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
// Ensure the installation directory exists.
if err := os.MkdirAll(config.InstallDir, 0755); err != nil {
return fmt.Errorf("failed to create install directory: %w", err)
}
// Calculate total number of files for progress.
totalFiles := len(bundleFiles)
copiedFiles := 0
for _, file := range bundleFiles {
dstPath := filepath.Join(config.InstallDir, file.dst)
if progress != nil {
progress((copiedFiles*100)/totalFiles, fmt.Sprintf("Copying %s...", file.dst))
}
if err := extractEmbeddedFile(file.src, dstPath); err != nil {
return fmt.Errorf("failed to copy %s: %w", file.dst, err)
}
copiedFiles++
}
// Create config.yaml from config.example.yaml if it doesn't exist.
configPath := filepath.Join(config.InstallDir, "config.yaml")
examplePath := filepath.Join(config.InstallDir, "config.example.yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if _, err := os.Stat(examplePath); err == nil {
if err := copyFile(examplePath, configPath); err != nil {
// Non-fatal: user can create config manually.
_ = err
} else if progress != nil {
progress(95, "Created default configuration")
}
}
}
if progress != nil {
progress(100, "All files copied successfully")
}
return nil
}
// extractEmbeddedFile extracts a file from the embedded bundle to the destination path.
func extractEmbeddedFile(src, dst string) error {
// Open the embedded file.
srcFile, err := embeddedBundle.Open(src)
if err != nil {
return fmt.Errorf("failed to open embedded file %s: %w", src, err)
}
defer srcFile.Close()
// Get file info for permissions.
info, err := srcFile.(fs.File).Stat()
if err != nil {
return fmt.Errorf("failed to stat embedded file: %w", err)
}
// Create destination directory if needed.
dstDir := filepath.Dir(dst)
if err := os.MkdirAll(dstDir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %w", dstDir, err)
}
// Create the destination file.
dstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode())
if err != nil {
return fmt.Errorf("failed to create file %s: %w", dst, err)
}
defer dstFile.Close()
// Copy the content.
if _, err := io.Copy(dstFile, srcFile); err != nil {
return fmt.Errorf("failed to write file %s: %w", dst, err)
}
return nil
}
// copyFile copies a file from src to dst.
func copyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
return err
}
return nil
}
// Cleanup removes all installed files on failure.
func Cleanup(config *InstallConfig) error {
if config.InstallDir == "" {
return nil
}
// Remove autostart registration.
_ = UnregisterAutostart(config)
// Remove uninstall registration.
_ = UnregisterUninstall()
// Remove shortcuts.
_ = RemoveShortcuts(config)
// Remove the installation directory.
// Only remove if it's under LocalAppData to prevent accidental deletion.
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData != "" && filepath.HasPrefix(config.InstallDir, localAppData) {
return os.RemoveAll(config.InstallDir)
}
return nil
}
// RemoveShortcuts removes all created shortcuts.
func RemoveShortcuts(config *InstallConfig) error {
var lastErr error
// Remove Start Menu shortcut.
startMenuPath := getStartMenuPath()
if startMenuPath != "" {
shortcutPath := filepath.Join(startMenuPath, appName+".lnk")
if err := os.Remove(shortcutPath); err != nil && !os.IsNotExist(err) {
lastErr = err
}
}
// Remove Desktop shortcut.
desktopPath := getDesktopPath()
if desktopPath != "" {
shortcutPath := filepath.Join(desktopPath, appName+".lnk")
if err := os.Remove(shortcutPath); err != nil && !os.IsNotExist(err) {
lastErr = err
}
}
return lastErr
}
+315
View File
@@ -0,0 +1,315 @@
//go:build windows
package main
import (
"encoding/json"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"unsafe"
"github.com/jchv/go-webview2"
)
const (
windowWidth = 500
windowHeight = 400
appName = "ProxyPilot"
)
var (
// assetServerURL holds the local HTTP server URL for serving embedded UI assets.
assetServerURL string
// webviewInstance is the global WebView2 instance for window control.
webviewInstance webview2.WebView
)
func main() {
// Lock this goroutine to an OS thread - required for Windows COM/GUI operations.
runtime.LockOSThread()
// Start embedded asset server for the installer UI.
assetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
_ = messageBox("ProxyPilot Installer", "Failed to start asset server: "+err.Error())
os.Exit(1)
}
assetServerURL = "http://" + assetLn.Addr().String()
go func() {
fsys, err := fs.Sub(embeddedUI, "ui")
if err != nil {
return
}
_ = http.Serve(assetLn, http.FileServer(http.FS(fsys)))
}()
// Create frameless WebView2 window with dark theme.
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: false,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ProxyPilot Installer",
Width: uint(windowWidth),
Height: uint(windowHeight),
Center: true,
IconId: 1, // Use embedded icon from resource.syso if present.
},
})
if w == nil {
_ = messageBox("ProxyPilot Installer", "Failed to initialize WebView2.\n\nPlease ensure WebView2 Runtime is installed.")
os.Exit(1)
}
defer w.Destroy()
webviewInstance = w
// Bind Go functions to JavaScript.
bindInstallerFunctions(w)
// Navigate to the embedded UI.
target := assetServerURL + "/index.html"
w.Navigate(target)
// Apply dark window chrome and frameless styling after navigation.
w.Dispatch(func() {
applyDarkWindowChrome(w)
})
w.Run()
}
// bindInstallerFunctions binds all Go functions to the JavaScript window.installer object.
func bindInstallerFunctions(w webview2.WebView) {
// Create the installer namespace.
w.Init(`window.installer = {};`)
// Bind startInstall - starts the installation process.
_ = w.Bind("installer_startInstall", func(optionsJSON string) (map[string]any, error) {
var options struct {
Desktop bool `json:"desktop"`
Autostart bool `json:"autostart"`
}
if err := json.Unmarshal([]byte(optionsJSON), &options); err != nil {
options.Desktop = false
options.Autostart = true
}
config := &InstallConfig{
CreateDesktopShortcut: options.Desktop,
EnableAutostart: options.Autostart,
}
// Run installation in a goroutine to not block the UI.
go func() {
if err := runInstallation(w, config); err != nil {
callSetProgress(w, -1, "Installation failed: "+err.Error())
}
}()
return map[string]any{"started": true}, nil
})
// Bind launch - launches the installed application.
_ = w.Bind("installer_launch", func() error {
installDir := getInstallDir()
exePath := filepath.Join(installDir, "ProxyPilot.exe")
if _, err := os.Stat(exePath); err != nil {
return fmt.Errorf("ProxyPilot.exe not found at %s", exePath)
}
cmd := exec.Command(exePath)
cmd.Dir = installDir
return cmd.Start()
})
// Bind close - closes the installer window.
_ = w.Bind("installer_close", func() error {
w.Dispatch(func() {
w.Terminate()
})
return nil
})
// Bind minimize - minimizes the window.
_ = w.Bind("installer_minimize", func() error {
w.Dispatch(func() {
minimizeWindow(w)
})
return nil
})
// Bind getInstallPath - returns the default installation path.
_ = w.Bind("installer_getInstallPath", func() (string, error) {
return getInstallDir(), nil
})
// Initialize the window.installer JavaScript API.
w.Init(`
window.installer.startInstall = function(options) {
return new Promise((resolve, reject) => {
installer_startInstall(JSON.stringify(options || {}))
.then(resolve)
.catch(reject);
});
};
window.installer.launch = installer_launch;
window.installer.close = installer_close;
window.installer.minimize = installer_minimize;
window.installer.getInstallPath = installer_getInstallPath;
`)
}
// runInstallation performs the complete installation process with progress reporting.
func runInstallation(w webview2.WebView, config *InstallConfig) error {
// Initialize install configuration with defaults.
config.InstallDir = getInstallDir()
// Step 1: Prepare installation directory (10%).
callSetProgress(w, 5, "Preparing installation directory...")
if err := os.MkdirAll(config.InstallDir, 0755); err != nil {
return fmt.Errorf("failed to create install directory: %w", err)
}
callSetProgress(w, 10, "Installation directory ready")
// Step 2: Copy files (10% - 60%).
callSetProgress(w, 15, "Copying application files...")
if err := CopyFiles(config, func(progress int, status string) {
// Map 0-100 to 15-60.
mappedProgress := 15 + (progress * 45 / 100)
callSetProgress(w, mappedProgress, status)
}); err != nil {
return fmt.Errorf("failed to copy files: %w", err)
}
callSetProgress(w, 60, "Files copied successfully")
// Step 3: Create shortcuts (60% - 80%).
callSetProgress(w, 65, "Creating shortcuts...")
if err := CreateShortcuts(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 70, "Warning: Some shortcuts could not be created")
} else {
callSetProgress(w, 80, "Shortcuts created")
}
// Step 4: Register autostart if enabled (80% - 90%).
if config.EnableAutostart {
callSetProgress(w, 85, "Configuring autostart...")
if err := RegisterAutostart(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 88, "Warning: Autostart could not be configured")
} else {
callSetProgress(w, 90, "Autostart configured")
}
} else {
callSetProgress(w, 90, "Skipping autostart configuration")
}
// Step 5: Register uninstaller (90% - 100%).
callSetProgress(w, 92, "Registering application...")
if err := RegisterUninstall(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 95, "Warning: Uninstall registration incomplete")
} else {
callSetProgress(w, 98, "Application registered")
}
callSetProgress(w, 100, "Installation complete!")
return nil
}
// callSetProgress calls window.setProgress in the WebView.
func callSetProgress(w webview2.WebView, percent int, statusText string) {
// Escape the status text for JavaScript.
escaped := strings.ReplaceAll(statusText, "\\", "\\\\")
escaped = strings.ReplaceAll(escaped, "'", "\\'")
escaped = strings.ReplaceAll(escaped, "\n", "\\n")
js := fmt.Sprintf("if(window.setProgress){window.setProgress(%d,'%s');}", percent, escaped)
w.Dispatch(func() {
w.Eval(js)
})
}
// getInstallDir returns the default installation directory.
func getInstallDir() string {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
home, _ := os.UserHomeDir()
localAppData = filepath.Join(home, "AppData", "Local")
}
return filepath.Join(localAppData, appName)
}
// applyDarkWindowChrome applies dark mode window chrome styling.
func applyDarkWindowChrome(w webview2.WebView) {
hwnd := getWindowHandle(w)
if hwnd == 0 {
return
}
// Enable dark mode for the window frame.
dwmapi := syscall.NewLazyDLL("dwmapi.dll")
dwmSetWindowAttribute := dwmapi.NewProc("DwmSetWindowAttribute")
// DWMWA_USE_IMMERSIVE_DARK_MODE = 20.
const DWMWA_USE_IMMERSIVE_DARK_MODE = 20
darkMode := int32(1)
_, _, _ = dwmSetWindowAttribute.Call(
hwnd,
uintptr(DWMWA_USE_IMMERSIVE_DARK_MODE),
uintptr(unsafe.Pointer(&darkMode)),
unsafe.Sizeof(darkMode),
)
// DWMWA_CAPTION_COLOR = 35 (Windows 11).
const DWMWA_CAPTION_COLOR = 35
captionColor := uint32(0x001E1E1E) // Dark gray in BGR format.
_, _, _ = dwmSetWindowAttribute.Call(
hwnd,
uintptr(DWMWA_CAPTION_COLOR),
uintptr(unsafe.Pointer(&captionColor)),
unsafe.Sizeof(captionColor),
)
}
// getWindowHandle retrieves the HWND for the WebView window.
func getWindowHandle(w webview2.WebView) uintptr {
// The go-webview2 library provides a Window() method that returns the HWND.
return uintptr(w.Window())
}
// minimizeWindow minimizes the WebView window.
func minimizeWindow(w webview2.WebView) {
hwnd := getWindowHandle(w)
if hwnd == 0 {
return
}
user32 := syscall.NewLazyDLL("user32.dll")
showWindow := user32.NewProc("ShowWindow")
const SW_MINIMIZE = 6
_, _, _ = showWindow.Call(hwnd, uintptr(SW_MINIMIZE))
}
// messageBox displays a Windows message box.
func messageBox(title, text string) error {
user32 := syscall.NewLazyDLL("user32.dll")
proc := user32.NewProc("MessageBoxW")
t, _ := syscall.UTF16PtrFromString(title)
m, _ := syscall.UTF16PtrFromString(text)
// MB_OK | MB_ICONERROR.
_, _, err := proc.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), 0x00000000|0x00000010)
if err == syscall.Errno(0) {
return nil
}
return err
}
+179
View File
@@ -0,0 +1,179 @@
//go:build windows
package main
import (
"fmt"
"path/filepath"
"golang.org/x/sys/windows/registry"
)
const (
// Registry key paths.
autostartKeyPath = `Software\Microsoft\Windows\CurrentVersion\Run`
uninstallKeyPath = `Software\Microsoft\Windows\CurrentVersion\Uninstall\` + appName
uninstallKeyBase = `Software\Microsoft\Windows\CurrentVersion\Uninstall`
// Application metadata.
appPublisher = "ProxyPilot"
appVersion = "1.0.0"
)
// RegisterAutostart adds the application to the Windows autostart registry.
func RegisterAutostart(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
key, _, err := registry.CreateKey(registry.CURRENT_USER, autostartKeyPath, registry.SET_VALUE)
if err != nil {
return fmt.Errorf("failed to open autostart registry key: %w", err)
}
defer key.Close()
// Add the application with quoted path to handle spaces.
if err := key.SetStringValue(appName, `"`+exePath+`"`); err != nil {
return fmt.Errorf("failed to set autostart value: %w", err)
}
return nil
}
// UnregisterAutostart removes the application from Windows autostart.
func UnregisterAutostart(config *InstallConfig) error {
key, err := registry.OpenKey(registry.CURRENT_USER, autostartKeyPath, registry.SET_VALUE)
if err != nil {
// Key doesn't exist or can't be opened; nothing to remove.
return nil
}
defer key.Close()
if err := key.DeleteValue(appName); err != nil {
// Value doesn't exist; that's fine.
if err == registry.ErrNotExist {
return nil
}
return fmt.Errorf("failed to remove autostart value: %w", err)
}
return nil
}
// IsAutostartEnabled checks if the application is registered for autostart.
func IsAutostartEnabled() bool {
key, err := registry.OpenKey(registry.CURRENT_USER, autostartKeyPath, registry.QUERY_VALUE)
if err != nil {
return false
}
defer key.Close()
_, _, err = key.GetStringValue(appName)
return err == nil
}
// RegisterUninstall registers the application in Add/Remove Programs.
func RegisterUninstall(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
iconPath := filepath.Join(config.InstallDir, "icon.ico")
// Create the uninstall key.
key, _, err := registry.CreateKey(registry.CURRENT_USER, uninstallKeyPath, registry.SET_VALUE)
if err != nil {
return fmt.Errorf("failed to create uninstall registry key: %w", err)
}
defer key.Close()
// Set the required values.
values := map[string]string{
"DisplayName": appName,
"DisplayVersion": appVersion,
"Publisher": appPublisher,
"InstallLocation": config.InstallDir,
"DisplayIcon": iconPath,
"UninstallString": `"` + exePath + `" --uninstall`,
"QuietUninstallString": `"` + exePath + `" --uninstall --quiet`,
}
for name, value := range values {
if err := key.SetStringValue(name, value); err != nil {
return fmt.Errorf("failed to set %s: %w", name, err)
}
}
// Set NoModify and NoRepair flags.
if err := key.SetDWordValue("NoModify", 1); err != nil {
return fmt.Errorf("failed to set NoModify: %w", err)
}
if err := key.SetDWordValue("NoRepair", 1); err != nil {
return fmt.Errorf("failed to set NoRepair: %w", err)
}
// Estimate the installed size in KB.
estimatedSize := uint32(40 * 1024) // ~40 MB estimate.
if err := key.SetDWordValue("EstimatedSize", estimatedSize); err != nil {
// Non-fatal.
_ = err
}
return nil
}
// UnregisterUninstall removes the application from Add/Remove Programs.
func UnregisterUninstall() error {
// Delete the entire uninstall key.
if err := registry.DeleteKey(registry.CURRENT_USER, uninstallKeyPath); err != nil {
if err == registry.ErrNotExist {
return nil
}
return fmt.Errorf("failed to delete uninstall registry key: %w", err)
}
return nil
}
// GetInstallPathFromRegistry retrieves the installation path from the registry.
// Returns an empty string if not found.
func GetInstallPathFromRegistry() string {
key, err := registry.OpenKey(registry.CURRENT_USER, uninstallKeyPath, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer key.Close()
path, _, err := key.GetStringValue("InstallLocation")
if err != nil {
return ""
}
return path
}
// SetRegistryString is a helper to set a string value in the registry.
func SetRegistryString(keyPath, valueName, value string) error {
key, _, err := registry.CreateKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE)
if err != nil {
return err
}
defer key.Close()
return key.SetStringValue(valueName, value)
}
// DeleteRegistryValue is a helper to delete a registry value.
func DeleteRegistryValue(keyPath, valueName string) error {
key, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE)
if err != nil {
return err
}
defer key.Close()
return key.DeleteValue(valueName)
}
// DeleteRegistryKey is a helper to delete a registry key.
func DeleteRegistryKey(keyPath string) error {
return registry.DeleteKey(registry.CURRENT_USER, keyPath)
}
+261
View File
@@ -0,0 +1,261 @@
//go:build windows
package main
import (
"fmt"
"os"
"path/filepath"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
// GUID for IShellLinkW.
var (
CLSID_ShellLink = windows.GUID{
Data1: 0x00021401,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
IID_IShellLinkW = windows.GUID{
Data1: 0x000214F9,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
IID_IPersistFile = windows.GUID{
Data1: 0x0000010B,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
)
// IShellLinkW virtual table.
type IShellLinkWVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetPath uintptr
GetIDList uintptr
SetIDList uintptr
GetDescription uintptr
SetDescription uintptr
GetWorkingDirectory uintptr
SetWorkingDirectory uintptr
GetArguments uintptr
SetArguments uintptr
GetHotkey uintptr
SetHotkey uintptr
GetShowCmd uintptr
SetShowCmd uintptr
GetIconLocation uintptr
SetIconLocation uintptr
SetRelativePath uintptr
Resolve uintptr
SetPath uintptr
}
type IShellLinkW struct {
vtbl *IShellLinkWVtbl
}
// IPersistFile virtual table.
type IPersistFileVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetClassID uintptr
IsDirty uintptr
Load uintptr
Save uintptr
SaveCompleted uintptr
GetCurFile uintptr
}
type IPersistFile struct {
vtbl *IPersistFileVtbl
}
var (
ole32 = syscall.NewLazyDLL("ole32.dll")
coInitializeEx = ole32.NewProc("CoInitializeEx")
coCreateInstance = ole32.NewProc("CoCreateInstance")
coUninitialize = ole32.NewProc("CoUninitialize")
)
const (
COINIT_APARTMENTTHREADED = 0x2
CLSCTX_INPROC_SERVER = 0x1
)
// CreateShortcuts creates Start Menu and optionally Desktop shortcuts.
func CreateShortcuts(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
iconPath := filepath.Join(config.InstallDir, "icon.ico")
// Create Start Menu shortcut.
startMenuPath := getStartMenuPath()
if startMenuPath != "" {
shortcutPath := filepath.Join(startMenuPath, appName+".lnk")
if err := createShortcut(shortcutPath, exePath, config.InstallDir, iconPath, "ProxyPilot - AI Proxy Router"); err != nil {
return fmt.Errorf("failed to create Start Menu shortcut: %w", err)
}
}
// Create Desktop shortcut if requested.
if config.CreateDesktopShortcut {
desktopPath := getDesktopPath()
if desktopPath != "" {
shortcutPath := filepath.Join(desktopPath, appName+".lnk")
if err := createShortcut(shortcutPath, exePath, config.InstallDir, iconPath, "ProxyPilot - AI Proxy Router"); err != nil {
return fmt.Errorf("failed to create Desktop shortcut: %w", err)
}
}
}
return nil
}
// createShortcut creates a Windows .lnk shortcut file using COM.
func createShortcut(shortcutPath, targetPath, workingDir, iconPath, description string) error {
// Initialize COM.
hr, _, _ := coInitializeEx.Call(0, uintptr(COINIT_APARTMENTTHREADED))
if hr != 0 && hr != 1 { // S_OK or S_FALSE.
return fmt.Errorf("CoInitializeEx failed: 0x%X", hr)
}
defer coUninitialize.Call()
// Create IShellLink instance.
var shellLink *IShellLinkW
hr, _, _ = coCreateInstance.Call(
uintptr(unsafe.Pointer(&CLSID_ShellLink)),
0,
uintptr(CLSCTX_INPROC_SERVER),
uintptr(unsafe.Pointer(&IID_IShellLinkW)),
uintptr(unsafe.Pointer(&shellLink)),
)
if hr != 0 {
return fmt.Errorf("CoCreateInstance failed: 0x%X", hr)
}
// Set the target path.
targetPathW, _ := syscall.UTF16PtrFromString(targetPath)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetPath, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(targetPathW)))
if hr != 0 {
return fmt.Errorf("SetPath failed: 0x%X", hr)
}
// Set the working directory.
workingDirW, _ := syscall.UTF16PtrFromString(workingDir)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetWorkingDirectory, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(workingDirW)))
if hr != 0 {
return fmt.Errorf("SetWorkingDirectory failed: 0x%X", hr)
}
// Set the description.
descriptionW, _ := syscall.UTF16PtrFromString(description)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetDescription, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(descriptionW)))
if hr != 0 {
return fmt.Errorf("SetDescription failed: 0x%X", hr)
}
// Set the icon.
if iconPath != "" {
iconPathW, _ := syscall.UTF16PtrFromString(iconPath)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetIconLocation, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(iconPathW)), 0)
if hr != 0 {
// Non-fatal: continue without icon.
_ = hr
}
}
// Query for IPersistFile interface.
var persistFile *IPersistFile
hr, _, _ = syscall.SyscallN(
shellLink.vtbl.QueryInterface,
uintptr(unsafe.Pointer(shellLink)),
uintptr(unsafe.Pointer(&IID_IPersistFile)),
uintptr(unsafe.Pointer(&persistFile)),
)
if hr != 0 {
return fmt.Errorf("QueryInterface for IPersistFile failed: 0x%X", hr)
}
// Ensure the shortcut directory exists.
shortcutDir := filepath.Dir(shortcutPath)
if err := os.MkdirAll(shortcutDir, 0755); err != nil {
return fmt.Errorf("failed to create shortcut directory: %w", err)
}
// Save the shortcut.
shortcutPathW, _ := syscall.UTF16PtrFromString(shortcutPath)
hr, _, _ = syscall.SyscallN(persistFile.vtbl.Save, uintptr(unsafe.Pointer(persistFile)), uintptr(unsafe.Pointer(shortcutPathW)), 1)
if hr != 0 {
return fmt.Errorf("Save failed: 0x%X", hr)
}
// Release interfaces.
syscall.SyscallN(persistFile.vtbl.Release, uintptr(unsafe.Pointer(persistFile)))
syscall.SyscallN(shellLink.vtbl.Release, uintptr(unsafe.Pointer(shellLink)))
return nil
}
// getStartMenuPath returns the user's Start Menu Programs folder.
func getStartMenuPath() string {
// CSIDL_PROGRAMS = 0x0002.
path := getKnownFolderPath(0x0002)
if path != "" {
return path
}
// Fallback to constructing the path manually.
appData := os.Getenv("APPDATA")
if appData != "" {
return filepath.Join(appData, "Microsoft", "Windows", "Start Menu", "Programs")
}
return ""
}
// getDesktopPath returns the user's Desktop folder.
func getDesktopPath() string {
// CSIDL_DESKTOP = 0x0000.
path := getKnownFolderPath(0x0000)
if path != "" {
return path
}
// Fallback.
home, _ := os.UserHomeDir()
if home != "" {
return filepath.Join(home, "Desktop")
}
return ""
}
// getKnownFolderPath retrieves a known folder path using SHGetFolderPath.
func getKnownFolderPath(csidl int) string {
shell32 := syscall.NewLazyDLL("shell32.dll")
shGetFolderPath := shell32.NewProc("SHGetFolderPathW")
buf := make([]uint16, 260) // MAX_PATH.
hr, _, _ := shGetFolderPath.Call(
0,
uintptr(csidl),
0,
0,
uintptr(unsafe.Pointer(&buf[0])),
)
if hr != 0 {
return ""
}
return syscall.UTF16ToString(buf)
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+35
View File
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ProxyPilot Installer</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #0a0a0b;
}
</style>
<script type="module" crossorigin src="./assets/index-Ct7uoBdX.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DTO-I4cJ.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+8 -27
View File
@@ -125,10 +125,6 @@ func buildBinaries(repoRoot, binRoot string) error {
if runtime.GOOS != "windows" {
trayExe = filepath.Join(binRoot, "ProxyPilot")
}
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
if runtime.GOOS != "windows" {
uiExe = filepath.Join(binRoot, "ProxyPilotUI")
}
if err := run(repoRoot, "go", "build", "-o", proxyExe, "./cmd/server"); err != nil {
return err
@@ -143,13 +139,6 @@ func buildBinaries(repoRoot, binRoot string) error {
return err
}
}
if runtime.GOOS == "windows" {
if err := run(repoRoot, "go", "build", "-ldflags", "-H=windowsgui", "-o", uiExe, "./cmd/proxypilotui"); err != nil {
return err
}
} else {
// The UI binary is only supported on Windows for now; skip on other OSes.
}
if runtime.GOOS == "windows" {
ico := trayicon.ProxyPilotICO()
@@ -169,7 +158,6 @@ func packageZip(repoRoot, binRoot, distRoot string) error {
dst string
}{
{src: filepath.Join(binRoot, "ProxyPilot.exe"), dst: "ProxyPilot.exe"},
{src: filepath.Join(binRoot, "ProxyPilotUI.exe"), dst: "ProxyPilotUI.exe"},
{src: filepath.Join(binRoot, "ProxyPilot.ico"), dst: "ProxyPilot.ico"},
{src: filepath.Join(binRoot, "proxypilot-engine.exe"), dst: "proxypilot-engine.exe"},
// Back-compat: keep a copy under the legacy name for older launchers/scripts.
@@ -223,14 +211,10 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
// Payload files
mgrExe := filepath.Join(binRoot, "ProxyPilot.exe")
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
srvExe := filepath.Join(binRoot, "proxypilot-engine.exe")
if err := copyFile(mgrExe, filepath.Join(staging, "ProxyPilot.exe")); err != nil {
return err
}
if err := copyFile(uiExe, filepath.Join(staging, "ProxyPilotUI.exe")); err != nil {
return err
}
if err := copyFile(srvExe, filepath.Join(staging, "proxypilot-engine.exe")); err != nil {
return err
}
@@ -250,7 +234,6 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
"set \"DEST=%LOCALAPPDATA%\\ProxyPilot\"\r\n" +
"if not exist \"%DEST%\" mkdir \"%DEST%\" >nul 2>&1\r\n" +
"copy /Y \"%SRC%ProxyPilot.exe\" \"%DEST%\\ProxyPilot.exe\" >nul\r\n" +
"copy /Y \"%SRC%ProxyPilotUI.exe\" \"%DEST%\\ProxyPilotUI.exe\" >nul\r\n" +
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\proxypilot-engine.exe\" >nul\r\n" +
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\cliproxyapi-latest.exe\" >nul\r\n" +
"if exist \"%SRC%config.example.yaml\" copy /Y \"%SRC%config.example.yaml\" \"%DEST%\\config.example.yaml\" >nul\r\n" +
@@ -279,8 +262,8 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
}
// If config.example.yaml is absent, omit it to avoid IExpress build failure.
if _, err := os.Stat(filepath.Join(staging, "config.example.yaml")); errors.Is(err, os.ErrNotExist) {
sed = strings.ReplaceAll(sed, "%FILE3%=config.example.yaml\r\n", "")
sed = strings.ReplaceAll(sed, "FILE3=config.example.yaml\r\n", "")
sed = strings.ReplaceAll(sed, "%FILE2%=config.example.yaml\r\n", "")
sed = strings.ReplaceAll(sed, "FILE2=config.example.yaml\r\n", "")
}
if err := os.WriteFile(sedPath, []byte(sed), 0o644); err != nil {
return err
@@ -334,16 +317,14 @@ SourceFiles=SourceFiles
SourceFiles0=%s
[SourceFiles0]
%%FILE0%%=ProxyPilot.exe
%%FILE1%%=ProxyPilotUI.exe
%%FILE2%%=proxypilot-engine.exe
%%FILE3%%=config.example.yaml
%%FILE4%%=install.cmd
%%FILE1%%=proxypilot-engine.exe
%%FILE2%%=config.example.yaml
%%FILE3%%=install.cmd
[Strings]
FILE0=ProxyPilot.exe
FILE1=ProxyPilotUI.exe
FILE2=proxypilot-engine.exe
FILE3=config.example.yaml
FILE4=install.cmd
FILE1=proxypilot-engine.exe
FILE2=config.example.yaml
FILE3=install.cmd
`, outEsc, stagingEsc), nil
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -2,5 +2,5 @@ package assets
import "embed"
//go:embed index.html vite.svg assets/*
//go:embed index.html vite.svg logo.png assets/*
var FS embed.FS
+7 -1
View File
@@ -4,7 +4,13 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>webui</title>
<meta name="pp-mgmt-key" content="test123" />
<title>ProxyPilot</title>
<!-- Google Fonts preconnect for performance -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Google Fonts: Space Grotesk (display/headers), JetBrains Mono (code), IBM Plex Sans (body) -->
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index.css">
</head>
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

-753
View File
@@ -1,753 +0,0 @@
//go:build windows
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"unsafe"
"github.com/jchv/go-webview2"
"github.com/router-for-me/CLIProxyAPI/v6/cmd/proxypilotui/assets"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
)
func main() {
var repoRoot string
var configPath string
var exePath string
var url string
var standalone bool
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
flag.StringVar(&exePath, "exe", "", "Path to proxy engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
flag.StringVar(&url, "url", "", "Open a specific URL in-app (advanced)")
flag.BoolVar(&standalone, "standalone", false, "Run standalone UI without connecting to proxy server")
flag.Parse()
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
var assetServerURL string
if standalone {
// Start embedded asset server
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
_ = messageBox("ProxyPilot", "Failed to start asset server: "+err.Error())
os.Exit(1)
}
assetServerURL = "http://" + ln.Addr().String()
go func() {
fsys, _ := fs.Sub(assets.FS, ".")
http.Serve(ln, http.FileServer(http.FS(fsys)))
}()
} else {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
_, _ = desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
st, _ = desktopctl.StatusFor(configPath)
if st.Running {
break
}
time.Sleep(200 * time.Millisecond)
}
}
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
_ = messageBox("ProxyPilot", "Proxy is not running.\n\nClick Start in the ProxyPilot tray menu, then try again.")
os.Exit(1)
}
}
if strings.TrimSpace(url) == "" {
url = "control"
}
var target string
if standalone {
if strings.EqualFold(strings.TrimSpace(url), "control") {
target = assetServerURL + "/index.html"
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
target = strings.TrimSpace(url)
} else {
target = assetServerURL + "/index.html"
}
} else {
st, _ := desktopctl.StatusFor(configPath)
if strings.EqualFold(strings.TrimSpace(url), "control") {
target = st.BaseURL + "/proxypilot.html"
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
target = strings.TrimSpace(url)
}
}
// Prefer an in-app window (WebView2) so this behaves like a native dashboard app.
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: true,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ProxyPilot",
Width: 1200,
Height: 850,
Center: true,
},
})
if w == nil {
// Fallback: Edge app mode or default browser.
if target == "" {
if standalone {
target = assetServerURL + "/index.html"
} else {
st, _ := desktopctl.StatusFor(configPath)
target = st.BaseURL + "/proxypilot.html"
}
}
edge, err := findEdge()
if err != nil {
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", target).Start()
return
}
_ = exec.Command(edge, "--app="+target, "--window-size=1200,850", "--lang=en-US").Start()
return
}
defer w.Destroy()
w.SetSize(1200, 850, webview2.HintNone)
// Bindings used by the Control Center UI.
_ = w.Bind("pp_status", func() (map[string]any, error) {
cur, _ := desktopctl.StatusFor(configPath)
return map[string]any{
"running": cur.Running,
"port": cur.Port,
"thinking_port": cur.ThinkingPort,
"thinking_running": cur.ThinkingRunning,
"base_url": cur.BaseURL,
"last_error": cur.LastError,
}, nil
})
_ = w.Bind("pp_start", func() error {
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
return err
})
_ = w.Bind("pp_stop", func() error { return desktopctl.Stop(desktopctl.StopOptions{}) })
_ = w.Bind("pp_restart", func() error {
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
return err
})
_ = w.Bind("pp_open_logs", func() error { return desktopctl.OpenLogsFolder(repoRoot, configPath) })
_ = w.Bind("pp_open_auth_folder", func() error {
dir, err := desktopctl.AuthDirFor(configPath)
if err != nil {
return err
}
return desktopctl.OpenFolder(dir)
})
_ = w.Bind("pp_open_legacy_ui", func() error {
cur, _ := desktopctl.StatusFor(configPath)
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/management.html?legacy=1")
})
_ = w.Bind("pp_open_diagnostics", func() error {
cur, _ := desktopctl.StatusFor(configPath)
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/proxypilot.html")
})
_ = w.Bind("pp_get_oauth_private", func() (bool, error) { return desktopctl.GetOAuthPrivate() })
_ = w.Bind("pp_set_oauth_private", func(enabled bool) error { return desktopctl.SetOAuthPrivate(enabled) })
_ = w.Bind("pp_oauth", func(provider string) error {
endpoint := ""
switch strings.ToLower(strings.TrimSpace(provider)) {
case "antigravity":
endpoint = "/v0/management/antigravity-auth-url"
case "gemini-cli", "geminicli":
endpoint = "/v0/management/gemini-cli-auth-url"
case "codex":
endpoint = "/v0/management/codex-auth-url"
case "claude", "anthropic":
endpoint = "/v0/management/anthropic-auth-url"
case "qwen":
endpoint = "/v0/management/qwen-auth-url"
case "iflow":
endpoint = "/v0/management/iflow-auth-url"
default:
return fmt.Errorf("unknown provider: %s", provider)
}
return startOAuthFlow(configPath, endpoint)
})
_ = w.Bind("pp_copy_diagnostics", func() error { return copyDiagnosticsToClipboard(configPath) })
_ = w.Bind("pp_get_management_key", func() (string, error) { return desktopctl.GetManagementPassword() })
// Integration bindings
_ = w.Bind("pp_get_integrations", func() ([]map[string]any, error) {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
return nil, fmt.Errorf("proxy not running")
}
key, _ := desktopctl.GetManagementPassword()
client := &http.Client{Timeout: 5 * time.Second}
req, _ := http.NewRequest("GET", st.BaseURL+"/v0/management/integrations", nil)
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res struct {
Integrations []map[string]any `json:"integrations"`
}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res.Integrations, nil
})
_ = w.Bind("pp_configure_integration", func(id string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
return fmt.Errorf("proxy not running")
}
key, _ := desktopctl.GetManagementPassword()
client := &http.Client{Timeout: 10 * time.Second}
req, _ := http.NewRequest("POST", st.BaseURL+"/v0/management/integrations/"+id, nil)
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed: %s", string(b))
}
return nil
})
if target != "" {
w.Navigate(target)
w.Run()
return
}
w.SetHtml(controlCenterHTML())
w.Run()
}
func findEdge() (string, error) {
if p, err := exec.LookPath("msedge.exe"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
if p, err := exec.LookPath("msedge"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
candidates := []string{
filepath.Join(os.Getenv("ProgramFiles(x86)"), "Microsoft", "Edge", "Application", "msedge.exe"),
filepath.Join(os.Getenv("ProgramFiles"), "Microsoft", "Edge", "Application", "msedge.exe"),
}
for _, c := range candidates {
if strings.TrimSpace(c) == "" {
continue
}
if _, err := os.Stat(c); err == nil {
return c, nil
}
}
return "", fmt.Errorf("msedge.exe not found")
}
func applyDefaults(repoRoot, configPath, exePath string) (string, string, string) {
repoRoot = strings.TrimSpace(repoRoot)
configPath = strings.TrimSpace(configPath)
exePath = strings.TrimSpace(exePath)
exe, _ := os.Executable()
exeDir := ""
if strings.TrimSpace(exe) != "" {
exeDir = filepath.Dir(filepath.Clean(exe))
}
// If launched from a repo/app "bin" directory, treat its parent as the root.
defaultRoot := exeDir
if strings.EqualFold(filepath.Base(defaultRoot), "bin") {
defaultRoot = filepath.Dir(defaultRoot)
}
if repoRoot == "" && defaultRoot != "" {
repoRoot = defaultRoot
}
if configPath == "" && exeDir != "" {
configPath = filepath.Join(repoRoot, "config.yaml")
}
if exePath == "" && exeDir != "" {
for _, name := range []string{"proxypilot-engine.exe", "cliproxyapi-latest.exe"} {
cand := filepath.Join(exeDir, name)
if _, err := os.Stat(cand); err == nil {
exePath = cand
break
}
}
}
return repoRoot, configPath, exePath
}
func openNewWindow(repoRoot, configPath, exePath, url string) error {
exe, err := os.Executable()
if err != nil || strings.TrimSpace(exe) == "" {
return desktopctl.OpenBrowser(url)
}
args := []string{"-url", url}
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return exec.Command(exe, args...).Start()
}
type authURLResponse struct {
Status string `json:"status"`
URL string `json:"url"`
State string `json:"state"`
Error string `json:"error"`
}
func startOAuthFlow(configPath string, endpointPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+endpointPath, nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var out authURLResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
if strings.TrimSpace(out.Error) != "" {
return fmt.Errorf("%s", out.Error)
}
return fmt.Errorf("auth url request failed: %s", resp.Status)
}
if strings.TrimSpace(out.URL) == "" {
return fmt.Errorf("missing auth url")
}
private, _ := desktopctl.GetOAuthPrivate()
return openOAuthURL(out.URL, private)
}
func openOAuthURL(url string, private bool) error {
if !private {
return desktopctl.OpenBrowser(url)
}
edge, err := findEdge()
if err != nil {
return desktopctl.OpenBrowser(url)
}
return exec.Command(edge, "--inprivate", url).Start()
}
func copyDiagnosticsToClipboard(configPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+"/v0/management/proxypilot/diagnostics?lines=200", nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
b, _ := io.ReadAll(resp.Body)
msg := strings.TrimSpace(string(b))
if msg == "" {
msg = resp.Status
}
return fmt.Errorf("diagnostics failed: %s", msg)
}
var payload struct {
Text string `json:"text"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return err
}
if strings.TrimSpace(payload.Text) == "" {
return fmt.Errorf("empty diagnostics")
}
return copyToClipboard(payload.Text)
}
func copyToClipboard(text string) error {
cmd := exec.Command("cmd", "/c", "clip")
cmd.Stdin = strings.NewReader(text)
return cmd.Run()
}
func controlCenterHTML() string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ProxyPilot</title>
<style>
:root{
--bg:#0b0f17;
--panel:#0f172a;
--panel2:#111c33;
--text:#e5e7eb;
--muted:#9ca3af;
--line:#1f2a44;
--brand:#60a5fa;
--good:#34d399;
--bad:#f87171;
--warn:#fbbf24;
--btn:#1f2a44;
--btn2:#243152;
}
*{box-sizing:border-box}
body{
margin:0;
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
background: radial-gradient(1000px 600px at 20% 0%, rgba(96,165,250,.18), transparent 60%),
radial-gradient(1000px 700px at 80% 10%, rgba(52,211,153,.12), transparent 55%),
var(--bg);
color:var(--text);
}
.wrap{max-width:1040px;margin:0 auto;padding:28px 22px 40px}
.top{display:flex;gap:14px;align-items:center;justify-content:space-between;margin-bottom:18px}
.brand{display:flex;align-items:center;gap:12px}
.logo{
width:42px;height:42px;border-radius:12px;
background: linear-gradient(135deg, rgba(96,165,250,.95), rgba(34,211,238,.75));
box-shadow: 0 10px 30px rgba(96,165,250,.18);
}
h1{font-size:22px;margin:0}
.sub{font-size:13px;color:var(--muted);margin-top:3px}
.pill{
display:inline-flex;align-items:center;gap:8px;
padding:8px 12px;border:1px solid var(--line);border-radius:999px;
background: rgba(15,23,42,.65);
font-size:13px;color:var(--muted)
}
.dot{width:9px;height:9px;border-radius:50%}
.card{
border:1px solid var(--line);
background: linear-gradient(180deg, rgba(15,23,42,.92), rgba(15,23,42,.78));
border-radius:16px;
padding:16px;
box-shadow: 0 20px 60px rgba(0,0,0,.35);
}
.grid{display:grid;grid-template-columns:1.4fr .9fr;gap:16px}
@media (max-width: 980px){.grid{grid-template-columns:1fr}}
.row{display:flex;flex-wrap:wrap;gap:10px}
button,.btn{
appearance:none;border:1px solid var(--line);background:var(--btn);color:var(--text);
border-radius:12px;padding:10px 12px;font-size:13px;cursor:pointer;
transition: transform .06s ease, background .12s ease, border-color .12s ease;
user-select:none;
}
button:hover{background:var(--btn2);border-color:#2c3a60}
button:active{transform: translateY(1px)}
button[disabled]{opacity:.45;cursor:not-allowed}
.btnPrimary{background: rgba(96,165,250,.18);border-color: rgba(96,165,250,.45)}
.btnPrimary:hover{background: rgba(96,165,250,.25);border-color: rgba(96,165,250,.65)}
.btnDanger{background: rgba(248,113,113,.14);border-color: rgba(248,113,113,.4)}
.btnDanger:hover{background: rgba(248,113,113,.2);border-color: rgba(248,113,113,.6)}
.btnGood{background: rgba(52,211,153,.14);border-color: rgba(52,211,153,.38)}
.btnGood:hover{background: rgba(52,211,153,.2);border-color: rgba(52,211,153,.55)}
.sectionTitle{font-size:13px;color:var(--muted);margin:0 0 10px}
.kv{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;font-size:13px;margin-top:8px}
.k{color:var(--muted)}
.v{color:var(--text);word-break:break-word}
.note{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.4}
.toggle{display:flex;align-items:center;gap:10px;margin-top:10px}
input[type="checkbox"]{width:16px;height:16px}
.toast{position:fixed;left:22px;bottom:18px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:rgba(15,23,42,.88);color:var(--text);font-size:13px;display:none;max-width: min(620px, calc(100vw - 44px));}
.toast.show{display:block}
.hint{font-size:12px;color:var(--muted);margin-top:8px}
</style>
</head>
<body>
<div class="wrap">
<div class="top">
<div class="brand">
<div class="logo"></div>
<div>
<h1>ProxyPilot</h1>
<div class="sub">Local proxy controller + dashboard (Windows)</div>
</div>
</div>
<div class="pill" id="statusPill">
<span class="dot" id="statusDot" style="background: var(--warn)"></span>
<span id="statusText">Checking…</span>
</div>
</div>
<div class="grid">
<div class="card">
<div class="sectionTitle">Engine</div>
<div class="row">
<button class="btnGood" id="startBtn">Start</button>
<button class="btnDanger" id="stopBtn">Stop</button>
<button id="restartBtn">Restart</button>
<button class="btnPrimary" id="diagBtn">Open Diagnostics</button>
<button id="legacyBtn">Advanced UI</button>
</div>
<div class="kv">
<div class="k">Base URL</div><div class="v" id="baseUrl">-</div>
<div class="k">Port</div><div class="v" id="port">-</div>
<div class="k">Thinking Port</div><div class="v" id="thinkingPort">-</div>
<div class="k">Last error</div><div class="v" id="lastErr">-</div>
</div>
<div class="row" style="margin-top:12px">
<button id="logsBtn">Open Logs Folder</button>
<button id="authBtn">Open Auth Folder</button>
<button id="copyDiagBtn">Copy Diagnostics</button>
</div>
<div class="toggle">
<input id="privateOAuth" type="checkbox" />
<label for="privateOAuth">Open OAuth in a private (InPrivate) window</label>
</div>
<div class="note">
Tip: keep the tray menu minimal — use this Control Center for day-to-day actions.
</div>
</div>
<div class="card">
<div class="sectionTitle">Logins</div>
<div class="row">
<button id="oauthAntigravity">Antigravity</button>
<button id="oauthGeminiCli">Gemini CLI</button>
<button id="oauthCodex">Codex</button>
<button id="oauthClaude">Claude</button>
<button id="oauthQwen">Qwen</button>
<button id="oauthIflow">iFlow</button>
</div>
<div class="hint">These open the provider login flow in your browser and save auth files for ProxyPilot.</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Integrations</div>
<div class="row" id="integrationsList">
<div style="color:var(--muted);font-size:13px">Loading integrations...</div>
</div>
<div class="note">
Automatically configure local tools to use ProxyPilot.
</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Live Logs</div>
<div id="logContent" style="height:240px;overflow-y:auto;background:rgba(0,0,0,.3);padding:10px;font-family:monospace;font-size:12px;border-radius:8px;border:1px solid var(--line);white-space:pre-wrap;color:var(--muted)">Waiting for logs...</div>
<div class="row" style="margin-top:10px">
<button id="toggleLogsBtn">Pause Updates</button>
<button id="clearLogsBtn">Clear View</button>
</div>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
const $ = (id) => document.getElementById(id);
let logPaused = false;
const toast = (msg) => {
const el = $('toast');
el.textContent = msg;
el.classList.add('show');
clearTimeout(window.__toastTimer);
window.__toastTimer = setTimeout(()=> el.classList.remove('show'), 2400);
};
const setRunningUI = (running) => {
$('startBtn').disabled = !!running;
$('stopBtn').disabled = !running;
$('restartBtn').disabled = !running;
$('diagBtn').disabled = !running;
$('legacyBtn').disabled = !running;
const dot = $('statusDot');
dot.style.background = running ? 'var(--good)' : 'var(--warn)';
if(running) refreshIntegrations();
};
async function refreshStatus() {
try{
const s = await window.pp_status();
$('baseUrl').textContent = s.base_url || '-';
$('port').textContent = s.port ? String(s.port) : '-';
const tp = $('thinkingPort');
if (s.thinking_port) {
tp.textContent = s.thinking_port + (s.thinking_running ? ' (Active)' : ' (Inactive)');
tp.style.color = s.thinking_running ? 'var(--good)' : 'var(--muted)';
} else {
tp.textContent = '-';
tp.style.color = 'var(--muted)';
}
$('lastErr').textContent = (s.last_error && s.last_error.trim()) ? s.last_error : '-';
$('statusText').textContent = s.running ? ('Running (:' + s.port + ')') : 'Stopped';
setRunningUI(!!s.running);
if(!logPaused && s.running) refreshLogs();
}catch(e){
$('statusText').textContent = 'Error';
$('lastErr').textContent = (e && e.message) ? e.message : String(e);
setRunningUI(false);
}
}
async function refreshLogs() {
const logEl = $('logContent');
const key = await window.pp_get_management_key();
const s = await window.pp_status();
if(!s.base_url) return;
try {
const resp = await fetch(s.base_url + '/v0/management/proxypilot/logs/tail?file=stdout&lines=50', {
headers: { 'X-Management-Key': key }
});
const data = await resp.json();
if(data.lines) {
logEl.textContent = data.lines.join('\n');
logEl.scrollTop = logEl.scrollHeight;
}
} catch(e) {}
}
async function refreshIntegrations() {
const list = $('integrationsList');
try {
const items = await window.pp_get_integrations();
if(!items || items.length === 0) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">No integrations available</div>';
return;
}
list.innerHTML = '';
items.forEach(i => {
const btn = document.createElement('button');
btn.className = i.configured ? 'btnGood' : 'btn';
btn.textContent = i.name + (i.configured ? ' (Active)' : '');
btn.onclick = async () => {
try {
await window.pp_configure_integration(i.id);
toast('Configured ' + i.name);
refreshIntegrations();
} catch(e) { toast(e.message||String(e)); }
};
if(!i.installed) {
btn.disabled = true;
btn.textContent += ' (Not Installed)';
}
list.appendChild(btn);
});
} catch(e) {
// quiet fail if proxy not ready
}
}
async function init() {
try{
const priv = await window.pp_get_oauth_private();
$('privateOAuth').checked = !!priv;
}catch(e){}
await refreshStatus();
setInterval(refreshStatus, 1200);
}
$('startBtn').addEventListener('click', async () => { try{ await window.pp_start(); toast('Started'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('stopBtn').addEventListener('click', async () => { try{ await window.pp_stop(); toast('Stopped'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('restartBtn').addEventListener('click', async () => { try{ await window.pp_restart(); toast('Restarted'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('logsBtn').addEventListener('click', async () => { try{ await window.pp_open_logs(); toast('Opened logs'); }catch(e){ toast(e.message||String(e)); } });
$('authBtn').addEventListener('click', async () => { try{ await window.pp_open_auth_folder(); toast('Opened auth folder'); }catch(e){ toast(e.message||String(e)); } });
$('copyDiagBtn').addEventListener('click', async () => { try{ await window.pp_copy_diagnostics(); toast('Copied'); }catch(e){ toast(e.message||String(e)); } });
$('diagBtn').addEventListener('click', async () => { try{ await window.pp_open_diagnostics(); }catch(e){ toast(e.message||String(e)); } });
$('legacyBtn').addEventListener('click', async () => { try{ await window.pp_open_legacy_ui(); }catch(e){ toast(e.message||String(e)); } });
$('toggleLogsBtn').addEventListener('click', () => {
logPaused = !logPaused;
$('toggleLogsBtn').textContent = logPaused ? 'Resume Updates' : 'Pause Updates';
});
$('clearLogsBtn').addEventListener('click', () => { $('logContent').textContent = ''; });
$('privateOAuth').addEventListener('change', async (ev) => {
try{ await window.pp_set_oauth_private(!!ev.target.checked); toast('Saved'); }catch(e){ toast(e.message||String(e)); }
});
const oauth = (provider) => async () => { try{ await window.pp_oauth(provider); toast('Opened login'); }catch(e){ toast(e.message||String(e)); } };
$('oauthAntigravity').addEventListener('click', oauth('antigravity'));
$('oauthGeminiCli').addEventListener('click', oauth('gemini-cli'));
$('oauthCodex').addEventListener('click', oauth('codex'));
$('oauthClaude').addEventListener('click', oauth('claude'));
$('oauthQwen').addEventListener('click', oauth('qwen'));
$('oauthIflow').addEventListener('click', oauth('iflow'));
init();
</script>
</body>
</html>`
}
func messageBox(title, text string) error {
user32 := syscall.NewLazyDLL("user32.dll")
proc := user32.NewProc("MessageBoxW")
t, _ := syscall.UTF16PtrFromString(title)
m, _ := syscall.UTF16PtrFromString(text)
// MB_OK | MB_ICONERROR
_, _, err := proc.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), 0x00000000|0x00000010)
if err == syscall.Errno(0) {
return nil
}
return err
}
+124 -14
View File
@@ -19,8 +19,8 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
"github.com/router-for-me/CLIProxyAPI/v6/internal/cmd"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v6/internal/store"
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
@@ -71,8 +71,6 @@ func main() {
var codexLogin bool
var claudeLogin bool
var qwenLogin bool
var iflowLogin bool
var iflowCookie bool
var noBrowser bool
var antigravityLogin bool
var kiroLogin bool
@@ -80,7 +78,23 @@ func main() {
var kiroAWSLogin bool
var kiroAWSAuthCode bool
var kiroImport bool
var amazonqImport bool
var antigravityImport bool
var minimaxLogin bool
var zhipuLogin bool
// var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded
var detectAgents bool
var setupClaude bool
var setupCodex bool
var setupDroid bool
var setupOpenCode bool
var setupGemini bool
var setupCursor bool
var setupKilo bool
var setupRooCode bool
var setupAll bool
var switchAgent string
var switchMode string
var projectID string
var vertexImport string
var configPath string
@@ -93,8 +107,6 @@ func main() {
flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth")
flag.BoolVar(&iflowLogin, "iflow-login", false, "Login to iFlow using OAuth")
flag.BoolVar(&iflowCookie, "iflow-cookie", false, "Login to iFlow using Cookie")
flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)")
flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)")
@@ -104,7 +116,23 @@ func main() {
flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)")
flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)")
flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)")
flag.BoolVar(&amazonqImport, "amazonq-import", false, "Import Amazon Q CLI token from SQLite database")
flag.BoolVar(&antigravityImport, "antigravity-import", false, "Import Antigravity token from Antigravity IDE")
flag.BoolVar(&minimaxLogin, "minimax-login", false, "Add MiniMax API key")
flag.BoolVar(&zhipuLogin, "zhipu-login", false, "Add Zhipu AI API key")
// GitHub Copilot login removed
flag.BoolVar(&detectAgents, "detect-agents", false, "Detect installed CLI agents")
flag.BoolVar(&setupClaude, "setup-claude", false, "Configure Claude Code to use ProxyPilot")
flag.BoolVar(&setupCodex, "setup-codex", false, "Configure Codex CLI to use ProxyPilot")
flag.BoolVar(&setupDroid, "setup-droid", false, "Configure Factory Droid to use ProxyPilot")
flag.BoolVar(&setupOpenCode, "setup-opencode", false, "Configure OpenCode to use ProxyPilot")
flag.BoolVar(&setupGemini, "setup-gemini", false, "Configure Gemini CLI to use ProxyPilot")
flag.BoolVar(&setupCursor, "setup-cursor", false, "Configure Cursor to use ProxyPilot")
flag.BoolVar(&setupKilo, "setup-kilo", false, "Configure Kilo Code CLI to use ProxyPilot")
flag.BoolVar(&setupRooCode, "setup-roocode", false, "Configure RooCode (VS Code) to use ProxyPilot")
flag.BoolVar(&setupAll, "setup-all", false, "Configure all detected CLI agents (with backup)")
flag.StringVar(&switchAgent, "switch", "", "Switch agent config mode (e.g., --switch claude)")
flag.StringVar(&switchMode, "mode", "", "Switch mode: proxy, native, or status (default: status)")
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
@@ -137,6 +165,37 @@ func main() {
})
}
// Check for subcommand-style switch command before flag.Parse()
// Supports: proxypilot switch [agent] [mode]
// agent can be: claude, gemini, codex, opencode, droid, cursor
// mode can be: proxy, native, status (default if omitted)
var subcommandSwitch bool
args := os.Args[1:]
if len(args) > 0 && args[0] == "switch" {
subcommandSwitch = true
switchArgs := args[1:]
// Filter out any flags like --status from positional args
var positionalArgs []string
for _, arg := range switchArgs {
if arg == "--status" {
switchMode = "status"
} else if !strings.HasPrefix(arg, "-") {
positionalArgs = append(positionalArgs, arg)
}
}
// Parse positional arguments: [agent] [mode]
if len(positionalArgs) >= 1 {
switchAgent = positionalArgs[0]
}
if len(positionalArgs) >= 2 {
switchMode = positionalArgs[1]
}
// Default mode to "status" if not specified
if switchMode == "" {
switchMode = "status"
}
}
// Parse the command-line flags.
flag.Parse()
@@ -404,8 +463,13 @@ func main() {
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
}
if err != nil {
log.Errorf("failed to load config: %v", err)
return
// For switch command, config is optional - use defaults
if subcommandSwitch || switchAgent != "" {
cfg = &config.Config{Port: 8317}
} else {
log.Errorf("failed to load config: %v", err)
return
}
}
if cfg == nil {
cfg = &config.Config{}
@@ -462,7 +526,6 @@ func main() {
} else {
cfg.AuthDir = resolvedAuthDir
}
managementasset.SetCurrentConfig(cfg)
// Create login options to be used in authentication flows.
options := &cmd.LoginOptions{
@@ -505,10 +568,6 @@ func main() {
cmd.DoClaudeLogin(cfg, options)
} else if qwenLogin {
cmd.DoQwenLogin(cfg, options)
} else if iflowLogin {
cmd.DoIFlowLogin(cfg, options)
} else if iflowCookie {
cmd.DoIFlowCookieAuth(cfg, options)
} else if kiroLogin {
// For Kiro auth, default to incognito mode for multi-account support
// Users can explicitly override with --no-incognito
@@ -533,6 +592,39 @@ func main() {
cmd.DoKiroAWSAuthCodeLogin(cfg, options)
} else if kiroImport {
cmd.DoKiroImport(cfg, options)
} else if amazonqImport {
cmd.DoAmazonQImport(cfg, options)
} else if antigravityImport {
cmd.DoAntigravityImport(cfg)
} else if minimaxLogin {
cmd.DoMiniMaxLogin(cfg, options)
} else if zhipuLogin {
cmd.DoZhipuLogin(cfg, options)
} else if detectAgents {
cmd.DoDetectAgents()
} else if setupClaude {
cmd.DoSetupClaude(cfg)
} else if setupCodex {
cmd.DoSetupCodex(cfg)
} else if setupDroid {
cmd.DoSetupDroid(cfg)
} else if setupOpenCode {
cmd.DoSetupOpenCode(cfg)
} else if setupGemini {
cmd.DoSetupGeminiCLI(cfg)
} else if setupCursor {
cmd.DoSetupCursor(cfg)
} else if setupKilo {
cmd.DoSetupKiloCode(cfg)
} else if setupRooCode {
cmd.DoSetupRooCode(cfg)
} else if setupAll {
cmd.DoSetupAll(cfg)
} else if subcommandSwitch || switchAgent != "" || switchMode != "" {
// Handle switch command:
// - Subcommand style: proxypilot switch claude proxy
// - Flag style: proxypilot --switch claude --mode proxy
cmd.DoSwitch(cfg, switchAgent, switchMode)
} else {
// In cloud deploy mode without config file, just wait for shutdown signals
if isCloudDeploy && !configFileExists {
@@ -540,8 +632,26 @@ func main() {
cmd.WaitForCloudDeploy()
return
}
// Start the main proxy service
managementasset.StartAutoUpdater(context.Background(), configFilePath)
cmd.StartService(cfg, configFilePath, password)
// Auto-generate management password if not provided
// This enables browser-based webui access without requiring the -password flag
autoGenPassword := false
if password == "" {
if pw, err := desktopctl.GetManagementPassword(); err == nil {
password = pw
autoGenPassword = true
log.Info("using auto-generated management password for webui access")
} else {
log.Warnf("failed to get management password: %v (webui may require manual authentication)", err)
}
}
// Use standalone mode (no keep-alive shutdown) when password was auto-generated
// Keep-alive shutdown is only needed when the tray app spawns the server as subprocess
if autoGenPassword {
cmd.StartServiceStandalone(cfg, configFilePath, password)
} else {
cmd.StartService(cfg, configFilePath, password)
}
}
}
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
{
"FixedFileInfo": {
"FileVersion": {
"Major": 0,
"Minor": 1,
"Patch": 6,
"Build": 0
},
"ProductVersion": {
"Major": 0,
"Minor": 1,
"Patch": 6,
"Build": 0
},
"FileFlagsMask": "3f",
"FileFlags ": "00",
"FileOS": "040004",
"FileType": "01",
"FileSubType": "00"
},
"StringFileInfo": {
"Comments": "Local AI Proxy Engine",
"CompanyName": "ProxyPilot",
"FileDescription": "ProxyPilot Engine",
"FileVersion": "0.1.6",
"InternalName": "proxypilot-engine",
"LegalCopyright": "MIT License",
"OriginalFilename": "proxypilot-engine.exe",
"ProductName": "ProxyPilot",
"ProductVersion": "0.1.6"
},
"VarFileInfo": {
"Translation": {
"LangID": "0409",
"CharsetID": "04B0"
}
},
"IconPath": "../../static/icon.ico",
"ManifestPath": ""
}
+121 -5
View File
@@ -26,8 +26,15 @@ remote-management:
# Authentication directory (supports ~ for home directory)
auth-dir: "~/.cli-proxy-api"
# Long-running agent harness files root directory (feature_list.json, claude-progress.txt).
# Defaults to the server working directory when empty.
# The harness guides AI agents through structured, incremental development workflows.
# - INITIALIZER mode: Creates feature list, progress log, and init.sh for new sessions
# - CODING mode: Forces one-feature-at-a-time workflow with verification
# Leave empty to use session-based memory storage (recommended).
# Set to a specific directory to share harness files across sessions.
# harness-root-dir: ""
#
# Environment variables:
# CLIPROXY_HARNESS_ENABLED=true/false # Enable/disable harness injection (default: true)
# API keys for authentication
api-keys:
@@ -38,6 +45,19 @@ debug: false
# When true, disable high-overhead HTTP middleware features to reduce per-request memory usage under high concurrency.
commercial-mode: false
# Lightweight profile (example)
# commercial-mode: true
# usage-statistics-enabled: false
# metrics-enabled: false
# request-history-enabled: false
# agentic-harness-enabled: false
# prompt-budget-enabled: false
# request-log: false
# response-cache:
# enabled: false
# prompt-cache:
# enabled: false
# Open OAuth URLs in incognito/private browser mode.
# Useful when you want to login with a different account without logging out from your current session.
# Default: false (but Kiro auth defaults to true for multi-account support)
@@ -52,6 +72,18 @@ logs-max-total-size-mb: 0
# When false, disable in-memory usage statistics aggregation
usage-statistics-enabled: false
# Usage sampling (0.0-1.0). Default: 1.0 (no sampling)
# usage-sample-rate: 1.0
# Prometheus metrics + /metrics endpoint (opt-in)
metrics-enabled: false
# Persistent request history (opt-in)
request-history-enabled: false
# Request history sampling (0.0-1.0). Default: 1.0 (no sampling)
# request-history-sample-rate: 1.0
# Agentic harness middleware (default: true)
agentic-harness-enabled: true
# Codex prompt budget middleware (default: true)
prompt-budget-enabled: true
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
proxy-url: ""
@@ -69,15 +101,98 @@ quota-exceeded:
# Routing strategy for selecting credentials when multiple match.
routing:
strategy: "round-robin" # round-robin (default), fill-first
strategy: "round-robin" # round-robin (default), fill-first, usage-aware
# Global model mappings - route friendly names to actual models across all providers.
# These mappings are checked before per-credential model mappings.
# global-model-mappings:
# - from: "smart" # Client requests "smart"
# to: "claude-opus-4-5-20251101" # Routes to Claude Opus
# - from: "rush"
# to: "claude-haiku-4-5-20251001" # Routes to Claude Haiku (fast)
# - from: "think"
# to: "claude-opus-4-5-thinking" # Routes to thinking model
# - from: "gemini-pro"
# to: "gemini-2.5-pro-preview"
# provider: "gemini" # Only applies to Gemini provider
# - from: "cheap"
# to: "gpt-4o-mini"
# provider: "codex"
# enabled: false # Disabled mapping (kept for reference)
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
# Streaming behavior (SSE keep-alives + safe bootstrap retries).
# Allow requests without API keys. Default: false (deny unauthenticated).
allow-unauthenticated: false
# CORS settings. By default, non-management endpoints allow "*" and
# management endpoints send no CORS headers.
# cors:
# allow-origins:
# - "http://localhost:5173"
# management-allow-origins:
# - "http://localhost:5173"
# allow-methods:
# - "GET"
# - "POST"
# - "PUT"
# - "PATCH"
# - "DELETE"
# - "OPTIONS"
# allow-headers:
# - "Authorization"
# - "Content-Type"
# - "X-Management-Key"
# - "X-Local-Password"
# Streaming behavior (SSE keep-alives, bootstrap retries, chunk sizing).
# streaming:
# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.
# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
# max-chunk-size: 65536 # Default: 65536 (64KB). Max bytes per response chunk. 0 disables limiting.
# Context compression behavior (Factory.ai-style structured summarization).
# Uses LLM to generate intelligent summaries with structured sections when context
# exceeds the threshold. Summaries include: session intent, file modifications,
# decisions made, next steps, and technical details.
# compression:
# enabled: true # Default: true. Enable LLM-based structured summarization.
# threshold-percent: 0.75 # Default: 0.75. Trigger compression at 75% of context window.
# max-summary-tokens: 2000 # Default: 2000. Maximum tokens for generated summaries.
# summarization-timeout-seconds: 30 # Default: 30. Timeout for LLM summarization calls.
# fallback-to-regex: true # Default: true. Use regex-based summary when LLM fails.
# Response caching - cache identical API responses to reduce upstream calls.
# response-cache:
# enabled: true
# max-size: 1000 # Max cached responses
# max-bytes: 0 # Optional total cache size cap in bytes
# ttl-seconds: 300 # 5 minutes
# exclude-models: # Don't cache these models
# - "*-thinking"
# - "o1-*"
# Prompt caching - track system prompts for analytics.
# prompt-cache:
# enabled: true
# max-size: 500
# max-bytes: 0 # Optional total cache size cap in bytes
# ttl-seconds: 1800 # 30 minutes
# warm-from-file: "./prompts-to-cache.json" # Optional: pre-load prompts on startup
# Format: [{"prompt": "...", "provider": "claude"}, ...]
# Token refresh and usage tracking configuration.
# auto-refresh-buffer: 5m # Default: 5m. Refresh tokens this long before expiry.
# # Supports Go duration format: "5m", "10m", "1h", etc.
# daily-reset-hour: 0 # Default: 0 (midnight UTC). Hour (0-23, UTC) to reset daily usage stats.
# Token-aware compression (proactive trimming based on model context window).
# Prevents "prompt too long" errors by trimming before hitting model limits.
# Environment variables:
# CLIPROXY_TOKEN_AWARE_ENABLED=true # Default: true. Enable token-based compression.
# CLIPROXY_COMPRESSION_THRESHOLD=0.75 # Default: 0.75. Trim at 75% of context window.
# CLIPROXY_RESERVE_TOKENS=8192 # Default: 8192. Tokens reserved for model output.
# Gemini API keys
# gemini-api-key:
@@ -102,6 +217,9 @@ ws-auth: false
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "gpt-5-codex" # upstream model name
# alias: "codex-latest" # client alias mapped to the upstream model
# excluded-models:
# - "gpt-5.2" # exclude specific models (exact match)
# - "gpt-5-*" # wildcard matching prefix (e.g. gpt-5-medium, gpt-5-codex)
@@ -196,8 +314,6 @@ ws-auth: false
# - "vision-model"
# kiro:
# - "kiro-claude-haiku"
# iflow:
# - "tstars2.0"
# Optional payload configuration
# payload:
+331
View File
@@ -0,0 +1,331 @@
# ProxyPilot CLI
**proxypilot** is the unified command-line interface for the ProxyPilot local AI proxy. It provides both **server** functionality (running the proxy server) and **switch** functionality (toggling AI agents between proxy mode and native mode).
## Installation
### Via bun (recommended)
```bash
bun install -g proxypilot
```
### Via npm
```bash
npm install -g proxypilot
```
### Via Go
```bash
go install github.com/Finesssee/ProxyPilot/cmd/server@latest
```
### Manual Download
Download pre-built binaries from [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases).
Available binaries:
- `proxypilot-darwin-amd64` - macOS Intel
- `proxypilot-darwin-arm64` - macOS Apple Silicon
- `proxypilot-linux-amd64` - Linux x64
- `proxypilot-linux-arm64` - Linux ARM64
- `proxypilot-windows-amd64.exe` - Windows x64
## Server Mode
Run ProxyPilot as a local proxy server:
```bash
proxypilot # Start server on default port (8317)
proxypilot -config /path/to/config # Use custom config file
```
### Server Features
- Routes AI requests through configured providers
- Automatic model aliasing and translation
- OAuth login helpers for various providers
- Agent configuration management
### Login Commands
```bash
proxypilot --login # Login to Google Account (Gemini)
proxypilot --codex-login # Login to Codex using OAuth
proxypilot --claude-login # Login to Claude using OAuth
proxypilot --qwen-login # Login to Qwen using OAuth
proxypilot --antigravity-login # Login to Antigravity using OAuth
proxypilot --kiro-login # Login to Kiro using Google OAuth
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID
proxypilot --minimax-login # Add MiniMax API key
proxypilot --zhipu-login # Add Zhipu AI API key
```
### Login Options
```bash
--no-browser # Don't open browser automatically for OAuth
--incognito # Use incognito/private mode (useful for multiple accounts)
--no-incognito # Force disable incognito mode
```
### Import Commands
```bash
proxypilot --vertex-import <file> # Import Vertex service account key JSON
proxypilot --kiro-import # Import Kiro token from Kiro IDE
proxypilot --amazonq-import # Import Amazon Q CLI token
```
## Agent Configuration
ProxyPilot can automatically configure AI CLI tools to use the proxy.
### Detect Installed Agents
```bash
proxypilot --detect-agents
```
Example output:
```
Detecting installed CLI agents...
Claude Code: [+] Installed
Binary: /usr/local/bin/claude
Config: ~/.claude/settings.json
Codex CLI: [+] Installed
Binary: /usr/local/bin/codex
Config: ~/.codex
Gemini CLI: [-] Not found
```
### Setup Commands
```bash
proxypilot --setup-all # Configure all detected agents
proxypilot --setup-claude # Configure Claude Code
proxypilot --setup-codex # Configure Codex CLI
proxypilot --setup-droid # Configure Factory Droid
proxypilot --setup-opencode # Configure OpenCode
proxypilot --setup-gemini # Configure Gemini CLI
proxypilot --setup-cursor # Configure Cursor
proxypilot --setup-kilo # Configure Kilo Code CLI
proxypilot --setup-roocode # Configure RooCode (VS Code)
```
## Switch Mode
Switch AI agents between proxy mode (through ProxyPilot) and native mode (direct API access). Think of it like `nvm` for Node versions, but for AI agent configurations.
### Usage
```bash
proxypilot --switch <agent> # Show status of specific agent
proxypilot --switch <agent> --mode proxy # Switch agent to proxy mode
proxypilot --switch <agent> --mode native # Switch agent to native mode
proxypilot --switch <agent> --mode status # Show current mode (default)
```
### Supported Agents
| Agent | CLI Tool | Config Location |
|-------|----------|-----------------|
| `claude` | Claude Code | `~/.claude/settings.json` |
| `gemini` | Gemini CLI | `~/.gemini/settings.json` |
| `codex` | Codex CLI | `~/.codex/config.toml` |
| `opencode` | OpenCode | `~/.opencode/config.json` |
| `droid` | Factory Droid | `~/.factory/settings.json` |
| `cursor` | Cursor IDE | `~/.cursor/config.json` |
| `kilo` | Kilo Code* | VS Code settings |
| `roocode` | RooCode* | VS Code settings |
*VS Code extensions require manual configuration - proxypilot will display instructions.
### Modes
| Mode | Description |
|------|-------------|
| `proxy` | Route through ProxyPilot (`http://127.0.0.1:8317`) |
| `native` | Use direct API access (restore original config) |
| `status` | Show current mode (default) |
### Examples
#### Check single agent status
```bash
$ proxypilot --switch claude
Claude Code: proxy
Config: ~/.claude/settings.json
```
#### Switch Claude to proxy mode
```bash
$ proxypilot --switch claude --mode proxy
Switched Claude Code to proxy mode
Config: ~/.claude/settings.json
Backup: ~/.claude/settings.json.native.json
```
#### Switch Gemini back to native mode
```bash
$ proxypilot --switch gemini --mode native
Switched Gemini CLI to native mode
Restored from: ~/.gemini/settings.json.native.json
```
### How Switch Works
#### Switching to proxy mode
1. Backs up current config to `<config>.native.json`
2. Updates config to point to `http://127.0.0.1:8317`
3. Preserves all other settings (API keys, preferences, etc.)
#### Switching to native mode
1. Restores config from `<config>.native.json` backup
2. Removes backup file after successful restore
3. Original API keys and settings are restored
#### Config Detection
ProxyPilot automatically detects which mode an agent is in by checking:
- If config contains `127.0.0.1:8317` -> proxy mode
- If backup file exists -> was previously in proxy mode
- Otherwise -> native mode
## Agent-Specific Notes
### Claude Code
Config location: `~/.claude/settings.json`
Proxy mode sets:
```json
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8317"
}
}
```
### Codex CLI
Config location: `~/.codex/config.toml`
Proxy mode sets:
```toml
[openai]
api_base_url = "http://127.0.0.1:8317"
```
### Gemini CLI
Config location: `~/.gemini/settings.json`
Proxy mode sets the API endpoint to ProxyPilot.
### Kilo Code & RooCode
These are VS Code extensions that require manual configuration:
1. Open VS Code Settings (Ctrl+,)
2. Search for the extension settings
3. Update the API base URL to `http://127.0.0.1:8317`
ProxyPilot will display these instructions when you run:
```bash
proxypilot --setup-kilo
proxypilot --setup-roocode
```
## Backup System
Before modifying any configuration file, ProxyPilot creates a timestamped backup:
```
~/.claude/.proxypilot-backups/
settings.json.20251228-221853.bak
~/.codex/.proxypilot-backups/
config.toml.20251228-221853.bak
```
### Restoring Backups
```bash
# List backups
ls ~/.claude/.proxypilot-backups/
# Restore
cp ~/.claude/.proxypilot-backups/settings.json.<timestamp>.bak ~/.claude/settings.json
```
## Troubleshooting
### "Config not found"
The agent's config file doesn't exist. Run the agent once to create it, or create the config manually.
### "Failed to backup config"
Check file permissions on the config directory.
### "Already in proxy/native mode"
The agent is already configured for the requested mode. No changes made.
### CLI not detected
If a CLI tool is installed but not detected:
1. Ensure the binary is in your `PATH`
2. Try running the tool directly to verify it's installed
3. Check if the config directory exists
### Configuration not applied
1. Restart the CLI tool after running setup
2. Verify ProxyPilot is running on port 8317
3. Check the backup directory for the original config
## Full Usage Reference
```bash
proxypilot -h, --help # Show help
proxypilot -v, --version # Show version
# Server
proxypilot # Start proxy server
proxypilot -config <path> # Use custom config file
# OAuth Logins
proxypilot --login # Google/Gemini login
proxypilot --codex-login # Codex OAuth
proxypilot --claude-login # Claude OAuth
proxypilot --qwen-login # Qwen OAuth
proxypilot --antigravity-login # Antigravity OAuth
proxypilot --kiro-login # Kiro Google OAuth
proxypilot --kiro-aws-login # Kiro AWS Builder ID
# Agent Detection & Setup
proxypilot --detect-agents # Detect installed agents
proxypilot --setup-all # Configure all agents
proxypilot --setup-<agent> # Configure specific agent
# Agent Switching
proxypilot --switch <agent> # Show agent status
proxypilot --switch <agent> --mode proxy # Switch to proxy
proxypilot --switch <agent> --mode native # Switch to native
```
## Links
- [npm package](https://www.npmjs.com/package/proxypilot)
- [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases)
- [Source Code](https://github.com/Finesssee/ProxyPilot)
+300
View File
@@ -0,0 +1,300 @@
# ProxyPilot CLI + Tray Build Process
Documentation of the CLI and system tray application build and release process.
## Overview
ProxyPilot uses a **CLI + system tray architecture**:
- **proxypilot.exe** - CLI executable with all proxy functionality
- **ProxyPilot.exe** - System tray app that manages the CLI process and provides quick access to controls
The dashboard is accessed via web browser at `http://127.0.0.1:<port>/proxypilot.html`.
## Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ ProxyPilot System │
│ │
│ ┌─────────────────────┐ ┌─────────────────────────────┐ │
│ │ ProxyPilot.exe │ │ proxypilot.exe │ │
│ │ (System Tray) │─────▶│ (CLI / Engine) │ │
│ │ │ │ │ │
│ │ - Start/Stop │ │ - Proxy Engine (port 8317) │ │
│ │ - Open Dashboard │ │ - Web Dashboard Server │ │
│ │ - Copy API URL │ │ - Provider Auth Mgmt │ │
│ │ - Autostart toggle │ │ - Routing Engine │ │
│ └─────────────────────┘ └─────────────────────────────┘ │
│ │
│ ┌─────────────────────┐ │
│ │ Web Browser │ │
│ │ (Dashboard UI) │ │
│ │ proxypilot.html │ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
### CLI + Tray Separation
The architecture separates concerns:
**proxypilot.exe (CLI)**:
- All proxy engine functionality
- Serves web dashboard at `/proxypilot.html`
- Can run standalone from command line
- Supports all CLI flags (`--help`, `--setup-claude`, etc.)
**ProxyPilot.exe (Tray)**:
- Lightweight system tray wrapper
- Manages CLI process lifecycle (start/stop/restart)
- Opens dashboard in default browser
- Provides quick-access menu
Benefits of CLI + tray architecture:
- **Flexibility**: Use CLI directly or via tray app
- **No WebView2 dependency**: Dashboard runs in any browser
- **Simpler debugging**: Inspect network/console in browser DevTools
- **Cross-platform dashboard**: Same web UI works on all platforms
## Build Process
### Prerequisites
```bash
# Required tools
go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest
```
Inno Setup 6 must be installed for creating the Windows installer.
### Step 1: Build Web UI Assets
```bash
cd webui
npm install
npm run build
```
This generates `webui/dist/` with the dashboard assets that are served by the CLI at `/proxypilot.html`.
### Step 2: Create Multi-Resolution Icon
The icon must have multiple sizes for proper Windows display (16px to 256px):
```python
from PIL import Image
img = Image.open('static/icon.png')
if img.mode != 'RGBA':
img = img.convert('RGBA')
sizes = [(16,16), (24,24), (32,32), (48,48), (64,64), (128,128), (256,256)]
img.save('static/icon.ico', format='ICO', sizes=sizes)
```
Copy to tray icon location:
```bash
cp static/icon.ico internal/trayicon/icon.ico
```
### Step 3: Generate Windows Resource Files
Generate `.syso` files for embedding icons in executables:
```bash
cd cmd/cliproxytray
goversioninfo -icon="../../static/icon.ico"
```
This creates `resource.syso` files that Go automatically includes during build.
### Step 4: Build Executables
```bash
# Build CLI executable
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o dist/proxypilot.exe ./cmd/server
# Build tray app (with -H windowsgui to hide console)
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H windowsgui" -o dist/ProxyPilot.exe ./cmd/cliproxytray
```
### Step 5: Build Installer
```bash
# Using Inno Setup
"C:\Users\FSOS\AppData\Local\Programs\Inno Setup 6\ISCC.exe" installer/proxypilot.iss
```
Output: `dist/ProxyPilot-0.1.0-Setup.exe`
## Key Files
### Version Info Configuration
**cmd/cliproxytray/versioninfo.json**
```json
{
"FixedFileInfo": {
"FileVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0},
"ProductVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0}
},
"StringFileInfo": {
"FileDescription": "ProxyPilot System Tray",
"ProductName": "ProxyPilot",
"ProductVersion": "0.1.0"
},
"IconPath": "../../static/icon.ico"
}
```
### Tray Process Manager
**cmd/cliproxytray/engine.go** - Manages the CLI process:
- Spawns/stops `proxypilot.exe` subprocess
- Monitors process health
- Passes configuration and management password
### Tray Icon Embedding
**internal/trayicon/ico.go**
```go
package trayicon
import (
_ "embed"
)
//go:embed icon.ico
var proxyPilotICO []byte
func ProxyPilotICO() []byte {
return proxyPilotICO
}
```
### Installer Script
**installer/proxypilot.iss** - Inno Setup script that:
- Installs `proxypilot.exe` and `ProxyPilot.exe` to `%LOCALAPPDATA%\ProxyPilot`
- Creates Start Menu shortcut
- Adds optional Windows startup entry
- Copies config.example.yaml and creates config.yaml on first install
- Uses ProxyPilot icon for installer and shortcuts
## System Tray Menu
Simplified flat menu structure:
```
┌─────────────────────┐
│ Open Dashboard │ → Opens browser to proxypilot.html
├─────────────────────┤
│ Start/Stop │ → Toggle proxy engine (CLI process)
│ Copy API URL │ → Copies http://127.0.0.1:8317/v1
├─────────────────────┤
│ Quit │ → Stop engine and exit
└─────────────────────┘
```
## Release Process
### Create Release on GitHub
```bash
# Tag the release
git tag v0.1.0
git push origin v0.1.0
# Create release with assets
gh release create v0.1.0 \
--title "ProxyPilot v0.1.0" \
--notes "Release notes here" \
dist/ProxyPilot-0.1.0-Setup.exe \
dist/ProxyPilot.exe \
config.example.yaml
```
### Update Existing Release
```bash
# Delete old asset
gh release delete-asset v0.1.0 ProxyPilot.exe --yes
# Upload new asset
gh release upload v0.1.0 dist/ProxyPilot.exe
```
## Troubleshooting
### Icon Not Showing in File Explorer
1. Ensure icon.ico has 256x256 size (required for Windows)
2. Clear Windows icon cache: `ie4uinit.exe -show`
3. Verify resource.syso was generated after icon update
4. Rebuild the executable
### Dashboard Not Loading in Browser
1. Ensure the CLI process is running (check tray status)
2. Verify the port is correct: `http://127.0.0.1:8317/proxypilot.html`
3. Check for port conflicts with another application
### Tray Icon Shows Wrong Image
1. Check internal/trayicon/icon.ico is the correct file
2. Rebuild the tray app to re-embed the icon
3. Restart the application
### Engine Not Starting
1. Check if port 8317/8318 are already in use
2. Review logs in `%LOCALAPPDATA%\ProxyPilot\logs\`
3. Ensure config.yaml is valid YAML
## File Structure
```
ProxyPilot/
├── cmd/
│ ├── server/
│ │ └── main.go # CLI entry point
│ └── cliproxytray/
│ ├── main_windows.go # Tray app entry point
│ ├── engine.go # CLI process manager
│ ├── versioninfo.json # Version/icon config
│ └── resource.syso # Compiled resources
├── internal/
│ └── trayicon/
│ ├── ico.go # Embeds icon.ico
│ └── icon.ico # ProxyPilot logo (multi-res)
├── static/
│ ├── icon.ico # Source icon (7 sizes)
│ └── icon.png # Original PNG logo
├── webui/
│ ├── src/ # React dashboard source
│ └── dist/ # Built assets (served by CLI)
├── installer/
│ └── proxypilot.iss # Inno Setup script
└── dist/ # Distribution files
├── proxypilot.exe # CLI executable
└── ProxyPilot.exe # Tray app
```
## Version History
- **v0.3.0** (2025-12-30) - CLI + Tray architecture
- Removed WebView2 dependency
- Dashboard served by CLI, opened in browser
- Tray app manages CLI subprocess
- Simplified deployment and debugging
- **v0.2.0** (2025-12-27) - Single-binary architecture
- Embedded proxy engine runs in-process
- Removed separate proxypilot-engine.exe
- Reduced total size from ~46MB to ~29MB
- Faster startup with no process spawning
- **v0.1.0** (2025-12-27) - Initial release
- System tray with minimal menu
- Multi-resolution icon support
- Single-file Windows installer
-128
View File
@@ -1,128 +0,0 @@
# Desktop UI (ProxyPilot) — Shared Spec (Windows first)
This doc captures shared architecture and product decisions for a desktop “controller app” that manages a local `ProxyPilot` instance.
OS-specific details live in:
- Windows: `docs/windows-ui-spec.md`
- macOS (future): `docs/macos-ui-spec.md` (not yet)
## What we’re building
A small tray-first desktop app that can:
- start/stop/restart the local proxy engine (ProxyPilot Engine)
- show health + port + “copy base URL” snippets for IDE/agentic CLIs
- surface logs/request diagnostics to debug issues like 400/429, “prompt too long”, streaming quirks
It is not a full replacement for the server’s Management UI; it’s a launcher + diagnostics tool.
## Two-shell strategy (Wails + Tauri)
We can support both Wails and Tauri without forking business logic by standardizing on a single control interface.
### Primary shell: Wails (Go)
- Pros: simplest integration with existing Go codebase, easiest to ship v1 fast.
- Architecture: Wails UI ↔ Go control layer (in-process).
### Secondary shell: Tauri (Rust)
- Pros: smaller footprint, strong native tray/window tooling, good distribution story.
- Architecture (recommended): Tauri UI ↔ helper CLI ↔ Go control layer.
- Tauri calls `cliproxyctl` (or similar) as a subprocess.
- Benefits: no Rust↔Go FFI, no duplicated process logic, easy testing.
## Shared control interface
### Go package
- `internal/desktopctl`
- Pure Go logic for process management, config reading/writing, health, logs, autostart primitives.
- No UI dependencies.
### Suggested helper CLI (used by Tauri and power users)
- `cmd/cliproxyctl`
- `cliproxyctl status --config <path>`
- `cliproxyctl start --config <path>`
- `cliproxyctl stop`
- `cliproxyctl restart --config <path>`
- `cliproxyctl diag --config <path> --out <file|clipboard>`
Wails can call `internal/desktopctl` directly; Tauri can call `cliproxyctl`.
## Feature scope (v1)
### Core controls
- Start/Stop/Restart the proxy engine.
- Detect if a proxy is already running:
- If owned by UI: show as “Managed”.
- If not owned: show as “External” and offer “Attach” (read-only) vs “Stop anyway” behind a confirmation.
### Health
- Health check: `GET http://127.0.0.1:<port>/healthz`.
- Show last successful check time and last error message.
### Config
- Config path chooser + remember last choice.
- “Open config” action (external editor).
- Validate YAML on save (or show parse error).
### Logs / request diagnostics
- Open logs folder.
- Tail last N lines of `proxypilot-engine.out.log` and `proxypilot-engine.err.log`.
- “Copy diagnostics” button that includes:
- app version, proxy version
- config path, port, pid
- last error + last N log lines
- pointers to recent request logs
### Quick-copy snippets
- `OPENAI_BASE_URL=http://127.0.0.1:<port>/v1`
- `OPENAI_API_KEY=<your local key>`
- Minimal curl sanity checks.
## Nice-to-haves (v1.1+)
- “Recent requests” viewer (parse `logs/v1-*.log`):
- list request IDs, status, provider, model, auth label, latency
- click to open the log file at the relevant section
- Surface auth status:
- list loaded auth files + provider + account email (when available)
- show “cooling down” vs “active”
- optionally display primary/backup preference (e.g. `antigravity`)
- “Safe config wizard”:
- toggle localhost-only management
- add/generate local dev API key
- Update mechanism (self-update) and server binary update strategy.
## Security / safety rules
- Default to localhost-only assumptions.
- Don’t display or log API keys unless user explicitly reveals/copies them.
- Autostart toggles must show exactly what command will run.
- Avoid writing outside user profile by default.
## Cross-platform notes
Split OS-specific operations behind small interfaces in `internal/desktopctl`:
- Process operations (spawn, signal/terminate, pid discovery)
- Autostart
- “Open folder” / “Open URL”
Windows and macOS implementations can live in separate files via Go build tags:
- `*_windows.go`
- `*_darwin.go`
## Open questions
- Should the desktop app bundle the engine binary, or manage an existing install?
- Do we want a dedicated “desktop control” HTTP endpoint in the proxy (vs local process control only)?
+352
View File
@@ -0,0 +1,352 @@
# Long-Context Features in ProxyPilot
ProxyPilot implements two research-backed features for handling long-running AI agent sessions:
1. **Context Compression** - Based on Factory.ai research
2. **Agentic Harness** - Based on Anthropic's "Building Effective Agents" blog
Both are enabled by default and can be toggled via environment variables.
---
## Sources
| Feature | Source | Link |
|---------|--------|------|
| Context Compression | Factory.ai Research | [Context Compression for Long-Running Agents](https://www.factory.ai/news/context-compression) |
| Agentic Harness | Anthropic Blog | [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) |
---
## 1. Context Compression (Factory.ai)
### What Factory.ai Found
Factory.ai researched how to handle long coding sessions where conversation context exceeds model limits. Their key findings:
- **Naive truncation fails** - Cutting old messages loses critical context
- **Structured summarization works** - Preserving key information in a specific format maintains continuity
- **Anchored approach is best** - Merging new info into existing summaries beats creating fresh ones
### How ProxyPilot Implements It
When conversation exceeds 75% of the model's context window:
1. **Trigger**: Token count check detects threshold exceeded
2. **Summarize**: LLM generates structured summary of older messages
3. **Inject**: Summary replaces compressed messages in subsequent requests
### Structured Summary Format
```
## Session Intent
[High-level goal of the conversation]
## File Modifications
- path/to/file1.go: Added function X, modified Y
- path/to/file2.ts: Refactored component Z
## Decisions Made
- Chose approach A over B because...
- Confirmed that X should use pattern Y
## Next Steps
1. Implement feature X
2. Add tests for Y
## Technical Details
- Key code snippets or patterns
- Important variable names or function signatures
```
### Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CLIPROXY_TOKEN_AWARE_ENABLED` | `true` | Enable token-based compression |
| `CLIPROXY_LLM_SUMMARY_ENABLED` | `true` | Use LLM for summaries (vs regex fallback) |
| `CLIPROXY_COMPRESSION_THRESHOLD` | `0.75` | Trigger at this % of context |
| `CLIPROXY_SUMMARY_MODEL` | `gemini-3-flash` | Model used for summarization |
### Summary Model Selection
ProxyPilot uses a dedicated model for context summarization:
- **Primary**: `gemini-3-flash` via Antigravity provider
- **Fallback**: `gemini-3-flash-preview` (on model-not-found errors)
- **Final fallback**: Regex-based extraction (on any LLM failure)
This separation keeps summarization costs low while maintaining quality. The fallback chain ensures summarization never blocks the main request.
### Disable
```bash
export CLIPROXY_LLM_SUMMARY_ENABLED=false
```
---
## 2. Agentic Harness (Anthropic)
### What Anthropic Found
Anthropic's research on long-running agents identified key failure modes:
- Agents try to do everything at once and fail
- Agents don't track state between turns
- Agents skip verification ("the code looks correct")
- Agents lose context of what was already done
Their solution: **Structured harness with explicit state files and disciplined workflow.**
### How ProxyPilot Implements It
ProxyPilot injects prompts based on conversation state:
#### INITIALIZER Mode (First Request)
Injected when agentic client sends first request:
```
You are the Initializer Agent. Your ONLY goal is to set up the project environment.
1. Create 'feature_list.json' - List ALL features with:
- id, category, description, steps, passes: false, priority
2. Create 'claude-progress.txt' - Session log with:
- [Initializer] Environment setup started
3. Create 'init.sh' - Dev server startup script
DO NOT implement features. Only scaffold the harness files.
```
#### CODING Mode (After Harness Files Exist)
Injected when `feature_list.json` or `claude-progress.txt` detected:
```
You are a Coding Agent. Follow this workflow:
STEP 1: GET BEARINGS (MANDATORY)
- pwd, git log, cat claude-progress.txt, cat feature_list.json
STEP 2: SANITY CHECK
- Verify existing features work
- Fix regressions before new work
STEP 3: PICK ONE TASK
- Find highest-priority feature where passes: false
- Announce: "I will implement: [description]"
STEP 4: IMPLEMENT & VERIFY
- Write code for ONE feature only
- Run tests to verify it works
- Do NOT mark complete without actual testing
STEP 5: UPDATE STATE
- Set passes: true in feature_list.json
- Append to claude-progress.txt
STEP 6: COMMIT
- Git commit with feature ID in message
```
#### PASSIVE Mode
For non-agentic clients (browsers, curl), no prompts injected.
### Client Detection
Harness activates for these User-Agents:
- `claude-cli`
- `codex`
- `droid`
Or when header `X-ProxyPilot-Harness: true` is set.
### Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CLIPROXY_HARNESS_ENABLED` | `true` | Enable agentic harness |
| `CLIPROXY_MEMORY_DIR` | `~/.proxypilot/memory` | Session storage location |
### Disable
```bash
export CLIPROXY_HARNESS_ENABLED=false
```
---
## Implementation Details
### Files Modified
| File | Change |
|------|--------|
| `internal/memory/summarizer_executor.go` | Added `CoreManagerExecutor` interface and `ManagerAuthAdapter` |
| `internal/api/middleware/codex_prompt_budget.go` | Added `InitSummarizerWithAuthManager()` |
| `sdk/cliproxy/service.go` | Added `coreManagerWrapper`, wired up compression |
| `internal/api/server.go` | Registered `AgenticHarnessMiddleware()` |
### Files Created
| File | Purpose |
|------|---------|
| `internal/memory/summarizer_executor_test.go` | 12 unit tests for adapter |
| `internal/api/features_integration_test.go` | 3 integration tests |
### Architecture
```
Request Flow (Context Compression):
Client Request
│
▼
┌─────────────────────┐
│ PromptBudget │
│ Middleware │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Token Count Check │──── < 75% ────▶ Pass through
└─────────────────────┘
│
│ > 75%
▼
┌─────────────────────┐
│ PipelineSummarizer │
│ Executor │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ ManagerAuthAdapter │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ coreManagerWrapper │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Auth Manager │
│ (claude/codex/ │
│ gemini) │
└─────────────────────┘
```
```
Request Flow (Agentic Harness):
Client Request
│
▼
┌─────────────────────┐
│ Check User-Agent │──── Not agentic ────▶ Pass through
└─────────────────────┘
│
│ Agentic client
▼
┌─────────────────────┐
│ Detect Harness │
│ State │
└─────────────────────┘
│
├── No harness files + short convo ──▶ INITIALIZER prompt
│
├── Harness files exist ──────────────▶ CODING prompt
│
└── Long convo, no files ─────────────▶ PASSIVE (no injection)
```
---
## What Was NOT Implemented
During implementation, we removed features that were added by a previous session but **not from the original sources**:
| Removed | Reason |
|---------|--------|
| Puppeteer MCP detection | Not in Factory.ai or Anthropic sources |
| Browser automation reminders | Made up, not from research |
The current implementation is pure to the original Factory.ai and Anthropic research.
---
## Testing
```bash
# Run all tests
go test ./...
# Run specific feature tests
go test ./internal/memory/... -v # Compression adapter
go test ./internal/api/middleware/... -v -run Harness # Harness middleware
go test ./internal/api/... -v -run Integration # Integration tests
```
### Test Coverage
| Test File | Tests | Coverage |
|-----------|-------|----------|
| `summarizer_executor_test.go` | 12 | Adapter, pipeline, edge cases |
| `agentic_harness_test.go` | 10 | All modes, injection, session storage |
| `features_integration_test.go` | 3 | Combined feature validation |
---
## Quick Reference
### Enable/Disable Features
```bash
# Disable context compression
export CLIPROXY_LLM_SUMMARY_ENABLED=false
# Disable agentic harness
export CLIPROXY_HARNESS_ENABLED=false
# Disable both
export CLIPROXY_TOKEN_AWARE_ENABLED=false
export CLIPROXY_HARNESS_ENABLED=false
```
### Key Integration Points
```go
// Context Compression - sdk/cliproxy/service.go:516
middleware.InitSummarizerWithAuthManager(wrapper, providers)
// Agentic Harness - internal/api/server.go:224
engine.Use(middleware.AgenticHarnessMiddleware())
```
---
## Changelog
### 2025-12-31
- **Enhanced**: Multi-format response parsing (OpenAI, Claude, Gemini)
- **Added**: `SummaryModelFallbackExecutor` for model fallback (`gemini-3-flash` → `gemini-3-flash-preview`)
- **Added**: `CLIPROXY_SUMMARY_MODEL` env var for custom summary model
- **Added**: Dual output format (`summary.md` + `summary.json`)
- **Added**: 30+ unit tests for response parsing and model fallback
### 2025-12-27
- **Implemented**: Factory.ai-style context compression with LLM summarization
- **Implemented**: Anthropic-style agentic harness (INITIALIZER/CODING modes)
- **Added**: `ManagerAuthAdapter` to bridge auth manager types
- **Added**: `coreManagerWrapper` to adapt concrete types to interfaces
- **Added**: `InitSummarizerWithAuthManager()` for initialization
- **Added**: Session-based harness file storage
- **Added**: Comprehensive test coverage (25+ tests)
- **Removed**: Puppeteer MCP detection (not from original sources)
+8
View File
@@ -176,3 +176,11 @@ Management endpoints (local only):
- `GET /v0/management/memory/export-all`
- `POST /v0/management/memory/import?session=...`
- `POST /v0/management/memory/delete-all`
## LLM-Based Context Compression
For advanced context compression using LLM-generated structured summaries and token-aware proactive trimming, see [Context Compression](context-compression.md).
## Agentic Harness
For structured incremental development workflows (INITIALIZER/CODING modes, feature tracking, progress logging), see [Agentic Harness](agentic-harness.md).
@@ -0,0 +1,223 @@
# Provider Migration: iFlow → MiniMax + Zhipu AI
**Date:** 2025-12-28
**Version:** 0.1.6
## Summary
Removed the iFlow provider (complex OAuth/cookie authentication) and replaced it with two new direct API providers:
- **MiniMax** - `https://api.minimax.io/v1` (OpenAI-compatible, API key auth)
- **Zhipu AI** - `https://open.bigmodel.cn/api/paas/v4/` (OpenAI-compatible, API key auth)
Both new providers are significantly simpler than iFlow because they use API keys instead of OAuth.
---
## Changes Overview
### Providers Before
| Provider | Auth Method |
|----------|-------------|
| Claude | OAuth2 |
| Codex | OAuth2 |
| Gemini | OAuth2 |
| Gemini CLI | OAuth2 |
| Kiro | OAuth2 + AWS SSO |
| Qwen | OAuth2 |
| iFlow | OAuth + Cookie |
| **Total: 7** | |
### Providers After
| Provider | Auth Method |
|----------|-------------|
| Claude | OAuth2 |
| Codex | OAuth2 |
| Gemini | OAuth2 |
| Gemini CLI | OAuth2 |
| Kiro | OAuth2 + AWS SSO |
| Qwen | OAuth2 |
| MiniMax | API Key |
| Zhipu AI | API Key |
| **Total: 8** | |
---
## Files Deleted (iFlow Removal)
```
internal/auth/iflow/iflow_auth.go
internal/auth/iflow/iflow_token.go
internal/auth/iflow/oauth_server.go
internal/auth/iflow/cookie_helpers.go
internal/cmd/iflow_login.go
internal/cmd/iflow_cookie.go
internal/runtime/executor/iflow_executor.go
internal/api/handlers/management/iflow_import.go
internal/api/handlers/management/iflow_import_test.go
sdk/auth/iflow.go
```
---
## Files Created (New Providers)
### MiniMax Provider
```
internal/runtime/executor/minimax_executor.go # OpenAI-compatible executor
sdk/auth/minimax.go # API key authenticator
```
### Zhipu AI Provider
```
internal/runtime/executor/zhipu_executor.go # OpenAI-compatible executor
sdk/auth/zhipu.go # API key authenticator
```
---
## Files Modified
### Core Registration Files
| File | Changes |
|------|---------|
| `sdk/auth/refresh_registry.go` | Removed iFlow, added MiniMax + Zhipu registrations |
| `sdk/cliproxy/service.go` | Removed iFlow executor/model cases, added MiniMax + Zhipu |
| `internal/registry/model_definitions.go` | Removed `GetIFlowModels()`, added `GetMiniMaxModels()` + `GetZhipuModels()` |
| `internal/cmd/auth_manager.go` | Removed iFlow authenticator, added MiniMax + Zhipu |
### API/Server Files
| File | Changes |
|------|---------|
| `internal/api/server.go` | Removed iFlow OAuth routes |
| `internal/api/handlers/management/auth_files.go` | Removed iFlow import, removed `RequestIFlowToken` + `RequestIFlowCookieToken` handlers |
| `internal/api/handlers/management/oauth_sessions.go` | Removed iFlow case from provider normalization |
| `internal/api/handlers/management/generic_import.go` | Removed iFlow import, added `importResult` type definition |
### CLI Files
| File | Changes |
|------|---------|
| `cmd/server/main.go` | Removed `--iflow-login` and `--iflow-cookie` flags |
| `cmd/proxypilotui/main_windows.go` | Removed iFlow button and handler |
| `cmd/cliproxytray/main_windows.go` | Removed iFlow endpoint case |
### UI Files
| File | Changes |
|------|---------|
| `webui/src/components/layout/StatusBar.tsx` | Removed iFlow from provider list |
| `webui/src/components/dashboard/ProviderLogins.tsx` | Removed iFlow from provider list and auth detection |
### Documentation
| File | Changes |
|------|---------|
| `README.md` | Updated provider count (7→8), updated provider table |
| `docs/proxypilot.md` | Removed iFlow from one-click login list |
| `config.example.yaml` | Removed iFlow example |
| `cmd/installer/bundle/config.example.yaml` | Removed iFlow example |
---
## New Model Definitions
### MiniMax Models
| Model ID | Display Name | Description |
|----------|--------------|-------------|
| `minimax-m2` | MiniMax-M2 | Base model |
| `minimax-m2.1` | MiniMax-M2.1 | With reasoning support |
| `minimax-m2.1-lightning` | MiniMax-M2.1-Lightning | Fast variant |
### Zhipu AI Models
| Model ID | Display Name | Description |
|----------|--------------|-------------|
| `glm-4.7` | GLM-4.7 | Flagship model with thinking |
| `glm-4.6` | GLM-4.6 | High performance |
| `glm-4.5` | GLM-4.5 | Excellent for coding |
| `glm-4-long` | GLM-4-Long | 1M context window |
| `glm-4.6v` | GLM-4.6V | Vision model |
---
## API Details
### MiniMax
- **Base URL:** `https://api.minimax.io/v1`
- **Auth:** `Authorization: Bearer <API_KEY>`
- **Format:** OpenAI-compatible
- **Thinking:** M2.1 models support reasoning via `reasoning_split=true`
### Zhipu AI
- **Base URL:** `https://open.bigmodel.cn/api/paas/v4/`
- **Auth:** `Authorization: Bearer <API_KEY>`
- **Format:** OpenAI-compatible
- **Thinking:** GLM-4.6/4.7 support via `extra_body={"thinking": {"type": "enabled"}}`
---
## Auth File Format
Both providers use simple JSON with API key (no OAuth tokens needed):
```json
{
"type": "minimax",
"api_key": "sk-xxx",
"label": "my-account",
"created_at": "2025-12-28T12:00:00Z"
}
```
```json
{
"type": "zhipu",
"api_key": "xxx.yyy",
"label": "my-account",
"created_at": "2025-12-28T12:00:00Z"
}
```
---
## Usage
### Adding MiniMax API Key
Create a file `auth/minimax-myaccount.json`:
```json
{
"type": "minimax",
"api_key": "YOUR_MINIMAX_API_KEY",
"label": "myaccount"
}
```
### Adding Zhipu AI API Key
Create a file `auth/zhipu-myaccount.json`:
```json
{
"type": "zhipu",
"api_key": "YOUR_ZHIPU_API_KEY",
"label": "myaccount"
}
```
---
## Build Verification
```bash
go build ./...
# ✓ Build successful
```
---
## Migration Notes
1. **iFlow users:** If you have existing iFlow auth files, they will no longer work. Remove them from your `auth/` directory.
2. **Model mapping:** If you had model mappings pointing to iFlow models, update them to use the new providers:
- `glm-4.6` → Use Zhipu provider directly
- `glm-4.7` → Use Zhipu provider directly
- `minimax-m2` → Use MiniMax provider directly
3. **API keys:** Both MiniMax and Zhipu require API keys from their respective platforms:
- MiniMax: https://www.minimax.io/
- Zhipu AI: https://open.bigmodel.cn/
+3 -3
View File
@@ -1,12 +1,12 @@
# ProxyPilot
ProxyPilot is a local “AI proxy + desktop UX” for agentic CLIs (Droid/Factory, Codex CLI, Warp).
ProxyPilot is a local AI proxy with CLI + system tray interface for agentic tools (Droid/Factory, Codex CLI, Warp).
This repo started as a fork of CLIProxyAPI, but is now branded as ProxyPilot. For compatibility, some internal names and headers still use `CLIProxyAPI` (e.g. `X-CLIProxyAPI-*`).
## What’s included
- ProxyPilot tray app (Windows) to start/stop/restart the proxy engine, open the dashboard, open logs, and toggle autostart.
- ProxyPilot tray app (Windows) to start/stop/restart the proxy engine, open the web dashboard in browser, open logs, and toggle autostart.
- Prompt-budget middleware to reduce “prompt too long” failures in strict CLIs.
- Long-session memory with pinned state + persistent TODO (local disk).
- Optional auth debugging and cooldown reset endpoints for local troubleshooting.
@@ -58,7 +58,7 @@ The password is stored in the ProxyPilot UI state file:
ProxyPilot tray app includes:
- `Private OAuth window` toggle (opens Edge `--inprivate` when available)
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen, iFlow
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen
- `Open Auth Folder` shortcut
## Logs / diagnostics
-171
View File
@@ -1,171 +0,0 @@
# Windows UI for ProxyPilot — Spec (Wails + Tauri)
This is the Windows-specific portion of the desktop UI plan. Shared (cross-platform) decisions and architecture live in `docs/desktop-ui-spec.md`.
## Goals
- Provide a Windows-friendly way to run and manage `ProxyPilot` without PowerShell.
- Surface request/log diagnostics to reduce “prompt too long” + debugging pain.
- Support two desktop shells over time:
- Primary: Wails (Go backend + web UI)
- Secondary/experimental: Tauri (Rust + web UI)
- Share logic via a Go control layer so features don’t fork.
## Non-goals (v1)
- Replacing the existing Management API UI shipped with the server.
- Full cross-platform parity (macOS/Linux can come later).
- Full OAuth flows inside the desktop UI (v1 can “open browser” and show status).
- Becoming an agent/IDE: this is a small controller + diagnostics utility.
## Product decisions (to avoid bikeshedding)
- v1 ships as Wails.
- Tauri is optional later; it should reuse the same control layer via a helper CLI.
- The UI controls an existing `proxypilot-engine.exe` (built by the UI or already present).
- The UI should not require elevated privileges and should default to localhost-only behavior.
## Personas / Use-cases
- “I just want it running”: start/stop, see port, see health.
- “I need to debug”: view logs, open request logs, copy diagnostics.
- “I’m configuring tools”: show local base URL, API key hints, and quick-copy snippets.
- “I want it to launch on login”: enable/disable autostart (per-user).
## UX requirements
- Tray-first: app sits in the system tray with minimal friction.
- Single click status: Running/Stopped + port + quick actions.
- No admin required for normal operation.
- Clear failure reasons: missing config, port in use, binary missing, auth dir missing.
## Functional requirements (v1)
### Process control
- Build (optional): build `cmd/server` into `bin/proxypilot-engine.exe`.
- Start:
- Uses a selectable config path (default: repo `config.yaml` if present).
- Writes logs to `logs/proxypilot-engine.out.log` and `logs/proxypilot-engine.err.log`.
- Stop:
- Prefer graceful stop; fallback to kill process if needed.
- Restart.
- Detect running instance:
- PID-based if started by UI, plus best-effort discovery by listening port.
- If an instance is running but not owned by the UI, show “External” and offer read-only “Attach” (don’t blindly kill it).
### Status & health
- Show:
- port (from config or detection)
- reachable status via `GET http://127.0.0.1:<port>/v1/models` (or a future `/healthz`)
- last start time and PID (when known)
- Buttons:
- Open Management UI (browser)
- Open logs folder
- Copy base URL (`http://127.0.0.1:<port>` and optionally `/v1`)
### Config
- Config path selector (browse + remember last choice).
- Validate YAML on save (or warn on parse failure).
- Minimal editor:
- open in external editor, and/or inline text editor with Save.
- Safe defaults:
- warn if management routes are remotely accessible.
### Autostart (Windows)
- Enable/disable per-user startup on Windows.
- Backend supports:
- registry `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`
- scheduled task fallback (optional; clearly labeled)
### Quick-copy snippets (v1)
- Show ready-to-paste snippets:
- `OPENAI_BASE_URL=http://127.0.0.1:<port>/v1`
- `OPENAI_API_KEY=<your local key>`
- curl sanity check for `GET /v1/models`
### Diagnostics / support bundle (v1.1)
- One-click “Copy diagnostics”:
- version, config path, port, PID, last 200 lines of logs
- recent request logs list (or last N request IDs)
## Shared Go control layer (Windows notes)
Wails and Tauri should both call the same operations (process management, config, logs, autostart, health checks). See `docs/desktop-ui-spec.md` for the proposed package/API shape.
Windows-specific notes:
- Persist UI state in `%LOCALAPPDATA%/ProxyPilot/ui-state.json`.
- Prefer discover-by-port over discover-by-process-name.
- When opening folders/URLs, use native Windows shell APIs (no admin).
## Wails app (primary) — MVP
### Packaging
- Ship `ProxyPilot.exe` with embedded web UI assets.
- Bundle or download `proxypilot-engine.exe` (open decision).
### Screens
- Tray menu:
- Start / Stop / Restart
- Open UI
- Open logs
- Quit
- Main window:
- Status card (Running/Stopped, port, last error)
- Buttons: Start/Stop/Restart, Open Management UI, Open Logs
- Config path selector + Open config
- Autostart toggle
- Copy snippets section (base URL + key + curl check)
### First-run UX
- If no config path is set:
- Detect `config.yaml` in common locations (repo root, `%LOCALAPPDATA%/ProxyPilot/`, user home).
- Offer “Use detected config” or “Browse…”.
- If no API key is configured:
- Offer “Generate local key” (writes to config) or “Open config” guidance.
## Tauri app (secondary) — MVP
### Purpose
- Evaluate smaller footprint distribution vs Wails.
- Prototype a more native-feeling tray + notifications.
### Integration options
- Option A (recommended): Tauri calls a helper CLI (`cliproxyctl.exe`).
- Option B: Tauri starts a small local HTTP control server.
## Security considerations
- Default to localhost-only assumptions.
- Don’t display or log API keys unless explicitly requested.
- When enabling autostart, show what command will run.
- Avoid writing outside the user profile unless configured.
## Open decisions
- Where config lives by default (repo-local vs user config dir).
- Whether UI bundles the server binary or manages an existing install.
- Whether to add a stable `/healthz` endpoint for fast health checks.
- Whether “Generate local key” should mutate `config.yaml` or use a UI-only key store.
- Whether the UI should surface auth selection state (primary/backup) for providers like `antigravity`.
## Acceptance criteria (v1)
- Installing and launching the app shows a tray icon and a status window.
- Start/Stop/Restart works reliably across app restarts (PID state persisted).
- Health check distinguishes:
- process running but endpoint not reachable
- endpoint reachable with `GET /v1/models` returning 200
- Open logs opens the correct folder.
- Copy base URL copies `http://127.0.0.1:<port>` (and optionally `/v1`).
+249 -6
View File
@@ -14,12 +14,14 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
@@ -31,6 +33,8 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/logging"
sdktr "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
"github.com/tidwall/gjson"
"github.com/tiktoken-go/tokenizer"
)
const (
@@ -61,6 +65,185 @@ func init() {
)
}
// ============================================================================
// Token Counting Utilities
// ============================================================================
//
// This section demonstrates how to implement token counting for a custom provider.
// Token counting is important for:
// - Quota management and billing estimation
// - Ensuring requests don't exceed model context limits
// - Client-side optimization and request batching
//
// There are several approaches you can use:
//
// 1. SIMPLE ESTIMATION (shown in estimateTokens):
// - Fast and requires no external dependencies beyond string operations
// - Uses character count / 4 as a rough approximation
// - Good for quick estimates, less accurate for complex text
//
// 2. TIKTOKEN (shown in countWithTiktoken):
// - Uses OpenAI's tiktoken library for accurate BPE token counting
// - Best for OpenAI-compatible models (GPT-4, GPT-3.5, etc.)
// - Very accurate but requires the tiktoken-go package
//
// 3. UPSTREAM API (not shown):
// - Call your provider's token counting API endpoint
// - Most accurate but adds latency and API costs
// - Implement this if your provider offers a /count_tokens endpoint
//
// Choose the approach that best fits your accuracy needs and performance requirements.
var (
// tokenizerCache stores tokenizer instances to avoid repeated initialization.
// The sync.Map is safe for concurrent access.
tokenizerCache sync.Map
)
// getOrCreateTokenizer returns a cached tokenizer codec for the given model.
// This improves performance by avoiding repeated tokenizer initialization.
//
// Customize this function to map your provider's model names to appropriate
// tokenizer encodings. The tiktoken-go library provides encodings for:
// - O200kBase: GPT-4o, GPT-5, and newer models (default fallback)
// - Cl100kBase: GPT-4, GPT-3.5-turbo
// - P50kBase: text-davinci-003, Codex models
func getOrCreateTokenizer(model string) (tokenizer.Codec, error) {
// Check cache first
if cached, ok := tokenizerCache.Load(model); ok {
return cached.(tokenizer.Codec), nil
}
// Select encoding based on model prefix
// Customize this mapping for your provider's model naming convention
var enc tokenizer.Codec
var err error
sanitized := strings.ToLower(strings.TrimSpace(model))
switch {
// Example: Map your custom models to appropriate encodings
case strings.HasPrefix(sanitized, "myprov-gpt4"):
enc, err = tokenizer.ForModel(tokenizer.GPT4)
case strings.HasPrefix(sanitized, "myprov-gpt3"):
enc, err = tokenizer.ForModel(tokenizer.GPT35Turbo)
case strings.HasPrefix(sanitized, "gpt-4o"), strings.HasPrefix(sanitized, "gpt-4.1"):
enc, err = tokenizer.ForModel(tokenizer.GPT4o)
case strings.HasPrefix(sanitized, "gpt-4"):
enc, err = tokenizer.ForModel(tokenizer.GPT4)
case strings.HasPrefix(sanitized, "gpt-3.5"):
enc, err = tokenizer.ForModel(tokenizer.GPT35Turbo)
default:
// Default to O200kBase - the most recent encoding for modern models
enc, err = tokenizer.Get(tokenizer.O200kBase)
}
if err != nil {
return nil, err
}
// Store in cache (use LoadOrStore to handle race conditions)
actual, _ := tokenizerCache.LoadOrStore(model, enc)
return actual.(tokenizer.Codec), nil
}
// estimateTokens provides a simple token count estimation without external libraries.
// This is useful as a fallback when tiktoken is unavailable or for quick approximations.
//
// The algorithm uses character count / 4, which is based on the observation that
// English text averages about 4 characters per token. This is less accurate for:
// - Code (typically more tokens per character)
// - Non-English text (varies by language)
// - Text with many special characters or numbers
//
// For production use, consider tiktoken for better accuracy.
func estimateTokens(text string) int {
if len(text) == 0 {
return 0
}
// Simple estimation: ~4 characters per token on average
// This is a reasonable approximation for English text
tokens := len(text) / 4
if tokens == 0 && len(text) > 0 {
tokens = 1 // At least 1 token for non-empty text
}
return tokens
}
// countWithTiktoken counts tokens using the tiktoken BPE tokenizer.
// This provides accurate token counts for OpenAI-compatible models.
//
// For custom providers with different tokenization schemes, you may need to:
// - Apply an adjustment factor (e.g., multiply by 1.1 for Claude models)
// - Use a custom tokenizer that matches your provider's implementation
// - Call your provider's native token counting API instead
func countWithTiktoken(enc tokenizer.Codec, text string) (int, error) {
if enc == nil {
return 0, fmt.Errorf("tokenizer is nil")
}
_, tokens, err := enc.Encode(text)
if err != nil {
return 0, err
}
return len(tokens), nil
}
// extractMessagesText extracts all text content from an OpenAI-format chat request.
// This handles the standard messages array structure with role/content fields.
//
// Customize this function if your provider uses a different request format.
func extractMessagesText(payload []byte) string {
if len(payload) == 0 {
return ""
}
root := gjson.ParseBytes(payload)
var segments []string
// Extract from messages array (OpenAI chat format)
messages := root.Get("messages")
if messages.Exists() && messages.IsArray() {
messages.ForEach(func(_, msg gjson.Result) bool {
// Extract role for context (adds ~1 token overhead per message)
if role := msg.Get("role").String(); role != "" {
segments = append(segments, role)
}
// Extract text content
content := msg.Get("content")
if content.IsArray() {
// Handle array content (e.g., with images)
content.ForEach(func(_, part gjson.Result) bool {
if part.Get("type").String() == "text" {
if text := part.Get("text").String(); text != "" {
segments = append(segments, text)
}
}
return true
})
} else if text := content.String(); text != "" {
segments = append(segments, text)
}
return true
})
}
// Extract from prompt field (completion format)
if prompt := root.Get("prompt").String(); prompt != "" {
segments = append(segments, prompt)
}
// Extract from input field (some APIs use this)
if input := root.Get("input").String(); input != "" {
segments = append(segments, input)
}
// Extract system prompt if present at top level
if system := root.Get("system").String(); system != "" {
segments = append(segments, system)
}
return strings.Join(segments, "\n")
}
// MyExecutor is a minimal provider implementation for demonstration purposes.
// It implements the Executor interface to handle requests to a custom AI provider.
type MyExecutor struct{}
@@ -122,7 +305,9 @@ func (MyExecutor) Execute(ctx context.Context, a *coreauth.Auth, req clipexec.Re
httpReq.Header.Set("Content-Type", "application/json")
// Inject credentials via PrepareRequest hook.
_ = (MyExecutor{}).PrepareRequest(httpReq, a)
if errPrep := (MyExecutor{}).PrepareRequest(httpReq, a); errPrep != nil {
return clipexec.Response{}, errPrep
}
resp, errDo := client.Do(httpReq)
if errDo != nil {
@@ -130,21 +315,79 @@ func (MyExecutor) Execute(ctx context.Context, a *coreauth.Auth, req clipexec.Re
}
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
// Best-effort close; log if needed in real projects.
fmt.Fprintf(os.Stderr, "close response body error: %v\n", errClose)
}
}()
body, _ := io.ReadAll(resp.Body)
return clipexec.Response{Payload: body}, nil
}
func (MyExecutor) CountTokens(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("count tokens not implemented")
// CountTokens counts tokens in the request payload.
// This implementation demonstrates a layered approach:
// 1. Try tiktoken for accurate BPE-based counting
// 2. Fall back to simple character-based estimation if tiktoken fails
//
// The response format follows the Anthropic API convention: {"count": <number>}
// Adjust the response format to match your provider's expected format.
//
// For production use, consider:
// - Caching token counts for identical payloads
// - Using your provider's native token counting API if available
// - Applying model-specific adjustment factors
func (MyExecutor) CountTokens(_ context.Context, _ *coreauth.Auth, req clipexec.Request, _ clipexec.Options) (clipexec.Response, error) {
var tokenCount int
// Extract text content from the request payload
text := extractMessagesText(req.Payload)
// If no text was extracted from structured fields, use raw payload
if text == "" && len(req.Payload) > 0 {
text = string(req.Payload)
}
// Try tiktoken first for accurate counting
enc, err := getOrCreateTokenizer(req.Model)
if err == nil {
// Successfully got a tokenizer, use it for accurate counting
count, countErr := countWithTiktoken(enc, text)
if countErr == nil {
tokenCount = count
} else {
// Tiktoken encoding failed, fall back to estimation
tokenCount = estimateTokens(text)
}
} else {
// Could not get tokenizer, fall back to simple estimation
tokenCount = estimateTokens(text)
}
// Return response in the expected format
// The format follows Anthropic's count_tokens response: {"count": <number>}
// Adjust this format to match your provider's API specification
response := fmt.Sprintf(`{"count":%d}`, tokenCount)
return clipexec.Response{Payload: []byte(response)}, nil
}
func (MyExecutor) Embed(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("embeddings not implemented")
}
func (MyExecutor) HttpRequest(ctx context.Context, a *coreauth.Auth, req *http.Request) (*http.Response, error) {
if req == nil {
return nil, fmt.Errorf("myprov executor: request is nil")
}
if ctx == nil {
ctx = req.Context()
}
httpReq := req.WithContext(ctx)
if errPrep := (MyExecutor{}).PrepareRequest(httpReq, a); errPrep != nil {
return nil, errPrep
}
client := buildHTTPClient(a)
return client.Do(httpReq)
}
func (MyExecutor) ExecuteStream(ctx context.Context, a *coreauth.Auth, req clipexec.Request, opts clipexec.Options) (<-chan clipexec.StreamChunk, error) {
ch := make(chan clipexec.StreamChunk, 1)
go func() {
@@ -203,8 +446,8 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := svc.Run(ctx); err != nil && !errors.Is(err, context.Canceled) {
panic(err)
if errRun := svc.Run(ctx); errRun != nil && !errors.Is(errRun, context.Canceled) {
panic(errRun)
}
_ = os.Stderr // keep os import used (demo only)
_ = time.Second
+144
View File
@@ -0,0 +1,144 @@
// Package main demonstrates how to use coreauth.Manager.HttpRequest/NewHttpRequest
// to execute arbitrary HTTP requests with provider credentials injected.
//
// This example registers a minimal custom executor that injects an Authorization
// header from auth.Attributes["api_key"], then performs two requests against
// httpbin.org to show the injected headers.
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
clipexec "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
log "github.com/sirupsen/logrus"
)
const providerKey = "echo"
// EchoExecutor is a minimal provider implementation for demonstration purposes.
type EchoExecutor struct{}
func (EchoExecutor) Identifier() string { return providerKey }
func (EchoExecutor) PrepareRequest(req *http.Request, auth *coreauth.Auth) error {
if req == nil || auth == nil {
return nil
}
if auth.Attributes != nil {
if apiKey := strings.TrimSpace(auth.Attributes["api_key"]); apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
}
return nil
}
func (EchoExecutor) HttpRequest(ctx context.Context, auth *coreauth.Auth, req *http.Request) (*http.Response, error) {
if req == nil {
return nil, fmt.Errorf("echo executor: request is nil")
}
if ctx == nil {
ctx = req.Context()
}
httpReq := req.WithContext(ctx)
if errPrep := (EchoExecutor{}).PrepareRequest(httpReq, auth); errPrep != nil {
return nil, errPrep
}
return http.DefaultClient.Do(httpReq)
}
func (EchoExecutor) Execute(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("echo executor: Execute not implemented")
}
func (EchoExecutor) ExecuteStream(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (<-chan clipexec.StreamChunk, error) {
return nil, errors.New("echo executor: ExecuteStream not implemented")
}
func (EchoExecutor) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) {
return nil, errors.New("echo executor: Refresh not implemented")
}
func (EchoExecutor) CountTokens(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("echo executor: CountTokens not implemented")
}
func (EchoExecutor) Embed(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("echo executor: Embed not implemented")
}
func main() {
log.SetLevel(log.InfoLevel)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
core := coreauth.NewManager(nil, nil, nil)
core.RegisterExecutor(EchoExecutor{})
auth := &coreauth.Auth{
ID: "demo-echo",
Provider: providerKey,
Attributes: map[string]string{
"api_key": "demo-api-key",
},
}
// Example 1: Build a prepared request and execute it using your own http.Client.
reqPrepared, errReqPrepared := core.NewHttpRequest(
ctx,
auth,
http.MethodGet,
"https://httpbin.org/anything",
nil,
http.Header{"X-Example": []string{"prepared"}},
)
if errReqPrepared != nil {
panic(errReqPrepared)
}
respPrepared, errDoPrepared := http.DefaultClient.Do(reqPrepared)
if errDoPrepared != nil {
panic(errDoPrepared)
}
defer func() {
if errClose := respPrepared.Body.Close(); errClose != nil {
log.Errorf("close response body error: %v", errClose)
}
}()
bodyPrepared, errReadPrepared := io.ReadAll(respPrepared.Body)
if errReadPrepared != nil {
panic(errReadPrepared)
}
fmt.Printf("Prepared request status: %d\n%s\n\n", respPrepared.StatusCode, bodyPrepared)
// Example 2: Execute a raw request via core.HttpRequest (auto inject + do).
rawBody := []byte(`{"hello":"world"}`)
rawReq, errRawReq := http.NewRequestWithContext(ctx, http.MethodPost, "https://httpbin.org/anything", bytes.NewReader(rawBody))
if errRawReq != nil {
panic(errRawReq)
}
rawReq.Header.Set("Content-Type", "application/json")
rawReq.Header.Set("X-Example", "executed")
respExec, errDoExec := core.HttpRequest(ctx, auth, rawReq)
if errDoExec != nil {
panic(errDoExec)
}
defer func() {
if errClose := respExec.Body.Close(); errClose != nil {
log.Errorf("close response body error: %v", errClose)
}
}()
bodyExec, errReadExec := io.ReadAll(respExec.Body)
if errReadExec != nil {
panic(errReadExec)
}
fmt.Printf("Manager HttpRequest status: %d\n%s\n", respExec.StatusCode, bodyExec)
}
+36 -4
View File
@@ -3,7 +3,11 @@ module github.com/router-for-me/CLIProxyAPI/v6
go 1.24.0
require (
github.com/ProtonMail/go-crypto v1.3.0
github.com/andybalholm/brotli v1.0.6
github.com/charmbracelet/bubbles v0.21.0
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/fsnotify/fsnotify v1.9.0
github.com/getlantern/systray v1.2.2
github.com/gin-gonic/gin v1.10.1
@@ -13,9 +17,11 @@ require (
github.com/jackc/pgx/v5 v5.7.6
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047
github.com/joho/godotenv v1.5.1
github.com/klauspost/compress v1.17.4
github.com/klauspost/compress v1.18.0
github.com/minio/minio-go/v7 v7.0.66
github.com/pelletier/go-toml/v2 v2.2.2
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/prometheus/client_golang v1.23.2
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
@@ -28,14 +34,21 @@ require (
golang.org/x/term v0.37.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.42.2
)
require (
cloud.google.com/go/compute/metadata v0.3.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.3.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/x/ansi v0.10.1 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/cloudflare/circl v1.6.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
@@ -44,6 +57,7 @@ require (
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 // indirect
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 // indirect
@@ -68,24 +82,42 @@ require (
github.com/kevinburke/ssh_config v1.4.0 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pjbgf/sha1cd v0.5.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
modernc.org/libc v1.66.10 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)
+100 -8
View File
@@ -10,10 +10,30 @@ github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFI
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
@@ -33,6 +53,8 @@ github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
@@ -79,9 +101,11 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -104,8 +128,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kevinburke/ssh_config v1.4.0 h1:6xxtP5bZ2E4NF5tuQulISpTO2z8XbtH8cg1PWkxoFkQ=
github.com/kevinburke/ssh_config v1.4.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
@@ -117,12 +141,20 @@ github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3x
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ=
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.0.66 h1:bnTOXOHjOqv/gcMuiVbN9o2ngRItvqE774dG9nq0Dzw=
@@ -134,6 +166,16 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
@@ -144,6 +186,19 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
@@ -182,11 +237,21 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
@@ -196,6 +261,7 @@ golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -205,10 +271,10 @@ golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -223,5 +289,31 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.42.2 h1:7hkZUNJvJFN2PgfUdjni9Kbvd4ef4mNLOu0B9FGxM74=
modernc.org/sqlite v1.42.2/go.mod h1:+VkC6v3pLOAE0A0uVucQEcbVW0I5nHCeDaBf+DpsQT8=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
+34
View File
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ProxyPilot Installer</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #0a0a0b;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1926
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "proxypilot-installer-ui",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"framer-motion": "^11.15.0"
},
"devDependencies": {
"@types/react": "^18.3.17",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"terser": "^5.37.0",
"typescript": "~5.6.2",
"vite": "^6.0.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+122
View File
@@ -0,0 +1,122 @@
import { useState, useEffect, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { WelcomeStep } from './components/WelcomeStep'
import { InstallingStep } from './components/InstallingStep'
import { CompleteStep } from './components/CompleteStep'
import { setProgressCallback } from './main'
type InstallStep = 'welcome' | 'installing' | 'complete'
function App() {
const [step, setStep] = useState<InstallStep>('welcome')
const [progress, setProgress] = useState(0)
const [status, setStatus] = useState('Preparing installation...')
const handleProgress = useCallback((percent: number, statusText: string) => {
setProgress(percent)
setStatus(statusText)
if (percent >= 100) {
setTimeout(() => setStep('complete'), 800)
}
}, [])
useEffect(() => {
setProgressCallback(handleProgress)
}, [handleProgress])
const handleInstall = () => {
setStep('installing')
setProgress(0)
setStatus('Preparing installation...')
window.installer.startInstall()
}
const handleLaunch = () => {
window.installer.launch()
}
const pageVariants = {
initial: {
opacity: 0,
y: 20
},
animate: {
opacity: 1,
y: 0,
transition: {
duration: 0.4,
ease: [0.25, 0.1, 0.25, 1]
}
},
exit: {
opacity: 0,
y: -20,
transition: {
duration: 0.3,
ease: [0.25, 0.1, 0.25, 1]
}
}
}
return (
<div className="app-container">
<main className="main-content">
<AnimatePresence mode="wait">
{step === 'welcome' && (
<motion.div
key="welcome"
variants={pageVariants}
initial="initial"
animate="animate"
exit="exit"
className="step-container"
>
<WelcomeStep onInstall={handleInstall} />
</motion.div>
)}
{step === 'installing' && (
<motion.div
key="installing"
variants={pageVariants}
initial="initial"
animate="animate"
exit="exit"
className="step-container"
>
<InstallingStep progress={progress} status={status} />
</motion.div>
)}
{step === 'complete' && (
<motion.div
key="complete"
variants={pageVariants}
initial="initial"
animate="animate"
exit="exit"
className="step-container"
>
<CompleteStep onLaunch={handleLaunch} />
</motion.div>
)}
</AnimatePresence>
</main>
{/* Window Controls */}
<div className="window-controls">
<button
className="window-btn"
onClick={() => window.installer.close()}
aria-label="Close"
>
<svg viewBox="0 0 10 10" fill="none">
<path d="M1 1L9 9M9 1L1 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
</svg>
</button>
</div>
</div>
)
}
export default App
@@ -0,0 +1,85 @@
import { motion } from 'framer-motion'
interface CompleteStepProps {
onLaunch: () => void
}
export function CompleteStep({ onLaunch }: CompleteStepProps) {
return (
<div className="complete-step">
{/* Success Icon */}
<motion.div
className="success-icon-container"
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{
type: 'spring',
stiffness: 200,
damping: 15,
delay: 0.1
}}
>
<div className="success-icon">
<svg viewBox="0 0 24 24" fill="none">
<motion.path
d="M5 13l4 4L19 7"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
strokeLinejoin="round"
initial={{ pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.4, delay: 0.3 }}
/>
</svg>
</div>
</motion.div>
{/* Success Content */}
<motion.div
className="success-content"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4, duration: 0.4 }}
>
<h2 className="success-title">Installation Complete</h2>
<p className="success-message">
ProxyPilot has been installed successfully and is ready to use.
</p>
</motion.div>
{/* Launch Button */}
<motion.button
className="launch-btn"
onClick={onLaunch}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5, duration: 0.4 }}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<svg viewBox="0 0 20 20" fill="none">
<path d="M4 10h12m0 0l-4-4m4 4l-4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
Launch ProxyPilot
</motion.button>
{/* Post Install Info */}
<motion.div
className="post-install-info"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.6, duration: 0.4 }}
>
<div className="info-icon">
<svg viewBox="0 0 16 16" fill="none">
<circle cx="8" cy="8" r="7" stroke="currentColor" strokeWidth="1.5"/>
<path d="M8 5v3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
<circle cx="8" cy="11" r="0.75" fill="currentColor"/>
</svg>
</div>
<p>ProxyPilot will start automatically and run in the system tray.</p>
</motion.div>
</div>
)
}
@@ -0,0 +1,78 @@
import { motion } from 'framer-motion'
interface InstallingStepProps {
progress: number
status: string
}
export function InstallingStep({ progress, status }: InstallingStepProps) {
const radius = 52
const circumference = 2 * Math.PI * radius
const strokeDashoffset = circumference - (circumference * progress) / 100
return (
<div className="installing-step">
{/* Progress Circle */}
<motion.div
className="progress-circle-container"
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.5 }}
>
<svg className="progress-circle" viewBox="0 0 120 120">
<circle
className="progress-circle-bg"
cx="60"
cy="60"
r={radius}
/>
<motion.circle
className="progress-circle-fill"
cx="60"
cy="60"
r={radius}
strokeDasharray={circumference}
strokeDashoffset={strokeDashoffset}
initial={{ strokeDashoffset: circumference }}
animate={{ strokeDashoffset }}
transition={{ duration: 0.3, ease: 'easeOut' }}
/>
</svg>
<div className="progress-percent">
{Math.round(progress)}<span>%</span>
</div>
</motion.div>
{/* Progress Info */}
<motion.div
className="progress-info"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.4 }}
>
<h2 className="installing-title">Installing ProxyPilot</h2>
{/* Progress Bar */}
<div className="progress-bar-container">
<motion.div
className="progress-bar-fill"
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 0.3, ease: 'easeOut' }}
/>
</div>
{/* Status */}
<motion.p
className="status-text"
key={status}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.2 }}
>
{status}
</motion.p>
</motion.div>
</div>
)
}
+104
View File
@@ -0,0 +1,104 @@
import { motion } from 'framer-motion'
interface WelcomeStepProps {
onInstall: () => void
}
export function WelcomeStep({ onInstall }: WelcomeStepProps) {
const features = [
{ icon: 'route', text: 'Route AI requests seamlessly' },
{ icon: 'config', text: 'One config, all providers' },
{ icon: 'shield', text: 'Privacy-first local processing' }
]
return (
<div className="welcome-step">
{/* Logo */}
<motion.div
className="logo-container"
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ duration: 0.5, ease: [0.25, 0.1, 0.25, 1] }}
>
<img src="/logo.png" alt="ProxyPilot" />
</motion.div>
{/* Text Content */}
<motion.div
className="text-content"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1, duration: 0.4 }}
>
<h1 className="app-name">ProxyPilot</h1>
<p className="app-tagline">Navigate AI with precision</p>
</motion.div>
{/* Features Card */}
<motion.div
className="features-card"
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.4 }}
>
<div className="features">
{features.map((feature, i) => (
<motion.div
key={feature.icon}
className="feature"
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.3 + i * 0.1, duration: 0.3 }}
>
<span className="feature-icon">
{feature.icon === 'route' && (
<svg viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M5.05 3.636a1 1 0 010 1.414 7 7 0 000 9.9 1 1 0 11-1.414 1.414 9 9 0 010-12.728 1 1 0 011.414 0zm9.9 0a1 1 0 011.414 0 9 9 0 010 12.728 1 1 0 11-1.414-1.414 7 7 0 000-9.9 1 1 0 010-1.414zM7.879 6.464a1 1 0 010 1.414 3 3 0 000 4.243 1 1 0 11-1.415 1.414 5 5 0 010-7.07 1 1 0 011.415 0zm4.242 0a1 1 0 011.415 0 5 5 0 010 7.072 1 1 0 01-1.415-1.415 3 3 0 000-4.242 1 1 0 010-1.415zM10 9a1 1 0 011 1v.01a1 1 0 11-2 0V10a1 1 0 011-1z" clipRule="evenodd"/>
</svg>
)}
{feature.icon === 'config' && (
<svg viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd"/>
</svg>
)}
{feature.icon === 'shield' && (
<svg viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd"/>
</svg>
)}
</span>
<span>{feature.text}</span>
</motion.div>
))}
</div>
</motion.div>
{/* Install Button */}
<motion.button
className="install-btn"
onClick={onInstall}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4, duration: 0.4 }}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<svg viewBox="0 0 20 20" fill="none">
<path d="M10 3v10m0 0l-4-4m4 4l4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
<path d="M3 15v1a2 2 0 002 2h10a2 2 0 002-2v-1" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
</svg>
Install ProxyPilot
</motion.button>
{/* Version */}
<motion.p
className="version-info"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.5, duration: 0.4 }}
>
v0.1.6
</motion.p>
</div>
)
}
+526
View File
@@ -0,0 +1,526 @@
/* ============================================
ProxyPilot Installer - Clean Professional Theme
Inspired by Perplexity Comet's minimal aesthetic
============================================ */
:root {
/* Dark theme colors */
--bg-primary: #0a0a0b;
--bg-secondary: #111113;
--bg-elevated: #18181b;
--bg-hover: #1f1f23;
/* Text colors */
--text-primary: #fafafa;
--text-secondary: #a1a1aa;
--text-muted: #71717a;
/* Accent - ProxyPilot blue */
--accent: #3b82f6;
--accent-hover: #2563eb;
--accent-glow: rgba(59, 130, 246, 0.15);
/* Success green */
--success: #22c55e;
--success-glow: rgba(34, 197, 94, 0.15);
/* Borders */
--border: rgba(255, 255, 255, 0.08);
--border-hover: rgba(255, 255, 255, 0.12);
/* Spacing */
--space-xs: 8px;
--space-sm: 12px;
--space-md: 16px;
--space-lg: 24px;
--space-xl: 32px;
--space-2xl: 48px;
/* Typography */
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-mono: 'SF Mono', 'Fira Code', monospace;
/* Transitions */
--transition-fast: 150ms ease;
--transition-base: 200ms ease;
--transition-slow: 300ms ease;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: var(--font-sans);
font-size: 14px;
line-height: 1.5;
color: var(--text-primary);
background: var(--bg-primary);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* ============================================
App Container
============================================ */
.app-container {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
background: var(--bg-primary);
position: relative;
}
/* Subtle gradient background */
.app-container::before {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(
ellipse 80% 50% at 50% -20%,
var(--accent-glow) 0%,
transparent 70%
);
pointer-events: none;
}
/* ============================================
Window Controls
============================================ */
.window-controls {
position: absolute;
top: var(--space-md);
right: var(--space-md);
z-index: 100;
-webkit-app-region: no-drag;
}
.window-btn {
width: 32px;
height: 32px;
border-radius: 8px;
border: none;
background: transparent;
color: var(--text-muted);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all var(--transition-fast);
}
.window-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.window-btn svg {
width: 12px;
height: 12px;
}
/* ============================================
Main Content
============================================ */
.main-content {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-xl);
-webkit-app-region: drag;
}
.step-container {
width: 100%;
max-width: 400px;
-webkit-app-region: no-drag;
}
/* ============================================
Welcome Step
============================================ */
.welcome-step {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-lg);
text-align: center;
}
/* Logo */
.logo-container {
width: 96px;
height: 96px;
border-radius: 24px;
overflow: hidden;
box-shadow:
0 0 0 1px var(--border),
0 8px 32px rgba(0, 0, 0, 0.4),
0 0 60px var(--accent-glow);
}
.logo-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
/* Text content */
.text-content {
display: flex;
flex-direction: column;
gap: var(--space-xs);
}
.app-name {
font-size: 28px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.02em;
}
.app-tagline {
font-size: 15px;
color: var(--text-secondary);
}
/* Features */
.features-card {
width: 100%;
padding: var(--space-lg);
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 16px;
}
.features {
display: flex;
flex-direction: column;
gap: var(--space-sm);
}
.feature {
display: flex;
align-items: center;
gap: var(--space-sm);
font-size: 14px;
color: var(--text-secondary);
}
.feature-icon {
width: 20px;
height: 20px;
color: var(--accent);
flex-shrink: 0;
}
.feature-icon svg {
width: 100%;
height: 100%;
}
/* Install Button */
.install-btn {
width: 100%;
height: 48px;
border: none;
border-radius: 12px;
background: var(--accent);
color: white;
font-family: var(--font-sans);
font-size: 15px;
font-weight: 500;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-xs);
transition: all var(--transition-fast);
}
.install-btn:hover {
background: var(--accent-hover);
transform: translateY(-1px);
}
.install-btn:active {
transform: translateY(0);
}
.install-btn svg {
width: 18px;
height: 18px;
}
/* Version */
.version-info {
font-size: 12px;
color: var(--text-muted);
font-family: var(--font-mono);
}
/* ============================================
Installing Step
============================================ */
.installing-step {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-xl);
text-align: center;
}
/* Progress Circle */
.progress-circle-container {
position: relative;
width: 120px;
height: 120px;
}
.progress-circle {
width: 100%;
height: 100%;
transform: rotate(-90deg);
}
.progress-circle-bg {
fill: none;
stroke: var(--bg-elevated);
stroke-width: 8;
}
.progress-circle-fill {
fill: none;
stroke: var(--accent);
stroke-width: 8;
stroke-linecap: round;
transition: stroke-dashoffset var(--transition-slow);
}
.progress-percent {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
font-weight: 600;
color: var(--text-primary);
}
.progress-percent span {
font-size: 16px;
color: var(--text-muted);
margin-left: 2px;
}
/* Progress Info */
.progress-info {
display: flex;
flex-direction: column;
gap: var(--space-md);
width: 100%;
}
.installing-title {
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
}
/* Progress Bar */
.progress-bar-container {
width: 100%;
height: 6px;
background: var(--bg-elevated);
border-radius: 3px;
overflow: hidden;
}
.progress-bar-fill {
height: 100%;
background: var(--accent);
border-radius: 3px;
transition: width var(--transition-slow);
}
/* Status */
.status-text {
font-size: 14px;
color: var(--text-secondary);
min-height: 21px;
}
/* ============================================
Complete Step
============================================ */
.complete-step {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-lg);
text-align: center;
}
/* Success Icon */
.success-icon-container {
width: 80px;
height: 80px;
border-radius: 50%;
background: var(--success-glow);
display: flex;
align-items: center;
justify-content: center;
}
.success-icon {
width: 48px;
height: 48px;
color: var(--success);
}
.success-icon svg {
width: 100%;
height: 100%;
}
/* Success Content */
.success-content {
display: flex;
flex-direction: column;
gap: var(--space-xs);
}
.success-title {
font-size: 24px;
font-weight: 600;
color: var(--text-primary);
}
.success-message {
font-size: 14px;
color: var(--text-secondary);
line-height: 1.6;
}
/* Launch Button */
.launch-btn {
width: 100%;
height: 48px;
border: none;
border-radius: 12px;
background: var(--success);
color: white;
font-family: var(--font-sans);
font-size: 15px;
font-weight: 500;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-xs);
transition: all var(--transition-fast);
}
.launch-btn:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.launch-btn:active {
transform: translateY(0);
}
.launch-btn svg {
width: 18px;
height: 18px;
}
/* Post Install Info */
.post-install-info {
display: flex;
align-items: center;
gap: var(--space-sm);
padding: var(--space-md);
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
width: 100%;
}
.info-icon {
width: 16px;
height: 16px;
color: var(--text-muted);
flex-shrink: 0;
}
.info-icon svg {
width: 100%;
height: 100%;
}
.post-install-info p {
font-size: 13px;
color: var(--text-muted);
text-align: left;
}
/* ============================================
Accessibility
============================================ */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* ============================================
Responsive
============================================ */
@media (max-height: 400px) {
.main-content {
padding: var(--space-md);
}
.logo-container {
width: 72px;
height: 72px;
border-radius: 18px;
}
.welcome-step,
.installing-step,
.complete-step {
gap: var(--space-md);
}
.progress-circle-container {
width: 100px;
height: 100px;
}
}
+68
View File
@@ -0,0 +1,68 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
// Type declarations for Go/WebView2 bridge
declare global {
interface Window {
installer: {
startInstall: (options?: { installPath?: string }) => void
launch: () => void
close: () => void
}
setProgress: (percent: number, status: string) => void
}
}
// Store progress callback for Go to call
let progressCallback: ((percent: number, status: string) => void) | null = null
export function setProgressCallback(callback: (percent: number, status: string) => void) {
progressCallback = callback
}
// Expose to Go backend
window.setProgress = (percent: number, status: string) => {
if (progressCallback) {
progressCallback(percent, status)
}
}
// Mock installer for development (will be replaced by WebView2 in production)
if (!window.installer) {
window.installer = {
startInstall: () => {
console.log('Mock: Starting installation...')
let progress = 0
const steps = [
'Preparing installation...',
'Extracting files...',
'Installing components...',
'Configuring ProxyPilot...',
'Finishing up...'
]
const interval = setInterval(() => {
progress += Math.random() * 15 + 5
if (progress >= 100) {
progress = 100
clearInterval(interval)
}
const stepIndex = Math.min(Math.floor(progress / 20), steps.length - 1)
window.setProgress(Math.round(progress), steps[stepIndex])
}, 500)
},
launch: () => {
console.log('Mock: Launching ProxyPilot...')
},
close: () => {
console.log('Mock: Closing installer...')
}
}
}
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/components/completestep.tsx","./src/components/installingstep.tsx","./src/components/welcomestep.tsx"],"version":"5.6.3"}
+2
View File
@@ -0,0 +1,2 @@
declare const _default: import("vite").UserConfig;
export default _default;
+28
View File
@@ -0,0 +1,28 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
base: './',
build: {
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},
rollupOptions: {
output: {
manualChunks: undefined,
inlineDynamicImports: true
}
}
},
server: {
port: 3000,
strictPort: true
}
});
+29
View File
@@ -0,0 +1,29 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: './',
build: {
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},
rollupOptions: {
output: {
manualChunks: undefined,
inlineDynamicImports: true
}
}
},
server: {
port: 3000,
strictPort: true
}
})
+38
View File
@@ -0,0 +1,38 @@
# ProxyPilot Installer Assets
This folder contains custom branding assets for the Inno Setup installer.
## Required Images
### 1. wizard-large.bmp (164x314 pixels)
- Displayed on the left side of the installer wizard
- Should feature the ProxyPilot logo/branding
- Must be a 24-bit BMP file (no alpha channel)
### 2. wizard-small.bmp (55x55 pixels)
- Displayed in the top-right corner of wizard pages
- Usually just the ProxyPilot icon
- Must be a 24-bit BMP file (no alpha channel)
## Generating Images
Run the PowerShell script to auto-generate from the existing icon:
```powershell
.\generate-wizard-images.ps1
```
Or manually create them:
1. Open `static/icon.png` in an image editor
2. Create a 164x314 canvas with your brand colors
3. Place the logo centered with product name below
4. Export as 24-bit BMP (no alpha)
## Enabling Custom Images
Once images are created, uncomment these lines in `proxypilot.iss`:
```ini
WizardImageFile={#RepoRoot}\installer\assets\wizard-large.bmp
WizardSmallImageFile={#RepoRoot}\installer\assets\wizard-small.bmp
```
@@ -0,0 +1,312 @@
# ProxyPilot Premium Installer Graphics Generator
# Creates distinctive, high-quality wizard images
param(
[string]$SourceIcon = "..\..\static\icon.png",
[string]$OutputDir = "."
)
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$ErrorActionPreference = "Stop"
# Premium color palette extracted from the icon
$Colors = @{
DeepNavy = [System.Drawing.Color]::FromArgb(255, 15, 23, 42) # #0F172A
RichBlue = [System.Drawing.Color]::FromArgb(255, 30, 58, 138) # #1E3A8A
VibrantBlue = [System.Drawing.Color]::FromArgb(255, 59, 130, 246) # #3B82F6
SkyBlue = [System.Drawing.Color]::FromArgb(255, 96, 165, 250) # #60A5FA
LightBlue = [System.Drawing.Color]::FromArgb(255, 147, 197, 253) # #93C5FD
PureWhite = [System.Drawing.Color]::FromArgb(255, 255, 255, 255)
SoftWhite = [System.Drawing.Color]::FromArgb(255, 248, 250, 252) # #F8FAFC
GlowBlue = [System.Drawing.Color]::FromArgb(80, 96, 165, 250) # Semi-transparent glow
SubtleGlow = [System.Drawing.Color]::FromArgb(30, 147, 197, 253)
}
function Add-Noise {
param(
[System.Drawing.Graphics]$g,
[int]$width,
[int]$height,
[int]$intensity = 8
)
$random = New-Object System.Random
for ($i = 0; $i -lt ($width * $height / 50); $i++) {
$x = $random.Next($width)
$y = $random.Next($height)
$alpha = $random.Next(5, $intensity)
$color = [System.Drawing.Color]::FromArgb($alpha, 255, 255, 255)
$brush = New-Object System.Drawing.SolidBrush($color)
$g.FillRectangle($brush, $x, $y, 1, 1)
$brush.Dispose()
}
}
function Draw-FlowingLine {
param(
[System.Drawing.Graphics]$g,
[float]$startX,
[float]$startY,
[float]$endX,
[float]$endY,
[System.Drawing.Color]$color,
[float]$width = 1.5
)
$pen = New-Object System.Drawing.Pen($color, $width)
$pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
$pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
# Create curved path
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
$ctrlX1 = $startX + ($endX - $startX) * 0.3
$ctrlY1 = $startY + ($endY - $startY) * 0.1
$ctrlX2 = $startX + ($endX - $startX) * 0.7
$ctrlY2 = $endY - ($endY - $startY) * 0.1
$path.AddBezier($startX, $startY, $ctrlX1, $ctrlY1, $ctrlX2, $ctrlY2, $endX, $endY)
$g.DrawPath($pen, $path)
# Draw node at end
$nodeBrush = New-Object System.Drawing.SolidBrush($color)
$g.FillEllipse($nodeBrush, ($endX - 2), ($endY - 2), 4, 4)
$pen.Dispose()
$path.Dispose()
$nodeBrush.Dispose()
}
function New-PremiumWizardLarge {
param([string]$IconPath, [string]$OutputPath)
$width = 164
$height = 314
$bitmap = New-Object System.Drawing.Bitmap($width, $height, [System.Drawing.Imaging.PixelFormat]::Format24bppRgb)
$g = [System.Drawing.Graphics]::FromImage($bitmap)
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
$g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
# === BACKGROUND: Rich multi-stop gradient ===
$gradientRect = New-Object System.Drawing.Rectangle(0, 0, $width, $height)
# Primary gradient: Deep navy to rich blue
$mainGradient = New-Object System.Drawing.Drawing2D.LinearGradientBrush(
(New-Object System.Drawing.Point(0, 0)),
(New-Object System.Drawing.Point(0, $height)),
$Colors.DeepNavy,
$Colors.RichBlue
)
$g.FillRectangle($mainGradient, $gradientRect)
$mainGradient.Dispose()
# Overlay: Subtle radial-like glow from center-top
$glowPath = New-Object System.Drawing.Drawing2D.GraphicsPath
$glowPath.AddEllipse(-50, -100, $width + 100, 300)
$glowBrush = New-Object System.Drawing.Drawing2D.PathGradientBrush($glowPath)
$glowBrush.CenterColor = [System.Drawing.Color]::FromArgb(40, 59, 130, 246)
$glowBrush.SurroundColors = @([System.Drawing.Color]::FromArgb(0, 59, 130, 246))
$g.FillPath($glowBrush, $glowPath)
$glowBrush.Dispose()
$glowPath.Dispose()
# === DECORATIVE ELEMENTS: Flowing network lines ===
$lineColor1 = [System.Drawing.Color]::FromArgb(25, 147, 197, 253)
$lineColor2 = [System.Drawing.Color]::FromArgb(35, 96, 165, 250)
$lineColor3 = [System.Drawing.Color]::FromArgb(20, 255, 255, 255)
# Network lines emanating from where icon will be
$centerX = $width / 2
$iconBottom = 140
Draw-FlowingLine $g $centerX $iconBottom 20 200 $lineColor1 1.2
Draw-FlowingLine $g $centerX $iconBottom 144 210 $lineColor2 1.0
Draw-FlowingLine $g $centerX $iconBottom 30 240 $lineColor3 0.8
Draw-FlowingLine $g $centerX $iconBottom 134 250 $lineColor1 1.0
Draw-FlowingLine $g $centerX $iconBottom 50 270 $lineColor2 0.8
Draw-FlowingLine $g $centerX $iconBottom 114 280 $lineColor3 0.6
# === SUBTLE NOISE TEXTURE ===
Add-Noise $g $width $height 6
# === ICON: Load and draw with glow effect ===
if (Test-Path $IconPath) {
$icon = [System.Drawing.Image]::FromFile((Resolve-Path $IconPath))
$iconSize = 90
$iconX = ($width - $iconSize) / 2
$iconY = 45
# Glow behind icon
$glowSize = $iconSize + 30
$glowX = ($width - $glowSize) / 2
$glowY = $iconY - 15
$iconGlowPath = New-Object System.Drawing.Drawing2D.GraphicsPath
$iconGlowPath.AddEllipse($glowX, $glowY, $glowSize, $glowSize)
$iconGlowBrush = New-Object System.Drawing.Drawing2D.PathGradientBrush($iconGlowPath)
$iconGlowBrush.CenterColor = [System.Drawing.Color]::FromArgb(60, 96, 165, 250)
$iconGlowBrush.SurroundColors = @([System.Drawing.Color]::FromArgb(0, 96, 165, 250))
$g.FillPath($iconGlowBrush, $iconGlowPath)
$iconGlowBrush.Dispose()
$iconGlowPath.Dispose()
# Draw the icon
$g.DrawImage($icon, $iconX, $iconY, $iconSize, $iconSize)
$icon.Dispose()
}
# === TYPOGRAPHY: Product name ===
# Try to use Segoe UI Semibold for modern Windows feel, fall back gracefully
$titleFont = $null
try {
$titleFont = New-Object System.Drawing.Font("Segoe UI Semibold", 16, [System.Drawing.FontStyle]::Regular)
} catch {
$titleFont = New-Object System.Drawing.Font("Segoe UI", 16, [System.Drawing.FontStyle]::Bold)
}
$titleBrush = New-Object System.Drawing.SolidBrush($Colors.PureWhite)
$titleFormat = New-Object System.Drawing.StringFormat
$titleFormat.Alignment = [System.Drawing.StringAlignment]::Center
$titleFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
$titleRect = New-Object System.Drawing.RectangleF(0, 150, $width, 30)
$g.DrawString("ProxyPilot", $titleFont, $titleBrush, $titleRect, $titleFormat)
$titleFont.Dispose()
# === TAGLINE ===
$tagFont = New-Object System.Drawing.Font("Segoe UI", 8.5, [System.Drawing.FontStyle]::Regular)
$tagBrush = New-Object System.Drawing.SolidBrush($Colors.LightBlue)
$tagRect = New-Object System.Drawing.RectangleF(0, 178, $width, 20)
$g.DrawString("Local AI Proxy", $tagFont, $tagBrush, $tagRect, $titleFormat)
$tagFont.Dispose()
$tagBrush.Dispose()
# === DECORATIVE SEPARATOR LINE ===
$separatorPen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(60, 96, 165, 250), 1)
$g.DrawLine($separatorPen, 30, 205, $width - 30, 205)
$separatorPen.Dispose()
# === VERSION/SETUP TEXT ===
$setupFont = New-Object System.Drawing.Font("Segoe UI", 7.5, [System.Drawing.FontStyle]::Regular)
$setupBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(140, 248, 250, 252))
$setupRect = New-Object System.Drawing.RectangleF(0, 290, $width, 18)
$g.DrawString("Setup Wizard", $setupFont, $setupBrush, $setupRect, $titleFormat)
$setupFont.Dispose()
$setupBrush.Dispose()
# === BOTTOM ACCENT: Subtle gradient bar ===
$accentY = $height - 4
$accentRect = New-Object System.Drawing.Rectangle(0, $accentY, $width, 4)
$accentGradient = New-Object System.Drawing.Drawing2D.LinearGradientBrush(
(New-Object System.Drawing.Point(0, 0)),
(New-Object System.Drawing.Point($width, 0)),
[System.Drawing.Color]::FromArgb(100, 30, 58, 138),
$Colors.VibrantBlue
)
$g.FillRectangle($accentGradient, $accentRect)
$accentGradient.Dispose()
# Cleanup
$titleBrush.Dispose()
$titleFormat.Dispose()
$g.Dispose()
# Save as 24-bit BMP
$bitmap.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Bmp)
$bitmap.Dispose()
Write-Host " Created: wizard-large.bmp (164x314)" -ForegroundColor Green
}
function New-PremiumWizardSmall {
param([string]$IconPath, [string]$OutputPath)
$size = 55
$bitmap = New-Object System.Drawing.Bitmap($size, $size, [System.Drawing.Imaging.PixelFormat]::Format24bppRgb)
$g = [System.Drawing.Graphics]::FromImage($bitmap)
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$g.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality
# Gradient background matching large panel
$gradient = New-Object System.Drawing.Drawing2D.LinearGradientBrush(
(New-Object System.Drawing.Point(0, 0)),
(New-Object System.Drawing.Point(0, $size)),
$Colors.DeepNavy,
$Colors.RichBlue
)
$g.FillRectangle($gradient, 0, 0, $size, $size)
$gradient.Dispose()
# Subtle glow in center
$glowPath = New-Object System.Drawing.Drawing2D.GraphicsPath
$glowDim = $size - 10
$glowPath.AddEllipse(5, 5, $glowDim, $glowDim)
$glowBrush = New-Object System.Drawing.Drawing2D.PathGradientBrush($glowPath)
$glowBrush.CenterColor = [System.Drawing.Color]::FromArgb(50, 59, 130, 246)
$glowBrush.SurroundColors = @([System.Drawing.Color]::FromArgb(0, 59, 130, 246))
$g.FillPath($glowBrush, $glowPath)
$glowBrush.Dispose()
$glowPath.Dispose()
# Draw icon
if (Test-Path $IconPath) {
$icon = [System.Drawing.Image]::FromFile((Resolve-Path $IconPath))
$iconSize = 42
$offset = ($size - $iconSize) / 2
$g.DrawImage($icon, $offset, $offset, $iconSize, $iconSize)
$icon.Dispose()
}
# Subtle border
$borderPen = New-Object System.Drawing.Pen([System.Drawing.Color]::FromArgb(40, 96, 165, 250), 1)
$borderSize = $size - 1
$g.DrawRectangle($borderPen, 0, 0, $borderSize, $borderSize)
$borderPen.Dispose()
$g.Dispose()
$bitmap.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Bmp)
$bitmap.Dispose()
Write-Host " Created: wizard-small.bmp (55x55)" -ForegroundColor Green
}
# === MAIN EXECUTION ===
Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host " ProxyPilot Premium Installer Graphics" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Push-Location $scriptDir
try {
$iconFullPath = Resolve-Path $SourceIcon -ErrorAction Stop
Write-Host "Source: $iconFullPath" -ForegroundColor DarkGray
Write-Host ""
Write-Host "Generating premium wizard images..." -ForegroundColor Yellow
Write-Host ""
New-PremiumWizardLarge -IconPath $iconFullPath -OutputPath (Join-Path $OutputDir "wizard-large.bmp")
New-PremiumWizardSmall -IconPath $iconFullPath -OutputPath (Join-Path $OutputDir "wizard-small.bmp")
Write-Host ""
Write-Host "Done! Premium graphics generated." -ForegroundColor Green
Write-Host ""
}
catch {
Write-Host "Error: $_" -ForegroundColor Red
Write-Host $_.ScriptStackTrace -ForegroundColor DarkRed
exit 1
}
finally {
Pop-Location
}
+157
View File
@@ -0,0 +1,157 @@
# ProxyPilot Installer - Wizard Image Generator
# Generates branded wizard images for Inno Setup installer
param(
[string]$SourceIcon = "..\..\static\icon.png",
[string]$OutputDir = "."
)
Add-Type -AssemblyName System.Drawing
$ErrorActionPreference = "Stop"
# ProxyPilot brand colors
$BrandColors = @{
Primary = [System.Drawing.Color]::FromArgb(59, 130, 246) # Blue
Secondary = [System.Drawing.Color]::FromArgb(30, 41, 59) # Dark slate
Background = [System.Drawing.Color]::FromArgb(15, 23, 42) # Darker slate
Text = [System.Drawing.Color]::FromArgb(248, 250, 252) # Light text
}
function New-WizardLargeImage {
param([string]$IconPath, [string]$OutputPath)
$width = 164
$height = 314
$bitmap = New-Object System.Drawing.Bitmap($width, $height)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
# Create gradient background
$gradientBrush = New-Object System.Drawing.Drawing2D.LinearGradientBrush(
(New-Object System.Drawing.Point(0, 0)),
(New-Object System.Drawing.Point(0, $height)),
$BrandColors.Background,
$BrandColors.Secondary
)
$graphics.FillRectangle($gradientBrush, 0, 0, $width, $height)
# Load and draw icon
if (Test-Path $IconPath) {
$icon = [System.Drawing.Image]::FromFile((Resolve-Path $IconPath))
$iconSize = 80
$iconX = ($width - $iconSize) / 2
$iconY = 60
$graphics.DrawImage($icon, $iconX, $iconY, $iconSize, $iconSize)
$icon.Dispose()
}
# Draw product name
$font = New-Object System.Drawing.Font("Segoe UI", 14, [System.Drawing.FontStyle]::Bold)
$textBrush = New-Object System.Drawing.SolidBrush($BrandColors.Text)
$textFormat = New-Object System.Drawing.StringFormat
$textFormat.Alignment = [System.Drawing.StringAlignment]::Center
$textRect = New-Object System.Drawing.RectangleF(0, 160, $width, 30)
$graphics.DrawString("ProxyPilot", $font, $textBrush, $textRect, $textFormat)
$font.Dispose()
# Draw tagline
$smallFont = New-Object System.Drawing.Font("Segoe UI", 8, [System.Drawing.FontStyle]::Regular)
$taglineRect = New-Object System.Drawing.RectangleF(0, 190, $width, 40)
$graphics.DrawString("Local AI Proxy", $smallFont, $textBrush, $taglineRect, $textFormat)
$smallFont.Dispose()
# Draw decorative line
$linePen = New-Object System.Drawing.Pen($BrandColors.Primary, 2)
$graphics.DrawLine($linePen, 30, 240, $width - 30, 240)
$linePen.Dispose()
# Draw version indicator area
$versionFont = New-Object System.Drawing.Font("Segoe UI", 7, [System.Drawing.FontStyle]::Regular)
$versionRect = New-Object System.Drawing.RectangleF(0, 280, $width, 20)
$dimBrush = New-Object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(150, 248, 250, 252))
$graphics.DrawString("Setup Wizard", $versionFont, $dimBrush, $versionRect, $textFormat)
$versionFont.Dispose()
$dimBrush.Dispose()
# Clean up
$textBrush.Dispose()
$textFormat.Dispose()
$gradientBrush.Dispose()
$graphics.Dispose()
# Save as 24-bit BMP (required by Inno Setup)
$bitmap.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Bmp)
$bitmap.Dispose()
Write-Host "Created: $OutputPath" -ForegroundColor Green
}
function New-WizardSmallImage {
param([string]$IconPath, [string]$OutputPath)
$size = 55
$bitmap = New-Object System.Drawing.Bitmap($size, $size)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
$graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
# Fill with brand background
$backgroundBrush = New-Object System.Drawing.SolidBrush($BrandColors.Secondary)
$graphics.FillRectangle($backgroundBrush, 0, 0, $size, $size)
$backgroundBrush.Dispose()
# Load and draw icon
if (Test-Path $IconPath) {
$icon = [System.Drawing.Image]::FromFile((Resolve-Path $IconPath))
$iconSize = 45
$offset = ($size - $iconSize) / 2
$graphics.DrawImage($icon, $offset, $offset, $iconSize, $iconSize)
$icon.Dispose()
}
$graphics.Dispose()
# Save as 24-bit BMP
$bitmap.Save($OutputPath, [System.Drawing.Imaging.ImageFormat]::Bmp)
$bitmap.Dispose()
Write-Host "Created: $OutputPath" -ForegroundColor Green
}
# Main execution
Write-Host ""
Write-Host "ProxyPilot Installer - Wizard Image Generator" -ForegroundColor Cyan
Write-Host "=============================================" -ForegroundColor Cyan
Write-Host ""
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Push-Location $scriptDir
try {
$iconFullPath = Resolve-Path $SourceIcon -ErrorAction Stop
Write-Host "Source icon: $iconFullPath"
Write-Host ""
New-WizardLargeImage -IconPath $iconFullPath -OutputPath (Join-Path $OutputDir "wizard-large.bmp")
New-WizardSmallImage -IconPath $iconFullPath -OutputPath (Join-Path $OutputDir "wizard-small.bmp")
Write-Host ""
Write-Host "Done! Wizard images created successfully." -ForegroundColor Green
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Uncomment the WizardImageFile lines in proxypilot.iss"
Write-Host "2. Rebuild the installer"
Write-Host ""
}
catch {
Write-Host "Error: $_" -ForegroundColor Red
exit 1
}
finally {
Pop-Location
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

+111 -20
View File
@@ -1,6 +1,6 @@
#define AppName "ProxyPilot"
#ifndef AppVersion
#define AppVersion "0.0.0-dev"
#define AppVersion "0.1.0"
#endif
#ifndef RepoRoot
#define RepoRoot ".."
@@ -10,50 +10,132 @@
#endif
[Setup]
; --- App Identity ---
AppId={{3D9053A0-3F6A-47D7-9D91-8BB1D1CC2A4E}
AppName={#AppName}
AppVersion={#AppVersion}
AppVerName={#AppName} {#AppVersion}
AppPublisher=ProxyPilot
SetupIconFile={#RepoRoot}\\bin\\ProxyPilot.ico
DefaultDirName={localappdata}\\{#AppName}
AppPublisherURL=https://github.com/Finesssee/ProxyPilot
AppSupportURL=https://github.com/Finesssee/ProxyPilot/issues
AppUpdatesURL=https://github.com/Finesssee/ProxyPilot/releases
AppComments=Local AI Proxy with Embedded Engine - Route AI requests seamlessly
AppContact=https://github.com/Finesssee/ProxyPilot
; --- Installation Paths ---
DefaultDirName={localappdata}\{#AppName}
DefaultGroupName={#AppName}
DisableProgramGroupPage=yes
PrivilegesRequired=lowest
Compression=lzma2
ArchitecturesInstallIn64BitMode=x64compatible
; --- Compression ---
Compression=lzma2/ultra64
SolidCompression=yes
; --- Installer Appearance ---
WizardStyle=modern
ArchitecturesInstallIn64BitMode=x64
WizardSizePercent=100
WizardResizable=no
; --- Custom Branding Images ---
; WizardImageFile: Left panel image (164x314 pixels for modern style)
; WizardSmallImageFile: Top-right corner image (55x55 pixels)
WizardImageFile={#RepoRoot}\installer\assets\wizard-large.bmp
WizardSmallImageFile={#RepoRoot}\installer\assets\wizard-small.bmp
; --- Icons ---
SetupIconFile={#RepoRoot}\static\icon.ico
UninstallDisplayIcon={app}\icon.ico
; --- Output ---
OutputDir={#OutDir}
OutputBaseFilename=ProxyPilot-Setup
UninstallDisplayIcon={app}\\ProxyPilot.ico
OutputBaseFilename=ProxyPilot-{#AppVersion}-Setup
; --- Installer Window Title ---
AppCopyright=MIT License - ProxyPilot Contributors
; --- Version Info Embedded in Installer ---
VersionInfoVersion={#AppVersion}
VersionInfoCompany=ProxyPilot
VersionInfoDescription=ProxyPilot Installer - Local AI Proxy
VersionInfoTextVersion={#AppVersion}
VersionInfoCopyright=MIT License
VersionInfoProductName=ProxyPilot
VersionInfoProductVersion={#AppVersion}
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Messages]
; --- Custom Welcome Page Text ---
WelcomeLabel1=Welcome to ProxyPilot
WelcomeLabel2=This will install [name/ver] on your computer.%n%nProxyPilot is a local AI proxy that routes requests to Claude, OpenAI, and other providers with automatic credential management.%n%nIt is recommended that you close all other applications before continuing.
; --- Custom Finished Page Text ---
FinishedHeadingLabel=ProxyPilot Installation Complete
FinishedLabelNoIcons=Setup has finished installing [name] on your computer.
FinishedLabel=Setup has finished installing [name] on your computer. ProxyPilot will appear in your system tray.
; --- Custom Ready Page ---
ReadyLabel1=Ready to Install
ReadyLabel2a=Click Install to begin the ProxyPilot installation.
ReadyLabel2b=Click Install to begin the ProxyPilot installation. Review your settings below:
; --- Custom Select Dir Page ---
SelectDirLabel3=ProxyPilot will be installed in the following folder.
SelectDirBrowseLabel=To continue, click Next. To select a different folder, click Browse.
; --- Custom Buttons (optional - uncomment to customize) ---
; ButtonNext=&Continue
; ButtonInstall=&Install ProxyPilot
; ButtonFinish=&Launch ProxyPilot
[Tasks]
Name: "desktopicon"; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:"
Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription: "Additional shortcuts:"; Flags: unchecked
Name: "startupicon"; Description: "Launch ProxyPilot when Windows starts"; GroupDescription: "Startup options:"; Flags: checkedonce
[Files]
Source: "{#RepoRoot}\\bin\\ProxyPilot.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\ProxyPilotUI.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\proxypilot-engine.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\ProxyPilot.ico"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\config.example.yaml"; DestDir: "{app}"; Flags: ignoreversion
; Main app (tray + dashboard UI)
Source: "{#OutDir}\ProxyPilot.exe"; DestDir: "{app}"; Flags: ignoreversion
; Config
Source: "{#RepoRoot}\config.example.yaml"; DestDir: "{app}"; Flags: ignoreversion
; Icons and branding
Source: "{#RepoRoot}\static\icon.ico"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\static\icon.png"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
Name: "{autoprograms}\\{#AppName}"; Filename: "{app}\\ProxyPilot.exe"; WorkingDir: "{app}"; IconFilename: "{app}\\ProxyPilot.ico"
Name: "{autodesktop}\\{#AppName}"; Filename: "{app}\\ProxyPilot.exe"; Tasks: desktopicon; WorkingDir: "{app}"; IconFilename: "{app}\\ProxyPilot.ico"
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\ProxyPilot.exe"; WorkingDir: "{app}"; IconFilename: "{app}\icon.ico"; Comment: "Launch ProxyPilot - Local AI Proxy"
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\ProxyPilot.exe"; Tasks: desktopicon; WorkingDir: "{app}"; IconFilename: "{app}\icon.ico"; Comment: "Launch ProxyPilot"
[Registry]
Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueType: string; ValueName: "ProxyPilot"; ValueData: """{app}\ProxyPilot.exe"""; Flags: uninsdeletevalue; Tasks: startupicon
[Run]
Filename: "{app}\\ProxyPilot.exe"; Description: "Launch {#AppName}"; Flags: nowait postinstall skipifsilent
Filename: "{app}\ProxyPilot.exe"; Description: "Launch {#AppName} now"; Flags: nowait postinstall skipifsilent
[UninstallRun]
Filename: "cmd.exe"; Parameters: "/c reg delete HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v ProxyPilot /f >nul 2>nul"; Flags: runhidden
Filename: "taskkill"; Parameters: "/F /IM ProxyPilot.exe"; Flags: runhidden; RunOnceId: "KillTray"
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
[Code]
// Custom colors and initialization
procedure InitializeWizard();
begin
// Set custom header color (ProxyPilot blue theme)
WizardForm.Color := $00362B21; // Dark background
// Customize the main panel if desired
// WizardForm.MainPanel.Color := $00362B21;
// Make the installer window title more branded
WizardForm.Caption := 'ProxyPilot Setup';
end;
procedure CurStepChanged(CurStep: TSetupStep);
var
ConfigYaml: string;
@@ -61,11 +143,20 @@ var
begin
if CurStep = ssPostInstall then
begin
ConfigYaml := ExpandConstant('{app}\\config.yaml');
ExampleYaml := ExpandConstant('{app}\\config.example.yaml');
// Auto-create config.yaml from example if it doesn't exist
ConfigYaml := ExpandConstant('{app}\config.yaml');
ExampleYaml := ExpandConstant('{app}\config.example.yaml');
if (not FileExists(ConfigYaml)) and FileExists(ExampleYaml) then
begin
FileCopy(ExampleYaml, ConfigYaml, False);
CopyFile(ExampleYaml, ConfigYaml, False);
end;
end;
end;
// Custom uninstall confirmation message
function InitializeUninstall(): Boolean;
begin
Result := MsgBox('Are you sure you want to uninstall ProxyPilot?' + #13#10 + #13#10 +
'Your configuration files will be preserved.',
mbConfirmation, MB_YESNO) = IDYES;
end;
+276
View File
@@ -0,0 +1,276 @@
package agents
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// AmazonQCLIHandler handles Amazon Q CLI detection and configuration.
// Amazon Q CLI is only available on Linux/macOS or via WSL on Windows.
// It stores tokens in a SQLite database at ~/.local/share/amazon-q/data.sqlite3
type AmazonQCLIHandler struct {
// wslDistro is the WSL distribution name (Windows only)
wslDistro string
// wslUser is the WSL username (Windows only)
wslUser string
}
// NewAmazonQCLIHandler creates a new Amazon Q CLI handler
func NewAmazonQCLIHandler() *AmazonQCLIHandler {
return &AmazonQCLIHandler{}
}
func (h *AmazonQCLIHandler) ID() string {
return "amazonq-cli"
}
func (h *AmazonQCLIHandler) Name() string {
return "Amazon Q CLI"
}
func (h *AmazonQCLIHandler) CanAutoConfigure() bool {
// Amazon Q CLI uses its own auth, no configuration needed from our side
return false
}
func (h *AmazonQCLIHandler) GetConfigPath() string {
if runtime.GOOS == "windows" {
// Return WSL path for display purposes
return "\\\\wsl$\\<distro>\\home\\<user>\\.local\\share\\amazon-q\\data.sqlite3"
}
homeDir, _ := os.UserHomeDir()
return filepath.Join(homeDir, ".local", "share", "amazon-q", "data.sqlite3")
}
// Detect checks if Amazon Q CLI is installed
func (h *AmazonQCLIHandler) Detect() (bool, error) {
if runtime.GOOS == "windows" {
return h.detectInWSL()
}
return h.detectNative()
}
// detectNative checks for q CLI on Linux/macOS
func (h *AmazonQCLIHandler) detectNative() (bool, error) {
// Check for 'q' binary in PATH
if _, err := exec.LookPath("q"); err == nil {
return true, nil
}
// Check common installation locations
homeDir, _ := os.UserHomeDir()
locations := []string{
filepath.Join(homeDir, ".local", "bin", "q"),
"/usr/local/bin/q",
}
for _, loc := range locations {
if _, err := os.Stat(loc); err == nil {
return true, nil
}
}
// Check for data directory (indicates Q CLI was installed and used)
dataDir := filepath.Join(homeDir, ".local", "share", "amazon-q")
if _, err := os.Stat(dataDir); err == nil {
return true, nil
}
return false, nil
}
// detectInWSL checks for q CLI within WSL
func (h *AmazonQCLIHandler) detectInWSL() (bool, error) {
// Check if WSL is available
if _, err := exec.LookPath("wsl"); err != nil {
return false, nil
}
// Get default WSL distro
distro, err := h.getDefaultWSLDistro()
if err != nil || distro == "" {
return false, nil
}
h.wslDistro = distro
// Get WSL username
user, err := h.getWSLUsername(distro)
if err != nil || user == "" {
return false, nil
}
h.wslUser = user
// Check for q CLI in WSL
cmd := exec.Command("wsl", "-d", distro, "--", "which", "q")
if err := cmd.Run(); err == nil {
return true, nil
}
// Check for common install locations in WSL
checkCmd := exec.Command("wsl", "-d", distro, "--", "test", "-f", fmt.Sprintf("/home/%s/.local/bin/q", user))
if err := checkCmd.Run(); err == nil {
return true, nil
}
// Check for data directory in WSL
dataCmd := exec.Command("wsl", "-d", distro, "--", "test", "-d", fmt.Sprintf("/home/%s/.local/share/amazon-q", user))
if err := dataCmd.Run(); err == nil {
return true, nil
}
return false, nil
}
// getDefaultWSLDistro returns the default WSL distribution name
func (h *AmazonQCLIHandler) getDefaultWSLDistro() (string, error) {
// First try to get default distro
cmd := exec.Command("wsl", "-l", "-q")
output, err := cmd.Output()
if err != nil {
return "", err
}
// Parse output - first line is usually the default distro
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, line := range lines {
// Clean up the line (remove null bytes from UTF-16 encoding on Windows)
line = strings.TrimSpace(line)
line = strings.ReplaceAll(line, "\x00", "")
if line != "" && line != "docker-desktop" && line != "docker-desktop-data" {
return line, nil
}
}
return "", fmt.Errorf("no WSL distribution found")
}
// getWSLUsername returns the default username in the WSL distribution
func (h *AmazonQCLIHandler) getWSLUsername(distro string) (string, error) {
cmd := exec.Command("wsl", "-d", distro, "--", "whoami")
output, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(output)), nil
}
// IsConfigured checks if Amazon Q CLI is authenticated
func (h *AmazonQCLIHandler) IsConfigured(proxyURL string) (bool, error) {
// Check if the SQLite database exists with auth tokens
dbPath, err := h.GetDatabasePath()
if err != nil {
return false, nil
}
// Check if file exists
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
return false, nil
}
// Database exists, assume configured (actual token validation happens in auth layer)
return true, nil
}
// GetDatabasePath returns the path to the Amazon Q SQLite database
func (h *AmazonQCLIHandler) GetDatabasePath() (string, error) {
if runtime.GOOS == "windows" {
if h.wslDistro == "" || h.wslUser == "" {
// Try to detect
distro, err := h.getDefaultWSLDistro()
if err != nil {
return "", fmt.Errorf("no WSL distribution found: %w", err)
}
h.wslDistro = distro
user, err := h.getWSLUsername(distro)
if err != nil {
return "", fmt.Errorf("failed to get WSL user: %w", err)
}
h.wslUser = user
}
// Windows UNC path to WSL filesystem
return fmt.Sprintf(`\\wsl$\%s\home\%s\.local\share\amazon-q\data.sqlite3`, h.wslDistro, h.wslUser), nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(homeDir, ".local", "share", "amazon-q", "data.sqlite3"), nil
}
// Enable is not supported for Amazon Q CLI (uses its own auth)
func (h *AmazonQCLIHandler) Enable(proxyURL string) ([]Change, error) {
return nil, fmt.Errorf("Amazon Q CLI uses its own authentication. Run 'q login' to authenticate")
}
// Disable is not supported for Amazon Q CLI
func (h *AmazonQCLIHandler) Disable(changes []Change) error {
// Nothing to disable - Q CLI manages its own auth
return nil
}
// GetInstructions returns instructions for Amazon Q CLI setup
func (h *AmazonQCLIHandler) GetInstructions(proxyURL string) string {
if runtime.GOOS == "windows" {
return `Amazon Q CLI is available via WSL on Windows.
To install and authenticate:
1. Open WSL (Ubuntu recommended)
2. Install Amazon Q CLI:
curl -sS https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip -o q.zip
unzip q.zip
./q/install.sh --no-confirm
3. Authenticate with AWS Builder ID:
q login
4. ProxyPilot will automatically detect and use your Amazon Q CLI tokens.
Note: Amazon Q CLI has separate usage quota from Kiro IDE.
`
}
return `To install and authenticate Amazon Q CLI:
1. Install Amazon Q CLI:
curl -sS https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip -o q.zip
unzip q.zip
./q/install.sh --no-confirm
2. Authenticate with AWS Builder ID:
q login
3. ProxyPilot will automatically detect and use your Amazon Q CLI tokens.
Note: Amazon Q CLI has separate usage quota from Kiro IDE.
`
}
// GetShellConfig returns shell profile configuration for Amazon Q CLI
func (h *AmazonQCLIHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Amazon Q CLI Configuration
# Amazon Q CLI uses its own authentication via 'q login'.
# ProxyPilot automatically imports the tokens after you authenticate.
# To authenticate:
# q login
# ProxyPilot will detect and use the tokens automatically.
# No additional environment variables needed.
# Optional: For other OpenAI-compatible tools
export OPENAI_BASE_URL="%s/v1"
export OPENAI_API_KEY="proxypilot-local"
`, proxyURL)
}
// GetWSLInfo returns WSL distro and user information (for external use)
func (h *AmazonQCLIHandler) GetWSLInfo() (distro, user string) {
return h.wslDistro, h.wslUser
}
+271
View File
@@ -0,0 +1,271 @@
package agents
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
)
// ClaudeCodeHandler handles Claude Code CLI configuration
type ClaudeCodeHandler struct {
configPath string
}
// NewClaudeCodeHandler creates a new Claude Code handler
func NewClaudeCodeHandler() *ClaudeCodeHandler {
homeDir, _ := os.UserHomeDir()
return &ClaudeCodeHandler{
configPath: filepath.Join(homeDir, ".claude", "settings.json"),
}
}
func (h *ClaudeCodeHandler) ID() string {
return "claude-code"
}
func (h *ClaudeCodeHandler) Name() string {
return "Claude Code"
}
func (h *ClaudeCodeHandler) CanAutoConfigure() bool {
return true
}
func (h *ClaudeCodeHandler) GetConfigPath() string {
return h.configPath
}
// Detect checks if Claude Code is installed
func (h *ClaudeCodeHandler) Detect() (bool, error) {
// Check for claude binary in PATH
if _, err := exec.LookPath("claude"); err == nil {
return true, nil
}
// Check for config directory existence
configDir := filepath.Dir(h.configPath)
if _, err := os.Stat(configDir); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if Claude Code is already configured for ProxyPilot
func (h *ClaudeCodeHandler) IsConfigured(proxyURL string) (bool, error) {
config, err := h.readConfig()
if err != nil {
return false, nil // Config doesn't exist or can't be read
}
// Check for ProxyPilot marker or ANTHROPIC_BASE_URL
if _, hasMarker := config["_proxypilot"]; hasMarker {
return true, nil
}
if env, ok := config["env"].(map[string]any); ok {
if baseURL, ok := env["ANTHROPIC_BASE_URL"].(string); ok {
if baseURL == proxyURL || baseURL == proxyURL+"/" {
return true, nil
}
}
}
return false, nil
}
// Enable configures Claude Code to use ProxyPilot
func (h *ClaudeCodeHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
// Ensure config directory exists
configDir := filepath.Dir(h.configPath)
if err := os.MkdirAll(configDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
// Read existing config or create new one
config, err := h.readConfig()
if err != nil {
config = make(map[string]any)
}
// Get or create env map
env, ok := config["env"].(map[string]any)
if !ok {
env = make(map[string]any)
}
// Record and apply ANTHROPIC_BASE_URL change
originalBaseURL := env["ANTHROPIC_BASE_URL"]
env["ANTHROPIC_BASE_URL"] = proxyURL
changes = append(changes, Change{
Path: "env.ANTHROPIC_BASE_URL",
Original: originalBaseURL,
Applied: proxyURL,
Type: "json",
})
// Record and apply ANTHROPIC_AUTH_TOKEN change
originalAuthToken := env["ANTHROPIC_AUTH_TOKEN"]
env["ANTHROPIC_AUTH_TOKEN"] = "proxypilot-local"
changes = append(changes, Change{
Path: "env.ANTHROPIC_AUTH_TOKEN",
Original: originalAuthToken,
Applied: "proxypilot-local",
Type: "json",
})
config["env"] = env
// Add ProxyPilot marker
originalMarker := config["_proxypilot"]
config["_proxypilot"] = true
changes = append(changes, Change{
Path: "_proxypilot",
Original: originalMarker,
Applied: true,
Type: "json",
})
// Write config
if err := h.writeConfig(config); err != nil {
return nil, fmt.Errorf("failed to write config: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from Claude Code
func (h *ClaudeCodeHandler) Disable(changes []Change) error {
config, err := h.readConfig()
if err != nil {
return nil // Config doesn't exist, nothing to disable
}
env, _ := config["env"].(map[string]any)
if env == nil {
env = make(map[string]any)
}
// Restore original values based on recorded changes
for _, change := range changes {
switch change.Path {
case "env.ANTHROPIC_BASE_URL":
if change.Original == nil {
delete(env, "ANTHROPIC_BASE_URL")
} else {
env["ANTHROPIC_BASE_URL"] = change.Original
}
case "env.ANTHROPIC_AUTH_TOKEN":
if change.Original == nil {
delete(env, "ANTHROPIC_AUTH_TOKEN")
} else {
env["ANTHROPIC_AUTH_TOKEN"] = change.Original
}
case "_proxypilot":
delete(config, "_proxypilot")
}
}
// Clean up empty env map
if len(env) == 0 {
delete(config, "env")
} else {
config["env"] = env
}
// Write config
if err := h.writeConfig(config); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
return nil
}
// GetInstructions returns manual configuration instructions
func (h *ClaudeCodeHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure Claude Code for ProxyPilot:
1. Edit %s
2. Add or update the "env" section:
{
"env": {
"ANTHROPIC_BASE_URL": "%s",
"ANTHROPIC_AUTH_TOKEN": "proxypilot-local"
}
}
3. Restart Claude Code for changes to take effect.
`, h.configPath, proxyURL)
}
// GetShellConfig returns shell profile configuration for Claude Code
func (h *ClaudeCodeHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Claude Code Configuration
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
export ANTHROPIC_BASE_URL="%s"
export ANTHROPIC_AUTH_TOKEN="proxypilot-local"
# For Claude Code 2.x, you can also set default models:
# export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4-1-20250805"
# export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-4-5-20250929"
# export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-3-5-haiku-20241022"
# For Claude Code 1.x:
# export ANTHROPIC_MODEL="claude-sonnet-4-5-20250929"
# export ANTHROPIC_SMALL_FAST_MODEL="claude-3-5-haiku-20241022"
`, proxyURL)
}
// readConfig reads the Claude Code settings file
func (h *ClaudeCodeHandler) readConfig() (map[string]any, error) {
data, err := os.ReadFile(h.configPath)
if err != nil {
return nil, err
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
return config, nil
}
// writeConfig writes the Claude Code settings file
func (h *ClaudeCodeHandler) writeConfig(config map[string]any) error {
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
// Add newline at end
data = append(data, '\n')
return os.WriteFile(h.configPath, data, 0644)
}
// GetClaudeConfigDir returns the Claude Code config directory based on platform
func GetClaudeConfigDir() string {
homeDir, _ := os.UserHomeDir()
switch runtime.GOOS {
case "windows":
// On Windows, Claude might use AppData
if appData := os.Getenv("APPDATA"); appData != "" {
claudeAppData := filepath.Join(appData, "Claude")
if _, err := os.Stat(claudeAppData); err == nil {
return claudeAppData
}
}
}
// Default: ~/.claude
return filepath.Join(homeDir, ".claude")
}
+219
View File
@@ -0,0 +1,219 @@
package agents
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// CodexHandler handles Codex CLI configuration
type CodexHandler struct {
configDir string
configPath string
}
// NewCodexHandler creates a new Codex CLI handler
func NewCodexHandler() *CodexHandler {
homeDir, _ := os.UserHomeDir()
configDir := filepath.Join(homeDir, ".codex")
return &CodexHandler{
configDir: configDir,
configPath: filepath.Join(configDir, "config.toml"),
}
}
func (h *CodexHandler) ID() string {
return "codex"
}
func (h *CodexHandler) Name() string {
return "Codex CLI"
}
func (h *CodexHandler) CanAutoConfigure() bool {
return true
}
func (h *CodexHandler) GetConfigPath() string {
return h.configPath
}
// Detect checks if Codex CLI is installed
func (h *CodexHandler) Detect() (bool, error) {
// Check for codex binary in PATH
if _, err := exec.LookPath("codex"); err == nil {
return true, nil
}
// Check for config directory existence
if _, err := os.Stat(h.configDir); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if Codex CLI is already configured for ProxyPilot
func (h *CodexHandler) IsConfigured(proxyURL string) (bool, error) {
content, err := os.ReadFile(h.configPath)
if err != nil {
return false, nil // Config doesn't exist
}
// Check for ProxyPilot section marker
if strings.Contains(string(content), "# ProxyPilot START") {
return true, nil
}
// Check for proxy URL in config
if strings.Contains(string(content), proxyURL) {
return true, nil
}
return false, nil
}
// Enable configures Codex CLI to use ProxyPilot
func (h *CodexHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
// Ensure config directory exists
if err := os.MkdirAll(h.configDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
// Read existing config
var existingContent string
if data, err := os.ReadFile(h.configPath); err == nil {
existingContent = string(data)
}
// Check if already has ProxyPilot section
if strings.Contains(existingContent, "# ProxyPilot START") {
// Already configured, update it
existingContent = h.removeProxyPilotSection(existingContent)
}
// Record original content
changes = append(changes, Change{
Path: "config.toml",
Original: existingContent,
Applied: "", // Will be set below
Type: "toml",
File: h.configPath,
})
// Create ProxyPilot section
proxyPilotSection := fmt.Sprintf(`
# ProxyPilot START
# ProxyPilot model provider for local proxy routing
[model_providers.proxypilot]
name = "ProxyPilot"
base_url = "%s/v1"
env_key = "PROXYPILOT_API_KEY"
wire_api = "openai"
# ProxyPilot END
`, proxyURL)
// Append to existing content
newContent := strings.TrimRight(existingContent, "\n\r\t ") + "\n" + proxyPilotSection
// Update the change record
changes[0].Applied = newContent
// Write config
if err := os.WriteFile(h.configPath, []byte(newContent), 0644); err != nil {
return nil, fmt.Errorf("failed to write config: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from Codex CLI
func (h *CodexHandler) Disable(changes []Change) error {
content, err := os.ReadFile(h.configPath)
if err != nil {
return nil // Config doesn't exist, nothing to disable
}
// Remove ProxyPilot section
newContent := h.removeProxyPilotSection(string(content))
// If we have recorded original content, we could restore it
// But for additive changes, just removing the section is cleaner
for _, change := range changes {
if change.Path == "config.toml" && change.Original != nil {
if origStr, ok := change.Original.(string); ok && origStr != "" {
// Restore original if it was recorded
newContent = origStr
break
}
}
}
// Write config
if err := os.WriteFile(h.configPath, []byte(newContent), 0644); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
return nil
}
// removeProxyPilotSection removes the ProxyPilot section from config content
func (h *CodexHandler) removeProxyPilotSection(content string) string {
lines := strings.Split(content, "\n")
var result []string
inProxyPilotSection := false
for _, line := range lines {
if strings.Contains(line, "# ProxyPilot START") {
inProxyPilotSection = true
continue
}
if strings.Contains(line, "# ProxyPilot END") {
inProxyPilotSection = false
continue
}
if !inProxyPilotSection {
result = append(result, line)
}
}
return strings.Join(result, "\n")
}
// GetInstructions returns manual configuration instructions
func (h *CodexHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure Codex CLI for ProxyPilot:
1. Edit %s
2. Add the following section:
[model_providers.proxypilot]
name = "ProxyPilot"
base_url = "%s/v1"
env_key = "PROXYPILOT_API_KEY"
wire_api = "openai"
3. Set the environment variable:
export PROXYPILOT_API_KEY="proxypilot-local"
4. Restart Codex CLI for changes to take effect.
`, h.configPath, proxyURL)
}
// GetShellConfig returns shell profile configuration for Codex CLI
func (h *CodexHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Codex CLI Configuration
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
export PROXYPILOT_API_KEY="proxypilot-local"
export OPENAI_BASE_URL="%s/v1"
export OPENAI_API_KEY="proxypilot-local"
# Note: Codex CLI also requires config.toml configuration.
# See the setup instructions for full details.
`, proxyURL)
}
+272
View File
@@ -0,0 +1,272 @@
package agents
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
)
// CursorHandler handles Cursor IDE configuration
type CursorHandler struct {
configPath string
}
// NewCursorHandler creates a new Cursor handler
func NewCursorHandler() *CursorHandler {
return &CursorHandler{
configPath: getCursorSettingsPath(),
}
}
func (h *CursorHandler) ID() string {
return "cursor"
}
func (h *CursorHandler) Name() string {
return "Cursor"
}
func (h *CursorHandler) CanAutoConfigure() bool {
return true
}
func (h *CursorHandler) GetConfigPath() string {
return h.configPath
}
// Detect checks if Cursor is installed
func (h *CursorHandler) Detect() (bool, error) {
if h.configPath == "" {
return false, nil
}
// Check if settings file or its directory exists
if _, err := os.Stat(h.configPath); err == nil {
return true, nil
}
if _, err := os.Stat(filepath.Dir(h.configPath)); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if Cursor is already configured for ProxyPilot
func (h *CursorHandler) IsConfigured(proxyURL string) (bool, error) {
config, err := h.readConfig()
if err != nil {
return false, nil // Config doesn't exist
}
// Check for proxypilot model in models section
if models, ok := config["models"].(map[string]any); ok {
if _, hasProxyPilot := models["proxypilot"]; hasProxyPilot {
return true, nil
}
}
return false, nil
}
// Enable configures Cursor to use ProxyPilot
func (h *CursorHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
if h.configPath == "" {
return nil, fmt.Errorf("could not determine Cursor settings path")
}
// Ensure config directory exists
if err := os.MkdirAll(filepath.Dir(h.configPath), 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
// Read existing config or create new one
config, err := h.readConfig()
if err != nil {
config = make(map[string]any)
}
// Get or create models map
var models map[string]any
if existingModels, ok := config["models"].(map[string]any); ok {
models = existingModels
} else {
models = make(map[string]any)
}
// Record original proxypilot model (if any)
originalModel := models["proxypilot"]
// Add ProxyPilot model configuration
models["proxypilot"] = map[string]any{
"name": "ProxyPilot",
"apiKey": "proxypilot-local",
"baseUrl": proxyURL + "/v1",
"contextLength": 200000,
}
changes = append(changes, Change{
Path: "models.proxypilot",
Original: originalModel,
Applied: models["proxypilot"],
Type: "json",
})
config["models"] = models
// Write config
if err := h.writeConfig(config); err != nil {
return nil, fmt.Errorf("failed to write config: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from Cursor
func (h *CursorHandler) Disable(changes []Change) error {
config, err := h.readConfig()
if err != nil {
return nil // Config doesn't exist, nothing to disable
}
// Get models map
models, ok := config["models"].(map[string]any)
if !ok {
return nil // No models, nothing to remove
}
// Restore original values based on recorded changes
for _, change := range changes {
if change.Path == "models.proxypilot" {
if change.Original == nil {
delete(models, "proxypilot")
} else {
models["proxypilot"] = change.Original
}
}
}
// Clean up empty models map
if len(models) == 0 {
delete(config, "models")
} else {
config["models"] = models
}
// Write config
if err := h.writeConfig(config); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
return nil
}
// GetInstructions returns manual configuration instructions
func (h *CursorHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure Cursor for ProxyPilot:
1. Open Cursor Settings (Cmd/Ctrl + ,)
2. Go to "Models" section
3. Add a new custom model with these settings:
- Name: ProxyPilot
- API Key: proxypilot-local
- Base URL: %s/v1
- Context Length: 200000
Or edit %s directly and add:
{
"models": {
"proxypilot": {
"name": "ProxyPilot",
"apiKey": "proxypilot-local",
"baseUrl": "%s/v1",
"contextLength": 200000
}
}
}
4. Select 'proxypilot' as your model in Cursor AI settings.
`, proxyURL, h.configPath, proxyURL)
}
// GetShellConfig returns shell profile configuration for Cursor
func (h *CursorHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Cursor IDE Configuration
# Note: Cursor primarily uses settings.json, not environment variables.
# Use the UI or edit settings.json directly.
# Optional: Set OPENAI-compatible environment variables as fallback
export OPENAI_BASE_URL="%s/v1"
export OPENAI_API_KEY="proxypilot-local"
`, proxyURL)
}
// readConfig reads the Cursor settings file
func (h *CursorHandler) readConfig() (map[string]any, error) {
data, err := os.ReadFile(h.configPath)
if err != nil {
return nil, err
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
return config, nil
}
// writeConfig writes the Cursor settings file
func (h *CursorHandler) writeConfig(config map[string]any) error {
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
// Add newline at end
data = append(data, '\n')
return os.WriteFile(h.configPath, data, 0644)
}
// getCursorSettingsPath returns the Cursor settings path based on platform
func getCursorSettingsPath() string {
homeDir, err := os.UserHomeDir()
if err != nil {
return ""
}
var paths []string
switch runtime.GOOS {
case "windows":
if appData := os.Getenv("APPDATA"); appData != "" {
paths = append(paths, filepath.Join(appData, "Cursor", "User", "settings.json"))
}
case "darwin":
paths = append(paths, filepath.Join(homeDir, "Library", "Application Support", "Cursor", "User", "settings.json"))
default: // Linux and others
paths = append(paths, filepath.Join(homeDir, ".config", "Cursor", "User", "settings.json"))
}
// Return first existing path, or first path as default
for _, p := range paths {
if _, err := os.Stat(p); err == nil {
return p
}
// If parent dir exists, use this path
if _, err := os.Stat(filepath.Dir(p)); err == nil {
return p
}
}
if len(paths) > 0 {
return paths[0]
}
return ""
}
+306
View File
@@ -0,0 +1,306 @@
package agents
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// FactoryDroidHandler handles Factory Droid CLI configuration
type FactoryDroidHandler struct {
configDir string
settingsPath string // Droid uses settings.json for customModels
}
// NewFactoryDroidHandler creates a new Factory Droid handler
func NewFactoryDroidHandler() *FactoryDroidHandler {
homeDir, _ := os.UserHomeDir()
configDir := filepath.Join(homeDir, ".factory")
return &FactoryDroidHandler{
configDir: configDir,
settingsPath: filepath.Join(configDir, "settings.json"),
}
}
func (h *FactoryDroidHandler) ID() string {
return "factory-droid"
}
func (h *FactoryDroidHandler) Name() string {
return "Factory Droid"
}
func (h *FactoryDroidHandler) CanAutoConfigure() bool {
return true
}
func (h *FactoryDroidHandler) GetConfigPath() string {
return h.settingsPath
}
// Detect checks if Factory Droid is installed
func (h *FactoryDroidHandler) Detect() (bool, error) {
if _, err := exec.LookPath("droid"); err == nil {
return true, nil
}
if _, err := exec.LookPath("factory"); err == nil {
return true, nil
}
if _, err := os.Stat(h.configDir); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if Factory Droid is already configured for ProxyPilot
func (h *FactoryDroidHandler) IsConfigured(proxyURL string) (bool, error) {
settings, err := h.readSettings()
if err != nil {
return false, nil
}
if customModels, ok := settings["customModels"].([]any); ok {
for _, entry := range customModels {
if m, ok := entry.(map[string]any); ok {
displayName, _ := m["displayName"].(string)
if strings.HasPrefix(displayName, "proxypilot-") {
return true, nil
}
}
}
}
return false, nil
}
// Enable configures Factory Droid to use ProxyPilot
func (h *FactoryDroidHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
if err := os.MkdirAll(h.configDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
settings, err := h.readSettings()
if err != nil {
settings = make(map[string]any)
}
// Build ProxyPilot models in Droid's format
proxyPilotModels := buildDroidModels(proxyURL)
originalCustomModels := settings["customModels"]
// Merge: proxypilot models first, then user's non-proxypilot models
var finalModels []any
for _, m := range proxyPilotModels {
finalModels = append(finalModels, m)
}
// Keep user's non-proxypilot models
if existing, ok := settings["customModels"].([]any); ok {
for _, entry := range existing {
if m, ok := entry.(map[string]any); ok {
displayName, _ := m["displayName"].(string)
if !isProxyPilotModel(displayName) {
// Re-index user models after proxypilot models
m["index"] = len(finalModels)
finalModels = append(finalModels, m)
}
}
}
}
settings["customModels"] = finalModels
changes = append(changes, Change{
Path: "customModels",
Original: originalCustomModels,
Applied: finalModels,
Type: "json",
})
if err := h.writeSettings(settings); err != nil {
return nil, fmt.Errorf("failed to write settings: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from Factory Droid
func (h *FactoryDroidHandler) Disable(changes []Change) error {
settings, err := h.readSettings()
if err != nil {
return nil
}
var filteredModels []any
idx := 0
if customModels, ok := settings["customModels"].([]any); ok {
for _, entry := range customModels {
if m, ok := entry.(map[string]any); ok {
displayName, _ := m["displayName"].(string)
// Remove all ProxyPilot models (various naming conventions)
if !isProxyPilotModel(displayName) {
m["index"] = idx
filteredModels = append(filteredModels, m)
idx++
}
}
}
}
if len(filteredModels) == 0 {
delete(settings, "customModels")
} else {
settings["customModels"] = filteredModels
}
if err := h.writeSettings(settings); err != nil {
return fmt.Errorf("failed to write settings: %w", err)
}
return nil
}
// isProxyPilotModel checks if a model name belongs to ProxyPilot
func isProxyPilotModel(displayName string) bool {
lower := strings.ToLower(displayName)
return strings.HasPrefix(lower, "proxypilot-") || strings.HasPrefix(lower, "proxypilot ")
}
// GetInstructions returns manual configuration instructions
func (h *FactoryDroidHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure Factory Droid for ProxyPilot:
1. Edit %s
2. Add ProxyPilot models to the "customModels" array with this format:
{
"customModels": [
{
"model": "claude-opus-4-5-20251101",
"id": "custom:proxypilot-Claude-4.5-Opus-0",
"index": 0,
"baseUrl": "%s/v1",
"apiKey": "proxypilot-local",
"displayName": "proxypilot-Claude 4.5 Opus",
"provider": "openai"
}
]
}
3. Restart Factory Droid and select a proxypilot model.
`, h.settingsPath, proxyURL)
}
// GetShellConfig returns shell profile configuration for Factory Droid
func (h *FactoryDroidHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Factory Droid Configuration
# Factory Droid uses settings.json for configuration, not environment variables.
# Use the auto-configure feature or edit %s directly.
# Optional: For other OpenAI-compatible tools
export OPENAI_BASE_URL="%s/v1"
export OPENAI_API_KEY="proxypilot-local"
`, h.settingsPath, proxyURL)
}
func (h *FactoryDroidHandler) readSettings() (map[string]any, error) {
data, err := os.ReadFile(h.settingsPath)
if err != nil {
return nil, err
}
var settings map[string]any
if err := json.Unmarshal(data, &settings); err != nil {
return nil, err
}
return settings, nil
}
func (h *FactoryDroidHandler) writeSettings(settings map[string]any) error {
data, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
return os.WriteFile(h.settingsPath, data, 0644)
}
// buildDroidModels builds models in Droid's expected format
func buildDroidModels(proxyURL string) []map[string]any {
curatedModels := []struct {
displayName string
modelID string
provider string
}{
// Claude 4.5 Direct (Anthropic API)
{"Claude 4.5 Opus", "claude-opus-4-5-20251101", "anthropic"},
{"Claude 4.5 Sonnet", "claude-sonnet-4-5-20250929", "anthropic"},
{"Claude 4.5 Haiku", "claude-haiku-4-5-20251001", "anthropic"},
// Antigravity (Claude via Gemini with extended thinking)
{"Claude 4.5 Opus Thinking", "gemini-claude-opus-4-5-thinking", "antigravity"},
{"Claude 4.5 Sonnet Thinking", "gemini-claude-sonnet-4-5-thinking", "antigravity"},
// Gemini latest
{"Gemini 2.5 Pro", "gemini-2.5-pro", "google"},
{"Gemini 2.5 Flash", "gemini-2.5-flash", "google"},
{"Gemini 3 Pro Preview", "gemini-3-pro-preview", "google"},
{"Gemini 3 Flash Preview", "gemini-3-flash-preview", "google"},
// OpenAI latest
{"GPT 5.2", "gpt-5.2", "openai"},
{"GPT 5.2 Codex", "gpt-5.2-codex", "openai"},
{"GPT 5.1 Codex Max", "gpt-5.1-codex-max", "openai"},
// Kiro (AWS)
{"Kiro Claude Opus 4.5", "kiro-claude-opus-4-5", "kiro"},
{"Kiro Claude Sonnet 4.5", "kiro-claude-sonnet-4-5", "kiro"},
{"Kiro Claude Haiku 4.5", "kiro-claude-haiku-4-5", "kiro"},
// Amazon Q
{"Amazon Q Auto", "amazonq-auto", "amazonq"},
{"Amazon Q Claude Opus 4.5", "amazonq-claude-opus-4.5", "amazonq"},
{"Amazon Q Claude Sonnet 4.5", "amazonq-claude-sonnet-4.5", "amazonq"},
// GitHub Copilot
{"Copilot GPT 5.2", "gpt-5.2", "github-copilot"},
{"Copilot Claude Opus 4.5", "claude-opus-4.5", "github-copilot"},
{"Copilot Claude Sonnet 4.5", "claude-sonnet-4.5", "github-copilot"},
{"Copilot Gemini 3 Pro", "gemini-3-pro", "github-copilot"},
// Qwen
{"Qwen3 Coder Plus", "qwen3-coder-plus", "qwen"},
{"Qwen3 Coder Flash", "qwen3-coder-flash", "qwen"},
// MiniMax
{"MiniMax M2.1", "minimax-m2.1", "minimax"},
// Zhipu
{"GLM 4.7", "glm-4.7", "zhipu"},
{"GLM 4.6V", "glm-4.6v", "zhipu"},
}
var models []map[string]any
for i, m := range curatedModels {
displayName := "proxypilot-" + m.displayName
// Create ID in Droid's format: custom:<name>-<index>
id := fmt.Sprintf("custom:%s-%d", strings.ReplaceAll(displayName, " ", "-"), i)
models = append(models, map[string]any{
"model": m.modelID,
"id": id,
"index": i,
"baseUrl": proxyURL + "/v1",
"apiKey": "proxypilot-local",
"displayName": displayName,
"noImageSupport": false,
"provider": "openai", // Droid uses "openai" for OpenAI-compatible endpoints
})
}
return models
}
+214
View File
@@ -0,0 +1,214 @@
package agents
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
)
// GeminiCLIHandler handles Gemini CLI configuration
type GeminiCLIHandler struct {
configDir string
configPath string
}
// NewGeminiCLIHandler creates a new Gemini CLI handler
func NewGeminiCLIHandler() *GeminiCLIHandler {
homeDir, _ := os.UserHomeDir()
configDir := filepath.Join(homeDir, ".gemini")
return &GeminiCLIHandler{
configDir: configDir,
configPath: filepath.Join(configDir, "settings.json"),
}
}
func (h *GeminiCLIHandler) ID() string {
return "gemini-cli"
}
func (h *GeminiCLIHandler) Name() string {
return "Gemini CLI"
}
func (h *GeminiCLIHandler) CanAutoConfigure() bool {
return true
}
func (h *GeminiCLIHandler) GetConfigPath() string {
return h.configPath
}
// Detect checks if Gemini CLI is installed
func (h *GeminiCLIHandler) Detect() (bool, error) {
// Check for gemini binary in PATH
if _, err := exec.LookPath("gemini"); err == nil {
return true, nil
}
// Check for config directory existence
if _, err := os.Stat(h.configDir); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if Gemini CLI is already configured for ProxyPilot
func (h *GeminiCLIHandler) IsConfigured(proxyURL string) (bool, error) {
config, err := h.readConfig()
if err != nil {
return false, nil // Config doesn't exist
}
// Check for ProxyPilot marker
if _, hasMarker := config["_proxypilot"]; hasMarker {
return true, nil
}
// Check for api_base pointing to proxy
if apiBase, ok := config["api_base"].(string); ok {
if apiBase == proxyURL || apiBase == proxyURL+"/" {
return true, nil
}
}
return false, nil
}
// Enable configures Gemini CLI to use ProxyPilot
func (h *GeminiCLIHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
// Ensure config directory exists
if err := os.MkdirAll(h.configDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
// Read existing config or create new one
config, err := h.readConfig()
if err != nil {
config = make(map[string]any)
}
// Record and apply api_base change
originalAPIBase := config["api_base"]
config["api_base"] = proxyURL
changes = append(changes, Change{
Path: "api_base",
Original: originalAPIBase,
Applied: proxyURL,
Type: "json",
})
// Add ProxyPilot marker
originalMarker := config["_proxypilot"]
config["_proxypilot"] = true
changes = append(changes, Change{
Path: "_proxypilot",
Original: originalMarker,
Applied: true,
Type: "json",
})
// Write config
if err := h.writeConfig(config); err != nil {
return nil, fmt.Errorf("failed to write config: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from Gemini CLI
func (h *GeminiCLIHandler) Disable(changes []Change) error {
config, err := h.readConfig()
if err != nil {
return nil // Config doesn't exist, nothing to disable
}
// Restore original values based on recorded changes
for _, change := range changes {
switch change.Path {
case "api_base":
if change.Original == nil {
delete(config, "api_base")
} else {
config["api_base"] = change.Original
}
case "_proxypilot":
delete(config, "_proxypilot")
}
}
// Write config
if err := h.writeConfig(config); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
return nil
}
// GetInstructions returns manual configuration instructions
func (h *GeminiCLIHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure Gemini CLI for ProxyPilot:
Option 1: Edit settings.json
1. Edit %s
2. Add or update the "api_base" field:
{
"api_base": "%s"
}
Option 2: Use environment variables
Add to your shell profile (~/.bashrc or ~/.zshrc):
export GOOGLE_GEMINI_BASE_URL="%s"
export GEMINI_API_KEY="proxypilot-local"
Then restart your shell or run: source ~/.bashrc
`, h.configPath, proxyURL, proxyURL)
}
// readConfig reads the Gemini CLI settings file
func (h *GeminiCLIHandler) readConfig() (map[string]any, error) {
data, err := os.ReadFile(h.configPath)
if err != nil {
return nil, err
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
return config, nil
}
// writeConfig writes the Gemini CLI settings file
func (h *GeminiCLIHandler) writeConfig(config map[string]any) error {
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
// Add newline at end
data = append(data, '\n')
return os.WriteFile(h.configPath, data, 0644)
}
// GetShellConfig returns shell profile configuration for Gemini CLI
func (h *GeminiCLIHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - Gemini CLI Configuration
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
# Option 1: OAuth mode (local only)
export CODE_ASSIST_ENDPOINT="%s"
# Option 2: API Key mode (works with any IP/domain)
# export GOOGLE_GEMINI_BASE_URL="%s"
# export GEMINI_API_KEY="proxypilot-local"
`, proxyURL, proxyURL)
}
+355
View File
@@ -0,0 +1,355 @@
package agents
import (
"fmt"
"sync"
)
// AgentInfo contains information about a CLI agent
type AgentInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Detected bool `json:"detected"`
Configured bool `json:"configured"`
CanAutoConfigure bool `json:"can_auto_configure"`
ConfigPath string `json:"config_path,omitempty"`
Instructions string `json:"instructions,omitempty"`
ShellConfig string `json:"shell_config,omitempty"`
EnvVars map[string]string `json:"env_vars,omitempty"`
}
// ConfigResult represents the result of a configuration operation
type ConfigResult struct {
Success bool `json:"success"`
AgentID string `json:"agent_id"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
ConfigPath string `json:"config_path,omitempty"`
Instructions string `json:"instructions,omitempty"`
}
// AgentHandler defines the interface for agent-specific configuration handlers
type AgentHandler interface {
// ID returns the unique identifier for this agent
ID() string
// Name returns the display name for this agent
Name() string
// Detect checks if the agent is installed on the system
Detect() (bool, error)
// IsConfigured checks if the agent is already configured for ProxyPilot
IsConfigured(proxyURL string) (bool, error)
// Enable configures the agent to use ProxyPilot and returns the changes made
Enable(proxyURL string) ([]Change, error)
// Disable removes ProxyPilot configuration from the agent using recorded changes
Disable(changes []Change) error
// GetConfigPath returns the path to the agent's configuration file
GetConfigPath() string
// CanAutoConfigure returns whether this agent supports automatic configuration
CanAutoConfigure() bool
// GetInstructions returns manual configuration instructions
GetInstructions(proxyURL string) string
// GetShellConfig returns shell script configuration for this agent.
// This is used for agents that need environment variables in shell profiles.
GetShellConfig(proxyURL string) string
}
// Manager manages all CLI agent configurations
type Manager struct {
mu sync.RWMutex
state *StateManager
handlers map[string]AgentHandler
proxyURL string
}
// NewManager creates a new agent configuration manager
func NewManager(proxyPort int) (*Manager, error) {
state, err := NewStateManager()
if err != nil {
return nil, fmt.Errorf("failed to create state manager: %w", err)
}
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", proxyPort)
m := &Manager{
state: state,
handlers: make(map[string]AgentHandler),
proxyURL: proxyURL,
}
// Register all known agent handlers
m.registerDefaultHandlers()
return m, nil
}
// registerDefaultHandlers registers all built-in agent handlers
func (m *Manager) registerDefaultHandlers() {
handlers := []AgentHandler{
NewClaudeCodeHandler(),
NewCodexHandler(),
NewGeminiCLIHandler(),
NewCursorHandler(),
NewOpenCodeHandler(),
NewFactoryDroidHandler(),
NewAmazonQCLIHandler(),
}
for _, h := range handlers {
m.handlers[h.ID()] = h
}
}
// RegisterHandler adds a custom agent handler
func (m *Manager) RegisterHandler(handler AgentHandler) {
m.mu.Lock()
defer m.mu.Unlock()
m.handlers[handler.ID()] = handler
}
// GetHandler returns a handler by ID
func (m *Manager) GetHandler(agentID string) (AgentHandler, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
h, ok := m.handlers[agentID]
return h, ok
}
// DetectAll detects all agents and returns their info
func (m *Manager) DetectAll() ([]AgentInfo, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var agents []AgentInfo
for _, handler := range m.handlers {
info := AgentInfo{
ID: handler.ID(),
Name: handler.Name(),
CanAutoConfigure: handler.CanAutoConfigure(),
ConfigPath: handler.GetConfigPath(),
Instructions: handler.GetInstructions(m.proxyURL),
ShellConfig: handler.GetShellConfig(m.proxyURL),
}
detected, err := handler.Detect()
if err != nil {
// Log error but continue with other agents
info.Detected = false
} else {
info.Detected = detected
}
if detected {
configured, err := handler.IsConfigured(m.proxyURL)
if err == nil {
info.Configured = configured
}
}
// Check if we have state for this agent
if state, exists := m.state.GetAgentState(handler.ID()); exists {
info.Configured = state.Enabled
}
agents = append(agents, info)
}
return agents, nil
}
// GetAgentInfo returns info for a specific agent
func (m *Manager) GetAgentInfo(agentID string) (AgentInfo, error) {
handler, ok := m.GetHandler(agentID)
if !ok {
return AgentInfo{}, fmt.Errorf("unknown agent: %s", agentID)
}
info := AgentInfo{
ID: handler.ID(),
Name: handler.Name(),
CanAutoConfigure: handler.CanAutoConfigure(),
ConfigPath: handler.GetConfigPath(),
Instructions: handler.GetInstructions(m.proxyURL),
ShellConfig: handler.GetShellConfig(m.proxyURL),
}
detected, _ := handler.Detect()
info.Detected = detected
if detected {
configured, _ := handler.IsConfigured(m.proxyURL)
info.Configured = configured
}
if state, exists := m.state.GetAgentState(agentID); exists {
info.Configured = state.Enabled
}
return info, nil
}
// Enable enables ProxyPilot for an agent
func (m *Manager) Enable(agentID string) ConfigResult {
handler, ok := m.GetHandler(agentID)
if !ok {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("unknown agent: %s", agentID),
}
}
if !handler.CanAutoConfigure() {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: "agent does not support automatic configuration",
Instructions: handler.GetInstructions(m.proxyURL),
}
}
// Check if already enabled
if m.state.IsAgentEnabled(agentID) {
return ConfigResult{
Success: true,
AgentID: agentID,
Message: "agent already configured",
ConfigPath: handler.GetConfigPath(),
}
}
// Enable the agent
changes, err := handler.Enable(m.proxyURL)
if err != nil {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("failed to enable: %v", err),
}
}
// Record the state
if err := m.state.RecordEnable(agentID, handler.GetConfigPath(), changes); err != nil {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("failed to save state: %v", err),
}
}
return ConfigResult{
Success: true,
AgentID: agentID,
Message: fmt.Sprintf("%s configured successfully", handler.Name()),
ConfigPath: handler.GetConfigPath(),
}
}
// Disable disables ProxyPilot for an agent
func (m *Manager) Disable(agentID string) ConfigResult {
handler, ok := m.GetHandler(agentID)
if !ok {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("unknown agent: %s", agentID),
}
}
// Get recorded changes
changes := m.state.GetChanges(agentID)
if len(changes) == 0 {
// No recorded changes, try to detect and remove anyway
if !m.state.IsAgentEnabled(agentID) {
return ConfigResult{
Success: true,
AgentID: agentID,
Message: "agent was not configured",
}
}
}
// Disable the agent
if err := handler.Disable(changes); err != nil {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("failed to disable: %v", err),
}
}
// Clear the state
if err := m.state.ClearAgent(agentID); err != nil {
return ConfigResult{
Success: false,
AgentID: agentID,
Error: fmt.Sprintf("failed to clear state: %v", err),
}
}
return ConfigResult{
Success: true,
AgentID: agentID,
Message: fmt.Sprintf("%s configuration removed", handler.Name()),
}
}
// EnableAll enables ProxyPilot for all detected agents that support auto-configuration
func (m *Manager) EnableAll() []ConfigResult {
var results []ConfigResult
for agentID, handler := range m.handlers {
if !handler.CanAutoConfigure() {
continue
}
detected, _ := handler.Detect()
if !detected {
continue
}
result := m.Enable(agentID)
results = append(results, result)
}
return results
}
// DisableAll disables ProxyPilot for all configured agents
func (m *Manager) DisableAll() []ConfigResult {
var results []ConfigResult
states := m.state.GetAllAgentStates()
for agentID, state := range states {
if !state.Enabled {
continue
}
result := m.Disable(agentID)
results = append(results, result)
}
return results
}
// GetState returns the state manager for direct access
func (m *Manager) GetState() *StateManager {
return m.state
}
// SetProxyURL updates the proxy URL
func (m *Manager) SetProxyURL(port int) {
m.mu.Lock()
defer m.mu.Unlock()
m.proxyURL = fmt.Sprintf("http://127.0.0.1:%d", port)
}
+240
View File
@@ -0,0 +1,240 @@
package agents
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
)
// OpenCodeHandler handles OpenCode CLI configuration
type OpenCodeHandler struct {
configDir string
configPath string
}
// NewOpenCodeHandler creates a new OpenCode handler
func NewOpenCodeHandler() *OpenCodeHandler {
homeDir, _ := os.UserHomeDir()
configDir := filepath.Join(homeDir, ".config", "opencode")
return &OpenCodeHandler{
configDir: configDir,
configPath: filepath.Join(configDir, "opencode.json"),
}
}
func (h *OpenCodeHandler) ID() string {
return "opencode"
}
func (h *OpenCodeHandler) Name() string {
return "OpenCode"
}
func (h *OpenCodeHandler) CanAutoConfigure() bool {
return true
}
func (h *OpenCodeHandler) GetConfigPath() string {
return h.configPath
}
// Detect checks if OpenCode is installed
func (h *OpenCodeHandler) Detect() (bool, error) {
// Check for opencode binary in PATH
if _, err := exec.LookPath("opencode"); err == nil {
return true, nil
}
// Check for config directory existence
if _, err := os.Stat(h.configDir); err == nil {
return true, nil
}
return false, nil
}
// IsConfigured checks if OpenCode is already configured for ProxyPilot
func (h *OpenCodeHandler) IsConfigured(proxyURL string) (bool, error) {
config, err := h.readConfig()
if err != nil {
return false, nil // Config doesn't exist
}
// Check for proxypilot provider
if providers, ok := config["providers"].(map[string]any); ok {
if _, hasProxyPilot := providers["proxypilot"]; hasProxyPilot {
return true, nil
}
}
return false, nil
}
// Enable configures OpenCode to use ProxyPilot
func (h *OpenCodeHandler) Enable(proxyURL string) ([]Change, error) {
var changes []Change
// Ensure config directory exists
if err := os.MkdirAll(h.configDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create config directory: %w", err)
}
// Read existing config or create new one
config, err := h.readConfig()
if err != nil {
config = make(map[string]any)
}
// Get or create providers map
var providers map[string]any
if existingProviders, ok := config["providers"].(map[string]any); ok {
providers = existingProviders
} else {
providers = make(map[string]any)
}
// Record original proxypilot provider (if any)
originalProvider := providers["proxypilot"]
// Add ProxyPilot provider configuration
providers["proxypilot"] = map[string]any{
"name": "ProxyPilot",
"apiKey": "proxypilot-local",
"options": map[string]any{
"baseURL": proxyURL + "/v1",
},
"models": []string{
"claude-sonnet-4-20250514",
"claude-opus-4-20250514",
"gpt-4o",
"gemini-2.0-flash",
},
}
changes = append(changes, Change{
Path: "providers.proxypilot",
Original: originalProvider,
Applied: providers["proxypilot"],
Type: "json",
})
config["providers"] = providers
// Write config
if err := h.writeConfig(config); err != nil {
return nil, fmt.Errorf("failed to write config: %w", err)
}
return changes, nil
}
// Disable removes ProxyPilot configuration from OpenCode
func (h *OpenCodeHandler) Disable(changes []Change) error {
config, err := h.readConfig()
if err != nil {
return nil // Config doesn't exist, nothing to disable
}
// Get providers map
providers, ok := config["providers"].(map[string]any)
if !ok {
return nil // No providers, nothing to remove
}
// Restore original values based on recorded changes
for _, change := range changes {
if change.Path == "providers.proxypilot" {
if change.Original == nil {
delete(providers, "proxypilot")
} else {
providers["proxypilot"] = change.Original
}
}
}
// Clean up empty providers map
if len(providers) == 0 {
delete(config, "providers")
} else {
config["providers"] = providers
}
// Write config
if err := h.writeConfig(config); err != nil {
return fmt.Errorf("failed to write config: %w", err)
}
return nil
}
// GetInstructions returns manual configuration instructions
func (h *OpenCodeHandler) GetInstructions(proxyURL string) string {
return fmt.Sprintf(`To manually configure OpenCode for ProxyPilot:
1. Edit %s
2. Add a "proxypilot" provider to the "providers" section:
{
"providers": {
"proxypilot": {
"name": "ProxyPilot",
"apiKey": "proxypilot-local",
"options": {
"baseURL": "%s/v1"
},
"models": [
"claude-sonnet-4-20250514",
"claude-opus-4-20250514",
"gpt-4o"
]
}
}
}
3. Restart OpenCode and select the ProxyPilot provider.
`, h.configPath, proxyURL)
}
// GetShellConfig returns shell profile configuration for OpenCode
func (h *OpenCodeHandler) GetShellConfig(proxyURL string) string {
return fmt.Sprintf(`# ProxyPilot - OpenCode Configuration
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
export OPENAI_BASE_URL="%s/v1"
export OPENAI_API_KEY="proxypilot-local"
# Or use Anthropic-compatible settings:
# export ANTHROPIC_BASE_URL="%s"
# export ANTHROPIC_AUTH_TOKEN="proxypilot-local"
`, proxyURL, proxyURL)
}
// readConfig reads the OpenCode settings file
func (h *OpenCodeHandler) readConfig() (map[string]any, error) {
data, err := os.ReadFile(h.configPath)
if err != nil {
return nil, err
}
var config map[string]any
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
return config, nil
}
// writeConfig writes the OpenCode settings file
func (h *OpenCodeHandler) writeConfig(config map[string]any) error {
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
// Add newline at end
data = append(data, '\n')
return os.WriteFile(h.configPath, data, 0644)
}
+218
View File
@@ -0,0 +1,218 @@
// Package agents provides unified agent configuration management for ProxyPilot.
// It tracks all changes made to CLI agent configurations and provides precise
// enable/disable functionality without destructive backup/restore operations.
package agents
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sync"
"time"
)
// StateVersion is the current version of the state file format
const StateVersion = 1
// State represents the overall state of ProxyPilot's agent configurations
type State struct {
Version int `json:"version"`
Agents map[string]AgentState `json:"agents"`
}
// AgentState represents the configuration state for a single agent
type AgentState struct {
Enabled bool `json:"enabled"`
ConfigPath string `json:"config_path"`
Changes []Change `json:"changes"`
EnabledAt time.Time `json:"enabled_at,omitempty"`
DisabledAt time.Time `json:"disabled_at,omitempty"`
}
// Change represents a single configuration change made to an agent
type Change struct {
Path string `json:"path"` // JSON path or config key (e.g., "env.ANTHROPIC_BASE_URL")
Original any `json:"original"` // Original value (nil if key didn't exist)
Applied any `json:"applied"` // Value applied by ProxyPilot
Type string `json:"type,omitempty"` // Type of change: "json", "toml", "env", "shell"
File string `json:"file,omitempty"` // Specific file if different from ConfigPath
}
// StateManager handles loading, saving, and manipulating ProxyPilot state
type StateManager struct {
mu sync.RWMutex
state *State
statePath string
baseDir string
}
// NewStateManager creates a new StateManager instance
func NewStateManager() (*StateManager, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
baseDir := filepath.Join(homeDir, ".proxypilot")
statePath := filepath.Join(baseDir, "state.json")
sm := &StateManager{
statePath: statePath,
baseDir: baseDir,
}
if err := sm.ensureBaseDir(); err != nil {
return nil, err
}
if err := sm.load(); err != nil {
return nil, err
}
return sm, nil
}
// ensureBaseDir creates the base directory if it doesn't exist
func (sm *StateManager) ensureBaseDir() error {
agentsDir := filepath.Join(sm.baseDir, "agents")
if err := os.MkdirAll(agentsDir, 0755); err != nil {
return fmt.Errorf("failed to create agents directory: %w", err)
}
return nil
}
// load reads the state from disk, or creates a new state if none exists
func (sm *StateManager) load() error {
sm.mu.Lock()
defer sm.mu.Unlock()
data, err := os.ReadFile(sm.statePath)
if os.IsNotExist(err) {
sm.state = &State{
Version: StateVersion,
Agents: make(map[string]AgentState),
}
return nil
}
if err != nil {
return fmt.Errorf("failed to read state file: %w", err)
}
var state State
if err := json.Unmarshal(data, &state); err != nil {
return fmt.Errorf("failed to parse state file: %w", err)
}
if state.Agents == nil {
state.Agents = make(map[string]AgentState)
}
sm.state = &state
return nil
}
// Save persists the current state to disk
func (sm *StateManager) Save() error {
sm.mu.Lock()
defer sm.mu.Unlock()
return sm.saveUnlocked()
}
func (sm *StateManager) saveUnlocked() error {
data, err := json.MarshalIndent(sm.state, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal state: %w", err)
}
if err := os.WriteFile(sm.statePath, data, 0644); err != nil {
return fmt.Errorf("failed to write state file: %w", err)
}
return nil
}
// GetAgentState returns the state for a specific agent
func (sm *StateManager) GetAgentState(agentID string) (AgentState, bool) {
sm.mu.RLock()
defer sm.mu.RUnlock()
state, exists := sm.state.Agents[agentID]
return state, exists
}
// IsAgentEnabled returns whether an agent is currently enabled
func (sm *StateManager) IsAgentEnabled(agentID string) bool {
state, exists := sm.GetAgentState(agentID)
return exists && state.Enabled
}
// RecordEnable records that an agent has been enabled with the given changes
func (sm *StateManager) RecordEnable(agentID string, configPath string, changes []Change) error {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.state.Agents[agentID] = AgentState{
Enabled: true,
ConfigPath: configPath,
Changes: changes,
EnabledAt: time.Now(),
}
return sm.saveUnlocked()
}
// RecordDisable records that an agent has been disabled
func (sm *StateManager) RecordDisable(agentID string) error {
sm.mu.Lock()
defer sm.mu.Unlock()
if state, exists := sm.state.Agents[agentID]; exists {
state.Enabled = false
state.DisabledAt = time.Now()
sm.state.Agents[agentID] = state
}
return sm.saveUnlocked()
}
// GetChanges returns the list of changes for an agent
func (sm *StateManager) GetChanges(agentID string) []Change {
state, exists := sm.GetAgentState(agentID)
if !exists {
return nil
}
return state.Changes
}
// GetAllAgentStates returns all agent states
func (sm *StateManager) GetAllAgentStates() map[string]AgentState {
sm.mu.RLock()
defer sm.mu.RUnlock()
result := make(map[string]AgentState, len(sm.state.Agents))
for k, v := range sm.state.Agents {
result[k] = v
}
return result
}
// GetBaseDir returns the base directory for ProxyPilot config
func (sm *StateManager) GetBaseDir() string {
return sm.baseDir
}
// GetAgentsDir returns the directory for agent-specific configs
func (sm *StateManager) GetAgentsDir() string {
return filepath.Join(sm.baseDir, "agents")
}
// ClearAgent removes all state for an agent (used after successful disable)
func (sm *StateManager) ClearAgent(agentID string) error {
sm.mu.Lock()
defer sm.mu.Unlock()
delete(sm.state.Agents, agentID)
return sm.saveUnlocked()
}
+123
View File
@@ -0,0 +1,123 @@
package api
import (
"context"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
)
// mockCoreManager implements memory.CoreManagerExecutor for testing
type mockCoreManager struct {
response interface{}
err error
}
func (m *mockCoreManager) Execute(ctx context.Context, providers []string, req interface{}, opts interface{}) (interface{}, error) {
return m.response, m.err
}
func TestContextCompression_AdapterIntegration(t *testing.T) {
// Test that the adapter correctly bridges manager to executor
mockResp := struct {
Payload []byte `json:"payload"`
}{
Payload: []byte(`{"choices":[{"message":{"content":"Test summary"}}]}`),
}
manager := &mockCoreManager{response: mockResp}
adapter := memory.NewManagerAuthAdapter(manager)
if adapter == nil {
t.Fatal("Expected adapter to be created")
}
// Test execute
resp, err := adapter.Execute(context.Background(), []string{"claude"}, memory.ExecutorRequest{
Model: "claude-3-opus",
Payload: []byte(`{"test": true}`),
}, memory.ExecutorOptions{})
if err != nil {
t.Fatalf("Execute failed: %v", err)
}
if len(resp) == 0 {
t.Error("Expected non-empty response")
}
}
func TestAgenticHarness_MiddlewareIntegration(t *testing.T) {
gin.SetMode(gin.TestMode)
// Create temp directory for harness files
tmpDir, err := os.MkdirTemp("", "harness-integration")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
handler := middleware.AgenticHarnessMiddlewareWithRootDir(tmpDir)
// Test 1: Fresh conversation should get INITIALIZER
t.Run("fresh_conversation_initializer", func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := `{"model":"gpt-4","messages":[{"role":"user","content":"Build a todo app"}]}`
c.Request = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
c.Request.Header.Set("User-Agent", "claude-cli/1.0")
c.Request.Header.Set("Content-Type", "application/json")
handler(c)
mode := c.Writer.Header().Get("X-ProxyPilot-Harness-Mode")
if mode != "INITIALIZER" {
t.Errorf("Expected INITIALIZER mode, got: %s", mode)
}
})
// Test 2: After creating harness files, should get CODING
t.Run("with_harness_files_coding", func(t *testing.T) {
// Create harness file
os.WriteFile(tmpDir+"/feature_list.json", []byte(`[{"id":"test","passes":false}]`), 0644)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := `{"model":"gpt-4","messages":[{"role":"user","content":"Continue"}]}`
c.Request = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
c.Request.Header.Set("User-Agent", "claude-cli/1.0")
c.Request.Header.Set("Content-Type", "application/json")
handler(c)
mode := c.Writer.Header().Get("X-ProxyPilot-Harness-Mode")
if mode != "CODING" {
t.Errorf("Expected CODING mode, got: %s", mode)
}
})
}
func TestCombinedFeatures_NoConflict(t *testing.T) {
// Verify both features can be enabled simultaneously without conflict
gin.SetMode(gin.TestMode)
// Set up harness
tmpDir, _ := os.MkdirTemp("", "combined-test")
defer os.RemoveAll(tmpDir)
// Create engine with both middlewares
engine := gin.New()
engine.Use(middleware.AgenticHarnessMiddleware())
// Verify engine was created without panic
if engine == nil {
t.Fatal("Engine should be created")
}
}
@@ -0,0 +1,129 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/agents"
)
// AgentsV2Handler provides the new unified agent configuration API
type AgentsV2Handler struct {
manager *agents.Manager
}
// NewAgentsV2Handler creates a new AgentsV2Handler
func NewAgentsV2Handler(port int) (*AgentsV2Handler, error) {
manager, err := agents.NewManager(port)
if err != nil {
return nil, err
}
return &AgentsV2Handler{manager: manager}, nil
}
// GetAgents returns the list of detected CLI agents
// GET /api/v2/agents
func (h *AgentsV2Handler) GetAgents(c *gin.Context) {
agentsList, err := h.manager.DetectAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"agents": agentsList})
}
// GetAgent returns info for a specific agent
// GET /api/v2/agents/:id
func (h *AgentsV2Handler) GetAgent(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
info, err := h.manager.GetAgentInfo(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, info)
}
// EnableAgent enables ProxyPilot for an agent
// POST /api/v2/agents/:id/enable
func (h *AgentsV2Handler) EnableAgent(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
result := h.manager.Enable(id)
if !result.Success {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": result.Error,
"instructions": result.Instructions,
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"agent_id": result.AgentID,
"message": result.Message,
"config_path": result.ConfigPath,
})
}
// DisableAgent disables ProxyPilot for an agent
// POST /api/v2/agents/:id/disable
func (h *AgentsV2Handler) DisableAgent(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
result := h.manager.Disable(id)
if !result.Success {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": result.Error,
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"agent_id": result.AgentID,
"message": result.Message,
})
}
// EnableAllAgents enables ProxyPilot for all detected agents
// POST /api/v2/agents/enable-all
func (h *AgentsV2Handler) EnableAllAgents(c *gin.Context) {
results := h.manager.EnableAll()
c.JSON(http.StatusOK, gin.H{"results": results})
}
// DisableAllAgents disables ProxyPilot for all configured agents
// POST /api/v2/agents/disable-all
func (h *AgentsV2Handler) DisableAllAgents(c *gin.Context) {
results := h.manager.DisableAll()
c.JSON(http.StatusOK, gin.H{"results": results})
}
// GetAgentState returns the current ProxyPilot state for all agents
// GET /api/v2/agents/state
func (h *AgentsV2Handler) GetAgentState(c *gin.Context) {
states := h.manager.GetState().GetAllAgentStates()
c.JSON(http.StatusOK, gin.H{"states": states})
}
// SetProxyPort updates the proxy port used by the manager
func (h *AgentsV2Handler) SetProxyPort(port int) {
h.manager.SetProxyURL(port)
}
@@ -0,0 +1,704 @@
package management
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/geminicli"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
const defaultAPICallTimeout = 60 * time.Second
const (
geminiOAuthClientID = "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com"
geminiOAuthClientSecret = "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"
)
var geminiOAuthScopes = []string{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
}
const (
antigravityOAuthClientID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"
antigravityOAuthClientSecret = "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"
)
var antigravityOAuthTokenURL = "https://oauth2.googleapis.com/token"
type apiCallRequest struct {
AuthIndexSnake *string `json:"auth_index"`
AuthIndexCamel *string `json:"authIndex"`
AuthIndexPascal *string `json:"AuthIndex"`
Method string `json:"method"`
URL string `json:"url"`
Header map[string]string `json:"header"`
Data string `json:"data"`
}
type apiCallResponse struct {
StatusCode int `json:"status_code"`
Header map[string][]string `json:"header"`
Body string `json:"body"`
}
// APICall makes a generic HTTP request on behalf of the management API caller.
// It is protected by the management middleware.
//
// Endpoint:
//
// POST /v0/management/api-call
//
// Authentication:
//
// Same as other management APIs (requires a management key and remote-management rules).
// You can provide the key via:
// - Authorization: Bearer <key>
// - X-Management-Key: <key>
//
// Request JSON:
// - auth_index / authIndex / AuthIndex (optional):
// The credential "auth_index" from GET /v0/management/auth-files (or other endpoints returning it).
// If omitted or not found, credential-specific proxy/token substitution is skipped.
// - method (required): HTTP method, e.g. GET, POST, PUT, PATCH, DELETE.
// - url (required): Absolute URL including scheme and host, e.g. "https://api.example.com/v1/ping".
// - header (optional): Request headers map.
// Supports magic variable "$TOKEN$" which is replaced using the selected credential:
// 1) metadata.access_token
// 2) attributes.api_key
// 3) metadata.token / metadata.id_token / metadata.cookie
// Example: {"Authorization":"Bearer $TOKEN$"}.
// Note: if you need to override the HTTP Host header, set header["Host"].
// - data (optional): Raw request body as string (useful for POST/PUT/PATCH).
//
// Proxy selection (highest priority first):
// 1. Selected credential proxy_url
// 2. Global config proxy-url
// 3. Direct connect (environment proxies are not used)
//
// Response JSON (returned with HTTP 200 when the APICall itself succeeds):
// - status_code: Upstream HTTP status code.
// - header: Upstream response headers.
// - body: Upstream response body as string.
//
// Example:
//
// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \
// -H "Authorization: Bearer <MANAGEMENT_KEY>" \
// -H "Content-Type: application/json" \
// -d '{"auth_index":"<AUTH_INDEX>","method":"GET","url":"https://api.example.com/v1/ping","header":{"Authorization":"Bearer $TOKEN$"}}'
//
// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \
// -H "Authorization: Bearer 831227" \
// -H "Content-Type: application/json" \
// -d '{"auth_index":"<AUTH_INDEX>","method":"POST","url":"https://api.example.com/v1/fetchAvailableModels","header":{"Authorization":"Bearer $TOKEN$","Content-Type":"application/json","User-Agent":"cliproxyapi"},"data":"{}"}'
func (h *Handler) APICall(c *gin.Context) {
var body apiCallRequest
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
method := strings.ToUpper(strings.TrimSpace(body.Method))
if method == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing method"})
return
}
urlStr := strings.TrimSpace(body.URL)
if urlStr == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing url"})
return
}
parsedURL, errParseURL := url.Parse(urlStr)
if errParseURL != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid url"})
return
}
authIndex := firstNonEmptyString(body.AuthIndexSnake, body.AuthIndexCamel, body.AuthIndexPascal)
auth := h.authByIndex(authIndex)
reqHeaders := body.Header
if reqHeaders == nil {
reqHeaders = map[string]string{}
}
var hostOverride string
var token string
var tokenResolved bool
var tokenErr error
for key, value := range reqHeaders {
if !strings.Contains(value, "$TOKEN$") {
continue
}
if !tokenResolved {
token, tokenErr = h.resolveTokenForAuth(c.Request.Context(), auth)
tokenResolved = true
}
if auth != nil && token == "" {
if tokenErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "auth token refresh failed"})
return
}
c.JSON(http.StatusBadRequest, gin.H{"error": "auth token not found"})
return
}
if token == "" {
continue
}
reqHeaders[key] = strings.ReplaceAll(value, "$TOKEN$", token)
}
var requestBody io.Reader
if body.Data != "" {
requestBody = strings.NewReader(body.Data)
}
req, errNewRequest := http.NewRequestWithContext(c.Request.Context(), method, urlStr, requestBody)
if errNewRequest != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to build request"})
return
}
for key, value := range reqHeaders {
if strings.EqualFold(key, "host") {
hostOverride = strings.TrimSpace(value)
continue
}
req.Header.Set(key, value)
}
if hostOverride != "" {
req.Host = hostOverride
}
httpClient := &http.Client{
Timeout: defaultAPICallTimeout,
}
httpClient.Transport = h.apiCallTransport(auth)
resp, errDo := httpClient.Do(req)
if errDo != nil {
log.WithError(errDo).Debug("management APICall request failed")
c.JSON(http.StatusBadGateway, gin.H{"error": "request failed"})
return
}
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
}()
respBody, errReadAll := io.ReadAll(resp.Body)
if errReadAll != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to read response"})
return
}
c.JSON(http.StatusOK, apiCallResponse{
StatusCode: resp.StatusCode,
Header: resp.Header,
Body: string(respBody),
})
}
func firstNonEmptyString(values ...*string) string {
for _, v := range values {
if v == nil {
continue
}
if out := strings.TrimSpace(*v); out != "" {
return out
}
}
return ""
}
func tokenValueForAuth(auth *coreauth.Auth) string {
if auth == nil {
return ""
}
if v := tokenValueFromMetadata(auth.Metadata); v != "" {
return v
}
if auth.Attributes != nil {
if v := strings.TrimSpace(auth.Attributes["api_key"]); v != "" {
return v
}
}
if shared := geminicli.ResolveSharedCredential(auth.Runtime); shared != nil {
if v := tokenValueFromMetadata(shared.MetadataSnapshot()); v != "" {
return v
}
}
return ""
}
func (h *Handler) resolveTokenForAuth(ctx context.Context, auth *coreauth.Auth) (string, error) {
if auth == nil {
return "", nil
}
provider := strings.ToLower(strings.TrimSpace(auth.Provider))
if provider == "gemini-cli" {
token, errToken := h.refreshGeminiOAuthAccessToken(ctx, auth)
return token, errToken
}
if provider == "antigravity" {
token, errToken := h.refreshAntigravityOAuthAccessToken(ctx, auth)
return token, errToken
}
return tokenValueForAuth(auth), nil
}
func (h *Handler) refreshGeminiOAuthAccessToken(ctx context.Context, auth *coreauth.Auth) (string, error) {
if ctx == nil {
ctx = context.Background()
}
if auth == nil {
return "", nil
}
metadata, updater := geminiOAuthMetadata(auth)
if len(metadata) == 0 {
return "", fmt.Errorf("gemini oauth metadata missing")
}
base := make(map[string]any)
if tokenRaw, ok := metadata["token"].(map[string]any); ok && tokenRaw != nil {
base = cloneMap(tokenRaw)
}
var token oauth2.Token
if len(base) > 0 {
if raw, errMarshal := json.Marshal(base); errMarshal == nil {
_ = json.Unmarshal(raw, &token)
}
}
if token.AccessToken == "" {
token.AccessToken = stringValue(metadata, "access_token")
}
if token.RefreshToken == "" {
token.RefreshToken = stringValue(metadata, "refresh_token")
}
if token.TokenType == "" {
token.TokenType = stringValue(metadata, "token_type")
}
if token.Expiry.IsZero() {
if expiry := stringValue(metadata, "expiry"); expiry != "" {
if ts, errParseTime := time.Parse(time.RFC3339, expiry); errParseTime == nil {
token.Expiry = ts
}
}
}
conf := &oauth2.Config{
ClientID: geminiOAuthClientID,
ClientSecret: geminiOAuthClientSecret,
Scopes: geminiOAuthScopes,
Endpoint: google.Endpoint,
}
ctxToken := ctx
httpClient := &http.Client{
Timeout: defaultAPICallTimeout,
Transport: h.apiCallTransport(auth),
}
ctxToken = context.WithValue(ctxToken, oauth2.HTTPClient, httpClient)
src := conf.TokenSource(ctxToken, &token)
currentToken, errToken := src.Token()
if errToken != nil {
return "", errToken
}
merged := buildOAuthTokenMap(base, currentToken)
fields := buildOAuthTokenFields(currentToken, merged)
if updater != nil {
updater(fields)
}
return strings.TrimSpace(currentToken.AccessToken), nil
}
func (h *Handler) refreshAntigravityOAuthAccessToken(ctx context.Context, auth *coreauth.Auth) (string, error) {
if ctx == nil {
ctx = context.Background()
}
if auth == nil {
return "", nil
}
metadata := auth.Metadata
if len(metadata) == 0 {
return "", fmt.Errorf("antigravity oauth metadata missing")
}
current := strings.TrimSpace(tokenValueFromMetadata(metadata))
if current != "" && !antigravityTokenNeedsRefresh(metadata) {
return current, nil
}
refreshToken := stringValue(metadata, "refresh_token")
if refreshToken == "" {
return "", fmt.Errorf("antigravity refresh token missing")
}
tokenURL := strings.TrimSpace(antigravityOAuthTokenURL)
if tokenURL == "" {
tokenURL = "https://oauth2.googleapis.com/token"
}
form := url.Values{}
form.Set("client_id", antigravityOAuthClientID)
form.Set("client_secret", antigravityOAuthClientSecret)
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
req, errReq := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
if errReq != nil {
return "", errReq
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{
Timeout: defaultAPICallTimeout,
Transport: h.apiCallTransport(auth),
}
resp, errDo := httpClient.Do(req)
if errDo != nil {
return "", errDo
}
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
log.Errorf("response body close error: %v", errClose)
}
}()
bodyBytes, errRead := io.ReadAll(resp.Body)
if errRead != nil {
return "", errRead
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return "", fmt.Errorf("antigravity oauth token refresh failed: status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
}
var tokenResp struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"`
TokenType string `json:"token_type"`
}
if errUnmarshal := json.Unmarshal(bodyBytes, &tokenResp); errUnmarshal != nil {
return "", errUnmarshal
}
if strings.TrimSpace(tokenResp.AccessToken) == "" {
return "", fmt.Errorf("antigravity oauth token refresh returned empty access_token")
}
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
now := time.Now()
auth.Metadata["access_token"] = strings.TrimSpace(tokenResp.AccessToken)
if strings.TrimSpace(tokenResp.RefreshToken) != "" {
auth.Metadata["refresh_token"] = strings.TrimSpace(tokenResp.RefreshToken)
}
if tokenResp.ExpiresIn > 0 {
auth.Metadata["expires_in"] = tokenResp.ExpiresIn
auth.Metadata["timestamp"] = now.UnixMilli()
auth.Metadata["expired"] = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339)
}
auth.Metadata["type"] = "antigravity"
if h != nil && h.authManager != nil {
auth.LastRefreshedAt = now
auth.UpdatedAt = now
_, _ = h.authManager.Update(ctx, auth)
}
return strings.TrimSpace(tokenResp.AccessToken), nil
}
func antigravityTokenNeedsRefresh(metadata map[string]any) bool {
// Refresh a bit early to avoid requests racing token expiry.
const skew = 30 * time.Second
if metadata == nil {
return true
}
if expStr, ok := metadata["expired"].(string); ok {
if ts, errParse := time.Parse(time.RFC3339, strings.TrimSpace(expStr)); errParse == nil {
return !ts.After(time.Now().Add(skew))
}
}
expiresIn := int64Value(metadata["expires_in"])
timestampMs := int64Value(metadata["timestamp"])
if expiresIn > 0 && timestampMs > 0 {
exp := time.UnixMilli(timestampMs).Add(time.Duration(expiresIn) * time.Second)
return !exp.After(time.Now().Add(skew))
}
return true
}
func int64Value(raw any) int64 {
switch typed := raw.(type) {
case int:
return int64(typed)
case int32:
return int64(typed)
case int64:
return typed
case uint:
return int64(typed)
case uint32:
return int64(typed)
case uint64:
if typed > uint64(^uint64(0)>>1) {
return 0
}
return int64(typed)
case float32:
return int64(typed)
case float64:
return int64(typed)
case json.Number:
if i, errParse := typed.Int64(); errParse == nil {
return i
}
case string:
if s := strings.TrimSpace(typed); s != "" {
if i, errParse := json.Number(s).Int64(); errParse == nil {
return i
}
}
}
return 0
}
func geminiOAuthMetadata(auth *coreauth.Auth) (map[string]any, func(map[string]any)) {
if auth == nil {
return nil, nil
}
if shared := geminicli.ResolveSharedCredential(auth.Runtime); shared != nil {
snapshot := shared.MetadataSnapshot()
return snapshot, func(fields map[string]any) { shared.MergeMetadata(fields) }
}
return auth.Metadata, func(fields map[string]any) {
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
for k, v := range fields {
auth.Metadata[k] = v
}
}
}
func stringValue(metadata map[string]any, key string) string {
if len(metadata) == 0 || key == "" {
return ""
}
if v, ok := metadata[key].(string); ok {
return strings.TrimSpace(v)
}
return ""
}
func cloneMap(in map[string]any) map[string]any {
if len(in) == 0 {
return nil
}
out := make(map[string]any, len(in))
for k, v := range in {
out[k] = v
}
return out
}
func buildOAuthTokenMap(base map[string]any, tok *oauth2.Token) map[string]any {
merged := cloneMap(base)
if merged == nil {
merged = make(map[string]any)
}
if tok == nil {
return merged
}
if raw, errMarshal := json.Marshal(tok); errMarshal == nil {
var tokenMap map[string]any
if errUnmarshal := json.Unmarshal(raw, &tokenMap); errUnmarshal == nil {
for k, v := range tokenMap {
merged[k] = v
}
}
}
return merged
}
func buildOAuthTokenFields(tok *oauth2.Token, merged map[string]any) map[string]any {
fields := make(map[string]any, 5)
if tok != nil && tok.AccessToken != "" {
fields["access_token"] = tok.AccessToken
}
if tok != nil && tok.TokenType != "" {
fields["token_type"] = tok.TokenType
}
if tok != nil && tok.RefreshToken != "" {
fields["refresh_token"] = tok.RefreshToken
}
if tok != nil && !tok.Expiry.IsZero() {
fields["expiry"] = tok.Expiry.Format(time.RFC3339)
}
if len(merged) > 0 {
fields["token"] = cloneMap(merged)
}
return fields
}
func tokenValueFromMetadata(metadata map[string]any) string {
if len(metadata) == 0 {
return ""
}
if v, ok := metadata["accessToken"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
if v, ok := metadata["access_token"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
if tokenRaw, ok := metadata["token"]; ok && tokenRaw != nil {
switch typed := tokenRaw.(type) {
case string:
if v := strings.TrimSpace(typed); v != "" {
return v
}
case map[string]any:
if v, ok := typed["access_token"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
if v, ok := typed["accessToken"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
case map[string]string:
if v := strings.TrimSpace(typed["access_token"]); v != "" {
return v
}
if v := strings.TrimSpace(typed["accessToken"]); v != "" {
return v
}
}
}
if v, ok := metadata["token"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
if v, ok := metadata["id_token"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
if v, ok := metadata["cookie"].(string); ok && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
return ""
}
func (h *Handler) authByIndex(authIndex string) *coreauth.Auth {
authIndex = strings.TrimSpace(authIndex)
if authIndex == "" || h == nil || h.authManager == nil {
return nil
}
auths := h.authManager.List()
for _, auth := range auths {
if auth == nil {
continue
}
auth.EnsureIndex()
if auth.Index == authIndex {
return auth
}
}
return nil
}
func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
var proxyCandidates []string
if auth != nil {
if proxyStr := strings.TrimSpace(auth.ProxyURL); proxyStr != "" {
proxyCandidates = append(proxyCandidates, proxyStr)
}
}
if h != nil && h.cfg != nil {
if proxyStr := strings.TrimSpace(h.cfg.ProxyURL); proxyStr != "" {
proxyCandidates = append(proxyCandidates, proxyStr)
}
}
for _, proxyStr := range proxyCandidates {
if transport := buildProxyTransport(proxyStr); transport != nil {
return transport
}
}
transport, ok := http.DefaultTransport.(*http.Transport)
if !ok || transport == nil {
return &http.Transport{Proxy: nil}
}
clone := transport.Clone()
clone.Proxy = nil
return clone
}
func buildProxyTransport(proxyStr string) *http.Transport {
proxyStr = strings.TrimSpace(proxyStr)
if proxyStr == "" {
return nil
}
proxyURL, errParse := url.Parse(proxyStr)
if errParse != nil {
log.WithError(errParse).Debug("parse proxy URL failed")
return nil
}
if proxyURL.Scheme == "" || proxyURL.Host == "" {
log.Debug("proxy URL missing scheme/host")
return nil
}
if proxyURL.Scheme == "socks5" {
var proxyAuth *proxy.Auth
if proxyURL.User != nil {
username := proxyURL.User.Username()
password, _ := proxyURL.User.Password()
proxyAuth = &proxy.Auth{User: username, Password: password}
}
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, proxyAuth, proxy.Direct)
if errSOCKS5 != nil {
log.WithError(errSOCKS5).Debug("create SOCKS5 dialer failed")
return nil
}
return &http.Transport{
Proxy: nil,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
},
}
}
if proxyURL.Scheme == "http" || proxyURL.Scheme == "https" {
return &http.Transport{Proxy: http.ProxyURL(proxyURL)}
}
log.Debugf("unsupported proxy scheme: %s", proxyURL.Scheme)
return nil
}
@@ -0,0 +1,173 @@
package management
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
type memoryAuthStore struct {
mu sync.Mutex
items map[string]*coreauth.Auth
}
func (s *memoryAuthStore) List(ctx context.Context) ([]*coreauth.Auth, error) {
_ = ctx
s.mu.Lock()
defer s.mu.Unlock()
out := make([]*coreauth.Auth, 0, len(s.items))
for _, a := range s.items {
out = append(out, a.Clone())
}
return out, nil
}
func (s *memoryAuthStore) Save(ctx context.Context, auth *coreauth.Auth) (string, error) {
_ = ctx
if auth == nil {
return "", nil
}
s.mu.Lock()
if s.items == nil {
s.items = make(map[string]*coreauth.Auth)
}
s.items[auth.ID] = auth.Clone()
s.mu.Unlock()
return auth.ID, nil
}
func (s *memoryAuthStore) Delete(ctx context.Context, id string) error {
_ = ctx
s.mu.Lock()
delete(s.items, id)
s.mu.Unlock()
return nil
}
func TestResolveTokenForAuth_Antigravity_RefreshesExpiredToken(t *testing.T) {
var callCount int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
if r.Method != http.MethodPost {
t.Fatalf("expected POST, got %s", r.Method)
}
if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/x-www-form-urlencoded") {
t.Fatalf("unexpected content-type: %s", ct)
}
bodyBytes, _ := io.ReadAll(r.Body)
_ = r.Body.Close()
values, err := url.ParseQuery(string(bodyBytes))
if err != nil {
t.Fatalf("parse form: %v", err)
}
if values.Get("grant_type") != "refresh_token" {
t.Fatalf("unexpected grant_type: %s", values.Get("grant_type"))
}
if values.Get("refresh_token") != "rt" {
t.Fatalf("unexpected refresh_token: %s", values.Get("refresh_token"))
}
if values.Get("client_id") != antigravityOAuthClientID {
t.Fatalf("unexpected client_id: %s", values.Get("client_id"))
}
if values.Get("client_secret") != antigravityOAuthClientSecret {
t.Fatalf("unexpected client_secret")
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "new-token",
"refresh_token": "rt2",
"expires_in": int64(3600),
"token_type": "Bearer",
})
}))
t.Cleanup(srv.Close)
originalURL := antigravityOAuthTokenURL
antigravityOAuthTokenURL = srv.URL
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
store := &memoryAuthStore{}
manager := coreauth.NewManager(store, nil, nil)
auth := &coreauth.Auth{
ID: "antigravity-test.json",
FileName: "antigravity-test.json",
Provider: "antigravity",
Metadata: map[string]any{
"type": "antigravity",
"access_token": "old-token",
"refresh_token": "rt",
"expires_in": int64(3600),
"timestamp": time.Now().Add(-2 * time.Hour).UnixMilli(),
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
},
}
if _, err := manager.Register(context.Background(), auth); err != nil {
t.Fatalf("register auth: %v", err)
}
h := &Handler{authManager: manager}
token, err := h.resolveTokenForAuth(context.Background(), auth)
if err != nil {
t.Fatalf("resolveTokenForAuth: %v", err)
}
if token != "new-token" {
t.Fatalf("expected refreshed token, got %q", token)
}
if callCount != 1 {
t.Fatalf("expected 1 refresh call, got %d", callCount)
}
updated, ok := manager.GetByID(auth.ID)
if !ok || updated == nil {
t.Fatalf("expected auth in manager after update")
}
if got := tokenValueFromMetadata(updated.Metadata); got != "new-token" {
t.Fatalf("expected manager metadata updated, got %q", got)
}
}
func TestResolveTokenForAuth_Antigravity_SkipsRefreshWhenTokenValid(t *testing.T) {
var callCount int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
w.WriteHeader(http.StatusInternalServerError)
}))
t.Cleanup(srv.Close)
originalURL := antigravityOAuthTokenURL
antigravityOAuthTokenURL = srv.URL
t.Cleanup(func() { antigravityOAuthTokenURL = originalURL })
auth := &coreauth.Auth{
ID: "antigravity-valid.json",
FileName: "antigravity-valid.json",
Provider: "antigravity",
Metadata: map[string]any{
"type": "antigravity",
"access_token": "ok-token",
"expired": time.Now().Add(30 * time.Minute).Format(time.RFC3339),
},
}
h := &Handler{}
token, err := h.resolveTokenForAuth(context.Background(), auth)
if err != nil {
t.Fatalf("resolveTokenForAuth: %v", err)
}
if token != "ok-token" {
t.Fatalf("expected existing token, got %q", token)
}
if callCount != 0 {
t.Fatalf("expected no refresh calls, got %d", callCount)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,50 @@
package management
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type setAuthPriorityRequest struct {
Priority *int `json:"priority"`
}
// SetAuthPriority updates the priority field for an auth entry.
func (h *Handler) SetAuthPriority(c *gin.Context) {
authID := strings.TrimSpace(c.Param("id"))
if authID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth id"})
return
}
var req setAuthPriorityRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Priority == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
auth, ok := h.authManager.GetByID(authID)
if !ok || auth == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
return
}
auth.Priority = *req.Priority
auth.UpdatedAt = time.Now()
updated, err := h.authManager.Update(c.Request.Context(), auth)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, h.buildAuthFileEntry(updated))
}

Some files were not shown because too many files have changed in this diff Show More