Sync upstream merge cleanup

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Copilot
2026-06-24 19:23:19 +08:00
parent c76adee007
commit 7ff4825858
40 changed files with 2259 additions and 4812 deletions
+28 -6
View File
@@ -9,17 +9,22 @@ require (
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
github.com/go-git/go-git/v6 v6.0.0-20251009132922-75a182125145
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/jackc/pgx/v5 v5.9.2
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808
github.com/joho/godotenv v1.5.1
github.com/klauspost/compress v1.17.4
github.com/klauspost/compress v1.18.0
github.com/minio/minio-go/v7 v7.0.66
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/prometheus/client_golang v1.23.2
github.com/redis/go-redis/v9 v9.19.0
github.com/refraction-networking/utls v1.8.2
github.com/sirupsen/logrus v1.9.3
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
github.com/tidwall/sjson v1.2.5
github.com/tiktoken-go/tokenizer v0.7.0
@@ -28,20 +33,37 @@ require (
golang.org/x/oauth2 v0.30.0
golang.org/x/sync v0.18.0
golang.org/x/sys v0.38.0
golang.org/x/term v0.37.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/redis/go-redis/v9 v9.19.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 // indirect
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 // indirect
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7 // indirect
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7 // indirect
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 // indirect
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
)
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/ProtonMail/go-crypto v1.3.0
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
@@ -87,7 +109,7 @@ require (
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/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2
github.com/pierrec/xxHash v0.1.5
github.com/pjbgf/sha1cd v0.5.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
@@ -100,6 +122,6 @@ require (
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
google.golang.org/protobuf v1.36.8
gopkg.in/ini.v1 v1.67.0 // indirect
)
+26 -25
View File
@@ -10,10 +10,10 @@ 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/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
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/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8=
github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
@@ -26,22 +26,26 @@ github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3z
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs=
github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg=
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
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/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
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/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=
github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
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=
@@ -120,14 +124,12 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047 h1:oQmbCpoIo/BQCUWzmMYR6hyq9Awgx0ingJHy4gWijTI=
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808 h1:ftnsTqIUH57XQEF+PnXX9++nlHCzdkuB5zbWyMMruZo=
github.com/jchv/go-webview2 v0.0.0-20260205173254-56598839c808/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
@@ -153,16 +155,16 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.3.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/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
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=
@@ -206,7 +208,6 @@ github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthO
github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
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=
@@ -262,8 +263,8 @@ 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/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
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=
@@ -1,129 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/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)
}
@@ -1,64 +0,0 @@
package management
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type setAuthPriorityRequest struct {
Priority *int `json:"priority"`
}
// SetAuthPriority updates the priority field for an auth entry.
func (h *Handler) SetAuthPriority(c *gin.Context) {
authID := strings.TrimSpace(c.Param("id"))
if authID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth id"})
return
}
var req setAuthPriorityRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Priority == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
auth, ok := h.authManager.GetByID(authID)
if !ok || auth == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
return
}
auth.Priority = *req.Priority
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
if auth.Attributes == nil {
auth.Attributes = make(map[string]string)
}
if *req.Priority == 0 {
delete(auth.Metadata, "priority")
delete(auth.Attributes, "priority")
} else {
auth.Metadata["priority"] = *req.Priority
auth.Attributes["priority"] = strconv.Itoa(*req.Priority)
}
auth.UpdatedAt = time.Now()
updated, err := h.authManager.Update(c.Request.Context(), auth)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, h.buildAuthFileEntry(updated))
}
@@ -1,92 +0,0 @@
package management
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
)
type authResetCooldownRequest struct {
AuthID string `json:"auth_id"`
Provider string `json:"provider"`
Model string `json:"model"`
}
// ResetAuthCooldown clears quota/cooldown flags so the next request can probe availability again.
// This is useful when an upstream 429 is suspected to be transient or misattributed.
func (h *Handler) ResetAuthCooldown(c *gin.Context) {
var req authResetCooldownRequest
_ = c.ShouldBindJSON(&req)
req.AuthID = strings.TrimSpace(req.AuthID)
req.Provider = strings.ToLower(strings.TrimSpace(req.Provider))
req.Model = strings.TrimSpace(req.Model)
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
updated := 0
now := time.Now()
resetAuth := func(a *coreauth.Auth) {
if a == nil {
return
}
a.Unavailable = false
a.NextRetryAfter = time.Time{}
a.Quota = coreauth.QuotaState{}
a.LastError = nil
a.StatusMessage = ""
a.UpdatedAt = now
if len(a.ModelStates) == 0 {
return
}
for modelID, st := range a.ModelStates {
if req.Model != "" && modelID != req.Model {
continue
}
if st == nil {
continue
}
st.Unavailable = false
st.NextRetryAfter = time.Time{}
st.Quota = coreauth.QuotaState{}
st.LastError = nil
st.StatusMessage = ""
st.Status = coreauth.StatusActive
st.UpdatedAt = now
registry.GetGlobalRegistry().ClearModelQuotaExceeded(a.ID, modelID)
registry.GetGlobalRegistry().ResumeClientModel(a.ID, modelID)
}
}
if req.AuthID != "" {
if a, ok := h.authManager.GetByID(req.AuthID); ok && a != nil {
resetAuth(a)
_, _ = h.authManager.Update(c.Request.Context(), a)
updated = 1
}
c.JSON(http.StatusOK, gin.H{"updated": updated})
return
}
for _, a := range h.authManager.List() {
if a == nil {
continue
}
if req.Provider != "" && strings.ToLower(strings.TrimSpace(a.Provider)) != req.Provider {
continue
}
resetAuth(a)
_, _ = h.authManager.Update(c.Request.Context(), a)
updated++
}
c.JSON(http.StatusOK, gin.H{"updated": updated})
}
@@ -1,34 +0,0 @@
package management
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// GetAuthUsage returns usage statistics for a specific auth entry.
func (h *Handler) GetAuthUsage(c *gin.Context) {
authID := strings.TrimSpace(c.Param("id"))
if authID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth id"})
return
}
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
auth, ok := h.authManager.GetByID(authID)
if !ok || auth == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
return
}
c.JSON(http.StatusOK, gin.H{
"total_input_tokens": auth.Usage.TotalInputTokens,
"total_output_tokens": auth.Usage.TotalOutputTokens,
"request_count": auth.Usage.RequestCount,
"daily_input_tokens": auth.Usage.DailyInputTokens,
"daily_output_tokens": auth.Usage.DailyOutputTokens,
"daily_request_count": auth.Usage.DailyRequestCount,
})
}
@@ -1,223 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/cache"
)
// CacheStatsResponse represents the response for cache statistics.
type CacheStatsResponse struct {
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Evictions int64 `json:"evictions"`
Size int `json:"size"`
TotalSaved int64 `json:"total_saved"`
Enabled bool `json:"enabled"`
}
// GetCacheStats returns cache statistics.
// GET /v0/management/cache/stats
func (h *Handler) GetCacheStats(c *gin.Context) {
responseCache := cache.GetDefaultResponseCache()
if responseCache == nil {
c.JSON(http.StatusOK, CacheStatsResponse{Enabled: false})
return
}
stats := responseCache.GetStats()
c.JSON(http.StatusOK, CacheStatsResponse{
Hits: stats.Hits,
Misses: stats.Misses,
Evictions: stats.Evictions,
Size: stats.Size,
TotalSaved: stats.TotalSaved,
Enabled: responseCache.IsEnabled(),
})
}
// ClearCache clears all cache entries.
// POST /v0/management/cache/clear
func (h *Handler) ClearCache(c *gin.Context) {
responseCache := cache.GetDefaultResponseCache()
if responseCache == nil {
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "cache not initialized"})
return
}
responseCache.Clear()
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "cache cleared"})
}
// CacheEnabledRequest is the request body for enabling/disabling cache.
type CacheEnabledRequest struct {
Enabled bool `json:"enabled"`
}
// SetCacheEnabled enables or disables the cache at runtime.
// PUT /v0/management/cache/enabled
func (h *Handler) SetCacheEnabled(c *gin.Context) {
var req CacheEnabledRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
responseCache := cache.GetDefaultResponseCache()
if responseCache == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "cache not initialized"})
return
}
responseCache.SetEnabled(req.Enabled)
c.JSON(http.StatusOK, gin.H{"status": "ok", "enabled": req.Enabled})
}
// PromptCacheStatsResponse represents the response for prompt cache statistics.
type PromptCacheStatsResponse struct {
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Evictions int64 `json:"evictions"`
Size int `json:"size"`
UniquePrompts int64 `json:"unique_prompts"`
TotalRequests int64 `json:"total_requests"`
EstimatedTokensSaved int64 `json:"estimated_tokens_saved"`
TopProviders map[string]int64 `json:"top_providers,omitempty"`
Enabled bool `json:"enabled"`
}
// GetPromptCacheStats returns prompt cache statistics.
// GET /v0/management/prompt-cache/stats
func (h *Handler) GetPromptCacheStats(c *gin.Context) {
promptCache := cache.GetDefaultPromptCache()
if promptCache == nil {
c.JSON(http.StatusOK, PromptCacheStatsResponse{Enabled: false})
return
}
stats := promptCache.GetStats()
c.JSON(http.StatusOK, PromptCacheStatsResponse{
Hits: stats.Hits,
Misses: stats.Misses,
Evictions: stats.Evictions,
Size: stats.Size,
UniquePrompts: stats.UniquePrompts,
TotalRequests: stats.TotalRequests,
EstimatedTokensSaved: stats.EstimatedTokensSaved,
TopProviders: stats.TopProviders,
Enabled: promptCache.IsEnabled(),
})
}
// ClearPromptCache clears all prompt cache entries.
// POST /v0/management/prompt-cache/clear
func (h *Handler) ClearPromptCache(c *gin.Context) {
promptCache := cache.GetDefaultPromptCache()
if promptCache == nil {
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "prompt cache not initialized"})
return
}
promptCache.Clear()
c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "prompt cache cleared"})
}
// SetPromptCacheEnabled enables or disables the prompt cache at runtime.
// PUT /v0/management/prompt-cache/enabled
func (h *Handler) SetPromptCacheEnabled(c *gin.Context) {
var req CacheEnabledRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
promptCache := cache.GetDefaultPromptCache()
if promptCache == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "prompt cache not initialized"})
return
}
promptCache.SetEnabled(req.Enabled)
c.JSON(http.StatusOK, gin.H{"status": "ok", "enabled": req.Enabled})
}
// TopPromptEntry represents a frequently used prompt.
type TopPromptEntry struct {
Hash string `json:"hash"`
TokenEstimate int `json:"token_estimate"`
HitCount int64 `json:"hit_count"`
Providers map[string]int `json:"providers,omitempty"`
PromptPreview string `json:"prompt_preview"`
}
// GetTopPrompts returns the most frequently hit prompts.
// GET /v0/management/prompt-cache/top
func (h *Handler) GetTopPrompts(c *gin.Context) {
promptCache := cache.GetDefaultPromptCache()
if promptCache == nil {
c.JSON(http.StatusOK, gin.H{"prompts": []TopPromptEntry{}})
return
}
top := promptCache.GetTopPrompts(10)
entries := make([]TopPromptEntry, 0, len(top))
for _, p := range top {
preview := p.Prompt
if len(preview) > 200 {
preview = preview[:200] + "..."
}
entries = append(entries, TopPromptEntry{
Hash: p.Hash,
TokenEstimate: p.TokenEstimate,
HitCount: p.HitCount,
Providers: p.Providers,
PromptPreview: preview,
})
}
c.JSON(http.StatusOK, gin.H{"prompts": entries})
}
// WarmPromptCacheRequest is the request body for warming the prompt cache.
type WarmPromptCacheRequest struct {
Prompts []cache.WarmPromptEntry `json:"prompts"`
}
// WarmPromptCacheResponse is the response for the warm operation.
type WarmPromptCacheResponse struct {
Status string `json:"status"`
Total int `json:"total"`
Added int `json:"added"`
Skipped int `json:"skipped"`
Errors int `json:"errors"`
}
// WarmPromptCache pre-populates the prompt cache with known system prompts.
// POST /v0/management/prompt-cache/warm
func (h *Handler) WarmPromptCache(c *gin.Context) {
var req WarmPromptCacheRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
if len(req.Prompts) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "no prompts provided"})
return
}
promptCache := cache.GetDefaultPromptCache()
if promptCache == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "prompt cache not initialized"})
return
}
result := promptCache.WarmCache(req.Prompts)
c.JSON(http.StatusOK, WarmPromptCacheResponse{
Status: "ok",
Total: result.Total,
Added: result.Added,
Skipped: result.Skipped,
Errors: result.Errors,
})
}
@@ -19,8 +19,8 @@ import (
)
const (
latestReleaseURL = "https://api.github.com/repos/Finesssee/ProxyPilot/releases/latest"
latestReleaseUserAgent = "ProxyPilot"
latestReleaseURL = "https://api.github.com/repos/router-for-me/CLIProxyAPI/releases/latest"
latestReleaseUserAgent = "CLIProxyAPI"
)
func (h *Handler) GetConfig(c *gin.Context) {
@@ -28,7 +28,7 @@ func (h *Handler) GetConfig(c *gin.Context) {
c.JSON(200, gin.H{})
return
}
c.JSON(200, h.cfg)
c.JSON(200, new(*h.cfg))
}
type releaseInfo struct {
@@ -158,8 +158,7 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()})
return
}
h.cfg = cloneConfig(newCfg)
h.committedCfg = cloneConfig(h.cfg)
h.cfg = newCfg
c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})
}
@@ -184,16 +183,14 @@ func (h *Handler) GetConfigYAML(c *gin.Context) {
// Debug
func (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }
func (h *Handler) PutDebug(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.Debug = v })
}
func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
// UsageStatisticsEnabled
func (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) {
c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})
}
func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.UsageStatisticsEnabled = v })
h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })
}
// UsageStatisticsEnabled
@@ -201,7 +198,7 @@ func (h *Handler) GetLoggingToFile(c *gin.Context) {
c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})
}
func (h *Handler) PutLoggingToFile(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.LoggingToFile = v })
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
}
// LogsMaxTotalSizeMB
@@ -220,9 +217,8 @@ func (h *Handler) PutLogsMaxTotalSizeMB(c *gin.Context) {
if value < 0 {
value = 0
}
h.mutateConfig(c, func(cfg *config.Config) {
cfg.LogsMaxTotalSizeMB = value
})
h.cfg.LogsMaxTotalSizeMB = value
h.persist(c)
}
// ErrorLogsMaxFiles
@@ -241,15 +237,14 @@ func (h *Handler) PutErrorLogsMaxFiles(c *gin.Context) {
if value < 0 {
value = 10
}
h.mutateConfig(c, func(cfg *config.Config) {
cfg.ErrorLogsMaxFiles = value
})
h.cfg.ErrorLogsMaxFiles = value
h.persist(c)
}
// Request log
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
func (h *Handler) PutRequestLog(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.RequestLog = v })
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
}
// Websocket auth
@@ -257,7 +252,7 @@ func (h *Handler) GetWebsocketAuth(c *gin.Context) {
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
}
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.WebsocketAuth = v })
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
}
// Request retry
@@ -265,7 +260,7 @@ func (h *Handler) GetRequestRetry(c *gin.Context) {
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
}
func (h *Handler) PutRequestRetry(c *gin.Context) {
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.RequestRetry = v })
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
}
// Max retry interval
@@ -273,7 +268,7 @@ func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
}
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
h.updateIntField(c, func(cfg *config.Config, v int) { cfg.MaxRetryInterval = v })
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
}
// ForceModelPrefix
@@ -281,7 +276,7 @@ func (h *Handler) GetForceModelPrefix(c *gin.Context) {
c.JSON(200, gin.H{"force-model-prefix": h.cfg.ForceModelPrefix})
}
func (h *Handler) PutForceModelPrefix(c *gin.Context) {
h.updateBoolField(c, func(cfg *config.Config, v bool) { cfg.ForceModelPrefix = v })
h.updateBoolField(c, func(v bool) { h.cfg.ForceModelPrefix = v })
}
func normalizeRoutingStrategy(strategy string) (string, bool) {
@@ -318,18 +313,16 @@ func (h *Handler) PutRoutingStrategy(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid strategy"})
return
}
h.mutateConfig(c, func(cfg *config.Config) {
cfg.Routing.Strategy = normalized
})
h.cfg.Routing.Strategy = normalized
h.persist(c)
}
// Proxy URL
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
func (h *Handler) PutProxyURL(c *gin.Context) {
h.updateStringField(c, func(cfg *config.Config, v string) { cfg.ProxyURL = v })
h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })
}
func (h *Handler) DeleteProxyURL(c *gin.Context) {
h.mutateConfig(c, func(cfg *config.Config) {
cfg.ProxyURL = ""
})
h.cfg.ProxyURL = ""
h.persist(c)
}
@@ -1,170 +0,0 @@
package management
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
)
// ImportCredential handles uploading a text file with credentials for a specific provider.
// Each credential is processed and saved as a separate auth record.
func (h *Handler) ImportCredential(c *gin.Context) {
provider := c.Param("provider")
if provider == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "provider required"})
return
}
if h == nil || h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "config unavailable"})
return
}
if h.cfg.AuthDir == "" {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth directory not configured"})
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
defer file.Close()
ctx := c.Request.Context()
if ctx == nil {
ctx = context.Background()
}
lines, err := parseLines(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to parse file", "details": err.Error()})
return
}
if len(lines) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "no valid credentials found in file"})
return
}
var results []importResult
successCount := 0
for i, raw := range lines {
lineNum := i + 1
var result importResult
switch provider {
case "openai", "claude", "gemini":
// Generic API Key import
result = h.processAPIKey(ctx, provider, raw, lineNum)
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported provider for bulk import"})
return
}
if result.Success {
successCount++
}
results = append(results, result)
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"provider": provider,
"total": len(lines),
"success_count": successCount,
"failed_count": len(lines) - successCount,
"results": results,
})
}
// 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
func (s GenericTokenStorage) SaveTokenToFile(path string) error {
return nil
}
// processAPIKey handles generic API key import
func (h *Handler) processAPIKey(ctx context.Context, provider, key string, lineNum int) importResult {
key = strings.TrimSpace(key)
if key == "" {
return importResult{Line: lineNum, Success: false, Error: "empty key"}
}
// Basic duplicate check could be added here if needed
timestamp := time.Now().Unix()
fileName := newImportedCredentialFileName(provider, timestamp)
record := &coreauth.Auth{
ID: fileName,
Provider: provider,
FileName: fileName,
Storage: GenericTokenStorage{
"api_key": key,
},
Metadata: map[string]any{
"imported_at": timestamp,
"source": "bulk_import",
},
Attributes: map[string]string{
"api_key": key,
},
}
savedPath, err := h.saveTokenRecord(ctx, record)
if err != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to save credential"}
}
return importResult{Line: lineNum, Success: true, SavedPath: savedPath}
}
func parseLines(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
func newImportedCredentialFileName(provider string, timestamp int64) string {
suffix := make([]byte, 6)
if _, err := rand.Read(suffix); err != nil {
return fmt.Sprintf("%s-import-%d.json", provider, timestamp)
}
return fmt.Sprintf("%s-import-%d-%s.json", provider, timestamp, hex.EncodeToString(suffix))
}
-171
View File
@@ -1,171 +0,0 @@
package management
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/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,80 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/integrations"
)
// GetIntegrationsStatus returns the list of detected tools and their configuration status.
func (h *Handler) GetIntegrationsStatus(c *gin.Context) {
if h.integrationManager == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "integration manager not initialized"})
return
}
statuses := h.integrationManager.ListStatus()
c.JSON(http.StatusOK, gin.H{"integrations": statuses})
}
// PostIntegrationConfigure triggers the configuration logic for a specific tool.
func (h *Handler) PostIntegrationConfigure(c *gin.Context) {
if h.integrationManager == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "integration manager not initialized"})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing integration id"})
return
}
if err := h.integrationManager.Configure(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "configured", "id": id})
}
// GetCLIAgents returns the list of detected CLI agents and IDEs.
func (h *Handler) GetCLIAgents(c *gin.Context) {
proxyURL := h.cfg.ProxyURL
if proxyURL == "" {
proxyURL = "http://localhost:8080"
}
agents := integrations.DetectCLIAgents(proxyURL)
c.JSON(http.StatusOK, gin.H{"agents": agents})
}
// PostCLIAgentConfigure configures a CLI agent to use the proxy.
func (h *Handler) PostCLIAgentConfigure(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
proxyURL := h.cfg.ProxyURL
if proxyURL == "" {
proxyURL = "http://localhost:8080"
}
if err := integrations.ConfigureCLIAgent(id, proxyURL); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "configured", "id": id})
}
// PostCLIAgentUnconfigure removes proxy configuration from a CLI agent.
func (h *Handler) PostCLIAgentUnconfigure(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing agent id"})
return
}
if err := integrations.UnconfigureCLIAgent(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "unconfigured", "id": id})
}
@@ -1,111 +0,0 @@
package management
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
)
func TestDeleteMemorySession_RejectsTraversal(t *testing.T) {
t.Setenv("CLIPROXY_MEMORY_DIR", t.TempDir())
gin.SetMode(gin.TestMode)
outsidePath := filepath.Join(t.TempDir(), "outside")
if err := os.WriteFile(outsidePath, []byte("keep"), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/memory/session?session="+url.QueryEscape("../outside"), nil)
h := &Handler{}
h.DeleteMemorySession(ctx)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
if _, err := os.Stat(outsidePath); err != nil {
t.Fatalf("outside path should remain untouched: %v", err)
}
}
func TestProcessAPIKey_DoesNotLeakSecretPrefixInSavedPath(t *testing.T) {
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
key := "sk-secret-prefix-1234567890"
result := h.processAPIKey(context.Background(), "openai", key, 1)
if !result.Success {
t.Fatalf("processAPIKey() failed: %+v", result)
}
if strings.Contains(result.SavedPath, "sk-secret") {
t.Fatalf("saved path leaked key prefix: %q", result.SavedPath)
}
if !strings.HasPrefix(filepath.Base(result.SavedPath), "openai-import-") {
t.Fatalf("saved path = %q, want generated import prefix", result.SavedPath)
}
}
func TestCommitUploadedAuthFile_InvalidDataDoesNotWriteFile(t *testing.T) {
gin.SetMode(gin.TestMode)
authDir := t.TempDir()
path := filepath.Join(authDir, "broken.json")
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
err := h.commitUploadedAuthFile(context.Background(), path, []byte(`{"type":`))
if err == nil {
t.Fatal("commitUploadedAuthFile() unexpectedly succeeded")
}
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("invalid upload should not leave a file behind, stat err=%v", statErr)
}
}
func TestGetConfig_ReturnsLiveConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
h := NewHandlerWithoutConfigFilePath(&config.Config{
SDKConfig: config.SDKConfig{
ProxyURL: "http://127.0.0.1:8080",
},
Debug: true,
UsageStatisticsEnabled: true,
}, nil)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/config", nil)
h.GetConfig(ctx)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want %d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
var got config.Config
if err := json.Unmarshal(recorder.Body.Bytes(), &got); err != nil {
t.Fatalf("Unmarshal() error = %v body=%s", err, recorder.Body.String())
}
if !got.Debug {
t.Fatalf("Debug = %v, want true", got.Debug)
}
if got.ProxyURL != "http://127.0.0.1:8080" {
t.Fatalf("ProxyURL = %q", got.ProxyURL)
}
if !got.UsageStatisticsEnabled {
t.Fatalf("UsageStatisticsEnabled = %v, want true", got.UsageStatisticsEnabled)
}
}
-477
View File
@@ -1,477 +0,0 @@
package management
import (
"archive/zip"
"bytes"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
)
func (h *Handler) ListMemorySessions(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"sessions": []any{}})
return
}
limit := 50
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
sessions, err := store.ListSessions(limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(sessions))
for _, s := range sessions {
out = append(out, gin.H{
"key": s.Key,
"updated_at": formatTime(s.UpdatedAt),
"size_bytes": s.SizeBytes,
"events_bytes": s.EventsBytes,
"has_summary": s.HasSummary,
"has_todo": s.HasTodo,
"has_pinned": s.HasPinned,
"has_anchor_pending": s.HasAnchorPending,
"semantic_disabled": s.SemanticDisabled,
})
}
c.JSON(http.StatusOK, gin.H{"sessions": out})
}
func (h *Handler) GetMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"session": gin.H{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
store := memory.NewFileStore(base)
info, err := store.GetSessionInfo(session)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := gin.H{
"key": info.Key,
"updated_at": formatTime(info.UpdatedAt),
"size_bytes": info.SizeBytes,
"events_bytes": info.EventsBytes,
"has_summary": info.HasSummary,
"has_todo": info.HasTodo,
"has_pinned": info.HasPinned,
"has_anchor_pending": info.HasAnchorPending,
"semantic_disabled": info.SemanticDisabled,
}
out["summary"] = store.ReadSummary(session, 14_000)
out["todo"] = store.ReadTodo(session, 8_000)
out["pinned"] = store.ReadPinned(session, 8_000)
out["anchor_pending"] = store.ReadPendingAnchor(session, 6_000)
c.JSON(http.StatusOK, gin.H{"session": out})
}
func (h *Handler) GetMemoryEvents(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"events": []any{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
limit := 100
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
events, err := store.ReadEventTail(session, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(events))
for _, e := range events {
out = append(out, gin.H{
"ts": formatTime(e.TS),
"kind": e.Kind,
"role": e.Role,
"type": e.Type,
"text": e.Text,
})
}
c.JSON(http.StatusOK, gin.H{"events": out})
}
func (h *Handler) GetMemoryAnchors(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"anchors": []any{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
limit := 20
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
limit = n
}
}
store := memory.NewFileStore(base)
anchors, err := store.ReadAnchorTail(session, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(anchors))
for _, a := range anchors {
out = append(out, gin.H{
"ts": formatTime(a.TS),
"summary": a.Summary,
})
}
c.JSON(http.StatusOK, gin.H{"anchors": out})
}
type memoryUpdateRequest struct {
Session string `json:"session"`
Value string `json:"value"`
}
func (h *Handler) PutMemoryTodo(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
return store.WriteTodo(session, value, 8000)
})
}
func (h *Handler) PutMemoryPinned(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
return store.WritePinned(session, value, 8000)
})
}
func (h *Handler) PutMemorySummary(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
if anchorAppendOnlyEnabled() {
return store.SetAnchorSummary(session, value, 14_000)
}
return store.WriteSummary(session, value, 14_000)
})
}
type memoryToggleRequest struct {
Session string `json:"session"`
Enabled *bool `json:"enabled"`
}
func (h *Handler) PutMemorySemanticToggle(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req memoryToggleRequest
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Session) == "" || req.Enabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
if err := store.SetSemanticDisabled(req.Session, !*req.Enabled); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) DeleteMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
store := memory.NewFileStore(base)
_, path, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
if err := os.RemoveAll(path); err != nil && !os.IsNotExist(err) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
type memoryPruneRequest struct {
MaxAgeDays *int `json:"max_age_days"`
MaxSessions *int `json:"max_sessions"`
MaxBytesPerSession *int64 `json:"max_bytes_per_session"`
MaxNamespaces *int `json:"max_namespaces"`
MaxBytesPerNamespace *int64 `json:"max_bytes_per_namespace"`
}
func (h *Handler) PruneMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
var req memoryPruneRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
maxAge := 0
maxSessions := 0
maxBytesSession := int64(0)
maxNamespaces := 0
maxBytesNamespace := int64(0)
if req.MaxAgeDays != nil {
maxAge = *req.MaxAgeDays
}
if req.MaxSessions != nil {
maxSessions = *req.MaxSessions
}
if req.MaxBytesPerSession != nil {
maxBytesSession = *req.MaxBytesPerSession
}
if req.MaxNamespaces != nil {
maxNamespaces = *req.MaxNamespaces
}
if req.MaxBytesPerNamespace != nil {
maxBytesNamespace = *req.MaxBytesPerNamespace
}
sres, err := store.PruneSessions(maxAge, maxSessions, maxBytesSession)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
semres, err := store.PruneSemantic(maxAge, maxNamespaces, maxBytesNamespace)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := memory.PruneResult{
SessionsRemoved: sres.SessionsRemoved,
SessionsTrimmed: sres.SessionsTrimmed,
SemanticNamespacesRemoved: semres.SemanticNamespacesRemoved,
SemanticNamespacesTrimmed: semres.SemanticNamespacesTrimmed,
BytesFreed: sres.BytesFreed + semres.BytesFreed,
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "result": out})
}
func (h *Handler) ExportMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
store := memory.NewFileStore(base)
session, dir, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
if _, err := os.Stat(dir); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
data, err := memory.ExportSessionZip(dir)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if max := memoryExportMaxBytes(); max > 0 && int64(len(data)) > max {
c.JSON(http.StatusInternalServerError, gin.H{"error": "export exceeds size limit"})
return
}
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\"proxypilot-session-"+session+".zip\"")
c.Data(http.StatusOK, "application/zip", data)
}
func (h *Handler) ExportAllMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
data, err := memory.ExportAllZip(base, memoryExportMaxBytes())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\"proxypilot-memory-all.zip\"")
c.Data(http.StatusOK, "application/zip", data)
}
func (h *Handler) DeleteAllMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
confirm := strings.TrimSpace(c.Query("confirm"))
if !strings.EqualFold(confirm, "true") && !strings.EqualFold(confirm, "yes") {
c.JSON(http.StatusBadRequest, gin.H{"error": "confirm=true required"})
return
}
if err := os.RemoveAll(base); err != nil && !os.IsNotExist(err) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) ImportMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
if ct := strings.TrimSpace(c.ContentType()); ct != "" && !strings.HasPrefix(strings.ToLower(ct), "multipart/") {
c.JSON(http.StatusBadRequest, gin.H{"error": "multipart form required"})
return
}
store := memory.NewFileStore(base)
_, dest, ok := resolveManagedMemorySession(c, store, c.Query("session"))
if !ok {
return
}
replace := strings.EqualFold(strings.TrimSpace(c.Query("replace")), "true")
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
return
}
if fileHeader.Size > 50*1024*1024 {
c.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, 50*1024*1024))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid zip"})
return
}
if replace {
_ = os.RemoveAll(dest)
}
if err := os.MkdirAll(dest, 0o755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
}
name := filepath.ToSlash(f.Name)
name = strings.TrimPrefix(name, "/")
if strings.Contains(name, "..") {
continue
}
target := filepath.Join(dest, filepath.FromSlash(name))
if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(dest)) {
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
continue
}
rc, err := f.Open()
if err != nil {
continue
}
b, err := io.ReadAll(io.LimitReader(rc, 10*1024*1024))
_ = rc.Close()
if err != nil {
continue
}
_ = os.WriteFile(target, b, 0o644)
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) updateMemoryField(c *gin.Context, fn func(store *memory.FileStore, session string, value string) error) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req memoryUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Session) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
if err := fn(store, req.Session, req.Value); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func formatTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
func anchorAppendOnlyEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_ANCHOR_APPEND_ONLY")); v != "" {
if strings.EqualFold(v, "0") || strings.EqualFold(v, "false") || strings.EqualFold(v, "off") || strings.EqualFold(v, "no") {
return false
}
}
return true
}
func resolveManagedMemorySession(c *gin.Context, store *memory.FileStore, rawSession string) (string, string, bool) {
session := strings.TrimSpace(rawSession)
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return "", "", false
}
if strings.Contains(session, "..") || strings.ContainsAny(session, `/\`) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid session"})
return "", "", false
}
dir := store.SessionDir(session)
if dir == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve session path"})
return "", "", false
}
return filepath.Base(dir), dir, true
}
@@ -1,29 +0,0 @@
package management
import (
"os"
"path/filepath"
"strconv"
"strings"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
)
func memoryBaseDir() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_MEMORY_DIR")); v != "" {
return v
}
if w := util.WritablePath(); w != "" {
return filepath.Join(w, ".proxypilot", "memory")
}
return filepath.Join(".proxypilot", "memory")
}
func memoryExportMaxBytes() int64 {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_MEMORY_EXPORT_MAX_BYTES")); v != "" {
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
return n
}
}
return 250 * 1024 * 1024
}
@@ -1,95 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
)
// ModelMappingEntry represents a global model mapping for the API
type ModelMappingEntry struct {
From string `json:"from"`
To string `json:"to"`
Provider string `json:"provider,omitempty"`
Enabled bool `json:"enabled"`
}
// GetModelMappings returns the current global model mappings
func (h *Handler) GetModelMappings(c *gin.Context) {
if h.cfg == nil {
c.JSON(http.StatusOK, gin.H{"mappings": []any{}})
return
}
mappings := make([]ModelMappingEntry, 0, len(h.cfg.GlobalModelMappings))
for _, m := range h.cfg.GlobalModelMappings {
mappings = append(mappings, ModelMappingEntry{
From: m.From,
To: m.To,
Provider: m.Provider,
Enabled: m.IsEnabled(),
})
}
c.JSON(http.StatusOK, gin.H{"mappings": mappings})
}
// SetModelMappings replaces all global model mappings
func (h *Handler) SetModelMappings(c *gin.Context) {
var req struct {
Mappings []ModelMappingEntry `json:"mappings"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if h.cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config not loaded"})
return
}
// Convert to config type
newMappings := make([]config.GlobalModelMapping, 0, len(req.Mappings))
for _, m := range req.Mappings {
enabled := m.Enabled
newMappings = append(newMappings, config.GlobalModelMapping{
From: m.From,
To: m.To,
Provider: m.Provider,
Enabled: &enabled,
})
}
h.cfg.GlobalModelMappings = newMappings
// Try to save config if configPath is available
// Note: This requires the config path to be stored somewhere accessible
c.JSON(http.StatusOK, gin.H{"status": "ok", "count": len(newMappings)})
}
// TestModelMapping tests a model name against global mappings
func (h *Handler) TestModelMapping(c *gin.Context) {
model := c.Query("model")
provider := c.Query("provider")
if model == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing model parameter"})
return
}
if h.cfg == nil {
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": model, "matched": false})
return
}
mappedTo := h.cfg.LookupGlobalModelMapping(model, provider)
if mappedTo == "" {
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": model, "matched": false})
return
}
c.JSON(http.StatusOK, gin.H{"model": model, "mapped_to": mappedTo, "matched": true})
}
@@ -1,176 +0,0 @@
package management
import (
"bytes"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
)
// GetProxyPilotLogTail returns tail lines for the launcher-managed stdout/stderr logs.
// These files are written by ProxyPilot when it spawns the server binary.
func (h *Handler) GetProxyPilotLogTail(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
kind := strings.ToLower(strings.TrimSpace(c.Query("file")))
lines := 200
if v := strings.TrimSpace(c.Query("lines")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 2000 {
lines = n
}
}
var name string
switch kind {
case "stdout", "out":
name = "proxypilot-engine.out.log"
case "stderr", "err":
name = "proxypilot-engine.err.log"
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file (use stdout|stderr)"})
return
}
dir := h.logDirectory()
full := filepath.Join(dir, name)
content, truncated, err := tailTextFile(full, lines, 512*1024)
if err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusOK, gin.H{"lines": []string{}, "truncated": false})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log: %v", err)})
return
}
outLines := splitLines(content)
if len(outLines) > lines {
outLines = outLines[len(outLines)-lines:]
truncated = true
}
c.JSON(http.StatusOK, gin.H{"lines": outLines, "truncated": truncated})
}
// GetProxyPilotDiagnostics returns a single text blob suitable for copy/paste.
func (h *Handler) GetProxyPilotDiagnostics(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
lines := 120
if v := strings.TrimSpace(c.Query("lines")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 1000 {
lines = n
}
}
var b strings.Builder
b.WriteString("ProxyPilot Diagnostics\n")
b.WriteString("\n")
b.WriteString(fmt.Sprintf("Built: version=%s commit=%s date=%s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate))
if h.cfg != nil {
b.WriteString(fmt.Sprintf("Port: %d\n", h.cfg.Port))
b.WriteString(fmt.Sprintf("AuthDir: %s\n", strings.TrimSpace(h.cfg.AuthDir)))
b.WriteString(fmt.Sprintf("RequestLog: %v\n", h.cfg.RequestLog))
b.WriteString(fmt.Sprintf("Debug: %v\n", h.cfg.Debug))
}
if strings.TrimSpace(h.configFilePath) != "" {
b.WriteString(fmt.Sprintf("ConfigPath: %s\n", h.configFilePath))
}
logDir := h.logDirectory()
b.WriteString(fmt.Sprintf("LogDir: %s\n", logDir))
b.WriteString(fmt.Sprintf("CapturedAt: %s\n", time.Now().Format(time.RFC3339)))
b.WriteString("\n")
addTail := func(label, fileName string) {
full := filepath.Join(logDir, fileName)
content, _, err := tailTextFile(full, lines, 512*1024)
b.WriteString("=== " + label + " (" + fileName + ") ===\n")
if err != nil {
if os.IsNotExist(err) {
b.WriteString("(file not found)\n\n")
return
}
b.WriteString("(error reading log: " + err.Error() + ")\n\n")
return
}
b.WriteString(content)
if !strings.HasSuffix(content, "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
}
addTail("Launcher Stdout", "proxypilot-engine.out.log")
addTail("Launcher Stderr", "proxypilot-engine.err.log")
c.JSON(http.StatusOK, gin.H{"text": b.String()})
}
func splitLines(s string) []string {
s = strings.ReplaceAll(s, "\r\n", "\n")
s = strings.TrimSuffix(s, "\n")
if strings.TrimSpace(s) == "" {
return []string{}
}
return strings.Split(s, "\n")
}
func tailTextFile(path string, wantLines int, maxBytes int64) (string, bool, error) {
f, err := os.Open(path)
if err != nil {
return "", false, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return "", false, err
}
size := info.Size()
if size <= 0 {
return "", false, nil
}
readBytes := maxBytes
if readBytes <= 0 {
readBytes = 256 * 1024
}
if readBytes > size {
readBytes = size
}
start := size - readBytes
if _, err := f.Seek(start, 0); err != nil {
return "", false, err
}
buf := make([]byte, readBytes)
n, err := f.Read(buf)
if err != nil && n == 0 {
return "", false, err
}
buf = buf[:n]
// Drop partial first line when we started mid-file.
if start > 0 {
if i := bytes.IndexByte(buf, '\n'); i >= 0 && i+1 < len(buf) {
buf = buf[i+1:]
}
}
text := string(buf)
// Best-effort: return enough lines; caller will truncate if needed.
truncated := start > 0
if wantLines <= 0 {
return text, truncated, nil
}
return text, truncated, nil
}
@@ -1,168 +0,0 @@
package management
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// RateLimitEntry represents the rate limit status for a single credential.
type RateLimitEntry struct {
AuthID string `json:"auth_id"`
Provider string `json:"provider"`
Label string `json:"label,omitempty"`
Email string `json:"email,omitempty"`
QuotaExceeded bool `json:"quota_exceeded"`
QuotaReason string `json:"quota_reason,omitempty"`
RecoverAt time.Time `json:"recover_at,omitempty"`
RecoverIn string `json:"recover_in,omitempty"`
BackoffLevel int `json:"backoff_level,omitempty"`
ModelLimits []ModelRateLimitEntry `json:"model_limits,omitempty"`
}
// ModelRateLimitEntry represents the rate limit status for a specific model.
type ModelRateLimitEntry struct {
Model string `json:"model"`
QuotaExceeded bool `json:"quota_exceeded"`
QuotaReason string `json:"quota_reason,omitempty"`
RecoverAt time.Time `json:"recover_at,omitempty"`
RecoverIn string `json:"recover_in,omitempty"`
BackoffLevel int `json:"backoff_level,omitempty"`
}
// RateLimitsResponse contains overall rate limit status.
type RateLimitsResponse struct {
TotalCredentials int `json:"total_credentials"`
CoolingDown int `json:"cooling_down"`
Available int `json:"available"`
Credentials []RateLimitEntry `json:"credentials"`
}
// GetRateLimits returns the rate limit status for all credentials.
// GET /v0/management/rate-limits
func (h *Handler) GetRateLimits(c *gin.Context) {
if h.authManager == nil {
c.JSON(http.StatusOK, RateLimitsResponse{})
return
}
auths := h.authManager.List()
now := time.Now()
resp := RateLimitsResponse{
TotalCredentials: len(auths),
Credentials: make([]RateLimitEntry, 0, len(auths)),
}
for _, auth := range auths {
entry := RateLimitEntry{
AuthID: auth.ID,
Provider: auth.Provider,
Label: auth.Label,
QuotaExceeded: auth.Quota.Exceeded,
QuotaReason: auth.Quota.Reason,
BackoffLevel: auth.Quota.BackoffLevel,
}
// Extract email from metadata
if auth.Metadata != nil {
if email, ok := auth.Metadata["email"].(string); ok {
entry.Email = email
}
}
// Calculate recover time
if !auth.Quota.NextRecoverAt.IsZero() {
entry.RecoverAt = auth.Quota.NextRecoverAt
if auth.Quota.NextRecoverAt.After(now) {
entry.RecoverIn = auth.Quota.NextRecoverAt.Sub(now).Round(time.Second).String()
}
}
// Per-model rate limits
if len(auth.ModelStates) > 0 {
entry.ModelLimits = make([]ModelRateLimitEntry, 0, len(auth.ModelStates))
for model, state := range auth.ModelStates {
if state.Quota.Exceeded || !state.Quota.NextRecoverAt.IsZero() {
modelEntry := ModelRateLimitEntry{
Model: model,
QuotaExceeded: state.Quota.Exceeded,
QuotaReason: state.Quota.Reason,
BackoffLevel: state.Quota.BackoffLevel,
}
if !state.Quota.NextRecoverAt.IsZero() {
modelEntry.RecoverAt = state.Quota.NextRecoverAt
if state.Quota.NextRecoverAt.After(now) {
modelEntry.RecoverIn = state.Quota.NextRecoverAt.Sub(now).Round(time.Second).String()
}
}
entry.ModelLimits = append(entry.ModelLimits, modelEntry)
}
}
}
// Count cooling down vs available
isCooling := auth.Quota.Exceeded || (auth.Quota.NextRecoverAt.After(now))
if isCooling {
resp.CoolingDown++
} else if !auth.Disabled && !auth.Unavailable {
resp.Available++
}
resp.Credentials = append(resp.Credentials, entry)
}
c.JSON(http.StatusOK, resp)
}
// GetRateLimitsSummary returns a brief summary of rate limit status.
// GET /v0/management/rate-limits/summary
func (h *Handler) GetRateLimitsSummary(c *gin.Context) {
if h.authManager == nil {
c.JSON(http.StatusOK, gin.H{
"total": 0,
"available": 0,
"cooling_down": 0,
"disabled": 0,
})
return
}
auths := h.authManager.List()
now := time.Now()
var available, coolingDown, disabled int
var nextRecovery time.Time
for _, auth := range auths {
if auth.Disabled {
disabled++
continue
}
isCooling := auth.Quota.Exceeded || (auth.Quota.NextRecoverAt.After(now))
if isCooling {
coolingDown++
if nextRecovery.IsZero() || auth.Quota.NextRecoverAt.Before(nextRecovery) {
nextRecovery = auth.Quota.NextRecoverAt
}
} else if !auth.Unavailable {
available++
}
}
resp := gin.H{
"total": len(auths),
"available": available,
"cooling_down": coolingDown,
"disabled": disabled,
}
if !nextRecovery.IsZero() && nextRecovery.After(now) {
resp["next_recovery_at"] = nextRecovery
resp["next_recovery_in"] = nextRecovery.Sub(now).Round(time.Second).String()
}
c.JSON(http.StatusOK, resp)
}
@@ -1,168 +0,0 @@
package management
import (
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
)
// GetRequestHistory returns the persistent request history with optional filtering.
// GET /v0/management/request-history
func (h *Handler) GetRequestHistory(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
// Parse filter parameters
filter := &middleware.RequestHistoryFilter{}
if startDateStr := c.Query("start_date"); startDateStr != "" {
if t, err := time.Parse(time.RFC3339, startDateStr); err == nil {
filter.StartDate = &t
}
}
if endDateStr := c.Query("end_date"); endDateStr != "" {
if t, err := time.Parse(time.RFC3339, endDateStr); err == nil {
filter.EndDate = &t
}
}
filter.Model = c.Query("model")
filter.Provider = c.Query("provider")
if statusMinStr := c.Query("status_min"); statusMinStr != "" {
if v, err := strconv.Atoi(statusMinStr); err == nil {
filter.StatusMin = v
}
}
if statusMaxStr := c.Query("status_max"); statusMaxStr != "" {
if v, err := strconv.Atoi(statusMaxStr); err == nil {
filter.StatusMax = v
}
}
if errorsOnly := c.Query("errors_only"); errorsOnly == "true" {
filter.ErrorsOnly = true
}
if limitStr := c.Query("limit"); limitStr != "" {
if v, err := strconv.Atoi(limitStr); err == nil {
filter.Limit = v
}
}
if offsetStr := c.Query("offset"); offsetStr != "" {
if v, err := strconv.Atoi(offsetStr); err == nil {
filter.Offset = v
}
}
entries := history.GetEntries(filter)
total := history.Count()
c.JSON(http.StatusOK, gin.H{
"entries": entries,
"total": total,
"count": len(entries),
"filter": filter,
})
}
// GetRequestHistoryStats returns aggregated statistics from request history.
// GET /v0/management/request-history/stats
func (h *Handler) GetRequestHistoryStats(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
stats := history.GetStats()
c.JSON(http.StatusOK, gin.H{
"stats": stats,
})
}
// ClearRequestHistory clears all entries from persistent request history.
// DELETE /v0/management/request-history
func (h *Handler) ClearRequestHistory(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
history.Clear()
c.JSON(http.StatusOK, gin.H{
"message": "Request history cleared",
})
}
// ExportRequestHistory exports the full request history for backup.
// GET /v0/management/request-history/export
func (h *Handler) ExportRequestHistory(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
snapshot := history.Export()
c.JSON(http.StatusOK, snapshot)
}
// ImportRequestHistory imports request history from a backup.
// POST /v0/management/request-history/import
func (h *Handler) ImportRequestHistory(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
data, err := c.GetRawData()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read request body"})
return
}
var snapshot middleware.RequestHistorySnapshot
if err := json.Unmarshal(data, &snapshot); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"})
return
}
added, skipped := history.Import(snapshot)
c.JSON(http.StatusOK, gin.H{
"added": added,
"skipped": skipped,
"total": history.Count(),
})
}
// SaveRequestHistory forces a save of request history to disk.
// POST /v0/management/request-history/save
func (h *Handler) SaveRequestHistory(c *gin.Context) {
history := middleware.GetRequestHistory()
if history == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "request history disabled"})
return
}
if err := history.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Request history saved",
})
}
@@ -1,16 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/api/middleware"
)
// GetRequests returns the list of recent requests from the in-memory ring buffer.
func (h *Handler) GetRequests(c *gin.Context) {
requests := middleware.GetRequestMonitor()
c.JSON(http.StatusOK, gin.H{
"requests": requests,
})
}
@@ -1,182 +0,0 @@
package management
import (
"bytes"
"encoding/json"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/memory"
)
func (h *Handler) GetSemanticHealth(c *gin.Context) {
enabled := semanticEnabled()
baseURL := semanticBaseURL()
model := semanticModel()
status := "disabled"
version := ""
errMsg := ""
modelPresent := false
latencyMs := int64(0)
if enabled {
status = "unreachable"
client := &http.Client{Timeout: 4 * time.Second}
req, _ := http.NewRequest(http.MethodGet, strings.TrimRight(baseURL, "/")+"/api/tags", nil)
resp, err := client.Do(req)
if err != nil {
errMsg = err.Error()
} else {
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var out struct {
Models []struct {
Name string `json:"name"`
} `json:"models"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err == nil {
for _, m := range out.Models {
if strings.EqualFold(strings.TrimSpace(m.Name), strings.TrimSpace(model)) {
modelPresent = true
break
}
}
}
version = resp.Status
} else {
errMsg = resp.Status
}
}
if modelPresent {
start := time.Now()
payload := map[string]any{"model": model, "prompt": "ping"}
body, _ := json.Marshal(payload)
embedReq, _ := http.NewRequest(http.MethodPost, strings.TrimRight(baseURL, "/")+"/api/embeddings", bytes.NewReader(body))
embedReq.Header.Set("Content-Type", "application/json")
embedResp, err := client.Do(embedReq)
if err != nil {
errMsg = err.Error()
} else {
defer embedResp.Body.Close()
if embedResp.StatusCode >= 200 && embedResp.StatusCode < 300 {
status = "ok"
latencyMs = time.Since(start).Milliseconds()
} else {
errMsg = embedResp.Status
}
}
} else if errMsg == "" {
status = "model_missing"
}
}
queueStats := memory.GetSemanticQueueStats()
c.JSON(http.StatusOK, gin.H{
"enabled": enabled,
"baseURL": baseURL,
"model": model,
"status": status,
"version": version,
"model_present": modelPresent,
"latency_ms": latencyMs,
"error": errMsg,
"queue": queueStats,
})
}
func (h *Handler) ListSemanticNamespaces(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"namespaces": []any{}})
return
}
limit := 200
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
namespaces, err := store.ListSemanticNamespaces(limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(namespaces))
for _, ns := range namespaces {
out = append(out, gin.H{
"key": ns.Key,
"label": ns.Namespace,
"updated_at": ns.UpdatedAt.Format(time.RFC3339),
"size_bytes": ns.SizeBytes,
"items_bytes": ns.ItemsBytes,
})
}
c.JSON(http.StatusOK, gin.H{"namespaces": out})
}
func (h *Handler) GetSemanticItems(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"items": []any{}})
return
}
key := strings.TrimSpace(c.Query("namespace"))
if key == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing namespace"})
return
}
limit := 50
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
limit = n
}
}
store := memory.NewFileStore(base)
items, err := store.ReadSemanticTail(key, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(items))
for _, it := range items {
out = append(out, gin.H{
"ts": it.TS.Format(time.RFC3339),
"role": it.Role,
"text": it.Text,
"source": it.Source,
"session": it.Session,
"repo": it.Repo,
})
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
func semanticEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_ENABLED")); v != "" {
if strings.EqualFold(v, "0") || strings.EqualFold(v, "false") || strings.EqualFold(v, "off") || strings.EqualFold(v, "no") {
return false
}
}
return true
}
func semanticModel() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_MODEL")); v != "" {
return v
}
return "embeddinggemma"
}
func semanticBaseURL() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_BASE_URL")); v != "" {
return v
}
return "http://127.0.0.1:11434"
}
@@ -1,107 +0,0 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
)
// ThinkingBudgetResponse represents the thinking budget settings response.
type ThinkingBudgetResponse struct {
Mode string `json:"mode"`
CustomTokens int `json:"custom_tokens"`
Enabled bool `json:"enabled"`
EffectiveTokens int `json:"effective_tokens"`
Presets map[string]int `json:"presets"`
}
// ThinkingBudgetRequest represents a request to update thinking budget settings.
type ThinkingBudgetRequest struct {
Mode string `json:"mode"`
CustomTokens int `json:"custom_tokens"`
Enabled *bool `json:"enabled"`
}
// GetThinkingBudget returns the current thinking budget settings.
// GET /v0/management/thinking-budget
func (h *Handler) GetThinkingBudget(c *gin.Context) {
cfg := h.cfg
if cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config not available"})
return
}
tb := cfg.ThinkingBudget
response := ThinkingBudgetResponse{
Mode: tb.Mode,
CustomTokens: tb.CustomTokens,
Enabled: tb.IsEnabled(),
EffectiveTokens: tb.GetThinkingBudgetTokens(),
Presets: config.ThinkingBudgetPresets,
}
// Default mode if empty
if response.Mode == "" {
response.Mode = "medium"
}
c.JSON(http.StatusOK, response)
}
// SetThinkingBudget updates the thinking budget settings.
// PUT /v0/management/thinking-budget
func (h *Handler) SetThinkingBudget(c *gin.Context) {
cfg := h.cfg
if cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "config not available"})
return
}
var req ThinkingBudgetRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate mode
validModes := map[string]bool{"low": true, "medium": true, "high": true, "custom": true}
if req.Mode != "" && !validModes[req.Mode] {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid mode, must be one of: low, medium, high, custom"})
return
}
// Validate custom tokens
if req.Mode == "custom" && req.CustomTokens <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "custom_tokens must be positive when mode is 'custom'"})
return
}
// Update config
if req.Mode != "" {
cfg.ThinkingBudget.Mode = req.Mode
}
if req.CustomTokens > 0 {
cfg.ThinkingBudget.CustomTokens = req.CustomTokens
}
if req.Enabled != nil {
cfg.ThinkingBudget.Enabled = req.Enabled
}
// Return updated settings
tb := cfg.ThinkingBudget
response := ThinkingBudgetResponse{
Mode: tb.Mode,
CustomTokens: tb.CustomTokens,
Enabled: tb.IsEnabled(),
EffectiveTokens: tb.GetThinkingBudgetTokens(),
Presets: config.ThinkingBudgetPresets,
}
if response.Mode == "" {
response.Mode = "medium"
}
c.JSON(http.StatusOK, response)
}
-145
View File
@@ -1,145 +0,0 @@
package management
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v7/internal/updates"
)
// updateState tracks the current update operation state.
type updateState struct {
mu sync.RWMutex
downloading bool
progress updates.DownloadProgress
downloadResult *updates.DownloadResult
lastError string
}
var currentUpdate = &updateState{}
func (h *Handler) GetUpdateInfo(c *gin.Context) {
info, err := updates.CheckForUpdates()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, info)
}
// GetUpdateStatus returns the current update download status.
func (h *Handler) GetUpdateStatus(c *gin.Context) {
currentUpdate.mu.RLock()
defer currentUpdate.mu.RUnlock()
c.JSON(http.StatusOK, gin.H{
"downloading": currentUpdate.downloading,
"progress": currentUpdate.progress,
"ready": currentUpdate.downloadResult != nil,
"error": currentUpdate.lastError,
})
}
// DownloadUpdate starts downloading an update.
func (h *Handler) DownloadUpdate(c *gin.Context) {
var req struct {
Version string `json:"version"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "version is required"})
return
}
currentUpdate.mu.Lock()
if currentUpdate.downloading {
currentUpdate.mu.Unlock()
c.JSON(http.StatusConflict, gin.H{"error": "download already in progress"})
return
}
currentUpdate.downloading = true
currentUpdate.progress = updates.DownloadProgress{}
currentUpdate.downloadResult = nil
currentUpdate.lastError = ""
currentUpdate.mu.Unlock()
// Start download in background
go func() {
result, err := updates.DownloadUpdate(req.Version, func(progress updates.DownloadProgress) {
currentUpdate.mu.Lock()
currentUpdate.progress = progress
currentUpdate.mu.Unlock()
})
currentUpdate.mu.Lock()
currentUpdate.downloading = false
if err != nil {
currentUpdate.lastError = err.Error()
} else {
currentUpdate.downloadResult = result
}
currentUpdate.mu.Unlock()
}()
c.JSON(http.StatusAccepted, gin.H{"message": "download started"})
}
// VerifyUpdate verifies the downloaded update.
func (h *Handler) VerifyUpdate(c *gin.Context) {
currentUpdate.mu.RLock()
result := currentUpdate.downloadResult
currentUpdate.mu.RUnlock()
if result == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "no download available to verify"})
return
}
verifyResult, err := updates.VerifyDownload(result)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, verifyResult)
}
// InstallUpdate installs the downloaded update.
func (h *Handler) InstallUpdate(c *gin.Context) {
currentUpdate.mu.RLock()
downloadResult := currentUpdate.downloadResult
currentUpdate.mu.RUnlock()
if downloadResult == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "no download available to install"})
return
}
// Verify before install
verifyResult, err := updates.VerifyDownload(downloadResult)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !verifyResult.Valid {
c.JSON(http.StatusBadRequest, gin.H{"error": "verification failed: " + verifyResult.Message})
return
}
// Prepare the update (extract if needed)
executablePath, err := updates.PrepareInstall(downloadResult)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Install
installResult, err := updates.InstallUpdate(executablePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, installResult)
}
+2 -1
View File
@@ -3,6 +3,7 @@ package gemini
import (
"os"
"path/filepath"
"runtime"
"testing"
)
@@ -93,7 +94,7 @@ func TestGeminiTokenStorage_SaveTokenToFile(t *testing.T) {
if err != nil {
t.Fatalf("Stat() error = %v", err)
}
if got := info.Mode().Perm(); got != 0o600 {
if got := info.Mode().Perm(); runtime.GOOS != "windows" && got != 0o600 {
t.Fatalf("file mode = %v, want %v", got, os.FileMode(0o600))
}
+3
View File
@@ -91,6 +91,9 @@ type Config struct {
// When <= 0, the default worker count is used.
AuthAutoRefreshWorkers int `yaml:"auth-auto-refresh-workers" json:"auth-auto-refresh-workers"`
// IncognitoBrowser opens OAuth browser sessions in private/incognito mode when supported.
IncognitoBrowser bool `yaml:"incognito-browser" json:"incognito-browser"`
// RequestRetry defines the retry times when the request failed.
RequestRetry int `yaml:"request-retry" json:"request-retry"`
// MaxRetryCredentials defines the maximum number of credentials to try for a failed request.
+14
View File
@@ -55,6 +55,8 @@ type ModelInfo struct {
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
// SupportedParameters lists supported parameters
SupportedParameters []string `json:"supported_parameters,omitempty"`
// SupportedEndpoints lists OpenAI-compatible endpoints the model supports.
SupportedEndpoints []string `json:"supported_endpoints,omitempty"`
// SupportedInputModalities lists supported input modalities (e.g., TEXT, IMAGE, VIDEO, AUDIO)
SupportedInputModalities []string `json:"supportedInputModalities,omitempty"`
// SupportedOutputModalities lists supported output modalities (e.g., TEXT, IMAGE)
@@ -542,6 +544,9 @@ func cloneModelInfo(model *ModelInfo) *ModelInfo {
if len(model.SupportedParameters) > 0 {
copyModel.SupportedParameters = append([]string(nil), model.SupportedParameters...)
}
if len(model.SupportedEndpoints) > 0 {
copyModel.SupportedEndpoints = append([]string(nil), model.SupportedEndpoints...)
}
if len(model.SupportedInputModalities) > 0 {
copyModel.SupportedInputModalities = append([]string(nil), model.SupportedInputModalities...)
}
@@ -1179,6 +1184,15 @@ func (r *ModelRegistry) convertModelToMap(model *ModelInfo, handlerType string)
}
result["max_input_tokens"] = maxInput
result["max_tokens"] = maxOutput
if model.Thinking != nil {
result["thinking"] = map[string]any{
"min": model.Thinking.Min,
"max": model.Thinking.Max,
"zero_allowed": model.Thinking.ZeroAllowed,
"dynamic_allowed": model.Thinking.DynamicAllowed,
"levels": append([]string(nil), model.Thinking.Levels...),
}
}
return result
case "gemini":
-1
View File
@@ -7,7 +7,6 @@ func TestMergeMissingForkModelSectionsPreservesQwenAndIFlow(t *testing.T) {
Claude: []*ModelInfo{{ID: "claude-1"}},
Gemini: []*ModelInfo{{ID: "gemini-1"}},
Vertex: []*ModelInfo{{ID: "vertex-1"}},
GeminiCLI: []*ModelInfo{{ID: "gemini-cli-1"}},
AIStudio: []*ModelInfo{{ID: "aistudio-1"}},
CodexFree: []*ModelInfo{{ID: "codex-free-1"}},
CodexTeam: []*ModelInfo{{ID: "codex-team-1"}},
+528
View File
@@ -0,0 +1,528 @@
package tui
import (
"fmt"
"io"
"os"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// Tab identifiers
const (
tabDashboard = iota
tabConfig
tabAuthFiles
tabAPIKeys
tabOAuth
tabLogs
)
// App is the root bubbletea model that contains all tab sub-models.
type App struct {
activeTab int
tabs []string
standalone bool
logsEnabled bool
authenticated bool
authInput textinput.Model
authError string
authConnecting bool
dashboard dashboardModel
config configTabModel
auth authTabModel
keys keysTabModel
oauth oauthTabModel
logs logsTabModel
client *Client
width int
height int
ready bool
// Track which tabs have been initialized (fetched data)
initialized [6]bool
}
type authConnectMsg struct {
cfg map[string]any
err error
}
// NewApp creates the root TUI application model.
func NewApp(port int, secretKey string, hook *LogHook) App {
standalone := hook != nil
authRequired := !standalone
ti := textinput.New()
ti.CharLimit = 512
ti.EchoMode = textinput.EchoPassword
ti.EchoCharacter = '*'
ti.SetValue(strings.TrimSpace(secretKey))
ti.Focus()
client := NewClient(port, secretKey)
app := App{
activeTab: tabDashboard,
standalone: standalone,
logsEnabled: true,
authenticated: !authRequired,
authInput: ti,
dashboard: newDashboardModel(client),
config: newConfigTabModel(client),
auth: newAuthTabModel(client),
keys: newKeysTabModel(client),
oauth: newOAuthTabModel(client),
logs: newLogsTabModel(client, hook),
client: client,
initialized: [6]bool{
tabDashboard: true,
tabLogs: true,
},
}
app.refreshTabs()
if authRequired {
app.initialized = [6]bool{}
}
app.setAuthInputPrompt()
return app
}
func (a App) Init() tea.Cmd {
if !a.authenticated {
return textinput.Blink
}
cmds := []tea.Cmd{a.dashboard.Init()}
if a.logsEnabled {
cmds = append(cmds, a.logs.Init())
}
return tea.Batch(cmds...)
}
func (a App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
a.width = msg.Width
a.height = msg.Height
a.ready = true
if a.width > 0 {
a.authInput.Width = a.width - 6
}
contentH := a.height - 4 // tab bar + status bar
if contentH < 1 {
contentH = 1
}
contentW := a.width
a.dashboard.SetSize(contentW, contentH)
a.config.SetSize(contentW, contentH)
a.auth.SetSize(contentW, contentH)
a.keys.SetSize(contentW, contentH)
a.oauth.SetSize(contentW, contentH)
a.logs.SetSize(contentW, contentH)
return a, nil
case authConnectMsg:
a.authConnecting = false
if msg.err != nil {
a.authError = fmt.Sprintf(T("auth_gate_connect_fail"), msg.err.Error())
return a, nil
}
a.authError = ""
a.authenticated = true
a.logsEnabled = a.standalone || isLogsEnabledFromConfig(msg.cfg)
a.refreshTabs()
a.initialized = [6]bool{}
a.initialized[tabDashboard] = true
cmds := []tea.Cmd{a.dashboard.Init()}
if a.logsEnabled {
a.initialized[tabLogs] = true
cmds = append(cmds, a.logs.Init())
}
return a, tea.Batch(cmds...)
case configUpdateMsg:
var cmdLogs tea.Cmd
if !a.standalone && msg.err == nil && msg.path == "logging-to-file" {
logsEnabledConfig, okConfig := msg.value.(bool)
if okConfig {
logsEnabledBefore := a.logsEnabled
a.logsEnabled = logsEnabledConfig
if logsEnabledBefore != a.logsEnabled {
a.refreshTabs()
}
if !a.logsEnabled {
a.initialized[tabLogs] = false
}
if !logsEnabledBefore && a.logsEnabled {
a.initialized[tabLogs] = true
cmdLogs = a.logs.Init()
}
}
}
var cmdConfig tea.Cmd
a.config, cmdConfig = a.config.Update(msg)
if cmdConfig != nil && cmdLogs != nil {
return a, tea.Batch(cmdConfig, cmdLogs)
}
if cmdConfig != nil {
return a, cmdConfig
}
return a, cmdLogs
case tea.KeyMsg:
if !a.authenticated {
switch msg.String() {
case "ctrl+c", "q":
return a, tea.Quit
case "L":
ToggleLocale()
a.refreshTabs()
a.setAuthInputPrompt()
return a, nil
case "enter":
if a.authConnecting {
return a, nil
}
password := strings.TrimSpace(a.authInput.Value())
if password == "" {
a.authError = T("auth_gate_password_required")
return a, nil
}
a.authError = ""
a.authConnecting = true
return a, a.connectWithPassword(password)
default:
var cmd tea.Cmd
a.authInput, cmd = a.authInput.Update(msg)
return a, cmd
}
}
switch msg.String() {
case "ctrl+c":
return a, tea.Quit
case "q":
// Only quit if not in logs tab (where 'q' might be useful)
if !a.logsEnabled || a.activeTab != tabLogs {
return a, tea.Quit
}
case "L":
ToggleLocale()
a.refreshTabs()
return a.broadcastToAllTabs(localeChangedMsg{})
case "tab":
if len(a.tabs) == 0 {
return a, nil
}
prevTab := a.activeTab
a.activeTab = (a.activeTab + 1) % len(a.tabs)
return a, a.initTabIfNeeded(prevTab)
case "shift+tab":
if len(a.tabs) == 0 {
return a, nil
}
prevTab := a.activeTab
a.activeTab = (a.activeTab - 1 + len(a.tabs)) % len(a.tabs)
return a, a.initTabIfNeeded(prevTab)
}
}
if !a.authenticated {
var cmd tea.Cmd
a.authInput, cmd = a.authInput.Update(msg)
return a, cmd
}
// Route msg to active tab
var cmd tea.Cmd
switch a.activeTab {
case tabDashboard:
a.dashboard, cmd = a.dashboard.Update(msg)
case tabConfig:
a.config, cmd = a.config.Update(msg)
case tabAuthFiles:
a.auth, cmd = a.auth.Update(msg)
case tabAPIKeys:
a.keys, cmd = a.keys.Update(msg)
case tabOAuth:
a.oauth, cmd = a.oauth.Update(msg)
case tabLogs:
a.logs, cmd = a.logs.Update(msg)
}
// Keep logs polling alive even when logs tab is not active.
if a.logsEnabled && a.activeTab != tabLogs {
switch msg.(type) {
case logsPollMsg, logsTickMsg, logLineMsg:
var logCmd tea.Cmd
a.logs, logCmd = a.logs.Update(msg)
if logCmd != nil {
cmd = logCmd
}
}
}
return a, cmd
}
// localeChangedMsg is broadcast to all tabs when the user toggles locale.
type localeChangedMsg struct{}
func (a *App) refreshTabs() {
names := TabNames()
if a.logsEnabled {
a.tabs = names
} else {
filtered := make([]string, 0, len(names)-1)
for idx, name := range names {
if idx == tabLogs {
continue
}
filtered = append(filtered, name)
}
a.tabs = filtered
}
if len(a.tabs) == 0 {
a.activeTab = tabDashboard
return
}
if a.activeTab >= len(a.tabs) {
a.activeTab = len(a.tabs) - 1
}
}
func (a *App) initTabIfNeeded(_ int) tea.Cmd {
if a.initialized[a.activeTab] {
return nil
}
a.initialized[a.activeTab] = true
switch a.activeTab {
case tabDashboard:
return a.dashboard.Init()
case tabConfig:
return a.config.Init()
case tabAuthFiles:
return a.auth.Init()
case tabAPIKeys:
return a.keys.Init()
case tabOAuth:
return a.oauth.Init()
case tabLogs:
if !a.logsEnabled {
return nil
}
return a.logs.Init()
}
return nil
}
func (a App) View() string {
if !a.authenticated {
return a.renderAuthView()
}
if !a.ready {
return T("initializing_tui")
}
var sb strings.Builder
// Tab bar
sb.WriteString(a.renderTabBar())
sb.WriteString("\n")
// Content
switch a.activeTab {
case tabDashboard:
sb.WriteString(a.dashboard.View())
case tabConfig:
sb.WriteString(a.config.View())
case tabAuthFiles:
sb.WriteString(a.auth.View())
case tabAPIKeys:
sb.WriteString(a.keys.View())
case tabOAuth:
sb.WriteString(a.oauth.View())
case tabLogs:
if a.logsEnabled {
sb.WriteString(a.logs.View())
}
}
// Status bar
sb.WriteString("\n")
sb.WriteString(a.renderStatusBar())
return sb.String()
}
func (a App) renderAuthView() string {
var sb strings.Builder
sb.WriteString(titleStyle.Render(T("auth_gate_title")))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("auth_gate_help")))
sb.WriteString("\n\n")
if a.authConnecting {
sb.WriteString(warningStyle.Render(T("auth_gate_connecting")))
sb.WriteString("\n\n")
}
if strings.TrimSpace(a.authError) != "" {
sb.WriteString(errorStyle.Render(a.authError))
sb.WriteString("\n\n")
}
sb.WriteString(a.authInput.View())
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("auth_gate_enter")))
return sb.String()
}
func (a App) renderTabBar() string {
var tabs []string
for i, name := range a.tabs {
if i == a.activeTab {
tabs = append(tabs, tabActiveStyle.Render(name))
} else {
tabs = append(tabs, tabInactiveStyle.Render(name))
}
}
tabBar := lipgloss.JoinHorizontal(lipgloss.Top, tabs...)
return tabBarStyle.Width(a.width).Render(tabBar)
}
func (a App) renderStatusBar() string {
left := strings.TrimRight(T("status_left"), " ")
right := strings.TrimRight(T("status_right"), " ")
width := a.width
if width < 1 {
width = 1
}
// statusBarStyle has left/right padding(1), so content area is width-2.
contentWidth := width - 2
if contentWidth < 0 {
contentWidth = 0
}
if lipgloss.Width(left) > contentWidth {
left = fitStringWidth(left, contentWidth)
right = ""
}
remaining := contentWidth - lipgloss.Width(left)
if remaining < 0 {
remaining = 0
}
if lipgloss.Width(right) > remaining {
right = fitStringWidth(right, remaining)
}
gap := contentWidth - lipgloss.Width(left) - lipgloss.Width(right)
if gap < 0 {
gap = 0
}
return statusBarStyle.Width(width).Render(left + strings.Repeat(" ", gap) + right)
}
func fitStringWidth(text string, maxWidth int) string {
if maxWidth <= 0 {
return ""
}
if lipgloss.Width(text) <= maxWidth {
return text
}
out := ""
for _, r := range text {
next := out + string(r)
if lipgloss.Width(next) > maxWidth {
break
}
out = next
}
return out
}
func isLogsEnabledFromConfig(cfg map[string]any) bool {
if cfg == nil {
return true
}
value, ok := cfg["logging-to-file"]
if !ok {
return true
}
enabled, ok := value.(bool)
if !ok {
return true
}
return enabled
}
func (a *App) setAuthInputPrompt() {
if a == nil {
return
}
a.authInput.Prompt = fmt.Sprintf(" %s: ", T("auth_gate_password"))
}
func (a App) connectWithPassword(password string) tea.Cmd {
return func() tea.Msg {
a.client.SetSecretKey(password)
cfg, errGetConfig := a.client.GetConfig()
return authConnectMsg{cfg: cfg, err: errGetConfig}
}
}
// Run starts the TUI application.
// output specifies where bubbletea renders. If nil, defaults to os.Stdout.
func Run(port int, secretKey string, hook *LogHook, output io.Writer) error {
if output == nil {
output = os.Stdout
}
app := NewApp(port, secretKey, hook)
p := tea.NewProgram(app, tea.WithAltScreen(), tea.WithOutput(output))
_, err := p.Run()
return err
}
func (a App) broadcastToAllTabs(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd
var cmd tea.Cmd
a.dashboard, cmd = a.dashboard.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
a.config, cmd = a.config.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
a.auth, cmd = a.auth.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
a.keys, cmd = a.keys.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
a.oauth, cmd = a.oauth.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
a.logs, cmd = a.logs.Update(msg)
if cmd != nil {
cmds = append(cmds, cmd)
}
return a, tea.Batch(cmds...)
}
+456
View File
@@ -0,0 +1,456 @@
package tui
import (
"fmt"
"strconv"
"strings"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// editableField represents an editable field on an auth file.
type editableField struct {
label string
key string // API field key: "prefix", "proxy_url", "priority"
}
var authEditableFields = []editableField{
{label: "Prefix", key: "prefix"},
{label: "Proxy URL", key: "proxy_url"},
{label: "Priority", key: "priority"},
}
// authTabModel displays auth credential files with interactive management.
type authTabModel struct {
client *Client
viewport viewport.Model
files []map[string]any
err error
width int
height int
ready bool
cursor int
expanded int // -1 = none expanded, >=0 = expanded index
confirm int // -1 = no confirmation, >=0 = confirm delete for index
status string
// Editing state
editing bool // true when editing a field
editField int // index into authEditableFields
editInput textinput.Model // text input for editing
editFileName string // name of file being edited
}
type authFilesMsg struct {
files []map[string]any
err error
}
type authActionMsg struct {
action string // "deleted", "toggled", "updated"
err error
}
func newAuthTabModel(client *Client) authTabModel {
ti := textinput.New()
ti.CharLimit = 256
return authTabModel{
client: client,
expanded: -1,
confirm: -1,
editInput: ti,
}
}
func (m authTabModel) Init() tea.Cmd {
return m.fetchFiles
}
func (m authTabModel) fetchFiles() tea.Msg {
files, err := m.client.GetAuthFiles()
return authFilesMsg{files: files, err: err}
}
func (m authTabModel) Update(msg tea.Msg) (authTabModel, tea.Cmd) {
switch msg := msg.(type) {
case localeChangedMsg:
m.viewport.SetContent(m.renderContent())
return m, nil
case authFilesMsg:
if msg.err != nil {
m.err = msg.err
} else {
m.err = nil
m.files = msg.files
if m.cursor >= len(m.files) {
m.cursor = max(0, len(m.files)-1)
}
m.status = ""
}
m.viewport.SetContent(m.renderContent())
return m, nil
case authActionMsg:
if msg.err != nil {
m.status = errorStyle.Render("✗ " + msg.err.Error())
} else {
m.status = successStyle.Render("✓ " + msg.action)
}
m.confirm = -1
m.viewport.SetContent(m.renderContent())
return m, m.fetchFiles
case tea.KeyMsg:
// ---- Editing mode ----
if m.editing {
return m.handleEditInput(msg)
}
// ---- Delete confirmation mode ----
if m.confirm >= 0 {
return m.handleConfirmInput(msg)
}
// ---- Normal mode ----
return m.handleNormalInput(msg)
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
// startEdit activates inline editing for a field on the currently selected auth file.
func (m *authTabModel) startEdit(fieldIdx int) tea.Cmd {
if m.cursor >= len(m.files) {
return nil
}
f := m.files[m.cursor]
m.editFileName = getString(f, "name")
m.editField = fieldIdx
m.editing = true
// Pre-populate with current value
key := authEditableFields[fieldIdx].key
currentVal := getAnyString(f, key)
m.editInput.SetValue(currentVal)
m.editInput.Focus()
m.editInput.Prompt = fmt.Sprintf(" %s: ", authEditableFields[fieldIdx].label)
m.viewport.SetContent(m.renderContent())
return textinput.Blink
}
func (m *authTabModel) SetSize(w, h int) {
m.width = w
m.height = h
m.editInput.Width = w - 20
if !m.ready {
m.viewport = viewport.New(w, h)
m.viewport.SetContent(m.renderContent())
m.ready = true
} else {
m.viewport.Width = w
m.viewport.Height = h
}
}
func (m authTabModel) View() string {
if !m.ready {
return T("loading")
}
return m.viewport.View()
}
func (m authTabModel) renderContent() string {
var sb strings.Builder
sb.WriteString(titleStyle.Render(T("auth_title")))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("auth_help1")))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("auth_help2")))
sb.WriteString("\n")
sb.WriteString(strings.Repeat("─", m.width))
sb.WriteString("\n")
if m.err != nil {
sb.WriteString(errorStyle.Render("⚠ Error: " + m.err.Error()))
sb.WriteString("\n")
return sb.String()
}
if len(m.files) == 0 {
sb.WriteString(subtitleStyle.Render(T("no_auth_files")))
sb.WriteString("\n")
return sb.String()
}
for i, f := range m.files {
name := getString(f, "name")
channel := getString(f, "channel")
email := getString(f, "email")
disabled := getBool(f, "disabled")
statusIcon := successStyle.Render("●")
statusText := T("status_active")
if disabled {
statusIcon = lipgloss.NewStyle().Foreground(colorMuted).Render("○")
statusText = T("status_disabled")
}
cursor := " "
rowStyle := lipgloss.NewStyle()
if i == m.cursor {
cursor = "▸ "
rowStyle = lipgloss.NewStyle().Bold(true)
}
displayName := name
if len(displayName) > 24 {
displayName = displayName[:21] + "..."
}
displayEmail := email
if len(displayEmail) > 28 {
displayEmail = displayEmail[:25] + "..."
}
row := fmt.Sprintf("%s%s %-24s %-12s %-28s %s",
cursor, statusIcon, displayName, channel, displayEmail, statusText)
sb.WriteString(rowStyle.Render(row))
sb.WriteString("\n")
// Delete confirmation
if m.confirm == i {
sb.WriteString(warningStyle.Render(fmt.Sprintf(" "+T("confirm_delete"), name)))
sb.WriteString("\n")
}
// Inline edit input
if m.editing && i == m.cursor {
sb.WriteString(m.editInput.View())
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(" " + T("enter_save") + " • " + T("esc_cancel")))
sb.WriteString("\n")
}
// Expanded detail view
if m.expanded == i {
sb.WriteString(m.renderDetail(f))
}
}
if m.status != "" {
sb.WriteString("\n")
sb.WriteString(m.status)
sb.WriteString("\n")
}
return sb.String()
}
func (m authTabModel) renderDetail(f map[string]any) string {
var sb strings.Builder
labelStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("111")).
Bold(true)
valueStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("252"))
editableMarker := lipgloss.NewStyle().
Foreground(lipgloss.Color("214")).
Render(" ✎")
sb.WriteString(" ┌─────────────────────────────────────────────\n")
fields := []struct {
label string
key string
editable bool
}{
{"Name", "name", false},
{"Channel", "channel", false},
{"Email", "email", false},
{"Status", "status", false},
{"Status Msg", "status_message", false},
{"File Name", "file_name", false},
{"Auth Type", "auth_type", false},
{"Prefix", "prefix", true},
{"Proxy URL", "proxy_url", true},
{"Priority", "priority", true},
{"Project ID", "project_id", false},
{"Disabled", "disabled", false},
{"Created", "created_at", false},
{"Updated", "updated_at", false},
}
for _, field := range fields {
val := getAnyString(f, field.key)
if val == "" || val == "<nil>" {
if field.editable {
val = T("not_set")
} else {
continue
}
}
editMark := ""
if field.editable {
editMark = editableMarker
}
line := fmt.Sprintf(" │ %s %s%s",
labelStyle.Render(fmt.Sprintf("%-12s:", field.label)),
valueStyle.Render(val),
editMark)
sb.WriteString(line)
sb.WriteString("\n")
}
sb.WriteString(" └─────────────────────────────────────────────\n")
return sb.String()
}
// getAnyString converts any value to its string representation.
func getAnyString(m map[string]any, key string) string {
v, ok := m[key]
if !ok || v == nil {
return ""
}
return fmt.Sprintf("%v", v)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func (m authTabModel) handleEditInput(msg tea.KeyMsg) (authTabModel, tea.Cmd) {
switch msg.String() {
case "enter":
value := m.editInput.Value()
fieldKey := authEditableFields[m.editField].key
fileName := m.editFileName
m.editing = false
m.editInput.Blur()
fields := map[string]any{}
if fieldKey == "priority" {
p, err := strconv.Atoi(value)
if err != nil {
return m, func() tea.Msg {
return authActionMsg{err: fmt.Errorf("%s: %s", T("invalid_int"), value)}
}
}
fields[fieldKey] = p
} else {
fields[fieldKey] = value
}
return m, func() tea.Msg {
err := m.client.PatchAuthFileFields(fileName, fields)
if err != nil {
return authActionMsg{err: err}
}
return authActionMsg{action: fmt.Sprintf(T("updated_field"), fieldKey, fileName)}
}
case "esc":
m.editing = false
m.editInput.Blur()
m.viewport.SetContent(m.renderContent())
return m, nil
default:
var cmd tea.Cmd
m.editInput, cmd = m.editInput.Update(msg)
m.viewport.SetContent(m.renderContent())
return m, cmd
}
}
func (m authTabModel) handleConfirmInput(msg tea.KeyMsg) (authTabModel, tea.Cmd) {
switch msg.String() {
case "y", "Y":
idx := m.confirm
m.confirm = -1
if idx < len(m.files) {
name := getString(m.files[idx], "name")
return m, func() tea.Msg {
err := m.client.DeleteAuthFile(name)
if err != nil {
return authActionMsg{err: err}
}
return authActionMsg{action: fmt.Sprintf(T("deleted"), name)}
}
}
m.viewport.SetContent(m.renderContent())
return m, nil
case "n", "N", "esc":
m.confirm = -1
m.viewport.SetContent(m.renderContent())
return m, nil
}
return m, nil
}
func (m authTabModel) handleNormalInput(msg tea.KeyMsg) (authTabModel, tea.Cmd) {
switch msg.String() {
case "j", "down":
if len(m.files) > 0 {
m.cursor = (m.cursor + 1) % len(m.files)
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "k", "up":
if len(m.files) > 0 {
m.cursor = (m.cursor - 1 + len(m.files)) % len(m.files)
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "enter", " ":
if m.expanded == m.cursor {
m.expanded = -1
} else {
m.expanded = m.cursor
}
m.viewport.SetContent(m.renderContent())
return m, nil
case "d", "D":
if m.cursor < len(m.files) {
m.confirm = m.cursor
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "e", "E":
if m.cursor < len(m.files) {
f := m.files[m.cursor]
name := getString(f, "name")
disabled := getBool(f, "disabled")
newDisabled := !disabled
return m, func() tea.Msg {
err := m.client.ToggleAuthFile(name, newDisabled)
if err != nil {
return authActionMsg{err: err}
}
action := T("enabled")
if newDisabled {
action = T("disabled")
}
return authActionMsg{action: fmt.Sprintf("%s %s", action, name)}
}
}
return m, nil
case "1":
return m, m.startEdit(0) // prefix
case "2":
return m, m.startEdit(1) // proxy_url
case "3":
return m, m.startEdit(2) // priority
case "r":
m.status = ""
return m, m.fetchFiles
default:
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
}
+8 -10
View File
@@ -5,18 +5,16 @@ import (
"runtime"
)
// openBrowser opens the specified URL in the default browser.
// openBrowser opens the specified URL in the user's default browser.
func openBrowser(url string) error {
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
case "darwin":
cmd = exec.Command("open", url)
default: // linux, freebsd, etc.
cmd = exec.Command("xdg-open", url)
return exec.Command("open", url).Start()
case "linux":
return exec.Command("xdg-open", url).Start()
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
default:
return exec.Command("xdg-open", url).Start()
}
return cmd.Start()
}
+4 -265
View File
@@ -2,10 +2,8 @@ package tui
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
@@ -13,9 +11,6 @@ import (
"time"
)
// ErrEngineNotRunning indicates the proxy engine is not running.
var ErrEngineNotRunning = errors.New("engine not running - start ProxyPilot first")
// Client wraps HTTP calls to the management API.
type Client struct {
baseURL string
@@ -23,20 +18,10 @@ type Client struct {
http *http.Client
}
// NewClient creates a management API client from either a port number or a base URL.
func NewClient(target any, secretKey string) *Client {
baseURL := ""
switch value := target.(type) {
case int:
baseURL = fmt.Sprintf("http://127.0.0.1:%d", value)
case string:
baseURL = strings.TrimRight(strings.TrimSpace(value), "/")
default:
baseURL = "http://127.0.0.1:8317"
}
// NewClient creates a new management API client.
func NewClient(port int, secretKey string) *Client {
return &Client{
baseURL: baseURL,
baseURL: fmt.Sprintf("http://127.0.0.1:%d", port),
secretKey: strings.TrimSpace(secretKey),
http: &http.Client{
Timeout: 10 * time.Second,
@@ -57,21 +42,12 @@ func (c *Client) doRequest(method, path string, body io.Reader) ([]byte, int, er
}
if c.secretKey != "" {
req.Header.Set("Authorization", "Bearer "+c.secretKey)
req.Header.Set("X-Management-Key", c.secretKey)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
var netErr *net.OpError
if errors.As(err, &netErr) {
return nil, 0, ErrEngineNotRunning
}
if strings.Contains(err.Error(), "connection refused") ||
strings.Contains(err.Error(), "No connection could be made") {
return nil, 0, ErrEngineNotRunning
}
return nil, 0, err
}
defer resp.Body.Close()
@@ -374,15 +350,6 @@ func (c *Client) GetDebug() (bool, error) {
return false, nil
}
// StartAuth initiates OAuth login for a provider.
func (c *Client) StartAuth(provider string) (string, string, error) {
wrapper, err := c.getJSON(fmt.Sprintf("/v0/management/%s-auth-url", provider))
if err != nil {
return "", "", err
}
return getString(wrapper, "url"), getString(wrapper, "state"), nil
}
// GetAuthStatus polls the OAuth session status.
// Returns status ("wait", "ok", "error") and optional error message.
func (c *Client) GetAuthStatus(state string) (string, string, error) {
@@ -391,13 +358,10 @@ func (c *Client) GetAuthStatus(state string) (string, string, error) {
path := "/v0/management/get-auth-status?" + query.Encode()
wrapper, err := c.getJSON(path)
if err != nil {
return "pending", "Waiting for auth...", nil
return "", "", err
}
status := getString(wrapper, "status")
errMsg := getString(wrapper, "error")
if errMsg == "" {
errMsg = getString(wrapper, "message")
}
return status, errMsg, nil
}
@@ -429,228 +393,3 @@ func (c *Client) DeleteField(path string) error {
_, _, err := c.doRequest("DELETE", "/v0/management/"+path, nil)
return err
}
func getString(m map[string]any, key string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
func getFloat(m map[string]any, key string) float64 {
if v, ok := m[key]; ok {
switch n := v.(type) {
case float64:
return n
case json.Number:
f, _ := n.Float64()
return f
}
}
return 0
}
func getBool(m map[string]any, key string) bool {
if v, ok := m[key]; ok {
if b, ok := v.(bool); ok {
return b
}
}
return false
}
// FetchStatus fetches proxy status for the legacy dashboard.
func (c *Client) FetchStatus() (ProxyStatus, error) {
status := ProxyStatus{Port: 8318}
resp, err := c.http.Get(c.baseURL + "/healthz")
if err != nil {
return status, nil
}
defer resp.Body.Close()
status.Running = resp.StatusCode == http.StatusOK
authFiles, err := c.GetAuthFiles()
if err == nil {
status.Accounts = len(authFiles)
}
data, err := c.get("/v1/models")
if err == nil {
var modelsResp struct {
Data []any `json:"data"`
}
if errUnmarshal := json.Unmarshal(data, &modelsResp); errUnmarshal == nil {
status.Models = len(modelsResp.Data)
}
}
return status, nil
}
// FetchAccounts fetches account list for the legacy dashboard.
func (c *Client) FetchAccounts() ([]AccountInfo, error) {
authFiles, err := c.GetAuthFiles()
if err != nil {
return nil, err
}
now := time.Now()
accounts := make([]AccountInfo, 0, len(authFiles))
for _, auth := range authFiles {
authIndex := getString(auth, "auth_index")
email := getString(auth, "email")
if email == "" {
email = getString(auth, "label")
}
if email == "" && len(authIndex) >= 8 {
email = authIndex[:8]
}
status := getString(auth, "status")
if getBool(auth, "disabled") {
status = "disabled"
}
expires := ""
if tokenExpiresAt := getString(auth, "token_expires_at"); tokenExpiresAt != "" {
if t, errParse := time.Parse(time.RFC3339, tokenExpiresAt); errParse == nil {
if t.After(now) {
expires = t.Format("Jan 02 15:04")
} else {
expires = "Expired"
}
}
}
usageText := "0K in / 0K out"
if usageMap, ok := auth["usage"].(map[string]any); ok {
input := int64(getFloat(usageMap, "daily_input_tokens"))
output := int64(getFloat(usageMap, "daily_output_tokens"))
usageText = fmt.Sprintf("%dK in / %dK out", input/1000, output/1000)
}
accounts = append(accounts, AccountInfo{
ID: authIndex,
Provider: getString(auth, "provider"),
Email: email,
Status: status,
Expires: expires,
Usage: usageText,
})
}
return accounts, nil
}
// FetchRateLimits fetches rate limit summary for the legacy dashboard.
func (c *Client) FetchRateLimits() (RateLimitSummary, error) {
data, err := c.get("/v0/management/rate-limits/summary")
if err != nil {
return RateLimitSummary{}, err
}
var resp struct {
Total int `json:"total"`
Available int `json:"available"`
CoolingDown int `json:"cooling_down"`
Disabled int `json:"disabled"`
NextRecoveryIn string `json:"next_recovery_in"`
}
if err := json.Unmarshal(data, &resp); err != nil {
return RateLimitSummary{}, err
}
return RateLimitSummary{
Total: resp.Total,
Available: resp.Available,
CoolingDown: resp.CoolingDown,
Disabled: resp.Disabled,
NextRecovery: resp.NextRecoveryIn,
}, nil
}
// FetchUsage fetches usage statistics for the legacy dashboard.
func (c *Client) FetchUsage() (UsageStats, error) {
data, err := c.get("/v0/management/usage")
if err != nil {
return UsageStats{}, err
}
var resp struct {
Usage struct {
TotalRequests int64 `json:"total_requests"`
TotalInputTokens int64 `json:"total_input_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
EstimatedCost float64 `json:"estimated_cost"`
ByModel map[string]struct {
Requests int64 `json:"requests"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
} `json:"by_model"`
} `json:"usage"`
}
if err := json.Unmarshal(data, &resp); err != nil {
return UsageStats{}, err
}
stats := UsageStats{
TotalRequests: resp.Usage.TotalRequests,
TotalInputTokens: resp.Usage.TotalInputTokens,
TotalOutputTokens: resp.Usage.TotalOutputTokens,
EstimatedCost: resp.Usage.EstimatedCost,
}
for model, usage := range resp.Usage.ByModel {
stats.TopModels = append(stats.TopModels, ModelUsage{
Model: model,
Requests: usage.Requests,
Tokens: usage.InputTokens + usage.OutputTokens,
})
}
for i := 0; i < len(stats.TopModels); i++ {
for j := i + 1; j < len(stats.TopModels); j++ {
if stats.TopModels[j].Requests > stats.TopModels[i].Requests {
stats.TopModels[i], stats.TopModels[j] = stats.TopModels[j], stats.TopModels[i]
}
}
}
if len(stats.TopModels) > 5 {
stats.TopModels = stats.TopModels[:5]
}
return stats, nil
}
// FetchLogs fetches recent log entries for the legacy dashboard.
func (c *Client) FetchLogs() ([]string, error) {
lines, _, err := c.GetLogs(0, 100)
if err == nil && len(lines) > 0 {
return lines, nil
}
data, getErr := c.get("/v0/management/logs?limit=100")
if getErr != nil {
if err != nil {
return nil, err
}
return nil, getErr
}
var resp struct {
Entries []struct {
Timestamp string `json:"timestamp"`
Level string `json:"level"`
Message string `json:"message"`
} `json:"entries"`
}
if err := json.Unmarshal(data, &resp); err != nil {
return nil, err
}
logs := make([]string, len(resp.Entries))
for i, entry := range resp.Entries {
logs[i] = fmt.Sprintf("[%s] %s: %s", entry.Timestamp, entry.Level, entry.Message)
}
return logs, nil
}
+297
View File
@@ -0,0 +1,297 @@
package tui
import (
"encoding/json"
"fmt"
"strings"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// dashboardModel displays server info, stats cards, and config overview.
type dashboardModel struct {
client *Client
viewport viewport.Model
content string
err error
width int
height int
ready bool
// Cached data for re-rendering on locale change
lastConfig map[string]any
lastAuthFiles []map[string]any
lastAPIKeys []string
}
type dashboardDataMsg struct {
config map[string]any
authFiles []map[string]any
apiKeys []string
err error
}
func newDashboardModel(client *Client) dashboardModel {
return dashboardModel{
client: client,
}
}
func (m dashboardModel) Init() tea.Cmd {
return m.fetchData
}
func (m dashboardModel) fetchData() tea.Msg {
cfg, cfgErr := m.client.GetConfig()
authFiles, authErr := m.client.GetAuthFiles()
apiKeys, keysErr := m.client.GetAPIKeys()
var err error
for _, e := range []error{cfgErr, authErr, keysErr} {
if e != nil {
err = e
break
}
}
return dashboardDataMsg{config: cfg, authFiles: authFiles, apiKeys: apiKeys, err: err}
}
func (m dashboardModel) Update(msg tea.Msg) (dashboardModel, tea.Cmd) {
switch msg := msg.(type) {
case localeChangedMsg:
// Re-render immediately with cached data using new locale
m.content = m.renderDashboard(m.lastConfig, m.lastAuthFiles, m.lastAPIKeys)
m.viewport.SetContent(m.content)
// Also fetch fresh data in background
return m, m.fetchData
case dashboardDataMsg:
if msg.err != nil {
m.err = msg.err
m.content = errorStyle.Render("⚠ Error: " + msg.err.Error())
} else {
m.err = nil
// Cache data for locale switching
m.lastConfig = msg.config
m.lastAuthFiles = msg.authFiles
m.lastAPIKeys = msg.apiKeys
m.content = m.renderDashboard(msg.config, msg.authFiles, msg.apiKeys)
}
m.viewport.SetContent(m.content)
return m, nil
case tea.KeyMsg:
if msg.String() == "r" {
return m, m.fetchData
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
func (m *dashboardModel) SetSize(w, h int) {
m.width = w
m.height = h
if !m.ready {
m.viewport = viewport.New(w, h)
m.viewport.SetContent(m.content)
m.ready = true
} else {
m.viewport.Width = w
m.viewport.Height = h
}
}
func (m dashboardModel) View() string {
if !m.ready {
return T("loading")
}
return m.viewport.View()
}
func (m dashboardModel) renderDashboard(cfg map[string]any, authFiles []map[string]any, apiKeys []string) string {
var sb strings.Builder
sb.WriteString(titleStyle.Render(T("dashboard_title")))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("dashboard_help")))
sb.WriteString("\n\n")
// ━━━ Connection Status ━━━
connStyle := lipgloss.NewStyle().Bold(true).Foreground(colorSuccess)
sb.WriteString(connStyle.Render(T("connected")))
sb.WriteString(fmt.Sprintf(" %s", m.client.baseURL))
sb.WriteString("\n\n")
// ━━━ Stats Cards ━━━
cardWidth := 25
if m.width > 0 {
cardWidth = (m.width - 2) / 2
if cardWidth < 18 {
cardWidth = 18
}
}
cardStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("240")).
Padding(0, 1).
Width(cardWidth).
Height(2)
// Card 1: API Keys
keyCount := len(apiKeys)
card1 := cardStyle.Render(fmt.Sprintf(
"%s\n%s",
lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("111")).Render(fmt.Sprintf("🔑 %d", keyCount)),
lipgloss.NewStyle().Foreground(colorMuted).Render(T("mgmt_keys")),
))
// Card 2: Auth Files
authCount := len(authFiles)
activeAuth := 0
for _, f := range authFiles {
if !getBool(f, "disabled") {
activeAuth++
}
}
card2 := cardStyle.Render(fmt.Sprintf(
"%s\n%s",
lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("76")).Render(fmt.Sprintf("📄 %d", authCount)),
lipgloss.NewStyle().Foreground(colorMuted).Render(fmt.Sprintf("%s (%d %s)", T("auth_files_label"), activeAuth, T("active_suffix"))),
))
sb.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, card1, " ", card2))
sb.WriteString("\n\n")
// ━━━ Current Config ━━━
sb.WriteString(lipgloss.NewStyle().Bold(true).Foreground(colorHighlight).Render(T("current_config")))
sb.WriteString("\n")
sb.WriteString(strings.Repeat("─", minInt(m.width, 60)))
sb.WriteString("\n")
if cfg != nil {
debug := getBool(cfg, "debug")
retry := getFloat(cfg, "request-retry")
proxyURL := getString(cfg, "proxy-url")
loggingToFile := getBool(cfg, "logging-to-file")
usageEnabled := true
if v, ok := cfg["usage-statistics-enabled"]; ok {
if b, ok2 := v.(bool); ok2 {
usageEnabled = b
}
}
configItems := []struct {
label string
value string
}{
{T("debug_mode"), boolEmoji(debug)},
{T("usage_stats"), boolEmoji(usageEnabled)},
{T("log_to_file"), boolEmoji(loggingToFile)},
{T("retry_count"), fmt.Sprintf("%.0f", retry)},
}
if proxyURL != "" {
configItems = append(configItems, struct {
label string
value string
}{T("proxy_url"), proxyURL})
}
// Render config items as a compact row
for _, item := range configItems {
sb.WriteString(fmt.Sprintf(" %s %s\n",
labelStyle.Render(item.label+":"),
valueStyle.Render(item.value)))
}
// Routing strategy
strategy := "round-robin"
if routing, ok := cfg["routing"].(map[string]any); ok {
if s := getString(routing, "strategy"); s != "" {
strategy = s
}
}
sb.WriteString(fmt.Sprintf(" %s %s\n",
labelStyle.Render(T("routing_strategy")+":"),
valueStyle.Render(strategy)))
}
sb.WriteString("\n")
return sb.String()
}
func formatKV(key, value string) string {
return fmt.Sprintf(" %s %s\n", labelStyle.Render(key+":"), valueStyle.Render(value))
}
func getString(m map[string]any, key string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
func getFloat(m map[string]any, key string) float64 {
if v, ok := m[key]; ok {
switch n := v.(type) {
case float64:
return n
case json.Number:
f, _ := n.Float64()
return f
}
}
return 0
}
func getBool(m map[string]any, key string) bool {
if v, ok := m[key]; ok {
if b, ok := v.(bool); ok {
return b
}
}
return false
}
func boolEmoji(b bool) string {
if b {
return T("bool_yes")
}
return T("bool_no")
}
func formatLargeNumber(n int64) string {
if n >= 1_000_000 {
return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
}
if n >= 1_000 {
return fmt.Sprintf("%.1fK", float64(n)/1_000)
}
return fmt.Sprintf("%d", n)
}
func truncate(s string, maxLen int) string {
if len(s) > maxLen {
return s[:maxLen-3] + "..."
}
return s
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
+405
View File
@@ -0,0 +1,405 @@
package tui
import (
"fmt"
"strings"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// keysTabModel displays and manages API keys.
type keysTabModel struct {
client *Client
viewport viewport.Model
keys []string
gemini []map[string]any
claude []map[string]any
codex []map[string]any
vertex []map[string]any
openai []map[string]any
err error
width int
height int
ready bool
cursor int
confirm int // -1 = no deletion pending
status string
// Editing / Adding
editing bool
adding bool
editIdx int
editInput textinput.Model
}
type keysDataMsg struct {
apiKeys []string
gemini []map[string]any
claude []map[string]any
codex []map[string]any
vertex []map[string]any
openai []map[string]any
err error
}
type keyActionMsg struct {
action string
err error
}
func newKeysTabModel(client *Client) keysTabModel {
ti := textinput.New()
ti.CharLimit = 512
ti.Prompt = " Key: "
return keysTabModel{
client: client,
confirm: -1,
editInput: ti,
}
}
func (m keysTabModel) Init() tea.Cmd {
return m.fetchKeys
}
func (m keysTabModel) fetchKeys() tea.Msg {
result := keysDataMsg{}
apiKeys, err := m.client.GetAPIKeys()
if err != nil {
result.err = err
return result
}
result.apiKeys = apiKeys
result.gemini, _ = m.client.GetGeminiKeys()
result.claude, _ = m.client.GetClaudeKeys()
result.codex, _ = m.client.GetCodexKeys()
result.vertex, _ = m.client.GetVertexKeys()
result.openai, _ = m.client.GetOpenAICompat()
return result
}
func (m keysTabModel) Update(msg tea.Msg) (keysTabModel, tea.Cmd) {
switch msg := msg.(type) {
case localeChangedMsg:
m.viewport.SetContent(m.renderContent())
return m, nil
case keysDataMsg:
if msg.err != nil {
m.err = msg.err
} else {
m.err = nil
m.keys = msg.apiKeys
m.gemini = msg.gemini
m.claude = msg.claude
m.codex = msg.codex
m.vertex = msg.vertex
m.openai = msg.openai
if m.cursor >= len(m.keys) {
m.cursor = max(0, len(m.keys)-1)
}
}
m.viewport.SetContent(m.renderContent())
return m, nil
case keyActionMsg:
if msg.err != nil {
m.status = errorStyle.Render("✗ " + msg.err.Error())
} else {
m.status = successStyle.Render("✓ " + msg.action)
}
m.confirm = -1
m.viewport.SetContent(m.renderContent())
return m, m.fetchKeys
case tea.KeyMsg:
// ---- Editing / Adding mode ----
if m.editing || m.adding {
switch msg.String() {
case "enter":
value := strings.TrimSpace(m.editInput.Value())
if value == "" {
m.editing = false
m.adding = false
m.editInput.Blur()
m.viewport.SetContent(m.renderContent())
return m, nil
}
isAdding := m.adding
editIdx := m.editIdx
m.editing = false
m.adding = false
m.editInput.Blur()
if isAdding {
return m, func() tea.Msg {
err := m.client.AddAPIKey(value)
if err != nil {
return keyActionMsg{err: err}
}
return keyActionMsg{action: T("key_added")}
}
}
return m, func() tea.Msg {
err := m.client.EditAPIKey(editIdx, value)
if err != nil {
return keyActionMsg{err: err}
}
return keyActionMsg{action: T("key_updated")}
}
case "esc":
m.editing = false
m.adding = false
m.editInput.Blur()
m.viewport.SetContent(m.renderContent())
return m, nil
default:
var cmd tea.Cmd
m.editInput, cmd = m.editInput.Update(msg)
m.viewport.SetContent(m.renderContent())
return m, cmd
}
}
// ---- Delete confirmation ----
if m.confirm >= 0 {
switch msg.String() {
case "y", "Y":
idx := m.confirm
m.confirm = -1
return m, func() tea.Msg {
err := m.client.DeleteAPIKey(idx)
if err != nil {
return keyActionMsg{err: err}
}
return keyActionMsg{action: T("key_deleted")}
}
case "n", "N", "esc":
m.confirm = -1
m.viewport.SetContent(m.renderContent())
return m, nil
}
return m, nil
}
// ---- Normal mode ----
switch msg.String() {
case "j", "down":
if len(m.keys) > 0 {
m.cursor = (m.cursor + 1) % len(m.keys)
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "k", "up":
if len(m.keys) > 0 {
m.cursor = (m.cursor - 1 + len(m.keys)) % len(m.keys)
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "a":
// Add new key
m.adding = true
m.editing = false
m.editInput.SetValue("")
m.editInput.Prompt = T("new_key_prompt")
m.editInput.Focus()
m.viewport.SetContent(m.renderContent())
return m, textinput.Blink
case "e":
// Edit selected key
if m.cursor < len(m.keys) {
m.editing = true
m.adding = false
m.editIdx = m.cursor
m.editInput.SetValue(m.keys[m.cursor])
m.editInput.Prompt = T("edit_key_prompt")
m.editInput.Focus()
m.viewport.SetContent(m.renderContent())
return m, textinput.Blink
}
return m, nil
case "d":
// Delete selected key
if m.cursor < len(m.keys) {
m.confirm = m.cursor
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "c":
// Copy selected key to clipboard
if m.cursor < len(m.keys) {
key := m.keys[m.cursor]
if err := clipboard.WriteAll(key); err != nil {
m.status = errorStyle.Render(T("copy_failed") + ": " + err.Error())
} else {
m.status = successStyle.Render(T("copied"))
}
m.viewport.SetContent(m.renderContent())
}
return m, nil
case "r":
m.status = ""
return m, m.fetchKeys
default:
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
func (m *keysTabModel) SetSize(w, h int) {
m.width = w
m.height = h
m.editInput.Width = w - 16
if !m.ready {
m.viewport = viewport.New(w, h)
m.viewport.SetContent(m.renderContent())
m.ready = true
} else {
m.viewport.Width = w
m.viewport.Height = h
}
}
func (m keysTabModel) View() string {
if !m.ready {
return T("loading")
}
return m.viewport.View()
}
func (m keysTabModel) renderContent() string {
var sb strings.Builder
sb.WriteString(titleStyle.Render(T("keys_title")))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("keys_help")))
sb.WriteString("\n")
sb.WriteString(strings.Repeat("─", m.width))
sb.WriteString("\n")
if m.err != nil {
sb.WriteString(errorStyle.Render(T("error_prefix") + m.err.Error()))
sb.WriteString("\n")
return sb.String()
}
// ━━━ Access API Keys (interactive) ━━━
sb.WriteString(tableHeaderStyle.Render(fmt.Sprintf(" %s (%d)", T("access_keys"), len(m.keys))))
sb.WriteString("\n")
if len(m.keys) == 0 {
sb.WriteString(subtitleStyle.Render(T("no_keys")))
sb.WriteString("\n")
}
for i, key := range m.keys {
cursor := " "
rowStyle := lipgloss.NewStyle()
if i == m.cursor {
cursor = "▸ "
rowStyle = lipgloss.NewStyle().Bold(true)
}
row := fmt.Sprintf("%s%d. %s", cursor, i+1, maskKey(key))
sb.WriteString(rowStyle.Render(row))
sb.WriteString("\n")
// Delete confirmation
if m.confirm == i {
sb.WriteString(warningStyle.Render(fmt.Sprintf(" "+T("confirm_delete_key"), maskKey(key))))
sb.WriteString("\n")
}
// Edit input
if m.editing && m.editIdx == i {
sb.WriteString(m.editInput.View())
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("enter_save_esc")))
sb.WriteString("\n")
}
}
// Add input
if m.adding {
sb.WriteString("\n")
sb.WriteString(m.editInput.View())
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("enter_add")))
sb.WriteString("\n")
}
sb.WriteString("\n")
// ━━━ Provider Keys (read-only display) ━━━
renderProviderKeys(&sb, "Gemini API Keys", m.gemini)
renderProviderKeys(&sb, "Claude API Keys", m.claude)
renderProviderKeys(&sb, "Codex API Keys", m.codex)
renderProviderKeys(&sb, "Vertex API Keys", m.vertex)
if len(m.openai) > 0 {
renderSection(&sb, "OpenAI Compatibility", len(m.openai))
for i, entry := range m.openai {
name := getString(entry, "name")
baseURL := getString(entry, "base-url")
prefix := getString(entry, "prefix")
info := name
if prefix != "" {
info += " (prefix: " + prefix + ")"
}
if baseURL != "" {
info += " → " + baseURL
}
sb.WriteString(fmt.Sprintf(" %d. %s\n", i+1, info))
}
sb.WriteString("\n")
}
if m.status != "" {
sb.WriteString(m.status)
sb.WriteString("\n")
}
return sb.String()
}
func renderSection(sb *strings.Builder, title string, count int) {
header := fmt.Sprintf("%s (%d)", title, count)
sb.WriteString(tableHeaderStyle.Render(" " + header))
sb.WriteString("\n")
}
func renderProviderKeys(sb *strings.Builder, title string, keys []map[string]any) {
if len(keys) == 0 {
return
}
renderSection(sb, title, len(keys))
for i, key := range keys {
apiKey := getString(key, "api-key")
prefix := getString(key, "prefix")
baseURL := getString(key, "base-url")
info := maskKey(apiKey)
if prefix != "" {
info += " (prefix: " + prefix + ")"
}
if baseURL != "" {
info += " → " + baseURL
}
sb.WriteString(fmt.Sprintf(" %d. %s\n", i+1, info))
}
sb.WriteString("\n")
}
func maskKey(key string) string {
if len(key) <= 8 {
return strings.Repeat("*", len(key))
}
return key[:4] + strings.Repeat("*", len(key)-8) + key[len(key)-4:]
}
+78
View File
@@ -0,0 +1,78 @@
package tui
import (
"fmt"
"strings"
"sync"
log "github.com/sirupsen/logrus"
)
// LogHook is a logrus hook that captures log entries and sends them to a channel.
type LogHook struct {
ch chan string
formatter log.Formatter
mu sync.Mutex
levels []log.Level
}
// NewLogHook creates a new LogHook with a buffered channel of the given size.
func NewLogHook(bufSize int) *LogHook {
return &LogHook{
ch: make(chan string, bufSize),
formatter: &log.TextFormatter{DisableColors: true, FullTimestamp: true},
levels: log.AllLevels,
}
}
// SetFormatter sets a custom formatter for the hook.
func (h *LogHook) SetFormatter(f log.Formatter) {
h.mu.Lock()
defer h.mu.Unlock()
h.formatter = f
}
// Levels returns the log levels this hook should fire on.
func (h *LogHook) Levels() []log.Level {
return h.levels
}
// Fire is called by logrus when a log entry is fired.
func (h *LogHook) Fire(entry *log.Entry) error {
h.mu.Lock()
f := h.formatter
h.mu.Unlock()
var line string
if f != nil {
b, err := f.Format(entry)
if err == nil {
line = strings.TrimRight(string(b), "\n\r")
} else {
line = fmt.Sprintf("[%s] %s", entry.Level, entry.Message)
}
} else {
line = fmt.Sprintf("[%s] %s", entry.Level, entry.Message)
}
// Non-blocking send
select {
case h.ch <- line:
default:
// Drop oldest if full
select {
case <-h.ch:
default:
}
select {
case h.ch <- line:
default:
}
}
return nil
}
// Chan returns the channel to read log lines from.
func (h *LogHook) Chan() <-chan string {
return h.ch
}
+261
View File
@@ -0,0 +1,261 @@
package tui
import (
"fmt"
"strings"
"time"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
)
// logsTabModel displays real-time log lines from hook/API source.
type logsTabModel struct {
client *Client
hook *LogHook
viewport viewport.Model
lines []string
maxLines int
autoScroll bool
width int
height int
ready bool
filter string // "", "debug", "info", "warn", "error"
after int64
lastErr error
}
type logsPollMsg struct {
lines []string
latest int64
err error
}
type logsTickMsg struct{}
type logLineMsg string
func newLogsTabModel(client *Client, hook *LogHook) logsTabModel {
return logsTabModel{
client: client,
hook: hook,
maxLines: 5000,
autoScroll: true,
}
}
func (m logsTabModel) Init() tea.Cmd {
if m.hook != nil {
return m.waitForLog
}
return m.fetchLogs
}
func (m logsTabModel) fetchLogs() tea.Msg {
lines, latest, err := m.client.GetLogs(m.after, 200)
return logsPollMsg{
lines: lines,
latest: latest,
err: err,
}
}
func (m logsTabModel) waitForNextPoll() tea.Cmd {
return tea.Tick(2*time.Second, func(_ time.Time) tea.Msg {
return logsTickMsg{}
})
}
func (m logsTabModel) waitForLog() tea.Msg {
if m.hook == nil {
return nil
}
line, ok := <-m.hook.Chan()
if !ok {
return nil
}
return logLineMsg(line)
}
func (m logsTabModel) Update(msg tea.Msg) (logsTabModel, tea.Cmd) {
switch msg := msg.(type) {
case localeChangedMsg:
m.viewport.SetContent(m.renderLogs())
return m, nil
case logsTickMsg:
if m.hook != nil {
return m, nil
}
return m, m.fetchLogs
case logsPollMsg:
if m.hook != nil {
return m, nil
}
if msg.err != nil {
m.lastErr = msg.err
} else {
m.lastErr = nil
m.after = msg.latest
if len(msg.lines) > 0 {
m.lines = append(m.lines, msg.lines...)
if len(m.lines) > m.maxLines {
m.lines = m.lines[len(m.lines)-m.maxLines:]
}
}
}
m.viewport.SetContent(m.renderLogs())
if m.autoScroll {
m.viewport.GotoBottom()
}
return m, m.waitForNextPoll()
case logLineMsg:
m.lines = append(m.lines, string(msg))
if len(m.lines) > m.maxLines {
m.lines = m.lines[len(m.lines)-m.maxLines:]
}
m.viewport.SetContent(m.renderLogs())
if m.autoScroll {
m.viewport.GotoBottom()
}
return m, m.waitForLog
case tea.KeyMsg:
switch msg.String() {
case "a":
m.autoScroll = !m.autoScroll
if m.autoScroll {
m.viewport.GotoBottom()
}
return m, nil
case "c":
m.lines = nil
m.lastErr = nil
m.viewport.SetContent(m.renderLogs())
return m, nil
case "1":
m.filter = ""
m.viewport.SetContent(m.renderLogs())
return m, nil
case "2":
m.filter = "info"
m.viewport.SetContent(m.renderLogs())
return m, nil
case "3":
m.filter = "warn"
m.viewport.SetContent(m.renderLogs())
return m, nil
case "4":
m.filter = "error"
m.viewport.SetContent(m.renderLogs())
return m, nil
default:
wasAtBottom := m.viewport.AtBottom()
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
// If user scrolls up, disable auto-scroll
if !m.viewport.AtBottom() && wasAtBottom {
m.autoScroll = false
}
// If user scrolls to bottom, re-enable auto-scroll
if m.viewport.AtBottom() {
m.autoScroll = true
}
return m, cmd
}
}
var cmd tea.Cmd
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
func (m *logsTabModel) SetSize(w, h int) {
m.width = w
m.height = h
if !m.ready {
m.viewport = viewport.New(w, h)
m.viewport.SetContent(m.renderLogs())
m.ready = true
} else {
m.viewport.Width = w
m.viewport.Height = h
}
}
func (m logsTabModel) View() string {
if !m.ready {
return T("loading")
}
return m.viewport.View()
}
func (m logsTabModel) renderLogs() string {
var sb strings.Builder
scrollStatus := successStyle.Render(T("logs_auto_scroll"))
if !m.autoScroll {
scrollStatus = warningStyle.Render(T("logs_paused"))
}
filterLabel := "ALL"
if m.filter != "" {
filterLabel = strings.ToUpper(m.filter) + "+"
}
header := fmt.Sprintf(" %s %s %s: %s %s: %d",
T("logs_title"), scrollStatus, T("logs_filter"), filterLabel, T("logs_lines"), len(m.lines))
sb.WriteString(titleStyle.Render(header))
sb.WriteString("\n")
sb.WriteString(helpStyle.Render(T("logs_help")))
sb.WriteString("\n")
sb.WriteString(strings.Repeat("─", m.width))
sb.WriteString("\n")
if m.lastErr != nil {
sb.WriteString(errorStyle.Render("⚠ Error: " + m.lastErr.Error()))
sb.WriteString("\n")
}
if len(m.lines) == 0 {
sb.WriteString(subtitleStyle.Render(T("logs_waiting")))
return sb.String()
}
for _, line := range m.lines {
if m.filter != "" && !m.matchLevel(line) {
continue
}
styled := m.styleLine(line)
sb.WriteString(styled)
sb.WriteString("\n")
}
return sb.String()
}
func (m logsTabModel) matchLevel(line string) bool {
switch m.filter {
case "error":
return strings.Contains(line, "[error]") || strings.Contains(line, "[fatal]") || strings.Contains(line, "[panic]")
case "warn":
return strings.Contains(line, "[warn") || strings.Contains(line, "[error]") || strings.Contains(line, "[fatal]")
case "info":
return !strings.Contains(line, "[debug]")
default:
return true
}
}
func (m logsTabModel) styleLine(line string) string {
if strings.Contains(line, "[error]") || strings.Contains(line, "[fatal]") {
return logErrorStyle.Render(line)
}
if strings.Contains(line, "[warn") {
return logWarnStyle.Render(line)
}
if strings.Contains(line, "[info") {
return logInfoStyle.Render(line)
}
if strings.Contains(line, "[debug]") {
return logDebugStyle.Render(line)
}
return line
}
-45
View File
@@ -1,45 +0,0 @@
package tui
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
)
// Run starts the TUI application.
func Run(proxyURL, managementKey string) error {
if proxyURL == "" {
proxyURL = "http://127.0.0.1:8318"
}
model := NewModel(proxyURL, managementKey)
p := tea.NewProgram(model, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
return fmt.Errorf("failed to run TUI: %w", err)
}
return nil
}
// RunWithStdio runs the TUI with custom stdio (for embedding in other programs).
func RunWithStdio(proxyURL, managementKey string, in *os.File, out *os.File) error {
if proxyURL == "" {
proxyURL = "http://127.0.0.1:8318"
}
model := NewModel(proxyURL, managementKey)
p := tea.NewProgram(
model,
tea.WithAltScreen(),
tea.WithInput(in),
tea.WithOutput(out),
)
if _, err := p.Run(); err != nil {
return fmt.Errorf("failed to run TUI: %w", err)
}
return nil
}
+126
View File
@@ -0,0 +1,126 @@
// Package tui provides a terminal-based management interface for CLIProxyAPI.
package tui
import "github.com/charmbracelet/lipgloss"
// Color palette
var (
colorPrimary = lipgloss.Color("#7C3AED") // violet
colorSecondary = lipgloss.Color("#6366F1") // indigo
colorSuccess = lipgloss.Color("#22C55E") // green
colorWarning = lipgloss.Color("#EAB308") // yellow
colorError = lipgloss.Color("#EF4444") // red
colorInfo = lipgloss.Color("#3B82F6") // blue
colorMuted = lipgloss.Color("#6B7280") // gray
colorBg = lipgloss.Color("#1E1E2E") // dark bg
colorSurface = lipgloss.Color("#313244") // slightly lighter
colorText = lipgloss.Color("#CDD6F4") // light text
colorSubtext = lipgloss.Color("#A6ADC8") // dimmer text
colorBorder = lipgloss.Color("#45475A") // border
colorHighlight = lipgloss.Color("#F5C2E7") // pink highlight
)
// Tab bar styles
var (
tabActiveStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#FFFFFF")).
Background(colorPrimary).
Padding(0, 2)
tabInactiveStyle = lipgloss.NewStyle().
Foreground(colorSubtext).
Background(colorSurface).
Padding(0, 2)
tabBarStyle = lipgloss.NewStyle().
Background(colorSurface).
PaddingLeft(1).
PaddingBottom(0)
)
// Content styles
var (
titleStyle = lipgloss.NewStyle().
Bold(true).
Foreground(colorHighlight).
MarginBottom(1)
subtitleStyle = lipgloss.NewStyle().
Foreground(colorSubtext).
Italic(true)
labelStyle = lipgloss.NewStyle().
Foreground(colorInfo).
Bold(true).
Width(24)
valueStyle = lipgloss.NewStyle().
Foreground(colorText)
sectionStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(colorBorder).
Padding(1, 2)
errorStyle = lipgloss.NewStyle().
Foreground(colorError).
Bold(true)
successStyle = lipgloss.NewStyle().
Foreground(colorSuccess)
warningStyle = lipgloss.NewStyle().
Foreground(colorWarning)
statusBarStyle = lipgloss.NewStyle().
Foreground(colorSubtext).
Background(colorSurface).
PaddingLeft(1).
PaddingRight(1)
helpStyle = lipgloss.NewStyle().
Foreground(colorMuted)
)
// Log level styles
var (
logDebugStyle = lipgloss.NewStyle().Foreground(colorMuted)
logInfoStyle = lipgloss.NewStyle().Foreground(colorInfo)
logWarnStyle = lipgloss.NewStyle().Foreground(colorWarning)
logErrorStyle = lipgloss.NewStyle().Foreground(colorError)
)
// Table styles
var (
tableHeaderStyle = lipgloss.NewStyle().
Bold(true).
Foreground(colorHighlight).
BorderBottom(true).
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(colorBorder)
tableCellStyle = lipgloss.NewStyle().
Foreground(colorText).
PaddingRight(2)
tableSelectedStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFFFFF")).
Background(colorPrimary).
Bold(true)
)
func logLevelStyle(level string) lipgloss.Style {
switch level {
case "debug":
return logDebugStyle
case "info":
return logInfoStyle
case "warn", "warning":
return logWarnStyle
case "error", "fatal", "panic":
return logErrorStyle
default:
return logInfoStyle
}
}
-1499
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,2 +1,2 @@
[tools]
go = "1.26.0"
go = "1.26.4"
+1
View File
@@ -6,6 +6,7 @@ const (
FormatOpenAIResponse Format = "openai-response"
FormatClaude Format = "claude"
FormatGemini Format = "gemini"
FormatGeminiCLI Format = "gemini-cli"
FormatCodex Format = "codex"
FormatAntigravity Format = "antigravity"
FormatKiro Format = "kiro"
-294
View File
@@ -1,294 +0,0 @@
package translator
import (
"context"
"sync/atomic"
"testing"
)
func TestRegistryLazy_BasicLoad(t *testing.T) {
reg := NewRegistry()
from := Format("lazy-from")
to := Format("lazy-to")
var loadCount atomic.Int32
// Register a lazy loader
reg.RegisterLazy(from, to, func() RequestTransform {
loadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return append([]byte("lazy:"), rawJSON...)
}
})
// Should not be loaded yet
if reg.IsLazyLoaded(from, to) {
t.Error("should not be loaded before first use")
}
if loadCount.Load() != 0 {
t.Error("loader should not have been called yet")
}
// First translation should trigger load
result := reg.TranslateRequest(from, to, "model", []byte("test"), false)
if string(result) != "lazy:test" {
t.Errorf("unexpected result: %s", string(result))
}
if loadCount.Load() != 1 {
t.Errorf("expected 1 load, got %d", loadCount.Load())
}
if !reg.IsLazyLoaded(from, to) {
t.Error("should be loaded after first use")
}
// Second translation should NOT trigger another load
result = reg.TranslateRequest(from, to, "model", []byte("test2"), false)
if string(result) != "lazy:test2" {
t.Errorf("unexpected result: %s", string(result))
}
if loadCount.Load() != 1 {
t.Errorf("expected still 1 load, got %d", loadCount.Load())
}
}
func TestRegistryLazy_HasRequestTranslator(t *testing.T) {
reg := NewRegistry()
from := Format("has-lazy-from")
to := Format("has-lazy-to")
// Before registration
if reg.HasRequestTranslator(from, to) {
t.Error("should not have translator before registration")
}
// Register lazy
reg.RegisterLazy(from, to, func() RequestTransform {
return func(model string, rawJSON []byte, stream bool) []byte {
return rawJSON
}
})
// After registration (but before load)
if !reg.HasRequestTranslator(from, to) {
t.Error("should have translator after lazy registration")
}
}
func TestRegistryLazy_ResponseLoader(t *testing.T) {
reg := NewRegistry()
from := Format("lazy-resp-from")
to := Format("lazy-resp-to")
var loadCount atomic.Int32
reg.RegisterLazyResponse(from, to, func() ResponseTransform {
loadCount.Add(1)
return ResponseTransform{
NonStream: func(ctx context.Context, model string, origReq, req, resp []byte, param *any) []byte {
return []byte("lazy-response")
},
}
})
// Should report having response transformer
if !reg.HasResponseTransformer(from, to) {
t.Error("should have response transformer after lazy registration")
}
// Load count should still be 0
if loadCount.Load() != 0 {
t.Error("loader should not have been called yet")
}
}
func TestRegistryLazy_BothLoaders(t *testing.T) {
reg := NewRegistry()
from := Format("both-from")
to := Format("both-to")
var reqLoadCount, respLoadCount atomic.Int32
reg.RegisterLazyBoth(from, to,
func() RequestTransform {
reqLoadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return rawJSON
}
},
func() ResponseTransform {
respLoadCount.Add(1)
return ResponseTransform{}
},
)
stats := reg.GetLazyLoadStats()
if stats.TotalLazy != 2 {
t.Errorf("expected 2 lazy registrations, got %d", stats.TotalLazy)
}
if stats.TotalLoaded != 0 {
t.Errorf("expected 0 loaded, got %d", stats.TotalLoaded)
}
// Trigger request load
reg.TranslateRequest(from, to, "m", []byte("t"), false)
stats = reg.GetLazyLoadStats()
if stats.TotalLoaded != 1 {
t.Errorf("expected 1 loaded after request, got %d", stats.TotalLoaded)
}
}
func TestRegistryLazy_ForceLoad(t *testing.T) {
reg := NewRegistry()
from := Format("force-from")
to := Format("force-to")
var loadCount atomic.Int32
reg.RegisterLazy(from, to, func() RequestTransform {
loadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return rawJSON
}
})
// Force load all lazy transformers
reg.ForceLoadLazy()
if loadCount.Load() != 1 {
t.Errorf("expected 1 load after ForceLoadLazy, got %d", loadCount.Load())
}
// Force load again - should not trigger additional loads
reg.ForceLoadLazy()
if loadCount.Load() != 1 {
t.Errorf("expected still 1 load, got %d", loadCount.Load())
}
}
func TestRegistryLazy_PriorityOverLazy(t *testing.T) {
reg := NewRegistry()
from := Format("priority-from")
to := Format("priority-to")
var lazyLoadCount atomic.Int32
// Register lazy first
reg.RegisterLazy(from, to, func() RequestTransform {
lazyLoadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return []byte("lazy")
}
})
// Register regular (should take priority)
reg.Register(from, to, func(model string, rawJSON []byte, stream bool) []byte {
return []byte("regular")
}, ResponseTransform{})
result := reg.TranslateRequest(from, to, "m", []byte("t"), false)
// Regular should take priority
if string(result) != "regular" {
t.Errorf("expected 'regular', got %s", string(result))
}
// Lazy loader should NOT have been called
if lazyLoadCount.Load() != 0 {
t.Errorf("lazy loader should not be called when regular exists, got %d calls", lazyLoadCount.Load())
}
}
func TestRegistryLazy_ConcurrentLoad(t *testing.T) {
reg := NewRegistry()
from := Format("concurrent-from")
to := Format("concurrent-to")
var loadCount atomic.Int32
reg.RegisterLazy(from, to, func() RequestTransform {
loadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return rawJSON
}
})
// Trigger concurrent loads
done := make(chan struct{})
for i := 0; i < 10; i++ {
go func() {
reg.TranslateRequest(from, to, "m", []byte("t"), false)
done <- struct{}{}
}()
}
for i := 0; i < 10; i++ {
<-done
}
// Should only load once despite concurrent access
if loadCount.Load() != 1 {
t.Errorf("expected exactly 1 load with concurrent access, got %d", loadCount.Load())
}
}
func TestPackageLevelLazy_Functions(t *testing.T) {
from := Format("pkg-lazy-from")
to := Format("pkg-lazy-to")
var loadCount atomic.Int32
RegisterLazy(from, to, func() RequestTransform {
loadCount.Add(1)
return func(model string, rawJSON []byte, stream bool) []byte {
return rawJSON
}
})
if IsLazyLoaded(from, to) {
t.Error("should not be loaded yet")
}
stats := GetLazyLoadStats()
if stats.TotalLazy == 0 {
t.Error("expected at least 1 lazy registration")
}
// Force load
ForceLoadLazy()
if !IsLazyLoaded(from, to) {
t.Error("should be loaded after ForceLoadLazy")
}
}
func TestRegistryLazy_IsLazyLoaded_NotRegistered(t *testing.T) {
reg := NewRegistry()
// Check a path that was never registered
if reg.IsLazyLoaded("never", "registered") {
t.Error("should return false for unregistered path")
}
}
func TestRegistryLazy_EmptyRegistry(t *testing.T) {
reg := NewRegistry()
stats := reg.GetLazyLoadStats()
if stats.TotalLazy != 0 || stats.TotalLoaded != 0 {
t.Error("empty registry should have zero lazy stats")
}
// ForceLoadLazy on empty should not panic
reg.ForceLoadLazy()
}