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
328 lines (296 loc) · 8.93 KB
/
start.ts
File metadata and controls
328 lines (296 loc) · 8.93 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
#!/usr/bin/env node
import { defineCommand } from "citty"
import clipboard from "clipboardy"
import consola from "consola"
import { serve, type ServerHandler, type ServerOptions } from "srvx"
import invariant from "tiny-invariant"
import { parseBackendId } from "./lib/backend"
import { initializeDashboardStore } from "./lib/dashboard-store"
import {
configureRuntimeLogger,
parseLogLevel,
type RuntimeLogLevel,
RUNTIME_LOG_LEVELS,
resolveRuntimeLogLevel,
} from "./lib/logger"
import { ensureOpenAIOAuth } from "./lib/openai-oauth"
import { ensurePaths } from "./lib/paths"
import { initProxyFromEnv } from "./lib/proxy"
import { generateEnvScript } from "./lib/shell"
import { state } from "./lib/state"
import { setupCopilotToken, setupGitHubToken } from "./lib/token"
import { cacheModels, cacheVSCodeVersion } from "./lib/utils"
import { server } from "./server"
interface RunServerOptions {
port: number
idleTimeout: number
verbose: boolean
logLevel?: RuntimeLogLevel
backend: string
accountType: string
manual: boolean
rateLimit?: number
rateLimitWait: boolean
githubToken?: string
claudeCode: boolean
showToken: boolean
proxyEnv: boolean
captureExchanges: boolean
ephemeralTelemetry: boolean
capturePath?: string
}
export const DEFAULT_IDLE_TIMEOUT_SECONDS = 255
export const MAX_IDLE_TIMEOUT_SECONDS = 255
export function parseIdleTimeoutSeconds(value: string): number {
const idleTimeout = Number(value)
if (
!Number.isInteger(idleTimeout)
|| idleTimeout < 0
|| idleTimeout > MAX_IDLE_TIMEOUT_SECONDS
) {
throw new Error(
`--idle-timeout must be an integer between 0 and ${MAX_IDLE_TIMEOUT_SECONDS} seconds`,
)
}
return idleTimeout
}
export function createServeOptions({
port,
idleTimeout,
}: Pick<RunServerOptions, "port" | "idleTimeout">): ServerOptions {
return {
fetch: server.fetch as ServerHandler,
port,
bun: {
idleTimeout,
},
}
}
export function resolveTelemetryStorageMode(options: {
captureExchanges: boolean
ephemeralTelemetry: boolean
}): "file" | "memory" {
if (options.captureExchanges && options.ephemeralTelemetry) {
throw new Error("--ephemeral cannot be used with --capture")
}
return options.ephemeralTelemetry ? "memory" : "file"
}
export async function runServer(options: RunServerOptions): Promise<void> {
configureRuntimeLogger(
resolveRuntimeLogLevel({
verbose: options.verbose,
logLevel: options.logLevel,
}),
)
if (options.proxyEnv) {
initProxyFromEnv()
}
const telemetryStorageMode = resolveTelemetryStorageMode({
captureExchanges: options.captureExchanges,
ephemeralTelemetry: options.ephemeralTelemetry,
})
state.backend = parseBackendId(options.backend)
state.accountType = options.accountType
if (state.backend === "copilot" && 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
state.captureExchanges = options.captureExchanges
state.ephemeralTelemetry = telemetryStorageMode === "memory"
state.capturePath = options.captureExchanges ? options.capturePath : undefined
if (state.ephemeralTelemetry) {
consola.info("Dashboard telemetry storage=memory (ephemeral)")
} else {
consola.info("Dashboard telemetry storage=file")
}
if (options.captureExchanges) {
consola.info(
`Proxy exchange capture enabled${options.capturePath ? ` -> ${options.capturePath}` : ""}`,
)
}
await ensurePaths()
await initializeDashboardStore()
await cacheVSCodeVersion()
if (state.backend === "copilot") {
if (options.githubToken) {
state.githubToken = options.githubToken
consola.info("Using provided GitHub token")
} else {
await setupGitHubToken()
}
await setupCopilotToken()
} else {
await ensureOpenAIOAuth()
}
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) {
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)
}
}
consola.info(`dashboard=${serverUrl}/dashboard`)
serve(createServeOptions(options))
}
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",
},
"idle-timeout": {
type: "string",
default: String(DEFAULT_IDLE_TIMEOUT_SECONDS),
description:
"HTTP idle timeout in seconds for Bun. Must be 0-255. Use 0 to disable for long-running requests",
},
verbose: {
alias: "v",
type: "boolean",
default: false,
description: "Enable verbose logging",
},
"log-level": {
type: "string",
description: `Set runtime log verbosity (${RUNTIME_LOG_LEVELS.join(", ")}). Overrides --verbose`,
},
"account-type": {
alias: "a",
type: "string",
default: "individual",
description: "Account type to use (individual, business, enterprise)",
},
backend: {
type: "string",
default: "copilot",
description: "Upstream backend to use (copilot, openai-oauth)",
},
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 directly (must be generated using the `auth` subcommand)",
},
"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",
},
capture: {
type: "boolean",
default: false,
description: "Persist proxied request and response exchanges to disk",
},
ephemeral: {
type: "boolean",
default: false,
description:
"Keep dashboard telemetry in memory for this run only. Conflicts with --capture",
},
"capture-path": {
type: "string",
description: "Path to the JSONL file used for exchange capture",
},
},
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)
const logLevel =
args["log-level"] ? parseLogLevel(args["log-level"]) : undefined
return runServer({
port: Number.parseInt(args.port, 10),
idleTimeout: parseIdleTimeoutSeconds(args["idle-timeout"]),
verbose: args.verbose,
logLevel,
backend: args.backend,
accountType: args["account-type"],
manual: args.manual,
rateLimit,
rateLimitWait: args.wait,
githubToken: args["github-token"],
claudeCode: args["claude-code"],
showToken: args["show-token"],
proxyEnv: args["proxy-env"],
captureExchanges: args.capture,
ephemeralTelemetry: args.ephemeral,
capturePath: args["capture-path"],
})
},
})