@juspay/neurolink 10.8.12 → 10.8.13

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.
@@ -116,6 +116,40 @@ const POPULAR_MCP_SERVERS = {
116
116
  },
117
117
  };
118
118
  const MCP_STATUS_TIMEOUT_MS = 30_000;
119
+ /** Where `externalServerManager` looks for manually configured servers. */
120
+ const MCP_CONFIG_FILENAME = ".mcp-config.json";
121
+ /**
122
+ * Explain an empty server list in terms of what the user's directory actually
123
+ * looks like.
124
+ *
125
+ * "Found 0 MCP servers" plus two generic tips reads as an error with no cause:
126
+ * the common case is simply that this project has no `.mcp-config.json`, and
127
+ * saying so turns a dead end into a next step. When the file *is* present, the
128
+ * cause is different — it parsed but declared nothing usable — so the advice
129
+ * has to be different too, otherwise we'd send the user to create a file they
130
+ * already have.
131
+ */
132
+ function explainEmptyServerList() {
133
+ const configPath = path.join(process.cwd(), MCP_CONFIG_FILENAME);
134
+ const configExists = fs.existsSync(configPath);
135
+ const lines = [];
136
+ if (configExists) {
137
+ lines.push(chalk.blue(`📄 Found ${MCP_CONFIG_FILENAME}, but it declares no usable servers.`), chalk.blue(` Check the "mcpServers" object in ${configPath} — each entry needs a "command" (stdio) or "url" (http/sse/websocket).`));
138
+ }
139
+ else {
140
+ lines.push(chalk.blue(`📄 No ${MCP_CONFIG_FILENAME} in this directory (${process.cwd()}).`), chalk.blue(" That file is where NeuroLink reads manually configured servers from."));
141
+ }
142
+ // Neither `install` nor `add` persists anything: both route through
143
+ // NeuroLink.addInMemoryMCPServer(), which registers into the in-process tool
144
+ // registry and is gone when the process exits. Nothing in the CLI writes
145
+ // MCP_CONFIG_FILENAME. Saying otherwise sends the user looking for a file
146
+ // that was never created — so the persistent path is spelled out as the
147
+ // manual edit it actually is.
148
+ lines.push("", chalk.blue("Next steps:"), chalk.blue(configExists
149
+ ? ` • Add an entry to the "mcpServers" object in ${MCP_CONFIG_FILENAME} — editing that file is the only way to configure a server permanently.`
150
+ : ` • Create ${MCP_CONFIG_FILENAME} here with an "mcpServers" object — each entry needs a "command" (stdio) or "url" (http/sse/websocket). Writing that file is the only way to configure a server permanently.`), chalk.blue(" • neurolink mcp install <server> register a popular server for the current run only"), chalk.blue(" • neurolink mcp discover discover tools from servers already reachable"), chalk.blue(" • neurolink mcp --help all MCP subcommands"));
151
+ return lines.join("\n");
152
+ }
119
153
  /**
120
154
  * MCP CLI command factory
121
155
  */
@@ -199,9 +233,9 @@ export class MCPCommandFactory {
199
233
  default: false,
200
234
  description: "Suppress non-essential output",
201
235
  })
202
- .example("neurolink discover", "Discover MCP servers from all sources")
203
- .example("neurolink discover --source claude-desktop", "Discover from Claude Desktop only")
204
- .example("neurolink discover --auto-install", "Discover and auto-install servers");
236
+ .example("neurolink mcp discover", "Discover MCP servers from all sources")
237
+ .example("neurolink mcp discover --source claude-desktop", "Discover from Claude Desktop only")
238
+ .example("neurolink mcp discover --auto-install", "Discover and auto-install servers");
205
239
  },
206
240
  handler: async (argv) => await MCPCommandFactory.executeDiscover(argv),
207
241
  };
@@ -357,8 +391,7 @@ export class MCPCommandFactory {
357
391
  }
358
392
  if (allServers.length === 0) {
359
393
  logger.always(chalk.yellow("No MCP servers configured."));
360
- logger.always(chalk.blue("💡 Use 'neurolink mcp install <server>' to install popular servers"));
361
- logger.always(chalk.blue("💡 Use 'neurolink discover' to find existing servers"));
394
+ logger.always(explainEmptyServerList());
362
395
  return;
363
396
  }
364
397
  // Format and display results
@@ -1,8 +1,18 @@
1
1
  import type { FallbackEntry, ModelMapping, ProxyRoutingConfig, RouteResult } from "../types/index.js";
2
- /** Default and accepted range for concurrent upstream requests per OAuth account. */
2
+ /** Accepted range for an explicitly configured OAuth account admission cap. */
3
3
  export declare const MIN_MAX_INFLIGHT_PER_ACCOUNT = 1;
4
4
  export declare const MAX_MAX_INFLIGHT_PER_ACCOUNT = 20;
5
- export declare const DEFAULT_MAX_INFLIGHT_PER_ACCOUNT = 2;
5
+ /**
6
+ * The single definition of "a usable admission cap": an integer inside the
7
+ * accepted range. Anything else — `0`, `1.5`, `21`, `NaN` — means unlimited.
8
+ *
9
+ * `parseProxyConfig()` already drops invalid YAML values, but `ProxyRoutingConfig`
10
+ * is an exported type, so a programmatic caller can hand `ModelRouter` a value
11
+ * that never passed through it. Without this, `getMaxInflightPerAccount()` would
12
+ * report a bound (`0`, `21`) that the admission path ignores as unlimited, and
13
+ * the two would disagree about whether the account is capped.
14
+ */
15
+ export declare function normalizeMaxInflightPerAccount(capacity: number | undefined): number | undefined;
6
16
  export declare class ModelRouter {
7
17
  private readonly mappings;
8
18
  private readonly passthrough;
@@ -15,8 +25,8 @@ export declare class ModelRouter {
15
25
  getFallbackChain(): FallbackEntry[];
16
26
  /** Whether translation-layer auto-provider fallback is explicitly enabled. */
17
27
  isAutoFallbackEnabled(): boolean;
18
- /** Maximum concurrent upstream requests admitted for each OAuth account. */
19
- getMaxInflightPerAccount(): number;
28
+ /** Explicit per-account admission cap, or undefined when admission is unlimited. */
29
+ getMaxInflightPerAccount(): number | undefined;
20
30
  /** Return the raw model mapping entries (used by /v1/models). */
21
31
  getModelMappings(): ModelMapping[];
22
32
  /** Return models configured for passthrough (used by /v1/models). */
@@ -1,7 +1,24 @@
1
- /** Default and accepted range for concurrent upstream requests per OAuth account. */
1
+ /** Accepted range for an explicitly configured OAuth account admission cap. */
2
2
  export const MIN_MAX_INFLIGHT_PER_ACCOUNT = 1;
3
3
  export const MAX_MAX_INFLIGHT_PER_ACCOUNT = 20;
4
- export const DEFAULT_MAX_INFLIGHT_PER_ACCOUNT = 2;
4
+ /**
5
+ * The single definition of "a usable admission cap": an integer inside the
6
+ * accepted range. Anything else — `0`, `1.5`, `21`, `NaN` — means unlimited.
7
+ *
8
+ * `parseProxyConfig()` already drops invalid YAML values, but `ProxyRoutingConfig`
9
+ * is an exported type, so a programmatic caller can hand `ModelRouter` a value
10
+ * that never passed through it. Without this, `getMaxInflightPerAccount()` would
11
+ * report a bound (`0`, `21`) that the admission path ignores as unlimited, and
12
+ * the two would disagree about whether the account is capped.
13
+ */
14
+ export function normalizeMaxInflightPerAccount(capacity) {
15
+ return typeof capacity === "number" &&
16
+ Number.isInteger(capacity) &&
17
+ capacity >= MIN_MAX_INFLIGHT_PER_ACCOUNT &&
18
+ capacity <= MAX_MAX_INFLIGHT_PER_ACCOUNT
19
+ ? capacity
20
+ : undefined;
21
+ }
5
22
  export class ModelRouter {
6
23
  mappings;
7
24
  passthrough;
@@ -13,8 +30,7 @@ export class ModelRouter {
13
30
  this.passthrough = new Set(config.passthroughModels ?? []);
14
31
  this.fallback = config.fallbackChain;
15
32
  this.autoFallback = config.autoFallback === true;
16
- this.maxInflightPerAccount =
17
- config.maxInflightPerAccount ?? DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
33
+ this.maxInflightPerAccount = normalizeMaxInflightPerAccount(config.maxInflightPerAccount);
18
34
  }
19
35
  resolve(requestedModel) {
20
36
  const mapping = this.mappings.get(requestedModel);
@@ -42,7 +58,7 @@ export class ModelRouter {
42
58
  isAutoFallbackEnabled() {
43
59
  return this.autoFallback;
44
60
  }
45
- /** Maximum concurrent upstream requests admitted for each OAuth account. */
61
+ /** Explicit per-account admission cap, or undefined when admission is unlimited. */
46
62
  getMaxInflightPerAccount() {
47
63
  return this.maxInflightPerAccount;
48
64
  }
@@ -12,8 +12,9 @@
12
12
  import { buildTranslationOptions } from "../../proxy/proxyTranslationEngine.js";
13
13
  import { ProxyTracer } from "../../proxy/proxyTracer.js";
14
14
  import { isPermanentRefreshFailure } from "../../proxy/tokenRefresh.js";
15
- import type { AccountAllowlist, AccountAdmissionLease, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicNonOkResult, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeLoggedErrorBuilder, ClaudeRequest, ClaudeProxyRouteRuntimeOptions, ModelRouterInterface, ParsedClaudeError, ProxyAccountRoutingDecision, ProxyAccountSortMetrics, ProxyBodyCaptureLogger, ProxyQuotaCooldownUpdate, ProxyPassthroughAccount, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
16
- declare function tryAcquireAccountAdmission(accountKey: string, capacity: number): AccountAdmissionLease | undefined;
15
+ import type { AccountAllowlist, AccountAdmissionLease, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicNonOkResult, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeLoggedErrorBuilder, ClaudeRequest, ClaudeProxyRouteRuntimeOptions, ModelRouterInterface, ParsedClaudeError, ProxyAccountRoutingDecision, ProxyAccountSortMetrics, ProxyBodyCaptureLogger, ProxyQuotaCooldownUpdate, ProxyPassthroughAccount, QueuedAccountAdmission, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
16
+ declare function tryAcquireAccountAdmission(accountKey: string, capacity: number | undefined): AccountAdmissionLease | undefined;
17
+ declare function enqueueAccountAdmission(accountKey: string, capacity: number): QueuedAccountAdmission;
17
18
  declare function acquireAccountAdmission(accountKey: string, capacity: number, abortSignal?: AbortSignal, timeoutMs?: number): Promise<AccountAdmissionLease | undefined>;
18
19
  declare function acquireFirstAvailableAccountAdmission(accountKeys: string[], capacity: number, abortSignal?: AbortSignal, timeoutMs?: number): Promise<{
19
20
  accountKey: string;
@@ -375,10 +376,12 @@ export declare const __testHooks: {
375
376
  acquireAccountAdmission: typeof acquireAccountAdmission;
376
377
  acquireFirstAvailableAccountAdmission: typeof acquireFirstAvailableAccountAdmission;
377
378
  tryAcquireAccountAdmission: typeof tryAcquireAccountAdmission;
379
+ enqueueAccountAdmission: typeof enqueueAccountAdmission;
378
380
  getAccountAdmissionSnapshot: (accountKey: string) => {
379
381
  active: number;
380
382
  waiting: number;
381
383
  };
384
+ hasAccountAdmissionState: (accountKey: string) => boolean;
382
385
  describeTransportError: typeof describeTransportError;
383
386
  redactProviderErrorMessage: typeof redactProviderErrorMessage;
384
387
  isUpstreamOverload: typeof isUpstreamOverload;
@@ -29,7 +29,7 @@ import { createSSEInterceptor } from "../../proxy/sseInterceptor.js";
29
29
  import { createStreamTerminalOutcomeTracker, mergeStreamTerminalOutcome, preflightAnthropicStream, } from "../../proxy/streamOutcome.js";
30
30
  import { isPermanentRefreshFailure, needsRefresh, persistTokens, refreshToken, refreshTokenFromLatest, } from "../../proxy/tokenRefresh.js";
31
31
  import { buildProxyTranslationPlan, parseRetryAfterMs, } from "../../proxy/routingPolicy.js";
32
- import { DEFAULT_MAX_INFLIGHT_PER_ACCOUNT, MAX_MAX_INFLIGHT_PER_ACCOUNT, MIN_MAX_INFLIGHT_PER_ACCOUNT, } from "../../proxy/modelRouter.js";
32
+ import { normalizeMaxInflightPerAccount } from "../../proxy/modelRouter.js";
33
33
  import { writeJsonSnapshotAtomically } from "../../proxy/snapshotPersistence.js";
34
34
  import { recordAttempt, recordAttemptError, recordFinalError, recordFinalSuccess, } from "../../proxy/usageStats.js";
35
35
  import { sanitizeForLog } from "../../utils/logSanitize.js";
@@ -122,6 +122,9 @@ const transientCooldownAdmissionSchedules = new Map();
122
122
  * make room for another stream on the same account.
123
123
  */
124
124
  const accountAdmissionStates = new Map();
125
+ const unlimitedAccountAdmissionLease = {
126
+ release: () => undefined,
127
+ };
125
128
  function getAccountAdmissionState(accountKey) {
126
129
  let state = accountAdmissionStates.get(accountKey);
127
130
  if (!state) {
@@ -130,13 +133,6 @@ function getAccountAdmissionState(accountKey) {
130
133
  }
131
134
  return state;
132
135
  }
133
- function normalizeAccountAdmissionCapacity(capacity) {
134
- return Number.isInteger(capacity) &&
135
- capacity >= MIN_MAX_INFLIGHT_PER_ACCOUNT &&
136
- capacity <= MAX_MAX_INFLIGHT_PER_ACCOUNT
137
- ? capacity
138
- : DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
139
- }
140
136
  function drainAccountAdmissionWaiters(accountKey, state) {
141
137
  while (state.waiters.length > 0 && state.active < state.waiters[0].capacity) {
142
138
  const waiter = state.waiters.shift();
@@ -167,8 +163,11 @@ function discardAccountAdmissionState(accountKey, state) {
167
163
  }
168
164
  }
169
165
  function tryAcquireAccountAdmission(accountKey, capacity) {
166
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
167
+ if (normalizedCapacity === undefined) {
168
+ return unlimitedAccountAdmissionLease;
169
+ }
170
170
  const state = getAccountAdmissionState(accountKey);
171
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
172
171
  if (state.waiters.length > 0 || state.active >= normalizedCapacity) {
173
172
  return undefined;
174
173
  }
@@ -176,13 +175,23 @@ function tryAcquireAccountAdmission(accountKey, capacity) {
176
175
  return createAccountAdmissionLease(accountKey, state);
177
176
  }
178
177
  function isAccountAdmissionAvailable(accountKey, capacity) {
178
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
179
+ if (normalizedCapacity === undefined) {
180
+ return true;
181
+ }
179
182
  const state = accountAdmissionStates.get(accountKey);
180
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
181
183
  return (!state || (state.waiters.length === 0 && state.active < normalizedCapacity));
182
184
  }
183
185
  function enqueueAccountAdmission(accountKey, capacity) {
186
+ // Validate BEFORE getAccountAdmissionState(), which inserts into the map as a
187
+ // side effect. Throwing after it would strand an empty entry for an account
188
+ // that never got admitted — and the throw path never calls
189
+ // discardAccountAdmissionState() to reap it.
190
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
191
+ if (normalizedCapacity === undefined) {
192
+ throw new Error("Account admission queue requires an explicit capacity");
193
+ }
184
194
  const state = getAccountAdmissionState(accountKey);
185
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
186
195
  let queued = true;
187
196
  let grantedLease;
188
197
  let resolveAdmission;
@@ -4309,12 +4318,12 @@ async function handleAnthropicRoutedClaudeRequest(args) {
4309
4318
  loopState.authCooldownMessage = `All ${orderedAccounts.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(earliestRetryAt).toISOString()}.`;
4310
4319
  }
4311
4320
  }
4312
- const accountAdmissionCapacity = modelRouter?.getMaxInflightPerAccount?.() ??
4313
- DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
4321
+ const accountAdmissionCapacity = modelRouter?.getMaxInflightPerAccount?.();
4314
4322
  // When every eligible account is busy, reserve the first account that frees
4315
4323
  // instead of arbitrarily waiting behind the last configured account.
4316
4324
  let queuedAccountAdmission;
4317
- if (effectiveAccounts.length > 0 &&
4325
+ if (accountAdmissionCapacity !== undefined &&
4326
+ effectiveAccounts.length > 0 &&
4318
4327
  effectiveAccounts.every((account) => !isAccountAdmissionAvailable(account.key, accountAdmissionCapacity))) {
4319
4328
  queuedAccountAdmission = await acquireFirstAvailableAccountAdmission(effectiveAccounts.map((account) => account.key), accountAdmissionCapacity, ctx.abortSignal);
4320
4329
  }
@@ -5275,12 +5284,16 @@ export const __testHooks = {
5275
5284
  acquireAccountAdmission,
5276
5285
  acquireFirstAvailableAccountAdmission,
5277
5286
  tryAcquireAccountAdmission,
5287
+ enqueueAccountAdmission,
5278
5288
  getAccountAdmissionSnapshot: (accountKey) => {
5279
5289
  const state = accountAdmissionStates.get(accountKey);
5280
5290
  return state
5281
5291
  ? { active: state.active, waiting: state.waiters.length }
5282
5292
  : { active: 0, waiting: 0 };
5283
5293
  },
5294
+ // The snapshot above reports {active:0, waiting:0} both for "no entry" and
5295
+ // for "empty entry", so it cannot see a stranded allocation. This can.
5296
+ hasAccountAdmissionState: (accountKey) => accountAdmissionStates.has(accountKey),
5284
5297
  describeTransportError,
5285
5298
  redactProviderErrorMessage,
5286
5299
  isUpstreamOverload,
@@ -500,4 +500,13 @@ export type BuildRealtimeMcpToolsParams = {
500
500
  publishEvent: RealtimeEventPublisher;
501
501
  /** Opens a HITL confirmation for destructive tools and awaits the decision. */
502
502
  requestConfirmation: RealtimeConfirmationRequester;
503
+ /**
504
+ * Hard cap per MCP tool call, in milliseconds (default 30000).
505
+ *
506
+ * Without one, a stalled MCP server holds the realtime turn open forever:
507
+ * Gemini waits on the function result, so the user gets silence rather than
508
+ * an error. Bounding the call turns that into a normal tool failure the
509
+ * model can talk about.
510
+ */
511
+ toolTimeoutMs?: number;
503
512
  };
@@ -30,7 +30,7 @@ export type ModelRouterInterface = {
30
30
  isClaudeTarget(requestedModel: string): boolean;
31
31
  getFallbackChain(): FallbackEntry[];
32
32
  isAutoFallbackEnabled?(): boolean;
33
- getMaxInflightPerAccount?(): number;
33
+ getMaxInflightPerAccount?(): number | undefined;
34
34
  getModelMappings?: () => ModelMapping[];
35
35
  getPassthroughModels?: () => string[];
36
36
  };
@@ -910,7 +910,13 @@ export type ProxyRoutingConfig = {
910
910
  fallbackChain: FallbackEntry[];
911
911
  /** Permit a last-resort provider chosen by the translation layer. Disabled by default. */
912
912
  autoFallback?: boolean;
913
- /** Maximum in-flight upstream requests per OAuth account. Defaults to two. */
913
+ /**
914
+ * Optional in-flight upstream request cap per OAuth account.
915
+ *
916
+ * Unlimited admission is the result of omitting it AND of any value outside
917
+ * the accepted range — a non-integer, or anything below 1 or above 20 — since
918
+ * `normalizeMaxInflightPerAccount()` discards those rather than clamping.
919
+ */
914
920
  maxInflightPerAccount?: number;
915
921
  passthroughModels?: string[];
916
922
  /** Enable quota-aware fill-first account ordering. Defaults to true. */
@@ -16,6 +16,14 @@
16
16
  import { z } from "zod";
17
17
  import { logger } from "../../utils/logger.js";
18
18
  import { findSchemaIssue, sanitizeToolParameters } from "./schemaSanitizer.js";
19
+ /**
20
+ * Default hard cap per MCP tool call.
21
+ *
22
+ * Chosen to sit well inside a conversational turn: a realtime voice user is
23
+ * waiting in silence while a tool runs, so a call that has not returned in
24
+ * 30s has already failed as far as the conversation is concerned.
25
+ */
26
+ const DEFAULT_TOOL_TIMEOUT_MS = 30_000;
19
27
  /**
20
28
  * The fields of an MCP tool result we render: text content parts and the error
21
29
  * flag. The result crosses a network boundary from an external MCP server, so it
@@ -86,7 +94,7 @@ function registerToolAliases(toolContext, mcpToolName, handler) {
86
94
  * filtering is needed.
87
95
  */
88
96
  export async function buildRealtimeMcpTools(params) {
89
- const { mcpUrl, authToken, xContext, publishEvent, requestConfirmation } = params;
97
+ const { mcpUrl, authToken, xContext, publishEvent, requestConfirmation, toolTimeoutMs = DEFAULT_TOOL_TIMEOUT_MS, } = params;
90
98
  const { llm } = await import("@livekit/agents");
91
99
  const { Client: McpClient } = await import("@modelcontextprotocol/sdk/client/index.js");
92
100
  const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
@@ -141,10 +149,14 @@ export async function buildRealtimeMcpTools(params) {
141
149
  publishEvent("tool-start", { name: mcpTool.name });
142
150
  const startedAt = Date.now();
143
151
  try {
152
+ // Third argument is RequestOptions; the SDK aborts the in-flight
153
+ // request when `timeout` elapses. Without it a stalled server holds
154
+ // the turn open indefinitely — Gemini blocks on the function
155
+ // result, so the user hears nothing at all rather than an error.
144
156
  const result = await client.callTool({
145
157
  name: mcpTool.name,
146
158
  arguments: args ?? {},
147
- });
159
+ }, undefined, { timeout: toolTimeoutMs });
148
160
  const text = mcpResultToText(result);
149
161
  logger.info("realtime.tool.result", {
150
162
  tool: mcpTool.name,
@@ -1,8 +1,18 @@
1
1
  import type { FallbackEntry, ModelMapping, ProxyRoutingConfig, RouteResult } from "../types/index.js";
2
- /** Default and accepted range for concurrent upstream requests per OAuth account. */
2
+ /** Accepted range for an explicitly configured OAuth account admission cap. */
3
3
  export declare const MIN_MAX_INFLIGHT_PER_ACCOUNT = 1;
4
4
  export declare const MAX_MAX_INFLIGHT_PER_ACCOUNT = 20;
5
- export declare const DEFAULT_MAX_INFLIGHT_PER_ACCOUNT = 2;
5
+ /**
6
+ * The single definition of "a usable admission cap": an integer inside the
7
+ * accepted range. Anything else — `0`, `1.5`, `21`, `NaN` — means unlimited.
8
+ *
9
+ * `parseProxyConfig()` already drops invalid YAML values, but `ProxyRoutingConfig`
10
+ * is an exported type, so a programmatic caller can hand `ModelRouter` a value
11
+ * that never passed through it. Without this, `getMaxInflightPerAccount()` would
12
+ * report a bound (`0`, `21`) that the admission path ignores as unlimited, and
13
+ * the two would disagree about whether the account is capped.
14
+ */
15
+ export declare function normalizeMaxInflightPerAccount(capacity: number | undefined): number | undefined;
6
16
  export declare class ModelRouter {
7
17
  private readonly mappings;
8
18
  private readonly passthrough;
@@ -15,8 +25,8 @@ export declare class ModelRouter {
15
25
  getFallbackChain(): FallbackEntry[];
16
26
  /** Whether translation-layer auto-provider fallback is explicitly enabled. */
17
27
  isAutoFallbackEnabled(): boolean;
18
- /** Maximum concurrent upstream requests admitted for each OAuth account. */
19
- getMaxInflightPerAccount(): number;
28
+ /** Explicit per-account admission cap, or undefined when admission is unlimited. */
29
+ getMaxInflightPerAccount(): number | undefined;
20
30
  /** Return the raw model mapping entries (used by /v1/models). */
21
31
  getModelMappings(): ModelMapping[];
22
32
  /** Return models configured for passthrough (used by /v1/models). */
@@ -1,7 +1,24 @@
1
- /** Default and accepted range for concurrent upstream requests per OAuth account. */
1
+ /** Accepted range for an explicitly configured OAuth account admission cap. */
2
2
  export const MIN_MAX_INFLIGHT_PER_ACCOUNT = 1;
3
3
  export const MAX_MAX_INFLIGHT_PER_ACCOUNT = 20;
4
- export const DEFAULT_MAX_INFLIGHT_PER_ACCOUNT = 2;
4
+ /**
5
+ * The single definition of "a usable admission cap": an integer inside the
6
+ * accepted range. Anything else — `0`, `1.5`, `21`, `NaN` — means unlimited.
7
+ *
8
+ * `parseProxyConfig()` already drops invalid YAML values, but `ProxyRoutingConfig`
9
+ * is an exported type, so a programmatic caller can hand `ModelRouter` a value
10
+ * that never passed through it. Without this, `getMaxInflightPerAccount()` would
11
+ * report a bound (`0`, `21`) that the admission path ignores as unlimited, and
12
+ * the two would disagree about whether the account is capped.
13
+ */
14
+ export function normalizeMaxInflightPerAccount(capacity) {
15
+ return typeof capacity === "number" &&
16
+ Number.isInteger(capacity) &&
17
+ capacity >= MIN_MAX_INFLIGHT_PER_ACCOUNT &&
18
+ capacity <= MAX_MAX_INFLIGHT_PER_ACCOUNT
19
+ ? capacity
20
+ : undefined;
21
+ }
5
22
  export class ModelRouter {
6
23
  mappings;
7
24
  passthrough;
@@ -13,8 +30,7 @@ export class ModelRouter {
13
30
  this.passthrough = new Set(config.passthroughModels ?? []);
14
31
  this.fallback = config.fallbackChain;
15
32
  this.autoFallback = config.autoFallback === true;
16
- this.maxInflightPerAccount =
17
- config.maxInflightPerAccount ?? DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
33
+ this.maxInflightPerAccount = normalizeMaxInflightPerAccount(config.maxInflightPerAccount);
18
34
  }
19
35
  resolve(requestedModel) {
20
36
  const mapping = this.mappings.get(requestedModel);
@@ -42,7 +58,7 @@ export class ModelRouter {
42
58
  isAutoFallbackEnabled() {
43
59
  return this.autoFallback;
44
60
  }
45
- /** Maximum concurrent upstream requests admitted for each OAuth account. */
61
+ /** Explicit per-account admission cap, or undefined when admission is unlimited. */
46
62
  getMaxInflightPerAccount() {
47
63
  return this.maxInflightPerAccount;
48
64
  }
@@ -12,8 +12,9 @@
12
12
  import { buildTranslationOptions } from "../../proxy/proxyTranslationEngine.js";
13
13
  import { ProxyTracer } from "../../proxy/proxyTracer.js";
14
14
  import { isPermanentRefreshFailure } from "../../proxy/tokenRefresh.js";
15
- import type { AccountAllowlist, AccountAdmissionLease, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicNonOkResult, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeLoggedErrorBuilder, ClaudeRequest, ClaudeProxyRouteRuntimeOptions, ModelRouterInterface, ParsedClaudeError, ProxyAccountRoutingDecision, ProxyAccountSortMetrics, ProxyBodyCaptureLogger, ProxyQuotaCooldownUpdate, ProxyPassthroughAccount, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
16
- declare function tryAcquireAccountAdmission(accountKey: string, capacity: number): AccountAdmissionLease | undefined;
15
+ import type { AccountAllowlist, AccountAdmissionLease, AccountCooldownPlan, AccountQuota, AnthropicAttemptLogger, AnthropicAuthRetryResult, AnthropicLoopState, AnthropicNonOkResult, AnthropicSuccessResult, AnthropicUpstreamFetchResult, ClaudeFinalRequestLogger, ClaudeLoggedErrorBuilder, ClaudeRequest, ClaudeProxyRouteRuntimeOptions, ModelRouterInterface, ParsedClaudeError, ProxyAccountRoutingDecision, ProxyAccountSortMetrics, ProxyBodyCaptureLogger, ProxyQuotaCooldownUpdate, ProxyPassthroughAccount, QueuedAccountAdmission, RouteGroup, RuntimeAccountState, ServerContext, StreamTerminalOutcome } from "../../types/index.js";
16
+ declare function tryAcquireAccountAdmission(accountKey: string, capacity: number | undefined): AccountAdmissionLease | undefined;
17
+ declare function enqueueAccountAdmission(accountKey: string, capacity: number): QueuedAccountAdmission;
17
18
  declare function acquireAccountAdmission(accountKey: string, capacity: number, abortSignal?: AbortSignal, timeoutMs?: number): Promise<AccountAdmissionLease | undefined>;
18
19
  declare function acquireFirstAvailableAccountAdmission(accountKeys: string[], capacity: number, abortSignal?: AbortSignal, timeoutMs?: number): Promise<{
19
20
  accountKey: string;
@@ -375,10 +376,12 @@ export declare const __testHooks: {
375
376
  acquireAccountAdmission: typeof acquireAccountAdmission;
376
377
  acquireFirstAvailableAccountAdmission: typeof acquireFirstAvailableAccountAdmission;
377
378
  tryAcquireAccountAdmission: typeof tryAcquireAccountAdmission;
379
+ enqueueAccountAdmission: typeof enqueueAccountAdmission;
378
380
  getAccountAdmissionSnapshot: (accountKey: string) => {
379
381
  active: number;
380
382
  waiting: number;
381
383
  };
384
+ hasAccountAdmissionState: (accountKey: string) => boolean;
382
385
  describeTransportError: typeof describeTransportError;
383
386
  redactProviderErrorMessage: typeof redactProviderErrorMessage;
384
387
  isUpstreamOverload: typeof isUpstreamOverload;
@@ -29,7 +29,7 @@ import { createSSEInterceptor } from "../../proxy/sseInterceptor.js";
29
29
  import { createStreamTerminalOutcomeTracker, mergeStreamTerminalOutcome, preflightAnthropicStream, } from "../../proxy/streamOutcome.js";
30
30
  import { isPermanentRefreshFailure, needsRefresh, persistTokens, refreshToken, refreshTokenFromLatest, } from "../../proxy/tokenRefresh.js";
31
31
  import { buildProxyTranslationPlan, parseRetryAfterMs, } from "../../proxy/routingPolicy.js";
32
- import { DEFAULT_MAX_INFLIGHT_PER_ACCOUNT, MAX_MAX_INFLIGHT_PER_ACCOUNT, MIN_MAX_INFLIGHT_PER_ACCOUNT, } from "../../proxy/modelRouter.js";
32
+ import { normalizeMaxInflightPerAccount } from "../../proxy/modelRouter.js";
33
33
  import { writeJsonSnapshotAtomically } from "../../proxy/snapshotPersistence.js";
34
34
  import { recordAttempt, recordAttemptError, recordFinalError, recordFinalSuccess, } from "../../proxy/usageStats.js";
35
35
  import { sanitizeForLog } from "../../utils/logSanitize.js";
@@ -122,6 +122,9 @@ const transientCooldownAdmissionSchedules = new Map();
122
122
  * make room for another stream on the same account.
123
123
  */
124
124
  const accountAdmissionStates = new Map();
125
+ const unlimitedAccountAdmissionLease = {
126
+ release: () => undefined,
127
+ };
125
128
  function getAccountAdmissionState(accountKey) {
126
129
  let state = accountAdmissionStates.get(accountKey);
127
130
  if (!state) {
@@ -130,13 +133,6 @@ function getAccountAdmissionState(accountKey) {
130
133
  }
131
134
  return state;
132
135
  }
133
- function normalizeAccountAdmissionCapacity(capacity) {
134
- return Number.isInteger(capacity) &&
135
- capacity >= MIN_MAX_INFLIGHT_PER_ACCOUNT &&
136
- capacity <= MAX_MAX_INFLIGHT_PER_ACCOUNT
137
- ? capacity
138
- : DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
139
- }
140
136
  function drainAccountAdmissionWaiters(accountKey, state) {
141
137
  while (state.waiters.length > 0 && state.active < state.waiters[0].capacity) {
142
138
  const waiter = state.waiters.shift();
@@ -167,8 +163,11 @@ function discardAccountAdmissionState(accountKey, state) {
167
163
  }
168
164
  }
169
165
  function tryAcquireAccountAdmission(accountKey, capacity) {
166
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
167
+ if (normalizedCapacity === undefined) {
168
+ return unlimitedAccountAdmissionLease;
169
+ }
170
170
  const state = getAccountAdmissionState(accountKey);
171
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
172
171
  if (state.waiters.length > 0 || state.active >= normalizedCapacity) {
173
172
  return undefined;
174
173
  }
@@ -176,13 +175,23 @@ function tryAcquireAccountAdmission(accountKey, capacity) {
176
175
  return createAccountAdmissionLease(accountKey, state);
177
176
  }
178
177
  function isAccountAdmissionAvailable(accountKey, capacity) {
178
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
179
+ if (normalizedCapacity === undefined) {
180
+ return true;
181
+ }
179
182
  const state = accountAdmissionStates.get(accountKey);
180
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
181
183
  return (!state || (state.waiters.length === 0 && state.active < normalizedCapacity));
182
184
  }
183
185
  function enqueueAccountAdmission(accountKey, capacity) {
186
+ // Validate BEFORE getAccountAdmissionState(), which inserts into the map as a
187
+ // side effect. Throwing after it would strand an empty entry for an account
188
+ // that never got admitted — and the throw path never calls
189
+ // discardAccountAdmissionState() to reap it.
190
+ const normalizedCapacity = normalizeMaxInflightPerAccount(capacity);
191
+ if (normalizedCapacity === undefined) {
192
+ throw new Error("Account admission queue requires an explicit capacity");
193
+ }
184
194
  const state = getAccountAdmissionState(accountKey);
185
- const normalizedCapacity = normalizeAccountAdmissionCapacity(capacity);
186
195
  let queued = true;
187
196
  let grantedLease;
188
197
  let resolveAdmission;
@@ -4309,12 +4318,12 @@ async function handleAnthropicRoutedClaudeRequest(args) {
4309
4318
  loopState.authCooldownMessage = `All ${orderedAccounts.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(earliestRetryAt).toISOString()}.`;
4310
4319
  }
4311
4320
  }
4312
- const accountAdmissionCapacity = modelRouter?.getMaxInflightPerAccount?.() ??
4313
- DEFAULT_MAX_INFLIGHT_PER_ACCOUNT;
4321
+ const accountAdmissionCapacity = modelRouter?.getMaxInflightPerAccount?.();
4314
4322
  // When every eligible account is busy, reserve the first account that frees
4315
4323
  // instead of arbitrarily waiting behind the last configured account.
4316
4324
  let queuedAccountAdmission;
4317
- if (effectiveAccounts.length > 0 &&
4325
+ if (accountAdmissionCapacity !== undefined &&
4326
+ effectiveAccounts.length > 0 &&
4318
4327
  effectiveAccounts.every((account) => !isAccountAdmissionAvailable(account.key, accountAdmissionCapacity))) {
4319
4328
  queuedAccountAdmission = await acquireFirstAvailableAccountAdmission(effectiveAccounts.map((account) => account.key), accountAdmissionCapacity, ctx.abortSignal);
4320
4329
  }
@@ -5275,12 +5284,16 @@ export const __testHooks = {
5275
5284
  acquireAccountAdmission,
5276
5285
  acquireFirstAvailableAccountAdmission,
5277
5286
  tryAcquireAccountAdmission,
5287
+ enqueueAccountAdmission,
5278
5288
  getAccountAdmissionSnapshot: (accountKey) => {
5279
5289
  const state = accountAdmissionStates.get(accountKey);
5280
5290
  return state
5281
5291
  ? { active: state.active, waiting: state.waiters.length }
5282
5292
  : { active: 0, waiting: 0 };
5283
5293
  },
5294
+ // The snapshot above reports {active:0, waiting:0} both for "no entry" and
5295
+ // for "empty entry", so it cannot see a stranded allocation. This can.
5296
+ hasAccountAdmissionState: (accountKey) => accountAdmissionStates.has(accountKey),
5284
5297
  describeTransportError,
5285
5298
  redactProviderErrorMessage,
5286
5299
  isUpstreamOverload,
@@ -500,4 +500,13 @@ export type BuildRealtimeMcpToolsParams = {
500
500
  publishEvent: RealtimeEventPublisher;
501
501
  /** Opens a HITL confirmation for destructive tools and awaits the decision. */
502
502
  requestConfirmation: RealtimeConfirmationRequester;
503
+ /**
504
+ * Hard cap per MCP tool call, in milliseconds (default 30000).
505
+ *
506
+ * Without one, a stalled MCP server holds the realtime turn open forever:
507
+ * Gemini waits on the function result, so the user gets silence rather than
508
+ * an error. Bounding the call turns that into a normal tool failure the
509
+ * model can talk about.
510
+ */
511
+ toolTimeoutMs?: number;
503
512
  };
@@ -30,7 +30,7 @@ export type ModelRouterInterface = {
30
30
  isClaudeTarget(requestedModel: string): boolean;
31
31
  getFallbackChain(): FallbackEntry[];
32
32
  isAutoFallbackEnabled?(): boolean;
33
- getMaxInflightPerAccount?(): number;
33
+ getMaxInflightPerAccount?(): number | undefined;
34
34
  getModelMappings?: () => ModelMapping[];
35
35
  getPassthroughModels?: () => string[];
36
36
  };
@@ -910,7 +910,13 @@ export type ProxyRoutingConfig = {
910
910
  fallbackChain: FallbackEntry[];
911
911
  /** Permit a last-resort provider chosen by the translation layer. Disabled by default. */
912
912
  autoFallback?: boolean;
913
- /** Maximum in-flight upstream requests per OAuth account. Defaults to two. */
913
+ /**
914
+ * Optional in-flight upstream request cap per OAuth account.
915
+ *
916
+ * Unlimited admission is the result of omitting it AND of any value outside
917
+ * the accepted range — a non-integer, or anything below 1 or above 20 — since
918
+ * `normalizeMaxInflightPerAccount()` discards those rather than clamping.
919
+ */
914
920
  maxInflightPerAccount?: number;
915
921
  passthroughModels?: string[];
916
922
  /** Enable quota-aware fill-first account ordering. Defaults to true. */