forked from privapps/github-copilot-svcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
352 lines (298 loc) · 9.59 KB
/
Copy pathcli.go
File metadata and controls
352 lines (298 loc) · 9.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package internal
import (
"encoding/json"
"flag"
"fmt"
"os"
"time"
"strings"
)
// Command constants to avoid goconst errors
const (
cmdAuth = "auth"
cmdRun = "run"
cmdStart = "start"
cmdModels = "models"
cmdConfig = "config"
cmdStatus = "status"
cmdRefresh = "refresh"
// Constants to avoid magic numbers
defaultRefreshThreshold = 300 // 5 minutes minimum refresh threshold
secondsInMinute = 60
refreshPercentThreshold = 5 // 20% = 1/5
)
// PrintUsage prints the command usage information
func PrintUsage() {
fmt.Printf(`GitHub Copilot SVCS Proxy
A reverse proxy for GitHub Copilot providing OpenAI-compatible endpoints.
Usage:
%s [command] [options]
Commands:
start Start the proxy server (default)
auth Authenticate with GitHub Copilot using device flow
status Show detailed authentication and token status
config Display current configuration details
models List all available AI models
refresh Manually force token refresh
help Show this help message
version Show version information
Examples:
%s auth # Authenticate with GitHub
%s run --port 8080 # Run server on port 8080
%s status --json # Show status in JSON format
Environment Variables:
COPILOT_PORT Server port (default: 8081)
GITHUB_TOKEN GitHub OAuth token
COPILOT_TOKEN GitHub Copilot API token
LOG_LEVEL Log level (debug, info, warn, error)
Options:
`, os.Args[0], os.Args[0], os.Args[0], os.Args[0])
flag.PrintDefaults()
}
// RunCommand executes the specified command with arguments
func RunCommand(command string, args []string, version string) error {
// Check for flags
jsonOutput := len(args) >= 1 && args[0] == "--json"
switch command {
case cmdAuth:
return handleAuth()
case cmdRun, cmdStart:
return handleRun()
case cmdModels:
return handleModels()
case cmdConfig:
return handleConfig()
case cmdStatus:
return handleStatusWithFormat(jsonOutput)
case cmdRefresh:
return handleRefresh()
case "version":
fmt.Printf("github-copilot-svcs version %s\n", version)
return nil
case "help", "--help", "-h":
PrintUsage()
return nil
default:
logger.Error("Unknown command", "command", command)
PrintUsage()
return fmt.Errorf("unknown command: %s", command)
}
}
func handleAuth() error {
cfg, err := LoadConfig(true)
if err != nil {
return fmt.Errorf("failed to load config: %v", err)
}
// Create HTTP client with timeouts
httpClient := CreateHTTPClient(cfg)
authService := NewAuthService(httpClient)
fmt.Println("Starting GitHub Copilot authentication...")
if err := authService.Authenticate(cfg); err != nil {
return fmt.Errorf("authentication failed: %v", err)
}
fmt.Println("Authentication successful!")
return nil
}
func handleStatusWithFormat(jsonOutput bool) error {
cfg, err := LoadConfig()
if err != nil {
if strings.Contains(err.Error(), "either github_token or copilot_token must be provided") {
fmt.Println("Not authenticated. Run 'auth' to authenticate.")
return nil
}
return fmt.Errorf("failed to load config: %v", err)
}
if jsonOutput {
return printStatusJSON(cfg)
}
return printStatusText(cfg)
}
func printStatusJSON(cfg *Config) error {
path, _ := GetConfigPath()
now := getCurrentTime()
status := map[string]interface{}{
"config_file": path,
"port": cfg.Port,
"authenticated": cfg.CopilotToken != "",
"has_github_token": cfg.GitHubToken != "",
"refresh_interval": cfg.RefreshIn,
}
if cfg.CopilotToken != "" {
timeUntilExpiry := cfg.ExpiresAt - now
status["token_expires_at"] = cfg.ExpiresAt
status["token_expires_in_seconds"] = timeUntilExpiry
if timeUntilExpiry > 0 {
refreshThreshold := cfg.RefreshIn / refreshPercentThreshold
if refreshThreshold < defaultRefreshThreshold {
refreshThreshold = defaultRefreshThreshold
}
if timeUntilExpiry <= refreshThreshold {
status["status"] = "token_will_refresh_soon"
} else {
status["status"] = "healthy"
}
} else {
status["status"] = "token_expired"
}
} else {
status["status"] = "not_authenticated"
}
if err := json.NewEncoder(os.Stdout).Encode(status); err != nil {
return fmt.Errorf("failed to encode status as JSON: %w", err)
}
return nil
}
func printStatusText(cfg *Config) error {
path, _ := GetConfigPath()
fmt.Printf("Configuration file: %s\n", path)
fmt.Printf("Port: %d\n", cfg.Port)
now := getCurrentTime()
if cfg.CopilotToken != "" {
fmt.Printf("Authentication: ✓ Authenticated\n")
timeUntilExpiry := cfg.ExpiresAt - now
if timeUntilExpiry > 0 {
minutes := timeUntilExpiry / secondsInMinute
seconds := timeUntilExpiry % secondsInMinute
fmt.Printf("Token expires: in %dm %ds (%d seconds)\n", minutes, seconds, timeUntilExpiry)
// Show refresh timing
if cfg.RefreshIn > 0 {
refreshThreshold := cfg.RefreshIn / refreshPercentThreshold // 20%
if refreshThreshold < defaultRefreshThreshold {
refreshThreshold = defaultRefreshThreshold // minimum 5 minutes
}
if timeUntilExpiry <= refreshThreshold {
fmt.Printf("Status: ⚠️ Token will be refreshed soon (threshold: %d seconds)\n", refreshThreshold)
} else {
fmt.Printf("Status: ✅ Token is healthy\n")
}
}
} else {
fmt.Printf("Token expires: ⚠️ EXPIRED (%d seconds ago)\n", -timeUntilExpiry)
fmt.Printf("Status: ❌ Token needs refresh\n")
}
fmt.Printf("Has GitHub token: %t\n", cfg.GitHubToken != "")
if cfg.RefreshIn > 0 {
fmt.Printf("Refresh interval: %d seconds\n", cfg.RefreshIn)
}
} else {
fmt.Printf("Authentication: ✗ Not authenticated\n")
fmt.Printf("Run '%s auth' to authenticate\n", os.Args[0])
}
return nil
}
func handleConfig() error {
cfg, err := LoadConfig()
if err != nil {
if strings.Contains(err.Error(), "either github_token or copilot_token must be provided") {
fmt.Println("Not authenticated. Run 'auth' to authenticate.")
return nil
}
return fmt.Errorf("failed to load config: %v", err)
}
path, _ := GetConfigPath()
fmt.Printf("Configuration file: %s\n", path)
fmt.Printf("Port: %d\n", cfg.Port)
fmt.Printf("Has GitHub token: %t\n", cfg.GitHubToken != "")
fmt.Printf("Has Copilot token: %t\n", cfg.CopilotToken != "")
if cfg.ExpiresAt > 0 {
fmt.Printf("Token expires at: %d\n", cfg.ExpiresAt)
}
fmt.Printf("\nHTTP Headers:\n")
fmt.Printf(" User-Agent: %s\n", cfg.Headers.UserAgent)
fmt.Printf(" Editor-Version: %s\n", cfg.Headers.EditorVersion)
fmt.Printf(" Editor-Plugin-Version: %s\n", cfg.Headers.EditorPluginVersion)
fmt.Printf(" Copilot-Integration-Id: %s\n", cfg.Headers.CopilotIntegrationID)
fmt.Printf(" Openai-Intent: %s\n", cfg.Headers.OpenaiIntent)
fmt.Printf(" X-Initiator: %s\n", cfg.Headers.XInitiator)
return nil
}
func getCurrentTime() int64 {
return time.Now().Unix()
}
func handleRun() error {
cfg, err := LoadConfig()
if err != nil {
if strings.Contains(err.Error(), "either github_token or copilot_token must be provided") {
if authErr := handleAuth(); authErr != nil {
return fmt.Errorf("authentication failed: %v", authErr)
}
cfg, err = LoadConfig()
if err != nil {
return fmt.Errorf("failed to load config after authentication: %v", err)
}
} else {
return fmt.Errorf("failed to load config: %v", err)
}
}
// Create HTTP client and auth service
httpClient := CreateHTTPClient(cfg)
authService := NewAuthService(httpClient)
// Ensure we're authenticated
if err := authService.EnsureValidToken(cfg); err != nil {
return fmt.Errorf("authentication failed: %v", err)
}
// Create and start server
srv := NewServer(cfg, httpClient)
return srv.Start()
}
func handleModels() error {
cfg, err := LoadConfig()
if err != nil {
if strings.Contains(err.Error(), "either github_token or copilot_token must be provided") {
fmt.Println("Not authenticated. Run 'auth' to authenticate.")
return nil
}
return fmt.Errorf("failed to load config: %v", err)
}
// Create HTTP client and auth service
httpClient := CreateHTTPClient(cfg)
authService := NewAuthService(httpClient)
// Ensure we're authenticated
if authErr := authService.EnsureValidToken(cfg); authErr != nil {
return fmt.Errorf("authentication failed: %v", authErr)
}
// Fetch models
modelList, err := FetchFromModelsDev(httpClient)
if err != nil {
fmt.Printf("Failed to fetch models from models.dev: %v\n", err)
fmt.Println("Using default models:")
defaultModels := GetDefault()
for _, model := range defaultModels {
fmt.Printf(" - %s (%s)\n", model.ID, model.OwnedBy)
}
return nil
}
fmt.Printf("Available models (%d total):\n", len(modelList.Data))
for _, model := range modelList.Data {
fmt.Printf(" - %s (%s)\n", model.ID, model.OwnedBy)
}
return nil
}
func handleRefresh() error {
cfg, err := LoadConfig()
if err != nil {
if strings.Contains(err.Error(), "either github_token or copilot_token must be provided") {
fmt.Println("Not authenticated. Run 'auth' to authenticate.")
return nil
}
return fmt.Errorf("failed to load config: %v", err)
}
if cfg.CopilotToken == "" {
return fmt.Errorf("no token to refresh - run 'auth' command first")
}
// Create HTTP client and auth service
httpClient := CreateHTTPClient(cfg)
authService := NewAuthService(httpClient)
fmt.Println("Forcing token refresh...")
if err := authService.RefreshToken(cfg); err != nil {
return fmt.Errorf("token refresh failed: %v", err)
}
fmt.Printf("✅ Token refresh successful!\n")
// Show new expiration time
now := getCurrentTime()
timeUntilExpiry := cfg.ExpiresAt - now
minutes := timeUntilExpiry / secondsInMinute
seconds := timeUntilExpiry % secondsInMinute
fmt.Printf("New token expires in: %dm %ds\n", minutes, seconds)
return nil
}