tuxevil-rotator 3.7.1 → 3.8.0

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.
@@ -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,
@@ -32,6 +37,11 @@ export interface CodexCompatOptions {
32
37
  apiKeyHash?: string | null;
33
38
  requesterIp?: string | null;
34
39
  rawRequest?: unknown;
40
+ providerId?: string;
41
+ requestedModel?: string;
42
+ selectionMode?: "typesafe" | "deterministic" | "disabled";
43
+ selectionConfidence?: number;
44
+ selectionReason?: string;
35
45
  }
36
46
 
37
47
  function recordCodexTokenUsage(
@@ -352,7 +362,7 @@ function codexResponseJson(
352
362
  };
353
363
  }
354
364
 
355
- function upstreamHeaders(response: Response, context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number }, model: string): Record<string, string> {
365
+ function upstreamHeaders(response: Response, context: RotationAttemptContext, model: string): Record<string, string> {
356
366
  const headers: Record<string, string> = {};
357
367
  response.headers.forEach((value, key) => {
358
368
  if (key !== "connection" && key !== "transfer-encoding" && key !== "content-length") headers[key] = value;
@@ -360,6 +370,11 @@ function upstreamHeaders(response: Response, context: { account?: { healthScore:
360
370
  Object.assign(headers, buildRotatorResponseHeaders({
361
371
  accountLabel: context.label,
362
372
  model,
373
+ requestedModel: context.requestedModel,
374
+ selectedProvider: context.providerId,
375
+ modelSelection: context.selectionMode,
376
+ selectionConfidence: context.selectionConfidence,
377
+ selectionReason: context.selectionReason,
363
378
  ttfbMs: Date.now() - context.requestStartMs,
364
379
  healthScore: context.account?.healthScore,
365
380
  retries: context.retries,
@@ -372,7 +387,7 @@ async function pipeNativeResponses(
372
387
  response: Response,
373
388
  req: IncomingMessage,
374
389
  res: ServerResponse,
375
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
390
+ context: RotationAttemptContext,
376
391
  model: string,
377
392
  ): Promise<CompatCompletion> {
378
393
  res.writeHead(response.status, upstreamHeaders(response, context, model));
@@ -384,16 +399,31 @@ async function pipeNativeResponses(
384
399
  const accumulator = createCodexStreamAccumulator();
385
400
  const streamStartMs = Date.now();
386
401
  let firstByteMs: number | undefined;
402
+ let streamError: string | undefined;
387
403
  const close = (): void => { if (!stream.destroyed) stream.destroy(); };
388
404
  req.once("close", close);
405
+ res.once("close", close);
406
+ const idleGuard = createStreamIdleGuard((error) => {
407
+ streamError = error.message;
408
+ if (!stream.destroyed) stream.destroy(error);
409
+ });
389
410
  try {
390
411
  for await (const chunk of stream) {
412
+ idleGuard.reset();
391
413
  if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
392
414
  accumulator.append(chunk.toString());
393
415
  if (!res.writableEnded) res.write(chunk);
416
+ await waitForResponseDrain(res);
417
+ }
418
+ } catch (error) {
419
+ streamError ??= redactSensitive(String(error)).slice(0, 200);
420
+ if (!res.writableEnded && !res.destroyed) {
421
+ res.write(`event: error\ndata: ${JSON.stringify({ type: "error", error: { code: "stream_error", message: streamError } })}\n\n`);
394
422
  }
395
423
  } finally {
424
+ idleGuard.clear();
396
425
  req.off("close", close);
426
+ res.off("close", close);
397
427
  if (!res.writableEnded) res.end();
398
428
  }
399
429
  const usage = accumulator.final();
@@ -402,6 +432,7 @@ async function pipeNativeResponses(
402
432
  inputTokens: usage?.inputTokens ?? 0,
403
433
  outputTokens: usage?.outputTokens ?? 0,
404
434
  firstByteMs,
435
+ streamError,
405
436
  };
406
437
  }
407
438
 
@@ -414,7 +445,7 @@ async function pipeCodexAsChat(
414
445
  req: IncomingMessage,
415
446
  res: ServerResponse,
416
447
  model: string,
417
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
448
+ context: RotationAttemptContext,
418
449
  ): Promise<CompatCompletion> {
419
450
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", ...upstreamHeaders(response, context, model) });
420
451
  const id = `chatcmpl-${Date.now().toString(36)}`;
@@ -432,8 +463,14 @@ async function pipeCodexAsChat(
432
463
  let toolIndex = 0;
433
464
  const streamStartMs = Date.now();
434
465
  let firstByteMs: number | undefined;
466
+ let streamError: string | undefined;
435
467
  const close = (): void => { if (!stream.destroyed) stream.destroy(); };
436
468
  req.once("close", close);
469
+ res.once("close", close);
470
+ const idleGuard = createStreamIdleGuard((error) => {
471
+ streamError = error.message;
472
+ if (!stream.destroyed) stream.destroy(error);
473
+ });
437
474
  const handle = (payload: string, event: string): void => {
438
475
  let data: Record<string, unknown>;
439
476
  try { data = JSON.parse(payload) as Record<string, unknown>; } catch { return; }
@@ -454,6 +491,7 @@ async function pipeCodexAsChat(
454
491
  };
455
492
  try {
456
493
  for await (const chunk of stream) {
494
+ idleGuard.reset();
457
495
  if (firstByteMs === undefined) firstByteMs = Date.now() - streamStartMs;
458
496
  buffer += chunk.toString();
459
497
  let newline = buffer.indexOf("\n");
@@ -464,12 +502,25 @@ async function pipeCodexAsChat(
464
502
  else if (line.startsWith("data:")) handle(line.slice(5).trim(), eventName);
465
503
  newline = buffer.indexOf("\n");
466
504
  }
505
+ await waitForResponseDrain(res);
467
506
  }
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 };
507
+ } catch (error) {
508
+ streamError ??= redactSensitive(String(error)).slice(0, 200);
509
+ if (!res.writableEnded && !res.destroyed) {
510
+ res.write(`data: ${JSON.stringify({ error: { message: streamError, type: "server_error" } })}\n\n`);
511
+ res.end("data: [DONE]\n\n");
512
+ }
513
+ } finally {
514
+ idleGuard.clear();
515
+ req.off("close", close);
516
+ res.off("close", close);
517
+ }
518
+ if (!streamError && !res.writableEnded) {
519
+ emitChatChunk(res, model, id, {}, toolIndex > 0 ? "tool_calls" : "stop");
520
+ if (inputTokens > 0 || outputTokens > 0) emitChatChunk(res, model, id, {}, null, { prompt_tokens: inputTokens, completion_tokens: outputTokens, total_tokens: inputTokens + outputTokens });
521
+ res.end("data: [DONE]\n\n");
522
+ }
523
+ return { text: "", inputTokens, outputTokens, firstByteMs, streamError };
473
524
  }
474
525
 
475
526
  export async function serveCodexResponses(
@@ -479,7 +530,16 @@ export async function serveCodexResponses(
479
530
  request: OpenAIResponsesRequest,
480
531
  options?: CodexCompatOptions,
481
532
  ): Promise<void> {
482
- const body: RequestBody = { project: "", model: request.model, request: buildCodexPayload({ project: "", model: request.model, request }) };
533
+ const body: RequestBody = {
534
+ project: "",
535
+ model: request.model,
536
+ request: buildCodexPayload({ project: "", model: request.model, request }),
537
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
538
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
539
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
540
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
541
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
542
+ };
483
543
  const controller = new AbortController();
484
544
  const abort = (): void => controller.abort();
485
545
  req.once("aborted", abort);
@@ -489,7 +549,14 @@ export async function serveCodexResponses(
489
549
  if (request.stream) {
490
550
  const completion = await pipeNativeResponses(response, req, res, context, request.model);
491
551
  recordCodexTokenUsage(rotator, request.model, completion);
492
- recordCodexOutcome(rotator, body, context, response.status, completion, options);
552
+ recordCodexOutcome(
553
+ rotator,
554
+ body,
555
+ context,
556
+ completion.streamError ? 502 : response.status,
557
+ completion,
558
+ options,
559
+ );
493
560
  return completion;
494
561
  }
495
562
  const raw = await response.text();
@@ -519,7 +586,16 @@ export async function serveCodexChat(
519
586
  options?: CodexCompatOptions,
520
587
  ): Promise<void> {
521
588
  const codexRequest = chatToCodexResponsesRequest(request);
522
- const body: RequestBody = { project: "", model: request.model, request: codexRequest };
589
+ const body: RequestBody = {
590
+ project: "",
591
+ model: request.model,
592
+ request: codexRequest,
593
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
594
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
595
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
596
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
597
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
598
+ };
523
599
  const controller = new AbortController();
524
600
  const abort = (): void => controller.abort();
525
601
  req.once("aborted", abort);
@@ -529,7 +605,14 @@ export async function serveCodexChat(
529
605
  if (request.stream) {
530
606
  const completion = await pipeCodexAsChat(response, req, res, request.model, context);
531
607
  recordCodexTokenUsage(rotator, request.model, completion);
532
- recordCodexOutcome(rotator, body, context, response.status, completion, options);
608
+ recordCodexOutcome(
609
+ rotator,
610
+ body,
611
+ context,
612
+ completion.streamError ? 502 : response.status,
613
+ completion,
614
+ options,
615
+ );
533
616
  return completion;
534
617
  }
535
618
  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),
@@ -5,7 +5,10 @@ import type { AccountRuntime } from "../../types.js";
5
5
  import type { ForwardedResponse, RequestBody } from "../../proxy.js";
6
6
  import type { StreamAccumulator, TokenUsage } from "../adapter.js";
7
7
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
8
- import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
8
+ import {
9
+ fetchWithHeadersTimeout,
10
+ type RequestInitWithDispatcher,
11
+ } from "../../fetch-with-retry.js";
9
12
  import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
10
13
  import {
11
14
  isOpenCodeZenResponsesModel,
@@ -282,7 +285,7 @@ export async function forwardRequest(
282
285
  forwardHeaders["Accept"] = payload.stream === true ? "text/event-stream" : "application/json";
283
286
 
284
287
  const endpoint = usesResponses ? OPENCODE_ZEN_RESPONSES_URL : OPENCODE_ZEN_CHAT_URL;
285
- const response = await fetch(endpoint, {
288
+ const response = await fetchWithHeadersTimeout(endpoint, {
286
289
  method: "POST",
287
290
  headers: forwardHeaders,
288
291
  body: JSON.stringify(payload),
@@ -406,6 +409,7 @@ function responseCompletionFromRecord(
406
409
  thinkingText: thinkingText || undefined,
407
410
  inputTokens: usage?.inputTokens ?? 0,
408
411
  outputTokens: usage?.outputTokens ?? 0,
412
+ cachedTokens: usage?.cachedTokens,
409
413
  responseId: typeof value.id === "string" ? value.id : undefined,
410
414
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
411
415
  rawResponse,
@@ -483,6 +487,7 @@ export class OpenCodeZenResponsesStreamParser {
483
487
  thinkingText: this.thinkingText || undefined,
484
488
  inputTokens: this.usage?.inputTokens ?? 0,
485
489
  outputTokens: this.usage?.outputTokens ?? 0,
490
+ cachedTokens: this.usage?.cachedTokens,
486
491
  responseId: this.responseId,
487
492
  toolCalls: this.toolCalls.size > 0 ? Array.from(this.toolCalls.values()) : undefined,
488
493
  streamError: this.streamError,
@@ -496,6 +501,9 @@ export class OpenCodeZenResponsesStreamParser {
496
501
  input_tokens: this.usage.inputTokens,
497
502
  output_tokens: this.usage.outputTokens,
498
503
  total_tokens: this.usage.inputTokens + this.usage.outputTokens,
504
+ ...(this.usage.cachedTokens !== undefined
505
+ ? { input_tokens_details: { cached_tokens: this.usage.cachedTokens } }
506
+ : {}),
499
507
  }
500
508
  : undefined,
501
509
  },
@@ -641,7 +649,7 @@ function openCodeZenChatChunk(
641
649
  id: string,
642
650
  model: string,
643
651
  delta: Record<string, unknown>,
644
- usage?: Record<string, number>,
652
+ usage?: Record<string, unknown>,
645
653
  ): string {
646
654
  return `data: ${JSON.stringify({
647
655
  id,
@@ -681,6 +689,9 @@ function updateToOpenCodeZenChatSse(
681
689
  prompt_tokens: update.usage.inputTokens,
682
690
  completion_tokens: update.usage.outputTokens,
683
691
  total_tokens: update.usage.inputTokens + update.usage.outputTokens,
692
+ ...(update.usage.cachedTokens !== undefined
693
+ ? { prompt_tokens_details: { cached_tokens: update.usage.cachedTokens } }
694
+ : {}),
684
695
  });
685
696
  case "finish":
686
697
  return "";
@@ -774,6 +785,9 @@ function openCodeZenResponsesToChatJson(
774
785
  prompt_tokens: completion.inputTokens,
775
786
  completion_tokens: completion.outputTokens,
776
787
  total_tokens: completion.inputTokens + completion.outputTokens,
788
+ ...(completion.cachedTokens !== undefined
789
+ ? { prompt_tokens_details: { cached_tokens: completion.cachedTokens } }
790
+ : {}),
777
791
  },
778
792
  };
779
793
  }
@@ -792,9 +806,27 @@ function extractUsageFromRecord(record: Record<string, unknown>): TokenUsage | n
792
806
  : typeof usage.output_tokens === "number"
793
807
  ? usage.output_tokens
794
808
  : 0;
809
+ const inputTokenDetails = isRecord(usage.input_tokens_details)
810
+ ? usage.input_tokens_details
811
+ : null;
812
+ const promptTokenDetails = isRecord(usage.prompt_tokens_details)
813
+ ? usage.prompt_tokens_details
814
+ : null;
815
+ const cachedTokens =
816
+ typeof inputTokenDetails?.cached_tokens === "number"
817
+ ? inputTokenDetails.cached_tokens
818
+ : typeof promptTokenDetails?.cached_tokens === "number"
819
+ ? promptTokenDetails.cached_tokens
820
+ : typeof usage.cached_tokens === "number"
821
+ ? usage.cached_tokens
822
+ : undefined;
795
823
 
796
824
  return inputTokens > 0 || outputTokens > 0
797
- ? { inputTokens, outputTokens }
825
+ ? {
826
+ inputTokens,
827
+ outputTokens,
828
+ ...(cachedTokens !== undefined ? { cachedTokens } : {}),
829
+ }
798
830
  : null;
799
831
  }
800
832
 
@@ -63,8 +63,19 @@ export function isKnownProvider(providerId: string): boolean {
63
63
 
64
64
  export function findProviderForModel(
65
65
  model: string,
66
- context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
66
+ context?: {
67
+ ollamaModels?: Set<string>;
68
+ codexModels?: Set<string>;
69
+ providerId?: string;
70
+ },
67
71
  ): ProviderAdapter | null {
72
+ if (context?.providerId) {
73
+ try {
74
+ return getProviderAdapter(context.providerId);
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
68
79
  // Check non-default explicit providers first to prevent Google fallback overlap
69
80
  for (const adapter of [opencodeZenAdapter, openaiCodexAdapter, ollamaAdapter, googleAntigravityAdapter]) {
70
81
  if (adapter.ownsModel?.(model, context)) {