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
410 lines (375 loc) · 13 KB
/
start.ts
File metadata and controls
410 lines (375 loc) · 13 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/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 { purgeExpiredSessions } from "./admin/session"
import { logAuthModeBanner, resolveAuthMode } from "./lib/auth-mode"
import { runBootstrap } from "./lib/bootstrap"
import {
getConfig,
initConfig,
setRuntimeAuthOverride,
} from "./lib/config-store"
import { closeDb, getDb, initDb } from "./lib/db"
import { ensurePaths, PATHS } from "./lib/paths"
import { initProxyFromEnv } from "./lib/proxy"
import { generateEnvScript } from "./lib/shell"
import { state } from "./lib/state"
import { setupCopilotToken, setupGitHubToken, stopCopilotTokenRefresh } from "./lib/token"
import { cacheModels } from "./lib/utils"
import { server } from "./server"
import { audit, initAudit } from "./services/audit"
import { unseededLearnedBetaFlags } from "./services/copilot/create-messages-native"
import { sweepExpiredDebugKeys } from "./services/debug-ttl-sweeper"
import { getCopilotChatVersion } from "./services/get-copilot-chat-version"
import { getVSCodeVersion } from "./services/get-vscode-version"
import { startEventRetention } from "./services/retention"
import { startTraceRetention } from "./services/trace-retention"
interface RunServerOptions {
port: number
host: string
verbose: boolean
accountType: string
manual: boolean
rateLimit?: number
rateLimitWait: boolean
githubToken?: string
claudeCode: boolean
showToken: boolean
proxyEnv: boolean
noAuth: boolean
acceptRisk: boolean
}
/** Apply CLI options to mutable state and kick off version fetches. */
async function applyOptions(options: RunServerOptions): Promise<void> {
if (options.proxyEnv) initProxyFromEnv()
if (options.verbose) {
consola.level = 5
consola.info("Verbose logging enabled")
}
state.accountType = options.accountType
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()
;[state.vsCodeVersion, state.copilotChatVersion] = await Promise.all([
getVSCodeVersion(),
getCopilotChatVersion(),
])
consola.info(
`VS Code: ${state.vsCodeVersion} Copilot Chat: ${state.copilotChatVersion}`,
)
if (options.githubToken) {
state.githubToken = options.githubToken
consola.info("Using provided GitHub token")
} else {
await setupGitHubToken()
}
await setupCopilotToken()
await cacheModels()
}
/** Start the session + debug-TTL background sweepers. */
function startPeriodicSweepers(): void {
// Purge expired sessions on startup, then sweep hourly.
purgeExpiredSessions()
setInterval(
() => {
purgeExpiredSessions()
},
60 * 60 * 1000,
)
// Sweep expired debug keys on startup, then every 60 seconds.
// The interval is purely a cleanup; correctness gates use isDebugActive(row).
sweepExpiredDebugKeys()
setInterval(() => {
sweepExpiredDebugKeys()
}, 60 * 1000)
}
/** Install SIGINT/SIGTERM handlers that flush the DB before exit. */
function installShutdownHandlers(
stopFns: Array<(() => void) | undefined> = [],
): void {
const shutdown = (code: number): void => {
for (const stop of stopFns) {
try {
stop?.()
} catch {
// cancellation must not block shutdown
}
}
try {
closeDb(getDb())
} catch {
// db was never initialized or already closed — safe to ignore
}
process.exit(code)
}
process.on("SIGINT", () => {
shutdown(0)
})
process.on("SIGTERM", () => {
shutdown(0)
})
}
export async function runServer(options: RunServerOptions): Promise<void> {
// Load config FIRST so we can read features.auth before resolving auth mode.
// This also creates the config.json file with defaults on first run.
// initConfig() also installs an fs.watch on the parent dir so subsequent
// edits (Settings page POST or hand-edits) are picked up live without a
// restart — the dispose handle is wired into installShutdownHandlers below.
await ensurePaths()
const stopConfigWatcher = await initConfig((next) => {
consola.info(
`config.json reloaded (models=${Object.keys(next.models).length}, telemetry=${String(next.features.telemetry)}, debug=${String(next.features.debug)}, traces_days=${String(next.retention.traces_days)})`,
)
})
// Resolve auth mode — this throws before any HTTP/network side-effects if
// --no-auth (or config features.auth=false) is requested on a non-loopback
// host without acknowledgement.
const authMode = resolveAuthMode({
noAuth: options.noAuth,
acceptRisk: options.acceptRisk,
host: options.host,
port: options.port,
configAuth: getConfig().features.auth,
})
// Apply the runtime override ONLY when the operator explicitly opted out
// via --no-auth. Otherwise the config value is authoritative — the safety
// guard above has already validated the combination.
if (options.noAuth) {
setRuntimeAuthOverride(false)
}
state.authModeLabel = authMode.label
state.bindAddress = authMode.bindAddress
// Plain-HTTP bypass for admin WebUI — operator-acknowledged convenience for
// LAN-only self-hosted setups. Session cookies travel in the clear; never
// expose this server to the open internet with this flag on.
if (process.env.ADMIN_INSECURE_HTTP === "true") {
consola.warn(
"ADMIN_INSECURE_HTTP=true — admin WebUI HTTPS check disabled. "
+ "Session cookies are sent in the clear. LAN-only use ONLY; "
+ "never expose this port to the open internet.",
)
}
await applyOptions(options)
// Run DB migrations BEFORE binding HTTP listener (no schema race)
initDb()
// Initialize audit log — prunes old files beyond retention
initAudit()
// Start hourly events retention sweeper (issue #34).
// Cancel handle is stored on the shutdown hook so SIGINT/SIGTERM stops it.
const stopEventRetention = startEventRetention()
// Start hourly trace retention sweeper (issue #36).
const stopTraceRetention = startTraceRetention()
installShutdownHandlers([
stopEventRetention,
stopTraceRetention,
stopConfigWatcher,
stopCopilotTokenRefresh,
])
logAuthModeBanner(authMode)
// First-run admin bootstrap (no-op if auth disabled or keys exist)
runBootstrap()
startPeriodicSweepers()
// Emit audit event when starting without authentication, with bind context.
if (!getConfig().features.auth) {
audit({
actor_key_id: "__system__",
actor_tier: "system",
action: "server.start_no_auth",
after: {
bind_address: authMode.bindAddress,
auth_mode: authMode.label,
},
})
}
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.box(`🖥 Admin Web UI: ${serverUrl}/admin/`)
// If the auto-learn deny-list file contains flags NOT yet in the source
// seed, surface them loudly so a future dev knows to promote them via a
// code commit. File lives at
// ~/.local/share/copilot-api-pro/learned-unsupported-beta.txt
const unseeded = unseededLearnedBetaFlags()
if (unseeded.length > 0) {
consola.warn(
`[anthropic-beta] auto-learned ${unseeded.length} unsupported beta flag(s)\n`
+ ` not yet in source seed: ${unseeded.join(", ")}\n`
+ ` → see ${PATHS.LEARNED_BETA_PATH}\n`
+ ` → add to SEEDED_UNSUPPORTED_BETA in src/services/copilot/create-messages-native.ts`,
)
}
serve({
fetch: server.fetch as ServerHandler,
port: options.port,
hostname: options.host,
// Bun's default idleTimeout is 10 seconds — far too short for LLM
// streaming where the model can think for 30-120+ seconds before
// producing any output. During thinking, no data flows to the
// client and Bun kills the TCP connection. 255 is the Bun maximum
// (4 min 15 s); for truly extreme thinking durations a keepalive
// heartbeat would be needed on top of this.
bun: { idleTimeout: 255 },
})
}
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",
},
host: {
type: "string",
default: "127.0.0.1",
description:
"Bind hostname. Default 127.0.0.1 (loopback only). Use 0.0.0.0 or :: to expose to LAN — requires auth or --i-accept-account-suspension-risk.",
},
// citty interprets `--no-auth` as setting `auth=false` (the citty
// convention is `--no-X` toggles a boolean named `X`). We declare the
// positive form `auth` here with default `true`. The CLI flag exposed
// to the user remains `--no-auth`, but inside `args` we read `args.auth`.
auth: {
type: "boolean",
default: true,
description:
"Authentication. Pass --no-auth to DISABLE. Refused on non-loopback bind unless --i-accept-account-suspension-risk is also set.",
},
"i-accept-account-suspension-risk": {
type: "boolean",
default: false,
description:
"Acknowledge that running --no-auth on a non-loopback bind can burn Copilot quota and trigger GitHub abuse detection.",
},
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 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",
},
},
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),
host: args.host,
verbose: args.verbose,
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"],
noAuth: !args.auth,
acceptRisk: args["i-accept-account-suspension-risk"],
}).catch((err: unknown) => {
// Auth-mode safety guard throws before any side-effects; surface the
// message in red and exit with status 2 (distinguishes from other errors).
consola.error(`\x1B[31m${String(err)}\x1B[0m`)
process.exit(2)
})
},
})