Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27036f44a2 | ||
|
|
3f737dc3c7 | ||
|
|
23a1fa749c | ||
|
|
e01976448c | ||
|
|
6e53bdade9 | ||
|
|
7d90fda663 | ||
|
|
93a0643466 | ||
|
|
dd113e5077 | ||
|
|
e20343eeec | ||
|
|
738cd4d365 | ||
|
|
244782281c | ||
|
|
1e803c918c | ||
|
|
3bf998591e | ||
|
|
bff94bd739 | ||
|
|
4f65198207 | ||
|
|
6737add91e | ||
|
|
470a371295 | ||
|
|
8e18f36d96 | ||
|
|
baa38a6420 | ||
|
|
b7cd41110e | ||
|
|
6fe6d743bd | ||
|
|
ea371ccfc6 | ||
|
|
7b58cdc5a6 | ||
|
|
d103729baf | ||
|
|
edacca735a | ||
|
|
3d8fe7d4e9 | ||
|
|
83160e11a7 | ||
|
|
594c830a39 | ||
|
|
cea2b82ffc | ||
|
|
8f0165f743 | ||
|
|
936cb0a873 | ||
|
|
4206d57bd9 | ||
|
|
b8ffbab975 | ||
|
|
9583beadb8 | ||
|
|
4827af9b48 | ||
|
|
710a2dc3bc | ||
|
|
2125f99650 | ||
|
|
997ea17f88 | ||
|
|
ffb7ae1b41 | ||
|
|
4f32ceac9b | ||
|
|
3e8d6e3c92 | ||
|
|
0da9aa6cd3 | ||
|
|
7afc014c0e | ||
|
|
1a85ba0e17 | ||
|
|
891a52c5de | ||
|
|
f7ae19d960 | ||
|
|
ad355f75a7 | ||
|
|
48c4cbcdf7 | ||
|
|
e6ea4295ab | ||
|
|
ea41ba8980 | ||
|
|
75cf72720c | ||
|
|
58035e8499 | ||
|
|
15bd80da7c | ||
|
|
9777997886 | ||
|
|
d02a63311c | ||
|
|
5ab8b5adf3 | ||
|
|
1e48d75aa8 | ||
|
|
233eb30219 | ||
|
|
e372d2220b | ||
|
|
551c664564 | ||
|
|
21101c7a03 | ||
|
|
5099678f17 | ||
|
|
b1653fc6d0 | ||
|
|
d3aa7ece4e | ||
|
|
f2c51915f0 | ||
|
|
ecbe4424cb | ||
|
|
cae634a64f | ||
|
|
42063d9f2a | ||
|
|
33eefe2ec3 | ||
|
|
3ca0cccc75 | ||
|
|
e590a2e7c7 | ||
|
|
a1ca0ddcb8 | ||
|
|
c6661972b1 | ||
|
|
e0756a566c | ||
|
|
89bafc418c | ||
|
|
ff0dea6cd6 | ||
|
|
cb4a7e0bbf | ||
|
|
310fd1f202 | ||
|
|
2a8565467b | ||
|
|
7d1b514a2e | ||
|
|
7fdbb17d47 | ||
|
|
4511e2a589 | ||
|
|
60582b647e | ||
|
|
e663c9d395 | ||
|
|
a20c4cefdc | ||
|
|
efda335476 | ||
|
|
833a560ae1 | ||
|
|
1a3c4ec586 | ||
|
|
50b453adc0 | ||
|
|
7d70539d80 | ||
|
|
1878476f76 | ||
|
|
9c19023a39 | ||
|
|
70f292a8c8 | ||
|
|
75a9908a3b | ||
|
|
f780519ee6 | ||
|
|
7457183dd1 | ||
|
|
8822013a74 | ||
|
|
bc30977567 | ||
|
|
0fb4f42ffb | ||
|
|
d8165d05d9 | ||
|
|
0b448f7aa7 | ||
|
|
91b13504f8 | ||
|
|
ffc608b7fe | ||
|
|
9e1cd7a61d | ||
|
|
277e66c542 | ||
|
|
9a2363d6bd | ||
|
|
352095c54c | ||
|
|
009fbb2a37 | ||
|
|
7d11a35a16 | ||
|
|
9cdce5e8d8 | ||
|
|
7d9a114bf8 | ||
|
|
82f02c6d59 | ||
|
|
096daa30a7 | ||
|
|
5b11c113fb | ||
|
|
b127b674e9 | ||
|
|
6163489aca | ||
|
|
0b12eafe6c | ||
|
|
e89a0f5fcb | ||
|
|
c7d06a3ace | ||
|
|
81848357c4 | ||
|
|
74319cd89e | ||
|
|
018cba3491 | ||
|
|
a6da22f391 | ||
|
|
8ae32d440a | ||
|
|
26a17c7456 | ||
|
|
d0c29cb584 | ||
|
|
0f5836e14b | ||
|
|
e96d568671 | ||
|
|
21125722cd | ||
|
|
3e47344da9 | ||
|
|
31e52f26e8 | ||
|
|
3cf08319d4 | ||
|
|
b1a4bede65 | ||
|
|
6cfd29ff1d | ||
|
|
2874e52a2a | ||
|
|
40c46acc08 | ||
|
|
d8eb83c8fd | ||
|
|
5de9cfa8ea | ||
|
|
185dcc46dd | ||
|
|
705039b410 | ||
|
|
782e3f26a5 | ||
|
|
25e73af418 | ||
|
|
ceec470273 | ||
|
|
bbcf06f163 | ||
|
|
00c64b3bcb | ||
|
|
24467aa957 | ||
|
|
68cf672e6b | ||
|
|
d9f67d1a8a | ||
|
|
7e8863b45b | ||
|
|
2ccbba05e5 | ||
|
|
5c60aea115 | ||
|
|
0a5b2f1fc0 | ||
|
|
8dd850241a | ||
|
|
3ee272620e | ||
|
|
6a1038871f | ||
|
|
2c09998780 | ||
|
|
9c91f3c511 | ||
|
|
281ac2e0ba | ||
|
|
2e7b68922a | ||
|
|
bb562e3d36 | ||
|
|
3f8366de1a | ||
|
|
f4a2ac6962 | ||
|
|
d014612bd6 | ||
|
|
f7b02ce207 | ||
|
|
9e2f45fcf5 | ||
|
|
95eb896831 | ||
|
|
660c0f7656 | ||
|
|
aca1f54478 | ||
|
|
c10abab37c | ||
|
|
d71582d7d8 | ||
|
|
f3bc99cc35 | ||
|
|
923f3f68b7 | ||
|
|
0e03289627 | ||
|
|
7631297204 | ||
|
|
3e3d0bf933 | ||
|
|
c6d8e6abb1 | ||
|
|
9fb39ff966 | ||
|
|
e08235b4d1 | ||
|
|
7a5fd20272 | ||
|
|
b37551edd8 | ||
|
|
39c7c6760a | ||
|
|
7e13a0dfdd | ||
|
|
9394166777 | ||
|
|
a6ea590cce | ||
|
|
7329675592 | ||
|
|
cab21a5089 | ||
|
|
c4701abb00 | ||
|
|
7b3ef0ea43 | ||
|
|
5a9c652f48 | ||
|
|
715c71830e | ||
|
|
aab8294d96 | ||
|
|
59e947e8a8 | ||
|
|
2617902571 | ||
|
|
270a176925 | ||
|
|
f4e7d5b92e | ||
|
|
eb84cbe543 | ||
|
|
e71648f4b6 | ||
|
|
1b5bd183b9 | ||
|
|
095718e31e | ||
|
|
abe7597d99 | ||
|
|
01cd7942b5 | ||
|
|
b669cfa650 | ||
|
|
c53fabd3a8 | ||
|
|
4ceed0428b | ||
|
|
462856639c | ||
|
|
b75ef23d5c | ||
|
|
8e236dd69d | ||
|
|
20146a1f7d | ||
|
|
b5b6d65e79 | ||
|
|
12aa47b91c | ||
|
|
5ce65eed85 | ||
|
|
e75e5716e9 | ||
|
|
d519feeba1 | ||
|
|
f1f8e2c1a6 | ||
|
|
bd893efee9 | ||
|
|
18757ebe7c | ||
|
|
09e96a45ca | ||
|
|
8e729276b0 | ||
|
|
1a1c85f043 | ||
|
|
9e187cd08f | ||
|
|
a8c389ffa6 | ||
|
|
999529c154 | ||
|
|
355932e138 | ||
|
|
d3466b31af | ||
|
|
f19594e490 | ||
|
|
946cc75e71 | ||
|
|
93c0b8703c | ||
|
|
0dda5a01a2 | ||
|
|
572792f2c6 | ||
|
|
12ac05a22f | ||
|
|
af37fbf2e0 | ||
|
|
f52bc59b2e | ||
|
|
5cf7518f26 | ||
|
|
6767188a8e | ||
|
|
7cbbf954d6 | ||
|
|
6e8f055816 | ||
|
|
87dbbedd4b | ||
|
|
a84e59f31c | ||
|
|
ca06786892 | ||
|
|
25dd8b2087 | ||
|
|
57d5b4b1b1 | ||
|
|
f80e1bb068 | ||
|
|
d68f32f00e |
@@ -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,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.
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -6,12 +6,14 @@ on:
|
||||
- v*
|
||||
|
||||
env:
|
||||
APP_NAME: CLIProxyAPI
|
||||
DOCKERHUB_REPO: eceasy/cli-proxy-api-plus
|
||||
APP_NAME: ProxyPilot
|
||||
DOCKERHUB_REPO: ${{ secrets.DOCKERHUB_REPO || 'proxypilot/proxypilot' }}
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
# Only run if DockerHub credentials are available
|
||||
if: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
name: Publish ProxyPilot via Bun
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["ProxyPilot Release"]
|
||||
types:
|
||||
- completed
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Setup registry auth
|
||||
working-directory: bun/proxypilot
|
||||
run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
|
||||
|
||||
- name: Publish package
|
||||
working-directory: bun/proxypilot
|
||||
run: bun publish --access public
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
@@ -0,0 +1,84 @@
|
||||
name: ProxyPilot Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.os }}-${{ matrix.arch }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- os: darwin
|
||||
arch: amd64
|
||||
extension: ''
|
||||
- os: darwin
|
||||
arch: arm64
|
||||
extension: ''
|
||||
- os: linux
|
||||
arch: amd64
|
||||
extension: ''
|
||||
- os: linux
|
||||
arch: arm64
|
||||
extension: ''
|
||||
- os: windows
|
||||
arch: amd64
|
||||
extension: '.exe'
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.21'
|
||||
|
||||
- name: Remove Windows resources for non-Windows builds
|
||||
if: matrix.os != 'windows'
|
||||
run: rm -f cmd/server/*.syso
|
||||
|
||||
- name: Build binary
|
||||
env:
|
||||
GOOS: ${{ matrix.os }}
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 0
|
||||
run: |
|
||||
go build -ldflags="-s -w" -o proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }} ./cmd/server
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: proxypilot-${{ matrix.os }}-${{ matrix.arch }}
|
||||
path: proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }}
|
||||
|
||||
release:
|
||||
name: Create Release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Prepare release assets
|
||||
run: |
|
||||
mkdir -p release
|
||||
find artifacts -type f -exec cp {} release/ \;
|
||||
ls -la release/
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: release/*
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,115 @@
|
||||
name: Build Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version (e.g., 0.1.0)'
|
||||
required: true
|
||||
default: '0.1.0'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.24'
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
- name: Build WebUI
|
||||
run: |
|
||||
cd webui
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
- name: Build Windows binaries
|
||||
run: |
|
||||
mkdir -p dist
|
||||
# Build tray app (includes embedded dashboard)
|
||||
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot.exe ./cmd/cliproxytray
|
||||
|
||||
- name: Build Installer UI
|
||||
run: |
|
||||
cd installer-ui
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
- name: Copy Installer UI to cmd/installer
|
||||
run: |
|
||||
# Ensure target directory exists
|
||||
New-Item -ItemType Directory -Force -Path cmd/installer/ui | Out-Null
|
||||
# Copy built UI files
|
||||
Copy-Item -Path installer-ui/dist/* -Destination cmd/installer/ui/ -Recurse -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Create bundle for installer
|
||||
run: |
|
||||
# Create bundle directory
|
||||
New-Item -ItemType Directory -Force -Path cmd/installer/bundle | Out-Null
|
||||
# Copy files for embedding
|
||||
Copy-Item -Path dist/ProxyPilot.exe -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path config.example.yaml -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path static/icon.ico -Destination cmd/installer/bundle/
|
||||
Copy-Item -Path static/icon.png -Destination cmd/installer/bundle/
|
||||
shell: pwsh
|
||||
|
||||
- name: Build Custom Installer
|
||||
run: |
|
||||
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot-Installer.exe ./cmd/installer
|
||||
|
||||
- name: Install Inno Setup
|
||||
run: |
|
||||
choco install innosetup -y
|
||||
|
||||
- name: Generate installer branding images
|
||||
run: |
|
||||
cd installer/assets
|
||||
powershell -ExecutionPolicy Bypass -File generate-wizard-images.ps1
|
||||
|
||||
- name: Get version
|
||||
id: version
|
||||
run: |
|
||||
if ("${{ github.event.inputs.version }}" -ne "") {
|
||||
echo "VERSION=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
|
||||
} else {
|
||||
$tag = "${{ github.ref_name }}"
|
||||
$version = $tag -replace '^v', ''
|
||||
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
|
||||
}
|
||||
|
||||
- name: Build Inno Setup Installer
|
||||
run: |
|
||||
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" installer\proxypilot.iss
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-release
|
||||
path: |
|
||||
dist/ProxyPilot.exe
|
||||
dist/ProxyPilot-Installer.exe
|
||||
dist/ProxyPilot-*-Setup.exe
|
||||
|
||||
- name: Upload to Release
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: |
|
||||
dist/ProxyPilot.exe
|
||||
dist/ProxyPilot-Installer.exe
|
||||
dist/ProxyPilot-${{ steps.version.outputs.VERSION }}-Setup.exe
|
||||
config.example.yaml
|
||||
@@ -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,9 @@ docs/*
|
||||
!docs/memory.md
|
||||
!docs/proxypilot.md
|
||||
!docs/agentic-harness-demo.md
|
||||
!docs/long-context-features.md
|
||||
!docs/desktop-app-build-process.md
|
||||
!docs/cli.md
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
GEMINI.md
|
||||
@@ -48,18 +59,43 @@ GEMINI.md
|
||||
.agent/*
|
||||
.bmad/*
|
||||
_bmad/*
|
||||
.mcp/cache/
|
||||
_bmad-output/*
|
||||
.mcp/*
|
||||
.cursor/*
|
||||
|
||||
# Local settings (user-specific)
|
||||
*.local.json
|
||||
*.local.yaml
|
||||
*.local.toml
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
._*
|
||||
|
||||
# Windows artifacts
|
||||
nul
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# Backup/temp files
|
||||
*~
|
||||
*.bak
|
||||
*.tmp
|
||||
*.swp
|
||||
*.orig
|
||||
*.proxypilot-backup
|
||||
|
||||
# Test scripts
|
||||
*.ahk
|
||||
tray_click_log.txt
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
*_out.txt
|
||||
|
||||
# Added by Gemini CLI fix
|
||||
node_modules/
|
||||
dist/
|
||||
.turbo/
|
||||
.env
|
||||
|
||||
*_out.txt
|
||||
|
||||
# Added by Gemini CLI fix
|
||||
node_modules/
|
||||
dist/
|
||||
.turbo/
|
||||
.env
|
||||
build/
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -1,31 +1,235 @@
|
||||
# CLIProxyAPI Plus
|
||||
<p align="center">
|
||||
<img src="./static/icon.png" width="128" height="128" alt="ProxyPilot Logo">
|
||||
</p>
|
||||
|
||||
English | [Chinese](README_CN.md)
|
||||
<h1 align="center">ProxyPilot</h1>
|
||||
|
||||
This is the Plus version of [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI), adding support for third-party providers on top of the mainline project.
|
||||
<p align="center">
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-28a745" alt="MIT License"></a>
|
||||
<a href="https://golang.org/"><img src="https://img.shields.io/badge/Go-1.24+-00ADD8?logo=go" alt="Go Version"></a>
|
||||
<a href="https://x.com/Finessse377721"><img src="https://img.shields.io/badge/Follow-%F0%9D%95%8F%2F%40Finessse377721-1c9bf0" alt="Follow on 𝕏"></a>
|
||||
<a href="https://github.com/Finesssee/ProxyPilot"><img src="https://img.shields.io/github/stars/Finesssee/ProxyPilot.svg?style=social&label=Star%20this%20repo" alt="Star this repo"></a>
|
||||
</p>
|
||||
|
||||
All third-party provider support is maintained by community contributors; CLIProxyAPI does not provide technical support. Please contact the corresponding community maintainer if you need assistance.
|
||||
<p align="center">
|
||||
<strong>Stop juggling API keys.</strong> ProxyPilot is a powerful local API proxy that lets you use your existing Claude Code, Codex, Gemini, Kiro, and Qwen subscriptions with any AI coding tool – no separate API keys required.
|
||||
</p>
|
||||
|
||||
The Plus release stays in lockstep with the mainline features.
|
||||
<p align="center">
|
||||
Built in Go, it handles OAuth authentication, token management, and API translation automatically. One server to route them all.
|
||||
</p>
|
||||
|
||||
## Differences from the Mainline
|
||||
---
|
||||
|
||||
- Added Kiro (AWS CodeWhisperer) support (OAuth login), provided by [fuko2935](https://github.com/fuko2935/CLIProxyAPI/tree/feature/kiro-integration), [Ravens2121](https://github.com/Ravens2121/CLIProxyAPIPlus/)
|
||||
> [!TIP]
|
||||
> 📣 **Latest models supported:**
|
||||
> Claude Opus 4.5 / Sonnet 4.5 with extended thinking, GPT-5.2 / GPT-5.2 Codex, Gemini 3 Pro/Flash, and Kiro (AWS CodeWhisperer)! 🚀
|
||||
|
||||
## Contributing
|
||||
**Setup Guides:**
|
||||
- [Claude Code Setup →](docs/claude-code-local-proxy.md)
|
||||
- [Cursor IDE Setup →](docs/cursor-ide.md)
|
||||
|
||||
This project only accepts pull requests that relate to third-party provider support. Any pull requests unrelated to third-party provider support will be rejected.
|
||||
---
|
||||
|
||||
If you need to submit any non-third-party provider changes, please open them against the mainline repository.
|
||||
## Features
|
||||
|
||||
- 🎯 **10 Auth Providers** - Claude, Codex (OpenAI), Gemini, Gemini CLI, Kiro (AWS), Amazon Q CLI, Qwen, Antigravity, MiniMax, Zhipu AI
|
||||
- 🔄 **Universal API Translation** - Auto-converts between OpenAI, Anthropic, and Gemini formats
|
||||
- 🔧 **Tool Calling Repair** - Fixes tool/function call mismatches between providers automatically
|
||||
- 🧠 **Extended Thinking** - Full support for Claude and Gemini thinking models
|
||||
- 🔐 **OAuth Integration** - Browser-based login with automatic token refresh
|
||||
- 👥 **Multi-Account Support** - Round-robin distribution with automatic failover
|
||||
- ⚡ **Quota Auto-Switch** - Automatically switches to backup project/model when quota exceeded
|
||||
- 📊 **Usage Statistics** - Track requests, tokens, and errors per provider/model
|
||||
- 🧩 **Context Compression** - LLM-based summarization for long sessions (Factory.ai research)
|
||||
- 🤖 **Agentic Harness** - Guided workflow for coding agents (Anthropic research)
|
||||
- 💾 **Session Memory** - Persistent storage across conversation turns
|
||||
- 🎨 **System Tray** - Native Windows tray app for quick access
|
||||
- 📡 **60+ Management APIs** - Full control via REST endpoints
|
||||
|
||||
---
|
||||
|
||||
## Supported Providers
|
||||
|
||||
| Provider | Auth Method | Models |
|
||||
|----------|-------------|--------|
|
||||
| Claude (Anthropic) | OAuth2 / API Key | Claude Opus 4.5, Sonnet 4.5, Haiku 4.5 |
|
||||
| Codex (OpenAI) | OAuth2 / API Key | GPT-5.2, GPT-5.2 Codex |
|
||||
| Gemini | OAuth2 / API Key | Gemini 3 Pro, Gemini 3 Flash |
|
||||
| Gemini CLI | OAuth2 | Cloud Code Assist (separate quota) |
|
||||
| Kiro | OAuth2 + AWS SSO | AWS CodeWhisperer |
|
||||
| Amazon Q CLI | Import from CLI | Amazon Q Developer |
|
||||
| Qwen | OAuth2 | Qwen models |
|
||||
| Antigravity | OAuth2 | Gemini via Antigravity (separate quota) |
|
||||
| MiniMax | API Key | MiniMax M2, M2.1 models |
|
||||
| Zhipu AI | API Key | GLM-4.5, GLM-4.6, GLM-4.7 |
|
||||
| Custom | API Key | Any OpenAI-compatible endpoint |
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
### Download Pre-built Release (Recommended)
|
||||
|
||||
1. Go to the [**Releases**](https://github.com/Finesssee/ProxyPilot/releases) page
|
||||
2. Download the latest binary for your platform
|
||||
3. Run `./proxypilot`
|
||||
|
||||
### Build from Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Finesssee/ProxyPilot.git
|
||||
cd ProxyPilot
|
||||
go build -o proxypilot ./cmd/server
|
||||
./proxypilot
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### First Launch
|
||||
|
||||
1. Copy config: `cp config.example.yaml config.yaml`
|
||||
2. Run: `./proxypilot`
|
||||
3. Server starts on `http://localhost:8317`
|
||||
4. Open dashboard: `http://localhost:8317/proxypilot.html`
|
||||
|
||||
### Authentication
|
||||
|
||||
Run OAuth login for your provider:
|
||||
|
||||
```bash
|
||||
# OAuth providers (opens browser)
|
||||
./proxypilot --claude-login # Claude
|
||||
./proxypilot --codex-login # OpenAI/Codex
|
||||
./proxypilot --login # Gemini
|
||||
./proxypilot --kiro-login # Kiro (Google OAuth)
|
||||
./proxypilot --kiro-aws-login # Kiro (AWS Builder ID)
|
||||
./proxypilot --qwen-login # Qwen
|
||||
./proxypilot --antigravity-login # Antigravity
|
||||
|
||||
# Import providers (from existing CLI tools)
|
||||
./proxypilot --amazonq-import # Amazon Q CLI (run 'q login' first)
|
||||
./proxypilot --kiro-import # Kiro IDE token
|
||||
|
||||
# API key providers (prompts for key)
|
||||
./proxypilot --minimax-login # MiniMax API key
|
||||
./proxypilot --zhipu-login # Zhipu AI API key
|
||||
```
|
||||
|
||||
OAuth tokens are stored locally and auto-refreshed before expiry.
|
||||
|
||||
### 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 CLI with server and config switching |
|
||||
| `cliproxytray` | System tray app |
|
||||
|
||||
---
|
||||
|
||||
## Tool Integrations
|
||||
|
||||
Works with these AI coding tools:
|
||||
|
||||
- **Claude Code** - Auto-configure via settings.json
|
||||
- **Codex CLI** - Auto-configure via config.toml
|
||||
- **Factory Droid** - Auto-configure via settings.json
|
||||
- **Cursor IDE** - Manual endpoint configuration
|
||||
- **Continue** - Manual endpoint configuration
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- macOS, Linux, or Windows
|
||||
- Go 1.24+ (for building from source)
|
||||
|
||||
---
|
||||
|
||||
## Author
|
||||
|
||||
ProxyPilot is developed and maintained by [@Finesssee](https://github.com/Finesssee). Some contributors shown in the git history are from upstream [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) merges. Direct contributors to ProxyPilot will be listed here as the project grows.
|
||||
|
||||
---
|
||||
|
||||
## Credits
|
||||
|
||||
ProxyPilot builds upon excellent work from the open-source community:
|
||||
|
||||
- **[CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)** - The original unified proxy server that inspired this project
|
||||
- **[VibeProxy](https://github.com/automazeio/vibeproxy)** - Native macOS menu bar app showcasing clean proxy UX
|
||||
|
||||
Long-context features are inspired by research from the AI community:
|
||||
|
||||
- **[Factory.ai](https://factory.ai/news/evaluating-compression)** - Context compression techniques for long-running coding agents
|
||||
- **[Anthropic](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)** - Effective harnesses for long-running agents
|
||||
|
||||
Special thanks to these teams for sharing their work and insights.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see `LICENSE`.
|
||||
MIT License - see [LICENSE](LICENSE) for details.
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
- **Report Issues**: [GitHub Issues](https://github.com/Finesssee/ProxyPilot/issues)
|
||||
|
||||
---
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This project is intended for educational and interoperability research purposes only. It interacts with various internal or undocumented APIs (such as Google's `v1internal`) to provide compatibility layers.
|
||||
This project is for educational and interoperability research purposes. It interacts with various APIs to provide compatibility layers.
|
||||
|
||||
- **Use at your own risk.** The authors are not responsible for any consequences arising from the use of this software, including but not limited to account suspensions or service interruptions.
|
||||
- This project is **not** affiliated with, endorsed by, or associated with Google, OpenAI, Anthropic, or any other service provider mentioned.
|
||||
- Users are expected to comply with the Terms of Service of the respective platforms they connect to.
|
||||
- **Use at your own risk.** Authors are not responsible for account suspensions or service interruptions.
|
||||
- **Not affiliated** with Google, OpenAI, Anthropic, Amazon, or any other provider.
|
||||
- Users must comply with the Terms of Service of connected platforms.
|
||||
|
||||
@@ -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) 文件。
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -0,0 +1,2 @@
|
||||
.npmrc
|
||||
node_modules/
|
||||
@@ -0,0 +1,74 @@
|
||||
# proxypilot
|
||||
|
||||
ProxyPilot CLI - Includes the ProxyPilot server and configuration switcher for AI CLI agents.
|
||||
|
||||
## Features
|
||||
|
||||
- **Server**: Run the ProxyPilot proxy server locally
|
||||
- **Switch**: Switch AI CLI agents between proxy and native modes
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
bun install -g proxypilot
|
||||
```
|
||||
|
||||
Or run without installing:
|
||||
|
||||
```bash
|
||||
bunx proxypilot
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# Start the ProxyPilot server
|
||||
proxypilot server
|
||||
|
||||
# Show status of all agents
|
||||
proxypilot switch
|
||||
|
||||
# Switch Claude to proxy mode
|
||||
proxypilot switch claude proxy
|
||||
|
||||
# Switch Gemini to native mode
|
||||
proxypilot switch gemini native
|
||||
|
||||
# Show help
|
||||
proxypilot --help
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
| Agent | Command |
|
||||
|-------|---------|
|
||||
| Claude Code | `proxypilot switch claude proxy` |
|
||||
| Gemini CLI | `proxypilot switch gemini proxy` |
|
||||
| Codex CLI | `proxypilot switch codex proxy` |
|
||||
| OpenCode | `proxypilot switch opencode proxy` |
|
||||
| Factory Droid | `proxypilot switch droid proxy` |
|
||||
| Cursor | `proxypilot switch cursor proxy` |
|
||||
| Kilo Code* | `proxypilot switch kilo proxy` |
|
||||
| RooCode* | `proxypilot switch roocode proxy` |
|
||||
|
||||
\* VS Code extensions require manual configuration
|
||||
|
||||
## Modes
|
||||
|
||||
- `proxy` - Route through ProxyPilot (http://127.0.0.1:8317)
|
||||
- `native` - Use direct API access (restore original config)
|
||||
|
||||
## How It Works
|
||||
|
||||
The switcher manages config files for each agent:
|
||||
|
||||
```
|
||||
~/.claude/
|
||||
├── settings.json # Active config
|
||||
├── settings.native.json # Original/backup config
|
||||
└── settings.proxy.json # ProxyPilot config
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { spawn } from "bun";
|
||||
import { join } from "path";
|
||||
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
const binary = join(import.meta.dir, `proxypilot${ext}`);
|
||||
|
||||
const proc = spawn([binary, ...process.argv.slice(2)], {
|
||||
stdio: ["inherit", "inherit", "inherit"],
|
||||
});
|
||||
|
||||
await proc.exited;
|
||||
process.exit(proc.exitCode ?? 0);
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { $ } from "bun";
|
||||
import { existsSync, chmodSync } from "fs";
|
||||
import { join } from "path";
|
||||
|
||||
const VERSION = "0.2.0";
|
||||
const REPO = "Finesssee/ProxyPilot";
|
||||
|
||||
const PLATFORM_MAP: Record<string, string> = {
|
||||
darwin: "darwin",
|
||||
linux: "linux",
|
||||
win32: "windows",
|
||||
};
|
||||
|
||||
const ARCH_MAP: Record<string, string> = {
|
||||
x64: "amd64",
|
||||
arm64: "arm64",
|
||||
};
|
||||
|
||||
async function install() {
|
||||
const platform = PLATFORM_MAP[process.platform];
|
||||
const arch = ARCH_MAP[process.arch];
|
||||
|
||||
if (!platform || !arch) {
|
||||
console.error(`Unsupported platform: ${process.platform}-${process.arch}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ext = platform === "windows" ? ".exe" : "";
|
||||
const binaryName = `proxypilot-${platform}-${arch}${ext}`;
|
||||
const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${binaryName}`;
|
||||
|
||||
const binDir = join(import.meta.dir, "bin");
|
||||
const binPath = join(binDir, platform === "windows" ? "proxypilot.exe" : "proxypilot");
|
||||
|
||||
console.log(`Downloading proxypilot v${VERSION} for ${platform}-${arch}...`);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { redirect: "follow" });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
await Bun.write(binPath, response);
|
||||
|
||||
// Make executable on Unix
|
||||
if (platform !== "windows") {
|
||||
chmodSync(binPath, 0o755);
|
||||
}
|
||||
|
||||
console.log("proxypilot installed successfully!");
|
||||
console.log('Run "proxypilot --help" to get started.');
|
||||
} catch (err: any) {
|
||||
console.error("Failed to download proxypilot:", err.message);
|
||||
console.error(`\nYou can manually download from:\nhttps://github.com/${REPO}/releases`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
install();
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "proxypilot",
|
||||
"version": "0.2.0",
|
||||
"description": "ProxyPilot - Local API proxy for AI coding tools with CLI control",
|
||||
"bin": {
|
||||
"proxypilot": "bin/proxypilot"
|
||||
},
|
||||
"scripts": {
|
||||
"postinstall": "bun run install.ts"
|
||||
},
|
||||
"keywords": [
|
||||
"proxypilot",
|
||||
"claude",
|
||||
"gemini",
|
||||
"codex",
|
||||
"ai",
|
||||
"cli",
|
||||
"proxy",
|
||||
"config",
|
||||
"switcher"
|
||||
],
|
||||
"author": "ProxyPilot",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Finesssee/ProxyPilot"
|
||||
},
|
||||
"homepage": "https://github.com/Finesssee/ProxyPilot",
|
||||
"os": [
|
||||
"darwin",
|
||||
"linux",
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64",
|
||||
"arm64"
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -14,36 +14,73 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/getlantern/systray"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
|
||||
"github.com/jchv/go-webview2"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/proxypilotupdate"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/trayicon"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/updates"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
)
|
||||
|
||||
const autostartAppName = "ProxyPilot"
|
||||
const thinkingProxyPort = 8317
|
||||
|
||||
var assetServerURL string
|
||||
var dashboardMu sync.Mutex
|
||||
var dashboardOpen bool
|
||||
|
||||
func main() {
|
||||
var repoRoot string
|
||||
var configPath string
|
||||
var exePath string
|
||||
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
|
||||
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate logs/)")
|
||||
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
|
||||
flag.StringVar(&exePath, "exe", "", "Path to ProxyPilot Engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
|
||||
flag.Parse()
|
||||
|
||||
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
|
||||
run(repoRoot, configPath, exePath)
|
||||
repoRoot, configPath = applyDefaults(repoRoot, configPath)
|
||||
run(repoRoot, configPath)
|
||||
}
|
||||
|
||||
func run(repoRoot, configPath, exePath string) {
|
||||
func run(repoRoot, configPath string) {
|
||||
// Initialize logging
|
||||
logging.SetupBaseLogger()
|
||||
|
||||
// Load config
|
||||
cfg, err := config.LoadConfigOptional(configPath, false)
|
||||
if err == nil && cfg != nil {
|
||||
logging.ConfigureLogOutput(cfg.LoggingToFile, cfg.LogsMaxTotalSizeMB)
|
||||
util.SetLogLevel(cfg)
|
||||
}
|
||||
if cfg == nil {
|
||||
cfg = &config.Config{Port: 8318} // Default config if load fails
|
||||
}
|
||||
|
||||
// Register token store
|
||||
sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore())
|
||||
|
||||
// Register access providers
|
||||
configaccess.Register()
|
||||
|
||||
// Create embedded engine (will be used instead of desktopctl)
|
||||
engine := NewEmbeddedEngine()
|
||||
|
||||
// Get or create management password
|
||||
password, _ := desktopctl.GetManagementPassword()
|
||||
|
||||
systray.Run(func() {
|
||||
thinkingProxy := startThinkingProxy(configPath)
|
||||
thinkingProxy := startThinkingProxy(engine)
|
||||
defer thinkingProxy.Close()
|
||||
|
||||
if ico := trayicon.ProxyPilotICO(); len(ico) > 0 {
|
||||
@@ -52,99 +89,76 @@ func run(repoRoot, configPath, exePath string) {
|
||||
systray.SetTitle("ProxyPilot")
|
||||
systray.SetTooltip("ProxyPilot")
|
||||
|
||||
statusItem := systray.AddMenuItem("Status: ...", "Current status")
|
||||
// Header
|
||||
systray.AddMenuItem("ProxyPilot", "ProxyPilot").Disable()
|
||||
systray.AddSeparator()
|
||||
|
||||
// Status display item (disabled, updated dynamically)
|
||||
statusItem := systray.AddMenuItem("○ Stopped", "Current proxy status")
|
||||
statusItem.Disable()
|
||||
systray.AddSeparator()
|
||||
|
||||
openProxyUI := systray.AddMenuItem("Open Dashboard", "Open ProxyPilot Control Center")
|
||||
|
||||
// Main actions
|
||||
openDashboard := systray.AddMenuItem("Open Dashboard", "Open ProxyPilot Dashboard")
|
||||
toggleItem := systray.AddMenuItem("Start Proxy", "Start/Stop proxy")
|
||||
copyURLItem := systray.AddMenuItem("Copy API URL", "Copy http://127.0.0.1:8317/v1")
|
||||
systray.AddSeparator()
|
||||
|
||||
// Engine submenu
|
||||
engineMenu := systray.AddMenuItem("Engine", "Engine controls")
|
||||
startItem := engineMenu.AddSubMenuItem("Start", "Start the ProxyPilot engine")
|
||||
stopItem := engineMenu.AddSubMenuItem("Stop", "Stop the ProxyPilot engine")
|
||||
restartItem := engineMenu.AddSubMenuItem("Restart", "Restart the ProxyPilot engine")
|
||||
// Providers submenu
|
||||
providersMenu := systray.AddMenuItem("Providers", "Provider status")
|
||||
claudeItem := providersMenu.AddSubMenuItem("○ Claude - Inactive", "Claude provider status")
|
||||
geminiItem := providersMenu.AddSubMenuItem("○ Gemini - Inactive", "Gemini provider status")
|
||||
codexItem := providersMenu.AddSubMenuItem("○ Codex - Inactive", "Codex provider status")
|
||||
qwenItem := providersMenu.AddSubMenuItem("○ Qwen - Inactive", "Qwen provider status")
|
||||
anthropicItem := providersMenu.AddSubMenuItem("○ Anthropic - Inactive", "Anthropic provider status")
|
||||
// Disable provider items (they're informational only for now)
|
||||
claudeItem.Disable()
|
||||
geminiItem.Disable()
|
||||
codexItem.Disable()
|
||||
qwenItem.Disable()
|
||||
anthropicItem.Disable()
|
||||
|
||||
// Connect submenu (VibeProxy-style easy setup)
|
||||
connectMenu := systray.AddMenuItem("Connect", "Environment variables")
|
||||
copyAnthropicEnv := connectMenu.AddSubMenuItem("Copy ANTHROPIC_BASE_URL", "Copy export ANTHROPIC_BASE_URL=http://127.0.0.1:8317/v1")
|
||||
copyOpenAIEnv := connectMenu.AddSubMenuItem("Copy OPENAI_BASE_URL", "Copy export OPENAI_BASE_URL=http://127.0.0.1:8317/v1")
|
||||
|
||||
// Settings submenu
|
||||
settingsMenu := systray.AddMenuItem("Settings", "ProxyPilot settings")
|
||||
autoOn, _, _ := desktopctl.IsWindowsRunAutostartEnabled(autostartAppName)
|
||||
autoStartItem := settingsMenu.AddSubMenuItemCheckbox("Launch on login", "Start this tray app when you log in", autoOn)
|
||||
// Diagnostics submenu
|
||||
diagMenu := systray.AddMenuItem("Diagnostics", "Diagnostic tools")
|
||||
copyDiagItem := diagMenu.AddSubMenuItem("Copy Diagnostics", "Copy diagnostics to clipboard")
|
||||
openLogsItem := diagMenu.AddSubMenuItem("Open Logs Folder", "Open logs folder in explorer")
|
||||
openAuthItem := diagMenu.AddSubMenuItem("Open Auth Folder", "Open auth folder in explorer")
|
||||
|
||||
systray.AddSeparator()
|
||||
quitItem := systray.AddMenuItem("Quit", "Quit ProxyPilot")
|
||||
|
||||
// Auto-start proxy on launch if enabled
|
||||
autoProxyOn, _ := desktopctl.GetAutoStartProxy()
|
||||
autoStartProxyItem := settingsMenu.AddSubMenuItemCheckbox("Auto-start proxy", "Start the proxy server automatically", autoProxyOn)
|
||||
|
||||
// Tools submenu
|
||||
toolsMenu := systray.AddMenuItem("Tools", "ProxyPilot tools")
|
||||
openLogs := toolsMenu.AddSubMenuItem("Open Logs", "Open logs folder")
|
||||
copyDiagnostics := toolsMenu.AddSubMenuItem("Copy Diagnostics", "Copy a support bundle to clipboard")
|
||||
openLegacyUI := toolsMenu.AddSubMenuItem("Advanced UI", "Open management UI (advanced)")
|
||||
|
||||
// Updates submenu
|
||||
updatesMenu := systray.AddMenuItem("Updates", "Check for updates")
|
||||
checkUpdates := updatesMenu.AddSubMenuItem("Check for Updates", "Check GitHub Releases for a newer ProxyPilot")
|
||||
updateNow := updatesMenu.AddSubMenuItem("Update ProxyPilot...", "Download and run the latest installer")
|
||||
updateNow.Disable()
|
||||
|
||||
systray.AddSeparator()
|
||||
|
||||
quitItem := systray.AddMenuItem("Quit", "Quit")
|
||||
|
||||
lastErr := ""
|
||||
var (
|
||||
latestVersion string
|
||||
assetName string
|
||||
assetURL string
|
||||
)
|
||||
refresh := func() {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
title := "Stopped"
|
||||
if st.Running {
|
||||
title = fmt.Sprintf("Running (:%d)", st.Port)
|
||||
}
|
||||
if st.LastError != "" && lastErr == "" {
|
||||
lastErr = st.LastError
|
||||
}
|
||||
if lastErr != "" {
|
||||
title = title + " - " + shorten(lastErr, 80)
|
||||
}
|
||||
statusItem.SetTitle("Status: " + title)
|
||||
systray.SetTooltip("ProxyPilot - " + title)
|
||||
|
||||
if st.Running {
|
||||
startItem.Disable()
|
||||
stopItem.Enable()
|
||||
restartItem.Enable()
|
||||
} else {
|
||||
startItem.Enable()
|
||||
stopItem.Disable()
|
||||
restartItem.Disable()
|
||||
}
|
||||
}
|
||||
|
||||
refresh()
|
||||
|
||||
// Optional: auto-start the proxy server on launch.
|
||||
if autoProxyOn {
|
||||
go func() {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if st.Running {
|
||||
return
|
||||
if !engine.IsRunning() {
|
||||
engine.Start(cfg, configPath, password)
|
||||
}
|
||||
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
} else {
|
||||
lastErr = ""
|
||||
}
|
||||
refresh()
|
||||
}()
|
||||
}
|
||||
|
||||
// Update UI based on status
|
||||
refresh := func() {
|
||||
st := engine.Status()
|
||||
if st.Running {
|
||||
port := st.Port
|
||||
if port <= 0 {
|
||||
port = 8318
|
||||
}
|
||||
statusItem.SetTitle(fmt.Sprintf("● Running on :%d", port))
|
||||
systray.SetTooltip(fmt.Sprintf("ProxyPilot - Running (:%d)", port))
|
||||
toggleItem.SetTitle("Stop Proxy")
|
||||
toggleItem.SetTooltip("Stop the proxy")
|
||||
} else {
|
||||
statusItem.SetTitle("○ Stopped")
|
||||
systray.SetTooltip("ProxyPilot - Stopped")
|
||||
toggleItem.SetTitle("Start Proxy")
|
||||
toggleItem.SetTooltip("Start the proxy")
|
||||
}
|
||||
}
|
||||
refresh()
|
||||
|
||||
// Refresh status periodically
|
||||
go func() {
|
||||
t := time.NewTicker(2 * time.Second)
|
||||
defer t.Stop()
|
||||
@@ -153,155 +167,29 @@ func run(repoRoot, configPath, exePath string) {
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle clicks
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-startItem.ClickedCh:
|
||||
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
lastErr = ""
|
||||
refresh()
|
||||
case <-stopItem.ClickedCh:
|
||||
if err := desktopctl.Stop(desktopctl.StopOptions{}); err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
lastErr = ""
|
||||
refresh()
|
||||
case <-restartItem.ClickedCh:
|
||||
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
lastErr = ""
|
||||
refresh()
|
||||
case <-copyAnthropicEnv.ClickedCh:
|
||||
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
|
||||
case <-copyOpenAIEnv.ClickedCh:
|
||||
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
|
||||
case <-autoStartItem.ClickedCh:
|
||||
if autoStartItem.Checked() {
|
||||
_ = desktopctl.DisableWindowsRunAutostart(autostartAppName)
|
||||
autoStartItem.Uncheck()
|
||||
lastErr = ""
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
cmd, err := autostartCommand(repoRoot, configPath, exePath)
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
if err := desktopctl.EnableWindowsRunAutostart(autostartAppName, cmd); err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
autoStartItem.Check()
|
||||
lastErr = ""
|
||||
refresh()
|
||||
case <-autoStartProxyItem.ClickedCh:
|
||||
if autoStartProxyItem.Checked() {
|
||||
_ = desktopctl.SetAutoStartProxy(false)
|
||||
autoStartProxyItem.Uncheck()
|
||||
lastErr = ""
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
_ = desktopctl.SetAutoStartProxy(true)
|
||||
autoStartProxyItem.Check()
|
||||
lastErr = ""
|
||||
refresh()
|
||||
case <-openProxyUI.ClickedCh:
|
||||
if err := openProxyUIWithAutostart(repoRoot, configPath, exePath); err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
case <-openDashboard.ClickedCh:
|
||||
openProxyUIWithAutostart(engine, cfg, configPath, password)
|
||||
case <-toggleItem.ClickedCh:
|
||||
if engine.IsRunning() {
|
||||
engine.Stop()
|
||||
} else {
|
||||
lastErr = ""
|
||||
refresh()
|
||||
}
|
||||
case <-openLegacyUI.ClickedCh:
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
|
||||
lastErr = "proxy is not running"
|
||||
refresh()
|
||||
continue
|
||||
}
|
||||
_ = desktopctl.OpenBrowser(st.BaseURL + "/management.html?legacy=1")
|
||||
case <-openLogs.ClickedCh:
|
||||
if err := desktopctl.OpenLogsFolder(repoRoot, configPath); err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
}
|
||||
case <-copyDiagnostics.ClickedCh:
|
||||
if err := copyDiagnosticsToClipboard(configPath); err != nil {
|
||||
lastErr = err.Error()
|
||||
} else {
|
||||
lastErr = "Diagnostics copied"
|
||||
engine.Start(cfg, configPath, password)
|
||||
}
|
||||
refresh()
|
||||
case <-checkUpdates.ClickedCh:
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
rel, err := proxypilotupdate.FetchLatestRelease(ctx)
|
||||
if err != nil {
|
||||
lastErr = err.Error()
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
latestVersion = rel.Version()
|
||||
assetName, assetURL = rel.FindPreferredAsset()
|
||||
if strings.TrimSpace(assetURL) == "" {
|
||||
lastErr = "no ProxyPilot asset found in latest release"
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
// If this build is already tagged, avoid prompting unnecessarily.
|
||||
if buildinfo.Version != "" && buildinfo.Version != "dev" && strings.EqualFold(buildinfo.Version, latestVersion) {
|
||||
lastErr = "Up to date (" + latestVersion + ")"
|
||||
updateNow.Disable()
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
updateNow.SetTitle("Update ProxyPilot... (" + latestVersion + ")")
|
||||
updateNow.Enable()
|
||||
lastErr = "Update available (" + latestVersion + ")"
|
||||
refresh()
|
||||
}()
|
||||
case <-updateNow.ClickedCh:
|
||||
if strings.TrimSpace(assetURL) == "" {
|
||||
lastErr = "no update asset URL (run Check for Updates)"
|
||||
refresh()
|
||||
continue
|
||||
case <-copyURLItem.ClickedCh:
|
||||
copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
|
||||
case <-copyDiagItem.ClickedCh:
|
||||
copyDiagnosticsToClipboard(engine)
|
||||
case <-openLogsItem.ClickedCh:
|
||||
desktopctl.OpenLogsFolder(repoRoot, configPath)
|
||||
case <-openAuthItem.ClickedCh:
|
||||
if dir, err := desktopctl.AuthDirFor(configPath); err == nil {
|
||||
desktopctl.OpenFolder(dir)
|
||||
}
|
||||
go func() {
|
||||
dest := filepath.Join(os.TempDir(), "ProxyPilot-"+sanitizeFileName(latestVersion)+"-"+sanitizeFileName(assetName))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
updateNow.SetTitle("Updating...")
|
||||
lastErr = "Downloading update..."
|
||||
refresh()
|
||||
if err := proxypilotupdate.DownloadToFile(ctx, assetURL, dest); err != nil {
|
||||
lastErr = err.Error()
|
||||
updateNow.SetTitle("Update ProxyPilot...")
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
// Run installer/zip handler and exit ProxyPilot so files can be replaced.
|
||||
lastErr = "Launching installer..."
|
||||
refresh()
|
||||
_ = launchUpdate(dest)
|
||||
systray.Quit()
|
||||
}()
|
||||
case <-quitItem.ClickedCh:
|
||||
systray.Quit()
|
||||
return
|
||||
@@ -315,7 +203,7 @@ type closeFn func() error
|
||||
|
||||
func (c closeFn) Close() error { return c() }
|
||||
|
||||
func startThinkingProxy(configPath string) ioCloser {
|
||||
func startThinkingProxy(engine *EmbeddedEngine) ioCloser {
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", thinkingProxyPort))
|
||||
if err != nil {
|
||||
// Best effort: don't crash the tray app if the port is already taken.
|
||||
@@ -330,7 +218,7 @@ func startThinkingProxy(configPath string) ioCloser {
|
||||
)
|
||||
|
||||
getProxy := func() (*httputil.ReverseProxy, *url.URL) {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
st := engine.Status()
|
||||
port := st.Port
|
||||
if port <= 0 {
|
||||
port = 8318
|
||||
@@ -391,45 +279,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 +494,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 +535,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 +612,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 +622,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 +660,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) {
|
||||
|
||||
@@ -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": ""
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"
|
||||
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 194 KiB |
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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>
|
||||
|
After Width: | Height: | Size: 194 KiB |
@@ -125,10 +125,6 @@ func buildBinaries(repoRoot, binRoot string) error {
|
||||
if runtime.GOOS != "windows" {
|
||||
trayExe = filepath.Join(binRoot, "ProxyPilot")
|
||||
}
|
||||
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
|
||||
if runtime.GOOS != "windows" {
|
||||
uiExe = filepath.Join(binRoot, "ProxyPilotUI")
|
||||
}
|
||||
|
||||
if err := run(repoRoot, "go", "build", "-o", proxyExe, "./cmd/server"); err != nil {
|
||||
return err
|
||||
@@ -143,13 +139,6 @@ func buildBinaries(repoRoot, binRoot string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
if err := run(repoRoot, "go", "build", "-ldflags", "-H=windowsgui", "-o", uiExe, "./cmd/proxypilotui"); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// The UI binary is only supported on Windows for now; skip on other OSes.
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
ico := trayicon.ProxyPilotICO()
|
||||
@@ -169,7 +158,6 @@ func packageZip(repoRoot, binRoot, distRoot string) error {
|
||||
dst string
|
||||
}{
|
||||
{src: filepath.Join(binRoot, "ProxyPilot.exe"), dst: "ProxyPilot.exe"},
|
||||
{src: filepath.Join(binRoot, "ProxyPilotUI.exe"), dst: "ProxyPilotUI.exe"},
|
||||
{src: filepath.Join(binRoot, "ProxyPilot.ico"), dst: "ProxyPilot.ico"},
|
||||
{src: filepath.Join(binRoot, "proxypilot-engine.exe"), dst: "proxypilot-engine.exe"},
|
||||
// Back-compat: keep a copy under the legacy name for older launchers/scripts.
|
||||
@@ -223,14 +211,10 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
|
||||
|
||||
// Payload files
|
||||
mgrExe := filepath.Join(binRoot, "ProxyPilot.exe")
|
||||
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
|
||||
srvExe := filepath.Join(binRoot, "proxypilot-engine.exe")
|
||||
if err := copyFile(mgrExe, filepath.Join(staging, "ProxyPilot.exe")); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := copyFile(uiExe, filepath.Join(staging, "ProxyPilotUI.exe")); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := copyFile(srvExe, filepath.Join(staging, "proxypilot-engine.exe")); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -250,7 +234,6 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
|
||||
"set \"DEST=%LOCALAPPDATA%\\ProxyPilot\"\r\n" +
|
||||
"if not exist \"%DEST%\" mkdir \"%DEST%\" >nul 2>&1\r\n" +
|
||||
"copy /Y \"%SRC%ProxyPilot.exe\" \"%DEST%\\ProxyPilot.exe\" >nul\r\n" +
|
||||
"copy /Y \"%SRC%ProxyPilotUI.exe\" \"%DEST%\\ProxyPilotUI.exe\" >nul\r\n" +
|
||||
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\proxypilot-engine.exe\" >nul\r\n" +
|
||||
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\cliproxyapi-latest.exe\" >nul\r\n" +
|
||||
"if exist \"%SRC%config.example.yaml\" copy /Y \"%SRC%config.example.yaml\" \"%DEST%\\config.example.yaml\" >nul\r\n" +
|
||||
@@ -279,8 +262,8 @@ func packageSetup(repoRoot, binRoot, distRoot string) error {
|
||||
}
|
||||
// If config.example.yaml is absent, omit it to avoid IExpress build failure.
|
||||
if _, err := os.Stat(filepath.Join(staging, "config.example.yaml")); errors.Is(err, os.ErrNotExist) {
|
||||
sed = strings.ReplaceAll(sed, "%FILE3%=config.example.yaml\r\n", "")
|
||||
sed = strings.ReplaceAll(sed, "FILE3=config.example.yaml\r\n", "")
|
||||
sed = strings.ReplaceAll(sed, "%FILE2%=config.example.yaml\r\n", "")
|
||||
sed = strings.ReplaceAll(sed, "FILE2=config.example.yaml\r\n", "")
|
||||
}
|
||||
if err := os.WriteFile(sedPath, []byte(sed), 0o644); err != nil {
|
||||
return err
|
||||
@@ -334,16 +317,14 @@ SourceFiles=SourceFiles
|
||||
SourceFiles0=%s
|
||||
[SourceFiles0]
|
||||
%%FILE0%%=ProxyPilot.exe
|
||||
%%FILE1%%=ProxyPilotUI.exe
|
||||
%%FILE2%%=proxypilot-engine.exe
|
||||
%%FILE3%%=config.example.yaml
|
||||
%%FILE4%%=install.cmd
|
||||
%%FILE1%%=proxypilot-engine.exe
|
||||
%%FILE2%%=config.example.yaml
|
||||
%%FILE3%%=install.cmd
|
||||
[Strings]
|
||||
FILE0=ProxyPilot.exe
|
||||
FILE1=ProxyPilotUI.exe
|
||||
FILE2=proxypilot-engine.exe
|
||||
FILE3=config.example.yaml
|
||||
FILE4=install.cmd
|
||||
FILE1=proxypilot-engine.exe
|
||||
FILE2=config.example.yaml
|
||||
FILE3=install.cmd
|
||||
`, outEsc, stagingEsc), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
<!doctype html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>webui</title>
|
||||
<script type="module" crossorigin src="/assets/index.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index.css">
|
||||
</head>
|
||||
<body>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="pp-mgmt-key" content="">
|
||||
<title>ProxyPilot</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
<p>Run <code>npm run build</code> in the webui directory to build the dashboard.</p>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
After Width: | Height: | Size: 194 KiB |
@@ -1,753 +0,0 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/jchv/go-webview2"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/cmd/proxypilotui/assets"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var repoRoot string
|
||||
var configPath string
|
||||
var exePath string
|
||||
var url string
|
||||
var standalone bool
|
||||
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
|
||||
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
|
||||
flag.StringVar(&exePath, "exe", "", "Path to proxy engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
|
||||
flag.StringVar(&url, "url", "", "Open a specific URL in-app (advanced)")
|
||||
flag.BoolVar(&standalone, "standalone", false, "Run standalone UI without connecting to proxy server")
|
||||
flag.Parse()
|
||||
|
||||
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
|
||||
|
||||
var assetServerURL string
|
||||
if standalone {
|
||||
// Start embedded asset server
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
_ = messageBox("ProxyPilot", "Failed to start asset server: "+err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
assetServerURL = "http://" + ln.Addr().String()
|
||||
go func() {
|
||||
fsys, _ := fs.Sub(assets.FS, ".")
|
||||
http.Serve(ln, http.FileServer(http.FS(fsys)))
|
||||
}()
|
||||
} else {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running {
|
||||
_, _ = desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
st, _ = desktopctl.StatusFor(configPath)
|
||||
if st.Running {
|
||||
break
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
|
||||
_ = messageBox("ProxyPilot", "Proxy is not running.\n\nClick Start in the ProxyPilot tray menu, then try again.")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.TrimSpace(url) == "" {
|
||||
url = "control"
|
||||
}
|
||||
|
||||
var target string
|
||||
if standalone {
|
||||
if strings.EqualFold(strings.TrimSpace(url), "control") {
|
||||
target = assetServerURL + "/index.html"
|
||||
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
|
||||
target = strings.TrimSpace(url)
|
||||
} else {
|
||||
target = assetServerURL + "/index.html"
|
||||
}
|
||||
} else {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if strings.EqualFold(strings.TrimSpace(url), "control") {
|
||||
target = st.BaseURL + "/proxypilot.html"
|
||||
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
|
||||
target = strings.TrimSpace(url)
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer an in-app window (WebView2) so this behaves like a native dashboard app.
|
||||
w := webview2.NewWithOptions(webview2.WebViewOptions{
|
||||
Debug: true,
|
||||
AutoFocus: true,
|
||||
WindowOptions: webview2.WindowOptions{
|
||||
Title: "ProxyPilot",
|
||||
Width: 1200,
|
||||
Height: 850,
|
||||
Center: true,
|
||||
},
|
||||
})
|
||||
if w == nil {
|
||||
// Fallback: Edge app mode or default browser.
|
||||
if target == "" {
|
||||
if standalone {
|
||||
target = assetServerURL + "/index.html"
|
||||
} else {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
target = st.BaseURL + "/proxypilot.html"
|
||||
}
|
||||
}
|
||||
edge, err := findEdge()
|
||||
if err != nil {
|
||||
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", target).Start()
|
||||
return
|
||||
}
|
||||
_ = exec.Command(edge, "--app="+target, "--window-size=1200,850", "--lang=en-US").Start()
|
||||
return
|
||||
}
|
||||
defer w.Destroy()
|
||||
w.SetSize(1200, 850, webview2.HintNone)
|
||||
|
||||
// Bindings used by the Control Center UI.
|
||||
_ = w.Bind("pp_status", func() (map[string]any, error) {
|
||||
cur, _ := desktopctl.StatusFor(configPath)
|
||||
return map[string]any{
|
||||
"running": cur.Running,
|
||||
"port": cur.Port,
|
||||
"thinking_port": cur.ThinkingPort,
|
||||
"thinking_running": cur.ThinkingRunning,
|
||||
"base_url": cur.BaseURL,
|
||||
"last_error": cur.LastError,
|
||||
}, nil
|
||||
})
|
||||
_ = w.Bind("pp_start", func() error {
|
||||
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
return err
|
||||
})
|
||||
_ = w.Bind("pp_stop", func() error { return desktopctl.Stop(desktopctl.StopOptions{}) })
|
||||
_ = w.Bind("pp_restart", func() error {
|
||||
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
|
||||
return err
|
||||
})
|
||||
_ = w.Bind("pp_open_logs", func() error { return desktopctl.OpenLogsFolder(repoRoot, configPath) })
|
||||
_ = w.Bind("pp_open_auth_folder", func() error {
|
||||
dir, err := desktopctl.AuthDirFor(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return desktopctl.OpenFolder(dir)
|
||||
})
|
||||
_ = w.Bind("pp_open_legacy_ui", func() error {
|
||||
cur, _ := desktopctl.StatusFor(configPath)
|
||||
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
|
||||
return fmt.Errorf("proxy is not running")
|
||||
}
|
||||
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/management.html?legacy=1")
|
||||
})
|
||||
_ = w.Bind("pp_open_diagnostics", func() error {
|
||||
cur, _ := desktopctl.StatusFor(configPath)
|
||||
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
|
||||
return fmt.Errorf("proxy is not running")
|
||||
}
|
||||
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/proxypilot.html")
|
||||
})
|
||||
_ = w.Bind("pp_get_oauth_private", func() (bool, error) { return desktopctl.GetOAuthPrivate() })
|
||||
_ = w.Bind("pp_set_oauth_private", func(enabled bool) error { return desktopctl.SetOAuthPrivate(enabled) })
|
||||
_ = w.Bind("pp_oauth", func(provider string) error {
|
||||
endpoint := ""
|
||||
switch strings.ToLower(strings.TrimSpace(provider)) {
|
||||
case "antigravity":
|
||||
endpoint = "/v0/management/antigravity-auth-url"
|
||||
case "gemini-cli", "geminicli":
|
||||
endpoint = "/v0/management/gemini-cli-auth-url"
|
||||
case "codex":
|
||||
endpoint = "/v0/management/codex-auth-url"
|
||||
case "claude", "anthropic":
|
||||
endpoint = "/v0/management/anthropic-auth-url"
|
||||
case "qwen":
|
||||
endpoint = "/v0/management/qwen-auth-url"
|
||||
case "iflow":
|
||||
endpoint = "/v0/management/iflow-auth-url"
|
||||
default:
|
||||
return fmt.Errorf("unknown provider: %s", provider)
|
||||
}
|
||||
return startOAuthFlow(configPath, endpoint)
|
||||
})
|
||||
_ = w.Bind("pp_copy_diagnostics", func() error { return copyDiagnosticsToClipboard(configPath) })
|
||||
_ = w.Bind("pp_get_management_key", func() (string, error) { return desktopctl.GetManagementPassword() })
|
||||
|
||||
// Integration bindings
|
||||
_ = w.Bind("pp_get_integrations", func() ([]map[string]any, error) {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running {
|
||||
return nil, fmt.Errorf("proxy not running")
|
||||
}
|
||||
key, _ := desktopctl.GetManagementPassword()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
req, _ := http.NewRequest("GET", st.BaseURL+"/v0/management/integrations", nil)
|
||||
req.Header.Set("X-Management-Key", key)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var res struct {
|
||||
Integrations []map[string]any `json:"integrations"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.Integrations, nil
|
||||
})
|
||||
|
||||
_ = w.Bind("pp_configure_integration", func(id string) error {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running {
|
||||
return fmt.Errorf("proxy not running")
|
||||
}
|
||||
key, _ := desktopctl.GetManagementPassword()
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
req, _ := http.NewRequest("POST", st.BaseURL+"/v0/management/integrations/"+id, nil)
|
||||
req.Header.Set("X-Management-Key", key)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("failed: %s", string(b))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if target != "" {
|
||||
w.Navigate(target)
|
||||
w.Run()
|
||||
return
|
||||
}
|
||||
|
||||
w.SetHtml(controlCenterHTML())
|
||||
w.Run()
|
||||
}
|
||||
|
||||
func findEdge() (string, error) {
|
||||
if p, err := exec.LookPath("msedge.exe"); err == nil && strings.TrimSpace(p) != "" {
|
||||
return p, nil
|
||||
}
|
||||
if p, err := exec.LookPath("msedge"); err == nil && strings.TrimSpace(p) != "" {
|
||||
return p, nil
|
||||
}
|
||||
candidates := []string{
|
||||
filepath.Join(os.Getenv("ProgramFiles(x86)"), "Microsoft", "Edge", "Application", "msedge.exe"),
|
||||
filepath.Join(os.Getenv("ProgramFiles"), "Microsoft", "Edge", "Application", "msedge.exe"),
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if strings.TrimSpace(c) == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(c); err == nil {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("msedge.exe not found")
|
||||
}
|
||||
|
||||
func applyDefaults(repoRoot, configPath, exePath string) (string, string, string) {
|
||||
repoRoot = strings.TrimSpace(repoRoot)
|
||||
configPath = strings.TrimSpace(configPath)
|
||||
exePath = strings.TrimSpace(exePath)
|
||||
|
||||
exe, _ := os.Executable()
|
||||
exeDir := ""
|
||||
if strings.TrimSpace(exe) != "" {
|
||||
exeDir = filepath.Dir(filepath.Clean(exe))
|
||||
}
|
||||
|
||||
// If launched from a repo/app "bin" directory, treat its parent as the root.
|
||||
defaultRoot := exeDir
|
||||
if strings.EqualFold(filepath.Base(defaultRoot), "bin") {
|
||||
defaultRoot = filepath.Dir(defaultRoot)
|
||||
}
|
||||
|
||||
if repoRoot == "" && defaultRoot != "" {
|
||||
repoRoot = defaultRoot
|
||||
}
|
||||
|
||||
if configPath == "" && exeDir != "" {
|
||||
configPath = filepath.Join(repoRoot, "config.yaml")
|
||||
}
|
||||
|
||||
if exePath == "" && exeDir != "" {
|
||||
for _, name := range []string{"proxypilot-engine.exe", "cliproxyapi-latest.exe"} {
|
||||
cand := filepath.Join(exeDir, name)
|
||||
if _, err := os.Stat(cand); err == nil {
|
||||
exePath = cand
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return repoRoot, configPath, exePath
|
||||
}
|
||||
|
||||
func openNewWindow(repoRoot, configPath, exePath, url string) error {
|
||||
exe, err := os.Executable()
|
||||
if err != nil || strings.TrimSpace(exe) == "" {
|
||||
return desktopctl.OpenBrowser(url)
|
||||
}
|
||||
args := []string{"-url", url}
|
||||
if strings.TrimSpace(repoRoot) != "" {
|
||||
args = append(args, "-repo", repoRoot)
|
||||
}
|
||||
if strings.TrimSpace(configPath) != "" {
|
||||
args = append(args, "-config", configPath)
|
||||
}
|
||||
if strings.TrimSpace(exePath) != "" {
|
||||
args = append(args, "-exe", exePath)
|
||||
}
|
||||
return exec.Command(exe, args...).Start()
|
||||
}
|
||||
|
||||
type authURLResponse struct {
|
||||
Status string `json:"status"`
|
||||
URL string `json:"url"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func startOAuthFlow(configPath string, endpointPath string) error {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
|
||||
return fmt.Errorf("proxy is not running")
|
||||
}
|
||||
key, err := desktopctl.GetManagementPassword()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
req, err := http.NewRequest(http.MethodGet, st.BaseURL+endpointPath, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("X-Management-Key", key)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var out authURLResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
if strings.TrimSpace(out.Error) != "" {
|
||||
return fmt.Errorf("%s", out.Error)
|
||||
}
|
||||
return fmt.Errorf("auth url request failed: %s", resp.Status)
|
||||
}
|
||||
if strings.TrimSpace(out.URL) == "" {
|
||||
return fmt.Errorf("missing auth url")
|
||||
}
|
||||
|
||||
private, _ := desktopctl.GetOAuthPrivate()
|
||||
return openOAuthURL(out.URL, private)
|
||||
}
|
||||
|
||||
func openOAuthURL(url string, private bool) error {
|
||||
if !private {
|
||||
return desktopctl.OpenBrowser(url)
|
||||
}
|
||||
edge, err := findEdge()
|
||||
if err != nil {
|
||||
return desktopctl.OpenBrowser(url)
|
||||
}
|
||||
return exec.Command(edge, "--inprivate", url).Start()
|
||||
}
|
||||
|
||||
func copyDiagnosticsToClipboard(configPath string) error {
|
||||
st, _ := desktopctl.StatusFor(configPath)
|
||||
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
|
||||
return fmt.Errorf("proxy is not running")
|
||||
}
|
||||
key, err := desktopctl.GetManagementPassword()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 15 * time.Second}
|
||||
req, err := http.NewRequest(http.MethodGet, st.BaseURL+"/v0/management/proxypilot/diagnostics?lines=200", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("X-Management-Key", key)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
msg := strings.TrimSpace(string(b))
|
||||
if msg == "" {
|
||||
msg = resp.Status
|
||||
}
|
||||
return fmt.Errorf("diagnostics failed: %s", msg)
|
||||
}
|
||||
|
||||
var payload struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.TrimSpace(payload.Text) == "" {
|
||||
return fmt.Errorf("empty diagnostics")
|
||||
}
|
||||
return copyToClipboard(payload.Text)
|
||||
}
|
||||
|
||||
func copyToClipboard(text string) error {
|
||||
cmd := exec.Command("cmd", "/c", "clip")
|
||||
cmd.Stdin = strings.NewReader(text)
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func controlCenterHTML() string {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>ProxyPilot</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#0b0f17;
|
||||
--panel:#0f172a;
|
||||
--panel2:#111c33;
|
||||
--text:#e5e7eb;
|
||||
--muted:#9ca3af;
|
||||
--line:#1f2a44;
|
||||
--brand:#60a5fa;
|
||||
--good:#34d399;
|
||||
--bad:#f87171;
|
||||
--warn:#fbbf24;
|
||||
--btn:#1f2a44;
|
||||
--btn2:#243152;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
body{
|
||||
margin:0;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
|
||||
background: radial-gradient(1000px 600px at 20% 0%, rgba(96,165,250,.18), transparent 60%),
|
||||
radial-gradient(1000px 700px at 80% 10%, rgba(52,211,153,.12), transparent 55%),
|
||||
var(--bg);
|
||||
color:var(--text);
|
||||
}
|
||||
.wrap{max-width:1040px;margin:0 auto;padding:28px 22px 40px}
|
||||
.top{display:flex;gap:14px;align-items:center;justify-content:space-between;margin-bottom:18px}
|
||||
.brand{display:flex;align-items:center;gap:12px}
|
||||
.logo{
|
||||
width:42px;height:42px;border-radius:12px;
|
||||
background: linear-gradient(135deg, rgba(96,165,250,.95), rgba(34,211,238,.75));
|
||||
box-shadow: 0 10px 30px rgba(96,165,250,.18);
|
||||
}
|
||||
h1{font-size:22px;margin:0}
|
||||
.sub{font-size:13px;color:var(--muted);margin-top:3px}
|
||||
.pill{
|
||||
display:inline-flex;align-items:center;gap:8px;
|
||||
padding:8px 12px;border:1px solid var(--line);border-radius:999px;
|
||||
background: rgba(15,23,42,.65);
|
||||
font-size:13px;color:var(--muted)
|
||||
}
|
||||
.dot{width:9px;height:9px;border-radius:50%}
|
||||
.card{
|
||||
border:1px solid var(--line);
|
||||
background: linear-gradient(180deg, rgba(15,23,42,.92), rgba(15,23,42,.78));
|
||||
border-radius:16px;
|
||||
padding:16px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,.35);
|
||||
}
|
||||
.grid{display:grid;grid-template-columns:1.4fr .9fr;gap:16px}
|
||||
@media (max-width: 980px){.grid{grid-template-columns:1fr}}
|
||||
.row{display:flex;flex-wrap:wrap;gap:10px}
|
||||
button,.btn{
|
||||
appearance:none;border:1px solid var(--line);background:var(--btn);color:var(--text);
|
||||
border-radius:12px;padding:10px 12px;font-size:13px;cursor:pointer;
|
||||
transition: transform .06s ease, background .12s ease, border-color .12s ease;
|
||||
user-select:none;
|
||||
}
|
||||
button:hover{background:var(--btn2);border-color:#2c3a60}
|
||||
button:active{transform: translateY(1px)}
|
||||
button[disabled]{opacity:.45;cursor:not-allowed}
|
||||
.btnPrimary{background: rgba(96,165,250,.18);border-color: rgba(96,165,250,.45)}
|
||||
.btnPrimary:hover{background: rgba(96,165,250,.25);border-color: rgba(96,165,250,.65)}
|
||||
.btnDanger{background: rgba(248,113,113,.14);border-color: rgba(248,113,113,.4)}
|
||||
.btnDanger:hover{background: rgba(248,113,113,.2);border-color: rgba(248,113,113,.6)}
|
||||
.btnGood{background: rgba(52,211,153,.14);border-color: rgba(52,211,153,.38)}
|
||||
.btnGood:hover{background: rgba(52,211,153,.2);border-color: rgba(52,211,153,.55)}
|
||||
.sectionTitle{font-size:13px;color:var(--muted);margin:0 0 10px}
|
||||
.kv{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;font-size:13px;margin-top:8px}
|
||||
.k{color:var(--muted)}
|
||||
.v{color:var(--text);word-break:break-word}
|
||||
.note{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.4}
|
||||
.toggle{display:flex;align-items:center;gap:10px;margin-top:10px}
|
||||
input[type="checkbox"]{width:16px;height:16px}
|
||||
.toast{position:fixed;left:22px;bottom:18px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:rgba(15,23,42,.88);color:var(--text);font-size:13px;display:none;max-width: min(620px, calc(100vw - 44px));}
|
||||
.toast.show{display:block}
|
||||
.hint{font-size:12px;color:var(--muted);margin-top:8px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="top">
|
||||
<div class="brand">
|
||||
<div class="logo"></div>
|
||||
<div>
|
||||
<h1>ProxyPilot</h1>
|
||||
<div class="sub">Local proxy controller + dashboard (Windows)</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pill" id="statusPill">
|
||||
<span class="dot" id="statusDot" style="background: var(--warn)"></span>
|
||||
<span id="statusText">Checking…</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card">
|
||||
<div class="sectionTitle">Engine</div>
|
||||
<div class="row">
|
||||
<button class="btnGood" id="startBtn">Start</button>
|
||||
<button class="btnDanger" id="stopBtn">Stop</button>
|
||||
<button id="restartBtn">Restart</button>
|
||||
<button class="btnPrimary" id="diagBtn">Open Diagnostics</button>
|
||||
<button id="legacyBtn">Advanced UI</button>
|
||||
</div>
|
||||
<div class="kv">
|
||||
<div class="k">Base URL</div><div class="v" id="baseUrl">-</div>
|
||||
<div class="k">Port</div><div class="v" id="port">-</div>
|
||||
<div class="k">Thinking Port</div><div class="v" id="thinkingPort">-</div>
|
||||
<div class="k">Last error</div><div class="v" id="lastErr">-</div>
|
||||
</div>
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button id="logsBtn">Open Logs Folder</button>
|
||||
<button id="authBtn">Open Auth Folder</button>
|
||||
<button id="copyDiagBtn">Copy Diagnostics</button>
|
||||
</div>
|
||||
<div class="toggle">
|
||||
<input id="privateOAuth" type="checkbox" />
|
||||
<label for="privateOAuth">Open OAuth in a private (InPrivate) window</label>
|
||||
</div>
|
||||
<div class="note">
|
||||
Tip: keep the tray menu minimal — use this Control Center for day-to-day actions.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="sectionTitle">Logins</div>
|
||||
<div class="row">
|
||||
<button id="oauthAntigravity">Antigravity</button>
|
||||
<button id="oauthGeminiCli">Gemini CLI</button>
|
||||
<button id="oauthCodex">Codex</button>
|
||||
<button id="oauthClaude">Claude</button>
|
||||
<button id="oauthQwen">Qwen</button>
|
||||
<button id="oauthIflow">iFlow</button>
|
||||
</div>
|
||||
<div class="hint">These open the provider login flow in your browser and save auth files for ProxyPilot.</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="grid-column: 1 / -1">
|
||||
<div class="sectionTitle">Integrations</div>
|
||||
<div class="row" id="integrationsList">
|
||||
<div style="color:var(--muted);font-size:13px">Loading integrations...</div>
|
||||
</div>
|
||||
<div class="note">
|
||||
Automatically configure local tools to use ProxyPilot.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="grid-column: 1 / -1">
|
||||
<div class="sectionTitle">Live Logs</div>
|
||||
<div id="logContent" style="height:240px;overflow-y:auto;background:rgba(0,0,0,.3);padding:10px;font-family:monospace;font-size:12px;border-radius:8px;border:1px solid var(--line);white-space:pre-wrap;color:var(--muted)">Waiting for logs...</div>
|
||||
<div class="row" style="margin-top:10px">
|
||||
<button id="toggleLogsBtn">Pause Updates</button>
|
||||
<button id="clearLogsBtn">Clear View</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let logPaused = false;
|
||||
const toast = (msg) => {
|
||||
const el = $('toast');
|
||||
el.textContent = msg;
|
||||
el.classList.add('show');
|
||||
clearTimeout(window.__toastTimer);
|
||||
window.__toastTimer = setTimeout(()=> el.classList.remove('show'), 2400);
|
||||
};
|
||||
|
||||
const setRunningUI = (running) => {
|
||||
$('startBtn').disabled = !!running;
|
||||
$('stopBtn').disabled = !running;
|
||||
$('restartBtn').disabled = !running;
|
||||
$('diagBtn').disabled = !running;
|
||||
$('legacyBtn').disabled = !running;
|
||||
const dot = $('statusDot');
|
||||
dot.style.background = running ? 'var(--good)' : 'var(--warn)';
|
||||
if(running) refreshIntegrations();
|
||||
};
|
||||
|
||||
async function refreshStatus() {
|
||||
try{
|
||||
const s = await window.pp_status();
|
||||
$('baseUrl').textContent = s.base_url || '-';
|
||||
$('port').textContent = s.port ? String(s.port) : '-';
|
||||
|
||||
const tp = $('thinkingPort');
|
||||
if (s.thinking_port) {
|
||||
tp.textContent = s.thinking_port + (s.thinking_running ? ' (Active)' : ' (Inactive)');
|
||||
tp.style.color = s.thinking_running ? 'var(--good)' : 'var(--muted)';
|
||||
} else {
|
||||
tp.textContent = '-';
|
||||
tp.style.color = 'var(--muted)';
|
||||
}
|
||||
|
||||
$('lastErr').textContent = (s.last_error && s.last_error.trim()) ? s.last_error : '-';
|
||||
$('statusText').textContent = s.running ? ('Running (:' + s.port + ')') : 'Stopped';
|
||||
setRunningUI(!!s.running);
|
||||
if(!logPaused && s.running) refreshLogs();
|
||||
}catch(e){
|
||||
$('statusText').textContent = 'Error';
|
||||
$('lastErr').textContent = (e && e.message) ? e.message : String(e);
|
||||
setRunningUI(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshLogs() {
|
||||
const logEl = $('logContent');
|
||||
const key = await window.pp_get_management_key();
|
||||
const s = await window.pp_status();
|
||||
if(!s.base_url) return;
|
||||
try {
|
||||
const resp = await fetch(s.base_url + '/v0/management/proxypilot/logs/tail?file=stdout&lines=50', {
|
||||
headers: { 'X-Management-Key': key }
|
||||
});
|
||||
const data = await resp.json();
|
||||
if(data.lines) {
|
||||
logEl.textContent = data.lines.join('\n');
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
async function refreshIntegrations() {
|
||||
const list = $('integrationsList');
|
||||
try {
|
||||
const items = await window.pp_get_integrations();
|
||||
if(!items || items.length === 0) {
|
||||
list.innerHTML = '<div style="color:var(--muted);font-size:13px">No integrations available</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = '';
|
||||
items.forEach(i => {
|
||||
const btn = document.createElement('button');
|
||||
btn.className = i.configured ? 'btnGood' : 'btn';
|
||||
btn.textContent = i.name + (i.configured ? ' (Active)' : '');
|
||||
btn.onclick = async () => {
|
||||
try {
|
||||
await window.pp_configure_integration(i.id);
|
||||
toast('Configured ' + i.name);
|
||||
refreshIntegrations();
|
||||
} catch(e) { toast(e.message||String(e)); }
|
||||
};
|
||||
if(!i.installed) {
|
||||
btn.disabled = true;
|
||||
btn.textContent += ' (Not Installed)';
|
||||
}
|
||||
list.appendChild(btn);
|
||||
});
|
||||
} catch(e) {
|
||||
// quiet fail if proxy not ready
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
try{
|
||||
const priv = await window.pp_get_oauth_private();
|
||||
$('privateOAuth').checked = !!priv;
|
||||
}catch(e){}
|
||||
await refreshStatus();
|
||||
setInterval(refreshStatus, 1200);
|
||||
}
|
||||
|
||||
$('startBtn').addEventListener('click', async () => { try{ await window.pp_start(); toast('Started'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
|
||||
$('stopBtn').addEventListener('click', async () => { try{ await window.pp_stop(); toast('Stopped'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
|
||||
$('restartBtn').addEventListener('click', async () => { try{ await window.pp_restart(); toast('Restarted'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
|
||||
$('logsBtn').addEventListener('click', async () => { try{ await window.pp_open_logs(); toast('Opened logs'); }catch(e){ toast(e.message||String(e)); } });
|
||||
$('authBtn').addEventListener('click', async () => { try{ await window.pp_open_auth_folder(); toast('Opened auth folder'); }catch(e){ toast(e.message||String(e)); } });
|
||||
$('copyDiagBtn').addEventListener('click', async () => { try{ await window.pp_copy_diagnostics(); toast('Copied'); }catch(e){ toast(e.message||String(e)); } });
|
||||
$('diagBtn').addEventListener('click', async () => { try{ await window.pp_open_diagnostics(); }catch(e){ toast(e.message||String(e)); } });
|
||||
$('legacyBtn').addEventListener('click', async () => { try{ await window.pp_open_legacy_ui(); }catch(e){ toast(e.message||String(e)); } });
|
||||
|
||||
$('toggleLogsBtn').addEventListener('click', () => {
|
||||
logPaused = !logPaused;
|
||||
$('toggleLogsBtn').textContent = logPaused ? 'Resume Updates' : 'Pause Updates';
|
||||
});
|
||||
$('clearLogsBtn').addEventListener('click', () => { $('logContent').textContent = ''; });
|
||||
|
||||
$('privateOAuth').addEventListener('change', async (ev) => {
|
||||
try{ await window.pp_set_oauth_private(!!ev.target.checked); toast('Saved'); }catch(e){ toast(e.message||String(e)); }
|
||||
});
|
||||
|
||||
const oauth = (provider) => async () => { try{ await window.pp_oauth(provider); toast('Opened login'); }catch(e){ toast(e.message||String(e)); } };
|
||||
$('oauthAntigravity').addEventListener('click', oauth('antigravity'));
|
||||
$('oauthGeminiCli').addEventListener('click', oauth('gemini-cli'));
|
||||
$('oauthCodex').addEventListener('click', oauth('codex'));
|
||||
$('oauthClaude').addEventListener('click', oauth('claude'));
|
||||
$('oauthQwen').addEventListener('click', oauth('qwen'));
|
||||
$('oauthIflow').addEventListener('click', oauth('iflow'));
|
||||
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
func messageBox(title, text string) error {
|
||||
user32 := syscall.NewLazyDLL("user32.dll")
|
||||
proc := user32.NewProc("MessageBoxW")
|
||||
t, _ := syscall.UTF16PtrFromString(title)
|
||||
m, _ := syscall.UTF16PtrFromString(text)
|
||||
// MB_OK | MB_ICONERROR
|
||||
_, _, err := proc.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), 0x00000000|0x00000010)
|
||||
if err == syscall.Errno(0) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -19,17 +19,20 @@ import (
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/cmd"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/store"
|
||||
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/tui"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -67,12 +70,11 @@ func main() {
|
||||
fmt.Printf("ProxyPilot Engine Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
|
||||
|
||||
// Command-line flags to control the application's behavior.
|
||||
var tuiMode bool
|
||||
var login bool
|
||||
var codexLogin bool
|
||||
var claudeLogin bool
|
||||
var qwenLogin bool
|
||||
var iflowLogin bool
|
||||
var iflowCookie bool
|
||||
var noBrowser bool
|
||||
var antigravityLogin bool
|
||||
var kiroLogin bool
|
||||
@@ -80,7 +82,22 @@ func main() {
|
||||
var kiroAWSLogin bool
|
||||
var kiroAWSAuthCode bool
|
||||
var kiroImport bool
|
||||
var amazonqImport bool
|
||||
var minimaxLogin bool
|
||||
var zhipuLogin bool
|
||||
// var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded
|
||||
var detectAgents bool
|
||||
var setupClaude bool
|
||||
var setupCodex bool
|
||||
var setupDroid bool
|
||||
var setupOpenCode bool
|
||||
var setupGemini bool
|
||||
var setupCursor bool
|
||||
var setupKilo bool
|
||||
var setupRooCode bool
|
||||
var setupAll bool
|
||||
var switchAgent string
|
||||
var switchMode string
|
||||
var projectID string
|
||||
var vertexImport string
|
||||
var configPath string
|
||||
@@ -89,12 +106,12 @@ func main() {
|
||||
var useIncognito bool
|
||||
|
||||
// Define command-line flags for different operation modes.
|
||||
flag.BoolVar(&tuiMode, "tui", false, "Launch interactive TUI mode")
|
||||
flag.BoolVar(&tuiMode, "i", false, "Launch interactive TUI mode (shorthand for --tui)")
|
||||
flag.BoolVar(&login, "login", false, "Login Google Account")
|
||||
flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
|
||||
flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
|
||||
flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth")
|
||||
flag.BoolVar(&iflowLogin, "iflow-login", false, "Login to iFlow using OAuth")
|
||||
flag.BoolVar(&iflowCookie, "iflow-cookie", false, "Login to iFlow using Cookie")
|
||||
flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
|
||||
flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)")
|
||||
flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)")
|
||||
@@ -104,7 +121,22 @@ func main() {
|
||||
flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)")
|
||||
flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)")
|
||||
flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)")
|
||||
flag.BoolVar(&amazonqImport, "amazonq-import", false, "Import Amazon Q CLI token from SQLite database")
|
||||
flag.BoolVar(&minimaxLogin, "minimax-login", false, "Add MiniMax API key")
|
||||
flag.BoolVar(&zhipuLogin, "zhipu-login", false, "Add Zhipu AI API key")
|
||||
// GitHub Copilot login removed
|
||||
flag.BoolVar(&detectAgents, "detect-agents", false, "Detect installed CLI agents")
|
||||
flag.BoolVar(&setupClaude, "setup-claude", false, "Configure Claude Code to use ProxyPilot")
|
||||
flag.BoolVar(&setupCodex, "setup-codex", false, "Configure Codex CLI to use ProxyPilot")
|
||||
flag.BoolVar(&setupDroid, "setup-droid", false, "Configure Factory Droid to use ProxyPilot")
|
||||
flag.BoolVar(&setupOpenCode, "setup-opencode", false, "Configure OpenCode to use ProxyPilot")
|
||||
flag.BoolVar(&setupGemini, "setup-gemini", false, "Configure Gemini CLI to use ProxyPilot")
|
||||
flag.BoolVar(&setupCursor, "setup-cursor", false, "Configure Cursor to use ProxyPilot")
|
||||
flag.BoolVar(&setupKilo, "setup-kilo", false, "Configure Kilo Code CLI to use ProxyPilot")
|
||||
flag.BoolVar(&setupRooCode, "setup-roocode", false, "Configure RooCode (VS Code) to use ProxyPilot")
|
||||
flag.BoolVar(&setupAll, "setup-all", false, "Configure all detected CLI agents (with backup)")
|
||||
flag.StringVar(&switchAgent, "switch", "", "Switch agent config mode (e.g., --switch claude)")
|
||||
flag.StringVar(&switchMode, "mode", "", "Switch mode: proxy, native, or status (default: status)")
|
||||
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
|
||||
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
|
||||
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
|
||||
@@ -137,6 +169,37 @@ func main() {
|
||||
})
|
||||
}
|
||||
|
||||
// Check for subcommand-style switch command before flag.Parse()
|
||||
// Supports: proxypilot switch [agent] [mode]
|
||||
// agent can be: claude, gemini, codex, opencode, droid, cursor
|
||||
// mode can be: proxy, native, status (default if omitted)
|
||||
var subcommandSwitch bool
|
||||
args := os.Args[1:]
|
||||
if len(args) > 0 && args[0] == "switch" {
|
||||
subcommandSwitch = true
|
||||
switchArgs := args[1:]
|
||||
// Filter out any flags like --status from positional args
|
||||
var positionalArgs []string
|
||||
for _, arg := range switchArgs {
|
||||
if arg == "--status" {
|
||||
switchMode = "status"
|
||||
} else if !strings.HasPrefix(arg, "-") {
|
||||
positionalArgs = append(positionalArgs, arg)
|
||||
}
|
||||
}
|
||||
// Parse positional arguments: [agent] [mode]
|
||||
if len(positionalArgs) >= 1 {
|
||||
switchAgent = positionalArgs[0]
|
||||
}
|
||||
if len(positionalArgs) >= 2 {
|
||||
switchMode = positionalArgs[1]
|
||||
}
|
||||
// Default mode to "status" if not specified
|
||||
if switchMode == "" {
|
||||
switchMode = "status"
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the command-line flags.
|
||||
flag.Parse()
|
||||
|
||||
@@ -404,8 +467,13 @@ func main() {
|
||||
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorf("failed to load config: %v", err)
|
||||
return
|
||||
// For switch command, config is optional - use defaults
|
||||
if subcommandSwitch || switchAgent != "" {
|
||||
cfg = &config.Config{Port: 8317}
|
||||
} else {
|
||||
log.Errorf("failed to load config: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if cfg == nil {
|
||||
cfg = &config.Config{}
|
||||
@@ -485,6 +553,15 @@ func main() {
|
||||
|
||||
// Handle different command modes based on the provided flags.
|
||||
|
||||
// Check if TUI mode was requested
|
||||
if tuiMode {
|
||||
if err := tui.Run(); err != nil {
|
||||
log.Errorf("TUI error: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if vertexImport != "" {
|
||||
// Handle Vertex service account import
|
||||
cmd.DoVertexImport(cfg, vertexImport)
|
||||
@@ -505,10 +582,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 +606,37 @@ func main() {
|
||||
cmd.DoKiroAWSAuthCodeLogin(cfg, options)
|
||||
} else if kiroImport {
|
||||
cmd.DoKiroImport(cfg, options)
|
||||
} else if amazonqImport {
|
||||
cmd.DoAmazonQImport(cfg, options)
|
||||
} else if minimaxLogin {
|
||||
cmd.DoMiniMaxLogin(cfg, options)
|
||||
} else if zhipuLogin {
|
||||
cmd.DoZhipuLogin(cfg, options)
|
||||
} else if detectAgents {
|
||||
cmd.DoDetectAgents()
|
||||
} else if setupClaude {
|
||||
cmd.DoSetupClaude(cfg)
|
||||
} else if setupCodex {
|
||||
cmd.DoSetupCodex(cfg)
|
||||
} else if setupDroid {
|
||||
cmd.DoSetupDroid(cfg)
|
||||
} else if setupOpenCode {
|
||||
cmd.DoSetupOpenCode(cfg)
|
||||
} else if setupGemini {
|
||||
cmd.DoSetupGeminiCLI(cfg)
|
||||
} else if setupCursor {
|
||||
cmd.DoSetupCursor(cfg)
|
||||
} else if setupKilo {
|
||||
cmd.DoSetupKiloCode(cfg)
|
||||
} else if setupRooCode {
|
||||
cmd.DoSetupRooCode(cfg)
|
||||
} else if setupAll {
|
||||
cmd.DoSetupAll(cfg)
|
||||
} else if subcommandSwitch || switchAgent != "" || switchMode != "" {
|
||||
// Handle switch command:
|
||||
// - Subcommand style: proxypilot switch claude proxy
|
||||
// - Flag style: proxypilot --switch claude --mode proxy
|
||||
cmd.DoSwitch(cfg, switchAgent, switchMode)
|
||||
} else {
|
||||
// In cloud deploy mode without config file, just wait for shutdown signals
|
||||
if isCloudDeploy && !configFileExists {
|
||||
@@ -540,8 +644,33 @@ func main() {
|
||||
cmd.WaitForCloudDeploy()
|
||||
return
|
||||
}
|
||||
|
||||
// Show hint about TUI mode when running interactively without flags
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
fmt.Println("Hint: Run with --tui or -i flag for interactive mode")
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// Start the main proxy service
|
||||
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
||||
cmd.StartService(cfg, configFilePath, password)
|
||||
// Auto-generate management password if not provided
|
||||
// This enables browser-based webui access without requiring the -password flag
|
||||
autoGenPassword := false
|
||||
if password == "" {
|
||||
if pw, err := desktopctl.GetManagementPassword(); err == nil {
|
||||
password = pw
|
||||
autoGenPassword = true
|
||||
log.Info("using auto-generated management password for webui access")
|
||||
} else {
|
||||
log.Warnf("failed to get management password: %v (webui may require manual authentication)", err)
|
||||
}
|
||||
}
|
||||
// Use standalone mode (no keep-alive shutdown) when password was auto-generated
|
||||
// Keep-alive shutdown is only needed when the tray app spawns the server as subprocess
|
||||
if autoGenPassword {
|
||||
cmd.StartServiceStandalone(cfg, configFilePath, password)
|
||||
} else {
|
||||
cmd.StartService(cfg, configFilePath, password)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": ""
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# ProxyPilot CLI
|
||||
|
||||
**proxypilot** is the unified command-line interface for the ProxyPilot local AI proxy. It provides both **server** functionality (running the proxy server) and **switch** functionality (toggling AI agents between proxy mode and native mode).
|
||||
|
||||
## Installation
|
||||
|
||||
### Via bun (recommended)
|
||||
|
||||
```bash
|
||||
bun install -g proxypilot
|
||||
```
|
||||
|
||||
### Via npm
|
||||
|
||||
```bash
|
||||
npm install -g proxypilot
|
||||
```
|
||||
|
||||
### Via Go
|
||||
|
||||
```bash
|
||||
go install github.com/Finesssee/ProxyPilot/cmd/server@latest
|
||||
```
|
||||
|
||||
### Manual Download
|
||||
|
||||
Download pre-built binaries from [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases).
|
||||
|
||||
Available binaries:
|
||||
- `proxypilot-darwin-amd64` - macOS Intel
|
||||
- `proxypilot-darwin-arm64` - macOS Apple Silicon
|
||||
- `proxypilot-linux-amd64` - Linux x64
|
||||
- `proxypilot-linux-arm64` - Linux ARM64
|
||||
- `proxypilot-windows-amd64.exe` - Windows x64
|
||||
|
||||
## Server Mode
|
||||
|
||||
Run ProxyPilot as a local proxy server:
|
||||
|
||||
```bash
|
||||
proxypilot # Start server on default port (8317)
|
||||
proxypilot -config /path/to/config # Use custom config file
|
||||
```
|
||||
|
||||
### Server Features
|
||||
|
||||
- Routes AI requests through configured providers
|
||||
- Automatic model aliasing and translation
|
||||
- OAuth login helpers for various providers
|
||||
- Agent configuration management
|
||||
|
||||
### Login Commands
|
||||
|
||||
```bash
|
||||
proxypilot --login # Login to Google Account (Gemini)
|
||||
proxypilot --codex-login # Login to Codex using OAuth
|
||||
proxypilot --claude-login # Login to Claude using OAuth
|
||||
proxypilot --qwen-login # Login to Qwen using OAuth
|
||||
proxypilot --antigravity-login # Login to Antigravity using OAuth
|
||||
proxypilot --kiro-login # Login to Kiro using Google OAuth
|
||||
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID
|
||||
proxypilot --minimax-login # Add MiniMax API key
|
||||
proxypilot --zhipu-login # Add Zhipu AI API key
|
||||
```
|
||||
|
||||
### Login Options
|
||||
|
||||
```bash
|
||||
--no-browser # Don't open browser automatically for OAuth
|
||||
--incognito # Use incognito/private mode (useful for multiple accounts)
|
||||
--no-incognito # Force disable incognito mode
|
||||
```
|
||||
|
||||
### Import Commands
|
||||
|
||||
```bash
|
||||
proxypilot --vertex-import <file> # Import Vertex service account key JSON
|
||||
proxypilot --kiro-import # Import Kiro token from Kiro IDE
|
||||
proxypilot --amazonq-import # Import Amazon Q CLI token
|
||||
```
|
||||
|
||||
## Agent Configuration
|
||||
|
||||
ProxyPilot can automatically configure AI CLI tools to use the proxy.
|
||||
|
||||
### Detect Installed Agents
|
||||
|
||||
```bash
|
||||
proxypilot --detect-agents
|
||||
```
|
||||
|
||||
Example output:
|
||||
```
|
||||
Detecting installed CLI agents...
|
||||
|
||||
Claude Code: [+] Installed
|
||||
Binary: /usr/local/bin/claude
|
||||
Config: ~/.claude/settings.json
|
||||
Codex CLI: [+] Installed
|
||||
Binary: /usr/local/bin/codex
|
||||
Config: ~/.codex
|
||||
Gemini CLI: [-] Not found
|
||||
```
|
||||
|
||||
### Setup Commands
|
||||
|
||||
```bash
|
||||
proxypilot --setup-all # Configure all detected agents
|
||||
proxypilot --setup-claude # Configure Claude Code
|
||||
proxypilot --setup-codex # Configure Codex CLI
|
||||
proxypilot --setup-droid # Configure Factory Droid
|
||||
proxypilot --setup-opencode # Configure OpenCode
|
||||
proxypilot --setup-gemini # Configure Gemini CLI
|
||||
proxypilot --setup-cursor # Configure Cursor
|
||||
proxypilot --setup-kilo # Configure Kilo Code CLI
|
||||
proxypilot --setup-roocode # Configure RooCode (VS Code)
|
||||
```
|
||||
|
||||
## Switch Mode
|
||||
|
||||
Switch AI agents between proxy mode (through ProxyPilot) and native mode (direct API access). Think of it like `nvm` for Node versions, but for AI agent configurations.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
proxypilot --switch <agent> # Show status of specific agent
|
||||
proxypilot --switch <agent> --mode proxy # Switch agent to proxy mode
|
||||
proxypilot --switch <agent> --mode native # Switch agent to native mode
|
||||
proxypilot --switch <agent> --mode status # Show current mode (default)
|
||||
```
|
||||
|
||||
### Supported Agents
|
||||
|
||||
| Agent | CLI Tool | Config Location |
|
||||
|-------|----------|-----------------|
|
||||
| `claude` | Claude Code | `~/.claude/settings.json` |
|
||||
| `gemini` | Gemini CLI | `~/.gemini/settings.json` |
|
||||
| `codex` | Codex CLI | `~/.codex/config.toml` |
|
||||
| `opencode` | OpenCode | `~/.opencode/config.json` |
|
||||
| `droid` | Factory Droid | `~/.factory/settings.json` |
|
||||
| `cursor` | Cursor IDE | `~/.cursor/config.json` |
|
||||
| `kilo` | Kilo Code* | VS Code settings |
|
||||
| `roocode` | RooCode* | VS Code settings |
|
||||
|
||||
*VS Code extensions require manual configuration - proxypilot will display instructions.
|
||||
|
||||
### Modes
|
||||
|
||||
| Mode | Description |
|
||||
|------|-------------|
|
||||
| `proxy` | Route through ProxyPilot (`http://127.0.0.1:8317`) |
|
||||
| `native` | Use direct API access (restore original config) |
|
||||
| `status` | Show current mode (default) |
|
||||
|
||||
### Examples
|
||||
|
||||
#### Check single agent status
|
||||
|
||||
```bash
|
||||
$ proxypilot --switch claude
|
||||
Claude Code: proxy
|
||||
Config: ~/.claude/settings.json
|
||||
```
|
||||
|
||||
#### Switch Claude to proxy mode
|
||||
|
||||
```bash
|
||||
$ proxypilot --switch claude --mode proxy
|
||||
Switched Claude Code to proxy mode
|
||||
Config: ~/.claude/settings.json
|
||||
Backup: ~/.claude/settings.json.native.json
|
||||
```
|
||||
|
||||
#### Switch Gemini back to native mode
|
||||
|
||||
```bash
|
||||
$ proxypilot --switch gemini --mode native
|
||||
Switched Gemini CLI to native mode
|
||||
Restored from: ~/.gemini/settings.json.native.json
|
||||
```
|
||||
|
||||
### How Switch Works
|
||||
|
||||
#### Switching to proxy mode
|
||||
|
||||
1. Backs up current config to `<config>.native.json`
|
||||
2. Updates config to point to `http://127.0.0.1:8317`
|
||||
3. Preserves all other settings (API keys, preferences, etc.)
|
||||
|
||||
#### Switching to native mode
|
||||
|
||||
1. Restores config from `<config>.native.json` backup
|
||||
2. Removes backup file after successful restore
|
||||
3. Original API keys and settings are restored
|
||||
|
||||
#### Config Detection
|
||||
|
||||
ProxyPilot automatically detects which mode an agent is in by checking:
|
||||
- If config contains `127.0.0.1:8317` -> proxy mode
|
||||
- If backup file exists -> was previously in proxy mode
|
||||
- Otherwise -> native mode
|
||||
|
||||
## Agent-Specific Notes
|
||||
|
||||
### Claude Code
|
||||
|
||||
Config location: `~/.claude/settings.json`
|
||||
|
||||
Proxy mode sets:
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8317"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Codex CLI
|
||||
|
||||
Config location: `~/.codex/config.toml`
|
||||
|
||||
Proxy mode sets:
|
||||
```toml
|
||||
[openai]
|
||||
api_base_url = "http://127.0.0.1:8317"
|
||||
```
|
||||
|
||||
### Gemini CLI
|
||||
|
||||
Config location: `~/.gemini/settings.json`
|
||||
|
||||
Proxy mode sets the API endpoint to ProxyPilot.
|
||||
|
||||
### Kilo Code & RooCode
|
||||
|
||||
These are VS Code extensions that require manual configuration:
|
||||
|
||||
1. Open VS Code Settings (Ctrl+,)
|
||||
2. Search for the extension settings
|
||||
3. Update the API base URL to `http://127.0.0.1:8317`
|
||||
|
||||
ProxyPilot will display these instructions when you run:
|
||||
```bash
|
||||
proxypilot --setup-kilo
|
||||
proxypilot --setup-roocode
|
||||
```
|
||||
|
||||
## Backup System
|
||||
|
||||
Before modifying any configuration file, ProxyPilot creates a timestamped backup:
|
||||
|
||||
```
|
||||
~/.claude/.proxypilot-backups/
|
||||
settings.json.20251228-221853.bak
|
||||
|
||||
~/.codex/.proxypilot-backups/
|
||||
config.toml.20251228-221853.bak
|
||||
```
|
||||
|
||||
### Restoring Backups
|
||||
|
||||
```bash
|
||||
# List backups
|
||||
ls ~/.claude/.proxypilot-backups/
|
||||
|
||||
# Restore
|
||||
cp ~/.claude/.proxypilot-backups/settings.json.<timestamp>.bak ~/.claude/settings.json
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Config not found"
|
||||
|
||||
The agent's config file doesn't exist. Run the agent once to create it, or create the config manually.
|
||||
|
||||
### "Failed to backup config"
|
||||
|
||||
Check file permissions on the config directory.
|
||||
|
||||
### "Already in proxy/native mode"
|
||||
|
||||
The agent is already configured for the requested mode. No changes made.
|
||||
|
||||
### CLI not detected
|
||||
|
||||
If a CLI tool is installed but not detected:
|
||||
1. Ensure the binary is in your `PATH`
|
||||
2. Try running the tool directly to verify it's installed
|
||||
3. Check if the config directory exists
|
||||
|
||||
### Configuration not applied
|
||||
|
||||
1. Restart the CLI tool after running setup
|
||||
2. Verify ProxyPilot is running on port 8317
|
||||
3. Check the backup directory for the original config
|
||||
|
||||
## Full Usage Reference
|
||||
|
||||
```bash
|
||||
proxypilot -h, --help # Show help
|
||||
proxypilot -v, --version # Show version
|
||||
|
||||
# Server
|
||||
proxypilot # Start proxy server
|
||||
proxypilot -config <path> # Use custom config file
|
||||
|
||||
# OAuth Logins
|
||||
proxypilot --login # Google/Gemini login
|
||||
proxypilot --codex-login # Codex OAuth
|
||||
proxypilot --claude-login # Claude OAuth
|
||||
proxypilot --qwen-login # Qwen OAuth
|
||||
proxypilot --antigravity-login # Antigravity OAuth
|
||||
proxypilot --kiro-login # Kiro Google OAuth
|
||||
proxypilot --kiro-aws-login # Kiro AWS Builder ID
|
||||
|
||||
# Agent Detection & Setup
|
||||
proxypilot --detect-agents # Detect installed agents
|
||||
proxypilot --setup-all # Configure all agents
|
||||
proxypilot --setup-<agent> # Configure specific agent
|
||||
|
||||
# Agent Switching
|
||||
proxypilot --switch <agent> # Show agent status
|
||||
proxypilot --switch <agent> --mode proxy # Switch to proxy
|
||||
proxypilot --switch <agent> --mode native # Switch to native
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [npm package](https://www.npmjs.com/package/proxypilot)
|
||||
- [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases)
|
||||
- [Source Code](https://github.com/Finesssee/ProxyPilot)
|
||||
@@ -0,0 +1,300 @@
|
||||
# ProxyPilot CLI + Tray Build Process
|
||||
|
||||
Documentation of the CLI and system tray application build and release process.
|
||||
|
||||
## Overview
|
||||
|
||||
ProxyPilot uses a **CLI + system tray architecture**:
|
||||
- **proxypilot.exe** - CLI executable with all proxy functionality
|
||||
- **ProxyPilot.exe** - System tray app that manages the CLI process and provides quick access to controls
|
||||
|
||||
The dashboard is accessed via web browser at `http://127.0.0.1:<port>/proxypilot.html`.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ProxyPilot System │
|
||||
│ │
|
||||
│ ┌─────────────────────┐ ┌─────────────────────────────┐ │
|
||||
│ │ ProxyPilot.exe │ │ proxypilot.exe │ │
|
||||
│ │ (System Tray) │─────▶│ (CLI / Engine) │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ - Start/Stop │ │ - Proxy Engine (port 8317) │ │
|
||||
│ │ - Open Dashboard │ │ - Web Dashboard Server │ │
|
||||
│ │ - Copy API URL │ │ - Provider Auth Mgmt │ │
|
||||
│ │ - Autostart toggle │ │ - Routing Engine │ │
|
||||
│ └─────────────────────┘ └─────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌─────────────────────┐ │
|
||||
│ │ Web Browser │ │
|
||||
│ │ (Dashboard UI) │ │
|
||||
│ │ proxypilot.html │ │
|
||||
│ └─────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### CLI + Tray Separation
|
||||
|
||||
The architecture separates concerns:
|
||||
|
||||
**proxypilot.exe (CLI)**:
|
||||
- All proxy engine functionality
|
||||
- Serves web dashboard at `/proxypilot.html`
|
||||
- Can run standalone from command line
|
||||
- Supports all CLI flags (`--help`, `--setup-claude`, etc.)
|
||||
|
||||
**ProxyPilot.exe (Tray)**:
|
||||
- Lightweight system tray wrapper
|
||||
- Manages CLI process lifecycle (start/stop/restart)
|
||||
- Opens dashboard in default browser
|
||||
- Provides quick-access menu
|
||||
|
||||
Benefits of CLI + tray architecture:
|
||||
- **Flexibility**: Use CLI directly or via tray app
|
||||
- **No WebView2 dependency**: Dashboard runs in any browser
|
||||
- **Simpler debugging**: Inspect network/console in browser DevTools
|
||||
- **Cross-platform dashboard**: Same web UI works on all platforms
|
||||
|
||||
## Build Process
|
||||
|
||||
### Prerequisites
|
||||
|
||||
```bash
|
||||
# Required tools
|
||||
go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest
|
||||
```
|
||||
|
||||
Inno Setup 6 must be installed for creating the Windows installer.
|
||||
|
||||
### Step 1: Build Web UI Assets
|
||||
|
||||
```bash
|
||||
cd webui
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
|
||||
This generates `webui/dist/` with the dashboard assets that are served by the CLI at `/proxypilot.html`.
|
||||
|
||||
### Step 2: Create Multi-Resolution Icon
|
||||
|
||||
The icon must have multiple sizes for proper Windows display (16px to 256px):
|
||||
|
||||
```python
|
||||
from PIL import Image
|
||||
|
||||
img = Image.open('static/icon.png')
|
||||
if img.mode != 'RGBA':
|
||||
img = img.convert('RGBA')
|
||||
|
||||
sizes = [(16,16), (24,24), (32,32), (48,48), (64,64), (128,128), (256,256)]
|
||||
img.save('static/icon.ico', format='ICO', sizes=sizes)
|
||||
```
|
||||
|
||||
Copy to tray icon location:
|
||||
```bash
|
||||
cp static/icon.ico internal/trayicon/icon.ico
|
||||
```
|
||||
|
||||
### Step 3: Generate Windows Resource Files
|
||||
|
||||
Generate `.syso` files for embedding icons in executables:
|
||||
|
||||
```bash
|
||||
cd cmd/cliproxytray
|
||||
goversioninfo -icon="../../static/icon.ico"
|
||||
```
|
||||
|
||||
This creates `resource.syso` files that Go automatically includes during build.
|
||||
|
||||
### Step 4: Build Executables
|
||||
|
||||
```bash
|
||||
# Build CLI executable
|
||||
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o dist/proxypilot.exe ./cmd/server
|
||||
|
||||
# Build tray app (with -H windowsgui to hide console)
|
||||
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H windowsgui" -o dist/ProxyPilot.exe ./cmd/cliproxytray
|
||||
```
|
||||
|
||||
### Step 5: Build Installer
|
||||
|
||||
```bash
|
||||
# Using Inno Setup
|
||||
"C:\Users\FSOS\AppData\Local\Programs\Inno Setup 6\ISCC.exe" installer/proxypilot.iss
|
||||
```
|
||||
|
||||
Output: `dist/ProxyPilot-0.1.0-Setup.exe`
|
||||
|
||||
## Key Files
|
||||
|
||||
### Version Info Configuration
|
||||
|
||||
**cmd/cliproxytray/versioninfo.json**
|
||||
```json
|
||||
{
|
||||
"FixedFileInfo": {
|
||||
"FileVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0},
|
||||
"ProductVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0}
|
||||
},
|
||||
"StringFileInfo": {
|
||||
"FileDescription": "ProxyPilot System Tray",
|
||||
"ProductName": "ProxyPilot",
|
||||
"ProductVersion": "0.1.0"
|
||||
},
|
||||
"IconPath": "../../static/icon.ico"
|
||||
}
|
||||
```
|
||||
|
||||
### Tray Process Manager
|
||||
|
||||
**cmd/cliproxytray/engine.go** - Manages the CLI process:
|
||||
- Spawns/stops `proxypilot.exe` subprocess
|
||||
- Monitors process health
|
||||
- Passes configuration and management password
|
||||
|
||||
### Tray Icon Embedding
|
||||
|
||||
**internal/trayicon/ico.go**
|
||||
```go
|
||||
package trayicon
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed icon.ico
|
||||
var proxyPilotICO []byte
|
||||
|
||||
func ProxyPilotICO() []byte {
|
||||
return proxyPilotICO
|
||||
}
|
||||
```
|
||||
|
||||
### Installer Script
|
||||
|
||||
**installer/proxypilot.iss** - Inno Setup script that:
|
||||
- Installs `proxypilot.exe` and `ProxyPilot.exe` to `%LOCALAPPDATA%\ProxyPilot`
|
||||
- Creates Start Menu shortcut
|
||||
- Adds optional Windows startup entry
|
||||
- Copies config.example.yaml and creates config.yaml on first install
|
||||
- Uses ProxyPilot icon for installer and shortcuts
|
||||
|
||||
## System Tray Menu
|
||||
|
||||
Simplified flat menu structure:
|
||||
|
||||
```
|
||||
┌─────────────────────┐
|
||||
│ Open Dashboard │ → Opens browser to proxypilot.html
|
||||
├─────────────────────┤
|
||||
│ Start/Stop │ → Toggle proxy engine (CLI process)
|
||||
│ Copy API URL │ → Copies http://127.0.0.1:8317/v1
|
||||
├─────────────────────┤
|
||||
│ Quit │ → Stop engine and exit
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
## Release Process
|
||||
|
||||
### Create Release on GitHub
|
||||
|
||||
```bash
|
||||
# Tag the release
|
||||
git tag v0.1.0
|
||||
git push origin v0.1.0
|
||||
|
||||
# Create release with assets
|
||||
gh release create v0.1.0 \
|
||||
--title "ProxyPilot v0.1.0" \
|
||||
--notes "Release notes here" \
|
||||
dist/ProxyPilot-0.1.0-Setup.exe \
|
||||
dist/ProxyPilot.exe \
|
||||
config.example.yaml
|
||||
```
|
||||
|
||||
### Update Existing Release
|
||||
|
||||
```bash
|
||||
# Delete old asset
|
||||
gh release delete-asset v0.1.0 ProxyPilot.exe --yes
|
||||
|
||||
# Upload new asset
|
||||
gh release upload v0.1.0 dist/ProxyPilot.exe
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Icon Not Showing in File Explorer
|
||||
|
||||
1. Ensure icon.ico has 256x256 size (required for Windows)
|
||||
2. Clear Windows icon cache: `ie4uinit.exe -show`
|
||||
3. Verify resource.syso was generated after icon update
|
||||
4. Rebuild the executable
|
||||
|
||||
### Dashboard Not Loading in Browser
|
||||
|
||||
1. Ensure the CLI process is running (check tray status)
|
||||
2. Verify the port is correct: `http://127.0.0.1:8317/proxypilot.html`
|
||||
3. Check for port conflicts with another application
|
||||
|
||||
### Tray Icon Shows Wrong Image
|
||||
|
||||
1. Check internal/trayicon/icon.ico is the correct file
|
||||
2. Rebuild the tray app to re-embed the icon
|
||||
3. Restart the application
|
||||
|
||||
### Engine Not Starting
|
||||
|
||||
1. Check if port 8317/8318 are already in use
|
||||
2. Review logs in `%LOCALAPPDATA%\ProxyPilot\logs\`
|
||||
3. Ensure config.yaml is valid YAML
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
ProxyPilot/
|
||||
├── cmd/
|
||||
│ ├── server/
|
||||
│ │ └── main.go # CLI entry point
|
||||
│ └── cliproxytray/
|
||||
│ ├── main_windows.go # Tray app entry point
|
||||
│ ├── engine.go # CLI process manager
|
||||
│ ├── versioninfo.json # Version/icon config
|
||||
│ └── resource.syso # Compiled resources
|
||||
├── internal/
|
||||
│ └── trayicon/
|
||||
│ ├── ico.go # Embeds icon.ico
|
||||
│ └── icon.ico # ProxyPilot logo (multi-res)
|
||||
├── static/
|
||||
│ ├── icon.ico # Source icon (7 sizes)
|
||||
│ └── icon.png # Original PNG logo
|
||||
├── webui/
|
||||
│ ├── src/ # React dashboard source
|
||||
│ └── dist/ # Built assets (served by CLI)
|
||||
├── installer/
|
||||
│ └── proxypilot.iss # Inno Setup script
|
||||
└── dist/ # Distribution files
|
||||
├── proxypilot.exe # CLI executable
|
||||
└── ProxyPilot.exe # Tray app
|
||||
```
|
||||
|
||||
## Version History
|
||||
|
||||
- **v0.3.0** (2025-12-30) - CLI + Tray architecture
|
||||
- Removed WebView2 dependency
|
||||
- Dashboard served by CLI, opened in browser
|
||||
- Tray app manages CLI subprocess
|
||||
- Simplified deployment and debugging
|
||||
|
||||
- **v0.2.0** (2025-12-27) - Single-binary architecture
|
||||
- Embedded proxy engine runs in-process
|
||||
- Removed separate proxypilot-engine.exe
|
||||
- Reduced total size from ~46MB to ~29MB
|
||||
- Faster startup with no process spawning
|
||||
|
||||
- **v0.1.0** (2025-12-27) - Initial release
|
||||
- System tray with minimal menu
|
||||
- Multi-resolution icon support
|
||||
- Single-file Windows installer
|
||||
@@ -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)?
|
||||
@@ -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)
|
||||
@@ -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,12 +1,12 @@
|
||||
# ProxyPilot
|
||||
|
||||
ProxyPilot is a local “AI proxy + desktop UX” for agentic CLIs (Droid/Factory, Codex CLI, Warp).
|
||||
ProxyPilot is a local AI proxy with CLI + system tray interface for agentic tools (Droid/Factory, Codex CLI, Warp).
|
||||
|
||||
This repo started as a fork of CLIProxyAPI, but is now branded as ProxyPilot. For compatibility, some internal names and headers still use `CLIProxyAPI` (e.g. `X-CLIProxyAPI-*`).
|
||||
|
||||
## What’s included
|
||||
|
||||
- ProxyPilot tray app (Windows) to start/stop/restart the proxy engine, open the dashboard, open logs, and toggle autostart.
|
||||
- ProxyPilot tray app (Windows) to start/stop/restart the proxy engine, open the web dashboard in browser, open logs, and toggle autostart.
|
||||
- Prompt-budget middleware to reduce “prompt too long” failures in strict CLIs.
|
||||
- Long-session memory with pinned state + persistent TODO (local disk).
|
||||
- Optional auth debugging and cooldown reset endpoints for local troubleshooting.
|
||||
@@ -58,7 +58,7 @@ The password is stored in the ProxyPilot UI state file:
|
||||
ProxyPilot tray app includes:
|
||||
|
||||
- `Private OAuth window` toggle (opens Edge `--inprivate` when available)
|
||||
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen, iFlow
|
||||
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen
|
||||
- `Open Auth Folder` shortcut
|
||||
|
||||
## Logs / diagnostics
|
||||
|
||||
@@ -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`).
|
||||
@@ -4,6 +4,9 @@ go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.0.6
|
||||
github.com/charmbracelet/bubbles v0.21.0
|
||||
github.com/charmbracelet/bubbletea v1.3.10
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/getlantern/systray v1.2.2
|
||||
github.com/gin-gonic/gin v1.10.1
|
||||
@@ -15,6 +18,7 @@ require (
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/klauspost/compress v1.17.4
|
||||
github.com/minio/minio-go/v7 v7.0.66
|
||||
github.com/pelletier/go-toml/v2 v2.2.2
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/stretchr/testify v1.11.1
|
||||
@@ -28,14 +32,20 @@ require (
|
||||
golang.org/x/term v0.37.0
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.42.2
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/compute/metadata v0.3.0 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/go-crypto v1.3.0 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
|
||||
github.com/charmbracelet/x/ansi v0.10.1 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
|
||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||
github.com/cloudflare/circl v1.6.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
@@ -44,6 +54,7 @@ require (
|
||||
github.com/dlclark/regexp2 v1.11.5 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 // indirect
|
||||
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 // indirect
|
||||
@@ -68,24 +79,37 @@ require (
|
||||
github.com/kevinburke/ssh_config v1.4.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/sha256-simd v1.0.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/pjbgf/sha1cd v0.5.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rs/xid v1.5.0 // indirect
|
||||
github.com/sergi/go-diff v1.4.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sync v0.18.0 // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
@@ -10,10 +10,26 @@ github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFI
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
||||
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
|
||||
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
|
||||
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
|
||||
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
|
||||
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
|
||||
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
|
||||
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
||||
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
||||
github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
|
||||
github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
|
||||
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
|
||||
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
|
||||
github.com/cloudflare/circl v1.6.1 h1:zqIqSPIndyBh1bjLVVDHMPpVKqp8Su/V+6MeDzzQBQ0=
|
||||
github.com/cloudflare/circl v1.6.1/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
@@ -33,6 +49,8 @@ github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o
|
||||
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
|
||||
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
@@ -79,9 +97,11 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
|
||||
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
@@ -119,10 +139,16 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ=
|
||||
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.66 h1:bnTOXOHjOqv/gcMuiVbN9o2ngRItvqE774dG9nq0Dzw=
|
||||
@@ -134,6 +160,14 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
|
||||
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
@@ -144,6 +178,11 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
|
||||
@@ -182,11 +221,17 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
@@ -196,6 +241,7 @@ golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -205,8 +251,8 @@ golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
||||
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=
|
||||
@@ -223,5 +269,31 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
|
||||
modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
|
||||
modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
|
||||
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.42.2 h1:7hkZUNJvJFN2PgfUdjni9Kbvd4ef4mNLOu0B9FGxM74=
|
||||
modernc.org/sqlite v1.42.2/go.mod h1:+VkC6v3pLOAE0A0uVucQEcbVW0I5nHCeDaBf+DpsQT8=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
|
||||
@@ -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>
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 194 KiB |
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
@@ -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" }]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -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"}
|
||||
@@ -0,0 +1,2 @@
|
||||
declare const _default: import("vite").UserConfig;
|
||||
export default _default;
|
||||
@@ -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
|
||||
}
|
||||
});
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
@@ -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;
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AmazonQCLIHandler handles Amazon Q CLI detection and configuration.
|
||||
// Amazon Q CLI is only available on Linux/macOS or via WSL on Windows.
|
||||
// It stores tokens in a SQLite database at ~/.local/share/amazon-q/data.sqlite3
|
||||
type AmazonQCLIHandler struct {
|
||||
// wslDistro is the WSL distribution name (Windows only)
|
||||
wslDistro string
|
||||
// wslUser is the WSL username (Windows only)
|
||||
wslUser string
|
||||
}
|
||||
|
||||
// NewAmazonQCLIHandler creates a new Amazon Q CLI handler
|
||||
func NewAmazonQCLIHandler() *AmazonQCLIHandler {
|
||||
return &AmazonQCLIHandler{}
|
||||
}
|
||||
|
||||
func (h *AmazonQCLIHandler) ID() string {
|
||||
return "amazonq-cli"
|
||||
}
|
||||
|
||||
func (h *AmazonQCLIHandler) Name() string {
|
||||
return "Amazon Q CLI"
|
||||
}
|
||||
|
||||
func (h *AmazonQCLIHandler) CanAutoConfigure() bool {
|
||||
// Amazon Q CLI uses its own auth, no configuration needed from our side
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *AmazonQCLIHandler) GetConfigPath() string {
|
||||
if runtime.GOOS == "windows" {
|
||||
// Return WSL path for display purposes
|
||||
return "\\\\wsl$\\<distro>\\home\\<user>\\.local\\share\\amazon-q\\data.sqlite3"
|
||||
}
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
return filepath.Join(homeDir, ".local", "share", "amazon-q", "data.sqlite3")
|
||||
}
|
||||
|
||||
// Detect checks if Amazon Q CLI is installed
|
||||
func (h *AmazonQCLIHandler) Detect() (bool, error) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return h.detectInWSL()
|
||||
}
|
||||
return h.detectNative()
|
||||
}
|
||||
|
||||
// detectNative checks for q CLI on Linux/macOS
|
||||
func (h *AmazonQCLIHandler) detectNative() (bool, error) {
|
||||
// Check for 'q' binary in PATH
|
||||
if _, err := exec.LookPath("q"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check common installation locations
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
locations := []string{
|
||||
filepath.Join(homeDir, ".local", "bin", "q"),
|
||||
"/usr/local/bin/q",
|
||||
}
|
||||
|
||||
for _, loc := range locations {
|
||||
if _, err := os.Stat(loc); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check for data directory (indicates Q CLI was installed and used)
|
||||
dataDir := filepath.Join(homeDir, ".local", "share", "amazon-q")
|
||||
if _, err := os.Stat(dataDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// detectInWSL checks for q CLI within WSL
|
||||
func (h *AmazonQCLIHandler) detectInWSL() (bool, error) {
|
||||
// Check if WSL is available
|
||||
if _, err := exec.LookPath("wsl"); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Get default WSL distro
|
||||
distro, err := h.getDefaultWSLDistro()
|
||||
if err != nil || distro == "" {
|
||||
return false, nil
|
||||
}
|
||||
h.wslDistro = distro
|
||||
|
||||
// Get WSL username
|
||||
user, err := h.getWSLUsername(distro)
|
||||
if err != nil || user == "" {
|
||||
return false, nil
|
||||
}
|
||||
h.wslUser = user
|
||||
|
||||
// Check for q CLI in WSL
|
||||
cmd := exec.Command("wsl", "-d", distro, "--", "which", "q")
|
||||
if err := cmd.Run(); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for common install locations in WSL
|
||||
checkCmd := exec.Command("wsl", "-d", distro, "--", "test", "-f", fmt.Sprintf("/home/%s/.local/bin/q", user))
|
||||
if err := checkCmd.Run(); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for data directory in WSL
|
||||
dataCmd := exec.Command("wsl", "-d", distro, "--", "test", "-d", fmt.Sprintf("/home/%s/.local/share/amazon-q", user))
|
||||
if err := dataCmd.Run(); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// getDefaultWSLDistro returns the default WSL distribution name
|
||||
func (h *AmazonQCLIHandler) getDefaultWSLDistro() (string, error) {
|
||||
// First try to get default distro
|
||||
cmd := exec.Command("wsl", "-l", "-q")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Parse output - first line is usually the default distro
|
||||
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
|
||||
for _, line := range lines {
|
||||
// Clean up the line (remove null bytes from UTF-16 encoding on Windows)
|
||||
line = strings.TrimSpace(line)
|
||||
line = strings.ReplaceAll(line, "\x00", "")
|
||||
if line != "" && line != "docker-desktop" && line != "docker-desktop-data" {
|
||||
return line, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("no WSL distribution found")
|
||||
}
|
||||
|
||||
// getWSLUsername returns the default username in the WSL distribution
|
||||
func (h *AmazonQCLIHandler) getWSLUsername(distro string) (string, error) {
|
||||
cmd := exec.Command("wsl", "-d", distro, "--", "whoami")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Amazon Q CLI is authenticated
|
||||
func (h *AmazonQCLIHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
// Check if the SQLite database exists with auth tokens
|
||||
dbPath, err := h.GetDatabasePath()
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(dbPath); os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Database exists, assume configured (actual token validation happens in auth layer)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// GetDatabasePath returns the path to the Amazon Q SQLite database
|
||||
func (h *AmazonQCLIHandler) GetDatabasePath() (string, error) {
|
||||
if runtime.GOOS == "windows" {
|
||||
if h.wslDistro == "" || h.wslUser == "" {
|
||||
// Try to detect
|
||||
distro, err := h.getDefaultWSLDistro()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("no WSL distribution found: %w", err)
|
||||
}
|
||||
h.wslDistro = distro
|
||||
|
||||
user, err := h.getWSLUsername(distro)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get WSL user: %w", err)
|
||||
}
|
||||
h.wslUser = user
|
||||
}
|
||||
// Windows UNC path to WSL filesystem
|
||||
return fmt.Sprintf(`\\wsl$\%s\home\%s\.local\share\amazon-q\data.sqlite3`, h.wslDistro, h.wslUser), nil
|
||||
}
|
||||
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(homeDir, ".local", "share", "amazon-q", "data.sqlite3"), nil
|
||||
}
|
||||
|
||||
// Enable is not supported for Amazon Q CLI (uses its own auth)
|
||||
func (h *AmazonQCLIHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
return nil, fmt.Errorf("Amazon Q CLI uses its own authentication. Run 'q login' to authenticate")
|
||||
}
|
||||
|
||||
// Disable is not supported for Amazon Q CLI
|
||||
func (h *AmazonQCLIHandler) Disable(changes []Change) error {
|
||||
// Nothing to disable - Q CLI manages its own auth
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstructions returns instructions for Amazon Q CLI setup
|
||||
func (h *AmazonQCLIHandler) GetInstructions(proxyURL string) string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return `Amazon Q CLI is available via WSL on Windows.
|
||||
|
||||
To install and authenticate:
|
||||
|
||||
1. Open WSL (Ubuntu recommended)
|
||||
2. Install Amazon Q CLI:
|
||||
curl -sS https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip -o q.zip
|
||||
unzip q.zip
|
||||
./q/install.sh --no-confirm
|
||||
|
||||
3. Authenticate with AWS Builder ID:
|
||||
q login
|
||||
|
||||
4. ProxyPilot will automatically detect and use your Amazon Q CLI tokens.
|
||||
|
||||
Note: Amazon Q CLI has separate usage quota from Kiro IDE.
|
||||
`
|
||||
}
|
||||
|
||||
return `To install and authenticate Amazon Q CLI:
|
||||
|
||||
1. Install Amazon Q CLI:
|
||||
curl -sS https://desktop-release.q.us-east-1.amazonaws.com/latest/q-x86_64-linux.zip -o q.zip
|
||||
unzip q.zip
|
||||
./q/install.sh --no-confirm
|
||||
|
||||
2. Authenticate with AWS Builder ID:
|
||||
q login
|
||||
|
||||
3. ProxyPilot will automatically detect and use your Amazon Q CLI tokens.
|
||||
|
||||
Note: Amazon Q CLI has separate usage quota from Kiro IDE.
|
||||
`
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Amazon Q CLI
|
||||
func (h *AmazonQCLIHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Amazon Q CLI Configuration
|
||||
# Amazon Q CLI uses its own authentication via 'q login'.
|
||||
# ProxyPilot automatically imports the tokens after you authenticate.
|
||||
|
||||
# To authenticate:
|
||||
# q login
|
||||
|
||||
# ProxyPilot will detect and use the tokens automatically.
|
||||
# No additional environment variables needed.
|
||||
|
||||
# Optional: For other OpenAI-compatible tools
|
||||
export OPENAI_BASE_URL="%s/v1"
|
||||
export OPENAI_API_KEY="proxypilot-local"
|
||||
`, proxyURL)
|
||||
}
|
||||
|
||||
// GetWSLInfo returns WSL distro and user information (for external use)
|
||||
func (h *AmazonQCLIHandler) GetWSLInfo() (distro, user string) {
|
||||
return h.wslDistro, h.wslUser
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// ClaudeCodeHandler handles Claude Code CLI configuration
|
||||
type ClaudeCodeHandler struct {
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewClaudeCodeHandler creates a new Claude Code handler
|
||||
func NewClaudeCodeHandler() *ClaudeCodeHandler {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
return &ClaudeCodeHandler{
|
||||
configPath: filepath.Join(homeDir, ".claude", "settings.json"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *ClaudeCodeHandler) ID() string {
|
||||
return "claude-code"
|
||||
}
|
||||
|
||||
func (h *ClaudeCodeHandler) Name() string {
|
||||
return "Claude Code"
|
||||
}
|
||||
|
||||
func (h *ClaudeCodeHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *ClaudeCodeHandler) GetConfigPath() string {
|
||||
return h.configPath
|
||||
}
|
||||
|
||||
// Detect checks if Claude Code is installed
|
||||
func (h *ClaudeCodeHandler) Detect() (bool, error) {
|
||||
// Check for claude binary in PATH
|
||||
if _, err := exec.LookPath("claude"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for config directory existence
|
||||
configDir := filepath.Dir(h.configPath)
|
||||
if _, err := os.Stat(configDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Claude Code is already configured for ProxyPilot
|
||||
func (h *ClaudeCodeHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return false, nil // Config doesn't exist or can't be read
|
||||
}
|
||||
|
||||
// Check for ProxyPilot marker or ANTHROPIC_BASE_URL
|
||||
if _, hasMarker := config["_proxypilot"]; hasMarker {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if env, ok := config["env"].(map[string]any); ok {
|
||||
if baseURL, ok := env["ANTHROPIC_BASE_URL"].(string); ok {
|
||||
if baseURL == proxyURL || baseURL == proxyURL+"/" {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures Claude Code to use ProxyPilot
|
||||
func (h *ClaudeCodeHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
// Ensure config directory exists
|
||||
configDir := filepath.Dir(h.configPath)
|
||||
if err := os.MkdirAll(configDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
// Read existing config or create new one
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
config = make(map[string]any)
|
||||
}
|
||||
|
||||
// Get or create env map
|
||||
env, ok := config["env"].(map[string]any)
|
||||
if !ok {
|
||||
env = make(map[string]any)
|
||||
}
|
||||
|
||||
// Record and apply ANTHROPIC_BASE_URL change
|
||||
originalBaseURL := env["ANTHROPIC_BASE_URL"]
|
||||
env["ANTHROPIC_BASE_URL"] = proxyURL
|
||||
changes = append(changes, Change{
|
||||
Path: "env.ANTHROPIC_BASE_URL",
|
||||
Original: originalBaseURL,
|
||||
Applied: proxyURL,
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
// Record and apply ANTHROPIC_AUTH_TOKEN change
|
||||
originalAuthToken := env["ANTHROPIC_AUTH_TOKEN"]
|
||||
env["ANTHROPIC_AUTH_TOKEN"] = "proxypilot-local"
|
||||
changes = append(changes, Change{
|
||||
Path: "env.ANTHROPIC_AUTH_TOKEN",
|
||||
Original: originalAuthToken,
|
||||
Applied: "proxypilot-local",
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
config["env"] = env
|
||||
|
||||
// Add ProxyPilot marker
|
||||
originalMarker := config["_proxypilot"]
|
||||
config["_proxypilot"] = true
|
||||
changes = append(changes, Change{
|
||||
Path: "_proxypilot",
|
||||
Original: originalMarker,
|
||||
Applied: true,
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return nil, fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from Claude Code
|
||||
func (h *ClaudeCodeHandler) Disable(changes []Change) error {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return nil // Config doesn't exist, nothing to disable
|
||||
}
|
||||
|
||||
env, _ := config["env"].(map[string]any)
|
||||
if env == nil {
|
||||
env = make(map[string]any)
|
||||
}
|
||||
|
||||
// Restore original values based on recorded changes
|
||||
for _, change := range changes {
|
||||
switch change.Path {
|
||||
case "env.ANTHROPIC_BASE_URL":
|
||||
if change.Original == nil {
|
||||
delete(env, "ANTHROPIC_BASE_URL")
|
||||
} else {
|
||||
env["ANTHROPIC_BASE_URL"] = change.Original
|
||||
}
|
||||
case "env.ANTHROPIC_AUTH_TOKEN":
|
||||
if change.Original == nil {
|
||||
delete(env, "ANTHROPIC_AUTH_TOKEN")
|
||||
} else {
|
||||
env["ANTHROPIC_AUTH_TOKEN"] = change.Original
|
||||
}
|
||||
case "_proxypilot":
|
||||
delete(config, "_proxypilot")
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up empty env map
|
||||
if len(env) == 0 {
|
||||
delete(config, "env")
|
||||
} else {
|
||||
config["env"] = env
|
||||
}
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *ClaudeCodeHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure Claude Code for ProxyPilot:
|
||||
|
||||
1. Edit %s
|
||||
2. Add or update the "env" section:
|
||||
|
||||
{
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "%s",
|
||||
"ANTHROPIC_AUTH_TOKEN": "proxypilot-local"
|
||||
}
|
||||
}
|
||||
|
||||
3. Restart Claude Code for changes to take effect.
|
||||
`, h.configPath, proxyURL)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Claude Code
|
||||
func (h *ClaudeCodeHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Claude Code Configuration
|
||||
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
|
||||
|
||||
export ANTHROPIC_BASE_URL="%s"
|
||||
export ANTHROPIC_AUTH_TOKEN="proxypilot-local"
|
||||
|
||||
# For Claude Code 2.x, you can also set default models:
|
||||
# export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4-1-20250805"
|
||||
# export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-4-5-20250929"
|
||||
# export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-3-5-haiku-20241022"
|
||||
|
||||
# For Claude Code 1.x:
|
||||
# export ANTHROPIC_MODEL="claude-sonnet-4-5-20250929"
|
||||
# export ANTHROPIC_SMALL_FAST_MODEL="claude-3-5-haiku-20241022"
|
||||
`, proxyURL)
|
||||
}
|
||||
|
||||
// readConfig reads the Claude Code settings file
|
||||
func (h *ClaudeCodeHandler) readConfig() (map[string]any, error) {
|
||||
data, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// writeConfig writes the Claude Code settings file
|
||||
func (h *ClaudeCodeHandler) writeConfig(config map[string]any) error {
|
||||
data, err := json.MarshalIndent(config, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add newline at end
|
||||
data = append(data, '\n')
|
||||
|
||||
return os.WriteFile(h.configPath, data, 0644)
|
||||
}
|
||||
|
||||
// GetClaudeConfigDir returns the Claude Code config directory based on platform
|
||||
func GetClaudeConfigDir() string {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
// On Windows, Claude might use AppData
|
||||
if appData := os.Getenv("APPDATA"); appData != "" {
|
||||
claudeAppData := filepath.Join(appData, "Claude")
|
||||
if _, err := os.Stat(claudeAppData); err == nil {
|
||||
return claudeAppData
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default: ~/.claude
|
||||
return filepath.Join(homeDir, ".claude")
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CodexHandler handles Codex CLI configuration
|
||||
type CodexHandler struct {
|
||||
configDir string
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewCodexHandler creates a new Codex CLI handler
|
||||
func NewCodexHandler() *CodexHandler {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
configDir := filepath.Join(homeDir, ".codex")
|
||||
return &CodexHandler{
|
||||
configDir: configDir,
|
||||
configPath: filepath.Join(configDir, "config.toml"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *CodexHandler) ID() string {
|
||||
return "codex"
|
||||
}
|
||||
|
||||
func (h *CodexHandler) Name() string {
|
||||
return "Codex CLI"
|
||||
}
|
||||
|
||||
func (h *CodexHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *CodexHandler) GetConfigPath() string {
|
||||
return h.configPath
|
||||
}
|
||||
|
||||
// Detect checks if Codex CLI is installed
|
||||
func (h *CodexHandler) Detect() (bool, error) {
|
||||
// Check for codex binary in PATH
|
||||
if _, err := exec.LookPath("codex"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for config directory existence
|
||||
if _, err := os.Stat(h.configDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Codex CLI is already configured for ProxyPilot
|
||||
func (h *CodexHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
content, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return false, nil // Config doesn't exist
|
||||
}
|
||||
|
||||
// Check for ProxyPilot section marker
|
||||
if strings.Contains(string(content), "# ProxyPilot START") {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for proxy URL in config
|
||||
if strings.Contains(string(content), proxyURL) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures Codex CLI to use ProxyPilot
|
||||
func (h *CodexHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
// Ensure config directory exists
|
||||
if err := os.MkdirAll(h.configDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
// Read existing config
|
||||
var existingContent string
|
||||
if data, err := os.ReadFile(h.configPath); err == nil {
|
||||
existingContent = string(data)
|
||||
}
|
||||
|
||||
// Check if already has ProxyPilot section
|
||||
if strings.Contains(existingContent, "# ProxyPilot START") {
|
||||
// Already configured, update it
|
||||
existingContent = h.removeProxyPilotSection(existingContent)
|
||||
}
|
||||
|
||||
// Record original content
|
||||
changes = append(changes, Change{
|
||||
Path: "config.toml",
|
||||
Original: existingContent,
|
||||
Applied: "", // Will be set below
|
||||
Type: "toml",
|
||||
File: h.configPath,
|
||||
})
|
||||
|
||||
// Create ProxyPilot section
|
||||
proxyPilotSection := fmt.Sprintf(`
|
||||
# ProxyPilot START
|
||||
# ProxyPilot model provider for local proxy routing
|
||||
[model_providers.proxypilot]
|
||||
name = "ProxyPilot"
|
||||
base_url = "%s/v1"
|
||||
env_key = "PROXYPILOT_API_KEY"
|
||||
wire_api = "openai"
|
||||
# ProxyPilot END
|
||||
`, proxyURL)
|
||||
|
||||
// Append to existing content
|
||||
newContent := strings.TrimRight(existingContent, "\n\r\t ") + "\n" + proxyPilotSection
|
||||
|
||||
// Update the change record
|
||||
changes[0].Applied = newContent
|
||||
|
||||
// Write config
|
||||
if err := os.WriteFile(h.configPath, []byte(newContent), 0644); err != nil {
|
||||
return nil, fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from Codex CLI
|
||||
func (h *CodexHandler) Disable(changes []Change) error {
|
||||
content, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return nil // Config doesn't exist, nothing to disable
|
||||
}
|
||||
|
||||
// Remove ProxyPilot section
|
||||
newContent := h.removeProxyPilotSection(string(content))
|
||||
|
||||
// If we have recorded original content, we could restore it
|
||||
// But for additive changes, just removing the section is cleaner
|
||||
for _, change := range changes {
|
||||
if change.Path == "config.toml" && change.Original != nil {
|
||||
if origStr, ok := change.Original.(string); ok && origStr != "" {
|
||||
// Restore original if it was recorded
|
||||
newContent = origStr
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write config
|
||||
if err := os.WriteFile(h.configPath, []byte(newContent), 0644); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// removeProxyPilotSection removes the ProxyPilot section from config content
|
||||
func (h *CodexHandler) removeProxyPilotSection(content string) string {
|
||||
lines := strings.Split(content, "\n")
|
||||
var result []string
|
||||
inProxyPilotSection := false
|
||||
|
||||
for _, line := range lines {
|
||||
if strings.Contains(line, "# ProxyPilot START") {
|
||||
inProxyPilotSection = true
|
||||
continue
|
||||
}
|
||||
if strings.Contains(line, "# ProxyPilot END") {
|
||||
inProxyPilotSection = false
|
||||
continue
|
||||
}
|
||||
if !inProxyPilotSection {
|
||||
result = append(result, line)
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(result, "\n")
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *CodexHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure Codex CLI for ProxyPilot:
|
||||
|
||||
1. Edit %s
|
||||
2. Add the following section:
|
||||
|
||||
[model_providers.proxypilot]
|
||||
name = "ProxyPilot"
|
||||
base_url = "%s/v1"
|
||||
env_key = "PROXYPILOT_API_KEY"
|
||||
wire_api = "openai"
|
||||
|
||||
3. Set the environment variable:
|
||||
export PROXYPILOT_API_KEY="proxypilot-local"
|
||||
|
||||
4. Restart Codex CLI for changes to take effect.
|
||||
`, h.configPath, proxyURL)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Codex CLI
|
||||
func (h *CodexHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Codex CLI Configuration
|
||||
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
|
||||
|
||||
export PROXYPILOT_API_KEY="proxypilot-local"
|
||||
export OPENAI_BASE_URL="%s/v1"
|
||||
export OPENAI_API_KEY="proxypilot-local"
|
||||
|
||||
# Note: Codex CLI also requires config.toml configuration.
|
||||
# See the setup instructions for full details.
|
||||
`, proxyURL)
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// CursorHandler handles Cursor IDE configuration
|
||||
type CursorHandler struct {
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewCursorHandler creates a new Cursor handler
|
||||
func NewCursorHandler() *CursorHandler {
|
||||
return &CursorHandler{
|
||||
configPath: getCursorSettingsPath(),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *CursorHandler) ID() string {
|
||||
return "cursor"
|
||||
}
|
||||
|
||||
func (h *CursorHandler) Name() string {
|
||||
return "Cursor"
|
||||
}
|
||||
|
||||
func (h *CursorHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *CursorHandler) GetConfigPath() string {
|
||||
return h.configPath
|
||||
}
|
||||
|
||||
// Detect checks if Cursor is installed
|
||||
func (h *CursorHandler) Detect() (bool, error) {
|
||||
if h.configPath == "" {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Check if settings file or its directory exists
|
||||
if _, err := os.Stat(h.configPath); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := os.Stat(filepath.Dir(h.configPath)); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Cursor is already configured for ProxyPilot
|
||||
func (h *CursorHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return false, nil // Config doesn't exist
|
||||
}
|
||||
|
||||
// Check for proxypilot model in models section
|
||||
if models, ok := config["models"].(map[string]any); ok {
|
||||
if _, hasProxyPilot := models["proxypilot"]; hasProxyPilot {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures Cursor to use ProxyPilot
|
||||
func (h *CursorHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
if h.configPath == "" {
|
||||
return nil, fmt.Errorf("could not determine Cursor settings path")
|
||||
}
|
||||
|
||||
// Ensure config directory exists
|
||||
if err := os.MkdirAll(filepath.Dir(h.configPath), 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
// Read existing config or create new one
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
config = make(map[string]any)
|
||||
}
|
||||
|
||||
// Get or create models map
|
||||
var models map[string]any
|
||||
if existingModels, ok := config["models"].(map[string]any); ok {
|
||||
models = existingModels
|
||||
} else {
|
||||
models = make(map[string]any)
|
||||
}
|
||||
|
||||
// Record original proxypilot model (if any)
|
||||
originalModel := models["proxypilot"]
|
||||
|
||||
// Add ProxyPilot model configuration
|
||||
models["proxypilot"] = map[string]any{
|
||||
"name": "ProxyPilot",
|
||||
"apiKey": "proxypilot-local",
|
||||
"baseUrl": proxyURL + "/v1",
|
||||
"contextLength": 200000,
|
||||
}
|
||||
|
||||
changes = append(changes, Change{
|
||||
Path: "models.proxypilot",
|
||||
Original: originalModel,
|
||||
Applied: models["proxypilot"],
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
config["models"] = models
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return nil, fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from Cursor
|
||||
func (h *CursorHandler) Disable(changes []Change) error {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return nil // Config doesn't exist, nothing to disable
|
||||
}
|
||||
|
||||
// Get models map
|
||||
models, ok := config["models"].(map[string]any)
|
||||
if !ok {
|
||||
return nil // No models, nothing to remove
|
||||
}
|
||||
|
||||
// Restore original values based on recorded changes
|
||||
for _, change := range changes {
|
||||
if change.Path == "models.proxypilot" {
|
||||
if change.Original == nil {
|
||||
delete(models, "proxypilot")
|
||||
} else {
|
||||
models["proxypilot"] = change.Original
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up empty models map
|
||||
if len(models) == 0 {
|
||||
delete(config, "models")
|
||||
} else {
|
||||
config["models"] = models
|
||||
}
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *CursorHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure Cursor for ProxyPilot:
|
||||
|
||||
1. Open Cursor Settings (Cmd/Ctrl + ,)
|
||||
2. Go to "Models" section
|
||||
3. Add a new custom model with these settings:
|
||||
- Name: ProxyPilot
|
||||
- API Key: proxypilot-local
|
||||
- Base URL: %s/v1
|
||||
- Context Length: 200000
|
||||
|
||||
Or edit %s directly and add:
|
||||
|
||||
{
|
||||
"models": {
|
||||
"proxypilot": {
|
||||
"name": "ProxyPilot",
|
||||
"apiKey": "proxypilot-local",
|
||||
"baseUrl": "%s/v1",
|
||||
"contextLength": 200000
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
4. Select 'proxypilot' as your model in Cursor AI settings.
|
||||
`, proxyURL, h.configPath, proxyURL)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Cursor
|
||||
func (h *CursorHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Cursor IDE Configuration
|
||||
# Note: Cursor primarily uses settings.json, not environment variables.
|
||||
# Use the UI or edit settings.json directly.
|
||||
|
||||
# Optional: Set OPENAI-compatible environment variables as fallback
|
||||
export OPENAI_BASE_URL="%s/v1"
|
||||
export OPENAI_API_KEY="proxypilot-local"
|
||||
`, proxyURL)
|
||||
}
|
||||
|
||||
// readConfig reads the Cursor settings file
|
||||
func (h *CursorHandler) readConfig() (map[string]any, error) {
|
||||
data, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// writeConfig writes the Cursor settings file
|
||||
func (h *CursorHandler) writeConfig(config map[string]any) error {
|
||||
data, err := json.MarshalIndent(config, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add newline at end
|
||||
data = append(data, '\n')
|
||||
|
||||
return os.WriteFile(h.configPath, data, 0644)
|
||||
}
|
||||
|
||||
// getCursorSettingsPath returns the Cursor settings path based on platform
|
||||
func getCursorSettingsPath() string {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
var paths []string
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if appData := os.Getenv("APPDATA"); appData != "" {
|
||||
paths = append(paths, filepath.Join(appData, "Cursor", "User", "settings.json"))
|
||||
}
|
||||
case "darwin":
|
||||
paths = append(paths, filepath.Join(homeDir, "Library", "Application Support", "Cursor", "User", "settings.json"))
|
||||
default: // Linux and others
|
||||
paths = append(paths, filepath.Join(homeDir, ".config", "Cursor", "User", "settings.json"))
|
||||
}
|
||||
|
||||
// Return first existing path, or first path as default
|
||||
for _, p := range paths {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return p
|
||||
}
|
||||
// If parent dir exists, use this path
|
||||
if _, err := os.Stat(filepath.Dir(p)); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
|
||||
if len(paths) > 0 {
|
||||
return paths[0]
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FactoryDroidHandler handles Factory Droid CLI configuration
|
||||
type FactoryDroidHandler struct {
|
||||
configDir string
|
||||
settingsPath string // Droid uses settings.json for customModels
|
||||
}
|
||||
|
||||
// NewFactoryDroidHandler creates a new Factory Droid handler
|
||||
func NewFactoryDroidHandler() *FactoryDroidHandler {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
configDir := filepath.Join(homeDir, ".factory")
|
||||
return &FactoryDroidHandler{
|
||||
configDir: configDir,
|
||||
settingsPath: filepath.Join(configDir, "settings.json"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) ID() string {
|
||||
return "factory-droid"
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) Name() string {
|
||||
return "Factory Droid"
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) GetConfigPath() string {
|
||||
return h.settingsPath
|
||||
}
|
||||
|
||||
// Detect checks if Factory Droid is installed
|
||||
func (h *FactoryDroidHandler) Detect() (bool, error) {
|
||||
if _, err := exec.LookPath("droid"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := exec.LookPath("factory"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if _, err := os.Stat(h.configDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Factory Droid is already configured for ProxyPilot
|
||||
func (h *FactoryDroidHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
settings, err := h.readSettings()
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if customModels, ok := settings["customModels"].([]any); ok {
|
||||
for _, entry := range customModels {
|
||||
if m, ok := entry.(map[string]any); ok {
|
||||
displayName, _ := m["displayName"].(string)
|
||||
if strings.HasPrefix(displayName, "proxypilot-") {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures Factory Droid to use ProxyPilot
|
||||
func (h *FactoryDroidHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
if err := os.MkdirAll(h.configDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
settings, err := h.readSettings()
|
||||
if err != nil {
|
||||
settings = make(map[string]any)
|
||||
}
|
||||
|
||||
// Build ProxyPilot models in Droid's format
|
||||
proxyPilotModels := buildDroidModels(proxyURL)
|
||||
|
||||
originalCustomModels := settings["customModels"]
|
||||
|
||||
// Merge: proxypilot models first, then user's non-proxypilot models
|
||||
var finalModels []any
|
||||
for _, m := range proxyPilotModels {
|
||||
finalModels = append(finalModels, m)
|
||||
}
|
||||
|
||||
// Keep user's non-proxypilot models
|
||||
if existing, ok := settings["customModels"].([]any); ok {
|
||||
for _, entry := range existing {
|
||||
if m, ok := entry.(map[string]any); ok {
|
||||
displayName, _ := m["displayName"].(string)
|
||||
if !isProxyPilotModel(displayName) {
|
||||
// Re-index user models after proxypilot models
|
||||
m["index"] = len(finalModels)
|
||||
finalModels = append(finalModels, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
settings["customModels"] = finalModels
|
||||
|
||||
changes = append(changes, Change{
|
||||
Path: "customModels",
|
||||
Original: originalCustomModels,
|
||||
Applied: finalModels,
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
if err := h.writeSettings(settings); err != nil {
|
||||
return nil, fmt.Errorf("failed to write settings: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from Factory Droid
|
||||
func (h *FactoryDroidHandler) Disable(changes []Change) error {
|
||||
settings, err := h.readSettings()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var filteredModels []any
|
||||
idx := 0
|
||||
if customModels, ok := settings["customModels"].([]any); ok {
|
||||
for _, entry := range customModels {
|
||||
if m, ok := entry.(map[string]any); ok {
|
||||
displayName, _ := m["displayName"].(string)
|
||||
// Remove all ProxyPilot models (various naming conventions)
|
||||
if !isProxyPilotModel(displayName) {
|
||||
m["index"] = idx
|
||||
filteredModels = append(filteredModels, m)
|
||||
idx++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(filteredModels) == 0 {
|
||||
delete(settings, "customModels")
|
||||
} else {
|
||||
settings["customModels"] = filteredModels
|
||||
}
|
||||
|
||||
if err := h.writeSettings(settings); err != nil {
|
||||
return fmt.Errorf("failed to write settings: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// isProxyPilotModel checks if a model name belongs to ProxyPilot
|
||||
func isProxyPilotModel(displayName string) bool {
|
||||
lower := strings.ToLower(displayName)
|
||||
return strings.HasPrefix(lower, "proxypilot-") || strings.HasPrefix(lower, "proxypilot ")
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *FactoryDroidHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure Factory Droid for ProxyPilot:
|
||||
|
||||
1. Edit %s
|
||||
2. Add ProxyPilot models to the "customModels" array with this format:
|
||||
|
||||
{
|
||||
"customModels": [
|
||||
{
|
||||
"model": "claude-opus-4-5-20251101",
|
||||
"id": "custom:proxypilot-Claude-4.5-Opus-0",
|
||||
"index": 0,
|
||||
"baseUrl": "%s/v1",
|
||||
"apiKey": "proxypilot-local",
|
||||
"displayName": "proxypilot-Claude 4.5 Opus",
|
||||
"provider": "openai"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
3. Restart Factory Droid and select a proxypilot model.
|
||||
`, h.settingsPath, proxyURL)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Factory Droid
|
||||
func (h *FactoryDroidHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Factory Droid Configuration
|
||||
# Factory Droid uses settings.json for configuration, not environment variables.
|
||||
# Use the auto-configure feature or edit %s directly.
|
||||
|
||||
# Optional: For other OpenAI-compatible tools
|
||||
export OPENAI_BASE_URL="%s/v1"
|
||||
export OPENAI_API_KEY="proxypilot-local"
|
||||
`, h.settingsPath, proxyURL)
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) readSettings() (map[string]any, error) {
|
||||
data, err := os.ReadFile(h.settingsPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var settings map[string]any
|
||||
if err := json.Unmarshal(data, &settings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func (h *FactoryDroidHandler) writeSettings(settings map[string]any) error {
|
||||
data, err := json.MarshalIndent(settings, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data = append(data, '\n')
|
||||
return os.WriteFile(h.settingsPath, data, 0644)
|
||||
}
|
||||
|
||||
// buildDroidModels builds models in Droid's expected format
|
||||
func buildDroidModels(proxyURL string) []map[string]any {
|
||||
curatedModels := []struct {
|
||||
displayName string
|
||||
modelID string
|
||||
provider string
|
||||
}{
|
||||
// Claude 4.5 Direct (Anthropic API)
|
||||
{"Claude 4.5 Opus", "claude-opus-4-5-20251101", "anthropic"},
|
||||
{"Claude 4.5 Sonnet", "claude-sonnet-4-5-20250929", "anthropic"},
|
||||
{"Claude 4.5 Haiku", "claude-haiku-4-5-20251001", "anthropic"},
|
||||
|
||||
// Antigravity (Claude via Gemini with extended thinking)
|
||||
{"Claude 4.5 Opus Thinking", "gemini-claude-opus-4-5-thinking", "antigravity"},
|
||||
{"Claude 4.5 Sonnet Thinking", "gemini-claude-sonnet-4-5-thinking", "antigravity"},
|
||||
|
||||
// Gemini latest
|
||||
{"Gemini 2.5 Pro", "gemini-2.5-pro", "google"},
|
||||
{"Gemini 2.5 Flash", "gemini-2.5-flash", "google"},
|
||||
{"Gemini 3 Pro Preview", "gemini-3-pro-preview", "google"},
|
||||
{"Gemini 3 Flash Preview", "gemini-3-flash-preview", "google"},
|
||||
|
||||
// OpenAI latest
|
||||
{"GPT 5.2", "gpt-5.2", "openai"},
|
||||
{"GPT 5.2 Codex", "gpt-5.2-codex", "openai"},
|
||||
{"GPT 5.1 Codex Max", "gpt-5.1-codex-max", "openai"},
|
||||
|
||||
// Kiro (AWS)
|
||||
{"Kiro Claude Opus 4.5", "kiro-claude-opus-4-5", "kiro"},
|
||||
{"Kiro Claude Sonnet 4.5", "kiro-claude-sonnet-4-5", "kiro"},
|
||||
{"Kiro Claude Haiku 4.5", "kiro-claude-haiku-4-5", "kiro"},
|
||||
|
||||
// Amazon Q
|
||||
{"Amazon Q Auto", "amazonq-auto", "amazonq"},
|
||||
{"Amazon Q Claude Opus 4.5", "amazonq-claude-opus-4.5", "amazonq"},
|
||||
{"Amazon Q Claude Sonnet 4.5", "amazonq-claude-sonnet-4.5", "amazonq"},
|
||||
|
||||
// GitHub Copilot
|
||||
{"Copilot GPT 5.2", "gpt-5.2", "github-copilot"},
|
||||
{"Copilot Claude Opus 4.5", "claude-opus-4.5", "github-copilot"},
|
||||
{"Copilot Claude Sonnet 4.5", "claude-sonnet-4.5", "github-copilot"},
|
||||
{"Copilot Gemini 3 Pro", "gemini-3-pro", "github-copilot"},
|
||||
|
||||
// Qwen
|
||||
{"Qwen3 Coder Plus", "qwen3-coder-plus", "qwen"},
|
||||
{"Qwen3 Coder Flash", "qwen3-coder-flash", "qwen"},
|
||||
|
||||
// MiniMax
|
||||
{"MiniMax M2.1", "minimax-m2.1", "minimax"},
|
||||
|
||||
// Zhipu
|
||||
{"GLM 4.7", "glm-4.7", "zhipu"},
|
||||
{"GLM 4.6V", "glm-4.6v", "zhipu"},
|
||||
}
|
||||
|
||||
var models []map[string]any
|
||||
for i, m := range curatedModels {
|
||||
displayName := "proxypilot-" + m.displayName
|
||||
// Create ID in Droid's format: custom:<name>-<index>
|
||||
id := fmt.Sprintf("custom:%s-%d", strings.ReplaceAll(displayName, " ", "-"), i)
|
||||
|
||||
models = append(models, map[string]any{
|
||||
"model": m.modelID,
|
||||
"id": id,
|
||||
"index": i,
|
||||
"baseUrl": proxyURL + "/v1",
|
||||
"apiKey": "proxypilot-local",
|
||||
"displayName": displayName,
|
||||
"noImageSupport": false,
|
||||
"provider": "openai", // Droid uses "openai" for OpenAI-compatible endpoints
|
||||
})
|
||||
}
|
||||
|
||||
return models
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// GeminiCLIHandler handles Gemini CLI configuration
|
||||
type GeminiCLIHandler struct {
|
||||
configDir string
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewGeminiCLIHandler creates a new Gemini CLI handler
|
||||
func NewGeminiCLIHandler() *GeminiCLIHandler {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
configDir := filepath.Join(homeDir, ".gemini")
|
||||
return &GeminiCLIHandler{
|
||||
configDir: configDir,
|
||||
configPath: filepath.Join(configDir, "settings.json"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *GeminiCLIHandler) ID() string {
|
||||
return "gemini-cli"
|
||||
}
|
||||
|
||||
func (h *GeminiCLIHandler) Name() string {
|
||||
return "Gemini CLI"
|
||||
}
|
||||
|
||||
func (h *GeminiCLIHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *GeminiCLIHandler) GetConfigPath() string {
|
||||
return h.configPath
|
||||
}
|
||||
|
||||
// Detect checks if Gemini CLI is installed
|
||||
func (h *GeminiCLIHandler) Detect() (bool, error) {
|
||||
// Check for gemini binary in PATH
|
||||
if _, err := exec.LookPath("gemini"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for config directory existence
|
||||
if _, err := os.Stat(h.configDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if Gemini CLI is already configured for ProxyPilot
|
||||
func (h *GeminiCLIHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return false, nil // Config doesn't exist
|
||||
}
|
||||
|
||||
// Check for ProxyPilot marker
|
||||
if _, hasMarker := config["_proxypilot"]; hasMarker {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for api_base pointing to proxy
|
||||
if apiBase, ok := config["api_base"].(string); ok {
|
||||
if apiBase == proxyURL || apiBase == proxyURL+"/" {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures Gemini CLI to use ProxyPilot
|
||||
func (h *GeminiCLIHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
// Ensure config directory exists
|
||||
if err := os.MkdirAll(h.configDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
// Read existing config or create new one
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
config = make(map[string]any)
|
||||
}
|
||||
|
||||
// Record and apply api_base change
|
||||
originalAPIBase := config["api_base"]
|
||||
config["api_base"] = proxyURL
|
||||
changes = append(changes, Change{
|
||||
Path: "api_base",
|
||||
Original: originalAPIBase,
|
||||
Applied: proxyURL,
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
// Add ProxyPilot marker
|
||||
originalMarker := config["_proxypilot"]
|
||||
config["_proxypilot"] = true
|
||||
changes = append(changes, Change{
|
||||
Path: "_proxypilot",
|
||||
Original: originalMarker,
|
||||
Applied: true,
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return nil, fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from Gemini CLI
|
||||
func (h *GeminiCLIHandler) Disable(changes []Change) error {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return nil // Config doesn't exist, nothing to disable
|
||||
}
|
||||
|
||||
// Restore original values based on recorded changes
|
||||
for _, change := range changes {
|
||||
switch change.Path {
|
||||
case "api_base":
|
||||
if change.Original == nil {
|
||||
delete(config, "api_base")
|
||||
} else {
|
||||
config["api_base"] = change.Original
|
||||
}
|
||||
case "_proxypilot":
|
||||
delete(config, "_proxypilot")
|
||||
}
|
||||
}
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *GeminiCLIHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure Gemini CLI for ProxyPilot:
|
||||
|
||||
Option 1: Edit settings.json
|
||||
1. Edit %s
|
||||
2. Add or update the "api_base" field:
|
||||
|
||||
{
|
||||
"api_base": "%s"
|
||||
}
|
||||
|
||||
Option 2: Use environment variables
|
||||
Add to your shell profile (~/.bashrc or ~/.zshrc):
|
||||
|
||||
export GOOGLE_GEMINI_BASE_URL="%s"
|
||||
export GEMINI_API_KEY="proxypilot-local"
|
||||
|
||||
Then restart your shell or run: source ~/.bashrc
|
||||
`, h.configPath, proxyURL, proxyURL)
|
||||
}
|
||||
|
||||
// readConfig reads the Gemini CLI settings file
|
||||
func (h *GeminiCLIHandler) readConfig() (map[string]any, error) {
|
||||
data, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// writeConfig writes the Gemini CLI settings file
|
||||
func (h *GeminiCLIHandler) writeConfig(config map[string]any) error {
|
||||
data, err := json.MarshalIndent(config, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add newline at end
|
||||
data = append(data, '\n')
|
||||
|
||||
return os.WriteFile(h.configPath, data, 0644)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for Gemini CLI
|
||||
func (h *GeminiCLIHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - Gemini CLI Configuration
|
||||
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
|
||||
|
||||
# Option 1: OAuth mode (local only)
|
||||
export CODE_ASSIST_ENDPOINT="%s"
|
||||
|
||||
# Option 2: API Key mode (works with any IP/domain)
|
||||
# export GOOGLE_GEMINI_BASE_URL="%s"
|
||||
# export GEMINI_API_KEY="proxypilot-local"
|
||||
`, proxyURL, proxyURL)
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// AgentInfo contains information about a CLI agent
|
||||
type AgentInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Detected bool `json:"detected"`
|
||||
Configured bool `json:"configured"`
|
||||
CanAutoConfigure bool `json:"can_auto_configure"`
|
||||
ConfigPath string `json:"config_path,omitempty"`
|
||||
Instructions string `json:"instructions,omitempty"`
|
||||
ShellConfig string `json:"shell_config,omitempty"`
|
||||
EnvVars map[string]string `json:"env_vars,omitempty"`
|
||||
}
|
||||
|
||||
// ConfigResult represents the result of a configuration operation
|
||||
type ConfigResult struct {
|
||||
Success bool `json:"success"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ConfigPath string `json:"config_path,omitempty"`
|
||||
Instructions string `json:"instructions,omitempty"`
|
||||
}
|
||||
|
||||
// AgentHandler defines the interface for agent-specific configuration handlers
|
||||
type AgentHandler interface {
|
||||
// ID returns the unique identifier for this agent
|
||||
ID() string
|
||||
|
||||
// Name returns the display name for this agent
|
||||
Name() string
|
||||
|
||||
// Detect checks if the agent is installed on the system
|
||||
Detect() (bool, error)
|
||||
|
||||
// IsConfigured checks if the agent is already configured for ProxyPilot
|
||||
IsConfigured(proxyURL string) (bool, error)
|
||||
|
||||
// Enable configures the agent to use ProxyPilot and returns the changes made
|
||||
Enable(proxyURL string) ([]Change, error)
|
||||
|
||||
// Disable removes ProxyPilot configuration from the agent using recorded changes
|
||||
Disable(changes []Change) error
|
||||
|
||||
// GetConfigPath returns the path to the agent's configuration file
|
||||
GetConfigPath() string
|
||||
|
||||
// CanAutoConfigure returns whether this agent supports automatic configuration
|
||||
CanAutoConfigure() bool
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
GetInstructions(proxyURL string) string
|
||||
|
||||
// GetShellConfig returns shell script configuration for this agent.
|
||||
// This is used for agents that need environment variables in shell profiles.
|
||||
GetShellConfig(proxyURL string) string
|
||||
}
|
||||
|
||||
// Manager manages all CLI agent configurations
|
||||
type Manager struct {
|
||||
mu sync.RWMutex
|
||||
state *StateManager
|
||||
handlers map[string]AgentHandler
|
||||
proxyURL string
|
||||
}
|
||||
|
||||
// NewManager creates a new agent configuration manager
|
||||
func NewManager(proxyPort int) (*Manager, error) {
|
||||
state, err := NewStateManager()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create state manager: %w", err)
|
||||
}
|
||||
|
||||
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", proxyPort)
|
||||
|
||||
m := &Manager{
|
||||
state: state,
|
||||
handlers: make(map[string]AgentHandler),
|
||||
proxyURL: proxyURL,
|
||||
}
|
||||
|
||||
// Register all known agent handlers
|
||||
m.registerDefaultHandlers()
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// registerDefaultHandlers registers all built-in agent handlers
|
||||
func (m *Manager) registerDefaultHandlers() {
|
||||
handlers := []AgentHandler{
|
||||
NewClaudeCodeHandler(),
|
||||
NewCodexHandler(),
|
||||
NewGeminiCLIHandler(),
|
||||
NewCursorHandler(),
|
||||
NewOpenCodeHandler(),
|
||||
NewFactoryDroidHandler(),
|
||||
NewAmazonQCLIHandler(),
|
||||
}
|
||||
|
||||
for _, h := range handlers {
|
||||
m.handlers[h.ID()] = h
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterHandler adds a custom agent handler
|
||||
func (m *Manager) RegisterHandler(handler AgentHandler) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.handlers[handler.ID()] = handler
|
||||
}
|
||||
|
||||
// GetHandler returns a handler by ID
|
||||
func (m *Manager) GetHandler(agentID string) (AgentHandler, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
h, ok := m.handlers[agentID]
|
||||
return h, ok
|
||||
}
|
||||
|
||||
// DetectAll detects all agents and returns their info
|
||||
func (m *Manager) DetectAll() ([]AgentInfo, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var agents []AgentInfo
|
||||
|
||||
for _, handler := range m.handlers {
|
||||
info := AgentInfo{
|
||||
ID: handler.ID(),
|
||||
Name: handler.Name(),
|
||||
CanAutoConfigure: handler.CanAutoConfigure(),
|
||||
ConfigPath: handler.GetConfigPath(),
|
||||
Instructions: handler.GetInstructions(m.proxyURL),
|
||||
ShellConfig: handler.GetShellConfig(m.proxyURL),
|
||||
}
|
||||
|
||||
detected, err := handler.Detect()
|
||||
if err != nil {
|
||||
// Log error but continue with other agents
|
||||
info.Detected = false
|
||||
} else {
|
||||
info.Detected = detected
|
||||
}
|
||||
|
||||
if detected {
|
||||
configured, err := handler.IsConfigured(m.proxyURL)
|
||||
if err == nil {
|
||||
info.Configured = configured
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we have state for this agent
|
||||
if state, exists := m.state.GetAgentState(handler.ID()); exists {
|
||||
info.Configured = state.Enabled
|
||||
}
|
||||
|
||||
agents = append(agents, info)
|
||||
}
|
||||
|
||||
return agents, nil
|
||||
}
|
||||
|
||||
// GetAgentInfo returns info for a specific agent
|
||||
func (m *Manager) GetAgentInfo(agentID string) (AgentInfo, error) {
|
||||
handler, ok := m.GetHandler(agentID)
|
||||
if !ok {
|
||||
return AgentInfo{}, fmt.Errorf("unknown agent: %s", agentID)
|
||||
}
|
||||
|
||||
info := AgentInfo{
|
||||
ID: handler.ID(),
|
||||
Name: handler.Name(),
|
||||
CanAutoConfigure: handler.CanAutoConfigure(),
|
||||
ConfigPath: handler.GetConfigPath(),
|
||||
Instructions: handler.GetInstructions(m.proxyURL),
|
||||
ShellConfig: handler.GetShellConfig(m.proxyURL),
|
||||
}
|
||||
|
||||
detected, _ := handler.Detect()
|
||||
info.Detected = detected
|
||||
|
||||
if detected {
|
||||
configured, _ := handler.IsConfigured(m.proxyURL)
|
||||
info.Configured = configured
|
||||
}
|
||||
|
||||
if state, exists := m.state.GetAgentState(agentID); exists {
|
||||
info.Configured = state.Enabled
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// Enable enables ProxyPilot for an agent
|
||||
func (m *Manager) Enable(agentID string) ConfigResult {
|
||||
handler, ok := m.GetHandler(agentID)
|
||||
if !ok {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("unknown agent: %s", agentID),
|
||||
}
|
||||
}
|
||||
|
||||
if !handler.CanAutoConfigure() {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: "agent does not support automatic configuration",
|
||||
Instructions: handler.GetInstructions(m.proxyURL),
|
||||
}
|
||||
}
|
||||
|
||||
// Check if already enabled
|
||||
if m.state.IsAgentEnabled(agentID) {
|
||||
return ConfigResult{
|
||||
Success: true,
|
||||
AgentID: agentID,
|
||||
Message: "agent already configured",
|
||||
ConfigPath: handler.GetConfigPath(),
|
||||
}
|
||||
}
|
||||
|
||||
// Enable the agent
|
||||
changes, err := handler.Enable(m.proxyURL)
|
||||
if err != nil {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("failed to enable: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
// Record the state
|
||||
if err := m.state.RecordEnable(agentID, handler.GetConfigPath(), changes); err != nil {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("failed to save state: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
return ConfigResult{
|
||||
Success: true,
|
||||
AgentID: agentID,
|
||||
Message: fmt.Sprintf("%s configured successfully", handler.Name()),
|
||||
ConfigPath: handler.GetConfigPath(),
|
||||
}
|
||||
}
|
||||
|
||||
// Disable disables ProxyPilot for an agent
|
||||
func (m *Manager) Disable(agentID string) ConfigResult {
|
||||
handler, ok := m.GetHandler(agentID)
|
||||
if !ok {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("unknown agent: %s", agentID),
|
||||
}
|
||||
}
|
||||
|
||||
// Get recorded changes
|
||||
changes := m.state.GetChanges(agentID)
|
||||
if len(changes) == 0 {
|
||||
// No recorded changes, try to detect and remove anyway
|
||||
if !m.state.IsAgentEnabled(agentID) {
|
||||
return ConfigResult{
|
||||
Success: true,
|
||||
AgentID: agentID,
|
||||
Message: "agent was not configured",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Disable the agent
|
||||
if err := handler.Disable(changes); err != nil {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("failed to disable: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear the state
|
||||
if err := m.state.ClearAgent(agentID); err != nil {
|
||||
return ConfigResult{
|
||||
Success: false,
|
||||
AgentID: agentID,
|
||||
Error: fmt.Sprintf("failed to clear state: %v", err),
|
||||
}
|
||||
}
|
||||
|
||||
return ConfigResult{
|
||||
Success: true,
|
||||
AgentID: agentID,
|
||||
Message: fmt.Sprintf("%s configuration removed", handler.Name()),
|
||||
}
|
||||
}
|
||||
|
||||
// EnableAll enables ProxyPilot for all detected agents that support auto-configuration
|
||||
func (m *Manager) EnableAll() []ConfigResult {
|
||||
var results []ConfigResult
|
||||
|
||||
for agentID, handler := range m.handlers {
|
||||
if !handler.CanAutoConfigure() {
|
||||
continue
|
||||
}
|
||||
|
||||
detected, _ := handler.Detect()
|
||||
if !detected {
|
||||
continue
|
||||
}
|
||||
|
||||
result := m.Enable(agentID)
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// DisableAll disables ProxyPilot for all configured agents
|
||||
func (m *Manager) DisableAll() []ConfigResult {
|
||||
var results []ConfigResult
|
||||
|
||||
states := m.state.GetAllAgentStates()
|
||||
for agentID, state := range states {
|
||||
if !state.Enabled {
|
||||
continue
|
||||
}
|
||||
|
||||
result := m.Disable(agentID)
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// GetState returns the state manager for direct access
|
||||
func (m *Manager) GetState() *StateManager {
|
||||
return m.state
|
||||
}
|
||||
|
||||
// SetProxyURL updates the proxy URL
|
||||
func (m *Manager) SetProxyURL(port int) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.proxyURL = fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// OpenCodeHandler handles OpenCode CLI configuration
|
||||
type OpenCodeHandler struct {
|
||||
configDir string
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewOpenCodeHandler creates a new OpenCode handler
|
||||
func NewOpenCodeHandler() *OpenCodeHandler {
|
||||
homeDir, _ := os.UserHomeDir()
|
||||
configDir := filepath.Join(homeDir, ".config", "opencode")
|
||||
return &OpenCodeHandler{
|
||||
configDir: configDir,
|
||||
configPath: filepath.Join(configDir, "opencode.json"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *OpenCodeHandler) ID() string {
|
||||
return "opencode"
|
||||
}
|
||||
|
||||
func (h *OpenCodeHandler) Name() string {
|
||||
return "OpenCode"
|
||||
}
|
||||
|
||||
func (h *OpenCodeHandler) CanAutoConfigure() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *OpenCodeHandler) GetConfigPath() string {
|
||||
return h.configPath
|
||||
}
|
||||
|
||||
// Detect checks if OpenCode is installed
|
||||
func (h *OpenCodeHandler) Detect() (bool, error) {
|
||||
// Check for opencode binary in PATH
|
||||
if _, err := exec.LookPath("opencode"); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check for config directory existence
|
||||
if _, err := os.Stat(h.configDir); err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// IsConfigured checks if OpenCode is already configured for ProxyPilot
|
||||
func (h *OpenCodeHandler) IsConfigured(proxyURL string) (bool, error) {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return false, nil // Config doesn't exist
|
||||
}
|
||||
|
||||
// Check for proxypilot provider
|
||||
if providers, ok := config["providers"].(map[string]any); ok {
|
||||
if _, hasProxyPilot := providers["proxypilot"]; hasProxyPilot {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Enable configures OpenCode to use ProxyPilot
|
||||
func (h *OpenCodeHandler) Enable(proxyURL string) ([]Change, error) {
|
||||
var changes []Change
|
||||
|
||||
// Ensure config directory exists
|
||||
if err := os.MkdirAll(h.configDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
|
||||
// Read existing config or create new one
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
config = make(map[string]any)
|
||||
}
|
||||
|
||||
// Get or create providers map
|
||||
var providers map[string]any
|
||||
if existingProviders, ok := config["providers"].(map[string]any); ok {
|
||||
providers = existingProviders
|
||||
} else {
|
||||
providers = make(map[string]any)
|
||||
}
|
||||
|
||||
// Record original proxypilot provider (if any)
|
||||
originalProvider := providers["proxypilot"]
|
||||
|
||||
// Add ProxyPilot provider configuration
|
||||
providers["proxypilot"] = map[string]any{
|
||||
"name": "ProxyPilot",
|
||||
"apiKey": "proxypilot-local",
|
||||
"options": map[string]any{
|
||||
"baseURL": proxyURL + "/v1",
|
||||
},
|
||||
"models": []string{
|
||||
"claude-sonnet-4-20250514",
|
||||
"claude-opus-4-20250514",
|
||||
"gpt-4o",
|
||||
"gemini-2.0-flash",
|
||||
},
|
||||
}
|
||||
|
||||
changes = append(changes, Change{
|
||||
Path: "providers.proxypilot",
|
||||
Original: originalProvider,
|
||||
Applied: providers["proxypilot"],
|
||||
Type: "json",
|
||||
})
|
||||
|
||||
config["providers"] = providers
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return nil, fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return changes, nil
|
||||
}
|
||||
|
||||
// Disable removes ProxyPilot configuration from OpenCode
|
||||
func (h *OpenCodeHandler) Disable(changes []Change) error {
|
||||
config, err := h.readConfig()
|
||||
if err != nil {
|
||||
return nil // Config doesn't exist, nothing to disable
|
||||
}
|
||||
|
||||
// Get providers map
|
||||
providers, ok := config["providers"].(map[string]any)
|
||||
if !ok {
|
||||
return nil // No providers, nothing to remove
|
||||
}
|
||||
|
||||
// Restore original values based on recorded changes
|
||||
for _, change := range changes {
|
||||
if change.Path == "providers.proxypilot" {
|
||||
if change.Original == nil {
|
||||
delete(providers, "proxypilot")
|
||||
} else {
|
||||
providers["proxypilot"] = change.Original
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up empty providers map
|
||||
if len(providers) == 0 {
|
||||
delete(config, "providers")
|
||||
} else {
|
||||
config["providers"] = providers
|
||||
}
|
||||
|
||||
// Write config
|
||||
if err := h.writeConfig(config); err != nil {
|
||||
return fmt.Errorf("failed to write config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstructions returns manual configuration instructions
|
||||
func (h *OpenCodeHandler) GetInstructions(proxyURL string) string {
|
||||
return fmt.Sprintf(`To manually configure OpenCode for ProxyPilot:
|
||||
|
||||
1. Edit %s
|
||||
2. Add a "proxypilot" provider to the "providers" section:
|
||||
|
||||
{
|
||||
"providers": {
|
||||
"proxypilot": {
|
||||
"name": "ProxyPilot",
|
||||
"apiKey": "proxypilot-local",
|
||||
"options": {
|
||||
"baseURL": "%s/v1"
|
||||
},
|
||||
"models": [
|
||||
"claude-sonnet-4-20250514",
|
||||
"claude-opus-4-20250514",
|
||||
"gpt-4o"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3. Restart OpenCode and select the ProxyPilot provider.
|
||||
`, h.configPath, proxyURL)
|
||||
}
|
||||
|
||||
// GetShellConfig returns shell profile configuration for OpenCode
|
||||
func (h *OpenCodeHandler) GetShellConfig(proxyURL string) string {
|
||||
return fmt.Sprintf(`# ProxyPilot - OpenCode Configuration
|
||||
# Add these lines to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile)
|
||||
|
||||
export OPENAI_BASE_URL="%s/v1"
|
||||
export OPENAI_API_KEY="proxypilot-local"
|
||||
|
||||
# Or use Anthropic-compatible settings:
|
||||
# export ANTHROPIC_BASE_URL="%s"
|
||||
# export ANTHROPIC_AUTH_TOKEN="proxypilot-local"
|
||||
`, proxyURL, proxyURL)
|
||||
}
|
||||
|
||||
// readConfig reads the OpenCode settings file
|
||||
func (h *OpenCodeHandler) readConfig() (map[string]any, error) {
|
||||
data, err := os.ReadFile(h.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var config map[string]any
|
||||
if err := json.Unmarshal(data, &config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// writeConfig writes the OpenCode settings file
|
||||
func (h *OpenCodeHandler) writeConfig(config map[string]any) error {
|
||||
data, err := json.MarshalIndent(config, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add newline at end
|
||||
data = append(data, '\n')
|
||||
|
||||
return os.WriteFile(h.configPath, data, 0644)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// Package agents provides unified agent configuration management for ProxyPilot.
|
||||
// It tracks all changes made to CLI agent configurations and provides precise
|
||||
// enable/disable functionality without destructive backup/restore operations.
|
||||
package agents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StateVersion is the current version of the state file format
|
||||
const StateVersion = 1
|
||||
|
||||
// State represents the overall state of ProxyPilot's agent configurations
|
||||
type State struct {
|
||||
Version int `json:"version"`
|
||||
Agents map[string]AgentState `json:"agents"`
|
||||
}
|
||||
|
||||
// AgentState represents the configuration state for a single agent
|
||||
type AgentState struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ConfigPath string `json:"config_path"`
|
||||
Changes []Change `json:"changes"`
|
||||
EnabledAt time.Time `json:"enabled_at,omitempty"`
|
||||
DisabledAt time.Time `json:"disabled_at,omitempty"`
|
||||
}
|
||||
|
||||
// Change represents a single configuration change made to an agent
|
||||
type Change struct {
|
||||
Path string `json:"path"` // JSON path or config key (e.g., "env.ANTHROPIC_BASE_URL")
|
||||
Original any `json:"original"` // Original value (nil if key didn't exist)
|
||||
Applied any `json:"applied"` // Value applied by ProxyPilot
|
||||
Type string `json:"type,omitempty"` // Type of change: "json", "toml", "env", "shell"
|
||||
File string `json:"file,omitempty"` // Specific file if different from ConfigPath
|
||||
}
|
||||
|
||||
// StateManager handles loading, saving, and manipulating ProxyPilot state
|
||||
type StateManager struct {
|
||||
mu sync.RWMutex
|
||||
state *State
|
||||
statePath string
|
||||
baseDir string
|
||||
}
|
||||
|
||||
// NewStateManager creates a new StateManager instance
|
||||
func NewStateManager() (*StateManager, error) {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get home directory: %w", err)
|
||||
}
|
||||
|
||||
baseDir := filepath.Join(homeDir, ".proxypilot")
|
||||
statePath := filepath.Join(baseDir, "state.json")
|
||||
|
||||
sm := &StateManager{
|
||||
statePath: statePath,
|
||||
baseDir: baseDir,
|
||||
}
|
||||
|
||||
if err := sm.ensureBaseDir(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := sm.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sm, nil
|
||||
}
|
||||
|
||||
// ensureBaseDir creates the base directory if it doesn't exist
|
||||
func (sm *StateManager) ensureBaseDir() error {
|
||||
agentsDir := filepath.Join(sm.baseDir, "agents")
|
||||
if err := os.MkdirAll(agentsDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create agents directory: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// load reads the state from disk, or creates a new state if none exists
|
||||
func (sm *StateManager) load() error {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(sm.statePath)
|
||||
if os.IsNotExist(err) {
|
||||
sm.state = &State{
|
||||
Version: StateVersion,
|
||||
Agents: make(map[string]AgentState),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read state file: %w", err)
|
||||
}
|
||||
|
||||
var state State
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return fmt.Errorf("failed to parse state file: %w", err)
|
||||
}
|
||||
|
||||
if state.Agents == nil {
|
||||
state.Agents = make(map[string]AgentState)
|
||||
}
|
||||
|
||||
sm.state = &state
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save persists the current state to disk
|
||||
func (sm *StateManager) Save() error {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
return sm.saveUnlocked()
|
||||
}
|
||||
|
||||
func (sm *StateManager) saveUnlocked() error {
|
||||
data, err := json.MarshalIndent(sm.state, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal state: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(sm.statePath, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write state file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAgentState returns the state for a specific agent
|
||||
func (sm *StateManager) GetAgentState(agentID string) (AgentState, bool) {
|
||||
sm.mu.RLock()
|
||||
defer sm.mu.RUnlock()
|
||||
|
||||
state, exists := sm.state.Agents[agentID]
|
||||
return state, exists
|
||||
}
|
||||
|
||||
// IsAgentEnabled returns whether an agent is currently enabled
|
||||
func (sm *StateManager) IsAgentEnabled(agentID string) bool {
|
||||
state, exists := sm.GetAgentState(agentID)
|
||||
return exists && state.Enabled
|
||||
}
|
||||
|
||||
// RecordEnable records that an agent has been enabled with the given changes
|
||||
func (sm *StateManager) RecordEnable(agentID string, configPath string, changes []Change) error {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
sm.state.Agents[agentID] = AgentState{
|
||||
Enabled: true,
|
||||
ConfigPath: configPath,
|
||||
Changes: changes,
|
||||
EnabledAt: time.Now(),
|
||||
}
|
||||
|
||||
return sm.saveUnlocked()
|
||||
}
|
||||
|
||||
// RecordDisable records that an agent has been disabled
|
||||
func (sm *StateManager) RecordDisable(agentID string) error {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
if state, exists := sm.state.Agents[agentID]; exists {
|
||||
state.Enabled = false
|
||||
state.DisabledAt = time.Now()
|
||||
sm.state.Agents[agentID] = state
|
||||
}
|
||||
|
||||
return sm.saveUnlocked()
|
||||
}
|
||||
|
||||
// GetChanges returns the list of changes for an agent
|
||||
func (sm *StateManager) GetChanges(agentID string) []Change {
|
||||
state, exists := sm.GetAgentState(agentID)
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
return state.Changes
|
||||
}
|
||||
|
||||
// GetAllAgentStates returns all agent states
|
||||
func (sm *StateManager) GetAllAgentStates() map[string]AgentState {
|
||||
sm.mu.RLock()
|
||||
defer sm.mu.RUnlock()
|
||||
|
||||
result := make(map[string]AgentState, len(sm.state.Agents))
|
||||
for k, v := range sm.state.Agents {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// GetBaseDir returns the base directory for ProxyPilot config
|
||||
func (sm *StateManager) GetBaseDir() string {
|
||||
return sm.baseDir
|
||||
}
|
||||
|
||||
// GetAgentsDir returns the directory for agent-specific configs
|
||||
func (sm *StateManager) GetAgentsDir() string {
|
||||
return filepath.Join(sm.baseDir, "agents")
|
||||
}
|
||||
|
||||
// ClearAgent removes all state for an agent (used after successful disable)
|
||||
func (sm *StateManager) ClearAgent(agentID string) error {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
|
||||
delete(sm.state.Agents, agentID)
|
||||
return sm.saveUnlocked()
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
|
||||
)
|
||||
|
||||
// mockCoreManager implements memory.CoreManagerExecutor for testing
|
||||
type mockCoreManager struct {
|
||||
response interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *mockCoreManager) Execute(ctx context.Context, providers []string, req interface{}, opts interface{}) (interface{}, error) {
|
||||
return m.response, m.err
|
||||
}
|
||||
|
||||
func TestContextCompression_AdapterIntegration(t *testing.T) {
|
||||
// Test that the adapter correctly bridges manager to executor
|
||||
mockResp := struct {
|
||||
Payload []byte `json:"payload"`
|
||||
}{
|
||||
Payload: []byte(`{"choices":[{"message":{"content":"Test summary"}}]}`),
|
||||
}
|
||||
|
||||
manager := &mockCoreManager{response: mockResp}
|
||||
adapter := memory.NewManagerAuthAdapter(manager)
|
||||
|
||||
if adapter == nil {
|
||||
t.Fatal("Expected adapter to be created")
|
||||
}
|
||||
|
||||
// Test execute
|
||||
resp, err := adapter.Execute(context.Background(), []string{"claude"}, memory.ExecutorRequest{
|
||||
Model: "claude-3-opus",
|
||||
Payload: []byte(`{"test": true}`),
|
||||
}, memory.ExecutorOptions{})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Execute failed: %v", err)
|
||||
}
|
||||
|
||||
if len(resp) == 0 {
|
||||
t.Error("Expected non-empty response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgenticHarness_MiddlewareIntegration(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
// Create temp directory for harness files
|
||||
tmpDir, err := os.MkdirTemp("", "harness-integration")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
handler := middleware.AgenticHarnessMiddlewareWithRootDir(tmpDir)
|
||||
|
||||
// Test 1: Fresh conversation should get INITIALIZER
|
||||
t.Run("fresh_conversation_initializer", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
|
||||
body := `{"model":"gpt-4","messages":[{"role":"user","content":"Build a todo app"}]}`
|
||||
c.Request = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
|
||||
c.Request.Header.Set("User-Agent", "claude-cli/1.0")
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler(c)
|
||||
|
||||
mode := c.Writer.Header().Get("X-ProxyPilot-Harness-Mode")
|
||||
if mode != "INITIALIZER" {
|
||||
t.Errorf("Expected INITIALIZER mode, got: %s", mode)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 2: After creating harness files, should get CODING
|
||||
t.Run("with_harness_files_coding", func(t *testing.T) {
|
||||
// Create harness file
|
||||
os.WriteFile(tmpDir+"/feature_list.json", []byte(`[{"id":"test","passes":false}]`), 0644)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
|
||||
body := `{"model":"gpt-4","messages":[{"role":"user","content":"Continue"}]}`
|
||||
c.Request = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
|
||||
c.Request.Header.Set("User-Agent", "claude-cli/1.0")
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
handler(c)
|
||||
|
||||
mode := c.Writer.Header().Get("X-ProxyPilot-Harness-Mode")
|
||||
if mode != "CODING" {
|
||||
t.Errorf("Expected CODING mode, got: %s", mode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCombinedFeatures_NoConflict(t *testing.T) {
|
||||
// Verify both features can be enabled simultaneously without conflict
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
// Set up harness
|
||||
tmpDir, _ := os.MkdirTemp("", "combined-test")
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Create engine with both middlewares
|
||||
engine := gin.New()
|
||||
engine.Use(middleware.AgenticHarnessMiddleware())
|
||||
|
||||
// Verify engine was created without panic
|
||||
if engine == nil {
|
||||
t.Fatal("Engine should be created")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/agents"
|
||||
)
|
||||
|
||||
// AgentsV2Handler provides the new unified agent configuration API
|
||||
type AgentsV2Handler struct {
|
||||
manager *agents.Manager
|
||||
}
|
||||
|
||||
// NewAgentsV2Handler creates a new AgentsV2Handler
|
||||
func NewAgentsV2Handler(port int) (*AgentsV2Handler, error) {
|
||||
manager, err := agents.NewManager(port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AgentsV2Handler{manager: manager}, nil
|
||||
}
|
||||
|
||||
// GetAgents returns the list of detected CLI agents
|
||||
// GET /api/v2/agents
|
||||
func (h *AgentsV2Handler) GetAgents(c *gin.Context) {
|
||||
agentsList, err := h.manager.DetectAll()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"agents": agentsList})
|
||||
}
|
||||
|
||||
// GetAgent returns info for a specific agent
|
||||
// GET /api/v2/agents/:id
|
||||
func (h *AgentsV2Handler) GetAgent(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
|
||||
return
|
||||
}
|
||||
|
||||
info, err := h.manager.GetAgentInfo(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, info)
|
||||
}
|
||||
|
||||
// EnableAgent enables ProxyPilot for an agent
|
||||
// POST /api/v2/agents/:id/enable
|
||||
func (h *AgentsV2Handler) EnableAgent(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
|
||||
return
|
||||
}
|
||||
|
||||
result := h.manager.Enable(id)
|
||||
if !result.Success {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": result.Error,
|
||||
"instructions": result.Instructions,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"agent_id": result.AgentID,
|
||||
"message": result.Message,
|
||||
"config_path": result.ConfigPath,
|
||||
})
|
||||
}
|
||||
|
||||
// DisableAgent disables ProxyPilot for an agent
|
||||
// POST /api/v2/agents/:id/disable
|
||||
func (h *AgentsV2Handler) DisableAgent(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
|
||||
return
|
||||
}
|
||||
|
||||
result := h.manager.Disable(id)
|
||||
if !result.Success {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": result.Error,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"agent_id": result.AgentID,
|
||||
"message": result.Message,
|
||||
})
|
||||
}
|
||||
|
||||
// EnableAllAgents enables ProxyPilot for all detected agents
|
||||
// POST /api/v2/agents/enable-all
|
||||
func (h *AgentsV2Handler) EnableAllAgents(c *gin.Context) {
|
||||
results := h.manager.EnableAll()
|
||||
c.JSON(http.StatusOK, gin.H{"results": results})
|
||||
}
|
||||
|
||||
// DisableAllAgents disables ProxyPilot for all configured agents
|
||||
// POST /api/v2/agents/disable-all
|
||||
func (h *AgentsV2Handler) DisableAllAgents(c *gin.Context) {
|
||||
results := h.manager.DisableAll()
|
||||
c.JSON(http.StatusOK, gin.H{"results": results})
|
||||
}
|
||||
|
||||
// GetAgentState returns the current ProxyPilot state for all agents
|
||||
// GET /api/v2/agents/state
|
||||
func (h *AgentsV2Handler) GetAgentState(c *gin.Context) {
|
||||
states := h.manager.GetState().GetAllAgentStates()
|
||||
c.JSON(http.StatusOK, gin.H{"states": states})
|
||||
}
|
||||
|
||||
// SetProxyPort updates the proxy port used by the manager
|
||||
func (h *AgentsV2Handler) SetProxyPort(port int) {
|
||||
h.manager.SetProxyURL(port)
|
||||
}
|
||||
@@ -24,8 +24,8 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
|
||||
amazonqauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/amazonq"
|
||||
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 +1687,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 {
|
||||
@@ -2567,3 +2361,237 @@ func generateKiroPKCE() (verifier, challenge string, err error) {
|
||||
|
||||
return verifier, challenge, nil
|
||||
}
|
||||
|
||||
// SaveMiniMaxAPIKey saves a MiniMax API key as an auth file.
|
||||
func (h *Handler) SaveMiniMaxAPIKey(c *gin.Context) {
|
||||
var req struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.APIKey == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "api_key is required"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
label := req.Label
|
||||
if label == "" {
|
||||
label = "minimax-api-key"
|
||||
}
|
||||
fileName := fmt.Sprintf("minimax-%s.json", now.Format("20060102-150405"))
|
||||
|
||||
record := &coreauth.Auth{
|
||||
ID: fileName,
|
||||
Provider: "minimax",
|
||||
FileName: fileName,
|
||||
Label: label,
|
||||
Status: coreauth.StatusActive,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
Metadata: map[string]any{
|
||||
"type": "minimax",
|
||||
"api_key": req.APIKey,
|
||||
},
|
||||
Attributes: map[string]string{
|
||||
"source": "webui",
|
||||
},
|
||||
}
|
||||
|
||||
authPath := filepath.Join(h.cfg.AuthDir, fileName)
|
||||
data, err := json.MarshalIndent(record, "", " ")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to serialize auth record"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(authPath, data, 0600); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save auth file"})
|
||||
return
|
||||
}
|
||||
|
||||
if h.authManager != nil {
|
||||
if reloader, ok := interface{}(h.authManager).(interface{ ReloadAuthFiles() error }); ok {
|
||||
_ = reloader.ReloadAuthFiles()
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("MiniMax API key saved: %s", fileName)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "MiniMax API key saved", "filename": fileName})
|
||||
}
|
||||
|
||||
// SaveZhipuAPIKey saves a Zhipu AI API key as an auth file.
|
||||
func (h *Handler) SaveZhipuAPIKey(c *gin.Context) {
|
||||
var req struct {
|
||||
APIKey string `json:"api_key"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.APIKey == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "api_key is required"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
label := req.Label
|
||||
if label == "" {
|
||||
label = "zhipu-api-key"
|
||||
}
|
||||
fileName := fmt.Sprintf("zhipu-%s.json", now.Format("20060102-150405"))
|
||||
|
||||
record := &coreauth.Auth{
|
||||
ID: fileName,
|
||||
Provider: "zhipu",
|
||||
FileName: fileName,
|
||||
Label: label,
|
||||
Status: coreauth.StatusActive,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
Metadata: map[string]any{
|
||||
"type": "zhipu",
|
||||
"api_key": req.APIKey,
|
||||
},
|
||||
Attributes: map[string]string{
|
||||
"source": "webui",
|
||||
},
|
||||
}
|
||||
|
||||
authPath := filepath.Join(h.cfg.AuthDir, fileName)
|
||||
data, err := json.MarshalIndent(record, "", " ")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to serialize auth record"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(authPath, data, 0600); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save auth file"})
|
||||
return
|
||||
}
|
||||
|
||||
if h.authManager != nil {
|
||||
if reloader, ok := interface{}(h.authManager).(interface{ ReloadAuthFiles() error }); ok {
|
||||
_ = reloader.ReloadAuthFiles()
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("Zhipu API key saved: %s", fileName)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Zhipu API key saved", "filename": fileName})
|
||||
}
|
||||
|
||||
// ImportAmazonQToken imports token from Amazon Q CLI's SQLite database.
|
||||
// Amazon Q CLI stores tokens at ~/.local/share/amazon-q/data.sqlite3 (or WSL path on Windows).
|
||||
// This provides access to a separate usage quota pool from Kiro IDE.
|
||||
func (h *Handler) ImportAmazonQToken(c *gin.Context) {
|
||||
log.Info("Importing Amazon Q CLI token...")
|
||||
|
||||
// Check if Amazon Q CLI tokens are available
|
||||
if !amazonqauth.IsAvailable() {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Amazon Q CLI token not available",
|
||||
"message": "Please run 'q login' in your terminal first to authenticate with Amazon Q CLI",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Load the token
|
||||
kiroToken, err := amazonqauth.LoadAmazonQToken()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to read Amazon Q CLI token",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Extract email from JWT if available
|
||||
email := kiroauth.ExtractEmailFromJWT(kiroToken.AccessToken)
|
||||
|
||||
// Create identifier for file naming
|
||||
idPart := "amazonq-cli"
|
||||
if email != "" {
|
||||
idPart = fmt.Sprintf("amazonq-cli-%s", kiroauth.SanitizeEmailForFilename(email))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
fileName := fmt.Sprintf("kiro-%s.json", idPart)
|
||||
|
||||
// Parse expires_at
|
||||
expiresAt, err := time.Parse(time.RFC3339, kiroToken.ExpiresAt)
|
||||
if err != nil {
|
||||
expiresAt = now.Add(1 * time.Hour)
|
||||
}
|
||||
|
||||
record := &coreauth.Auth{
|
||||
ID: fileName,
|
||||
Provider: "kiro", // Uses kiro provider since same API
|
||||
FileName: fileName,
|
||||
Label: "kiro-amazonq-cli",
|
||||
Status: coreauth.StatusActive,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
Metadata: map[string]any{
|
||||
"type": "kiro",
|
||||
"access_token": kiroToken.AccessToken,
|
||||
"refresh_token": kiroToken.RefreshToken,
|
||||
"expires_at": kiroToken.ExpiresAt,
|
||||
"auth_method": kiroToken.AuthMethod,
|
||||
"provider": kiroToken.Provider,
|
||||
"client_id": kiroToken.ClientID,
|
||||
"client_secret": kiroToken.ClientSecret,
|
||||
"email": email,
|
||||
"start_url": kiroToken.StartURL,
|
||||
"region": kiroToken.Region,
|
||||
"preferred_endpoint": "amazonq", // Force Amazon Q endpoint (CLI origin)
|
||||
},
|
||||
Attributes: map[string]string{
|
||||
"source": "amazonq-cli-import",
|
||||
"email": email,
|
||||
"preferred_endpoint": "amazonq", // Force Amazon Q endpoint (CLI origin)
|
||||
},
|
||||
NextRefreshAfter: expiresAt.Add(-5 * time.Minute),
|
||||
}
|
||||
|
||||
// Save the auth file
|
||||
authPath := filepath.Join(h.cfg.AuthDir, fileName)
|
||||
data, err := json.MarshalIndent(record, "", " ")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to serialize auth record",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(authPath, data, 0600); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to save auth file",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Reload auth files
|
||||
if h.authManager != nil {
|
||||
if reloader, ok := interface{}(h.authManager).(interface{ ReloadAuthFiles() error }); ok {
|
||||
_ = reloader.ReloadAuthFiles()
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("Amazon Q CLI token imported successfully: %s", fileName)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Amazon Q CLI token imported successfully",
|
||||
"email": email,
|
||||
"filename": fileName,
|
||||
"note": "Amazon Q CLI has separate usage quota from Kiro IDE",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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])
|
||||
}
|
||||