tuxevil-rotator 3.7.0 → 3.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,23 @@ export interface FetchWithRetryOptions extends RequestInit {
15
15
  export type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
16
16
 
17
17
  export const DEFAULT_RETRY_STATUSES = [408, 429, 500, 502, 503, 504] as const;
18
+ export const DEFAULT_HEADERS_TIMEOUT_MS = 30_000;
19
+
20
+ /** Raised when an upstream accepts a request but never sends response headers. */
21
+ export class UpstreamHeadersTimeoutError extends Error {
22
+ readonly code = "UND_ERR_HEADERS_TIMEOUT";
23
+
24
+ constructor(timeoutMs: number) {
25
+ super(`upstream response headers timeout after ${timeoutMs}ms`);
26
+ this.name = "UpstreamHeadersTimeoutError";
27
+ }
28
+ }
29
+
30
+ export interface FetchWithHeadersTimeoutOptions extends RequestInit {
31
+ timeoutMs?: number;
32
+ fetchImpl?: typeof fetch;
33
+ dispatcher?: Dispatcher;
34
+ }
18
35
 
19
36
  export function isRetryableStatus(status: number, retryStatuses: readonly number[] = DEFAULT_RETRY_STATUSES): boolean {
20
37
  return retryStatuses.includes(status);
@@ -22,6 +39,7 @@ export function isRetryableStatus(status: number, retryStatuses: readonly number
22
39
 
23
40
  export function isRetryableFetchError(error: unknown): boolean {
24
41
  if (error instanceof DOMException && error.name === "AbortError") return true;
42
+ if (error instanceof UpstreamHeadersTimeoutError) return true;
25
43
  return error instanceof TypeError;
26
44
  }
27
45
 
@@ -47,6 +65,59 @@ function createTimeoutSignal(timeoutMs: number | undefined, inputSignal: AbortSi
47
65
  return AbortSignal.any([inputSignal, timeoutSignal]);
48
66
  }
49
67
 
68
+ /**
69
+ * Fetch a response while bounding only the time spent waiting for its headers.
70
+ * Once headers arrive, the caller owns the response body and its stream-level
71
+ * idle/backpressure guards continue to apply.
72
+ */
73
+ export async function fetchWithHeadersTimeout(
74
+ input: RequestInfo | URL,
75
+ options: FetchWithHeadersTimeoutOptions = {},
76
+ ): Promise<Response> {
77
+ const {
78
+ timeoutMs = DEFAULT_HEADERS_TIMEOUT_MS,
79
+ fetchImpl = fetch,
80
+ dispatcher,
81
+ signal: inputSignal,
82
+ ...init
83
+ } = options;
84
+
85
+ if (!timeoutMs || timeoutMs <= 0) {
86
+ return fetchImpl(input, {
87
+ ...init,
88
+ dispatcher,
89
+ signal: inputSignal,
90
+ } as RequestInitWithDispatcher);
91
+ }
92
+
93
+ const timeoutController = new AbortController();
94
+ let timedOut = false;
95
+ const timeout = setTimeout(() => {
96
+ timedOut = true;
97
+ timeoutController.abort();
98
+ }, timeoutMs);
99
+ const requestSignal = inputSignal
100
+ ? AbortSignal.any([inputSignal, timeoutController.signal])
101
+ : timeoutController.signal;
102
+
103
+ try {
104
+ return await fetchImpl(input, {
105
+ ...init,
106
+ dispatcher,
107
+ signal: requestSignal,
108
+ } as RequestInitWithDispatcher);
109
+ } catch (error) {
110
+ // A client cancellation must retain its original error and must not cause
111
+ // the rotator to retry work the client no longer wants.
112
+ if (timedOut && !inputSignal?.aborted) {
113
+ throw new UpstreamHeadersTimeoutError(timeoutMs);
114
+ }
115
+ throw error;
116
+ } finally {
117
+ clearTimeout(timeout);
118
+ }
119
+ }
120
+
50
121
  /**
51
122
  * Fetch wrapper for non-streaming calls. Retries only transport failures and explicit retryable statuses.
52
123
  * Do not use for streaming responses: retrying streams can duplicate upstream work.
@@ -14,6 +14,7 @@ import type { AccountConfig } from "../types.js";
14
14
  export interface TokenUsage {
15
15
  inputTokens: number;
16
16
  outputTokens: number;
17
+ cachedTokens?: number;
17
18
  }
18
19
 
19
20
  /**
@@ -130,6 +131,15 @@ export interface ProviderAdapter {
130
131
  /** Accumulator matching this provider's stream format. */
131
132
  createStreamAccumulator(): StreamAccumulator;
132
133
 
134
+ /** Provider-native minimal request used to start an idle quota timer. */
135
+ forwardKickstartRequest?(
136
+ account: AccountRuntime,
137
+ model: string,
138
+ signal?: AbortSignal,
139
+ ): Promise<ForwardedResponse>;
140
+ /** Drop provider-local quota cache after a state-changing kickstart. */
141
+ clearQuotaCache?(account: AccountRuntime): void;
142
+
133
143
  // --- Catalog / helpers ---
134
144
  /** Whether a model belongs to this provider. */
135
145
  ownsModel?(
@@ -104,10 +104,21 @@ export const PROVIDER_ORDER_RANK: Record<string, number> = {
104
104
  "openai-codex": 4,
105
105
  };
106
106
 
107
+ // Ollama Cloud currently exposes one account-wide usage pool. Keep the old
108
+ // names as aliases so persisted state and older API responses remain readable
109
+ // during the transition.
110
+ export const OLLAMA_QUOTA_POOL_KEY = "monthly";
111
+
112
+ export function isOllamaQuotaPoolKey(poolKey: string): boolean {
113
+ return poolKey === OLLAMA_QUOTA_POOL_KEY ||
114
+ poolKey === "session" ||
115
+ poolKey === "weekly";
116
+ }
117
+
107
118
  export function getProviderIdForPoolKey(poolKey: string): string {
108
119
  if (poolKey.startsWith("codex:") || poolKey.startsWith("openai-codex")) return "openai-codex";
109
120
  if (poolKey.startsWith("opencode-zen:") || poolKey === "opencode-zen") return "opencode-zen";
110
- if (poolKey === "session" || poolKey === "weekly") return "ollama";
121
+ if (isOllamaQuotaPoolKey(poolKey)) return "ollama";
111
122
  if (poolKey === "claude" || poolKey === "gemini") return "google-antigravity";
112
123
  if (PROVIDER_ORDER_RANK[poolKey] !== undefined) return poolKey;
113
124
  return DEFAULT_PROVIDER;
@@ -15,7 +15,10 @@ import { logger } from "../../logger.js";
15
15
  import type { TokenUsage } from "../adapter.js";
16
16
  import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
18
+ import {
19
+ fetchWithHeadersTimeout,
20
+ type RequestInitWithDispatcher,
21
+ } from "../../fetch-with-retry.js";
19
22
 
20
23
  const forwardLogger = logger.child("google-forward");
21
24
 
@@ -53,8 +56,18 @@ function findUsageInJson(
53
56
  : typeof usageMetadata.outputTokenCount === "number"
54
57
  ? usageMetadata.outputTokenCount
55
58
  : 0;
59
+ const cached =
60
+ typeof usageMetadata.cachedContentTokenCount === "number"
61
+ ? usageMetadata.cachedContentTokenCount
62
+ : typeof usageMetadata.cached_tokens === "number"
63
+ ? usageMetadata.cached_tokens
64
+ : undefined;
56
65
  if (input > 0 || output > 0)
57
- return { inputTokens: input, outputTokens: output };
66
+ return {
67
+ inputTokens: input,
68
+ outputTokens: output,
69
+ ...(cached !== undefined ? { cachedTokens: cached } : {}),
70
+ };
58
71
  }
59
72
  // OpenAI / Anthropic format
60
73
  const usage = value.usage;
@@ -71,8 +84,21 @@ function findUsageInJson(
71
84
  : typeof usage.output_tokens === "number"
72
85
  ? usage.output_tokens
73
86
  : 0;
87
+ const cached =
88
+ isRecord(usage.prompt_tokens_details) &&
89
+ typeof usage.prompt_tokens_details.cached_tokens === "number"
90
+ ? usage.prompt_tokens_details.cached_tokens
91
+ : typeof usage.cached_tokens === "number"
92
+ ? usage.cached_tokens
93
+ : typeof usage.cache_read_input_tokens === "number"
94
+ ? usage.cache_read_input_tokens
95
+ : undefined;
74
96
  if (input > 0 || output > 0)
75
- return { inputTokens: input, outputTokens: output };
97
+ return {
98
+ inputTokens: input,
99
+ outputTokens: output,
100
+ ...(cached !== undefined ? { cachedTokens: cached } : {}),
101
+ };
76
102
  }
77
103
  // Recurse into common nesting locations.
78
104
  for (const key of ["candidates", "output", "response", "message"]) {
@@ -381,7 +407,7 @@ export async function forwardRequest(
381
407
  ? AbortSignal.any([controller.signal, signal])
382
408
  : signal ?? controller?.signal;
383
409
 
384
- const response = await fetch(url, {
410
+ const response = await fetchWithHeadersTimeout(url, {
385
411
  method: "POST",
386
412
  headers: forwardHeaders,
387
413
  body: requestBody,
@@ -178,6 +178,7 @@ export interface CompatCompletion {
178
178
  thinkingText?: string; // Gemini thought blocks (thought: true), emitted as reasoning_content
179
179
  inputTokens: number;
180
180
  outputTokens: number;
181
+ cachedTokens?: number;
181
182
  firstByteMs?: number;
182
183
  responseId?: string;
183
184
  toolCalls?: OpenAIToolCall[];
@@ -1683,7 +1684,7 @@ export function responseUsageFromCompletion(
1683
1684
  ): Record<string, unknown> {
1684
1685
  return {
1685
1686
  input_tokens: completion.inputTokens,
1686
- input_tokens_details: { cached_tokens: 0 },
1687
+ input_tokens_details: { cached_tokens: completion.cachedTokens ?? 0 },
1687
1688
  output_tokens: completion.outputTokens,
1688
1689
  output_tokens_details: { reasoning_tokens: 0 },
1689
1690
  total_tokens: completion.inputTokens + completion.outputTokens,
@@ -18,7 +18,10 @@ import {
18
18
  } from "../google-antigravity/translators.js";
19
19
  import type { StreamAccumulator, TokenUsage } from "../adapter.js";
20
20
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
21
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
21
+ import {
22
+ fetchWithHeadersTimeout,
23
+ type RequestInitWithDispatcher,
24
+ } from "../../fetch-with-retry.js";
22
25
 
23
26
  const OLLAMA_BENCHMARK_MODEL = "gpt-oss:20b";
24
27
 
@@ -146,7 +149,7 @@ export async function forwardRequest(
146
149
  delete forwardHeaders["content-length"];
147
150
 
148
151
  const endpoint = OLLAMA_CHAT_ENDPOINTS[0] || "https://ollama.com/api/chat";
149
- const response = await fetch(endpoint, {
152
+ const response = await fetchWithHeadersTimeout(endpoint, {
150
153
  method: "POST",
151
154
  headers: forwardHeaders,
152
155
  body: requestBody,
@@ -1,7 +1,7 @@
1
1
  // Ollama Cloud provider adapter.
2
2
  //
3
3
  // Implements the ProviderAdapter contract for Ollama Cloud (ollama.com):
4
- // static API keys, NDJSON `/api/chat` forwarding, and session/weekly
4
+ // static API keys, NDJSON `/api/chat` forwarding, and monthly
5
5
  // usage-fraction quota pools with exhaustion prediction.
6
6
  //
7
7
  // Ported from the ollama-rotator project (same author) into the
@@ -18,6 +18,7 @@ import { runLogin } from "./login.js";
18
18
  import { getOllamaApiKey, validateCredentials } from "./credentials.js";
19
19
  import { UsagePredictor, type ExhaustionPrediction } from "./prediction.js";
20
20
  import type { AccountRuntime } from "../../types.js";
21
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
21
22
 
22
23
  const OLLAMA_TIER_RANKING = {
23
24
  max: 0,
@@ -75,7 +76,8 @@ export const ollamaAdapter: ProviderAdapter = {
75
76
  createStreamAccumulator: () => new OllamaNdjsonAccumulator(),
76
77
 
77
78
  getKickstartModelForPool(quotaModelKey: string): string | undefined {
78
- // Only the session pool can be kickstarted for Ollama accounts.
79
+ // The current monthly pool has no idle timer to start. Keep the legacy
80
+ // session path for operators upgrading from the old API shape.
79
81
  return quotaModelKey === "session" ? OLLAMA_KICKSTART_MODEL : undefined;
80
82
  },
81
83
 
@@ -85,7 +87,7 @@ export const ollamaAdapter: ProviderAdapter = {
85
87
  },
86
88
 
87
89
  getPoolKey(): string {
88
- return "session";
90
+ return OLLAMA_QUOTA_POOL_KEY;
89
91
  },
90
92
 
91
93
  getBenchmark() {
@@ -7,18 +7,19 @@
7
7
  // that window. The rotator rounds these to whole percents for routing;
8
8
  // this store keeps the raw values so operators can correlate tokens
9
9
  // (from `rotator_spend_logs`) against usage fractions over time and
10
- // calibrate the real per-model session/weekly budgets without burning
10
+ // calibrate the real per-model monthly budget without burning
11
11
  // quota (see docs/usage-calibration.md).
12
12
  //
13
13
  // Postgres-only, like spend logs: when no database is configured the
14
14
  // store is a silent no-op.
15
15
  //
16
16
  // The table is created lazily on first write. A typical deployment
17
- // produces ~2 rows per account per poll (session + weekly), which at the
17
+ // current API produces ~1 row per account per poll (monthly), which at the
18
18
  // default 5-minute poll interval is ~576 rows/account/day.
19
19
 
20
20
  import { rotatorEnv } from "../../env.js";
21
21
  import type { OllamaUsageResponse } from "./quota.js";
22
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
22
23
 
23
24
  const RETENTION_DEFAULT_DAYS = 14;
24
25
 
@@ -27,7 +28,7 @@ let schemaReady: Promise<void> | null = null;
27
28
  export interface QuotaPollRecord {
28
29
  accountEmail: string;
29
30
  polledAt: string;
30
- pool: "session" | "weekly";
31
+ pool: "monthly" | "session" | "weekly";
31
32
  usageRaw: number;
32
33
  percentRemaining: number;
33
34
  /** Per-model request counts observed inside this pool's window. */
@@ -93,8 +94,9 @@ export async function recordQuotaPoll(record: QuotaPollRecord): Promise<void> {
93
94
  }
94
95
 
95
96
  /**
96
- * Persist both pools from a parsed `GET /api/usage` response. No-op when
97
- * the response lacks the expected shape.
97
+ * Persist the current monthly pool, or both legacy pools when talking to an
98
+ * older `GET /api/usage` response. No-op when the response lacks the expected
99
+ * shape.
98
100
  */
99
101
  export async function recordUsagePoll(
100
102
  accountEmail: string,
@@ -104,7 +106,13 @@ export async function recordUsagePoll(
104
106
  const limits = data?.limits;
105
107
  if (!limits || typeof limits !== "object") return;
106
108
 
107
- for (const pool of ["session", "weekly"] as const) {
109
+ const monthlyLimit = limits[OLLAMA_QUOTA_POOL_KEY];
110
+ const pools: Array<"monthly" | "session" | "weekly"> =
111
+ monthlyLimit && typeof monthlyLimit === "object"
112
+ ? [OLLAMA_QUOTA_POOL_KEY]
113
+ : ["session", "weekly"];
114
+
115
+ for (const pool of pools) {
108
116
  const info = limits[pool] as
109
117
  | { usage?: number | string; models?: unknown[] }
110
118
  | undefined;
@@ -1,4 +1,4 @@
1
- // Ollama Cloud quota polling: `GET /api/usage` → session/weekly pools.
1
+ // Ollama Cloud quota polling: `GET /api/usage` → monthly pool.
2
2
  //
3
3
  // Ported from the ollama-rotator project (same author) into the
4
4
  // tuxevil-rotator provider layer.
@@ -16,6 +16,7 @@ import {
16
16
  } from "./usage-windows.js";
17
17
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
18
18
  import { sortQuotaPools } from "../registry.js";
19
+ import { OLLAMA_QUOTA_POOL_KEY } from "../credential-helpers.js";
19
20
 
20
21
  /**
21
22
  * Poll `GET /api/usage` for one account and store the parsed pool quotas.
@@ -103,10 +104,11 @@ export interface OllamaUsageResponse {
103
104
  }
104
105
 
105
106
  /**
106
- * Parse `GET /api/usage` into the two Ollama quota pools (session + weekly).
107
- * The API reports each pool's usage as a fraction (0..1); reset times are
108
- * computed from the window rules in ./usage-windows.ts, anchored at the
109
- * first observed usage for the session pool.
107
+ * Parse `GET /api/usage` into Ollama quota pools.
108
+ *
109
+ * Current Ollama Cloud responses expose one account-wide `monthly` pool. The
110
+ * legacy session/weekly parser remains as a fallback for older responses so
111
+ * an upgrade does not make an account temporarily unroutable.
110
112
  */
111
113
  export function extractUsagePools(
112
114
  data: OllamaUsageResponse,
@@ -117,6 +119,30 @@ export function extractUsagePools(
117
119
  const limits = data?.limits;
118
120
  if (!limits || typeof limits !== "object") return quotas;
119
121
 
122
+ const monthly = limits[OLLAMA_QUOTA_POOL_KEY];
123
+ if (monthly && typeof monthly === "object") {
124
+ const usageFraction =
125
+ typeof monthly.usage === "number"
126
+ ? monthly.usage
127
+ : typeof monthly.usage === "string"
128
+ ? parseFloat(monthly.usage)
129
+ : NaN;
130
+ if (Number.isFinite(usageFraction)) {
131
+ quotas.push({
132
+ modelKey: OLLAMA_QUOTA_POOL_KEY,
133
+ displayName: "Ollama",
134
+ percentRemaining: Math.max(
135
+ 0,
136
+ Math.min(100, Math.round((1 - usageFraction) * 100)),
137
+ ),
138
+ usageRaw: usageFraction,
139
+ resetTime: null,
140
+ timerType: "monthly",
141
+ });
142
+ return quotas;
143
+ }
144
+ }
145
+
120
146
  for (const pool of ["session", "weekly"] as const) {
121
147
  const info = limits[pool];
122
148
  if (!info || typeof info !== "object") continue;
@@ -11,6 +11,11 @@ import type { AccountRotator } from "../../rotator.js";
11
11
  import type { OpenAIChatCompletionRequest, OpenAIResponsesRequest, CompatCompletion, OpenAIToolCall } from "../google-antigravity/translators.js";
12
12
  import { buildRotatorResponseHeaders } from "../../response-headers.js";
13
13
  import { logSpend } from "../../spend-logger.js";
14
+ import { redactSensitive } from "../../logger.js";
15
+ import {
16
+ createStreamIdleGuard,
17
+ waitForResponseDrain,
18
+ } from "../../stream-guards.js";
14
19
  import {
15
20
  buildCodexPayload,
16
21
  createCodexStreamAccumulator,
@@ -384,16 +389,31 @@ async function pipeNativeResponses(
384
389
  const accumulator = createCodexStreamAccumulator();
385
390
  const streamStartMs = Date.now();
386
391
  let firstByteMs: number | undefined;
392
+ let streamError: string | undefined;
387
393
  const close = (): void => { if (!stream.destroyed) stream.destroy(); };
388
394
  req.once("close", close);
395
+ res.once("close", close);
396
+ const idleGuard = createStreamIdleGuard((error) => {
397
+ streamError = error.message;
398
+ if (!stream.destroyed) stream.destroy(error);
399
+ });
389
400
  try {
390
401
  for await (const chunk of stream) {
402
+ idleGuard.reset();
391
403
  if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
392
404
  accumulator.append(chunk.toString());
393
405
  if (!res.writableEnded) res.write(chunk);
406
+ await waitForResponseDrain(res);
407
+ }
408
+ } catch (error) {
409
+ streamError ??= redactSensitive(String(error)).slice(0, 200);
410
+ if (!res.writableEnded && !res.destroyed) {
411
+ res.write(`event: error\ndata: ${JSON.stringify({ type: "error", error: { code: "stream_error", message: streamError } })}\n\n`);
394
412
  }
395
413
  } finally {
414
+ idleGuard.clear();
396
415
  req.off("close", close);
416
+ res.off("close", close);
397
417
  if (!res.writableEnded) res.end();
398
418
  }
399
419
  const usage = accumulator.final();
@@ -402,6 +422,7 @@ async function pipeNativeResponses(
402
422
  inputTokens: usage?.inputTokens ?? 0,
403
423
  outputTokens: usage?.outputTokens ?? 0,
404
424
  firstByteMs,
425
+ streamError,
405
426
  };
406
427
  }
407
428
 
@@ -432,8 +453,14 @@ async function pipeCodexAsChat(
432
453
  let toolIndex = 0;
433
454
  const streamStartMs = Date.now();
434
455
  let firstByteMs: number | undefined;
456
+ let streamError: string | undefined;
435
457
  const close = (): void => { if (!stream.destroyed) stream.destroy(); };
436
458
  req.once("close", close);
459
+ res.once("close", close);
460
+ const idleGuard = createStreamIdleGuard((error) => {
461
+ streamError = error.message;
462
+ if (!stream.destroyed) stream.destroy(error);
463
+ });
437
464
  const handle = (payload: string, event: string): void => {
438
465
  let data: Record<string, unknown>;
439
466
  try { data = JSON.parse(payload) as Record<string, unknown>; } catch { return; }
@@ -454,6 +481,7 @@ async function pipeCodexAsChat(
454
481
  };
455
482
  try {
456
483
  for await (const chunk of stream) {
484
+ idleGuard.reset();
457
485
  if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
458
486
  buffer += chunk.toString();
459
487
  let newline = buffer.indexOf("\n");
@@ -464,12 +492,25 @@ async function pipeCodexAsChat(
464
492
  else if (line.startsWith("data:")) handle(line.slice(5).trim(), eventName);
465
493
  newline = buffer.indexOf("\n");
466
494
  }
495
+ await waitForResponseDrain(res);
496
+ }
497
+ } catch (error) {
498
+ streamError ??= redactSensitive(String(error)).slice(0, 200);
499
+ if (!res.writableEnded && !res.destroyed) {
500
+ res.write(`data: ${JSON.stringify({ error: { message: streamError, type: "server_error" } })}\n\n`);
501
+ res.end("data: [DONE]\n\n");
467
502
  }
468
- } finally { req.off("close", close); }
469
- emitChatChunk(res, model, id, {}, toolIndex > 0 ? "tool_calls" : "stop");
470
- if (inputTokens > 0 || outputTokens > 0) emitChatChunk(res, model, id, {}, null, { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens });
471
- res.end("data: [DONE]\n\n");
472
- return { text: "", inputTokens, outputTokens, firstByteMs };
503
+ } finally {
504
+ idleGuard.clear();
505
+ req.off("close", close);
506
+ res.off("close", close);
507
+ }
508
+ if (!streamError && !res.writableEnded) {
509
+ emitChatChunk(res, model, id, {}, toolIndex > 0 ? "tool_calls" : "stop");
510
+ if (inputTokens > 0 || outputTokens > 0) emitChatChunk(res, model, id, {}, null, { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens });
511
+ res.end("data: [DONE]\n\n");
512
+ }
513
+ return { text: "", inputTokens, outputTokens, firstByteMs, streamError };
473
514
  }
474
515
 
475
516
  export async function serveCodexResponses(
@@ -489,7 +530,14 @@ export async function serveCodexResponses(
489
530
  if (request.stream) {
490
531
  const completion = await pipeNativeResponses(response, req, res, context, request.model);
491
532
  recordCodexTokenUsage(rotator, request.model, completion);
492
- recordCodexOutcome(rotator, body, context, response.status, completion, options);
533
+ recordCodexOutcome(
534
+ rotator,
535
+ body,
536
+ context,
537
+ completion.streamError ? 502 : response.status,
538
+ completion,
539
+ options,
540
+ );
493
541
  return completion;
494
542
  }
495
543
  const raw = await response.text();
@@ -529,7 +577,14 @@ export async function serveCodexChat(
529
577
  if (request.stream) {
530
578
  const completion = await pipeCodexAsChat(response, req, res, request.model, context);
531
579
  recordCodexTokenUsage(rotator, request.model, completion);
532
- recordCodexOutcome(rotator, body, context, response.status, completion, options);
580
+ recordCodexOutcome(
581
+ rotator,
582
+ body,
583
+ context,
584
+ completion.streamError ? 502 : response.status,
585
+ completion,
586
+ options,
587
+ );
533
588
  return completion;
534
589
  }
535
590
  const raw = await response.text();
@@ -2,7 +2,10 @@ import type { AccountRuntime, ProviderCredential } from "../../types.js";
2
2
  import type { ForwardedResponse, RequestBody } from "../../proxy.js";
3
3
  import type { StreamAccumulator, TokenUsage } from "../adapter.js";
4
4
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
5
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
5
+ import {
6
+ fetchWithHeadersTimeout,
7
+ type RequestInitWithDispatcher,
8
+ } from "../../fetch-with-retry.js";
6
9
  import { getCodexAccountId, getCodexCredential, getCodexTokenState } from "./credentials.js";
7
10
  import { DEFAULT_CODEX_BASE_URL, CODEX_PROVIDER_ID } from "./oauth.js";
8
11
 
@@ -148,7 +151,7 @@ export async function forwardCodexRequest(
148
151
  signal?: AbortSignal,
149
152
  ): Promise<ForwardedResponse> {
150
153
  const payload = buildCodexPayload(body);
151
- const response = await fetch(codexResponsesEndpoint(), {
154
+ const response = await fetchWithHeadersTimeout(codexResponsesEndpoint(), {
152
155
  method: "POST",
153
156
  headers: forwardHeaders(originalHeaders, account, payload),
154
157
  body: JSON.stringify(payload),
@@ -158,6 +161,54 @@ export async function forwardCodexRequest(
158
161
  return { response, endpoint: codexResponsesEndpoint() };
159
162
  }
160
163
 
164
+ function codexStreamErrorMessage(value: Record<string, unknown>): string {
165
+ const error = value.error;
166
+ if (typeof error === "string" && error.trim()) return error.trim();
167
+ if (isRecord(error) && typeof error.message === "string" && error.message.trim()) {
168
+ return error.message.trim();
169
+ }
170
+ return "Codex Responses stream failed";
171
+ }
172
+
173
+ /**
174
+ * A kickstart must let Codex finish its Responses stream. Receiving HTTP 200
175
+ * only means that the stream was accepted; cancelling it before a terminal
176
+ * event can prevent the provider from recording quota consumption.
177
+ */
178
+ export async function consumeCodexKickstartResponse(response: Response): Promise<void> {
179
+ if (!response.body) throw new Error("Codex kickstart returned an empty response body");
180
+ const raw = await response.text();
181
+ if (!raw.trim()) throw new Error("Codex kickstart returned an empty stream");
182
+
183
+ let terminal = false;
184
+ for (const line of raw.split(/\r?\n/)) {
185
+ const payload = line.startsWith("data:") ? line.slice(5).trim() : line.trim();
186
+ if (!payload) continue;
187
+ if (payload === "[DONE]") {
188
+ terminal = true;
189
+ continue;
190
+ }
191
+ let parsed: unknown;
192
+ try {
193
+ parsed = JSON.parse(payload);
194
+ } catch {
195
+ continue;
196
+ }
197
+ if (!isRecord(parsed)) continue;
198
+ const type = typeof parsed.type === "string" ? parsed.type : "";
199
+ if (type === "error" || type === "response.error" || type === "response.failed") {
200
+ throw new Error(codexStreamErrorMessage(parsed));
201
+ }
202
+ if (type === "response.completed" || type === "response.incomplete") {
203
+ terminal = true;
204
+ }
205
+ }
206
+
207
+ if (!terminal) {
208
+ throw new Error("Codex kickstart stream ended before a terminal response event");
209
+ }
210
+ }
211
+
161
212
  function usageFromRecord(record: Record<string, unknown>): TokenUsage | null {
162
213
  const usage = isRecord(record.usage)
163
214
  ? record.usage
@@ -15,10 +15,15 @@ import {
15
15
  import { runCodexLogin } from "./login.js";
16
16
  import {
17
17
  CodexSseAccumulator,
18
+ consumeCodexKickstartResponse,
18
19
  extractCodexUsage,
19
20
  forwardCodexRequest,
20
21
  } from "./forward.js";
21
- import { fetchCodexQuota, CODEX_QUOTA_MODEL_KEY } from "./quota.js";
22
+ import {
23
+ clearCodexQuotaCache,
24
+ fetchCodexQuota,
25
+ CODEX_QUOTA_MODEL_KEY,
26
+ } from "./quota.js";
22
27
  import { isCodexRequestModel, isCodexProviderModelId } from "./catalog.js";
23
28
 
24
29
  const providerLog = logger.child("provider/openai-codex");
@@ -122,7 +127,26 @@ export const openaiCodexAdapter: ProviderAdapter = {
122
127
  forwardRequest: forwardCodexRequest,
123
128
  createStreamAccumulator: () => new CodexSseAccumulator(),
124
129
 
125
- getKickstartModelForPool(): string | undefined { return undefined; },
130
+ async forwardKickstartRequest(account, model, signal) {
131
+ const forwarded = await forwardCodexRequest(
132
+ account,
133
+ {
134
+ project: "",
135
+ model,
136
+ request: { input: ".", stream: true, store: false },
137
+ },
138
+ {},
139
+ signal,
140
+ );
141
+ if (forwarded.response.ok) {
142
+ await consumeCodexKickstartResponse(forwarded.response);
143
+ }
144
+ return forwarded;
145
+ },
146
+
147
+ clearQuotaCache: clearCodexQuotaCache,
148
+
149
+ getKickstartModelForPool(): string | undefined { return "gpt-5.6-luna"; },
126
150
 
127
151
  ownsModel(model: string, context?: { codexModels?: Set<string> }): boolean {
128
152
  if (isCodexRequestModel(model)) return true;