Compare commits

...
Author SHA1 Message Date
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
258 changed files with 41578 additions and 8136 deletions
+1 -2
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)
@@ -32,3 +30,4 @@ bin/*
.agent/*
.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"
+104
View File
@@ -0,0 +1,104 @@
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: 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
+19 -8
View File
@@ -12,10 +12,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 +44,8 @@ docs/*
!docs/memory.md
!docs/proxypilot.md
!docs/agentic-harness-demo.md
!docs/long-context-features.md
!docs/desktop-app-build-process.md
AGENTS.md
CLAUDE.md
GEMINI.md
@@ -48,6 +58,7 @@ GEMINI.md
.agent/*
.bmad/*
_bmad/*
_bmad-output/*
.mcp/cache/
# macOS
@@ -55,11 +66,11 @@ _bmad/*
._*
*.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/
+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.
+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
+207 -15
View File
@@ -1,31 +1,223 @@
# 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
- 🎯 **8 Auth Providers** - Claude, Codex (OpenAI), Gemini, Gemini CLI, Kiro (AWS), Qwen, 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
- 🎨 **Desktop App** - Native Windows control center with system tray
- 📡 **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 models |
| Kiro | OAuth2 + AWS SSO | AWS CodeWhisperer |
| Qwen | OAuth2 | Qwen models |
| 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
./proxypilot --claude-login # Claude
./proxypilot --codex-login # OpenAI/Codex
./proxypilot --login # Gemini
./proxypilot --kiro-login # Kiro/AWS
```
Your browser opens automatically. Tokens are stored and auto-refreshed.
### 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.
---
## CLI Tools
| Binary | Description |
|--------|-------------|
| `proxypilot` | Main API proxy server |
| `proxypilotui` | Desktop control center (Windows) |
| `cliproxytray` | System tray application (Windows) |
| `proxypilotpack` | Build and packaging tool |
---
## 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)
+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
}
+310 -288
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
"flag"
"fmt"
"io/fs"
"net"
"net/http"
"net/http/httputil"
@@ -14,36 +15,84 @@ 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/cmd/proxypilotui/assets"
"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() {
// Start embedded asset server for the dashboard UI
assetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err == nil {
assetServerURL = "http://" + assetLn.Addr().String()
go func() {
fsys, _ := fs.Sub(assets.FS, ".")
http.Serve(assetLn, http.FileServer(http.FS(fsys)))
}()
}
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 +101,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 +179,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 +215,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 +230,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 +291,181 @@ 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_legacy_ui", func() error {
cur := engine.Status()
if !cur.Running {
return fmt.Errorf("proxy not running")
}
return desktopctl.OpenBrowser(cur.BaseURL + "/management.html?legacy=1")
})
_ = 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 +506,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 +547,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 +624,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 +634,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 +672,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
}
+259
View File
@@ -0,0 +1,259 @@
# 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
# 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.
# 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

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
+6
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" />
<meta name="pp-mgmt-key" content="test123" />
<title>webui</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

+312 -5
View File
@@ -21,6 +21,8 @@ import (
"github.com/jchv/go-webview2"
"github.com/router-for-me/CLIProxyAPI/v6/cmd/proxypilotui/assets"
"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/translator"
)
func main() {
@@ -29,13 +31,21 @@ func main() {
var exePath string
var url string
var standalone bool
var legacyMode 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(&exePath, "exe", "", "Path to proxy engine binary (legacy mode only)")
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.BoolVar(&legacyMode, "legacy", false, "Use legacy subprocess mode (separate engine binary)")
flag.Parse()
// Enable embedded mode by default (single binary)
if !legacyMode {
desktopctl.SetEmbeddedMode(true)
logging.SetupBaseLogger()
}
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
var assetServerURL string
@@ -130,6 +140,7 @@ func main() {
cur, _ := desktopctl.StatusFor(configPath)
return map[string]any{
"running": cur.Running,
"version": cur.Version,
"port": cur.Port,
"thinking_port": cur.ThinkingPort,
"thinking_running": cur.ThinkingRunning,
@@ -183,8 +194,6 @@ func main() {
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)
}
@@ -193,6 +202,31 @@ func main() {
_ = w.Bind("pp_copy_diagnostics", func() error { return copyDiagnosticsToClipboard(configPath) })
_ = w.Bind("pp_get_management_key", func() (string, error) { return desktopctl.GetManagementPassword() })
_ = w.Bind("pp_check_updates", 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: 10 * time.Second}
req, _ := http.NewRequest("GET", st.BaseURL+"/v0/management/updates/check", 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 map[string]any
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res, nil
})
_ = w.Bind("pp_download_update", func(url string) error {
return desktopctl.OpenBrowser(url)
})
// Integration bindings
_ = w.Bind("pp_get_integrations", func() ([]map[string]any, error) {
st, _ := desktopctl.StatusFor(configPath)
@@ -238,6 +272,42 @@ func main() {
return nil
})
// Agent detection bindings
_ = w.Bind("pp_detect_agents", func() ([]map[string]any, error) {
agents := detectCLIAgents()
return agents, nil
})
_ = w.Bind("pp_configure_agent", func(agentID 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/"+agentID, 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
})
// Model mappings bindings
_ = w.Bind("pp_get_model_mappings", func() ([]map[string]any, error) {
return getModelMappings(), nil
})
_ = w.Bind("pp_save_model_mappings", func(mappings []map[string]any) error {
return saveModelMappings(mappings)
})
if target != "" {
w.Navigate(target)
w.Run()
@@ -574,11 +644,33 @@ func controlCenterHTML() string {
<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">CLI Agents</div>
<div class="row" id="agentsList">
<div style="color:var(--muted);font-size:13px">Detecting agents...</div>
</div>
<div class="note">
Detected CLI agents. Click to configure for ProxyPilot.
</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Model Mappings</div>
<div id="mappingsList" style="margin-bottom:12px"></div>
<div class="row" style="gap:8px;flex-wrap:wrap">
<input type="text" id="mapFrom" placeholder="Alias (e.g. smart)" style="flex:1;min-width:120px;padding:8px 10px;background:rgba(0,0,0,.3);border:1px solid var(--line);border-radius:8px;color:var(--text);font-size:13px" />
<input type="text" id="mapTo" placeholder="Model (e.g. claude-opus-4-5)" style="flex:2;min-width:180px;padding:8px 10px;background:rgba(0,0,0,.3);border:1px solid var(--line);border-radius:8px;color:var(--text);font-size:13px" />
<button id="addMappingBtn" class="btnPrimary">Add</button>
</div>
<div class="note">
Route friendly model names to actual models.
</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Integrations</div>
<div class="row" id="integrationsList">
@@ -697,12 +789,84 @@ func controlCenterHTML() string {
}
}
async function refreshAgents() {
const list = $('agentsList');
try {
const agents = await window.pp_detect_agents();
if(!agents || agents.length === 0) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">No agents detected</div>';
return;
}
list.innerHTML = '';
agents.forEach(a => {
const btn = document.createElement('button');
if (!a.detected) {
btn.className = 'btn';
btn.disabled = true;
btn.textContent = a.name + ' (Not Found)';
} else if (a.configured) {
btn.className = 'btnGood';
btn.textContent = a.name + ' (Configured)';
} else {
btn.className = 'btnPrimary';
btn.textContent = a.name + ' (Configure)';
}
btn.onclick = async () => {
if (!a.detected) return;
try {
await window.pp_configure_agent(a.id);
toast('Configured ' + a.name);
refreshAgents();
} catch(e) { toast(e.message||String(e)); }
};
list.appendChild(btn);
});
} catch(e) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">Error: ' + (e.message||e) + '</div>';
}
}
async function refreshMappings() {
const list = $('mappingsList');
try {
const mappings = await window.pp_get_model_mappings();
if(!mappings || mappings.length === 0) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">No mappings configured</div>';
return;
}
list.innerHTML = '<div style="display:flex;flex-direction:column;gap:6px">' +
mappings.map((m, i) =>
'<div style="display:flex;align-items:center;gap:8px;padding:8px 10px;background:rgba(0,0,0,.25);border-radius:6px;font-size:13px">' +
'<code style="color:var(--brand)">' + m.from + '</code>' +
'<span style="color:var(--muted)">&rarr;</span>' +
'<code style="color:var(--good)">' + m.to + '</code>' +
'<button class="btnDanger" style="margin-left:auto;padding:4px 8px;font-size:11px" data-idx="' + i + '">Remove</button>' +
'</div>'
).join('') + '</div>';
list.querySelectorAll('button[data-idx]').forEach(btn => {
btn.onclick = async () => {
const idx = parseInt(btn.dataset.idx);
const updated = mappings.filter((_, i) => i !== idx);
try {
await window.pp_save_model_mappings(updated);
toast('Mapping removed');
refreshMappings();
} catch(e) { toast(e.message||String(e)); }
};
});
} catch(e) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">Error loading mappings</div>';
}
}
async function init() {
try{
const priv = await window.pp_get_oauth_private();
$('privateOAuth').checked = !!priv;
}catch(e){}
await refreshStatus();
await refreshAgents();
await refreshMappings();
setInterval(refreshStatus, 1200);
}
@@ -731,7 +895,21 @@ func controlCenterHTML() string {
$('oauthCodex').addEventListener('click', oauth('codex'));
$('oauthClaude').addEventListener('click', oauth('claude'));
$('oauthQwen').addEventListener('click', oauth('qwen'));
$('oauthIflow').addEventListener('click', oauth('iflow'));
$('addMappingBtn').addEventListener('click', async () => {
const from = $('mapFrom').value.trim();
const to = $('mapTo').value.trim();
if (!from || !to) { toast('Both fields required'); return; }
try {
const existing = await window.pp_get_model_mappings() || [];
existing.push({ from, to, enabled: true });
await window.pp_save_model_mappings(existing);
$('mapFrom').value = '';
$('mapTo').value = '';
toast('Mapping added');
refreshMappings();
} catch(e) { toast(e.message||String(e)); }
});
init();
</script>
@@ -751,3 +929,132 @@ func messageBox(title, text string) error {
}
return err
}
// detectCLIAgents returns a list of detected CLI agents
func detectCLIAgents() []map[string]any {
agents := []map[string]any{}
// Claude Code
claude := map[string]any{
"id": "claude",
"name": "Claude Code",
"detected": false,
"configured": false,
}
if path, err := exec.LookPath("claude"); err == nil {
claude["detected"] = true
claude["binary_path"] = path
}
home, _ := os.UserHomeDir()
claudeConfig := filepath.Join(home, ".claude", "settings.json")
if _, err := os.Stat(claudeConfig); err == nil {
claude["detected"] = true
claude["config_path"] = claudeConfig
if content, err := os.ReadFile(claudeConfig); err == nil {
if strings.Contains(string(content), "127.0.0.1:8317") || strings.Contains(string(content), "127.0.0.1:8318") {
claude["configured"] = true
}
}
}
agents = append(agents, claude)
// Codex CLI
codex := map[string]any{
"id": "codex",
"name": "Codex CLI",
"detected": false,
"configured": false,
}
if path, err := exec.LookPath("codex"); err == nil {
codex["detected"] = true
codex["binary_path"] = path
}
codexDir := filepath.Join(home, ".codex")
if info, err := os.Stat(codexDir); err == nil && info.IsDir() {
codex["detected"] = true
codex["config_path"] = codexDir
codexConfig := filepath.Join(codexDir, "config.toml")
if content, err := os.ReadFile(codexConfig); err == nil {
if strings.Contains(string(content), "127.0.0.1:8317") || strings.Contains(string(content), "127.0.0.1:8318") {
codex["configured"] = true
}
}
}
agents = append(agents, codex)
// Factory Droid
droid := map[string]any{
"id": "droid",
"name": "Factory Droid",
"detected": false,
"configured": false,
}
if path, err := exec.LookPath("droid"); err == nil {
droid["detected"] = true
droid["binary_path"] = path
} else if path, err := exec.LookPath("factory"); err == nil {
droid["detected"] = true
droid["binary_path"] = path
}
// Droid uses settings.json for runtime config (not config.json)
droidSettings := filepath.Join(home, ".factory", "settings.json")
if _, err := os.Stat(droidSettings); err == nil {
droid["config_path"] = droidSettings
droid["detected"] = true
if content, err := os.ReadFile(droidSettings); err == nil {
// Check for ProxyPilot models in customModels array
if strings.Contains(string(content), "ProxyPilot") || strings.Contains(string(content), "127.0.0.1:8318") {
droid["configured"] = true
}
}
}
agents = append(agents, droid)
// Gemini CLI
gemini := map[string]any{
"id": "gemini",
"name": "Gemini CLI",
"detected": false,
"configured": false,
}
if path, err := exec.LookPath("gemini"); err == nil {
gemini["detected"] = true
gemini["binary_path"] = path
}
agents = append(agents, gemini)
return agents
}
// getModelMappings reads model mappings from the config file
func getModelMappings() []map[string]any {
home, _ := os.UserHomeDir()
mappingsPath := filepath.Join(home, ".proxypilot", "model-mappings.json")
data, err := os.ReadFile(mappingsPath)
if err != nil {
return []map[string]any{}
}
var mappings []map[string]any
if err := json.Unmarshal(data, &mappings); err != nil {
return []map[string]any{}
}
return mappings
}
// saveModelMappings saves model mappings to the config file
func saveModelMappings(mappings []map[string]any) error {
home, _ := os.UserHomeDir()
mappingsDir := filepath.Join(home, ".proxypilot")
if err := os.MkdirAll(mappingsDir, 0755); err != nil {
return err
}
mappingsPath := filepath.Join(mappingsDir, "model-mappings.json")
data, err := json.MarshalIndent(mappings, "", " ")
if err != nil {
return err
}
return os.WriteFile(mappingsPath, data, 0644)
}
+16 -8
View File
@@ -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
@@ -81,6 +79,10 @@ func main() {
var kiroAWSAuthCode bool
var kiroImport bool
// var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded
var detectAgents bool
var setupClaude bool
var setupCodex bool
var setupDroid bool
var projectID string
var vertexImport string
var configPath string
@@ -93,8 +95,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)")
@@ -105,6 +105,10 @@ func main() {
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)")
// 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.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")
@@ -505,10 +509,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 +533,14 @@ func main() {
cmd.DoKiroAWSAuthCodeLogin(cfg, options)
} else if kiroImport {
cmd.DoKiroImport(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 {
// In cloud deploy mode without config file, just wait for shutdown signals
if isCloudDeploy && !configFileExists {
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": ""
}
+48 -4
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:
@@ -71,13 +78,49 @@ quota-exceeded:
routing:
strategy: "round-robin" # round-robin (default), fill-first
# 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).
# 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.
# 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 +145,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 +242,6 @@ ws-auth: false
# - "vision-model"
# kiro:
# - "kiro-claude-haiku"
# iflow:
# - "tstars2.0"
# Optional payload configuration
# payload:
+287
View File
@@ -0,0 +1,287 @@
# ProxyPilot Desktop App Build Process
Documentation of the desktop application build and release process established on December 27, 2025.
## Overview
ProxyPilot Desktop is a **single executable** that includes both the system tray UI and the proxy engine:
- **ProxyPilot.exe** - System tray app with embedded WebView2 dashboard and embedded proxy engine
## Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ ProxyPilot.exe │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │
│ │ System Tray │ │ WebView2 │ │ Embedded Assets │ │
│ │ (systray) │ │ Dashboard │ │ (webui/dist) │ │
│ └─────────────┘ └─────────────┘ └─────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────┐│
│ │ Embedded Proxy Engine (goroutine) ││
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ ││
│ │ │Thinking Proxy│ │ Routing │ │ Provider Auth │ ││
│ │ │ (port 8317) │ │ Engine │ │ Management │ ││
│ │ └─────────────┘ └─────────────┘ └─────────────────────┘ ││
│ └─────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────┘
```
### In-Process Engine
The proxy engine runs as a goroutine within the same process, managed by `EmbeddedEngine`:
```go
// cmd/cliproxytray/engine.go
type EmbeddedEngine struct {
mu sync.Mutex
service *cliproxy.Service
cancel context.CancelFunc
running bool
port int
// ...
}
func (e *EmbeddedEngine) Start(cfg *config.Config, configPath, password string) error
func (e *EmbeddedEngine) Stop() error
func (e *EmbeddedEngine) Restart(cfg *config.Config, configPath, password string) error
func (e *EmbeddedEngine) Status() Status
```
Benefits of single-binary architecture:
- **Simpler deployment**: One file to distribute and install
- **Smaller total size**: ~29MB vs ~46MB (shared Go runtime)
- **Faster startup**: No process spawning overhead
- **Easier debugging**: Single process to monitor
## 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.
### 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 Executable
```bash
# Build single-binary 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 Desktop App",
"ProductName": "ProxyPilot",
"ProductVersion": "0.1.0"
},
"IconPath": "../../static/icon.ico"
}
```
### Embedded Engine
**cmd/cliproxytray/engine.go** - Manages the in-process proxy service:
- Uses `cliproxy.NewBuilder()` SDK to build the service
- Runs in a goroutine with cancellable context
- Thread-safe start/stop/restart operations
### 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 to `%LOCALAPPDATA%\ProxyPilot`
- Creates Start Menu and Desktop shortcuts
- 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 WebView2 window
├─────────────────────┤
│ Start/Stop │ → Toggle proxy engine
│ Copy API URL │ → Copies http://127.0.0.1:8317/v1
├─────────────────────┤
│ Quit │ → Exit application
└─────────────────────┘
```
## 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
### WebView2 Dashboard Not Loading
1. Ensure WebView2 runtime is installed on the system
2. Check that webui/dist/ assets are embedded (go:embed directive)
3. Verify the asset server is starting on a free port
### 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/
│ └── cliproxytray/
│ ├── main_windows.go # Tray app with embedded engine
│ ├── engine.go # EmbeddedEngine implementation
│ ├── 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 (embedded)
├── installer/
│ └── proxypilot.iss # Inno Setup script
└── dist/ # Distribution files
└── ProxyPilot.exe # Single-binary (~29MB)
```
## Version History
- **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 desktop app release
- System tray with minimal menu
- Embedded WebView2 dashboard
- 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)?
+333
View File
@@ -0,0 +1,333 @@
# 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 |
### 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-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/
+1 -1
View File
@@ -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`).
+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;
+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")
}
}
@@ -25,7 +25,6 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude"
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
geminiAuth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/gemini"
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
kiroauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kiro"
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/qwen"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
@@ -1687,212 +1686,6 @@ func (h *Handler) RequestQwenToken(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})
}
func (h *Handler) RequestIFlowToken(c *gin.Context) {
ctx := context.Background()
fmt.Println("Initializing iFlow authentication...")
state := fmt.Sprintf("ifl-%d", time.Now().UnixNano())
authSvc := iflowauth.NewIFlowAuth(h.cfg)
authURL, redirectURI := authSvc.AuthorizationURL(state, iflowauth.CallbackPort)
RegisterOAuthSession(state, "iflow")
isWebUI := isWebUIRequest(c)
var forwarder *callbackForwarder
if isWebUI {
targetURL, errTarget := h.managementCallbackURL("/iflow/callback")
if errTarget != nil {
log.WithError(errTarget).Error("failed to compute iflow callback target")
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "callback server unavailable"})
return
}
var errStart error
if forwarder, errStart = startCallbackForwarder(iflowauth.CallbackPort, "iflow", targetURL); errStart != nil {
log.WithError(errStart).Error("failed to start iflow callback forwarder")
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to start callback server"})
return
}
}
go func() {
if isWebUI {
defer stopCallbackForwarderInstance(iflowauth.CallbackPort, forwarder)
}
fmt.Println("Waiting for authentication...")
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-iflow-%s.oauth", state))
deadline := time.Now().Add(5 * time.Minute)
var resultMap map[string]string
for {
if !IsOAuthSessionPending(state, "iflow") {
return
}
if time.Now().After(deadline) {
SetOAuthSessionError(state, "Authentication failed")
fmt.Println("Authentication failed: timeout waiting for callback")
return
}
if data, errR := os.ReadFile(waitFile); errR == nil {
_ = os.Remove(waitFile)
_ = json.Unmarshal(data, &resultMap)
break
}
time.Sleep(500 * time.Millisecond)
}
if errStr := strings.TrimSpace(resultMap["error"]); errStr != "" {
SetOAuthSessionError(state, "Authentication failed")
fmt.Printf("Authentication failed: %s\n", errStr)
return
}
if resultState := strings.TrimSpace(resultMap["state"]); resultState != state {
SetOAuthSessionError(state, "Authentication failed")
fmt.Println("Authentication failed: state mismatch")
return
}
code := strings.TrimSpace(resultMap["code"])
if code == "" {
SetOAuthSessionError(state, "Authentication failed")
fmt.Println("Authentication failed: code missing")
return
}
tokenData, errExchange := authSvc.ExchangeCodeForTokens(ctx, code, redirectURI)
if errExchange != nil {
SetOAuthSessionError(state, "Authentication failed")
fmt.Printf("Authentication failed: %v\n", errExchange)
return
}
tokenStorage := authSvc.CreateTokenStorage(tokenData)
identifier := strings.TrimSpace(tokenStorage.Email)
if identifier == "" {
identifier = fmt.Sprintf("iflow-%d", time.Now().UnixMilli())
tokenStorage.Email = identifier
}
record := &coreauth.Auth{
ID: fmt.Sprintf("iflow-%s.json", identifier),
Provider: "iflow",
FileName: fmt.Sprintf("iflow-%s.json", identifier),
Storage: tokenStorage,
Metadata: map[string]any{"email": identifier, "api_key": tokenStorage.APIKey},
Attributes: map[string]string{"api_key": tokenStorage.APIKey},
}
savedPath, errSave := h.saveTokenRecord(ctx, record)
if errSave != nil {
SetOAuthSessionError(state, "Failed to save authentication tokens")
log.Errorf("Failed to save authentication tokens: %v", errSave)
return
}
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
if tokenStorage.APIKey != "" {
fmt.Println("API key obtained and saved")
}
fmt.Println("You can now use iFlow services through this CLI")
CompleteOAuthSession(state)
CompleteOAuthSessionsByProvider("iflow")
}()
c.JSON(http.StatusOK, gin.H{"status": "ok", "url": authURL, "state": state})
}
func (h *Handler) RequestIFlowCookieToken(c *gin.Context) {
ctx := context.Background()
var payload struct {
Cookie string `json:"cookie"`
}
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "cookie is required"})
return
}
cookieValue := strings.TrimSpace(payload.Cookie)
if cookieValue == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "cookie is required"})
return
}
cookieValue, errNormalize := iflowauth.NormalizeCookie(cookieValue)
if errNormalize != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": errNormalize.Error()})
return
}
// Check for duplicate BXAuth before authentication
bxAuth := iflowauth.ExtractBXAuth(cookieValue)
if existingFile, err := iflowauth.CheckDuplicateBXAuth(h.cfg.AuthDir, bxAuth); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to check duplicate"})
return
} else if existingFile != "" {
existingFileName := filepath.Base(existingFile)
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "duplicate BXAuth found", "existing_file": existingFileName})
return
}
authSvc := iflowauth.NewIFlowAuth(h.cfg)
tokenData, errAuth := authSvc.AuthenticateWithCookie(ctx, cookieValue)
if errAuth != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": errAuth.Error()})
return
}
tokenData.Cookie = cookieValue
tokenStorage := authSvc.CreateCookieTokenStorage(tokenData)
email := strings.TrimSpace(tokenStorage.Email)
if email == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "failed to extract email from token"})
return
}
fileName := iflowauth.SanitizeIFlowFileName(email)
if fileName == "" {
fileName = fmt.Sprintf("iflow-%d", time.Now().UnixMilli())
}
tokenStorage.Email = email
timestamp := time.Now().Unix()
record := &coreauth.Auth{
ID: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Provider: "iflow",
FileName: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Storage: tokenStorage,
Metadata: map[string]any{
"email": email,
"api_key": tokenStorage.APIKey,
"expired": tokenStorage.Expire,
"cookie": tokenStorage.Cookie,
"type": tokenStorage.Type,
"last_refresh": tokenStorage.LastRefresh,
},
Attributes: map[string]string{
"api_key": tokenStorage.APIKey,
},
}
savedPath, errSave := h.saveTokenRecord(ctx, record)
if errSave != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to save authentication tokens"})
return
}
fmt.Printf("iFlow cookie authentication successful. Token saved to %s\n", savedPath)
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"saved_path": savedPath,
"email": email,
"expired": tokenStorage.Expire,
"type": tokenStorage.Type,
})
}
type projectSelectionRequiredError struct{}
func (e *projectSelectionRequiredError) Error() string {
@@ -597,11 +597,7 @@ func (h *Handler) PutCodexKeys(c *gin.Context) {
filtered := make([]config.CodexKey, 0, len(arr))
for i := range arr {
entry := arr[i]
entry.APIKey = strings.TrimSpace(entry.APIKey)
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
entry.Headers = config.NormalizeHeaders(entry.Headers)
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
normalizeCodexKey(&entry)
if entry.BaseURL == "" {
continue
}
@@ -613,12 +609,13 @@ func (h *Handler) PutCodexKeys(c *gin.Context) {
}
func (h *Handler) PatchCodexKey(c *gin.Context) {
type codexKeyPatch struct {
APIKey *string `json:"api-key"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
ProxyURL *string `json:"proxy-url"`
Headers *map[string]string `json:"headers"`
ExcludedModels *[]string `json:"excluded-models"`
APIKey *string `json:"api-key"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
ProxyURL *string `json:"proxy-url"`
Models *[]config.CodexModel `json:"models"`
Headers *map[string]string `json:"headers"`
ExcludedModels *[]string `json:"excluded-models"`
}
var body struct {
Index *int `json:"index"`
@@ -667,12 +664,16 @@ func (h *Handler) PatchCodexKey(c *gin.Context) {
if body.Value.ProxyURL != nil {
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
}
if body.Value.Models != nil {
entry.Models = append([]config.CodexModel(nil), (*body.Value.Models)...)
}
if body.Value.Headers != nil {
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
}
if body.Value.ExcludedModels != nil {
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
}
normalizeCodexKey(&entry)
h.cfg.CodexKey[targetIndex] = entry
h.cfg.SanitizeCodexKeys()
h.persist(c)
@@ -761,3 +762,29 @@ func normalizeClaudeKey(entry *config.ClaudeKey) {
}
entry.Models = normalized
}
func normalizeCodexKey(entry *config.CodexKey) {
if entry == nil {
return
}
entry.APIKey = strings.TrimSpace(entry.APIKey)
entry.Prefix = strings.TrimSpace(entry.Prefix)
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
entry.Headers = config.NormalizeHeaders(entry.Headers)
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
if len(entry.Models) == 0 {
return
}
normalized := make([]config.CodexModel, 0, len(entry.Models))
for i := range entry.Models {
model := entry.Models[i]
model.Name = strings.TrimSpace(model.Name)
model.Alias = strings.TrimSpace(model.Alias)
if model.Name == "" && model.Alias == "" {
continue
}
normalized = append(normalized, model)
}
entry.Models = normalized
}
@@ -10,7 +10,6 @@ import (
"time"
"github.com/gin-gonic/gin"
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
@@ -69,9 +68,6 @@ func (h *Handler) ImportCredential(c *gin.Context) {
var result importResult
switch provider {
case "iflow":
authSvc := iflowauth.NewIFlowAuth(h.cfg)
result = h.processIFlowCookie(ctx, authSvc, raw, lineNum)
case "openai", "claude", "gemini":
// Generic API Key import
result = h.processAPIKey(ctx, provider, raw, lineNum)
@@ -96,10 +92,13 @@ func (h *Handler) ImportCredential(c *gin.Context) {
})
}
// Re-using importResult from iflow_import.go if it's exported, otherwise redefined here for clarity in new file.
// Ideally, we'd refactor iflow_import.go to share types, but for now assuming it stays as is or we modify it.
// Since we are creating a new file, let's assume we might replace iflow_import with this generic one eventually.
// For this step, I will assume we are ADDING this handler alongside existing ones.
// importResult captures the result of importing a single credential line.
type importResult struct {
Line int `json:"line"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
SavedPath string `json:"saved_path,omitempty"`
}
// GenericTokenStorage is a simple map wrapper to satisfy TokenStorage interface
type GenericTokenStorage map[string]string
@@ -333,6 +333,15 @@ func (h *Handler) Middleware() gin.HandlerFunc {
return
}
}
// For localhost, also accept configured API keys (same keys that work for main API)
if cfg != nil {
for _, apiKey := range cfg.APIKeys {
if apiKey != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(apiKey)) == 1 {
c.Next()
return
}
}
}
}
if envSecret != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(envSecret)) == 1 {
+171
View File
@@ -0,0 +1,171 @@
package management
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
)
// GetHarnessFiles returns the list of harness files for a session.
// GET /v0/management/harness/files?session=...
func (h *Handler) GetHarnessFiles(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"files": []string{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
store := memory.NewFileStore(base)
files, err := store.ListHarnessFiles(session)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if files == nil {
files = []string{}
}
c.JSON(http.StatusOK, gin.H{"files": files})
}
// GetHarnessFile returns the content of a specific harness file.
// GET /v0/management/harness/file?session=...&filename=...
func (h *Handler) GetHarnessFile(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
filename := strings.TrimSpace(c.Query("filename"))
if filename == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing filename"})
return
}
store := memory.NewFileStore(base)
content := store.ReadHarnessFile(session, filename, 100000)
c.JSON(http.StatusOK, gin.H{"filename": filename, "content": content})
}
type putHarnessFileRequest struct {
Session string `json:"session"`
Filename string `json:"filename"`
Content string `json:"content"`
}
// PutHarnessFile creates or updates a harness file.
// PUT /v0/management/harness/file
// Body: {"session": "...", "filename": "...", "content": "..."}
func (h *Handler) PutHarnessFile(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req putHarnessFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if strings.TrimSpace(req.Session) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
if strings.TrimSpace(req.Filename) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing filename"})
return
}
store := memory.NewFileStore(base)
if err := store.WriteHarnessFile(req.Session, req.Filename, req.Content, 100000); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// ExportHarness returns all harness files for a session as JSON.
// GET /v0/management/harness/export?session=...
func (h *Handler) ExportHarness(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
store := memory.NewFileStore(base)
files, err := store.ListHarnessFiles(session)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
result := make(map[string]string, len(files))
for _, filename := range files {
content := store.ReadHarnessFile(session, filename, 100000)
result[filename] = content
}
c.JSON(http.StatusOK, gin.H{"session": session, "files": result})
}
type importHarnessRequest struct {
Session string `json:"session"`
Files map[string]string `json:"files"`
}
// ImportHarness imports harness files from JSON.
// POST /v0/management/harness/import
// Body: {"session": "...", "files": {"feature_list.json": "...", "claude-progress.txt": "..."}}
func (h *Handler) ImportHarness(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req importHarnessRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if strings.TrimSpace(req.Session) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
if len(req.Files) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
return
}
store := memory.NewFileStore(base)
var errors []string
imported := 0
for filename, content := range req.Files {
if strings.TrimSpace(filename) == "" {
continue
}
if err := store.WriteHarnessFile(req.Session, filename, content, 100000); err != nil {
errors = append(errors, filename+": "+err.Error())
continue
}
imported++
}
if len(errors) > 0 {
c.JSON(http.StatusInternalServerError, gin.H{
"status": "partial",
"imported": imported,
"errors": errors,
})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "imported": imported})
}
@@ -1,172 +0,0 @@
package management
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
"github.com/router-for-me/CLIProxyAPI/v6/internal/errors"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
// ImportIFlowCredential handles uploading a text file with iFlow cookies (one per line).
// Each cookie is authenticated and saved as a separate auth record.
func (h *Handler) ImportIFlowCredential(c *gin.Context) {
if h == nil || h.cfg == nil {
e := errors.New(http.StatusServiceUnavailable, "service_unavailable", "config unavailable", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
if h.cfg.AuthDir == "" {
e := errors.New(http.StatusServiceUnavailable, "config_error", "auth directory not configured", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
e := errors.New(http.StatusBadRequest, "invalid_request", "file required", err)
c.JSON(e.HTTPStatusCode, e)
return
}
file, err := fileHeader.Open()
if err != nil {
e := errors.New(http.StatusBadRequest, "file_error", fmt.Sprintf("failed to read file: %v", err), err)
c.JSON(e.HTTPStatusCode, e)
return
}
defer file.Close()
ctx := context.Background()
if reqCtx := c.Request.Context(); reqCtx != nil {
ctx = reqCtx
}
cookies, err := parseCookieLines(file)
if err != nil {
e := errors.New(http.StatusBadRequest, "parse_error", "failed to parse file", err)
c.JSON(e.HTTPStatusCode, e)
return
}
if len(cookies) == 0 {
e := errors.New(http.StatusBadRequest, "invalid_file", "no valid cookies found in file", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
authSvc := iflowauth.NewIFlowAuth(h.cfg)
var results []importResult
successCount := 0
for i, raw := range cookies {
lineNum := i + 1
result := h.processIFlowCookie(ctx, authSvc, raw, lineNum)
if result.Success {
successCount++
}
results = append(results, result)
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"total": len(cookies),
"success_count": successCount,
"failed_count": len(cookies) - successCount,
"results": results,
})
}
type importResult struct {
Line int `json:"line"`
Success bool `json:"success"`
Email string `json:"email,omitempty"`
SavedPath string `json:"saved_path,omitempty"`
Error string `json:"error,omitempty"`
}
func parseCookieLines(r io.Reader) ([]string, error) {
var cookies []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
cookies = append(cookies, line)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return cookies, nil
}
func (h *Handler) processIFlowCookie(ctx context.Context, authSvc *iflowauth.IFlowAuth, raw string, lineNum int) importResult {
cookieValue, errNormalize := iflowauth.NormalizeCookie(raw)
if errNormalize != nil {
return importResult{Line: lineNum, Success: false, Error: errNormalize.Error()}
}
// Check for duplicate BXAuth before authentication
bxAuth := iflowauth.ExtractBXAuth(cookieValue)
if existingFile, err := iflowauth.CheckDuplicateBXAuth(h.cfg.AuthDir, bxAuth); err != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to check duplicate"}
} else if existingFile != "" {
existingFileName := filepath.Base(existingFile)
return importResult{Line: lineNum, Success: false, Error: fmt.Sprintf("duplicate BXAuth found: %s", existingFileName)}
}
tokenData, errAuth := authSvc.AuthenticateWithCookie(ctx, cookieValue)
if errAuth != nil {
return importResult{Line: lineNum, Success: false, Error: errAuth.Error()}
}
tokenData.Cookie = cookieValue
tokenStorage := authSvc.CreateCookieTokenStorage(tokenData)
email := strings.TrimSpace(tokenStorage.Email)
if email == "" {
return importResult{Line: lineNum, Success: false, Error: "failed to extract email from token"}
}
fileName := iflowauth.SanitizeIFlowFileName(email)
if fileName == "" {
fileName = fmt.Sprintf("iflow-%d", time.Now().UnixMilli())
}
tokenStorage.Email = email
timestamp := time.Now().Unix()
record := &coreauth.Auth{
ID: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Provider: "iflow",
FileName: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Storage: tokenStorage,
Metadata: map[string]any{
"email": email,
"api_key": tokenStorage.APIKey,
"expired": tokenStorage.Expire,
"cookie": tokenStorage.Cookie,
"type": tokenStorage.Type,
"last_refresh": tokenStorage.LastRefresh,
},
Attributes: map[string]string{
"api_key": tokenStorage.APIKey,
},
}
savedPath, errSave := h.saveTokenRecord(ctx, record)
if errSave != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to save authentication tokens"}
}
return importResult{Line: lineNum, Success: true, Email: email, SavedPath: savedPath}
}
@@ -1,93 +0,0 @@
package management
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/stretchr/testify/assert"
)
func TestImportIFlowCredential_NoConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: nil}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "config unavailable")
}
func TestImportIFlowCredential_NoAuthDir(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "auth directory not configured")
}
func TestImportIFlowCredential_NoFile(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{AuthDir: "/tmp"}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req, _ := http.NewRequest("POST", "/import", nil)
c.Request = req
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "file required")
}
func TestImportIFlowCredential_EmptyFile(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{AuthDir: "/tmp"}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte(""))
writer.Close()
req, _ := http.NewRequest("POST", "/import", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
c.Request = req
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "no valid cookies found")
}
func TestParseCookieLines(t *testing.T) {
content := `
# Comment
cookie1
cookie2
`
reader := bytes.NewReader([]byte(content))
cookies, err := parseCookieLines(reader)
assert.NoError(t, err)
assert.Len(t, cookies, 2)
assert.Equal(t, "cookie1", cookies[0])
assert.Equal(t, "cookie2", cookies[1])
}
@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
)
// GetIntegrationsStatus returns the list of detected tools and their configuration status.
@@ -35,3 +36,45 @@ func (h *Handler) PostIntegrationConfigure(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "configured", "id": id})
}
// GetCLIAgents returns the list of detected CLI agents and IDEs.
func (h *Handler) GetCLIAgents(c *gin.Context) {
proxyURL := h.cfg.ProxyURL
if proxyURL == "" {
proxyURL = "http://localhost:8080"
}
agents := integrations.DetectCLIAgents(proxyURL)
c.JSON(http.StatusOK, gin.H{"agents": agents})
}
// PostCLIAgentConfigure configures a CLI agent to use the proxy.
func (h *Handler) PostCLIAgentConfigure(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
proxyURL := h.cfg.ProxyURL
if proxyURL == "" {
proxyURL = "http://localhost:8080"
}
if err := integrations.ConfigureCLIAgent(id, proxyURL); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "configured", "id": id})
}
// PostCLIAgentUnconfigure removes proxy configuration from a CLI agent.
func (h *Handler) PostCLIAgentUnconfigure(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
if err := integrations.UnconfigureCLIAgent(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "unconfigured", "id": id})
}
@@ -0,0 +1,95 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
// ModelMappingEntry represents a global model mapping for the API
type ModelMappingEntry struct {
From string `json:"from"`
To string `json:"to"`
Provider string `json:"provider,omitempty"`
Enabled bool `json:"enabled"`
}
// GetModelMappings returns the current global model mappings
func (h *Handler) GetModelMappings(c *gin.Context) {
if h.cfg == nil {
c.JSON(http.StatusOK, gin.H{"mappings": []any{}})
return
}
mappings := make([]ModelMappingEntry, 0, len(h.cfg.GlobalModelMappings))
for _, m := range h.cfg.GlobalModelMappings {
mappings = append(mappings, ModelMappingEntry{
From: m.From,
To: m.To,
Provider: m.Provider,
Enabled: m.IsEnabled(),
})
}
c.JSON(http.StatusOK, gin.H{"mappings": mappings})
}
// SetModelMappings replaces all global model mappings
func (h *Handler) SetModelMappings(c *gin.Context) {
var req struct {
Mappings []ModelMappingEntry `json:"mappings"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if h.cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config not loaded"})
return
}
// Convert to config type
newMappings := make([]config.GlobalModelMapping, 0, len(req.Mappings))
for _, m := range req.Mappings {
enabled := m.Enabled
newMappings = append(newMappings, config.GlobalModelMapping{
From: m.From,
To: m.To,
Provider: m.Provider,
Enabled: &enabled,
})
}
h.cfg.GlobalModelMappings = newMappings
// Try to save config if configPath is available
// Note: This requires the config path to be stored somewhere accessible
c.JSON(http.StatusOK, gin.H{"status": "ok", "count": len(newMappings)})
}
// TestModelMapping tests a model name against global mappings
func (h *Handler) TestModelMapping(c *gin.Context) {
model := c.Query("model")
provider := c.Query("provider")
if model == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing model parameter"})
return
}
if h.cfg == nil {
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": model, "matched": false})
return
}
mappedTo := h.cfg.LookupGlobalModelMapping(model, provider)
if mappedTo == "" {
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": model, "matched": false})
return
}
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": mappedTo, "matched": true})
}
@@ -230,8 +230,6 @@ func NormalizeOAuthProvider(provider string) (string, error) {
return "codex", nil
case "gemini", "google":
return "gemini", nil
case "iflow", "i-flow":
return "iflow", nil
case "antigravity", "anti-gravity":
return "antigravity", nil
case "qwen":
@@ -0,0 +1,16 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
)
// GetRequests returns the list of recent requests from the in-memory ring buffer.
func (h *Handler) GetRequests(c *gin.Context) {
requests := middleware.GetRequestMonitor()
c.JSON(http.StatusOK, gin.H{
"requests": requests,
})
}
+145
View File
@@ -0,0 +1,145 @@
package management
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/updates"
)
// updateState tracks the current update operation state.
type updateState struct {
mu sync.RWMutex
downloading bool
progress updates.DownloadProgress
downloadResult *updates.DownloadResult
lastError string
}
var currentUpdate = &updateState{}
func (h *Handler) GetUpdateInfo(c *gin.Context) {
info, err := updates.CheckForUpdates()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, info)
}
// GetUpdateStatus returns the current update download status.
func (h *Handler) GetUpdateStatus(c *gin.Context) {
currentUpdate.mu.RLock()
defer currentUpdate.mu.RUnlock()
c.JSON(http.StatusOK, gin.H{
"downloading": currentUpdate.downloading,
"progress": currentUpdate.progress,
"ready": currentUpdate.downloadResult != nil,
"error": currentUpdate.lastError,
})
}
// DownloadUpdate starts downloading an update.
func (h *Handler) DownloadUpdate(c *gin.Context) {
var req struct {
Version string `json:"version"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "version is required"})
return
}
currentUpdate.mu.Lock()
if currentUpdate.downloading {
currentUpdate.mu.Unlock()
c.JSON(http.StatusConflict, gin.H{"error": "download already in progress"})
return
}
currentUpdate.downloading = true
currentUpdate.progress = updates.DownloadProgress{}
currentUpdate.downloadResult = nil
currentUpdate.lastError = ""
currentUpdate.mu.Unlock()
// Start download in background
go func() {
result, err := updates.DownloadUpdate(req.Version, func(progress updates.DownloadProgress) {
currentUpdate.mu.Lock()
currentUpdate.progress = progress
currentUpdate.mu.Unlock()
})
currentUpdate.mu.Lock()
currentUpdate.downloading = false
if err != nil {
currentUpdate.lastError = err.Error()
} else {
currentUpdate.downloadResult = result
}
currentUpdate.mu.Unlock()
}()
c.JSON(http.StatusAccepted, gin.H{"message": "download started"})
}
// VerifyUpdate verifies the downloaded update.
func (h *Handler) VerifyUpdate(c *gin.Context) {
currentUpdate.mu.RLock()
result := currentUpdate.downloadResult
currentUpdate.mu.RUnlock()
if result == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "no download available to verify"})
return
}
verifyResult, err := updates.VerifyDownload(result)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, verifyResult)
}
// InstallUpdate installs the downloaded update.
func (h *Handler) InstallUpdate(c *gin.Context) {
currentUpdate.mu.RLock()
downloadResult := currentUpdate.downloadResult
currentUpdate.mu.RUnlock()
if downloadResult == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "no download available to install"})
return
}
// Verify before install
verifyResult, err := updates.VerifyDownload(downloadResult)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !verifyResult.Valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "verification failed: " + verifyResult.Message})
return
}
// Prepare the update (extract if needed)
executablePath, err := updates.PrepareInstall(downloadResult)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Install
installResult, err := updates.InstallUpdate(executablePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, installResult)
}
+64 -1
View File
@@ -1,20 +1,83 @@
package management
import (
"encoding/json"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
)
type usageExportPayload struct {
Version int `json:"version"`
ExportedAt time.Time `json:"exported_at"`
Usage usage.StatisticsSnapshot `json:"usage"`
}
type usageImportPayload struct {
Version int `json:"version"`
Usage usage.StatisticsSnapshot `json:"usage"`
}
// GetUsageStatistics returns the in-memory request statistics snapshot.
func (h *Handler) GetUsageStatistics(c *gin.Context) {
var snapshot usage.StatisticsSnapshot
if h != nil && h.usageStats != nil {
snapshot = h.usageStats.Snapshot()
}
usageStats := usage.ComputeUsageStats(snapshot)
c.JSON(http.StatusOK, gin.H{
"usage": snapshot,
"usage": usageStats,
"raw_snapshot": snapshot,
"failed_requests": snapshot.FailureCount,
})
}
// ExportUsageStatistics returns a complete usage snapshot for backup/migration.
func (h *Handler) ExportUsageStatistics(c *gin.Context) {
var snapshot usage.StatisticsSnapshot
if h != nil && h.usageStats != nil {
snapshot = h.usageStats.Snapshot()
}
c.JSON(http.StatusOK, usageExportPayload{
Version: 1,
ExportedAt: time.Now().UTC(),
Usage: snapshot,
})
}
// ImportUsageStatistics merges a previously exported usage snapshot into memory.
func (h *Handler) ImportUsageStatistics(c *gin.Context) {
if h == nil || h.usageStats == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "usage statistics unavailable"})
return
}
data, err := c.GetRawData()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read request body"})
return
}
var payload usageImportPayload
if err := json.Unmarshal(data, &payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"})
return
}
if payload.Version != 0 && payload.Version != 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported version"})
return
}
result := h.usageStats.MergeSnapshot(payload.Usage)
snapshot := h.usageStats.Snapshot()
c.JSON(http.StatusOK, gin.H{
"added": result.Added,
"skipped": result.Skipped,
"total_requests": snapshot.TotalRequests,
"failed_requests": snapshot.FailureCount,
})
}
@@ -0,0 +1,203 @@
// Package handlers provides HTTP handlers for the API server.
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
)
// TranslatorHandler provides HTTP handlers for translation-related endpoints.
type TranslatorHandler struct{}
// NewTranslatorHandler creates a new translator handler.
func NewTranslatorHandler() *TranslatorHandler {
return &TranslatorHandler{}
}
// TranslationsMatrixResponse represents the response for the translations matrix endpoint.
type TranslationsMatrixResponse struct {
Matrix map[string][]string `json:"matrix"`
Formats []string `json:"formats"`
Total int `json:"total_translations"`
Details []translator.TranslationInfo `json:"details,omitempty"`
}
// GetTranslationsMatrix returns the full compatibility matrix of supported translations.
// GET /v1/translations
func (h *TranslatorHandler) GetTranslationsMatrix(c *gin.Context) {
matrix := translator.GetCompatibilityMatrix()
formats := translator.GetSupportedFormats()
translations := translator.GetAllTranslations()
// Convert formats to strings
formatStrings := make([]string, len(formats))
for i, f := range formats {
formatStrings[i] = f.String()
}
// Count total translations
total := 0
for _, targets := range matrix {
total += len(targets)
}
// Check if detailed info is requested
includeDetails := c.Query("details") == "true"
response := TranslationsMatrixResponse{
Matrix: matrix,
Formats: formatStrings,
Total: total,
}
if includeDetails {
response.Details = translations
}
c.JSON(http.StatusOK, response)
}
// CheckTranslationResponse represents the response for checking a specific translation.
type CheckTranslationResponse struct {
Supported bool `json:"supported"`
Fallback bool `json:"fallback"`
From string `json:"from"`
To string `json:"to"`
Info *translator.TranslationInfo `json:"info,omitempty"`
Alternatives []string `json:"alternatives,omitempty"`
}
// CheckTranslation checks if a specific translation path is supported.
// GET /v1/translations/check?from=X&to=Y
func (h *TranslatorHandler) CheckTranslation(c *gin.Context) {
from := c.Query("from")
to := c.Query("to")
if from == "" || to == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "missing required query parameters",
"details": "both 'from' and 'to' query parameters are required",
})
return
}
fromFormat := translator.FromString(from)
toFormat := translator.FromString(to)
supported := translator.IsTranslationSupported(fromFormat, toFormat)
info := translator.GetTranslationInfo(fromFormat, toFormat)
response := CheckTranslationResponse{
Supported: supported,
Fallback: false,
From: from,
To: to,
}
// Include detailed info if translation exists
if supported {
response.Info = info
} else {
// Check for potential fallback paths or alternatives
matrix := translator.GetCompatibilityMatrix()
if targets, exists := matrix[from]; exists {
response.Alternatives = targets
}
// Mark as fallback if the request would pass through unchanged
// (same format translation is always supported as a no-op)
if from == to {
response.Fallback = true
response.Supported = true
}
}
c.JSON(http.StatusOK, response)
}
// GetTranslationDocs returns markdown documentation for all translations.
// GET /v1/translations/docs
func (h *TranslatorHandler) GetTranslationDocs(c *gin.Context) {
format := c.Query("format")
switch format {
case "mermaid":
c.Header("Content-Type", "text/plain; charset=utf-8")
c.String(http.StatusOK, translator.GenerateMermaidDiagram())
case "summary":
c.Header("Content-Type", "text/plain; charset=utf-8")
c.String(http.StatusOK, translator.GenerateTranslationSummary())
default:
// Default to markdown
c.Header("Content-Type", "text/markdown; charset=utf-8")
c.String(http.StatusOK, translator.GenerateMarkdownDocs())
}
}
// ScoreTranslationRequest represents the request body for scoring a translation.
type ScoreTranslationRequest struct {
From string `json:"from" binding:"required"`
To string `json:"to" binding:"required"`
Before string `json:"before" binding:"required"`
After string `json:"after" binding:"required"`
}
// ScoreTranslation analyzes the quality of a translation.
// POST /v1/translations/score
func (h *TranslatorHandler) ScoreTranslation(c *gin.Context) {
var req ScoreTranslationRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "invalid request body",
"details": err.Error(),
})
return
}
fromFormat := translator.FromString(req.From)
toFormat := translator.FromString(req.To)
report := translator.ScoreTranslation(
fromFormat,
toFormat,
[]byte(req.Before),
[]byte(req.After),
)
c.JSON(http.StatusOK, report)
}
// CompareStructuresRequest represents the request body for comparing JSON structures.
type CompareStructuresRequest struct {
Before string `json:"before" binding:"required"`
After string `json:"after" binding:"required"`
}
// CompareStructures provides detailed comparison of two JSON structures.
// POST /v1/translations/compare
func (h *TranslatorHandler) CompareStructures(c *gin.Context) {
var req CompareStructuresRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "invalid request body",
"details": err.Error(),
})
return
}
comparison, err := translator.CompareJSONStructures(
[]byte(req.Before),
[]byte(req.After),
)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "failed to compare structures",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, comparison)
}
@@ -0,0 +1,414 @@
package handlers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
)
func init() {
gin.SetMode(gin.TestMode)
}
func setupTestRouter() *gin.Engine {
router := gin.New()
handler := NewTranslatorHandler()
v1 := router.Group("/v1")
{
v1.GET("/translations", handler.GetTranslationsMatrix)
v1.GET("/translations/check", handler.CheckTranslation)
v1.GET("/translations/docs", handler.GetTranslationDocs)
v1.POST("/translations/score", handler.ScoreTranslation)
v1.POST("/translations/compare", handler.CompareStructures)
}
return router
}
func TestGetTranslationsMatrix(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var response TranslationsMatrixResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response.Matrix == nil {
t.Error("Matrix should not be nil")
}
if response.Formats == nil {
t.Error("Formats should not be nil")
}
}
func TestGetTranslationsMatrix_WithDetails(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations?details=true", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var response TranslationsMatrixResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
// When details=true, Details should be populated
// (may be empty if no translations registered, but should be non-nil conceptually)
}
func TestCheckTranslation_Supported(t *testing.T) {
router := setupTestRouter()
// Register a test translator
translator.Register(translator.FormatOpenAI, translator.FormatClaude, func(model string, data []byte, stream bool) []byte {
return data
}, translator.ResponseTransform{})
defer translator.Unregister(translator.FormatOpenAI, translator.FormatClaude)
req, _ := http.NewRequest("GET", "/v1/translations/check?from=openai&to=claude", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var response CheckTranslationResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if !response.Supported {
t.Error("Translation should be supported")
}
if response.From != "openai" {
t.Errorf("From = %s, want openai", response.From)
}
if response.To != "claude" {
t.Errorf("To = %s, want claude", response.To)
}
}
func TestCheckTranslation_NotSupported(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations/check?from=unknown&to=unknown2", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var response CheckTranslationResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if response.Supported {
t.Error("Translation should not be supported for unknown formats")
}
}
func TestCheckTranslation_MissingParams(t *testing.T) {
router := setupTestRouter()
tests := []struct {
name string
url string
}{
{"missing both", "/v1/translations/check"},
{"missing to", "/v1/translations/check?from=openai"},
{"missing from", "/v1/translations/check?to=claude"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", tt.url, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status %d, got %d", http.StatusBadRequest, w.Code)
}
})
}
}
func TestCheckTranslation_SameFormat(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations/check?from=openai&to=openai", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var response CheckTranslationResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
// Same format translation is a fallback/no-op
if !response.Fallback {
t.Error("Same format should be marked as fallback")
}
if !response.Supported {
t.Error("Same format should be supported")
}
}
func TestGetTranslationDocs_Markdown(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations/docs", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "text/markdown; charset=utf-8" {
t.Errorf("Content-Type = %s, want text/markdown; charset=utf-8", contentType)
}
body := w.Body.String()
if body == "" {
t.Error("Response body should not be empty")
}
}
func TestGetTranslationDocs_Mermaid(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations/docs?format=mermaid", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "text/plain; charset=utf-8" {
t.Errorf("Content-Type = %s, want text/plain; charset=utf-8", contentType)
}
body := w.Body.String()
if !containsString(body, "mermaid") {
t.Error("Response should contain mermaid diagram")
}
}
func TestGetTranslationDocs_Summary(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("GET", "/v1/translations/docs?format=summary", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "text/plain; charset=utf-8" {
t.Errorf("Content-Type = %s, want text/plain; charset=utf-8", contentType)
}
body := w.Body.String()
if !containsString(body, "Summary") {
t.Error("Response should contain summary")
}
}
func TestScoreTranslation(t *testing.T) {
router := setupTestRouter()
requestBody := ScoreTranslationRequest{
From: "openai",
To: "claude",
Before: `{"model": "gpt-4", "messages": []}`,
After: `{"model": "gpt-4", "messages": []}`,
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "/v1/translations/score", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var report translator.QualityReport
if err := json.Unmarshal(w.Body.Bytes(), &report); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
// Perfect match should have high score
if report.Score < 0.9 {
t.Errorf("Score = %v, expected >= 0.9 for identical payloads", report.Score)
}
}
func TestScoreTranslation_InvalidBody(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("POST", "/v1/translations/score", bytes.NewBufferString("invalid json"))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status %d, got %d", http.StatusBadRequest, w.Code)
}
}
func TestScoreTranslation_MissingFields(t *testing.T) {
router := setupTestRouter()
// Missing required fields
requestBody := map[string]string{
"from": "openai",
// missing to, before, after
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "/v1/translations/score", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status %d, got %d", http.StatusBadRequest, w.Code)
}
}
func TestCompareStructures(t *testing.T) {
router := setupTestRouter()
requestBody := CompareStructuresRequest{
Before: `{"a": 1, "b": 2}`,
After: `{"a": 1, "c": 3}`,
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "/v1/translations/compare", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var comparison translator.StructureComparison
if err := json.Unmarshal(w.Body.Bytes(), &comparison); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if comparison.SourceType != "object" {
t.Errorf("SourceType = %s, want object", comparison.SourceType)
}
if comparison.TargetType != "object" {
t.Errorf("TargetType = %s, want object", comparison.TargetType)
}
if len(comparison.Diffs) == 0 {
t.Error("Should detect differences between the structures")
}
}
func TestCompareStructures_InvalidBody(t *testing.T) {
router := setupTestRouter()
req, _ := http.NewRequest("POST", "/v1/translations/compare", bytes.NewBufferString("invalid json"))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status %d, got %d", http.StatusBadRequest, w.Code)
}
}
func TestCompareStructures_InvalidJSON(t *testing.T) {
router := setupTestRouter()
requestBody := CompareStructuresRequest{
Before: `{invalid}`,
After: `{"valid": true}`,
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "/v1/translations/compare", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status %d, got %d for invalid JSON in payload", http.StatusBadRequest, w.Code)
}
}
func TestCompareStructures_IdenticalStructures(t *testing.T) {
router := setupTestRouter()
requestBody := CompareStructuresRequest{
Before: `{"a": 1, "b": 2}`,
After: `{"a": 1, "b": 2}`,
}
body, _ := json.Marshal(requestBody)
req, _ := http.NewRequest("POST", "/v1/translations/compare", bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, w.Code)
}
var comparison translator.StructureComparison
if err := json.Unmarshal(w.Body.Bytes(), &comparison); err != nil {
t.Fatalf("Failed to parse response: %v", err)
}
if len(comparison.Diffs) != 0 {
t.Errorf("Identical structures should have no diffs, got %d", len(comparison.Diffs))
}
}
// Helper function
func containsString(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
+244 -49
View File
@@ -8,12 +8,33 @@ import (
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
var (
harnessEnabledOnce sync.Once
harnessEnabled bool
)
// isHarnessEnabled checks if the agentic harness is enabled via environment variable.
// Defaults to true if CLIPROXY_HARNESS_ENABLED is not set or is "true"/"1".
func isHarnessEnabled() bool {
harnessEnabledOnce.Do(func() {
val := os.Getenv("CLIPROXY_HARNESS_ENABLED")
if val == "" {
harnessEnabled = true
return
}
val = strings.ToLower(strings.TrimSpace(val))
harnessEnabled = val == "true" || val == "1" || val == "yes"
})
return harnessEnabled
}
const (
// Initializer prompt: forces the agent to set up the environment.
harnessInitializerPrompt = `
@@ -21,28 +42,85 @@ const (
You are the **Initializer Agent** in a Long-Running Agent Harness.
Your ONLY goal is to set up the project environment for future Coding Agents.
**CRITICAL INSTRUCTIONS**:
1. **Analyze the User's Request**: Understand what feature or app needs to be built.
2. **Create 'feature_list.json'**:
- Write a JSON file listing ALL features/requirements as separate items.
- Mark them all as "passes": false.
- Format:
Request: "Build a todo app"
File Content:
[
{ "category": "core", "description": "User can add a todo", "steps": ["Open app", "Enter text", "Press enter", "See new item"], "passes": false },
{ "category": "core", "description": "User can delete a todo", "steps": ["Open app", "Click delete", "Item removed"], "passes": false }
]
3. **Create 'claude-progress.txt'**:
- Create this file with a header "## Progress Log".
- Add an initial entry: "- [Initializer] Environment setup started."
4. **Create 'init.sh' (Optional)**:
- If a dev server is needed, create a script to start it (e.g., 'npm run dev').
5. **Initial Commit**:
- Initialize git if not present.
- Commit these foundational files.
## CRITICAL: YOU DO NOT IMPLEMENT FEATURES
Your job is ONLY to scaffold the harness files. Do NOT write any application code.
Do NOT create components, pages, or business logic. Only create the harness metadata files.
**DO NOT** start implementing features yourself. Your job is ONLY to scaffold the harness.
## INSTRUCTIONS
### 1. Analyze the User's Request
Understand what feature or app needs to be built. Break it down into discrete, testable features.
### 2. Create 'feature_list.json'
Write a JSON file listing ALL features/requirements as separate items.
**Required Format:**
{
"features": [
{
"id": "feat-001",
"category": "core",
"description": "User can add a todo item",
"steps": [
"Open the application",
"Enter text in the input field",
"Press Enter or click Add button",
"Verify new item appears in the list"
],
"passes": false,
"priority": 1
},
{
"id": "feat-002",
"category": "core",
"description": "User can delete a todo item",
"steps": [
"Open the application with existing items",
"Click the delete button on an item",
"Verify item is removed from the list"
],
"passes": false,
"priority": 2
}
]
}
**Field Descriptions:**
- id: Unique identifier (feat-XXX format)
- category: "core", "enhancement", "ui", "integration", etc.
- description: Clear, testable user-facing behavior
- steps: Exact steps to verify this feature works
- passes: Always false initially
- priority: Lower number = higher priority (implement first)
### 3. Create 'claude-progress.txt'
Create this file with structured session logging:
## Progress Log
### Session: YYYY-MM-DD HH:MM
- [Initializer] Environment setup started.
- [Initializer] Created feature_list.json with N features.
- [Initializer] Created init.sh for development server.
### 4. Create 'init.sh' (REQUIRED for web apps)
For ANY web application, you MUST create init.sh:
#!/bin/bash
# Start the development server
npm install
npm run dev &
sleep 5
echo "Dev server started at http://localhost:3000"
Make it executable and ensure it handles common setup tasks.
### 5. Initial Commit
- Initialize git if not present.
- Commit these foundational files with message: "chore: initialize agent harness"
## REMINDER
You are ONLY scaffolding. The Coding Agent will implement features in future turns.
Do NOT write application code. Do NOT create UI components. ONLY create the harness files.
`
// Coding prompt: forces the agent to work incrementally.
@@ -51,30 +129,61 @@ Your ONLY goal is to set up the project environment for future Coding Agents.
You are a **Coding Agent** in a Long-Running Agent Harness.
Your goal is to make **incremental progress** on the project.
**WORKFLOW**:
1. **Read Context**:
- Read 'claude-progress.txt' to see what was done last.
- Read 'feature_list.json' to see what is missing.
- Read recent git log to understand recent changes.
- If 'init.sh' exists, run it to start the dev server.
- Run a basic end-to-end sanity check before new work.
2. **Pick ONE Task**:
- Choose the highest-priority failing feature from 'feature_list.json'.
- Announce your plan.
3. **Implement & Verify**:
- Write code for that ONE feature.
- Verify it works end-to-end (tests or browser check).
4. **Update State**:
- Update 'feature_list.json': set "passes": true for the completed feature.
- Append to 'claude-progress.txt': "- [Coding] Implemented <feature>."
5. **Commit**:
- Git commit your changes.
## STEP 1: GET BEARINGS (MANDATORY - DO THIS FIRST)
Before ANY coding, you MUST execute these commands in order:
**RESTRICTIONS**:
- Do NOT try to finish the whole project in one turn.
- Do NOT leave the code in a broken state.
- Always update the harness files ('feature_list.json', 'claude-progress.txt') before stopping.
- Do NOT edit 'feature_list.json' except toggling a feature's "passes" field after verified testing.
1. pwd # Know where you are
2. git log --oneline -5 # See recent changes
3. cat claude-progress.txt # Read what was done before
4. cat feature_list.json # See all features and their status
5. ./init.sh # Start dev server if it exists
Do NOT skip this step. Do NOT assume you know the project state.
## STEP 2: SANITY CHECK (MANDATORY)
Before implementing anything new:
- Verify existing features still work
- Check for any regressions from previous changes
- If something is broken, FIX IT FIRST before new work
## STEP 3: PICK ONE TASK
- Find the highest-priority feature where "passes": false
- Announce: "I will implement: [feature description]"
- Do NOT pick multiple features
## STEP 4: IMPLEMENT & VERIFY
- Write code for that ONE feature only
- You MUST verify it works before marking complete
- Verification methods (in order of preference):
1. **Run tests**: Execute unit/integration test suites
2. **Build check**: Ensure the project compiles without errors
3. **Manual verification**: Test the feature manually if automated tests unavailable
**VERIFICATION IS NOT OPTIONAL.** You must ACTUALLY TEST the feature.
Do NOT mark a feature as passing based on "the code looks correct."
## STEP 5: UPDATE STATE
After VERIFIED implementation:
1. Update feature_list.json:
- Set "passes": true ONLY for features you have ACTUALLY VERIFIED
2. Append to claude-progress.txt:
- [Coding] Implemented <feature id>: <description>. Verified via <method>.
Example:
- [Coding] Implemented feat-003: User can mark todo complete. Verified via unit tests.
## STEP 6: COMMIT
- Git commit with descriptive message
- Include feature ID in commit message
## RESTRICTIONS
- Do NOT try to finish the whole project in one turn
- Do NOT leave the code in a broken state
- Do NOT mark features as "passes": true without ACTUAL verification
- Do NOT edit feature_list.json except to toggle "passes" after verified testing
- ALWAYS update harness files before stopping
`
)
@@ -87,6 +196,12 @@ func AgenticHarnessMiddleware() gin.HandlerFunc {
// If rootDir is empty, the current working directory is used.
func AgenticHarnessMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
return func(c *gin.Context) {
// Check if harness is enabled via environment variable
if !isHarnessEnabled() {
c.Next()
return
}
req := c.Request
if req == nil || req.Method != http.MethodPost {
c.Next()
@@ -116,8 +231,8 @@ func AgenticHarnessMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
// 3. Detect State
// We look for evidence that the harness is already active (features/progress files).
// We also check conversation length.
state := detectHarnessState(body, rootDir)
// We also check conversation length and session-based storage.
state := detectHarnessState(body, c, rootDir)
// 4. Inject Prompt
var promptToInject string
@@ -146,7 +261,72 @@ func AgenticHarnessMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
}
}
func detectHarnessState(body []byte, rootDir string) string {
// extractSessionKeyFromContext extracts session key from request headers.
func extractSessionKeyFromContext(c *gin.Context) string {
if v := c.GetHeader("X-CLIProxyAPI-Session"); v != "" {
return v
}
if v := c.GetHeader("X-Session-Id"); v != "" {
return v
}
return ""
}
// extractSessionKeyFromBody extracts session key from request body JSON fields.
func extractSessionKeyFromBody(body []byte) string {
if v := gjson.GetBytes(body, "prompt_cache_key"); v.Exists() && v.Type == gjson.String {
return v.String()
}
if v := gjson.GetBytes(body, "metadata.session_id"); v.Exists() && v.Type == gjson.String {
return v.String()
}
if v := gjson.GetBytes(body, "session_id"); v.Exists() && v.Type == gjson.String {
return v.String()
}
return ""
}
// memoryBaseDirForHarness returns the base directory for memory/session storage.
func memoryBaseDirForHarness() string {
if v := os.Getenv("CLIPROXY_MEMORY_DIR"); v != "" {
return v
}
// Try default locations
if home, err := os.UserHomeDir(); err == nil {
return filepath.Join(home, ".proxypilot", "memory")
}
return filepath.Join(".", ".proxypilot", "memory")
}
// harnessFileVariations lists possible file name variations for harness files.
var harnessProgressFileVariations = []string{
"claude-progress.txt",
"claude-progress",
"progress.txt",
}
var harnessFeatureFileVariations = []string{
"feature_list.json",
"feature_list",
"features.json",
}
// checkHarnessFilesExist checks if any harness files exist in the given directory.
func checkHarnessFilesExist(dir string) bool {
for _, f := range harnessProgressFileVariations {
if fileExists(dir, f) {
return true
}
}
for _, f := range harnessFeatureFileVariations {
if fileExists(dir, f) {
return true
}
}
return false
}
func detectHarnessState(body []byte, c *gin.Context, rootDir string) string {
// Simple heuristic:
// If the conversation contains references to "claude-progress.txt" or "feature_list.json",
// it's likely already in the harness flow -> CODING.
@@ -157,8 +337,23 @@ func detectHarnessState(body []byte, rootDir string) string {
return "CODING"
}
// Prefer filesystem truth when available.
if fileExists(rootDir, "claude-progress.txt") || fileExists(rootDir, "feature_list.json") {
// Try to get session key from context headers first, then from body
sessionKey := extractSessionKeyFromContext(c)
if sessionKey == "" {
sessionKey = extractSessionKeyFromBody(body)
}
// Check session-based storage for harness files
if sessionKey != "" {
memoryDir := memoryBaseDirForHarness()
sessionHarnessDir := filepath.Join(memoryDir, "sessions", sessionKey, "harness")
if checkHarnessFilesExist(sessionHarnessDir) {
return "CODING"
}
}
// Prefer filesystem truth when available (check rootDir with file variations).
if checkHarnessFilesExist(rootDir) {
return "CODING"
}
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
@@ -182,3 +183,35 @@ func TestAgenticHarnessMiddleware_ResponsesAPI(t *testing.T) {
})
}
}
func TestAgenticHarnessMiddleware_SessionStorage(t *testing.T) {
gin.SetMode(gin.TestMode)
// Create temp memory directory
tmpDir, err := os.MkdirTemp("", "harness-session-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
os.Setenv("CLIPROXY_MEMORY_DIR", tmpDir)
defer os.Unsetenv("CLIPROXY_MEMORY_DIR")
handler := AgenticHarnessMiddleware()
// First request with session header
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := `{"model":"gpt-4","messages":[{"role":"user","content":"hello"}]}`
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("X-CLIProxyAPI-Session", "test-session-123")
c.Request.Header.Set("Content-Type", "application/json")
handler(c)
// Verify session directory was considered
if c.Writer.Header().Get("X-ProxyPilot-Harness-Mode") == "" {
t.Error("Expected harness mode header to be set")
}
}
+274 -3
View File
@@ -18,6 +18,7 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/embeddings"
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/internal/runtime/executor"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
@@ -134,10 +135,56 @@ func agenticMemoryStore() memory.Store {
}
}
memStore = memory.NewFileStore(base)
// Initialize summarizer with default config (uses regex fallback until executor is set)
if agenticLLMSummaryEnabled() {
if fs, ok := memStore.(*memory.FileStore); ok {
config := memory.DefaultSummarizerConfig()
// Start with NoOp executor - will fall back to regex
// Call SetSummarizerExecutor() later with a real executor to enable LLM summarization
summarizer := memory.NewSummarizer(config, memory.NewNoOpSummarizerExecutor())
fs.SetSummarizer(summarizer)
}
}
})
return memStore
}
// SetSummarizerExecutor configures the LLM executor for context summarization.
// Call this from server initialization with the auth manager to enable full LLM summarization.
// Example: middleware.SetSummarizerExecutor(memory.NewPipelineSummarizerExecutor(authManager, providers))
func SetSummarizerExecutor(executor memory.SummarizerExecutor) {
store := agenticMemoryStore()
if store == nil {
return
}
fs, ok := store.(*memory.FileStore)
if !ok || fs == nil {
return
}
summarizer := fs.GetSummarizer()
if summarizer == nil {
config := memory.DefaultSummarizerConfig()
summarizer = memory.NewSummarizer(config, executor)
fs.SetSummarizer(summarizer)
} else {
// Replace the existing summarizer with one that has the real executor
config := memory.DefaultSummarizerConfig()
fs.SetSummarizer(memory.NewSummarizer(config, executor))
}
}
// InitSummarizerWithAuthManager configures LLM-based summarization using the core auth manager.
// Call this after the auth manager is initialized to enable Factory.ai-style context compression.
func InitSummarizerWithAuthManager(manager memory.CoreManagerExecutor, providers []string) {
if manager == nil {
return
}
adapter := memory.NewManagerAuthAdapter(manager)
executor := memory.NewPipelineSummarizerExecutor(adapter, providers)
SetSummarizerExecutor(executor)
}
func agenticSemanticEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_ENABLED")); v != "" {
if strings.EqualFold(v, "0") || strings.EqualFold(v, "false") || strings.EqualFold(v, "off") || strings.EqualFold(v, "no") {
@@ -400,6 +447,176 @@ func agenticAnchorSummaryMaxChars() int {
return 14_000
}
// agenticCompressionThreshold returns the context usage ratio at which to trigger LLM compression.
// Default: 0.75 (75% of context window)
func agenticCompressionThreshold() float64 {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_COMPRESSION_THRESHOLD")); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 && f < 1 {
return f
}
}
return 0.75
}
// agenticLLMSummaryEnabled returns whether LLM-based summarization is enabled.
// Default: true
func agenticLLMSummaryEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_LLM_SUMMARY_ENABLED")); v != "" {
return strings.EqualFold(v, "1") || strings.EqualFold(v, "true") || strings.EqualFold(v, "on")
}
return true
}
// getModelContextWindow returns the context window size for a model.
func getModelContextWindow(model string) int {
// Try registry first
info := registry.GetGlobalRegistry().GetModelInfo(model)
if info != nil && info.ContextLength > 0 {
return info.ContextLength
}
// Fallback based on model name patterns
lowerModel := strings.ToLower(model)
switch {
case strings.Contains(lowerModel, "claude-3.5"), strings.Contains(lowerModel, "claude-3-5"):
return 200000
case strings.Contains(lowerModel, "claude-3"):
return 200000
case strings.Contains(lowerModel, "claude"):
return 100000
case strings.Contains(lowerModel, "gpt-4-turbo"), strings.Contains(lowerModel, "gpt-4o"):
return 128000
case strings.Contains(lowerModel, "gpt-4"):
return 8192
case strings.Contains(lowerModel, "gpt-3.5"):
return 16384
case strings.Contains(lowerModel, "gemini"):
return 1000000
case strings.Contains(lowerModel, "o1"), strings.Contains(lowerModel, "o3"):
return 200000
default:
return 100000
}
}
// agenticTokenAwareEnabled returns whether token-aware compression is enabled.
// Default: true
func agenticTokenAwareEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_TOKEN_AWARE_ENABLED")); v != "" {
return strings.EqualFold(v, "1") || strings.EqualFold(v, "true") || strings.EqualFold(v, "on")
}
return true
}
// agenticReserveTokens returns the number of tokens to reserve for model output.
// Default: 8192 (reasonable output buffer)
func agenticReserveTokens() int {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_RESERVE_TOKENS")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return 8192
}
// tokenAwareCompressionResult contains the result of token-aware analysis
type tokenAwareCompressionResult struct {
ShouldTrim bool // Whether trimming is needed
CurrentTokens int64 // Estimated current token count
ContextWindow int // Model's context window
TargetTokens int64 // Target token count after trimming
TargetMaxBytes int // Approximate bytes to achieve target tokens
Model string // The model name
}
// analyzeTokenBudget checks if the request exceeds the token threshold and calculates trimming targets.
// Returns whether trimming is needed and the target byte limit.
func analyzeTokenBudget(body []byte) *tokenAwareCompressionResult {
result := &tokenAwareCompressionResult{
ShouldTrim: false,
TargetMaxBytes: agenticMaxBodyBytes(), // Default fallback
}
if !agenticTokenAwareEnabled() {
return result
}
model := gjson.GetBytes(body, "model").String()
if model == "" {
return result
}
result.Model = model
// Get context window for this model
contextWindow := getModelContextWindow(model)
result.ContextWindow = contextWindow
// Estimate current token count
currentTokens, err := executor.EstimateRequestTokens(model, body)
if err != nil {
// Fallback to byte-based heuristic: ~4 chars per token
currentTokens = int64(len(body) / 4)
}
result.CurrentTokens = currentTokens
// Reserve tokens for output
reserveTokens := agenticReserveTokens()
availableContext := contextWindow - reserveTokens
if availableContext < 1000 {
availableContext = contextWindow / 2 // At least half for input
}
// Check against threshold
threshold := agenticCompressionThreshold()
maxInputTokens := int64(float64(availableContext) * threshold)
if currentTokens <= maxInputTokens {
// Under threshold, no trimming needed
result.ShouldTrim = false
return result
}
// Calculate target tokens (aim for 70% of threshold to give buffer)
targetRatio := threshold * 0.9 // Slightly under threshold
targetTokens := int64(float64(availableContext) * targetRatio)
result.TargetTokens = targetTokens
result.ShouldTrim = true
// Convert target tokens to approximate byte limit
// Use ~4 bytes per token as heuristic, but be conservative
targetBytes := int(targetTokens * 4)
// Clamp to reasonable bounds
minBytes := 32 * 1024 // 32KB minimum
if targetBytes < minBytes {
targetBytes = minBytes
}
// Don't exceed the configured max
maxBytes := agenticMaxBodyBytes()
if targetBytes > maxBytes {
targetBytes = maxBytes
}
result.TargetMaxBytes = targetBytes
return result
}
// getTokenAwareMaxBytes returns the maximum body size based on token analysis.
// This is more accurate than the byte-based heuristic in agenticMaxBodyBytesForModel.
func getTokenAwareMaxBytes(body []byte) int {
if !agenticTokenAwareEnabled() {
return agenticMaxBodyBytesForModel(body)
}
result := analyzeTokenBudget(body)
if result.ShouldTrim {
return result.TargetMaxBytes
}
// Not over threshold, but still apply model-specific limits
return agenticMaxBodyBytesForModel(body)
}
func allowMemoryWrite(session string) bool {
limit := agenticMemoryMaxWritesPerMin()
if limit <= 0 || session == "" {
@@ -523,7 +740,31 @@ func CodexPromptBudgetMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
}
originalLen := len(body)
maxBytes := agenticMaxBodyBytesForModel(body)
// Token-aware compression: analyze token budget before byte-based check
tokenAnalysis := analyzeTokenBudget(body)
maxBytes := tokenAnalysis.TargetMaxBytes
// If token analysis didn't trigger, fall back to byte-based model limit
if !tokenAnalysis.ShouldTrim {
maxBytes = agenticMaxBodyBytesForModel(body)
}
// Add diagnostic headers for localhost debugging
if c != nil {
ip := c.ClientIP()
if ip == "127.0.0.1" || ip == "::1" {
if tokenAnalysis.Model != "" {
c.Header("X-ProxyPilot-Model", tokenAnalysis.Model)
c.Header("X-ProxyPilot-Context-Window", strconv.Itoa(tokenAnalysis.ContextWindow))
c.Header("X-ProxyPilot-Current-Tokens", strconv.FormatInt(tokenAnalysis.CurrentTokens, 10))
if tokenAnalysis.ShouldTrim {
c.Header("X-ProxyPilot-Token-Triggered", "true")
c.Header("X-ProxyPilot-Target-Tokens", strconv.FormatInt(tokenAnalysis.TargetTokens, 10))
}
}
}
}
// Session-scoped state (pinned + anchor + TODO + spec) is injected as append-only
// scaffolding when enabled. This preserves prompt-cache friendliness.
@@ -533,7 +774,9 @@ func CodexPromptBudgetMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
originalLen = len(body)
}
if originalLen <= maxBytes {
// Proactive compression: trim if over token threshold OR over byte limit
needsTrim := tokenAnalysis.ShouldTrim || originalLen > maxBytes
if !needsTrim {
req.Body = io.NopCloser(bytes.NewReader(body))
req.ContentLength = int64(originalLen)
req.Header.Set("Content-Length", strconv.Itoa(originalLen))
@@ -1349,7 +1592,13 @@ func agenticStoreAndInjectMemory(c *gin.Context, req *http.Request, session stri
_ = fs.WritePinned(session, pinned, 8000)
}
if len(res.Dropped) > 0 {
_ = agenticUpdateAnchoredSummary(fs, session, res.Dropped, pinned, res.Query)
if agenticLLMSummaryEnabled() {
model := gjson.GetBytes(res.Body, "model").String()
ctx := c.Request.Context()
_ = agenticUpdateAnchoredSummaryWithLLM(ctx, model, fs, session, res.Dropped, pinned, res.Query)
} else {
_ = agenticUpdateAnchoredSummary(fs, session, res.Dropped, pinned, res.Query)
}
}
if agenticSemanticEnabled() && len(res.Dropped) > 0 && !fs.IsSemanticDisabled(session) {
ns := semanticNamespace(req, res.Body, session)
@@ -1410,6 +1659,28 @@ func agenticUpdateAnchoredSummary(fs *memory.FileStore, session string, dropped
return fs.WriteSummary(session, next, agenticAnchorSummaryMaxChars())
}
// agenticUpdateAnchoredSummaryWithLLM updates the anchored summary using LLM.
func agenticUpdateAnchoredSummaryWithLLM(ctx context.Context, model string, fs *memory.FileStore, session string, dropped []memory.Event, pinned string, latestIntent string) error {
if fs == nil || session == "" {
return nil
}
summarizer := fs.GetSummarizer()
if summarizer == nil {
// Fall back to regex-based
return agenticUpdateAnchoredSummary(fs, session, dropped, pinned, latestIntent)
}
prev := fs.ReadSummary(session, agenticAnchorSummaryMaxChars())
next := memory.BuildAnchoredSummaryWithLLM(ctx, model, prev, dropped, latestIntent, summarizer)
if strings.TrimSpace(next) == "" {
return nil
}
if agenticAnchorAppendOnly() {
return fs.SetAnchorSummary(session, next, agenticAnchorSummaryMaxChars())
}
return fs.WriteSummary(session, next, agenticAnchorSummaryMaxChars())
}
func agenticMaybePruneMemory() {
maxAge := agenticMemoryMaxAgeDays()
maxSessions := agenticMemoryMaxSessions()
@@ -8,12 +8,41 @@ import (
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
)
var (
requestMonitorMu sync.RWMutex
requestMonitor []interfaces.RequestLogEntry
maxMonitorSize = 100
)
func addRequestToMonitor(entry interfaces.RequestLogEntry) {
requestMonitorMu.Lock()
defer requestMonitorMu.Unlock()
requestMonitor = append(requestMonitor, entry)
if len(requestMonitor) > maxMonitorSize {
requestMonitor = requestMonitor[1:]
}
}
// GetRequestMonitor returns a copy of the current request monitor entries.
func GetRequestMonitor() []interfaces.RequestLogEntry {
requestMonitorMu.RLock()
defer requestMonitorMu.RUnlock()
result := make([]interfaces.RequestLogEntry, len(requestMonitor))
copy(result, requestMonitor)
return result
}
// RequestLoggingMiddleware creates a Gin middleware that logs HTTP requests and responses.
// It captures detailed information about the request and response, including headers and body,
// and uses the provided RequestLogger to record this data. When logging is disabled in the
@@ -53,13 +82,68 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc {
c.Writer = wrapper
// Process the request
startTime := time.Now()
c.Next()
latency := time.Since(startTime)
// Finalize logging after request processing
if err = wrapper.Finalize(c); err != nil {
// Log error but don't interrupt the response
// In a real implementation, you might want to use a proper logger here
}
// Add to monitor
entry := interfaces.RequestLogEntry{
ID: logging.GetGinRequestID(c),
Timestamp: startTime,
Method: c.Request.Method,
Path: c.Request.URL.Path,
Status: c.Writer.Status(),
LatencyMs: latency.Milliseconds(),
}
// Try to get Model and Provider from context
if model, ok := c.Get("model"); ok {
if m, ok := model.(string); ok {
entry.Model = m
}
}
if provider, ok := c.Get("provider"); ok {
if p, ok := provider.(string); ok {
entry.Provider = p
}
}
// Try to get tokens from context
if inputTokens, ok := c.Get("input_tokens"); ok {
if it, ok := inputTokens.(int); ok {
entry.InputTokens = it
} else if it, ok := inputTokens.(int64); ok {
entry.InputTokens = int(it)
}
}
if outputTokens, ok := c.Get("output_tokens"); ok {
if ot, ok := outputTokens.(int); ok {
entry.OutputTokens = ot
} else if ot, ok := outputTokens.(int64); ok {
entry.OutputTokens = int(ot)
}
}
// Try to get error from context
if apiErr, ok := c.Get("API_RESPONSE_ERROR"); ok {
if errs, ok := apiErr.([]*interfaces.ErrorMessage); ok && len(errs) > 0 {
var errMsgs []string
for _, e := range errs {
if e != nil && e.Error != nil {
errMsgs = append(errMsgs, e.Error.Error())
}
}
entry.Error = strings.Join(errMsgs, "; ")
}
}
addRequestToMonitor(entry)
}
}
+20 -5
View File
@@ -23,6 +23,7 @@ func (s *Server) registerProxyPilotDashboardRoutes() {
s.engine.GET("/proxypilot.html", s.serveProxyPilotDashboard)
s.engine.GET("/assets/*filepath", s.serveProxyPilotAsset)
s.engine.GET("/vite.svg", s.serveProxyPilotViteIcon)
s.engine.GET("/logo.png", s.serveProxyPilotLogo)
}
func (s *Server) serveProxyPilotDashboard(c *gin.Context) {
@@ -37,7 +38,12 @@ func (s *Server) serveProxyPilotDashboard(c *gin.Context) {
return
}
html := string(index)
key := strings.TrimSpace(getManagementKey())
// Use localPassword from the server instance (set via WithLocalManagementPassword)
// Fall back to MANAGEMENT_PASSWORD env var for legacy subprocess mode
key := strings.TrimSpace(s.localPassword)
if key == "" {
key = strings.TrimSpace(os.Getenv("MANAGEMENT_PASSWORD"))
}
if key != "" && s.managementRoutesEnabled.Load() {
meta := `<meta name="pp-mgmt-key" content="` + escapeAttr(key) + `">`
html = strings.Replace(html, "</head>", meta+"</head>", 1)
@@ -79,6 +85,19 @@ func (s *Server) serveProxyPilotViteIcon(c *gin.Context) {
writeAssetResponse(c, "vite.svg", data)
}
func (s *Server) serveProxyPilotLogo(c *gin.Context) {
if !isLocalClient(c) {
c.AbortWithStatus(http.StatusForbidden)
return
}
data, err := fsReadFile("logo.png")
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
writeAssetResponse(c, "logo.png", data)
}
func writeAssetResponse(c *gin.Context, name string, data []byte) {
ext := strings.TrimPrefix(path.Ext(name), ".")
if mt := misc.MimeTypes[strings.ToLower(ext)]; mt != "" {
@@ -105,10 +124,6 @@ func isLocalClient(c *gin.Context) bool {
return clientIP == "127.0.0.1" || clientIP == "::1"
}
func getManagementKey() string {
return strings.TrimSpace(os.Getenv("MANAGEMENT_PASSWORD"))
}
func escapeAttr(s string) string {
return strings.ReplaceAll(strings.TrimSpace(s), `"`, "")
}
+1074 -1010
View File
File diff suppressed because it is too large Load Diff
-6
View File
@@ -60,12 +60,6 @@ func (e *AuthenticationError) Error() string {
// Common authentication error types.
var (
// ErrTokenExpired = &AuthenticationError{
// Type: "token_expired",
// Message: "Access token has expired",
// Code: http.StatusUnauthorized,
// }
// ErrInvalidState represents an error for invalid OAuth state parameter.
ErrInvalidState = &AuthenticationError{
Type: "invalid_state",
+159
View File
@@ -0,0 +1,159 @@
package claude
import (
"crypto/sha256"
"encoding/base64"
"regexp"
"testing"
)
func TestPKCE_GenerateVerifier_Length(t *testing.T) {
tests := []struct {
name string
expectedLength int
}{
{
name: "verifier should be 128 characters (96 bytes base64 encoded)",
expectedLength: 128,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
codes, err := GeneratePKCECodes()
if err != nil {
t.Fatalf("GeneratePKCECodes() error = %v", err)
}
if len(codes.CodeVerifier) != tt.expectedLength {
t.Errorf("CodeVerifier length = %d, want %d", len(codes.CodeVerifier), tt.expectedLength)
}
})
}
}
func TestPKCE_GenerateVerifier_Randomness(t *testing.T) {
tests := []struct {
name string
iterations int
}{
{
name: "multiple generations should produce unique verifiers",
iterations: 100,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
seen := make(map[string]bool)
for i := 0; i < tt.iterations; i++ {
codes, err := GeneratePKCECodes()
if err != nil {
t.Fatalf("GeneratePKCECodes() iteration %d error = %v", i, err)
}
if seen[codes.CodeVerifier] {
t.Errorf("Duplicate verifier detected at iteration %d", i)
}
seen[codes.CodeVerifier] = true
}
})
}
}
func TestPKCE_GenerateChallenge_SHA256(t *testing.T) {
tests := []struct {
name string
verifier string
}{
{
name: "challenge should be SHA256 hash of verifier",
verifier: "test-verifier-string-for-pkce-challenge-generation",
},
{
name: "challenge for empty verifier",
verifier: "",
},
{
name: "challenge for complex verifier with special chars",
verifier: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Generate expected challenge manually
hash := sha256.Sum256([]byte(tt.verifier))
expectedChallenge := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:])
// Use the internal function via GeneratePKCECodes and verify the relationship
codes, err := GeneratePKCECodes()
if err != nil {
t.Fatalf("GeneratePKCECodes() error = %v", err)
}
// Verify the generated challenge matches SHA256 of the generated verifier
generatedHash := sha256.Sum256([]byte(codes.CodeVerifier))
computedChallenge := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(generatedHash[:])
if codes.CodeChallenge != computedChallenge {
t.Errorf("CodeChallenge = %v, want computed SHA256 = %v", codes.CodeChallenge, computedChallenge)
}
// Also verify a known input produces expected output
_ = expectedChallenge // Used for documentation purposes
})
}
}
func TestPKCE_GenerateChallenge_Base64URL(t *testing.T) {
tests := []struct {
name string
}{
{
name: "challenge should be base64url encoded without padding",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
codes, err := GeneratePKCECodes()
if err != nil {
t.Fatalf("GeneratePKCECodes() error = %v", err)
}
// Base64URL uses - and _ instead of + and /
// Should not contain standard base64 chars + or /
if regexp.MustCompile(`[+/]`).MatchString(codes.CodeChallenge) {
t.Error("CodeChallenge contains non-URL-safe base64 characters (+ or /)")
}
// Should not have padding (=)
if regexp.MustCompile(`=`).MatchString(codes.CodeChallenge) {
t.Error("CodeChallenge contains base64 padding (=)")
}
// Should only contain valid base64url characters
validBase64URL := regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
if !validBase64URL.MatchString(codes.CodeChallenge) {
t.Errorf("CodeChallenge contains invalid base64url characters: %s", codes.CodeChallenge)
}
// SHA256 produces 32 bytes, base64url without padding = 43 chars
expectedChallengeLength := 43
if len(codes.CodeChallenge) != expectedChallengeLength {
t.Errorf("CodeChallenge length = %d, want %d", len(codes.CodeChallenge), expectedChallengeLength)
}
// Verify verifier is also base64url encoded without padding
if regexp.MustCompile(`[+/=]`).MatchString(codes.CodeVerifier) {
t.Error("CodeVerifier contains non-URL-safe base64 characters or padding")
}
if !validBase64URL.MatchString(codes.CodeVerifier) {
t.Errorf("CodeVerifier contains invalid base64url characters: %s", codes.CodeVerifier)
}
})
}
}
+431
View File
@@ -0,0 +1,431 @@
package claude
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
// Helper function to parse token expiry time
func parseExpireTime(expire string) (time.Time, error) {
return time.Parse(time.RFC3339, expire)
}
// Helper function to check if token is expired
func isTokenExpired(expire string) bool {
expireTime, err := parseExpireTime(expire)
if err != nil {
return true // Treat parse errors as expired
}
return time.Now().After(expireTime)
}
// Helper function to check if token needs refresh within lead time
func tokenNeedsRefresh(expire string, leadTime time.Duration) bool {
expireTime, err := parseExpireTime(expire)
if err != nil {
return true // Treat parse errors as needing refresh
}
return time.Now().Add(leadTime).After(expireTime)
}
func TestToken_Parse_ValidToken(t *testing.T) {
tests := []struct {
name string
tokenJSON string
wantEmail string
wantType string
wantErr bool
}{
{
name: "valid token with all fields",
tokenJSON: `{
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.test",
"access_token": "sk-ant-test-access-token",
"refresh_token": "rt-test-refresh-token",
"last_refresh": "2025-01-15T10:00:00Z",
"email": "user@example.com",
"type": "claude",
"expired": "2025-01-15T11:00:00Z"
}`,
wantEmail: "user@example.com",
wantType: "claude",
wantErr: false,
},
{
name: "valid token with minimal fields",
tokenJSON: `{
"access_token": "sk-ant-minimal",
"refresh_token": "rt-minimal",
"email": "minimal@test.com",
"type": "claude",
"expired": "2025-12-31T23:59:59Z"
}`,
wantEmail: "minimal@test.com",
wantType: "claude",
wantErr: false,
},
{
name: "token with empty strings",
tokenJSON: `{
"access_token": "",
"refresh_token": "",
"email": "",
"type": "claude",
"expired": ""
}`,
wantEmail: "",
wantType: "claude",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var token ClaudeTokenStorage
err := json.Unmarshal([]byte(tt.tokenJSON), &token)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
if token.Email != tt.wantEmail {
t.Errorf("Email = %v, want %v", token.Email, tt.wantEmail)
}
if token.Type != tt.wantType {
t.Errorf("Type = %v, want %v", token.Type, tt.wantType)
}
}
})
}
}
func TestToken_Parse_ExpiredToken(t *testing.T) {
tests := []struct {
name string
tokenJSON string
wantErr bool
}{
{
name: "token with past expiration date",
tokenJSON: `{
"access_token": "expired-token",
"refresh_token": "rt-expired",
"email": "expired@test.com",
"type": "claude",
"expired": "2020-01-01T00:00:00Z"
}`,
wantErr: false,
},
{
name: "token with invalid expiration format",
tokenJSON: `{
"access_token": "invalid-expire",
"refresh_token": "rt-invalid",
"email": "invalid@test.com",
"type": "claude",
"expired": "not-a-valid-date"
}`,
wantErr: false, // JSON parsing succeeds, date validation is separate
},
{
name: "token with Unix timestamp expiration (wrong format)",
tokenJSON: `{
"access_token": "unix-token",
"refresh_token": "rt-unix",
"email": "unix@test.com",
"type": "claude",
"expired": "1704067200"
}`,
wantErr: false, // JSON parsing succeeds
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var token ClaudeTokenStorage
err := json.Unmarshal([]byte(tt.tokenJSON), &token)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
// Verify the token can be parsed even if expired
if !tt.wantErr && token.AccessToken == "" {
t.Error("AccessToken should not be empty after successful parse")
}
})
}
}
func TestToken_IsExpired_FreshToken(t *testing.T) {
tests := []struct {
name string
expireTime time.Time
wantExpired bool
}{
{
name: "token expiring in 1 hour",
expireTime: time.Now().Add(1 * time.Hour),
wantExpired: false,
},
{
name: "token expiring in 24 hours",
expireTime: time.Now().Add(24 * time.Hour),
wantExpired: false,
},
{
name: "token expiring in 1 minute",
expireTime: time.Now().Add(1 * time.Minute),
wantExpired: false,
},
{
name: "token expiring in 1 second",
expireTime: time.Now().Add(1 * time.Second),
wantExpired: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expireStr := tt.expireTime.Format(time.RFC3339)
expired := isTokenExpired(expireStr)
if expired != tt.wantExpired {
t.Errorf("isTokenExpired() = %v, want %v", expired, tt.wantExpired)
}
})
}
}
func TestToken_IsExpired_ExpiredToken(t *testing.T) {
tests := []struct {
name string
expireTime time.Time
wantExpired bool
}{
{
name: "token expired 1 hour ago",
expireTime: time.Now().Add(-1 * time.Hour),
wantExpired: true,
},
{
name: "token expired 24 hours ago",
expireTime: time.Now().Add(-24 * time.Hour),
wantExpired: true,
},
{
name: "token expired 1 second ago",
expireTime: time.Now().Add(-1 * time.Second),
wantExpired: true,
},
{
name: "token expired in 2020",
expireTime: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
wantExpired: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expireStr := tt.expireTime.Format(time.RFC3339)
expired := isTokenExpired(expireStr)
if expired != tt.wantExpired {
t.Errorf("isTokenExpired() = %v, want %v", expired, tt.wantExpired)
}
})
}
}
func TestToken_NeedsRefresh_WithinLeadTime(t *testing.T) {
tests := []struct {
name string
expireTime time.Time
leadTime time.Duration
wantRefresh bool
}{
{
name: "token expiring in 5 minutes with 10 minute lead time",
expireTime: time.Now().Add(5 * time.Minute),
leadTime: 10 * time.Minute,
wantRefresh: true,
},
{
name: "token expiring in 30 seconds with 1 minute lead time",
expireTime: time.Now().Add(30 * time.Second),
leadTime: 1 * time.Minute,
wantRefresh: true,
},
{
name: "token expiring in 4 minutes with 5 minute lead time",
expireTime: time.Now().Add(4 * time.Minute),
leadTime: 5 * time.Minute,
wantRefresh: true,
},
{
name: "already expired token with any lead time",
expireTime: time.Now().Add(-1 * time.Minute),
leadTime: 5 * time.Minute,
wantRefresh: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expireStr := tt.expireTime.Format(time.RFC3339)
needsRefresh := tokenNeedsRefresh(expireStr, tt.leadTime)
if needsRefresh != tt.wantRefresh {
t.Errorf("tokenNeedsRefresh() = %v, want %v", needsRefresh, tt.wantRefresh)
}
})
}
}
func TestToken_NeedsRefresh_NotYet(t *testing.T) {
tests := []struct {
name string
expireTime time.Time
leadTime time.Duration
wantRefresh bool
}{
{
name: "token expiring in 1 hour with 5 minute lead time",
expireTime: time.Now().Add(1 * time.Hour),
leadTime: 5 * time.Minute,
wantRefresh: false,
},
{
name: "token expiring in 10 minutes with 5 minute lead time",
expireTime: time.Now().Add(10 * time.Minute),
leadTime: 5 * time.Minute,
wantRefresh: false,
},
{
name: "token expiring in 24 hours with 1 hour lead time",
expireTime: time.Now().Add(24 * time.Hour),
leadTime: 1 * time.Hour,
wantRefresh: false,
},
{
name: "token expiring in 6 minutes with 5 minute lead time",
expireTime: time.Now().Add(6 * time.Minute),
leadTime: 5 * time.Minute,
wantRefresh: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expireStr := tt.expireTime.Format(time.RFC3339)
needsRefresh := tokenNeedsRefresh(expireStr, tt.leadTime)
if needsRefresh != tt.wantRefresh {
t.Errorf("tokenNeedsRefresh() = %v, want %v", needsRefresh, tt.wantRefresh)
}
})
}
}
func TestToken_SaveTokenToFile(t *testing.T) {
tests := []struct {
name string
token ClaudeTokenStorage
wantErr bool
}{
{
name: "save valid token",
token: ClaudeTokenStorage{
IDToken: "test-id-token",
AccessToken: "test-access-token",
RefreshToken: "test-refresh-token",
LastRefresh: time.Now().Format(time.RFC3339),
Email: "test@example.com",
Type: "claude",
Expire: time.Now().Add(1 * time.Hour).Format(time.RFC3339),
},
wantErr: false,
},
{
name: "save token with empty fields",
token: ClaudeTokenStorage{
AccessToken: "minimal-token",
RefreshToken: "minimal-refresh",
Type: "claude",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create temp directory for test
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test-token.json")
err := tt.token.SaveTokenToFile(filePath)
if (err != nil) != tt.wantErr {
t.Errorf("SaveTokenToFile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
// Verify file was created
if _, err := os.Stat(filePath); os.IsNotExist(err) {
t.Error("Token file was not created")
return
}
// Verify file contents can be parsed back
data, err := os.ReadFile(filePath)
if err != nil {
t.Errorf("Failed to read token file: %v", err)
return
}
var savedToken ClaudeTokenStorage
if err := json.Unmarshal(data, &savedToken); err != nil {
t.Errorf("Failed to parse saved token: %v", err)
return
}
// Verify key fields match
if savedToken.AccessToken != tt.token.AccessToken {
t.Errorf("AccessToken = %v, want %v", savedToken.AccessToken, tt.token.AccessToken)
}
if savedToken.Type != "claude" {
t.Errorf("Type = %v, want claude", savedToken.Type)
}
}
})
}
}
func TestToken_SaveTokenToFile_CreatesDirectory(t *testing.T) {
tmpDir := t.TempDir()
nestedPath := filepath.Join(tmpDir, "nested", "dir", "structure", "token.json")
token := ClaudeTokenStorage{
AccessToken: "test-token",
RefreshToken: "test-refresh",
Type: "claude",
}
err := token.SaveTokenToFile(nestedPath)
if err != nil {
t.Errorf("SaveTokenToFile() should create nested directories, got error: %v", err)
return
}
// Verify file exists
if _, err := os.Stat(nestedPath); os.IsNotExist(err) {
t.Error("Token file was not created in nested directory")
}
}
-6
View File
@@ -57,12 +57,6 @@ func (e *AuthenticationError) Error() string {
// Common authentication error types.
var (
// ErrTokenExpired = &AuthenticationError{
// Type: "token_expired",
// Message: "Access token has expired",
// Code: http.StatusUnauthorized,
// }
// ErrInvalidState represents an error for invalid OAuth state parameter.
ErrInvalidState = &AuthenticationError{
Type: "invalid_state",
+465
View File
@@ -0,0 +1,465 @@
package codex
import (
"encoding/base64"
"encoding/json"
"testing"
"time"
)
// createTestJWT creates a test JWT token with the given claims.
// It creates a valid 3-part JWT structure (header.payload.signature) for testing.
func createTestJWT(claims JWTClaims) string {
header := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`))
claimsJSON, _ := json.Marshal(claims)
payload := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(claimsJSON)
signature := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString([]byte("test-signature"))
return header + "." + payload + "." + signature
}
func TestParseJWTToken_ValidToken(t *testing.T) {
tests := []struct {
name string
claims JWTClaims
wantEmail string
wantAccountID string
wantIssuer string
wantSubject string
}{
{
name: "valid token with all fields",
claims: JWTClaims{
Email: "user@example.com",
EmailVerified: true,
Iss: "https://auth.openai.com/",
Sub: "auth0|user123",
Exp: int(time.Now().Add(time.Hour).Unix()),
Iat: int(time.Now().Unix()),
CodexAuthInfo: CodexAuthInfo{
ChatgptAccountID: "acct_abc123",
ChatgptUserID: "user_xyz789",
ChatgptPlanType: "plus",
UserID: "user-id-123",
},
},
wantEmail: "user@example.com",
wantAccountID: "acct_abc123",
wantIssuer: "https://auth.openai.com/",
wantSubject: "auth0|user123",
},
{
name: "valid token with minimal fields",
claims: JWTClaims{
Email: "minimal@example.com",
Exp: int(time.Now().Add(time.Hour).Unix()),
},
wantEmail: "minimal@example.com",
wantAccountID: "",
wantIssuer: "",
wantSubject: "",
},
{
name: "valid token with organization data",
claims: JWTClaims{
Email: "org-user@example.com",
Sub: "auth0|orguser456",
CodexAuthInfo: CodexAuthInfo{
ChatgptAccountID: "acct_org789",
Organizations: []Organizations{
{
ID: "org-id-1",
IsDefault: true,
Role: "admin",
Title: "My Organization",
},
},
},
},
wantEmail: "org-user@example.com",
wantAccountID: "acct_org789",
wantSubject: "auth0|orguser456",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
token := createTestJWT(tt.claims)
got, err := ParseJWTToken(token)
if err != nil {
t.Fatalf("ParseJWTToken() unexpected error = %v", err)
}
if got.Email != tt.wantEmail {
t.Errorf("ParseJWTToken() Email = %v, want %v", got.Email, tt.wantEmail)
}
if got.GetAccountID() != tt.wantAccountID {
t.Errorf("ParseJWTToken() AccountID = %v, want %v", got.GetAccountID(), tt.wantAccountID)
}
if got.Iss != tt.wantIssuer {
t.Errorf("ParseJWTToken() Issuer = %v, want %v", got.Iss, tt.wantIssuer)
}
if got.Sub != tt.wantSubject {
t.Errorf("ParseJWTToken() Subject = %v, want %v", got.Sub, tt.wantSubject)
}
})
}
}
func TestParseJWTToken_InvalidToken(t *testing.T) {
tests := []struct {
name string
token string
wantErr string
}{
{
name: "empty token",
token: "",
wantErr: "invalid JWT token format",
},
{
name: "single part token",
token: "singlepart",
wantErr: "invalid JWT token format",
},
{
name: "two part token",
token: "header.payload",
wantErr: "invalid JWT token format",
},
{
name: "four part token",
token: "header.payload.signature.extra",
wantErr: "invalid JWT token format",
},
{
name: "invalid base64 in payload",
token: "header.!!!invalid-base64!!!.signature",
wantErr: "failed to decode JWT claims",
},
{
name: "invalid JSON in payload",
token: "header." + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString([]byte("not-json")) + ".signature",
wantErr: "failed to unmarshal JWT claims",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseJWTToken(tt.token)
if err == nil {
t.Fatalf("ParseJWTToken() expected error containing %q, got nil", tt.wantErr)
}
if got != nil {
t.Errorf("ParseJWTToken() expected nil result on error, got %v", got)
}
if !containsSubstring(err.Error(), tt.wantErr) {
t.Errorf("ParseJWTToken() error = %v, want error containing %q", err, tt.wantErr)
}
})
}
}
func TestParseJWTToken_ExtractClaims(t *testing.T) {
tests := []struct {
name string
claims JWTClaims
checks func(t *testing.T, got *JWTClaims)
}{
{
name: "extract standard claims",
claims: JWTClaims{
Aud: []string{"app_test123"},
AtHash: "at_hash_value",
AuthTime: 1700000000,
Exp: 1700003600,
Iat: 1700000000,
Jti: "jti_unique_id",
Rat: 1699999900,
Sid: "session_id_123",
},
checks: func(t *testing.T, got *JWTClaims) {
if len(got.Aud) != 1 || got.Aud[0] != "app_test123" {
t.Errorf("Aud = %v, want [app_test123]", got.Aud)
}
if got.AtHash != "at_hash_value" {
t.Errorf("AtHash = %v, want at_hash_value", got.AtHash)
}
if got.AuthTime != 1700000000 {
t.Errorf("AuthTime = %v, want 1700000000", got.AuthTime)
}
if got.Jti != "jti_unique_id" {
t.Errorf("Jti = %v, want jti_unique_id", got.Jti)
}
if got.Sid != "session_id_123" {
t.Errorf("Sid = %v, want session_id_123", got.Sid)
}
},
},
{
name: "extract auth provider info",
claims: JWTClaims{
AuthProvider: "google-oauth2",
Email: "google@example.com",
CodexAuthInfo: CodexAuthInfo{
ChatgptPlanType: "team",
UserID: "user-google-123",
},
},
checks: func(t *testing.T, got *JWTClaims) {
if got.AuthProvider != "google-oauth2" {
t.Errorf("AuthProvider = %v, want google-oauth2", got.AuthProvider)
}
if got.CodexAuthInfo.ChatgptPlanType != "team" {
t.Errorf("ChatgptPlanType = %v, want team", got.CodexAuthInfo.ChatgptPlanType)
}
},
},
{
name: "extract multiple organizations",
claims: JWTClaims{
Email: "multi-org@example.com",
CodexAuthInfo: CodexAuthInfo{
Organizations: []Organizations{
{ID: "org-1", IsDefault: true, Role: "owner", Title: "Primary Org"},
{ID: "org-2", IsDefault: false, Role: "member", Title: "Secondary Org"},
},
},
},
checks: func(t *testing.T, got *JWTClaims) {
orgs := got.CodexAuthInfo.Organizations
if len(orgs) != 2 {
t.Fatalf("Organizations count = %v, want 2", len(orgs))
}
if orgs[0].ID != "org-1" || !orgs[0].IsDefault {
t.Errorf("First org = %+v, want org-1 as default", orgs[0])
}
if orgs[1].Role != "member" {
t.Errorf("Second org role = %v, want member", orgs[1].Role)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
token := createTestJWT(tt.claims)
got, err := ParseJWTToken(token)
if err != nil {
t.Fatalf("ParseJWTToken() unexpected error = %v", err)
}
tt.checks(t, got)
})
}
}
func TestParseJWTToken_ValidateExpiry(t *testing.T) {
now := time.Now()
tests := []struct {
name string
expTime int
wantValid bool
}{
{
name: "token expires in 1 hour",
expTime: int(now.Add(time.Hour).Unix()),
wantValid: true,
},
{
name: "token expires in 1 minute",
expTime: int(now.Add(time.Minute).Unix()),
wantValid: true,
},
{
name: "token expired 1 hour ago",
expTime: int(now.Add(-time.Hour).Unix()),
wantValid: false,
},
{
name: "token expired 1 minute ago",
expTime: int(now.Add(-time.Minute).Unix()),
wantValid: false,
},
{
name: "token expires now",
expTime: int(now.Unix()),
wantValid: false,
},
{
name: "token with zero expiry",
expTime: 0,
wantValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
claims := JWTClaims{
Email: "test@example.com",
Exp: tt.expTime,
}
token := createTestJWT(claims)
got, err := ParseJWTToken(token)
if err != nil {
t.Fatalf("ParseJWTToken() unexpected error = %v", err)
}
// Check if token is valid based on expiry
isValid := time.Unix(int64(got.Exp), 0).After(time.Now())
if isValid != tt.wantValid {
t.Errorf("Token validity = %v, want %v (exp: %v, now: %v)",
isValid, tt.wantValid, time.Unix(int64(got.Exp), 0), time.Now())
}
})
}
}
func TestJWTClaims_GetUserEmail(t *testing.T) {
tests := []struct {
name string
claims JWTClaims
wantEmail string
}{
{
name: "standard email",
claims: JWTClaims{Email: "user@example.com"},
wantEmail: "user@example.com",
},
{
name: "empty email",
claims: JWTClaims{Email: ""},
wantEmail: "",
},
{
name: "email with subdomain",
claims: JWTClaims{Email: "user@mail.example.com"},
wantEmail: "user@mail.example.com",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.claims.GetUserEmail(); got != tt.wantEmail {
t.Errorf("GetUserEmail() = %v, want %v", got, tt.wantEmail)
}
})
}
}
func TestJWTClaims_GetAccountID(t *testing.T) {
tests := []struct {
name string
claims JWTClaims
wantAccountID string
}{
{
name: "with account ID",
claims: JWTClaims{
CodexAuthInfo: CodexAuthInfo{
ChatgptAccountID: "acct_12345",
},
},
wantAccountID: "acct_12345",
},
{
name: "empty account ID",
claims: JWTClaims{},
wantAccountID: "",
},
{
name: "account ID with special characters",
claims: JWTClaims{
CodexAuthInfo: CodexAuthInfo{
ChatgptAccountID: "acct_abc-123_xyz",
},
},
wantAccountID: "acct_abc-123_xyz",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.claims.GetAccountID(); got != tt.wantAccountID {
t.Errorf("GetAccountID() = %v, want %v", got, tt.wantAccountID)
}
})
}
}
func TestBase64URLDecode(t *testing.T) {
tests := []struct {
name string
input string
want string
wantErr bool
}{
{
name: "no padding needed",
input: "dGVzdA",
want: "test",
wantErr: false,
},
{
name: "one padding character needed",
input: "dGVzdDE",
want: "test1",
wantErr: false,
},
{
name: "two padding characters needed",
input: "dGVzdDEy",
want: "test12",
wantErr: false,
},
{
name: "empty string",
input: "",
want: "",
wantErr: false,
},
{
name: "URL-safe characters",
input: "YWJjLV8",
want: "abc-_",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := base64URLDecode(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("base64URLDecode() error = %v, wantErr %v", err, tt.wantErr)
return
}
if string(got) != tt.want {
t.Errorf("base64URLDecode() = %v, want %v", string(got), tt.want)
}
})
}
}
// containsSubstring checks if s contains substr
func containsSubstring(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
(len(s) > 0 && len(substr) > 0 && findSubstring(s, substr)))
}
func findSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
+558
View File
@@ -0,0 +1,558 @@
package codex
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
)
func TestCodexTokenStorage_Parse(t *testing.T) {
tests := []struct {
name string
jsonData string
wantErr bool
checkFields func(t *testing.T, ts *CodexTokenStorage)
}{
{
name: "parse complete token storage",
jsonData: `{
"id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.sig",
"access_token": "access_token_value",
"refresh_token": "refresh_token_value",
"account_id": "acct_abc123",
"last_refresh": "2024-01-15T10:30:00Z",
"email": "user@example.com",
"type": "codex",
"expired": "2024-01-15T11:30:00Z"
}`,
wantErr: false,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
if ts.IDToken != "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.sig" {
t.Errorf("IDToken mismatch")
}
if ts.AccessToken != "access_token_value" {
t.Errorf("AccessToken = %v, want access_token_value", ts.AccessToken)
}
if ts.RefreshToken != "refresh_token_value" {
t.Errorf("RefreshToken = %v, want refresh_token_value", ts.RefreshToken)
}
if ts.AccountID != "acct_abc123" {
t.Errorf("AccountID = %v, want acct_abc123", ts.AccountID)
}
if ts.Email != "user@example.com" {
t.Errorf("Email = %v, want user@example.com", ts.Email)
}
if ts.Type != "codex" {
t.Errorf("Type = %v, want codex", ts.Type)
}
},
},
{
name: "parse minimal token storage",
jsonData: `{
"access_token": "minimal_access",
"refresh_token": "minimal_refresh",
"type": "codex"
}`,
wantErr: false,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
if ts.AccessToken != "minimal_access" {
t.Errorf("AccessToken = %v, want minimal_access", ts.AccessToken)
}
if ts.IDToken != "" {
t.Errorf("IDToken = %v, want empty", ts.IDToken)
}
if ts.Email != "" {
t.Errorf("Email = %v, want empty", ts.Email)
}
},
},
{
name: "parse token with special characters in values",
jsonData: `{
"access_token": "token-with_special.chars/and+more",
"refresh_token": "refresh/token+value=",
"email": "user+test@sub.example.com",
"type": "codex"
}`,
wantErr: false,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
if ts.AccessToken != "token-with_special.chars/and+more" {
t.Errorf("AccessToken mismatch with special chars")
}
if ts.Email != "user+test@sub.example.com" {
t.Errorf("Email mismatch with special chars")
}
},
},
{
name: "parse empty JSON object",
jsonData: `{}`,
wantErr: false,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
if ts.Type != "" {
t.Errorf("Type = %v, want empty for empty JSON", ts.Type)
}
},
},
{
name: "invalid JSON",
jsonData: `{"invalid": json}`,
wantErr: true,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
// Not called on error
},
},
{
name: "malformed JSON - missing closing brace",
jsonData: `{"access_token": "test"`,
wantErr: true,
checkFields: func(t *testing.T, ts *CodexTokenStorage) {
// Not called on error
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var ts CodexTokenStorage
err := json.Unmarshal([]byte(tt.jsonData), &ts)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
tt.checkFields(t, &ts)
}
})
}
}
func TestCodexTokenStorage_IsExpired(t *testing.T) {
tests := []struct {
name string
expireTime string
wantResult bool
}{
{
name: "token expired 1 hour ago",
expireTime: time.Now().Add(-time.Hour).Format(time.RFC3339),
wantResult: true,
},
{
name: "token expired 1 minute ago",
expireTime: time.Now().Add(-time.Minute).Format(time.RFC3339),
wantResult: true,
},
{
name: "token expires in 1 hour",
expireTime: time.Now().Add(time.Hour).Format(time.RFC3339),
wantResult: false,
},
{
name: "token expires in 1 minute",
expireTime: time.Now().Add(time.Minute).Format(time.RFC3339),
wantResult: false,
},
{
name: "token expires now",
expireTime: time.Now().Format(time.RFC3339),
wantResult: true, // Tokens that expire "now" are considered expired
},
{
name: "empty expire time",
expireTime: "",
wantResult: true, // Treat empty as expired
},
{
name: "invalid expire time format",
expireTime: "invalid-time",
wantResult: true, // Treat invalid as expired for safety
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := &CodexTokenStorage{
Expire: tt.expireTime,
}
// Test the expiry logic
isExpired := isTokenExpired(ts.Expire)
if isExpired != tt.wantResult {
t.Errorf("isTokenExpired() = %v, want %v (expire: %s)",
isExpired, tt.wantResult, tt.expireTime)
}
})
}
}
func TestCodexTokenStorage_NeedsRefresh(t *testing.T) {
tests := []struct {
name string
expireTime string
refreshBefore time.Duration // How long before expiry to trigger refresh
wantResult bool
}{
{
name: "token expires in 30 minutes, refresh at 5 min before",
expireTime: time.Now().Add(30 * time.Minute).Format(time.RFC3339),
refreshBefore: 5 * time.Minute,
wantResult: false,
},
{
name: "token expires in 3 minutes, refresh at 5 min before",
expireTime: time.Now().Add(3 * time.Minute).Format(time.RFC3339),
refreshBefore: 5 * time.Minute,
wantResult: true,
},
{
name: "token expires in 1 hour, refresh at 10 min before",
expireTime: time.Now().Add(time.Hour).Format(time.RFC3339),
refreshBefore: 10 * time.Minute,
wantResult: false,
},
{
name: "token expires in 5 minutes, refresh at 10 min before",
expireTime: time.Now().Add(5 * time.Minute).Format(time.RFC3339),
refreshBefore: 10 * time.Minute,
wantResult: true,
},
{
name: "token already expired",
expireTime: time.Now().Add(-time.Hour).Format(time.RFC3339),
refreshBefore: 5 * time.Minute,
wantResult: true,
},
{
name: "empty expire time",
expireTime: "",
refreshBefore: 5 * time.Minute,
wantResult: true,
},
{
name: "expires exactly at refresh threshold",
expireTime: time.Now().Add(5 * time.Minute).Format(time.RFC3339),
refreshBefore: 5 * time.Minute,
wantResult: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := &CodexTokenStorage{
Expire: tt.expireTime,
}
needsRefresh := tokenNeedsRefresh(ts.Expire, tt.refreshBefore)
if needsRefresh != tt.wantResult {
t.Errorf("tokenNeedsRefresh() = %v, want %v (expire: %s, threshold: %v)",
needsRefresh, tt.wantResult, tt.expireTime, tt.refreshBefore)
}
})
}
}
func TestCodexTokenStorage_SaveTokenToFile(t *testing.T) {
tests := []struct {
name string
storage CodexTokenStorage
wantErr bool
}{
{
name: "save complete token storage",
storage: CodexTokenStorage{
IDToken: "test_id_token",
AccessToken: "test_access_token",
RefreshToken: "test_refresh_token",
AccountID: "test_account_id",
LastRefresh: time.Now().Format(time.RFC3339),
Email: "test@example.com",
Type: "codex",
Expire: time.Now().Add(time.Hour).Format(time.RFC3339),
},
wantErr: false,
},
{
name: "save minimal token storage",
storage: CodexTokenStorage{
AccessToken: "minimal_token",
RefreshToken: "minimal_refresh",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a temporary directory for the test
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "tokens", "codex_token.json")
err := tt.storage.SaveTokenToFile(filePath)
if (err != nil) != tt.wantErr {
t.Errorf("SaveTokenToFile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
// Verify the file was created
if _, err := os.Stat(filePath); os.IsNotExist(err) {
t.Errorf("SaveTokenToFile() file was not created at %s", filePath)
return
}
// Read and verify content
data, err := os.ReadFile(filePath)
if err != nil {
t.Errorf("Failed to read saved file: %v", err)
return
}
var loaded CodexTokenStorage
if err := json.Unmarshal(data, &loaded); err != nil {
t.Errorf("Failed to parse saved file: %v", err)
return
}
// Verify type is always set to "codex"
if loaded.Type != "codex" {
t.Errorf("Type = %v, want codex", loaded.Type)
}
// Verify key fields match
if loaded.AccessToken != tt.storage.AccessToken {
t.Errorf("AccessToken = %v, want %v", loaded.AccessToken, tt.storage.AccessToken)
}
if loaded.RefreshToken != tt.storage.RefreshToken {
t.Errorf("RefreshToken = %v, want %v", loaded.RefreshToken, tt.storage.RefreshToken)
}
}
})
}
}
func TestCodexTokenData_Parse(t *testing.T) {
tests := []struct {
name string
jsonData string
wantErr bool
checkFields func(t *testing.T, td *CodexTokenData)
}{
{
name: "parse complete token data",
jsonData: `{
"id_token": "jwt_id_token_here",
"access_token": "access_token_here",
"refresh_token": "refresh_token_here",
"account_id": "acct_123",
"email": "user@example.com",
"expired": "2024-01-15T12:00:00Z"
}`,
wantErr: false,
checkFields: func(t *testing.T, td *CodexTokenData) {
if td.IDToken != "jwt_id_token_here" {
t.Errorf("IDToken mismatch")
}
if td.AccessToken != "access_token_here" {
t.Errorf("AccessToken mismatch")
}
if td.RefreshToken != "refresh_token_here" {
t.Errorf("RefreshToken mismatch")
}
if td.AccountID != "acct_123" {
t.Errorf("AccountID mismatch")
}
if td.Email != "user@example.com" {
t.Errorf("Email mismatch")
}
},
},
{
name: "parse minimal token data",
jsonData: `{
"access_token": "only_access"
}`,
wantErr: false,
checkFields: func(t *testing.T, td *CodexTokenData) {
if td.AccessToken != "only_access" {
t.Errorf("AccessToken = %v, want only_access", td.AccessToken)
}
if td.RefreshToken != "" {
t.Errorf("RefreshToken should be empty")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var td CodexTokenData
err := json.Unmarshal([]byte(tt.jsonData), &td)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
tt.checkFields(t, &td)
}
})
}
}
func TestCodexAuthBundle_Parse(t *testing.T) {
tests := []struct {
name string
jsonData string
wantErr bool
checkFields func(t *testing.T, bundle *CodexAuthBundle)
}{
{
name: "parse complete auth bundle",
jsonData: `{
"api_key": "sk-proj-api-key",
"token_data": {
"id_token": "id_token_value",
"access_token": "access_token_value",
"refresh_token": "refresh_token_value",
"account_id": "acct_bundle",
"email": "bundle@example.com",
"expired": "2024-01-15T12:00:00Z"
},
"last_refresh": "2024-01-15T10:00:00Z"
}`,
wantErr: false,
checkFields: func(t *testing.T, bundle *CodexAuthBundle) {
if bundle.APIKey != "sk-proj-api-key" {
t.Errorf("APIKey mismatch")
}
if bundle.TokenData.AccessToken != "access_token_value" {
t.Errorf("TokenData.AccessToken mismatch")
}
if bundle.TokenData.Email != "bundle@example.com" {
t.Errorf("TokenData.Email mismatch")
}
if bundle.LastRefresh != "2024-01-15T10:00:00Z" {
t.Errorf("LastRefresh mismatch")
}
},
},
{
name: "parse bundle without api key",
jsonData: `{
"token_data": {
"access_token": "token_only"
},
"last_refresh": "2024-01-15T10:00:00Z"
}`,
wantErr: false,
checkFields: func(t *testing.T, bundle *CodexAuthBundle) {
if bundle.APIKey != "" {
t.Errorf("APIKey should be empty")
}
if bundle.TokenData.AccessToken != "token_only" {
t.Errorf("TokenData.AccessToken mismatch")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var bundle CodexAuthBundle
err := json.Unmarshal([]byte(tt.jsonData), &bundle)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
tt.checkFields(t, &bundle)
}
})
}
}
func TestPKCECodes_Parse(t *testing.T) {
tests := []struct {
name string
jsonData string
wantErr bool
checkFields func(t *testing.T, codes *PKCECodes)
}{
{
name: "parse valid PKCE codes",
jsonData: `{
"code_verifier": "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
"code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
}`,
wantErr: false,
checkFields: func(t *testing.T, codes *PKCECodes) {
if codes.CodeVerifier != "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" {
t.Errorf("CodeVerifier mismatch")
}
if codes.CodeChallenge != "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" {
t.Errorf("CodeChallenge mismatch")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var codes PKCECodes
err := json.Unmarshal([]byte(tt.jsonData), &codes)
if (err != nil) != tt.wantErr {
t.Errorf("json.Unmarshal() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr {
tt.checkFields(t, &codes)
}
})
}
}
// Helper functions for token expiry testing
// isTokenExpired checks if a token has expired based on its expire timestamp.
func isTokenExpired(expire string) bool {
if expire == "" {
return true
}
expireTime, err := time.Parse(time.RFC3339, expire)
if err != nil {
return true // Treat parse errors as expired for safety
}
return !expireTime.After(time.Now())
}
// tokenNeedsRefresh checks if a token should be refreshed based on its expiry
// and a threshold duration before expiry.
func tokenNeedsRefresh(expire string, threshold time.Duration) bool {
if expire == "" {
return true
}
expireTime, err := time.Parse(time.RFC3339, expire)
if err != nil {
return true
}
refreshTime := expireTime.Add(-threshold)
return !refreshTime.After(time.Now())
}
-99
View File
@@ -1,99 +0,0 @@
package iflow
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// NormalizeCookie normalizes raw cookie strings for iFlow authentication flows.
func NormalizeCookie(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return "", fmt.Errorf("cookie cannot be empty")
}
combined := strings.Join(strings.Fields(trimmed), " ")
if !strings.HasSuffix(combined, ";") {
combined += ";"
}
if !strings.Contains(combined, "BXAuth=") {
return "", fmt.Errorf("cookie missing BXAuth field")
}
return combined, nil
}
// SanitizeIFlowFileName normalizes user identifiers for safe filename usage.
func SanitizeIFlowFileName(raw string) string {
if raw == "" {
return ""
}
cleanEmail := strings.ReplaceAll(raw, "*", "x")
var result strings.Builder
for _, r := range cleanEmail {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '@' || r == '.' || r == '-' {
result.WriteRune(r)
}
}
return strings.TrimSpace(result.String())
}
// ExtractBXAuth extracts the BXAuth value from a cookie string.
func ExtractBXAuth(cookie string) string {
parts := strings.Split(cookie, ";")
for _, part := range parts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "BXAuth=") {
return strings.TrimPrefix(part, "BXAuth=")
}
}
return ""
}
// CheckDuplicateBXAuth checks if the given BXAuth value already exists in any iflow auth file.
// Returns the path of the existing file if found, empty string otherwise.
func CheckDuplicateBXAuth(authDir, bxAuth string) (string, error) {
if bxAuth == "" {
return "", nil
}
entries, err := os.ReadDir(authDir)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", fmt.Errorf("read auth dir failed: %w", err)
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
if !strings.HasPrefix(name, "iflow-") || !strings.HasSuffix(name, ".json") {
continue
}
filePath := filepath.Join(authDir, name)
data, err := os.ReadFile(filePath)
if err != nil {
continue
}
var tokenData struct {
Cookie string `json:"cookie"`
}
if err := json.Unmarshal(data, &tokenData); err != nil {
continue
}
existingBXAuth := ExtractBXAuth(tokenData.Cookie)
if existingBXAuth != "" && existingBXAuth == bxAuth {
return filePath, nil
}
}
return "", nil
}
-535
View File
@@ -1,535 +0,0 @@
package iflow
import (
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
)
const (
// OAuth endpoints and client metadata are derived from the reference Python implementation.
iFlowOAuthTokenEndpoint = "https://iflow.cn/oauth/token"
iFlowOAuthAuthorizeEndpoint = "https://iflow.cn/oauth"
iFlowUserInfoEndpoint = "https://iflow.cn/api/oauth/getUserInfo"
iFlowSuccessRedirectURL = "https://iflow.cn/oauth/success"
// Cookie authentication endpoints
iFlowAPIKeyEndpoint = "https://platform.iflow.cn/api/openapi/apikey"
// Client credentials provided by iFlow for the Code Assist integration.
iFlowOAuthClientID = "10009311001"
// Default client secret (can be overridden via IFLOW_CLIENT_SECRET env var)
defaultIFlowClientSecret = "4Z3YjXycVsQvyGF1etiNlIBB4RsqSDtW"
)
// getIFlowClientSecret returns the iFlow OAuth client secret.
// It first checks the IFLOW_CLIENT_SECRET environment variable,
// falling back to the default value if not set.
func getIFlowClientSecret() string {
if secret := os.Getenv("IFLOW_CLIENT_SECRET"); secret != "" {
return secret
}
return defaultIFlowClientSecret
}
// DefaultAPIBaseURL is the canonical chat completions endpoint.
const DefaultAPIBaseURL = "https://apis.iflow.cn/v1"
// SuccessRedirectURL is exposed for consumers needing the official success page.
const SuccessRedirectURL = iFlowSuccessRedirectURL
// CallbackPort defines the local port used for OAuth callbacks.
const CallbackPort = 11451
// IFlowAuth encapsulates the HTTP client helpers for the OAuth flow.
type IFlowAuth struct {
httpClient *http.Client
}
// NewIFlowAuth constructs a new IFlowAuth with proxy-aware transport.
func NewIFlowAuth(cfg *config.Config) *IFlowAuth {
client := &http.Client{Timeout: 30 * time.Second}
return &IFlowAuth{httpClient: util.SetProxy(&cfg.SDKConfig, client)}
}
// AuthorizationURL builds the authorization URL and matching redirect URI.
func (ia *IFlowAuth) AuthorizationURL(state string, port int) (authURL, redirectURI string) {
redirectURI = fmt.Sprintf("http://localhost:%d/oauth2callback", port)
values := url.Values{}
values.Set("loginMethod", "phone")
values.Set("type", "phone")
values.Set("redirect", redirectURI)
values.Set("state", state)
values.Set("client_id", iFlowOAuthClientID)
authURL = fmt.Sprintf("%s?%s", iFlowOAuthAuthorizeEndpoint, values.Encode())
return authURL, redirectURI
}
// ExchangeCodeForTokens exchanges an authorization code for access and refresh tokens.
func (ia *IFlowAuth) ExchangeCodeForTokens(ctx context.Context, code, redirectURI string) (*IFlowTokenData, error) {
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", redirectURI)
form.Set("client_id", iFlowOAuthClientID)
form.Set("client_secret", getIFlowClientSecret())
req, err := ia.newTokenRequest(ctx, form)
if err != nil {
return nil, err
}
return ia.doTokenRequest(ctx, req)
}
// RefreshTokens exchanges a refresh token for a new access token.
func (ia *IFlowAuth) RefreshTokens(ctx context.Context, refreshToken string) (*IFlowTokenData, error) {
form := url.Values{}
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
form.Set("client_id", iFlowOAuthClientID)
form.Set("client_secret", getIFlowClientSecret())
req, err := ia.newTokenRequest(ctx, form)
if err != nil {
return nil, err
}
return ia.doTokenRequest(ctx, req)
}
func (ia *IFlowAuth) newTokenRequest(ctx context.Context, form url.Values) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, iFlowOAuthTokenEndpoint, strings.NewReader(form.Encode()))
if err != nil {
return nil, fmt.Errorf("iflow token: create request failed: %w", err)
}
basic := base64.StdEncoding.EncodeToString([]byte(iFlowOAuthClientID + ":" + getIFlowClientSecret()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Basic "+basic)
return req, nil
}
func (ia *IFlowAuth) doTokenRequest(ctx context.Context, req *http.Request) (*IFlowTokenData, error) {
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow token: request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow token: read response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow token request failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow token: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var tokenResp IFlowTokenResponse
if err = json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("iflow token: decode response failed: %w", err)
}
data := &IFlowTokenData{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
TokenType: tokenResp.TokenType,
Scope: tokenResp.Scope,
Expire: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339),
}
if tokenResp.AccessToken == "" {
log.Debug(string(body))
return nil, fmt.Errorf("iflow token: missing access token in response")
}
info, errAPI := ia.FetchUserInfo(ctx, tokenResp.AccessToken)
if errAPI != nil {
return nil, fmt.Errorf("iflow token: fetch user info failed: %w", errAPI)
}
if strings.TrimSpace(info.APIKey) == "" {
return nil, fmt.Errorf("iflow token: empty api key returned")
}
email := strings.TrimSpace(info.Email)
if email == "" {
email = strings.TrimSpace(info.Phone)
}
if email == "" {
return nil, fmt.Errorf("iflow token: missing account email/phone in user info")
}
data.APIKey = info.APIKey
data.Email = email
return data, nil
}
// FetchUserInfo retrieves account metadata (including API key) for the provided access token.
func (ia *IFlowAuth) FetchUserInfo(ctx context.Context, accessToken string) (*userInfoData, error) {
if strings.TrimSpace(accessToken) == "" {
return nil, fmt.Errorf("iflow api key: access token is empty")
}
endpoint := fmt.Sprintf("%s?accessToken=%s", iFlowUserInfoEndpoint, url.QueryEscape(accessToken))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("iflow api key: create request failed: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow api key: request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow api key: read response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow api key failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow api key: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var result userInfoResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("iflow api key: decode body failed: %w", err)
}
if !result.Success {
return nil, fmt.Errorf("iflow api key: request not successful")
}
if result.Data.APIKey == "" {
return nil, fmt.Errorf("iflow api key: missing api key in response")
}
return &result.Data, nil
}
// CreateTokenStorage converts token data into persistence storage.
func (ia *IFlowAuth) CreateTokenStorage(data *IFlowTokenData) *IFlowTokenStorage {
if data == nil {
return nil
}
return &IFlowTokenStorage{
AccessToken: data.AccessToken,
RefreshToken: data.RefreshToken,
LastRefresh: time.Now().Format(time.RFC3339),
Expire: data.Expire,
APIKey: data.APIKey,
Email: data.Email,
TokenType: data.TokenType,
Scope: data.Scope,
}
}
// UpdateTokenStorage updates the persisted token storage with latest token data.
func (ia *IFlowAuth) UpdateTokenStorage(storage *IFlowTokenStorage, data *IFlowTokenData) {
if storage == nil || data == nil {
return
}
storage.AccessToken = data.AccessToken
storage.RefreshToken = data.RefreshToken
storage.LastRefresh = time.Now().Format(time.RFC3339)
storage.Expire = data.Expire
if data.APIKey != "" {
storage.APIKey = data.APIKey
}
if data.Email != "" {
storage.Email = data.Email
}
storage.TokenType = data.TokenType
storage.Scope = data.Scope
}
// IFlowTokenResponse models the OAuth token endpoint response.
type IFlowTokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
}
// IFlowTokenData captures processed token details.
type IFlowTokenData struct {
AccessToken string
RefreshToken string
TokenType string
Scope string
Expire string
APIKey string
Email string
Cookie string
}
// userInfoResponse represents the structure returned by the user info endpoint.
type userInfoResponse struct {
Success bool `json:"success"`
Data userInfoData `json:"data"`
}
type userInfoData struct {
APIKey string `json:"apiKey"`
Email string `json:"email"`
Phone string `json:"phone"`
}
// iFlowAPIKeyResponse represents the response from the API key endpoint
type iFlowAPIKeyResponse struct {
Success bool `json:"success"`
Code string `json:"code"`
Message string `json:"message"`
Data iFlowKeyData `json:"data"`
Extra interface{} `json:"extra"`
}
// iFlowKeyData contains the API key information
type iFlowKeyData struct {
HasExpired bool `json:"hasExpired"`
ExpireTime string `json:"expireTime"`
Name string `json:"name"`
APIKey string `json:"apiKey"`
APIKeyMask string `json:"apiKeyMask"`
}
// iFlowRefreshRequest represents the request body for refreshing API key
type iFlowRefreshRequest struct {
Name string `json:"name"`
}
// AuthenticateWithCookie performs authentication using browser cookies
func (ia *IFlowAuth) AuthenticateWithCookie(ctx context.Context, cookie string) (*IFlowTokenData, error) {
if strings.TrimSpace(cookie) == "" {
return nil, fmt.Errorf("iflow cookie authentication: cookie is empty")
}
// First, get initial API key information using GET request to obtain the name
keyInfo, err := ia.fetchAPIKeyInfo(ctx, cookie)
if err != nil {
return nil, fmt.Errorf("iflow cookie authentication: fetch initial API key info failed: %w", err)
}
// Refresh the API key using POST request
refreshedKeyInfo, err := ia.RefreshAPIKey(ctx, cookie, keyInfo.Name)
if err != nil {
return nil, fmt.Errorf("iflow cookie authentication: refresh API key failed: %w", err)
}
// Convert to token data format using refreshed key
data := &IFlowTokenData{
APIKey: refreshedKeyInfo.APIKey,
Expire: refreshedKeyInfo.ExpireTime,
Email: refreshedKeyInfo.Name,
Cookie: cookie,
}
return data, nil
}
// fetchAPIKeyInfo retrieves API key information using GET request with cookie
func (ia *IFlowAuth) fetchAPIKeyInfo(ctx context.Context, cookie string) (*iFlowKeyData, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, iFlowAPIKeyEndpoint, nil)
if err != nil {
return nil, fmt.Errorf("iflow cookie: create GET request failed: %w", err)
}
// Set cookie and other headers to mimic browser
req.Header.Set("Cookie", cookie)
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Site", "same-origin")
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow cookie: GET request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Handle gzip compression
var reader io.Reader = resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow cookie: create gzip reader failed: %w", err)
}
defer func() { _ = gzipReader.Close() }()
reader = gzipReader
}
body, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("iflow cookie: read GET response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow cookie GET request failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow cookie: GET request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var keyResp iFlowAPIKeyResponse
if err = json.Unmarshal(body, &keyResp); err != nil {
return nil, fmt.Errorf("iflow cookie: decode GET response failed: %w", err)
}
if !keyResp.Success {
return nil, fmt.Errorf("iflow cookie: GET request not successful: %s", keyResp.Message)
}
// Handle initial response where apiKey field might be apiKeyMask
if keyResp.Data.APIKey == "" && keyResp.Data.APIKeyMask != "" {
keyResp.Data.APIKey = keyResp.Data.APIKeyMask
}
return &keyResp.Data, nil
}
// RefreshAPIKey refreshes the API key using POST request
func (ia *IFlowAuth) RefreshAPIKey(ctx context.Context, cookie, name string) (*iFlowKeyData, error) {
if strings.TrimSpace(cookie) == "" {
return nil, fmt.Errorf("iflow cookie refresh: cookie is empty")
}
if strings.TrimSpace(name) == "" {
return nil, fmt.Errorf("iflow cookie refresh: name is empty")
}
// Prepare request body
refreshReq := iFlowRefreshRequest{
Name: name,
}
bodyBytes, err := json.Marshal(refreshReq)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: marshal request failed: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, iFlowAPIKeyEndpoint, strings.NewReader(string(bodyBytes)))
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: create POST request failed: %w", err)
}
// Set cookie and other headers to mimic browser
req.Header.Set("Cookie", cookie)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Origin", "https://platform.iflow.cn")
req.Header.Set("Referer", "https://platform.iflow.cn/")
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: POST request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Handle gzip compression
var reader io.Reader = resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: create gzip reader failed: %w", err)
}
defer func() { _ = gzipReader.Close() }()
reader = gzipReader
}
body, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: read POST response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow cookie POST request failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow cookie refresh: POST request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var keyResp iFlowAPIKeyResponse
if err = json.Unmarshal(body, &keyResp); err != nil {
return nil, fmt.Errorf("iflow cookie refresh: decode POST response failed: %w", err)
}
if !keyResp.Success {
return nil, fmt.Errorf("iflow cookie refresh: POST request not successful: %s", keyResp.Message)
}
return &keyResp.Data, nil
}
// ShouldRefreshAPIKey checks if the API key needs to be refreshed (within 2 days of expiry)
func ShouldRefreshAPIKey(expireTime string) (bool, time.Duration, error) {
if strings.TrimSpace(expireTime) == "" {
return false, 0, fmt.Errorf("iflow cookie: expire time is empty")
}
expire, err := time.Parse("2006-01-02 15:04", expireTime)
if err != nil {
return false, 0, fmt.Errorf("iflow cookie: parse expire time failed: %w", err)
}
now := time.Now()
twoDaysFromNow := now.Add(48 * time.Hour)
needsRefresh := expire.Before(twoDaysFromNow)
timeUntilExpiry := expire.Sub(now)
return needsRefresh, timeUntilExpiry, nil
}
// CreateCookieTokenStorage converts cookie-based token data into persistence storage
func (ia *IFlowAuth) CreateCookieTokenStorage(data *IFlowTokenData) *IFlowTokenStorage {
if data == nil {
return nil
}
// Only save the BXAuth field from the cookie
bxAuth := ExtractBXAuth(data.Cookie)
cookieToSave := ""
if bxAuth != "" {
cookieToSave = "BXAuth=" + bxAuth + ";"
}
return &IFlowTokenStorage{
APIKey: data.APIKey,
Email: data.Email,
Expire: data.Expire,
Cookie: cookieToSave,
LastRefresh: time.Now().Format(time.RFC3339),
Type: "iflow",
}
}
// UpdateCookieTokenStorage updates the persisted token storage with refreshed API key data
func (ia *IFlowAuth) UpdateCookieTokenStorage(storage *IFlowTokenStorage, keyData *iFlowKeyData) {
if storage == nil || keyData == nil {
return
}
storage.APIKey = keyData.APIKey
storage.Expire = keyData.ExpireTime
storage.LastRefresh = time.Now().Format(time.RFC3339)
}

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