mirror of
https://github.com/Finesssee/ProxyPilot.git
synced 2026-11-19 02:17:46 +00:00
feat(cli): add advanced account management commands
- Add -usage flag (token usage stats per provider) - Add -logs flag (view recent logs, -n for line count) - Add -refresh flag (force token refresh) - Add -list-models flag (show available models) - Add -export-accounts/-import-accounts (backup/restore) - Add --include-tokens and --force flags for export/import
This commit is contained in:
+785
-710
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,237 @@
|
||||
// Package cmd provides CLI command implementations for ProxyPilot.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
// ExportBundle represents exported accounts
|
||||
type ExportBundle struct {
|
||||
Version string `json:"version"`
|
||||
ExportedAt string `json:"exported_at"`
|
||||
Accounts []ExportedAccount `json:"accounts"`
|
||||
}
|
||||
|
||||
// ExportedAccount represents a single exported account
|
||||
type ExportedAccount struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Attributes map[string]string `json:"attributes,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
}
|
||||
|
||||
var sensitiveKeys = []string{
|
||||
"access_token", "refresh_token", "token", "api_key", "secret",
|
||||
"password", "credential", "session", "cookie", "id_token", "bearer",
|
||||
}
|
||||
|
||||
// ExportAccounts exports all accounts to JSON
|
||||
func ExportAccounts(outputPath string, includeTokens bool, jsonOutput bool) error {
|
||||
store := sdkAuth.NewFileTokenStore()
|
||||
store.SetBaseDir(util.DefaultAuthDir())
|
||||
|
||||
auths, err := store.List(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list accounts: %w", err)
|
||||
}
|
||||
|
||||
bundle := ExportBundle{
|
||||
Version: "1.0",
|
||||
ExportedAt: time.Now().Format(time.RFC3339),
|
||||
Accounts: make([]ExportedAccount, 0, len(auths)),
|
||||
}
|
||||
|
||||
for _, auth := range auths {
|
||||
exported := ExportedAccount{
|
||||
ID: auth.ID,
|
||||
Provider: auth.Provider,
|
||||
Label: auth.Label,
|
||||
Attributes: auth.Attributes,
|
||||
CreatedAt: auth.CreatedAt,
|
||||
}
|
||||
|
||||
if auth.Metadata != nil {
|
||||
exported.Metadata = make(map[string]any, len(auth.Metadata))
|
||||
for k, v := range auth.Metadata {
|
||||
if !includeTokens && isSensitiveKey(k) {
|
||||
exported.Metadata[k] = "[REDACTED]"
|
||||
} else {
|
||||
exported.Metadata[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
bundle.Accounts = append(bundle.Accounts, exported)
|
||||
}
|
||||
|
||||
// Determine output target
|
||||
var out io.Writer = os.Stdout
|
||||
if outputPath != "" && outputPath != "-" {
|
||||
f, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create output file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
out = f
|
||||
}
|
||||
|
||||
enc := json.NewEncoder(out)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(bundle); err != nil {
|
||||
return fmt.Errorf("failed to encode accounts: %w", err)
|
||||
}
|
||||
|
||||
if !jsonOutput && outputPath != "" && outputPath != "-" {
|
||||
fmt.Fprintf(os.Stderr, "%sExported %d accounts to %s%s\n",
|
||||
colorGreen, len(bundle.Accounts), outputPath, colorReset)
|
||||
if !includeTokens {
|
||||
fmt.Fprintf(os.Stderr, "%sNote: Sensitive tokens redacted. Use --include-tokens to include.%s\n",
|
||||
colorYellow, colorReset)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ImportAccounts imports accounts from a JSON bundle
|
||||
func ImportAccounts(inputPath string, force bool, jsonOutput bool) error {
|
||||
data, err := os.ReadFile(inputPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read import file: %w", err)
|
||||
}
|
||||
|
||||
var bundle ExportBundle
|
||||
if err := json.Unmarshal(data, &bundle); err != nil {
|
||||
return fmt.Errorf("failed to parse import file: %w", err)
|
||||
}
|
||||
|
||||
store := sdkAuth.NewFileTokenStore()
|
||||
store.SetBaseDir(util.DefaultAuthDir())
|
||||
|
||||
ctx := context.Background()
|
||||
existing, err := store.List(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list existing accounts: %w", err)
|
||||
}
|
||||
|
||||
existingIDs := make(map[string]bool)
|
||||
for _, auth := range existing {
|
||||
existingIDs[auth.ID] = true
|
||||
}
|
||||
|
||||
var imported, skipped, skippedRedacted int
|
||||
var results []map[string]any
|
||||
|
||||
for _, acc := range bundle.Accounts {
|
||||
// Skip if has redacted tokens
|
||||
hasRedacted := false
|
||||
if acc.Metadata != nil {
|
||||
for k, v := range acc.Metadata {
|
||||
if s, ok := v.(string); ok && s == "[REDACTED]" && isSensitiveKey(k) {
|
||||
hasRedacted = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if hasRedacted {
|
||||
skippedRedacted++
|
||||
if jsonOutput {
|
||||
results = append(results, map[string]any{
|
||||
"id": acc.ID, "status": "skipped", "reason": "redacted tokens",
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if exists
|
||||
if existingIDs[acc.ID] && !force {
|
||||
skipped++
|
||||
if jsonOutput {
|
||||
results = append(results, map[string]any{
|
||||
"id": acc.ID, "status": "skipped", "reason": "already exists",
|
||||
})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "%sSkipping %s (exists). Use --force to overwrite.%s\n",
|
||||
colorYellow, acc.ID, colorReset)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Convert to Auth
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: acc.ID,
|
||||
Provider: acc.Provider,
|
||||
Label: acc.Label,
|
||||
Attributes: acc.Attributes,
|
||||
Metadata: acc.Metadata,
|
||||
CreatedAt: acc.CreatedAt,
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Set FileName based on authdir
|
||||
auth.FileName = filepath.Join(util.DefaultAuthDir(), acc.ID+".json")
|
||||
|
||||
if _, err := store.Save(ctx, auth); err != nil {
|
||||
if jsonOutput {
|
||||
results = append(results, map[string]any{
|
||||
"id": acc.ID, "status": "error", "error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "%sFailed to import %s: %v%s\n",
|
||||
colorRed, acc.ID, err, colorReset)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
imported++
|
||||
if jsonOutput {
|
||||
results = append(results, map[string]any{
|
||||
"id": acc.ID, "status": "imported",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
return outputJSON(map[string]any{
|
||||
"imported": imported,
|
||||
"skipped": skipped,
|
||||
"skipped_redacted": skippedRedacted,
|
||||
"results": results,
|
||||
})
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s%sImport Summary%s\n", colorBold, colorCyan, colorReset)
|
||||
fmt.Printf("%s─────────────────────────%s\n", colorDim, colorReset)
|
||||
fmt.Printf(" Imported: %s%d%s\n", colorGreen, imported, colorReset)
|
||||
if skipped > 0 {
|
||||
fmt.Printf(" Skipped (existing): %s%d%s\n", colorYellow, skipped, colorReset)
|
||||
}
|
||||
if skippedRedacted > 0 {
|
||||
fmt.Printf(" Skipped (redacted): %s%d%s\n", colorYellow, skippedRedacted, colorReset)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isSensitiveKey(key string) bool {
|
||||
keyLower := strings.ToLower(key)
|
||||
for _, s := range sensitiveKeys {
|
||||
if strings.Contains(keyLower, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Package cmd provides CLI command implementations for ProxyPilot.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
||||
)
|
||||
|
||||
// ModelGroup represents a provider and its models
|
||||
type ModelGroup struct {
|
||||
Provider string `json:"provider"`
|
||||
Models []ModelEntry `json:"models"`
|
||||
}
|
||||
|
||||
// ModelEntry represents a single model entry for output
|
||||
type ModelEntry struct {
|
||||
ID string `json:"id"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Thinking bool `json:"thinking,omitempty"`
|
||||
}
|
||||
|
||||
// ListModels lists all available models grouped by provider
|
||||
func ListModels(jsonOutput bool) error {
|
||||
groups := collectModelGroups()
|
||||
if jsonOutput {
|
||||
return outputModelsAsJSON(groups)
|
||||
}
|
||||
return outputModelsTable(groups)
|
||||
}
|
||||
|
||||
func collectModelGroups() []ModelGroup {
|
||||
providers := []struct {
|
||||
name string
|
||||
models []*registry.ModelInfo
|
||||
}{
|
||||
{"Claude", registry.GetClaudeModels()},
|
||||
{"Gemini", registry.GetGeminiModels()},
|
||||
{"AI Studio", registry.GetAIStudioModels()},
|
||||
{"OpenAI (Codex)", registry.GetOpenAIModels()},
|
||||
{"Qwen", registry.GetQwenModels()},
|
||||
{"MiniMax", registry.GetMiniMaxModels()},
|
||||
{"Zhipu", registry.GetZhipuModels()},
|
||||
{"Kiro", registry.GetKiroModels()},
|
||||
{"Amazon Q", registry.GetAmazonQModels()},
|
||||
{"GitHub Copilot", registry.GetGitHubCopilotModels()},
|
||||
}
|
||||
|
||||
var groups []ModelGroup
|
||||
for _, p := range providers {
|
||||
if len(p.models) == 0 {
|
||||
continue
|
||||
}
|
||||
entries := make([]ModelEntry, 0, len(p.models))
|
||||
for _, m := range p.models {
|
||||
entry := ModelEntry{
|
||||
ID: m.ID,
|
||||
DisplayName: m.DisplayName,
|
||||
Description: m.Description,
|
||||
Thinking: m.Thinking != nil,
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
return entries[i].ID < entries[j].ID
|
||||
})
|
||||
groups = append(groups, ModelGroup{Provider: p.name, Models: entries})
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
func outputModelsTable(groups []ModelGroup) error {
|
||||
if len(groups) == 0 {
|
||||
fmt.Printf("%sNo models available%s\n", colorYellow, colorReset)
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, g := range groups {
|
||||
fmt.Printf("\n%s%s%s %s(%d models)%s\n",
|
||||
colorBold, g.Provider, colorReset, colorDim, len(g.Models), colorReset)
|
||||
fmt.Printf("%s─────────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
for _, m := range g.Models {
|
||||
thinkTag := ""
|
||||
if m.Thinking {
|
||||
thinkTag = fmt.Sprintf(" %s[thinking]%s", colorCyan, colorReset)
|
||||
}
|
||||
name := m.ID
|
||||
if m.DisplayName != "" && m.DisplayName != m.ID {
|
||||
name = fmt.Sprintf("%s %s(%s)%s", m.ID, colorDim, m.DisplayName, colorReset)
|
||||
}
|
||||
fmt.Printf(" %s%s%s\n", colorGreen, name, thinkTag)
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
|
||||
func outputModelsAsJSON(groups []ModelGroup) error {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(groups)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// Package cmd provides CLI command implementations for ProxyPilot.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
|
||||
)
|
||||
|
||||
// DefaultLogLines is the default number of log lines to show
|
||||
const DefaultLogLines = 50
|
||||
|
||||
// LogEntryOutput represents a log entry for JSON output
|
||||
type LogEntryOutput struct {
|
||||
Timestamp string `json:"timestamp"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Source string `json:"source,omitempty"`
|
||||
Fields map[string]interface{} `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
// LogsOutput represents the JSON output structure for logs
|
||||
type LogsOutput struct {
|
||||
Count int `json:"count"`
|
||||
Entries []LogEntryOutput `json:"entries"`
|
||||
}
|
||||
|
||||
// ShowLogs displays recent proxy log entries
|
||||
func ShowLogs(n int, jsonOutput bool) error {
|
||||
if n <= 0 {
|
||||
n = DefaultLogLines
|
||||
}
|
||||
|
||||
entries := logging.GetRecentGlobalEntries(n)
|
||||
|
||||
if jsonOutput {
|
||||
return outputLogsJSON(entries)
|
||||
}
|
||||
|
||||
return outputLogsTable(entries)
|
||||
}
|
||||
|
||||
func outputLogsJSON(entries []logging.LogEntry) error {
|
||||
output := LogsOutput{
|
||||
Count: len(entries),
|
||||
Entries: make([]LogEntryOutput, len(entries)),
|
||||
}
|
||||
|
||||
for i, entry := range entries {
|
||||
output.Entries[i] = LogEntryOutput{
|
||||
Timestamp: entry.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"),
|
||||
Level: entry.Level,
|
||||
Message: entry.Message,
|
||||
Source: entry.Source,
|
||||
Fields: entry.Fields,
|
||||
}
|
||||
}
|
||||
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(output)
|
||||
}
|
||||
|
||||
func outputLogsTable(entries []logging.LogEntry) error {
|
||||
if len(entries) == 0 {
|
||||
fmt.Printf("%sNo log entries available%s\n", colorYellow, colorReset)
|
||||
fmt.Printf("%sLogs are captured during proxy operation.%s\n", colorDim, colorReset)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s%sProxyPilot Logs%s (%d entries)\n", colorBold, colorCyan, colorReset, len(entries))
|
||||
fmt.Printf("%s───────────────────────────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset)
|
||||
|
||||
for _, entry := range entries {
|
||||
timestamp := entry.Timestamp.Format("15:04:05")
|
||||
level := formatLogLevel(entry.Level)
|
||||
message := entry.Message
|
||||
|
||||
// Truncate very long messages
|
||||
if len(message) > 100 {
|
||||
message = message[:97] + "..."
|
||||
}
|
||||
|
||||
// Remove trailing newlines
|
||||
message = strings.TrimRight(message, "\r\n")
|
||||
|
||||
fmt.Printf("%s%s%s %s %s\n", colorDim, timestamp, colorReset, level, message)
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s───────────────────────────────────────────────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatLogLevel(level string) string {
|
||||
switch strings.ToLower(level) {
|
||||
case "debug":
|
||||
return colorDim + "[DEBUG]" + colorReset
|
||||
case "info":
|
||||
return colorBlue + "[INFO] " + colorReset
|
||||
case "warn", "warning":
|
||||
return colorYellow + "[WARN] " + colorReset
|
||||
case "error":
|
||||
return colorRed + "[ERROR]" + colorReset
|
||||
case "fatal":
|
||||
return colorRed + colorBold + "[FATAL]" + colorReset
|
||||
default:
|
||||
return "[" + strings.ToUpper(level) + "]"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
// Package cmd provides CLI command implementations for ProxyPilot.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
claudeauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude"
|
||||
codexauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
|
||||
kiroauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kiro"
|
||||
qwenauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/qwen"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
// RefreshResult holds the result of a token refresh operation
|
||||
type RefreshResult struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
// RefreshTokens refreshes tokens for matching accounts.
|
||||
// If identifier is empty, refresh all accounts.
|
||||
// If identifier is provided, match by email or ID.
|
||||
func RefreshTokens(cfg *config.Config, identifier string, jsonOutput bool) error {
|
||||
store := sdkAuth.NewFileTokenStore()
|
||||
store.SetBaseDir(util.DefaultAuthDir())
|
||||
|
||||
auths, err := store.List(context.Background())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list accounts: %w", err)
|
||||
}
|
||||
|
||||
// Filter accounts if identifier provided
|
||||
var toRefresh []*cliproxyauth.Auth
|
||||
identifier = strings.TrimSpace(strings.ToLower(identifier))
|
||||
|
||||
for _, auth := range auths {
|
||||
if identifier == "" {
|
||||
toRefresh = append(toRefresh, auth)
|
||||
continue
|
||||
}
|
||||
|
||||
// Match by ID, email, or label
|
||||
id := strings.ToLower(auth.ID)
|
||||
email := strings.ToLower(auth.Attributes["email"])
|
||||
label := strings.ToLower(auth.Label)
|
||||
|
||||
if id == identifier || strings.Contains(id, identifier) ||
|
||||
email == identifier || strings.Contains(email, identifier) ||
|
||||
label == identifier || strings.Contains(label, identifier) {
|
||||
toRefresh = append(toRefresh, auth)
|
||||
}
|
||||
}
|
||||
|
||||
if len(toRefresh) == 0 {
|
||||
if identifier != "" {
|
||||
return fmt.Errorf("no matching accounts found for: %s", identifier)
|
||||
}
|
||||
if jsonOutput {
|
||||
return outputJSON([]RefreshResult{})
|
||||
}
|
||||
fmt.Printf("%sNo accounts found to refresh%s\n", colorYellow, colorReset)
|
||||
return nil
|
||||
}
|
||||
|
||||
results := make([]RefreshResult, 0, len(toRefresh))
|
||||
|
||||
if !jsonOutput {
|
||||
fmt.Printf("\n%s%sRefreshing tokens...%s\n", colorBold, colorCyan, colorReset)
|
||||
fmt.Printf("%s─────────────────────────────%s\n\n", colorDim, colorReset)
|
||||
}
|
||||
|
||||
for _, auth := range toRefresh {
|
||||
result := refreshSingleAuth(cfg, auth, store)
|
||||
results = append(results, result)
|
||||
|
||||
if !jsonOutput {
|
||||
printRefreshResult(result)
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
return outputJSON(results)
|
||||
}
|
||||
|
||||
// Print summary
|
||||
succeeded := 0
|
||||
failed := 0
|
||||
for _, r := range results {
|
||||
if r.Success {
|
||||
succeeded++
|
||||
} else {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s─────────────────────────────%s\n", colorDim, colorReset)
|
||||
fmt.Printf("Refreshed: %s%d succeeded%s", colorGreen, succeeded, colorReset)
|
||||
if failed > 0 {
|
||||
fmt.Printf(", %s%d failed%s", colorRed, failed, colorReset)
|
||||
}
|
||||
fmt.Printf("\n\n")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func refreshSingleAuth(cfg *config.Config, auth *cliproxyauth.Auth, store *sdkAuth.FileTokenStore) RefreshResult {
|
||||
result := RefreshResult{
|
||||
ID: auth.ID,
|
||||
Provider: auth.Provider,
|
||||
Email: auth.Attributes["email"],
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var refreshErr error
|
||||
var updated *cliproxyauth.Auth
|
||||
|
||||
switch strings.ToLower(auth.Provider) {
|
||||
case "claude":
|
||||
updated, refreshErr = refreshClaude(ctx, cfg, auth)
|
||||
case "codex":
|
||||
updated, refreshErr = refreshCodex(ctx, cfg, auth)
|
||||
case "gemini", "gemini-cli":
|
||||
// Gemini tokens are refreshed automatically by the OAuth2 library
|
||||
refreshErr = fmt.Errorf("gemini tokens refresh automatically; use re-login if expired")
|
||||
case "kiro":
|
||||
updated, refreshErr = refreshKiro(ctx, cfg, auth)
|
||||
case "qwen":
|
||||
updated, refreshErr = refreshQwen(ctx, cfg, auth)
|
||||
case "antigravity":
|
||||
// Antigravity uses short-lived tokens - needs re-import
|
||||
refreshErr = fmt.Errorf("antigravity requires re-import (use --antigravity-import)")
|
||||
case "vertex":
|
||||
// Vertex uses service account - no refresh needed
|
||||
result.Success = true
|
||||
return result
|
||||
case "minimax", "zhipu":
|
||||
// API key based - no refresh needed
|
||||
result.Success = true
|
||||
return result
|
||||
default:
|
||||
refreshErr = fmt.Errorf("unsupported provider: %s", auth.Provider)
|
||||
}
|
||||
|
||||
if refreshErr != nil {
|
||||
result.Error = refreshErr.Error()
|
||||
return result
|
||||
}
|
||||
|
||||
if updated != nil {
|
||||
// Save updated auth
|
||||
if _, saveErr := store.Save(ctx, updated); saveErr != nil {
|
||||
result.Error = fmt.Sprintf("refresh succeeded but save failed: %v", saveErr)
|
||||
return result
|
||||
}
|
||||
|
||||
// Extract new expiry
|
||||
if expiry, ok := updated.ExpirationTime(); ok {
|
||||
result.ExpiresAt = expiry.Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
return result
|
||||
}
|
||||
|
||||
func refreshClaude(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if auth.Metadata == nil {
|
||||
return nil, fmt.Errorf("no metadata")
|
||||
}
|
||||
|
||||
refreshToken, ok := auth.Metadata["refresh_token"].(string)
|
||||
if !ok || refreshToken == "" {
|
||||
return nil, fmt.Errorf("no refresh token")
|
||||
}
|
||||
|
||||
svc := claudeauth.NewClaudeAuth(cfg)
|
||||
td, err := svc.RefreshTokens(ctx, refreshToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updated := auth.Clone()
|
||||
updated.Metadata["access_token"] = td.AccessToken
|
||||
if td.RefreshToken != "" {
|
||||
updated.Metadata["refresh_token"] = td.RefreshToken
|
||||
}
|
||||
updated.Metadata["email"] = td.Email
|
||||
updated.Metadata["expired"] = td.Expire
|
||||
updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
|
||||
|
||||
if expiry, ok := updated.ExpirationTime(); ok {
|
||||
updated.TokenExpiresAt = expiry
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func refreshCodex(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if auth.Metadata == nil {
|
||||
return nil, fmt.Errorf("no metadata")
|
||||
}
|
||||
|
||||
refreshToken, ok := auth.Metadata["refresh_token"].(string)
|
||||
if !ok || refreshToken == "" {
|
||||
return nil, fmt.Errorf("no refresh token")
|
||||
}
|
||||
|
||||
svc := codexauth.NewCodexAuth(cfg)
|
||||
td, err := svc.RefreshTokensWithRetry(ctx, refreshToken, 3)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updated := auth.Clone()
|
||||
updated.Metadata["id_token"] = td.IDToken
|
||||
updated.Metadata["access_token"] = td.AccessToken
|
||||
if td.RefreshToken != "" {
|
||||
updated.Metadata["refresh_token"] = td.RefreshToken
|
||||
}
|
||||
if td.AccountID != "" {
|
||||
updated.Metadata["account_id"] = td.AccountID
|
||||
}
|
||||
updated.Metadata["email"] = td.Email
|
||||
updated.Metadata["expired"] = td.Expire
|
||||
updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
|
||||
|
||||
if expiry, ok := updated.ExpirationTime(); ok {
|
||||
updated.TokenExpiresAt = expiry
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func refreshKiro(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if auth.Metadata == nil {
|
||||
return nil, fmt.Errorf("no metadata")
|
||||
}
|
||||
|
||||
refreshToken, ok := auth.Metadata["refresh_token"].(string)
|
||||
if !ok || refreshToken == "" {
|
||||
return nil, fmt.Errorf("no refresh token")
|
||||
}
|
||||
|
||||
clientID, _ := auth.Metadata["client_id"].(string)
|
||||
clientSecret, _ := auth.Metadata["client_secret"].(string)
|
||||
authMethod, _ := auth.Metadata["auth_method"].(string)
|
||||
startURL, _ := auth.Metadata["start_url"].(string)
|
||||
region, _ := auth.Metadata["region"].(string)
|
||||
|
||||
var tokenData *kiroauth.KiroTokenData
|
||||
var err error
|
||||
|
||||
ssoClient := kiroauth.NewSSOOIDCClient(cfg)
|
||||
|
||||
switch {
|
||||
case clientID != "" && clientSecret != "" && authMethod == "idc" && region != "":
|
||||
tokenData, err = ssoClient.RefreshTokenWithRegion(ctx, clientID, clientSecret, refreshToken, region, startURL)
|
||||
case clientID != "" && clientSecret != "" && authMethod == "builder-id":
|
||||
tokenData, err = ssoClient.RefreshToken(ctx, clientID, clientSecret, refreshToken)
|
||||
default:
|
||||
oauth := kiroauth.NewKiroOAuth(cfg)
|
||||
tokenData, err = oauth.RefreshToken(ctx, refreshToken)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updated := auth.Clone()
|
||||
now := time.Now()
|
||||
updated.UpdatedAt = now
|
||||
updated.LastRefreshedAt = now
|
||||
updated.Metadata["access_token"] = tokenData.AccessToken
|
||||
updated.Metadata["refresh_token"] = tokenData.RefreshToken
|
||||
updated.Metadata["expires_at"] = tokenData.ExpiresAt
|
||||
updated.Metadata["last_refresh"] = now.Format(time.RFC3339)
|
||||
|
||||
expiresAt, _ := time.Parse(time.RFC3339, tokenData.ExpiresAt)
|
||||
if !expiresAt.IsZero() {
|
||||
updated.NextRefreshAfter = expiresAt.Add(-5 * time.Minute)
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func refreshQwen(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if auth.Metadata == nil {
|
||||
return nil, fmt.Errorf("no metadata")
|
||||
}
|
||||
|
||||
refreshToken, ok := auth.Metadata["refresh_token"].(string)
|
||||
if !ok || refreshToken == "" {
|
||||
return nil, fmt.Errorf("no refresh token")
|
||||
}
|
||||
|
||||
svc := qwenauth.NewQwenAuth(cfg)
|
||||
td, err := svc.RefreshTokens(ctx, refreshToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updated := auth.Clone()
|
||||
updated.Metadata["access_token"] = td.AccessToken
|
||||
if td.RefreshToken != "" {
|
||||
updated.Metadata["refresh_token"] = td.RefreshToken
|
||||
}
|
||||
updated.Metadata["expired"] = td.Expire
|
||||
updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
|
||||
|
||||
if expiry, ok := updated.ExpirationTime(); ok {
|
||||
updated.TokenExpiresAt = expiry
|
||||
}
|
||||
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func printRefreshResult(result RefreshResult) {
|
||||
email := result.Email
|
||||
if email == "" {
|
||||
email = result.ID
|
||||
}
|
||||
if len(email) > 35 {
|
||||
email = email[:32] + "..."
|
||||
}
|
||||
|
||||
if result.Success {
|
||||
expiry := ""
|
||||
if result.ExpiresAt != "" {
|
||||
if t, err := time.Parse(time.RFC3339, result.ExpiresAt); err == nil {
|
||||
expiry = fmt.Sprintf(" (expires: %s)", t.Format("2006-01-02 15:04"))
|
||||
}
|
||||
}
|
||||
fmt.Printf(" %s+%s %-12s %-35s %srefreshed%s%s\n",
|
||||
colorGreen, colorReset,
|
||||
result.Provider, email,
|
||||
colorGreen, colorReset, expiry)
|
||||
} else {
|
||||
errMsg := result.Error
|
||||
if len(errMsg) > 40 {
|
||||
errMsg = errMsg[:37] + "..."
|
||||
}
|
||||
fmt.Printf(" %sx%s %-12s %-35s %sfailed%s: %s\n",
|
||||
colorRed, colorReset,
|
||||
result.Provider, email,
|
||||
colorRed, colorReset, errMsg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
// Package cmd provides CLI command implementations for ProxyPilot.
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
|
||||
)
|
||||
|
||||
// UsageOutput represents the JSON output structure for usage stats
|
||||
type UsageOutput struct {
|
||||
TotalRequests int64 `json:"total_requests"`
|
||||
SuccessCount int64 `json:"success_count"`
|
||||
FailureCount int64 `json:"failure_count"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
TotalInputTokens int64 `json:"total_input_tokens"`
|
||||
TotalOutputTokens int64 `json:"total_output_tokens"`
|
||||
ByProvider map[string]ProviderStats `json:"by_provider"`
|
||||
ByDay map[string]DayStats `json:"by_day,omitempty"`
|
||||
}
|
||||
|
||||
// ProviderStats holds usage stats for a single provider
|
||||
type ProviderStats struct {
|
||||
Requests int64 `json:"requests"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
Models map[string]int64 `json:"models,omitempty"`
|
||||
}
|
||||
|
||||
// DayStats holds daily usage stats
|
||||
type DayStats struct {
|
||||
Requests int64 `json:"requests"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
}
|
||||
|
||||
// ShowUsage displays token usage stats per account/provider
|
||||
func ShowUsage(jsonOutput bool) error {
|
||||
stats := usage.GetRequestStatistics()
|
||||
if stats == nil {
|
||||
if jsonOutput {
|
||||
return outputJSON(UsageOutput{
|
||||
ByProvider: make(map[string]ProviderStats),
|
||||
ByDay: make(map[string]DayStats),
|
||||
})
|
||||
}
|
||||
fmt.Printf("%sNo usage data available%s\n", colorYellow, colorReset)
|
||||
return nil
|
||||
}
|
||||
|
||||
snapshot := stats.Snapshot()
|
||||
|
||||
if jsonOutput {
|
||||
return outputUsageJSON(snapshot)
|
||||
}
|
||||
|
||||
return outputUsageTable(snapshot)
|
||||
}
|
||||
|
||||
func outputUsageJSON(snapshot usage.StatisticsSnapshot) error {
|
||||
output := UsageOutput{
|
||||
TotalRequests: snapshot.TotalRequests,
|
||||
SuccessCount: snapshot.SuccessCount,
|
||||
FailureCount: snapshot.FailureCount,
|
||||
TotalTokens: snapshot.TotalTokens,
|
||||
TotalInputTokens: snapshot.TotalInputTokens,
|
||||
TotalOutputTokens: snapshot.TotalOutputTokens,
|
||||
ByProvider: make(map[string]ProviderStats),
|
||||
ByDay: make(map[string]DayStats),
|
||||
}
|
||||
|
||||
// Aggregate by provider
|
||||
for apiName, apiSnapshot := range snapshot.APIs {
|
||||
provider := inferProvider(apiName)
|
||||
ps := output.ByProvider[provider]
|
||||
ps.Requests += apiSnapshot.TotalRequests
|
||||
ps.Tokens += apiSnapshot.TotalTokens
|
||||
if ps.Models == nil {
|
||||
ps.Models = make(map[string]int64)
|
||||
}
|
||||
for modelName, modelSnapshot := range apiSnapshot.Models {
|
||||
ps.Models[modelName] += modelSnapshot.TotalRequests
|
||||
}
|
||||
output.ByProvider[provider] = ps
|
||||
}
|
||||
|
||||
// Daily stats
|
||||
for day, requests := range snapshot.RequestsByDay {
|
||||
ds := output.ByDay[day]
|
||||
ds.Requests = requests
|
||||
ds.Tokens = snapshot.TokensByDay[day]
|
||||
ds.InputTokens = snapshot.InputTokensByDay[day]
|
||||
ds.OutputTokens = snapshot.OutputTokensByDay[day]
|
||||
output.ByDay[day] = ds
|
||||
}
|
||||
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
return enc.Encode(output)
|
||||
}
|
||||
|
||||
func outputUsageTable(snapshot usage.StatisticsSnapshot) error {
|
||||
if snapshot.TotalRequests == 0 {
|
||||
fmt.Printf("%sNo usage data available%s\n", colorYellow, colorReset)
|
||||
fmt.Printf("%sUsage statistics are collected during proxy operation.%s\n", colorDim, colorReset)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s%sProxyPilot Usage Statistics%s\n", colorBold, colorCyan, colorReset)
|
||||
fmt.Printf("%s─────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset)
|
||||
|
||||
// Summary
|
||||
fmt.Printf("%sTotal Requests:%s %d", colorBold, colorReset, snapshot.TotalRequests)
|
||||
if snapshot.FailureCount > 0 {
|
||||
fmt.Printf(" (%s%d failed%s)", colorRed, snapshot.FailureCount, colorReset)
|
||||
}
|
||||
fmt.Println()
|
||||
fmt.Printf("%sTotal Tokens:%s %s\n", colorBold, colorReset, formatTokenCount(snapshot.TotalTokens))
|
||||
fmt.Printf(" Input: %s\n", formatTokenCount(snapshot.TotalInputTokens))
|
||||
fmt.Printf(" Output: %s\n", formatTokenCount(snapshot.TotalOutputTokens))
|
||||
|
||||
// By provider
|
||||
if len(snapshot.APIs) > 0 {
|
||||
fmt.Printf("\n%s%sByProvider%s\n", colorBold, colorCyan, colorReset)
|
||||
fmt.Printf("%s─────────────────────────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
// Aggregate by provider
|
||||
providerStats := make(map[string]struct {
|
||||
requests int64
|
||||
tokens int64
|
||||
})
|
||||
|
||||
for apiName, apiSnapshot := range snapshot.APIs {
|
||||
provider := inferProvider(apiName)
|
||||
ps := providerStats[provider]
|
||||
ps.requests += apiSnapshot.TotalRequests
|
||||
ps.tokens += apiSnapshot.TotalTokens
|
||||
providerStats[provider] = ps
|
||||
}
|
||||
|
||||
// Sort providers
|
||||
providers := make([]string, 0, len(providerStats))
|
||||
for p := range providerStats {
|
||||
providers = append(providers, p)
|
||||
}
|
||||
sort.Strings(providers)
|
||||
|
||||
fmt.Printf(" %-15s %10s %15s\n", "Provider", "Requests", "Tokens")
|
||||
fmt.Printf(" %s───────────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
for _, provider := range providers {
|
||||
ps := providerStats[provider]
|
||||
fmt.Printf(" %-15s %10d %15s\n", provider, ps.requests, formatTokenCount(ps.tokens))
|
||||
}
|
||||
}
|
||||
|
||||
// Recent daily stats
|
||||
if len(snapshot.RequestsByDay) > 0 {
|
||||
fmt.Printf("\n%s%sRecent Activity%s\n", colorBold, colorCyan, colorReset)
|
||||
fmt.Printf("%s─────────────────────────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
// Sort days
|
||||
days := make([]string, 0, len(snapshot.RequestsByDay))
|
||||
for day := range snapshot.RequestsByDay {
|
||||
days = append(days, day)
|
||||
}
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(days)))
|
||||
|
||||
// Show last 7 days max
|
||||
if len(days) > 7 {
|
||||
days = days[:7]
|
||||
}
|
||||
|
||||
fmt.Printf(" %-12s %10s %15s\n", "Date", "Requests", "Tokens")
|
||||
fmt.Printf(" %s─────────────────────────────────────%s\n", colorDim, colorReset)
|
||||
|
||||
for _, day := range days {
|
||||
requests := snapshot.RequestsByDay[day]
|
||||
tokens := snapshot.TokensByDay[day]
|
||||
fmt.Printf(" %-12s %10d %15s\n", day, requests, formatTokenCount(tokens))
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s─────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func inferProvider(apiName string) string {
|
||||
switch {
|
||||
case contains(apiName, "claude", "anthropic"):
|
||||
return "anthropic"
|
||||
case contains(apiName, "gpt", "openai", "codex"):
|
||||
return "openai"
|
||||
case contains(apiName, "gemini", "google"):
|
||||
return "google"
|
||||
case contains(apiName, "qwen"):
|
||||
return "qwen"
|
||||
case contains(apiName, "deepseek"):
|
||||
return "deepseek"
|
||||
case contains(apiName, "kiro", "amazon"):
|
||||
return "kiro"
|
||||
default:
|
||||
return apiName
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s string, substrs ...string) bool {
|
||||
lower := toLower(s)
|
||||
for _, sub := range substrs {
|
||||
if indexOfLower(lower, sub) >= 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func toLower(s string) string {
|
||||
b := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
b[i] = c
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func indexOfLower(s, sub string) int {
|
||||
for i := 0; i <= len(s)-len(sub); i++ {
|
||||
match := true
|
||||
for j := 0; j < len(sub); j++ {
|
||||
if s[i+j] != sub[j] {
|
||||
match = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if match {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func formatTokenCount(tokens int64) string {
|
||||
if tokens < 1000 {
|
||||
return fmt.Sprintf("%d", tokens)
|
||||
}
|
||||
if tokens < 1000000 {
|
||||
return fmt.Sprintf("%.1fK", float64(tokens)/1000)
|
||||
}
|
||||
return fmt.Sprintf("%.2fM", float64(tokens)/1000000)
|
||||
}
|
||||
Reference in New Issue
Block a user