forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.ts
More file actions
357 lines (322 loc) · 10 KB
/
start.ts
File metadata and controls
357 lines (322 loc) · 10 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
353
354
355
356
357
#!/usr/bin/env node
import { defineCommand } from "citty"
import clipboard from "clipboardy"
import consola from "consola"
import { serve, type ServerHandler } from "srvx"
import invariant from "tiny-invariant"
import { AccountPool, type Strategy } from "./lib/account-pool"
import {
loadAccounts,
parseGithubTokenArgs,
persistAccounts,
} from "./lib/accounts-loader"
import { initDb } from "./lib/db"
import { ensurePaths, PATHS } from "./lib/paths"
import { schedulePricingSync } from "./lib/pricing-scheduler"
import { initProxyFromEnv } from "./lib/proxy"
import { parseRecordParts } from "./lib/request-recorder"
import { generateEnvScript } from "./lib/shell"
import { state } from "./lib/state"
import { setupCopilotTokenFor, setupGitHubToken } from "./lib/token"
import { cacheModels, cacheVSCodeVersion } from "./lib/utils"
import { createServer } from "./server"
interface RunServerOptions {
port: number
verbose: boolean
accountType: string
manual: boolean
rateLimit?: number
rateLimitWait: boolean
githubToken?: string
claudeCode: boolean
showToken: boolean
proxyEnv: boolean
dbPath: string
accountsFile?: string
strategy: Strategy
pricingSyncModel?: string
pricingSyncIntervalDays: number
pricingSyncDisabled: boolean
recordRequests: boolean
recordDir: string
recordParts: string
}
/** Citty may return a string or string[] for repeated --github-token flags. Normalize to comma-separated. */
function normalizeGithubToken(
raw: string | Array<string> | undefined,
): string | undefined {
if (!raw) return undefined
return Array.isArray(raw) ? raw.join(",") : raw
}
async function promptClaudeCodeSetup(serverUrl: string): Promise<void> {
invariant(state.models, "Models should be loaded by now")
const selectedModel = await consola.prompt(
"Select a model to use with Claude Code",
{
type: "select",
options: state.models.data.map((model) => model.id),
},
)
const selectedSmallModel = await consola.prompt(
"Select a small model to use with Claude Code",
{
type: "select",
options: state.models.data.map((model) => model.id),
},
)
const command = generateEnvScript(
{
ANTHROPIC_BASE_URL: serverUrl,
ANTHROPIC_AUTH_TOKEN: "dummy",
ANTHROPIC_MODEL: selectedModel,
ANTHROPIC_DEFAULT_SONNET_MODEL: selectedModel,
ANTHROPIC_SMALL_FAST_MODEL: selectedSmallModel,
ANTHROPIC_DEFAULT_HAIKU_MODEL: selectedSmallModel,
DISABLE_NON_ESSENTIAL_MODEL_CALLS: "1",
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
},
"claude",
)
try {
clipboard.writeSync(command)
consola.success("Copied Claude Code command to clipboard!")
} catch {
consola.warn(
"Failed to copy to clipboard. Here is the Claude Code command:",
)
consola.log(command)
}
}
// eslint-disable-next-line complexity
export async function runServer(options: RunServerOptions): Promise<void> {
if (options.proxyEnv) {
initProxyFromEnv()
}
if (options.verbose) {
consola.level = 5
consola.info("Verbose logging enabled")
}
state.accountType = options.accountType
state.strategy = options.strategy
if (options.accountType !== "individual") {
consola.info(`Using ${options.accountType} plan GitHub account`)
}
state.manualApprove = options.manual
state.rateLimitSeconds = options.rateLimit
state.rateLimitWait = options.rateLimitWait
state.showToken = options.showToken
await ensurePaths()
initDb(options.dbPath)
await cacheVSCodeVersion()
// Resolve accounts: multi-token CLI → accounts file → single token → interactive
let legacyToken: string | undefined
let multiTokenEntries: ReturnType<typeof parseGithubTokenArgs> | undefined
if (options.githubToken && !options.accountsFile) {
multiTokenEntries = parseGithubTokenArgs(options.githubToken)
if (multiTokenEntries.length > 0) {
consola.info("Using provided GitHub token(s)")
}
}
if (!multiTokenEntries?.length && !options.accountsFile) {
legacyToken = await setupGitHubToken()
}
const loaded = await loadAccounts({
accountsFile: options.accountsFile,
legacyTokens: multiTokenEntries,
legacyToken,
defaultAccountType: options.accountType,
})
if (loaded.length === 0) {
throw new Error(
"No accounts available. Provide --accounts-file or --github-token, or run `auth`.",
)
}
const pool = new AccountPool(loaded, options.strategy)
state.pool = pool
persistAccounts(loaded)
consola.info(
`Loaded ${loaded.length} account${loaded.length === 1 ? "" : "s"} (strategy: ${options.strategy})`,
)
// Fetch Copilot token for each account in parallel.
await Promise.all(loaded.map((a) => setupCopilotTokenFor(a)))
for (const a of loaded) {
consola.info(`[${a.name}] ready`)
}
await cacheModels()
consola.info(
`Available models: \n${state.models?.data.map((model) => `- ${model.id}`).join("\n")}`,
)
const serverUrl = `http://localhost:${options.port}`
if (options.claudeCode) {
await promptClaudeCodeSetup(serverUrl)
}
consola.box(
`🌐 Usage Viewer: https://ericc-ch.github.io/copilot-api?endpoint=${serverUrl}/usage`,
)
// Create server with optional request recording
const recorderOpts =
options.recordRequests ?
{ logDir: options.recordDir, ...parseRecordParts(options.recordParts) }
: undefined
if (recorderOpts) {
consola.info(`Request recording enabled → ${options.recordDir}`)
}
const server = createServer({ recorder: recorderOpts })
serve({
fetch: server.fetch as ServerHandler,
port: options.port,
})
if (!options.pricingSyncDisabled) {
schedulePricingSync({
port: options.port,
intervalDays: options.pricingSyncIntervalDays,
syncModel: options.pricingSyncModel,
})
}
}
export const start = defineCommand({
meta: {
name: "start",
description: "Start the Copilot API server",
},
args: {
port: {
alias: "p",
type: "string",
default: "4141",
description: "Port to listen on",
},
verbose: {
alias: "v",
type: "boolean",
default: false,
description: "Enable verbose logging",
},
"account-type": {
alias: "a",
type: "string",
default: "individual",
description: "Account type to use (individual, business, enterprise)",
},
manual: {
type: "boolean",
default: false,
description: "Enable manual request approval",
},
"rate-limit": {
alias: "r",
type: "string",
description: "Rate limit in seconds between requests",
},
wait: {
alias: "w",
type: "boolean",
default: false,
description:
"Wait instead of error when rate limit is hit. Has no effect if rate limit is not set",
},
"github-token": {
alias: "g",
type: "string",
description:
"Provide GitHub token(s) directly. Supports comma-separated multi-token format: "
+ 'name:type:token (e.g. "personal:individual:ghu_aaa,work:business:ghu_bbb")',
},
"claude-code": {
alias: "c",
type: "boolean",
default: false,
description:
"Generate a command to launch Claude Code with Copilot API config",
},
"show-token": {
type: "boolean",
default: false,
description: "Show GitHub and Copilot tokens on fetch and refresh",
},
"proxy-env": {
type: "boolean",
default: false,
description: "Initialize proxy from environment variables",
},
"db-path": {
type: "string",
default: PATHS.USAGE_DB_PATH,
description:
"Path to the usage SQLite database (defaults to ~/.local/share/copilot-api/usage.sqlite)",
},
"accounts-file": {
type: "string",
description:
"Path to a JSON file containing multiple GitHub Copilot accounts",
},
strategy: {
type: "string",
default: "round-robin",
description:
"Account selection strategy: round-robin | least-busy | least-recent",
},
"pricing-sync-model": {
type: "string",
description:
"Model to use for LLM-powered pricing sync (default: auto-select from whitelist)",
},
"pricing-sync-interval-days": {
type: "string",
default: "7",
description: "How often (in days) to re-sync model pricing",
},
"pricing-sync-disabled": {
type: "boolean",
default: false,
description: "Disable automatic background pricing sync",
},
"record-requests": {
type: "boolean",
default: false,
description: "Enable recording of HTTP requests and responses to disk",
},
"record-dir": {
type: "string",
default: PATHS.RECORD_DIR,
description:
"Directory for recorded request data (default: ~/.local/share/copilot-api/logs)",
},
"record-parts": {
type: "string",
default: "req-header,req-body,res-header,res-body",
description:
"Comma-separated parts to record: req-header, req-body, res-header, res-body",
},
},
run({ args }) {
const rateLimitRaw = args["rate-limit"]
const rateLimit =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
rateLimitRaw === undefined ? undefined : Number.parseInt(rateLimitRaw, 10)
return runServer({
port: Number.parseInt(args.port, 10),
verbose: args.verbose,
accountType: args["account-type"],
manual: args.manual,
rateLimit,
rateLimitWait: args.wait,
githubToken: normalizeGithubToken(args["github-token"]),
claudeCode: args["claude-code"],
showToken: args["show-token"],
proxyEnv: args["proxy-env"],
dbPath: args["db-path"],
accountsFile: args["accounts-file"],
strategy: args.strategy as Strategy,
pricingSyncModel: args["pricing-sync-model"],
pricingSyncIntervalDays: Number.parseInt(
args["pricing-sync-interval-days"],
10,
),
pricingSyncDisabled: args["pricing-sync-disabled"],
recordRequests: args["record-requests"],
recordDir: args["record-dir"],
recordParts: args["record-parts"],
})
},
})