File size: 24,707 Bytes
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8c220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8c220
476094d
 
 
4b8c220
 
476094d
4b8c220
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8c220
 
 
 
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8c220
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8c220
 
 
 
 
476094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#!/usr/bin/env node

import { spawn } from "node:child_process";
import http from "node:http";
import path from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";

import { ApiEndpointPool, normalizeEndpointType } from "../proxy/api-endpoint-pool.mjs";
import { classifyFailure } from "../proxy/codex-account-pool.mjs";
import { sanitizeForLogs } from "../shared/secret-sanitizer.mjs";

const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_PORT = 8789;
const DEFAULT_PROVIDER = "codex";
const DEFAULT_POOL_DIR = path.resolve(process.cwd(), "api_pool", DEFAULT_PROVIDER);
const DEFAULT_LOCAL_API_KEY = "local-api-pool-proxy-key";
const DEFAULT_MAX_SWITCH_ATTEMPTS = 3;
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
const DEFAULT_ENABLE_SCHEDULED_SWITCH = true;
const DEFAULT_SCHEDULED_SWITCH_INTERVAL_MS = 15 * 60_000;

const SUPPORTED_PATHS = {
  codex: new Set(["/models", "/responses", "/v1/models", "/v1/responses", "/v1/chat/completions"]),
  "claude-code": new Set(["/v1/messages", "/messages", "/v1/models"]),
};

function parseArgs(argv) {
  const args = {};
  for (const part of argv) {
    if (!part.startsWith("--")) continue;
    const raw = part.slice(2);
    const idx = raw.indexOf("=");
    if (idx < 0) {
      args[raw] = "true";
      continue;
    }
    args[raw.slice(0, idx)] = raw.slice(idx + 1);
  }
  return args;
}

function printUsage() {
  console.log(`Usage:
  node src/scripts/api-pool-proxy.mjs

Options:
  --provider=codex
  --pool-dir=api_pool/codex
  --host=127.0.0.1
  --port=8789
  --local-api-key=local-api-pool-proxy-key
  --max-switch-attempts=3
  --request-timeout-ms=60000
  --enable-scheduled-switch=true
  --scheduled-switch-interval-ms=900000
  --proxy-url=http://127.0.0.1:8118
  --help
`);
}

function parseBooleanish(value, fallback) {
  if (value == null || value === "") return fallback;
  if (typeof value === "boolean") return value;
  const text = String(value).trim().toLowerCase();
  if (["true", "1", "yes", "on"].includes(text)) return true;
  if (["false", "0", "no", "off"].includes(text)) return false;
  return fallback;
}

async function maybeRespawnWithProxy(argv) {
  const args = parseArgs(argv);
  const proxyUrl = args["proxy-url"] || "";
  if (!proxyUrl || process.env.CODEX_PROXY_BOOTSTRAPPED === "1") {
    return false;
  }

  const child = spawn(process.execPath, [process.argv[1], ...argv], {
    stdio: "inherit",
    env: {
      ...process.env,
      CODEX_PROXY_BOOTSTRAPPED: "1",
      NODE_USE_ENV_PROXY: "1",
      HTTPS_PROXY: proxyUrl,
      HTTP_PROXY: proxyUrl,
      ALL_PROXY: proxyUrl,
    },
  });

  await new Promise((resolve, reject) => {
    child.on("exit", (code) => {
      process.exitCode = code ?? 1;
      resolve();
    });
    child.on("error", reject);
  });
  return true;
}

function safeJson(value) {
  return JSON.stringify(value, null, 2);
}

function getRequestPath(url = "/") {
  try {
    return new URL(url, "http://localhost").pathname;
  } catch {
    return "/";
  }
}

function requireLocalAuth(req, expectedKey) {
  return String(req.headers.authorization || "") === `Bearer ${expectedKey}`;
}

function copyHeadersToClient(res, upstreamHeaders) {
  for (const [key, value] of upstreamHeaders.entries()) {
    if (key.toLowerCase() === "transfer-encoding") continue;
    res.setHeader(key, value);
  }
}

function copyHeadersForUpstream(reqHeaders, apiKey, provider) {
  const headers = {};
  for (const [key, value] of Object.entries(reqHeaders || {})) {
    if (value == null) continue;
    const lower = key.toLowerCase();
    if (["host", "authorization", "content-length", "connection", "x-api-key"].includes(lower)) {
      continue;
    }
    headers[key] = value;
  }

  if (provider === "claude-code") {
    headers["x-api-key"] = apiKey;
    headers.authorization = `Bearer ${apiKey}`;
    if (!headers["anthropic-version"]) {
      headers["anthropic-version"] = "2023-06-01";
    }
  } else {
    headers.authorization = `Bearer ${apiKey}`;
  }
  return headers;
}

function readRequestBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on("data", (chunk) => chunks.push(chunk));
    req.on("error", reject);
    req.on("end", () => resolve(Buffer.concat(chunks)));
  });
}

function classifyRetryableFailure(status, detail) {
  const result = classifyFailure({ status, detail });
  return {
    ...result,
    retryable:
      ["auth", "rate_limit", "quota", "server", "network"].includes(result.category) ||
      (result.category === "invalid" && isRetryableInvalidDetail(detail)),
  };
}

function isRetryableInvalidDetail(detail) {
  const lower = String(detail || "").toLowerCase();
  return [
    "model_not_found",
    "no available channel for model",
    "unsupported model",
    "model not found",
    "invalid model",
    "does not support",
  ].some((needle) => lower.includes(needle));
}

export function endpointSummary(endpoint) {
  if (!endpoint) return null;
  return {
    id: endpoint.id,
    name: endpoint.name,
    type: endpoint.type,
    baseUrl: endpoint.baseUrl,
    model: endpoint.model || "",
    healthy: endpoint.healthy,
    cooldownUntil: endpoint.cooldownUntilMs ? new Date(endpoint.cooldownUntilMs).toISOString() : null,
    lastValidation: endpoint.lastValidation,
    lastFailureReason: endpoint.lastFailureReason,
  };
}

function createConsoleStartupLogger() {
  return (event, payload = {}) => {
    const time = new Date().toISOString();
    const sanitized = sanitizeForLogs(payload);
    const details = Object.entries(sanitized)
      .filter(([, value]) => value !== undefined && value !== null && value !== "")
      .map(([key, value]) => `${key}=${JSON.stringify(value)}`)
      .join(" ");
    console.log(`[startup] ${time} ${event}${details ? ` ${details}` : ""}`);
  };
}

function resolveUpstreamUrl(baseUrl, reqUrl, requestPath) {
  const upstream = new URL(baseUrl);
  const requestUrl = new URL(reqUrl || "/", "http://localhost");
  const basePath = upstream.pathname.replace(/\/+$/, "");
  const incomingPath = requestPath;
  let finalPath = incomingPath;

  if (basePath && basePath !== "/" && incomingPath.startsWith(`${basePath}/`)) {
    finalPath = incomingPath;
  } else if (basePath === "/v1" && incomingPath.startsWith("/v1/")) {
    finalPath = incomingPath;
  } else if (basePath && basePath !== "/" && incomingPath.startsWith("/")) {
    finalPath = `${basePath}${incomingPath}`;
  }

  upstream.pathname = finalPath;
  upstream.search = requestUrl.search;
  return upstream.toString();
}

async function createFetchWithProxy(proxyUrl) {
  if (!proxyUrl) return fetch;
  process.env.NODE_USE_ENV_PROXY = "1";
  process.env.HTTPS_PROXY = proxyUrl;
  process.env.HTTP_PROXY = proxyUrl;
  process.env.ALL_PROXY = proxyUrl;
  return fetch;
}

function unauthorized(res) {
  res.statusCode = 401;
  res.setHeader("content-type", "application/json");
  res.end(safeJson({ error: { message: "Unauthorized local proxy key." } }));
}

export async function createApiPoolProxyService(options) {
  const startupLogger =
    typeof options.logger === "function" ? options.logger : createConsoleStartupLogger();
  const fetchFn = options.fetchFn || (await createFetchWithProxy(options.proxyUrl));
  const pool = new ApiEndpointPool({
    poolDir: options.poolDir,
    provider: options.provider,
    fetchFn,
    logger: startupLogger,
    loadSnapshot: options.loadSnapshot,
    sourcePath: options.sourcePath,
  });

  startupLogger("pool:load:start", {
    provider: options.provider,
    poolDir: options.poolDir,
  });
  await pool.load();
  startupLogger("pool:load:done", { count: pool.listEndpoints().length });
  const active = await pool.getInitialEndpoint();
  if (!active) {
    throw new Error(`No usable endpoint for provider=${options.provider}`);
  }

  const scheduledSwitchEnabled = parseBooleanish(
    options.enableScheduledSwitch,
    DEFAULT_ENABLE_SCHEDULED_SWITCH,
  );
  const scheduledSwitchIntervalMs = Math.max(
    1_000,
    Number(options.scheduledSwitchIntervalMs || DEFAULT_SCHEDULED_SWITCH_INTERVAL_MS),
  );
  const scheduleState = {
    inflightRequests: 0,
    lastScheduledSwitchAt: null,
    nextScheduledSwitchAt: scheduledSwitchEnabled
      ? new Date(Date.now() + scheduledSwitchIntervalMs).toISOString()
      : null,
    lastScheduledSwitchReason: scheduledSwitchEnabled ? "waiting" : "disabled",
    pendingScheduledSwitch: false,
    timer: null,
    closed: false,
  };

  function clearScheduledTimer() {
    if (scheduleState.timer) {
      clearTimeout(scheduleState.timer);
      scheduleState.timer = null;
    }
  }

  function scheduleNextSwitch(delayMs = scheduledSwitchIntervalMs) {
    clearScheduledTimer();
    if (!scheduledSwitchEnabled || scheduleState.closed) {
      scheduleState.nextScheduledSwitchAt = null;
      return;
    }
    scheduleState.nextScheduledSwitchAt = new Date(Date.now() + delayMs).toISOString();
    scheduleState.timer = setTimeout(() => {
      void runScheduledSwitch("timer");
    }, delayMs);
    scheduleState.timer.unref?.();
  }

  async function runScheduledSwitch(trigger = "timer") {
    if (!scheduledSwitchEnabled || scheduleState.closed) {
      scheduleState.lastScheduledSwitchReason = "disabled";
      scheduleState.nextScheduledSwitchAt = null;
      return { switched: false, reason: "disabled" };
    }

    if (scheduleState.inflightRequests > 0) {
      scheduleState.pendingScheduledSwitch = true;
      scheduleState.lastScheduledSwitchReason = "busy";
      scheduleState.nextScheduledSwitchAt = null;
      startupLogger("scheduled-switch:defer", {
        provider: options.provider,
        trigger,
        inflightRequests: scheduleState.inflightRequests,
      });
      return { switched: false, reason: "busy" };
    }

    const currentActive = pool.getActiveEndpoint();
    if (!currentActive) {
      scheduleState.lastScheduledSwitchReason = "no-active";
      scheduleState.pendingScheduledSwitch = false;
      scheduleNextSwitch();
      return { switched: false, reason: "no-active" };
    }

    const excluded = new Set([currentActive.id]);
    for (let attempt = 0; attempt < pool.listEndpoints().length; attempt += 1) {
      const candidate = pool.pickNextRotationCandidate(excluded);
      if (!candidate) {
        scheduleState.lastScheduledSwitchReason = "no-healthy-spare";
        scheduleState.pendingScheduledSwitch = false;
        scheduleNextSwitch();
        startupLogger("scheduled-switch:skip", {
          provider: options.provider,
          trigger,
          reason: "no-healthy-spare",
        });
        return { switched: false, reason: "no-healthy-spare" };
      }
      excluded.add(candidate.id);

      const probe = await pool.probeEndpoint(candidate, {
        activateOnSuccess: false,
        activationMode: "scheduled",
      });
      if (!probe.ok) {
        continue;
      }

      pool.markScheduledSwitch(candidate);
      scheduleState.lastScheduledSwitchAt = new Date().toISOString();
      scheduleState.lastScheduledSwitchReason = "switched";
      scheduleState.pendingScheduledSwitch = false;
      scheduleNextSwitch();
      startupLogger("scheduled-switch:done", {
        provider: options.provider,
        trigger,
        previousId: currentActive.id,
        nextId: candidate.id,
        nextName: candidate.name,
      });
      return { switched: true, reason: "switched", endpoint: candidate };
    }

    scheduleState.lastScheduledSwitchReason = "no-healthy-spare";
    scheduleState.pendingScheduledSwitch = false;
    scheduleNextSwitch();
    return { switched: false, reason: "no-healthy-spare" };
  }

  function attachInflightTracker(res) {
    scheduleState.inflightRequests += 1;
    let done = false;
    const finish = () => {
      if (done) return;
      done = true;
      scheduleState.inflightRequests = Math.max(0, scheduleState.inflightRequests - 1);
      if (scheduleState.inflightRequests === 0 && scheduleState.pendingScheduledSwitch) {
        queueMicrotask(() => {
          void runScheduledSwitch("idle-drain");
        });
      }
    };
    res.once("finish", finish);
    res.once("close", finish);
  }

  scheduleNextSwitch();

  async function reload() {
    await pool.load();
    const nextActive = await pool.getInitialEndpoint();
    if (!nextActive) {
      throw new Error(`No usable endpoint for provider=${options.provider}`);
    }
    scheduleState.pendingScheduledSwitch = false;
    scheduleState.lastScheduledSwitchReason = scheduledSwitchEnabled ? "reloaded" : "disabled";
    scheduleNextSwitch();
    return nextActive;
  }

  function getAdminStatus() {
    return {
      provider: options.provider,
      active: endpointSummary(pool.getActiveEndpoint()),
      endpoints: pool.listEndpoints().map(endpointSummary),
      inflightRequests: scheduleState.inflightRequests,
      lastScheduledSwitchAt: scheduleState.lastScheduledSwitchAt,
      nextScheduledSwitchAt: scheduleState.nextScheduledSwitchAt,
      scheduledSwitchEnabled,
      scheduledSwitchIntervalMs,
      lastScheduledSwitchReason: scheduleState.lastScheduledSwitchReason,
    };
  }

  function close() {
    scheduleState.closed = true;
    clearScheduledTimer();
  }

  function promoteNextEndpointAfterFailure(
    failedEndpoint,
    { expectedId = null, expectedVersion = null, excluded = new Set() } = {},
  ) {
    const currentActive = pool.getActiveEndpoint();
    if (!failedEndpoint || !currentActive || currentActive.id !== failedEndpoint.id) {
      return null;
    }

    const localExcluded = new Set(excluded);
    localExcluded.add(failedEndpoint.id);
    const candidate = pool.pickNextHealthyEndpoint(localExcluded);
    if (!candidate) {
      return null;
    }

    const activated = pool.setActiveEndpoint(candidate, "failover", {
      expectedId,
      expectedVersion,
    });
    return activated ? candidate : null;
  }

  async function handleRequest(
    req,
    res,
    { requestUrl = req.url, exposeHealthDetails = true, exposeStatus = true } = {},
  ) {
    const requestPath = getRequestPath(requestUrl);

    if (requestPath === "/healthz") {
      res.statusCode = 200;
      res.setHeader("content-type", "application/json");
      res.end(
        safeJson(
          exposeHealthDetails
            ? {
                ok: true,
                provider: options.provider,
                active: endpointSummary(pool.getActiveEndpoint()),
              }
            : { ok: true },
        ),
      );
      return;
    }

    if (requestPath === "/proxy/status" && exposeStatus) {
      res.statusCode = 200;
      res.setHeader("content-type", "application/json");
      res.end(safeJson(getAdminStatus()));
      return;
    }

    if (!requireLocalAuth(req, options.localApiKey)) {
      unauthorized(res);
      return;
    }

    const supported = SUPPORTED_PATHS[options.provider] || new Set();
    if (!supported.has(requestPath)) {
      res.statusCode = 404;
      res.setHeader("content-type", "application/json");
      res.end(
        safeJson({
          error: {
            message: `Unsupported path: ${requestPath}. Supported: ${[...supported].join(", ")}`,
          },
        }),
      );
      return;
    }

    const requestBody =
      req.method === "GET" || req.method === "HEAD" ? null : await readRequestBody(req);
    attachInflightTracker(res);

    const excluded = new Set();
    const maxAttempts = Math.max(1, Number(options.maxSwitchAttempts) + 1);
    let lastFailure = null;
    let nextCandidate = null;

    for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
      const current =
        nextCandidate ||
        (attempt === 0
          ? pool.getActiveEndpoint() || (await pool.getInitialEndpoint())
          : pool.pickNextHealthyEndpoint(excluded));
      nextCandidate = null;
      if (!current) break;
      excluded.add(current.id);
      if (pool.isCoolingDown(current)) continue;
      const selectedActiveId = pool.getActiveEndpoint()?.id || null;
      const selectedActiveVersion = pool.getActiveEndpointVersion();

      try {
        const upstreamUrl = resolveUpstreamUrl(current.baseUrl, requestUrl, requestPath);
        const headers = copyHeadersForUpstream(req.headers, current.apiKey, current.type);
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), options.requestTimeoutMs);

        let upstream;
        try {
          upstream = await fetchFn(upstreamUrl, {
            method: req.method,
            headers,
            body: requestBody,
            signal: controller.signal,
          });
        } finally {
          clearTimeout(timeout);
        }

        if (!upstream.ok) {
          const detail = await upstream.text();
          const classified = classifyRetryableFailure(upstream.status, detail);
          pool.markFailure(current, classified.category, detail || classified.reason);
          lastFailure = {
            status: upstream.status,
            category: classified.category,
            reason: detail || classified.reason,
          };
          if (classified.retryable) {
            nextCandidate = promoteNextEndpointAfterFailure(current, {
              expectedId: selectedActiveId,
              expectedVersion: selectedActiveVersion,
              excluded,
            });
            continue;
          }
          res.statusCode = upstream.status;
          res.setHeader("content-type", "application/json");
          res.end(
            safeJson({
              error: {
                message: detail || "Upstream request failed.",
                category: classified.category,
              },
            }),
          );
          return;
        }

        res.statusCode = upstream.status;
        copyHeadersToClient(res, upstream.headers);
        if (!upstream.body) {
          const activated = pool.markSuccess(current, {
            expectedId: selectedActiveId,
            expectedVersion: selectedActiveVersion,
          });
          if (!activated) {
            startupLogger("pool:active-endpoint:stale-success", {
              provider: options.provider,
              requestPath,
              endpointId: current.id,
              endpointName: current.name,
              selectedActiveId,
              selectedActiveVersion,
              currentActiveId: pool.getActiveEndpoint()?.id || null,
              currentActiveVersion: pool.getActiveEndpointVersion(),
              message: `忽略旧请求成功回写:请求开始时活跃节点=${selectedActiveId || "none"}@v${selectedActiveVersion},当前活跃节点=${pool.getActiveEndpoint()?.id || "none"}@v${pool.getActiveEndpointVersion()},成功节点=${current.id}`,
            });
          }
          res.end();
          return;
        }

        try {
          await pipeline(Readable.fromWeb(upstream.body), res);
        } catch (error) {
          const detail = error?.message || String(error);
          const classified = classifyRetryableFailure(0, detail);
          pool.markFailure(current, classified.category, detail);
          lastFailure = {
            status: 0,
            category: classified.category,
            reason: detail,
          };
          promoteNextEndpointAfterFailure(current, {
            expectedId: selectedActiveId,
            expectedVersion: selectedActiveVersion,
            excluded,
          });
          if (!res.destroyed) {
            res.destroy(error);
          }
          return;
        }

        const activated = pool.markSuccess(current, {
          expectedId: selectedActiveId,
          expectedVersion: selectedActiveVersion,
        });
        if (!activated) {
          startupLogger("pool:active-endpoint:stale-success", {
            provider: options.provider,
            requestPath,
            endpointId: current.id,
            endpointName: current.name,
            selectedActiveId,
            selectedActiveVersion,
            currentActiveId: pool.getActiveEndpoint()?.id || null,
            currentActiveVersion: pool.getActiveEndpointVersion(),
            message: `忽略旧请求成功回写:请求开始时活跃节点=${selectedActiveId || "none"}@v${selectedActiveVersion},当前活跃节点=${pool.getActiveEndpoint()?.id || "none"}@v${pool.getActiveEndpointVersion()},成功节点=${current.id}`,
          });
        }
        return;
      } catch (error) {
        const detail = error?.message || String(error);
        const classified = classifyRetryableFailure(0, detail);
        pool.markFailure(current, classified.category, detail);
        lastFailure = {
          status: 0,
          category: classified.category,
          reason: detail,
        };
        nextCandidate = promoteNextEndpointAfterFailure(current, {
          expectedId: selectedActiveId,
          expectedVersion: selectedActiveVersion,
          excluded,
        });
      }
    }

    res.statusCode = 503;
    res.setHeader("content-type", "application/json");
    res.end(
      safeJson({
        error: {
          message: "No healthy endpoint available.",
          lastFailure,
        },
      }),
    );
  }

  return {
    pool,
    handleRequest,
    reload,
    getAdminStatus,
    runScheduledSwitchNow: () => runScheduledSwitch("manual"),
    close,
  };
}

export async function createApiPoolProxyServer(options) {
  const service = await createApiPoolProxyService(options);
  const server = http.createServer((req, res) =>
    service.handleRequest(req, res, {
      exposeHealthDetails: true,
      exposeStatus: true,
    }),
  );
  const originalClose = server.close.bind(server);
  server.close = (callback) => {
    service.close?.();
    return originalClose(callback);
  };

  return { server, pool: service.pool, service };
}

async function main() {
  if (await maybeRespawnWithProxy(process.argv.slice(2))) {
    return;
  }

  const args = parseArgs(process.argv.slice(2));
  if (args.help === "true") {
    printUsage();
    return;
  }

  const provider = normalizeEndpointType(
    args.provider || process.env.API_POOL_PROVIDER || DEFAULT_PROVIDER,
  );
  if (!provider) {
    throw new Error("provider must be codex or claude-code");
  }

  const defaultPoolDir = path.resolve(process.cwd(), "api_pool", provider);
  const options = {
    provider,
    poolDir: path.resolve(args["pool-dir"] || process.env.API_POOL_DIR || defaultPoolDir || DEFAULT_POOL_DIR),
    host: args.host || process.env.API_POOL_HOST || DEFAULT_HOST,
    port: Number(args.port || process.env.API_POOL_PORT || DEFAULT_PORT),
    localApiKey: args["local-api-key"] || process.env.API_POOL_LOCAL_API_KEY || DEFAULT_LOCAL_API_KEY,
    maxSwitchAttempts: Number(
      args["max-switch-attempts"] || process.env.API_POOL_MAX_SWITCH_ATTEMPTS || DEFAULT_MAX_SWITCH_ATTEMPTS,
    ),
    requestTimeoutMs: Number(
      args["request-timeout-ms"] || process.env.API_POOL_REQUEST_TIMEOUT_MS || DEFAULT_REQUEST_TIMEOUT_MS,
    ),
    enableScheduledSwitch: parseBooleanish(
      args["enable-scheduled-switch"] ?? process.env.API_POOL_SCHEDULED_SWITCH_ENABLED,
      DEFAULT_ENABLE_SCHEDULED_SWITCH,
    ),
    scheduledSwitchIntervalMs: Number(
      args["scheduled-switch-interval-ms"] ||
        process.env.API_POOL_SCHEDULED_SWITCH_INTERVAL_MS ||
        DEFAULT_SCHEDULED_SWITCH_INTERVAL_MS,
    ),
    proxyUrl:
      args["proxy-url"] ||
      process.env.API_POOL_PROXY_URL ||
      process.env.HTTPS_PROXY ||
      process.env.HTTP_PROXY ||
      "",
  };

  console.log("[startup] preparing api pool proxy");
  console.log(`[startup] provider=${options.provider}`);
  console.log(`[startup] host=${options.host} port=${options.port}`);
  console.log(`[startup] poolDir=${options.poolDir}`);
  console.log(`[startup] scheduledSwitch=${options.enableScheduledSwitch ? "on" : "off"}`);
  console.log(`[startup] scheduledSwitchIntervalMs=${options.scheduledSwitchIntervalMs}`);
  console.log(`[startup] upstreamProxy=${options.proxyUrl || "(none)"}`);

  const { server, pool } = await createApiPoolProxyServer(options);
  server.listen(options.port, options.host, () => {
    const active = pool.getActiveEndpoint();
    console.log(`API 池代理已启动:http://${options.host}:${options.port}`);
    console.log(`Provider: ${options.provider}`);
    console.log(`初始活跃节点:${active?.name || active?.id || "(none)"}`);
  });
}

const directRun = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname);
if (directRun) {
  main().catch((error) => {
    console.error(error?.message || error);
    process.exitCode = 1;
  });
}