@juspay/neurolink 13.10.3 → 13.10.4

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.
@@ -239,8 +239,8 @@ function formatTimeUntil(unixTimestamp) {
239
239
  * Format session/weekly quota into compact display strings.
240
240
  */
241
241
  function formatQuotaColumns(quota) {
242
- const sessionRemaining = Math.round((1 - quota.sessionUsed) * 100);
243
- const weeklyRemaining = Math.round((1 - quota.weeklyUsed) * 100);
242
+ const sessionRemaining = Math.round((1 - (quota.sessionUsed ?? 0)) * 100);
243
+ const weeklyRemaining = Math.round((1 - (quota.weeklyUsed ?? 0)) * 100);
244
244
  const colorize = (pct, text) => {
245
245
  if (pct <= 10) {
246
246
  return chalk.red(text);
@@ -251,17 +251,23 @@ function formatQuotaColumns(quota) {
251
251
  return chalk.green(text);
252
252
  };
253
253
  return {
254
- sessionText: quota.sessionStatus === "unknown"
255
- ? chalk.gray("unknown")
256
- : colorize(sessionRemaining, `${sessionRemaining}% left`),
257
- weeklyText: quota.weeklyStatus === "unknown"
258
- ? chalk.gray("unknown")
259
- : colorize(weeklyRemaining, `${weeklyRemaining}% left`),
260
- sessionReset: quota.sessionResetAt > 0
261
- ? chalk.gray(`resets ${formatTimeUntil(quota.sessionResetAt)}`)
254
+ // A window the provider does not report (the 5h window is optional on some
255
+ // plans) renders blank rather than as a fabricated "100% left".
256
+ sessionText: quota.sessionUsed === undefined
257
+ ? ""
258
+ : quota.sessionStatus === "unknown"
259
+ ? chalk.gray("unknown")
260
+ : colorize(sessionRemaining, `${sessionRemaining}% left`),
261
+ weeklyText: quota.weeklyUsed === undefined
262
+ ? ""
263
+ : quota.weeklyStatus === "unknown"
264
+ ? chalk.gray("unknown")
265
+ : colorize(weeklyRemaining, `${weeklyRemaining}% left`),
266
+ sessionReset: quota.sessionUsed !== undefined && (quota.sessionResetAt ?? 0) > 0
267
+ ? chalk.gray(`resets ${formatTimeUntil(quota.sessionResetAt ?? 0)}`)
262
268
  : "",
263
- weeklyReset: quota.weeklyResetAt > 0
264
- ? chalk.gray(`resets ${formatTimeUntil(quota.weeklyResetAt)}`)
269
+ weeklyReset: quota.weeklyUsed !== undefined && (quota.weeklyResetAt ?? 0) > 0
270
+ ? chalk.gray(`resets ${formatTimeUntil(quota.weeklyResetAt ?? 0)}`)
265
271
  : "",
266
272
  };
267
273
  }
@@ -697,14 +703,28 @@ export async function handleList(argv) {
697
703
  // Why an account is (or isn't) in the proxy pool. Without this a
698
704
  // disabled or parked account simply vanishes from routing with no clue.
699
705
  const poolState = await collectAccountPoolState(enrichedAccounts.map((acct) => acct.key));
706
+ const quotaFor = (acct) => quotas[acct.key] ??
707
+ (acct.provider === "anthropic" && acct.label
708
+ ? quotas[acct.label]
709
+ : undefined);
710
+ const knownQuotas = enrichedAccounts
711
+ .map(quotaFor)
712
+ .filter((q) => q !== undefined);
713
+ const anySession = knownQuotas.some((q) => q.sessionUsed !== undefined);
714
+ const anyWeekly = knownQuotas.some((q) => q.weeklyUsed !== undefined);
715
+ // Drop a column no account has data for; with no data at all keep both so
716
+ // the explicit "unavailable" / "n/a" refresh state still has a home.
717
+ const noQuotaData = !anySession && !anyWeekly;
718
+ const showSession = hasQuota && (anySession || noQuotaData);
719
+ const showWeekly = hasQuota && (anyWeekly || noQuotaData);
720
+ const limitHeader = (showSession ? ` ${chalk.gray("SESSION".padEnd(14))}` : "") +
721
+ (showWeekly ? ` ${chalk.gray("WEEKLY".padEnd(14))}` : "");
700
722
  const colKey = "LABEL".padEnd(20);
701
723
  const colEmail = "EMAIL".padEnd(28);
702
724
  const colStatus = "TOKEN STATUS".padEnd(14);
703
725
  const colProvider = "PROVIDER".padEnd(12);
704
- const colSession = hasQuota ? "SESSION".padEnd(14) : "";
705
- const colWeekly = hasQuota ? "WEEKLY".padEnd(14) : "";
706
- logger.always(` ${chalk.gray(colKey)} ${chalk.gray(colProvider)} ${chalk.gray(colEmail)} ${chalk.gray(colStatus)}${hasQuota ? ` ${chalk.gray(colSession)} ${chalk.gray(colWeekly)}` : ""}`);
707
- logger.always(` ${chalk.gray("-".repeat(hasQuota ? 108 : 78))}`);
726
+ logger.always(` ${chalk.gray(colKey)} ${chalk.gray(colProvider)} ${chalk.gray(colEmail)} ${chalk.gray(colStatus)}${limitHeader}`);
727
+ logger.always(` ${chalk.gray("-".repeat(78 + (showSession ? 15 : 0) + (showWeekly ? 15 : 0)))}`);
708
728
  for (const acct of enrichedAccounts) {
709
729
  const displayLabel = (acct.label ?? acct.key).padEnd(20);
710
730
  const displayEmail = (acct.email ?? "-").padEnd(28);
@@ -719,18 +739,19 @@ export async function handleList(argv) {
719
739
  else {
720
740
  statusText = chalk.yellow("unknown".padEnd(14));
721
741
  }
722
- const quota = quotas[acct.key] ??
723
- (acct.provider === "anthropic" && acct.label
724
- ? quotas[acct.label]
725
- : undefined);
742
+ const quota = quotaFor(acct);
726
743
  const poolNote = poolState[acct.key];
727
744
  if (hasQuota && quota) {
728
745
  const qc = formatQuotaColumns(quota);
729
- logger.always(` ${chalk.cyan(displayLabel)} ${displayProvider} ${displayEmail} ${statusText} ${qc.sessionText.padEnd(14)} ${qc.weeklyText.padEnd(14)}`);
746
+ logger.always(` ${chalk.cyan(displayLabel)} ${displayProvider} ${displayEmail} ${statusText}${showSession ? ` ${qc.sessionText.padEnd(14)}` : ""}${showWeekly ? ` ${qc.weeklyText.padEnd(14)}` : ""}`);
730
747
  const indent = " ".repeat(2 + 20 + 1 + 12 + 1 + 28 + 1 + 14 + 1);
731
748
  // Second line: reset times (indented under session/weekly columns)
732
- if (qc.sessionReset || qc.weeklyReset) {
733
- logger.always(`${indent}${(qc.sessionReset || "").padEnd(14)} ${qc.weeklyReset || ""}`);
749
+ const resetCells = [
750
+ ...(showSession ? [qc.sessionReset] : []),
751
+ ...(showWeekly ? [qc.weeklyReset] : []),
752
+ ];
753
+ if (resetCells.some((cell) => cell !== "")) {
754
+ logger.always(`${indent}${resetCells.map((cell, i) => (i < resetCells.length - 1 ? cell.padEnd(14) : cell)).join(" ")}`);
734
755
  }
735
756
  // Dynamic per-plan windows (e.g. the Fable-only weekly limit)
736
757
  for (const windowRow of formatQuotaWindowRows(quota)) {
@@ -750,7 +771,7 @@ export async function handleList(argv) {
750
771
  const apiKeyNote = refreshOutcome && acct.tokenType && acct.tokenType !== "Bearer"
751
772
  ? chalk.gray(" (api key — not refreshed)")
752
773
  : "";
753
- logger.always(` ${chalk.cyan(displayLabel)} ${displayProvider} ${displayEmail} ${statusText}${hasQuota ? ` ${chalk.yellow(unavailableText.padEnd(14))} ${chalk.gray("n/a".padEnd(14))}` : ""}${apiKeyNote}`);
774
+ logger.always(` ${chalk.cyan(displayLabel)} ${displayProvider} ${displayEmail} ${statusText}${showSession ? ` ${chalk.yellow(unavailableText.padEnd(14))}` : ""}${showWeekly ? ` ${showSession ? chalk.gray("n/a".padEnd(14)) : chalk.yellow(unavailableText.padEnd(14))}` : ""}${apiKeyNote}`);
754
775
  if (poolNote) {
755
776
  logger.always(` ${poolNote}`);
756
777
  }
@@ -43,7 +43,7 @@ import { modelSupportsForcedToolChoice, resolveSamplingParams, } from "../../mod
43
43
  import { createDeferredAnalytics, stringifyToolInput, } from "../openaiChatCompletionsClient.js";
44
44
  import { createStreamChannel } from "../../core/streamChannel.js";
45
45
  import { toNativeToolDeclarations } from "../../core/nativeToolFormat.js";
46
- import { ANTHROPIC_BETA_HEADERS } from "./constants.js";
46
+ import { ANTHROPIC_API_VERSION, ANTHROPIC_BETA_HEADERS } from "./constants.js";
47
47
  import { cacheControlOf, withLastToolCacheBreakpoint } from "./cacheControl.js";
48
48
  import { createNativeGenerateGuard } from "../../context/nativeGenerateGuard.js";
49
49
  import { appendFinalResultInstruction, appendFinalResultTool, appendToolAnswerInstruction, FINAL_RESULT_TOOL_NAME, } from "./structuredOutput.js";
@@ -606,6 +606,10 @@ export class AnthropicProvider extends BaseProvider {
606
606
  // The claude-code-20250219 beta header triggers "credential only for Claude Code" error
607
607
  client = new Anthropic({
608
608
  apiKey: "oauth-authenticated", // Placeholder, actual auth is in fetch wrapper
609
+ // The fetch wrapper returns before it sets a version when it skips the
610
+ // body transform, which this client always does, so the SDK's own
611
+ // default (2026-10-21 in 1.x) would go out. Pin what this path sent.
612
+ defaultHeaders: { "anthropic-version": ANTHROPIC_API_VERSION },
609
613
  // The same gateway the API-key branch honours: without it, OAuth
610
614
  // credentials that also name a base URL would still reach the vendor.
611
615
  ...(this.baseURL && { baseURL: this.baseURL }),
@@ -640,7 +644,18 @@ export class AnthropicProvider extends BaseProvider {
640
644
  const apiKeyToUse = credentials?.apiKey ?? config?.apiKey ?? getAnthropicApiKey();
641
645
  client = new Anthropic({
642
646
  apiKey: apiKeyToUse,
643
- defaultHeaders: headers,
647
+ // SDK 1.x moved two defaults with its API version: it sends an apiKey
648
+ // as `Authorization: Bearer` and states 2026-10-21. This provider, the
649
+ // gateways in front of it and the NeuroLink Claude proxy authenticate
650
+ // with `x-api-key` on 2023-06-01, so both are stated here (a null
651
+ // `authorization` drops the SDK's own). A caller's headers still win.
652
+ defaultHeaders: {
653
+ "anthropic-version": ANTHROPIC_API_VERSION,
654
+ ...(apiKeyToUse
655
+ ? { "x-api-key": apiKeyToUse, authorization: null }
656
+ : {}),
657
+ ...headers,
658
+ },
644
659
  ...(this.baseURL && { baseURL: this.baseURL }),
645
660
  // Same capture as the OAuth branch: works for direct API-key traffic
646
661
  // (legacy requests/tokens counters) and for the NeuroLink Claude proxy
@@ -1904,7 +1919,9 @@ export class AnthropicProvider extends BaseProvider {
1904
1919
  continue;
1905
1920
  }
1906
1921
  const message = conversation[i];
1907
- if (truncateSet.has(i) && Array.isArray(message.content)) {
1922
+ if (truncateSet.has(i) &&
1923
+ message.role !== "system" &&
1924
+ Array.isArray(message.content)) {
1908
1925
  rebuilt.push({
1909
1926
  ...message,
1910
1927
  content: message.content.map((block) => block.type === "tool_result"
@@ -1,3 +1,5 @@
1
+ export declare const ANTHROPIC_API_VERSION = "2023-06-01";
2
+ export declare const VERTEX_ANTHROPIC_VERSION = "vertex-2023-10-16";
1
3
  export declare const ANTHROPIC_BETA_HEADERS: {
2
4
  "anthropic-beta": string;
3
5
  };
@@ -1,3 +1,11 @@
1
+ // The Messages API version NeuroLink speaks. The SDK picks its own default per
2
+ // release (1.x moved to 2026-10-21), so a version bump must not move the wire
3
+ // version with it: the client sets this one explicitly.
4
+ export const ANTHROPIC_API_VERSION = "2023-06-01";
5
+ // Vertex pins the Anthropic API version in the request body, not in a header.
6
+ // The Vertex SDK copies its default into the body when none is set, so this is
7
+ // handed over explicitly for the same reason.
8
+ export const VERTEX_ANTHROPIC_VERSION = "vertex-2023-10-16";
1
9
  export const ANTHROPIC_BETA_HEADERS = {
2
10
  "anthropic-beta": [
3
11
  "claude-code-20250219",
@@ -22,6 +22,7 @@ import { applyVertexAnthropicCacheBreakpoints } from "../../utils/anthropicCache
22
22
  import { FileDetector } from "../../utils/fileDetector.js";
23
23
  import { mergeMediaFileAliases, normalizeVisionImageFormats, processUnifiedFilesArray, } from "../../utils/messageBuilder.js";
24
24
  import { logger } from "../../utils/logger.js";
25
+ import { VERTEX_ANTHROPIC_VERSION } from "../anthropic/constants.js";
25
26
  import { drainDetachedPump } from "../../utils/drainDetachedPump.js";
26
27
  import { releaseIterator } from "../../utils/streamCancellation.js";
27
28
  import { fireOnErrorOnce, getLifecycleMiddlewareConfig, isLifecycleStreamCallbacksOwnedByBaseProvider, } from "../../utils/lifecycleCallbacks.js";
@@ -404,6 +405,9 @@ const createVertexAnthropicSettings = async (region, timeoutMs, direct, baseURL)
404
405
  // bound (a 429 with retry-after: 8549 sleeps 2.4h per retry, invisible
405
406
  // to fallback orchestration). Retries are the orchestrator's job.
406
407
  maxRetries: 0,
408
+ // The Vertex SDK copies its default API version into the body when none is
409
+ // set, and that default moves with its releases; Vertex expects this one.
410
+ defaultHeaders: { "anthropic-version": VERTEX_ANTHROPIC_VERSION },
407
411
  // Outside the express branch too: an endpoint override is about WHERE the
408
412
  // request goes, not how it is authenticated, so a caller using ADC against
409
413
  // a gateway needs it just as much.
@@ -417,9 +421,7 @@ const createVertexAnthropicSettings = async (region, timeoutMs, direct, baseURL)
417
421
  // credentials error that names nothing useful. `authClient` is the
418
422
  // option the SDK actually consults.
419
423
  authClient: {
420
- getRequestHeaders: async () => ({
421
- Authorization: `Bearer ${direct.apiKey}`,
422
- }),
424
+ getRequestHeaders: async () => new Headers({ Authorization: `Bearer ${direct.apiKey}` }),
423
425
  projectId: null,
424
426
  },
425
427
  }
@@ -168,12 +168,19 @@ export function parseQuotaHeaders(headers, opts) {
168
168
  const P = "anthropic-ratelimit-";
169
169
  const sessionUtilRaw = getHeader(headers, `${P}unified-5h-utilization`);
170
170
  const weeklyUtilRaw = getHeader(headers, `${P}unified-7d-utilization`);
171
- if (sessionUtilRaw === undefined || weeklyUtilRaw === undefined) {
172
- return null;
173
- }
174
- const sessionUsed = parseFloat(sessionUtilRaw);
175
- const weeklyUsed = parseFloat(weeklyUtilRaw);
176
- if (Number.isNaN(sessionUsed) || Number.isNaN(weeklyUsed)) {
171
+ // Either window may be legitimately absent (the 5h window is optional on
172
+ // some plans). A window is reported only when its utilization parses; the
173
+ // snapshot is unusable only when neither does.
174
+ const parseUtilization = (raw) => {
175
+ if (raw === undefined) {
176
+ return undefined;
177
+ }
178
+ const value = parseFloat(raw);
179
+ return Number.isNaN(value) ? undefined : value;
180
+ };
181
+ const sessionUsed = parseUtilization(sessionUtilRaw);
182
+ const weeklyUsed = parseUtilization(weeklyUtilRaw);
183
+ if (sessionUsed === undefined && weeklyUsed === undefined) {
177
184
  return null;
178
185
  }
179
186
  const sessionResetRaw = getHeader(headers, `${P}unified-5h-reset`);
@@ -185,12 +192,22 @@ export function parseQuotaHeaders(headers, opts) {
185
192
  const representativeClaim = getHeader(headers, `${P}unified-representative-claim`);
186
193
  return {
187
194
  unifiedStatus: getUnifiedRateLimitStatus(headers),
188
- sessionUsed,
189
- sessionStatus: getHeader(headers, `${P}unified-5h-status`) ?? "unknown",
190
- sessionResetAt: sessionResetRaw ? parseInt(sessionResetRaw, 10) || 0 : 0,
191
- weeklyUsed,
192
- weeklyStatus: getHeader(headers, `${P}unified-7d-status`) ?? "unknown",
193
- weeklyResetAt: weeklyResetRaw ? parseInt(weeklyResetRaw, 10) || 0 : 0,
195
+ ...(sessionUsed !== undefined
196
+ ? {
197
+ sessionUsed,
198
+ sessionStatus: getHeader(headers, `${P}unified-5h-status`) ?? "unknown",
199
+ sessionResetAt: sessionResetRaw
200
+ ? parseInt(sessionResetRaw, 10) || 0
201
+ : 0,
202
+ }
203
+ : {}),
204
+ ...(weeklyUsed !== undefined
205
+ ? {
206
+ weeklyUsed,
207
+ weeklyStatus: getHeader(headers, `${P}unified-7d-status`) ?? "unknown",
208
+ weeklyResetAt: weeklyResetRaw ? parseInt(weeklyResetRaw, 10) || 0 : 0,
209
+ }
210
+ : {}),
194
211
  fallbackPercentage: fallbackRaw ? parseFloat(fallbackRaw) || 0 : 0,
195
212
  // Anthropic does not send `unified-fallback` on the current wire, so this is
196
213
  // always "unknown" in practice, which keeps the legacy back-compat branch of
@@ -255,6 +255,11 @@ export function usageToQuota(usage, opts) {
255
255
  const windows = limits.map((entry) => mapUsageLimit(entry, now));
256
256
  const sessionLimit = limits.find((entry) => entry.kind === "session");
257
257
  const weeklyLimit = limits.find((entry) => entry.kind === "weekly_all");
258
+ // A window the provider does not report is omitted from the quota rather
259
+ // than defaulted to "0% used": the 5h window is optional on some plans, and
260
+ // a fabricated value reads as full headroom.
261
+ const hasSession = Boolean(usage.five_hour) || sessionLimit !== undefined;
262
+ const hasWeekly = Boolean(usage.seven_day) || weeklyLimit !== undefined;
258
263
  const sessionPct = usage.five_hour?.utilization ?? sessionLimit?.percent ?? undefined;
259
264
  const weeklyPct = usage.seven_day?.utilization ?? weeklyLimit?.percent ?? undefined;
260
265
  // A refresh must never replace a known reset with 0: the payload omits
@@ -275,12 +280,20 @@ export function usageToQuota(usage, opts) {
275
280
  ? "rejected"
276
281
  : (prior?.overageStatus ?? "unknown");
277
282
  const quota = {
278
- sessionUsed: toFraction(sessionPct) ?? prior?.sessionUsed ?? 0,
279
- sessionStatus: deriveWindowStatus(sessionPct, sessionLimit?.severity),
280
- sessionResetAt,
281
- weeklyUsed: toFraction(weeklyPct) ?? prior?.weeklyUsed ?? 0,
282
- weeklyStatus: deriveWindowStatus(weeklyPct, weeklyLimit?.severity),
283
- weeklyResetAt,
283
+ ...(hasSession
284
+ ? {
285
+ sessionUsed: toFraction(sessionPct) ?? prior?.sessionUsed ?? 0,
286
+ sessionStatus: deriveWindowStatus(sessionPct, sessionLimit?.severity),
287
+ sessionResetAt,
288
+ }
289
+ : {}),
290
+ ...(hasWeekly
291
+ ? {
292
+ weeklyUsed: toFraction(weeklyPct) ?? prior?.weeklyUsed ?? 0,
293
+ weeklyStatus: deriveWindowStatus(weeklyPct, weeklyLimit?.severity),
294
+ weeklyResetAt,
295
+ }
296
+ : {}),
284
297
  fallbackPercentage: prior?.fallbackPercentage ?? 0,
285
298
  overageStatus,
286
299
  // Authoritative: the header trio the legacy overage checks rely on is only
@@ -146,8 +146,6 @@ export function codexRateLimitsToQuota(rateLimits, now = Date.now()) {
146
146
  const nowSeconds = Math.floor(now / 1000);
147
147
  const primary = rateLimits?.primary ?? null;
148
148
  const secondary = rateLimits?.secondary ?? null;
149
- const sessionUsed = toFraction(primary?.used_percent);
150
- const weeklyUsed = toFraction(secondary?.used_percent);
151
149
  const windows = [];
152
150
  const primaryWindow = toQuotaWindow("session", "session", primary, nowSeconds);
153
151
  const secondaryWindow = toQuotaWindow("weekly_all", "weekly", secondary, nowSeconds);
@@ -163,12 +161,20 @@ export function codexRateLimitsToQuota(rateLimits, now = Date.now()) {
163
161
  : rateLimits?.allowed === true
164
162
  ? "allowed"
165
163
  : "unknown",
166
- sessionUsed,
167
- sessionStatus: deriveWindowStatus(primary?.used_percent),
168
- sessionResetAt: windowResetEpochSeconds(primary, nowSeconds),
169
- weeklyUsed,
170
- weeklyStatus: deriveWindowStatus(secondary?.used_percent),
171
- weeklyResetAt: windowResetEpochSeconds(secondary, nowSeconds),
164
+ ...(primary
165
+ ? {
166
+ sessionUsed: toFraction(primary.used_percent),
167
+ sessionStatus: deriveWindowStatus(primary.used_percent),
168
+ sessionResetAt: windowResetEpochSeconds(primary, nowSeconds),
169
+ }
170
+ : {}),
171
+ ...(secondary
172
+ ? {
173
+ weeklyUsed: toFraction(secondary.used_percent),
174
+ weeklyStatus: deriveWindowStatus(secondary.used_percent),
175
+ weeklyResetAt: windowResetEpochSeconds(secondary, nowSeconds),
176
+ }
177
+ : {}),
172
178
  // Codex has no overage/fallback concept; keep neutral defaults.
173
179
  fallbackPercentage: 0,
174
180
  overageStatus: "rejected",
@@ -133,12 +133,12 @@ export function buildQuotaResponseHeaders(context, now = Date.now()) {
133
133
  }
134
134
  const quota = context.quota;
135
135
  if (quota && context.source !== "none") {
136
- set("x-neurolink-quota-session-left-pct", quota.sessionStatus === "unknown"
136
+ set("x-neurolink-quota-session-left-pct", quota.sessionUsed === undefined || quota.sessionStatus === "unknown"
137
137
  ? undefined
138
138
  : utilizationToLeftPct(quota.sessionUsed));
139
139
  set("x-neurolink-quota-session-status", quota.sessionStatus);
140
140
  set("x-neurolink-quota-session-resets-in", secondsUntil(quota.sessionResetAt, now));
141
- set("x-neurolink-quota-weekly-left-pct", quota.weeklyStatus === "unknown"
141
+ set("x-neurolink-quota-weekly-left-pct", quota.weeklyUsed === undefined || quota.weeklyStatus === "unknown"
142
142
  ? undefined
143
143
  : utilizationToLeftPct(quota.weeklyUsed));
144
144
  set("x-neurolink-quota-weekly-status", quota.weeklyStatus);
@@ -177,7 +177,9 @@ export function summarizePoolHeadroom(entries, now = Date.now()) {
177
177
  continue;
178
178
  }
179
179
  available += 1;
180
- if (entry.quota && entry.quota.sessionStatus !== "unknown") {
180
+ if (entry.quota &&
181
+ entry.quota.sessionUsed !== undefined &&
182
+ entry.quota.sessionStatus !== "unknown") {
181
183
  const left = utilizationToLeftPct(entry.quota.sessionUsed);
182
184
  if (bestSessionLeftPct === undefined || left > bestSessionLeftPct) {
183
185
  bestSessionLeftPct = left;
@@ -13,11 +13,10 @@
13
13
  * here because nothing reshapes them.
14
14
  */
15
15
  import { logger } from "../utils/logger.js";
16
+ import { VERTEX_ANTHROPIC_VERSION } from "../providers/anthropic/constants.js";
16
17
  import { claudeDisabledThinkingReplacement, modelSupportsForcedToolChoice, } from "../models/modelRegistry.js";
17
18
  import { fetchProxyAware, isTransientNetworkError } from "./proxyFetch.js";
18
19
  import { readCacheCreation1hTokens } from "./proxyTokenUsage.js";
19
- /** Vertex pins the Anthropic API version in the body, not a header. */
20
- const VERTEX_ANTHROPIC_VERSION = "vertex-2023-10-16";
21
20
  const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
22
21
  /**
23
22
  * Fields the Anthropic first-party API accepts that Vertex's publisher endpoint
@@ -835,6 +835,11 @@ function clampCooldownUntil(untilMs, now, reason) {
835
835
  function isAllowedQuotaStatus(status) {
836
836
  return status?.trim().toLowerCase() === "allowed";
837
837
  }
838
+ /** An unreported window (status undefined) cannot be blocking; only a reported
839
+ * status that is not "allowed" counts against the account. */
840
+ function isAllowedOrAbsentQuotaStatus(status) {
841
+ return status === undefined || isAllowedQuotaStatus(status);
842
+ }
838
843
  function isScopedWindowExhausted(window, now) {
839
844
  if (!window || resetEpochToMs(window.resetsAt, now) === undefined) {
840
845
  return false;
@@ -851,8 +856,8 @@ function isScopedWindowExhausted(window, now) {
851
856
  function getScopedOnlyExhaustion(quota, requestedModel, now, policy = overagePolicy) {
852
857
  if (!quota ||
853
858
  !requestedModel ||
854
- !isAllowedQuotaStatus(quota.sessionStatus) ||
855
- !isAllowedQuotaStatus(quota.weeklyStatus) ||
859
+ !isAllowedOrAbsentQuotaStatus(quota.sessionStatus) ||
860
+ !isAllowedOrAbsentQuotaStatus(quota.weeklyStatus) ||
856
861
  isOverageUsable(quota, policy)) {
857
862
  return null;
858
863
  }
@@ -860,8 +865,8 @@ function getScopedOnlyExhaustion(quota, requestedModel, now, policy = overagePol
860
865
  return isScopedWindowExhausted(scopedWindow, now) ? scopedWindow : null;
861
866
  }
862
867
  function hasScopedOnlyExhaustion(quota, now, policy = overagePolicy) {
863
- if (!isAllowedQuotaStatus(quota.sessionStatus) ||
864
- !isAllowedQuotaStatus(quota.weeklyStatus) ||
868
+ if (!isAllowedOrAbsentQuotaStatus(quota.sessionStatus) ||
869
+ !isAllowedOrAbsentQuotaStatus(quota.weeklyStatus) ||
865
870
  isOverageUsable(quota, policy)) {
866
871
  return false;
867
872
  }
@@ -1572,6 +1577,14 @@ function accountSortMetrics(accountKey, now, sessionSoftLimit, sessionResetToler
1572
1577
  const sessionReset = resetEpochToMs(routingQuota?.sessionResetAt, now);
1573
1578
  const sessionTicking = sessionReset !== undefined;
1574
1579
  const weeklyTicking = weeklyReset !== undefined;
1580
+ const sessionObserved = routingQuota !== undefined &&
1581
+ (routingQuota.sessionUsed !== undefined ||
1582
+ routingQuota.sessionStatus !== undefined ||
1583
+ routingQuota.sessionResetAt !== undefined);
1584
+ const weeklyObserved = routingQuota !== undefined &&
1585
+ (routingQuota.weeklyUsed !== undefined ||
1586
+ routingQuota.weeklyStatus !== undefined ||
1587
+ routingQuota.weeklyResetAt !== undefined);
1575
1588
  const sessionUsed = routingQuota
1576
1589
  ? sessionTicking
1577
1590
  ? (routingQuota.sessionUsed ?? 0)
@@ -1672,6 +1685,8 @@ function accountSortMetrics(accountKey, now, sessionSoftLimit, sessionResetToler
1672
1685
  coolingActive,
1673
1686
  coolingReason: st?.coolingReason ?? null,
1674
1687
  coolingUntil: st?.coolingUntil ?? 0,
1688
+ sessionObserved,
1689
+ weeklyObserved,
1675
1690
  unifiedStatus: routingQuota?.unifiedStatus ?? null,
1676
1691
  fallbackStatus: routingQuota?.fallbackStatus ?? null,
1677
1692
  upgradePaths: routingQuota?.upgradePaths ?? null,
@@ -1833,16 +1848,16 @@ function buildRoutingDecision(args) {
1833
1848
  upgradePaths: metrics.upgradePaths,
1834
1849
  overageEligible: metrics.overageEligible,
1835
1850
  overageStatus: metrics.overageStatus,
1836
- sessionStatus: metrics.sessionStatus,
1837
- sessionUsed: metrics.sessionUsed,
1851
+ sessionStatus: metrics.sessionObserved ? metrics.sessionStatus : null,
1852
+ sessionUsed: metrics.sessionObserved ? metrics.sessionUsed : null,
1838
1853
  sessionResetAt: Number.isFinite(metrics.sessionReset)
1839
1854
  ? metrics.sessionReset
1840
1855
  : null,
1841
1856
  sessionResetBucket: Number.isFinite(metrics.sessionResetBucket)
1842
1857
  ? metrics.sessionResetBucket
1843
1858
  : null,
1844
- weeklyStatus: metrics.weeklyStatus,
1845
- weeklyUsed: metrics.weeklyUsed,
1859
+ weeklyStatus: metrics.weeklyObserved ? metrics.weeklyStatus : null,
1860
+ weeklyUsed: metrics.weeklyObserved ? metrics.weeklyUsed : null,
1846
1861
  weeklyResetAt: Number.isFinite(metrics.weeklyReset)
1847
1862
  ? metrics.weeklyReset
1848
1863
  : null,
@@ -314,9 +314,10 @@ function orderCodexAccounts(accounts, now) {
314
314
  if (aRejected !== bRejected) {
315
315
  return aRejected ? 1 : -1;
316
316
  }
317
- const aUsed = a.quota && a.quota.sessionStatus !== "unknown" ? a.quota.sessionUsed : -1;
318
- const bUsed = b.quota && b.quota.sessionStatus !== "unknown" ? b.quota.sessionUsed : -1;
319
- return aUsed - bUsed;
317
+ const sessionUsedOf = (entry) => entry.quota?.sessionStatus !== "unknown"
318
+ ? (entry.quota?.sessionUsed ?? -1)
319
+ : -1;
320
+ return sessionUsedOf(a) - sessionUsedOf(b);
320
321
  });
321
322
  }
322
323
  /** Build the upstream request headers, replacing client auth with the account's. */
@@ -400,15 +401,17 @@ function planCodexCooldown(quota, retryAfterMs, now, errorText = "") {
400
401
  // an account until someone edits the cooldown file by hand.
401
402
  const clamp = (untilMs, reason) => Math.min(Math.max(untilMs, floor), now + (MAX_COOLDOWN_MS_BY_REASON[reason] ?? MAX_TRANSIENT_COOLDOWN_MS));
402
403
  if (quota) {
403
- if (quota.weeklyStatus === "rejected" && quota.weeklyResetAt > 0) {
404
+ const weeklyResetAt = quota.weeklyResetAt ?? 0;
405
+ const sessionResetAt = quota.sessionResetAt ?? 0;
406
+ if (quota.weeklyStatus === "rejected" && weeklyResetAt > 0) {
404
407
  return {
405
- coolingUntil: clamp(quota.weeklyResetAt * 1000, "weekly"),
408
+ coolingUntil: clamp(weeklyResetAt * 1000, "weekly"),
406
409
  reason: "weekly",
407
410
  };
408
411
  }
409
- if (quota.sessionStatus === "rejected" && quota.sessionResetAt > 0) {
412
+ if (quota.sessionStatus === "rejected" && sessionResetAt > 0) {
410
413
  return {
411
- coolingUntil: clamp(quota.sessionResetAt * 1000, "session"),
414
+ coolingUntil: clamp(sessionResetAt * 1000, "session"),
412
415
  reason: "session",
413
416
  };
414
417
  }
@@ -448,10 +451,14 @@ function publishCodexHeaders(ctx, account, attempt, quota) {
448
451
  ctx.responseHeaders["x-neurolink-served-by"] = "codex";
449
452
  ctx.responseHeaders["x-neurolink-attempt"] = String(attempt);
450
453
  ctx.responseHeaders["x-neurolink-quota-source"] = quota ? "live" : "none";
451
- if (quota && quota.sessionStatus !== "unknown") {
454
+ if (quota &&
455
+ quota.sessionUsed !== undefined &&
456
+ quota.sessionStatus !== "unknown") {
452
457
  ctx.responseHeaders["x-neurolink-quota-session-left-pct"] = String(Math.round((1 - quota.sessionUsed) * 100));
453
458
  }
454
- if (quota && quota.weeklyStatus !== "unknown") {
459
+ if (quota &&
460
+ quota.weeklyUsed !== undefined &&
461
+ quota.weeklyStatus !== "unknown") {
455
462
  const remaining = String(Math.round((1 - quota.weeklyUsed) * 100));
456
463
  ctx.responseHeaders["x-neurolink-quota-weekly-left-pct"] = remaining;
457
464
  // Preserve the original Codex header for existing clients.
@@ -3,6 +3,7 @@ import type { Span } from "@opentelemetry/api";
3
3
  import type { Tool } from "./tools.js";
4
4
  import type { GenerateStopReason } from "./generate.js";
5
5
  import type { UnknownRecord } from "./common.js";
6
+ import type { AnthropicSamplingParams } from "./providers.js";
6
7
  import type { GenerationOperation, GenerationRecord } from "./observability.js";
7
8
  import type { CollectedChunkResult, NativeFunctionCall, NativeToolDeclarationsResult } from "./providers.js";
8
9
  import type { ExecutionControlDecision, ExecutionControlStepContext } from "./stream.js";
@@ -278,7 +279,7 @@ export type AnthropicLoopAdapterConfig<TMessage = Anthropic.Messages.MessagePara
278
279
  * type carries `stream?: boolean` fails to match `stream: true` for a field
279
280
  * the adapter is about to overwrite.
280
281
  */
281
- buildParams: (conversation: TMessage[], step: number) => Anthropic.Messages.MessageCreateParamsNonStreaming | Promise<Anthropic.Messages.MessageCreateParamsNonStreaming>;
282
+ buildParams: (conversation: TMessage[], step: number) => (Anthropic.Messages.MessageCreateParamsNonStreaming & AnthropicSamplingParams) | Promise<Anthropic.Messages.MessageCreateParamsNonStreaming & AnthropicSamplingParams>;
282
283
  /** The turn's live tool record, used for deferred-catalog resolution. */
283
284
  toolsRecord: Record<string, Tool>;
284
285
  /**
@@ -1548,9 +1548,18 @@ export type GoogleVertexProviderSettings = {
1548
1548
  * instead of standing up Application Default Credentials.
1549
1549
  */
1550
1550
  export type VertexAnthropicAuthClient = {
1551
- getRequestHeaders: () => Promise<Record<string, string>>;
1551
+ getRequestHeaders: () => Promise<Headers>;
1552
1552
  projectId?: string | null;
1553
1553
  };
1554
+ /**
1555
+ * The sampling fields a Messages request still carries on the wire. SDK 1.x no
1556
+ * longer declares them on its request types, but NeuroLink sends them (per
1557
+ * model, through `resolveSamplingParams`) and reads them back for tracing.
1558
+ */
1559
+ export type AnthropicSamplingParams = {
1560
+ temperature?: number;
1561
+ top_p?: number;
1562
+ };
1554
1563
  export type AnthropicVertexSettings = {
1555
1564
  /** Google Cloud project ID */
1556
1565
  projectId: string;
@@ -1566,6 +1575,8 @@ export type AnthropicVertexSettings = {
1566
1575
  * a compatible endpoint is reached by setting this instead.
1567
1576
  */
1568
1577
  baseURL?: string;
1578
+ /** Headers sent with every request (the SDK reads the API version from here). */
1579
+ defaultHeaders?: Record<string, string>;
1569
1580
  /**
1570
1581
  * Supply the request credentials directly, bypassing Application Default
1571
1582
  * Credentials.
@@ -572,6 +572,11 @@ export type ProxyAccountSortMetrics = {
572
572
  coolingActive: boolean;
573
573
  coolingReason: AccountCoolingReason | null;
574
574
  coolingUntil: number;
575
+ /** False when the provider reports no 5h / 7d window for this account, as
576
+ * opposed to a window that has expired. Ranking keeps its neutral defaults;
577
+ * routing evidence uses these to leave the window out. */
578
+ sessionObserved: boolean;
579
+ weeklyObserved: boolean;
575
580
  unifiedStatus: string | null;
576
581
  fallbackStatus?: string | null;
577
582
  upgradePaths?: string | null;
@@ -1522,18 +1527,19 @@ export type AccountQuota = {
1522
1527
  /** Top-level unified status. A rejected value can be authoritative even
1523
1528
  * while both 5h and 7d sub-window statuses still report allowed. */
1524
1529
  unifiedStatus?: string;
1525
- /** 0.0-1.0 utilization; ignore the numeric placeholder when status is unknown. */
1526
- sessionUsed: number;
1527
- /** "allowed" | "throttled" | "rejected" | "unknown" */
1528
- sessionStatus: string;
1530
+ /** 0.0-1.0 utilization. Absent when the provider does not report a 5h
1531
+ * window for this account (the window is optional, not "0% used"). */
1532
+ sessionUsed?: number;
1533
+ /** "allowed" | "throttled" | "rejected" | "unknown". Absent with sessionUsed. */
1534
+ sessionStatus?: string;
1529
1535
  /** Unix timestamp (seconds) when the 5h window resets */
1530
- sessionResetAt: number;
1531
- /** 0.0-1.0 utilization; ignore the numeric placeholder when status is unknown. */
1532
- weeklyUsed: number;
1533
- /** "allowed" | "throttled" | "rejected" | "unknown" */
1534
- weeklyStatus: string;
1536
+ sessionResetAt?: number;
1537
+ /** 0.0-1.0 utilization. Absent when the provider reports no 7d window. */
1538
+ weeklyUsed?: number;
1539
+ /** "allowed" | "throttled" | "rejected" | "unknown". Absent with weeklyUsed. */
1540
+ weeklyStatus?: string;
1535
1541
  /** Unix timestamp (seconds) when the 7d window resets */
1536
- weeklyResetAt: number;
1542
+ weeklyResetAt?: number;
1537
1543
  /** 0.0-1.0 (from fallback-percentage) */
1538
1544
  fallbackPercentage: number;
1539
1545
  /** Provider fallback availability, for example "available". */